Compare commits

...
Author SHA1 Message Date
yp 8e14ce386e add suport sp include awg/vless 2026-09-17 12:32:11 +03:00
yp 435a1ea09d fixed code signature invalid, add test ind systemextension 2026-09-15 12:45:58 +03:00
yp bcbf97b28b update allow excluded apps & ref code 2026-09-14 22:19:05 +03:00
yp 665cfb17aa update ind sp 2026-09-14 18:29:36 +03:00
yp f74c7d880e test profile 2026-09-14 18:01:52 +03:00
yp 82505dcb1d Feat: Add support SplitTunnel MacOS 2026-09-14 17:56:29 +03:00
49 changed files with 4337 additions and 31 deletions

No files matched your search

@@ -8,10 +8,16 @@ inputs:
description: Base64-encoded provisioning profile
required: true
outputs:
path:
description: Installed provisioning profile path
value: ${{ steps.install.outputs.path }}
runs:
using: composite
steps:
- name: Setup provisioning profile
id: install
shell: bash
run: |
PROFILES_DIR="$HOME/Library/MobileDevice/Provisioning Profiles"
@@ -27,5 +33,6 @@ runs:
fi
mkdir -p "$PROFILES_DIR"
mv "$TEMP_FILE" "$PROFILES_DIR/$PROFILE_UUID.mobileprovision"
echo "Installed profile: $PROFILE_UUID"
PROFILE_PATH="$PROFILES_DIR/$PROFILE_UUID.mobileprovision"
mv "$TEMP_FILE" "$PROFILE_PATH"
echo "path=$PROFILE_PATH" >> "$GITHUB_OUTPUT"
+12
View File
@@ -498,6 +498,16 @@ jobs:
cert-base64: ${{ secrets.MAC_INSTALLER_SIGNER_CERT }}
cert-password: ${{ secrets.MAC_INSTALL_CERT_PW }}
- uses: ./.github/actions/apple-setup-provisioning-profile
id: pkg-app-profile
with:
provisioning_profile_base64: ${{ secrets.MAC_PKG_APP_PROVISIONING_PROFILE }}
- uses: ./.github/actions/apple-setup-provisioning-profile
id: pkg-st-profile
with:
provisioning_profile_base64: ${{ secrets.MAC_PKG_ST_PROVISIONING_PROFILE }}
- name: 'Setup xcode'
uses: maxim-lobanov/setup-xcode@v1
with:
@@ -533,6 +543,8 @@ jobs:
CODESIGN_INSTALLER_SIGNATURE: ${{ secrets.MAC_INSTALLER_SIGNER_ID }}
CODESIGN_KEYCHAIN: ${{ steps.setup-keychain.outputs.keychain-path }}
CODESIGN_INSTALLER_KEYCHAIN: ${{ steps.setup-keychain.outputs.keychain-path }}
CODESIGN_APP_PROVISION_PROFILE: ${{ steps.pkg-app-profile.outputs.path }}
CODESIGN_ST_PROVISION_PROFILE: ${{ steps.pkg-st-profile.outputs.path }}
NOTARYTOOL_TEAM_ID: ${{ secrets.MAC_TEAM_ID }}
NOTARYTOOL_EMAIL: ${{ secrets.APPLE_DEV_EMAIL }}
NOTARYTOOL_PASSWORD: ${{ secrets.APPLE_DEV_PASSWORD }}
+5
View File
@@ -3,6 +3,11 @@ cmake_minimum_required(VERSION 3.25.0 FATAL_ERROR)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(APPLE AND NOT IOS AND NOT MACOS_NE)
enable_language(OBJC)
enable_language(OBJCXX)
endif()
set(PROJECT AmneziaVPN)
if(NOT AMNEZIAVPN_VERSION)
set(AMNEZIAVPN_VERSION 5.0.2.2 CACHE STRING "Client app version")
+19
View File
@@ -7,10 +7,29 @@ endif()
if(NOT CLIENT_NETWORK_EXTENSION_NAME)
set(CLIENT_NETWORK_EXTENSION_NAME "${CLIENT_APPLICATION_NAME}NetworkExtension" CACHE STRING "Display name for Apple network extension targets")
endif()
if(NOT CLIENT_MACOS_ST_TARGET_NAME)
set(CLIENT_MACOS_ST_TARGET_NAME "${CLIENT_APPLICATION_NAME}SplitTunnel" CACHE STRING "macOS app split-tunnel system extension target name")
endif()
if(NOT CLIENT_MACOS_ST_BUNDLE_SUFFIX)
# TEMPORARY: reuses the App ID of the App Store packet-tunnel appex, because
# org.amnezia.AmneziaVPN.split-tunnel has not been created in the developer
# portal yet. The two never ship together (appex only when MACOS_NE=TRUE,
# this system extension only when MACOS_NE=OFF), so they do not collide on
# disk. Switch back to "split-tunnel" once the App ID and its profiles exist.
set(CLIENT_MACOS_ST_BUNDLE_SUFFIX "network-extension" CACHE STRING "Bundle id suffix for the macOS split-tunnel system extension")
endif()
if(NOT CLIENT_MACOS_ST_BUNDLE_VERSION)
# Bump on every change to the extension, otherwise sysextd keeps the copy it
# already installed instead of replacing it.
set(CLIENT_MACOS_ST_BUNDLE_VERSION "10" CACHE STRING "CFBundleVersion of the macOS split-tunnel system extension")
endif()
if(NOT BUILD_OSX_APP_IDENTIFIER)
set(BUILD_OSX_APP_IDENTIFIER org.amnezia.AmneziaVPN CACHE STRING "OSX Application identifier")
endif()
if(NOT CLIENT_MACOS_ST_BUNDLE_ID)
set(CLIENT_MACOS_ST_BUNDLE_ID "${BUILD_OSX_APP_IDENTIFIER}.${CLIENT_MACOS_ST_BUNDLE_SUFFIX}" CACHE STRING "Bundle identifier for the macOS split-tunnel system extension")
endif()
if(NOT BUILD_IOS_APP_IDENTIFIER)
set(BUILD_IOS_APP_IDENTIFIER org.amnezia.AmneziaVPN CACHE STRING "iOS Application identifier")
endif()
+3
View File
@@ -35,3 +35,6 @@ endif()
if(NOT CLIENT_MACOS_NE_PROVISIONING_PROFILE_SPECIFIER_DEBUG)
set(CLIENT_MACOS_NE_PROVISIONING_PROFILE_SPECIFIER_DEBUG "dev macos.org.amnezia.amneziaVPN.NE" CACHE STRING "macOS network extension provisioning profile specifier for debug")
endif()
if(NOT CLIENT_MACOS_ST_PROVISIONING_PROFILE_SPECIFIER)
set(CLIENT_MACOS_ST_PROVISIONING_PROFILE_SPECIFIER "distr macos.org.amnezia.amneziaVPN.NE" CACHE STRING "macOS split-tunnel system extension provisioning profile specifier for release")
endif()
+86 -14
View File
@@ -7,6 +7,8 @@ find_library(FW_COREWLAN CoreWLAN)
find_library(FW_NETWORK Network)
find_library(FW_USER_NOTIFICATIONS UserNotifications)
find_library(FW_NETWORK_EXTENSION NetworkExtension)
find_library(FW_SYSTEM_EXTENSIONS SystemExtensions)
find_library(FW_APPKIT AppKit)
set(LIBS ${LIBS}
${FW_SYSTEMCONFIG}
@@ -16,32 +18,74 @@ set(LIBS ${LIBS}
${FW_NETWORK}
${FW_USER_NOTIFICATIONS}
${FW_NETWORK_EXTENSION}
${FW_SYSTEM_EXTENSIONS}
${FW_APPKIT}
)
set_target_properties(${PROJECT} PROPERTIES
MACOSX_BUNDLE TRUE
MACOSX_BUNDLE_SHORT_VERSION_STRING "${CMAKE_PROJECT_VERSION_MAJOR}.${CMAKE_PROJECT_VERSION_MINOR}.${CMAKE_PROJECT_VERSION_PATCH}"
MACOSX_BUNDLE_BUNDLE_VERSION "${CMAKE_PROJECT_VERSION_TWEAK}"
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/macos/app/app-developerid.entitlements.in
${CMAKE_CURRENT_BINARY_DIR}/app-developerid.entitlements
@ONLY
)
set(HEADERS ${HEADERS}
${CMAKE_CURRENT_SOURCE_DIR}/ui/utils/macosUtil.h
)
set(SOURCES ${SOURCES}
${CMAKE_CURRENT_SOURCE_DIR}/ui/utils/macosUtil.mm
)
set(CLIENT_MACOS_APP_DEVELOPERID_ENTITLEMENTS_PATH
${CMAKE_CURRENT_BINARY_DIR}/app-developerid.entitlements
CACHE FILEPATH "Developer ID entitlements for the .pkg app bundle" FORCE)
set(ICON_FILE ${CLIENT_MACOS_APP_ICNS_PATH})
get_filename_component(MACOSX_BUNDLE_ICON_FILE "${CLIENT_MACOS_APP_ICNS_PATH}" NAME)
set_source_files_properties(${ICON_FILE} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
set(SOURCES ${SOURCES} ${ICON_FILE})
# CMake only substitutes MACOSX_BUNDLE_* into MACOSX_BUNDLE_INFO_PLIST, so
# ${MACOSX_DEPLOYMENT_TARGET} used to expand to an empty <string/>. Pre-configure
# the template with @ONLY (which leaves ${...} alone) and drop the key entirely
# when no deployment target is pinned.
if(CMAKE_OSX_DEPLOYMENT_TARGET)
set(AMN_MACOS_MIN_VERSION_ENTRY
"\t<key>LSMinimumSystemVersion</key>\n\t<string>${CMAKE_OSX_DEPLOYMENT_TARGET}</string>\n")
else()
set(AMN_MACOS_MIN_VERSION_ENTRY "")
message(STATUS "CMAKE_OSX_DEPLOYMENT_TARGET is not set: the app bundle will not declare LSMinimumSystemVersion")
endif()
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/macos/app/Info-developerid.plist.in
${CMAKE_CURRENT_BINARY_DIR}/Info-developerid.plist.in
@ONLY
)
set_target_properties(${PROJECT} PROPERTIES
MACOSX_BUNDLE TRUE
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_BINARY_DIR}/Info-developerid.plist.in
MACOSX_BUNDLE_SHORT_VERSION_STRING "${CMAKE_PROJECT_VERSION_MAJOR}.${CMAKE_PROJECT_VERSION_MINOR}.${CMAKE_PROJECT_VERSION_PATCH}"
MACOSX_BUNDLE_BUNDLE_VERSION "${CMAKE_PROJECT_VERSION_TWEAK}"
MACOSX_BUNDLE_GUI_IDENTIFIER "${BUILD_OSX_APP_IDENTIFIER}"
MACOSX_BUNDLE_BUNDLE_NAME "${CLIENT_APPLICATION_NAME}"
MACOSX_BUNDLE_ICON_FILE "${MACOSX_BUNDLE_ICON_FILE}"
)
set(HEADERS ${HEADERS}
${CMAKE_CURRENT_SOURCE_DIR}/ui/utils/macosUtil.h
${CMAKE_CURRENT_SOURCE_DIR}/platforms/macos/splittunnel/macosSplitTunnelManager.h
${CMAKE_CURRENT_SOURCE_DIR}/platforms/macos/splittunnel/macosAppInfo.h
)
set(SOURCES ${SOURCES}
${CMAKE_CURRENT_SOURCE_DIR}/ui/utils/macosUtil.mm
${CMAKE_CURRENT_SOURCE_DIR}/platforms/macos/splittunnel/macosSplitTunnelManager.mm
${CMAKE_CURRENT_SOURCE_DIR}/platforms/macos/splittunnel/macosAppInfo.mm
)
set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/platforms/macos/splittunnel/macosSplitTunnelManager.mm
${CMAKE_CURRENT_SOURCE_DIR}/platforms/macos/splittunnel/macosAppInfo.mm
PROPERTIES
COMPILE_FLAGS "-fobjc-arc"
)
target_compile_options(${PROJECT} PRIVATE
-DGROUP_ID=\"${BUILD_IOS_GROUP_IDENTIFIER}\"
-DVPN_NE_BUNDLEID=\"${BUILD_IOS_APP_IDENTIFIER}.network-extension\"
-DCLIENT_MACOS_ST_BUNDLE_ID=\"${CLIENT_MACOS_ST_BUNDLE_ID}\"
)
# Get SDK path
@@ -52,3 +96,31 @@ execute_process(
)
message("OSX_SDK_PATH is: ${OSX_SDK_PATH}")
# The daemon reads its pf anchor files from applicationDirPath(), i.e. from
# Contents/MacOS next to its own executable. Do this for every configuration,
# not just Debug - a Release bundle copied to /Applications by hand needs the
# rules just as much.
add_custom_command(TARGET ${PROJECT} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_SOURCE_DIR}/deploy/data/macos/pf"
"$<TARGET_BUNDLE_CONTENT_DIR:${PROJECT}>/MacOS/pf"
COMMENT "Copy pf anchor rules into the app bundle"
)
add_subdirectory(macos/splittunnelextension)
add_dependencies(${PROJECT} ${CLIENT_MACOS_ST_TARGET_NAME})
# Wipe the whole directory rather than just the current bundle name: renaming the
# extension (its bundle name follows CFBundleIdentifier) would otherwise leave the
# previous bundle behind, and two bundles claiming the same identifier make
# sysextd fail with OSSystemExtensionErrorDuplicateExtensionIdentifer.
add_custom_command(TARGET ${PROJECT} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rm -rf
"$<TARGET_BUNDLE_CONTENT_DIR:${PROJECT}>/Library/SystemExtensions"
COMMAND ${CMAKE_COMMAND} -E make_directory
"$<TARGET_BUNDLE_CONTENT_DIR:${PROJECT}>/Library/SystemExtensions"
COMMAND ${CMAKE_COMMAND} -E copy_directory
"$<TARGET_BUNDLE_DIR:${CLIENT_MACOS_ST_TARGET_NAME}>"
"$<TARGET_BUNDLE_CONTENT_DIR:${PROJECT}>/Library/SystemExtensions/$<TARGET_FILE_NAME:${CLIENT_MACOS_ST_TARGET_NAME}>.systemextension"
COMMENT "Embed split-tunnel system extension into app bundle"
)
@@ -1,5 +1,23 @@
#include "appSplitTunnelingController.h"
#include "logger.h"
namespace {
Logger logger("AppSplitTunneling");
void logApps(const char *where, const QVector<amnezia::InstalledAppInfo> &apps)
{
logger.debug() << where << "count=" << apps.size();
for (int i = 0; i < apps.size(); ++i) {
const auto &app = apps.at(i);
logger.debug() << where << i
<< "name=" << app.appName
<< "bundleId=" << app.packageName
<< "path=" << app.appPath;
}
}
} // namespace
AppSplitTunnelingController::AppSplitTunnelingController(SecureAppSettingsRepository* appSettingsRepository)
: m_appSettingsRepository(appSettingsRepository)
{
@@ -11,16 +29,25 @@ AppSplitTunnelingController::AppSplitTunnelingController(SecureAppSettingsReposi
} else {
m_apps = m_appSettingsRepository->vpnApps(m_currentRouteMode);
}
logger.debug() << "ctor routeMode=" << static_cast<int>(m_currentRouteMode)
<< "enabled=" << m_appSettingsRepository->isAppsSplitTunnelingEnabled();
logApps("ctor", m_apps);
}
bool AppSplitTunnelingController::addApp(const amnezia::InstalledAppInfo &appInfo)
{
logger.debug() << "addApp name=" << appInfo.appName
<< "bundleId=" << appInfo.packageName
<< "path=" << appInfo.appPath
<< "routeMode=" << static_cast<int>(m_currentRouteMode);
if (m_apps.contains(appInfo)) {
logger.debug() << "addApp skipped: already in list";
return false;
}
m_apps.append(appInfo);
m_appSettingsRepository->setVpnApps(m_currentRouteMode, m_apps);
logApps("after addApp", m_apps);
return true;
}
@@ -28,28 +55,43 @@ bool AppSplitTunnelingController::addApp(const amnezia::InstalledAppInfo &appInf
void AppSplitTunnelingController::removeApp(int index)
{
if (index < 0 || index >= m_apps.size()) {
logger.error() << "removeApp: index" << index << "is out of range (size=" << m_apps.size() << ")";
return;
}
const auto removed = m_apps.at(index);
logger.info() << "removeApp index=" << index
<< "name=" << removed.appName
<< "bundleId=" << removed.packageName
<< "path=" << removed.appPath;
m_apps.removeAt(index);
m_appSettingsRepository->setVpnApps(m_currentRouteMode, m_apps);
logApps("after removeApp", m_apps);
}
void AppSplitTunnelingController::clearAppsList()
{
logger.info() << "clearAppsList: dropping" << m_apps.size() << "apps for route mode"
<< static_cast<int>(m_currentRouteMode);
m_apps.clear();
m_appSettingsRepository->setVpnApps(m_currentRouteMode, m_apps);
}
void AppSplitTunnelingController::setRouteMode(AppsRouteMode routeMode)
{
logger.info() << "setRouteMode" << static_cast<int>(m_currentRouteMode) << "->" << static_cast<int>(routeMode);
m_currentRouteMode = routeMode;
// Each route mode keeps its own app list, so the list changes with the mode.
m_apps = m_appSettingsRepository->vpnApps(m_currentRouteMode);
m_appSettingsRepository->setAppsRouteMode(routeMode);
logApps("after setRouteMode", m_apps);
}
void AppSplitTunnelingController::toggleSplitTunneling(bool enabled)
{
logger.debug() << "toggleSplitTunneling" << enabled
<< "routeMode=" << static_cast<int>(m_currentRouteMode);
logApps("toggleSplitTunneling", m_apps);
m_appSettingsRepository->setAppsSplitTunnelingEnabled(enabled);
}
@@ -11,6 +11,7 @@
#include "core/utils/serverConfigUtils.h"
#include "core/repositories/secureAppSettingsRepository.h"
#include "vpnConnection.h"
#include "logger.h"
#include "ui/controllers/qml/pageController.h"
#include "ui/controllers/connectionUiController.h"
#include "ui/controllers/settingsUiController.h"
@@ -51,6 +52,14 @@
#include "core/utils/swiftBridge.h"
#endif
#if defined(Q_OS_MACOS) && !defined(MACOS_NE)
#include "platforms/macos/splittunnel/macosSplitTunnelManager.h"
#endif
namespace {
Logger logger("CoreSignalHandlers");
}
CoreSignalHandlers::CoreSignalHandlers(CoreController* coreController, QObject* parent)
: QObject(parent),
m_coreController(coreController)
@@ -86,6 +95,7 @@ void CoreSignalHandlers::initAllHandlers()
initIosSettingsHandler();
initNotificationHandler();
initUpdateFoundHandler();
initMacosSplitTunnelHandler();
}
void CoreSignalHandlers::initErrorMessagesHandler()
@@ -444,3 +454,128 @@ void CoreSignalHandlers::initUpdateFoundHandler()
});
}
void CoreSignalHandlers::initMacosSplitTunnelHandler()
{
#if defined(Q_OS_MACOS) && !defined(MACOS_NE)
auto *manager = MacOSSplitTunnelManager::instance();
auto reconcile = [this, manager](const char *trigger) {
auto *st = m_coreController->m_appSplitTunnelingController;
// The resolved address of the server we are actually connected to. It
// has to reach the extension, otherwise the VPN's own traffic to the
// server is claimed by the proxy and relayed through userspace - which
// is what broke AmneziaWG, whose tunnel is run by the service and so is
// not covered by the bundle-path self-exclusion.
// Taken from VpnConnection rather than from the stored credentials:
// credentials are empty for API configs, the live connection is not.
QString vpnServer = m_coreController->m_vpnConnection->remoteAddress();
if (vpnServer.isEmpty()) {
const QString serverId = m_coreController->m_serversController->getDefaultServerId();
if (!serverId.isEmpty()) {
vpnServer = m_coreController->m_serversController->getServerCredentials(serverId).hostName;
}
if (vpnServer.isEmpty()) {
logger.debug() << "macos split tunnel [" << trigger
<< "]: no server address yet (not connected, or an API config before connect)";
}
}
logger.info() << "macos split tunnel [" << trigger << "]:"
<< "connected=" << m_coreController->m_connectionController->isConnected()
<< "enabled=" << st->isSplitTunnelingEnabled()
<< "mode=" << static_cast<int>(st->getRouteMode())
<< "apps=" << st->getApps().size()
<< "vpnServer=" << (vpnServer.isEmpty() ? QStringLiteral("(empty)") : vpnServer);
manager->reconcile(m_coreController->m_connectionController->isConnected(),
st->isSplitTunnelingEnabled(),
st->getRouteMode(),
st->getApps(),
vpnServer);
};
// Surface the extension state to the user: without this a first run just
// silently does nothing until the extension is approved.
connect(manager, &MacOSSplitTunnelManager::needsUserApproval, this, [this]() {
logger.info() << "macos split tunnel: asking the user to approve the system extension";
emit m_coreController->m_pageController->showNotificationMessage(
tr("Allow the AmneziaVPN system extension in System Settings > General > "
"Login Items & Extensions > Network Extensions, then reconnect the VPN"));
});
connect(manager, &MacOSSplitTunnelManager::extensionActivated, this, []() {
logger.info() << "macos split tunnel: system extension registered";
});
connect(manager, &MacOSSplitTunnelManager::extensionStateChanged, this,
[this](bool installed, bool enabled, bool awaitingApproval) {
logger.info() << "macos split tunnel: extension installed=" << installed << "enabled=" << enabled
<< "awaitingApproval=" << awaitingApproval;
if (installed && !enabled && !awaitingApproval) {
// The user switched the extension off in System Settings while
// the app still shows the feature as on; say so instead of
// silently doing nothing.
emit m_coreController->m_pageController->showNotificationMessage(
tr("The AmneziaVPN system extension is switched off in System Settings > General > "
"Login Items & Extensions > Network Extensions"));
}
});
connect(manager, &MacOSSplitTunnelManager::proxyStarted, this, [this]() {
// Mode-neutral on purpose: in exclude mode the listed apps leave the
// tunnel, in include mode everything except them does.
logger.info() << "macos split tunnel: proxy is running";
emit m_coreController->m_pageController->showNotificationMessage(
tr("App split tunneling is active"));
});
connect(manager, &MacOSSplitTunnelManager::proxyStopped, this, []() {
logger.info() << "macos split tunnel: proxy stopped";
});
connect(manager, &MacOSSplitTunnelManager::errorOccurred, this, [this](const QString &message) {
logger.error() << "macos split tunnel error:" << message;
emit m_coreController->m_pageController->showErrorMessage(
tr("App split tunneling: %1").arg(message));
});
connect(m_coreController->m_connectionController, &ConnectionController::connectionStateChanged, this,
[reconcile](Vpn::ConnectionState state) {
logger.debug() << "macos split tunnel: connection state ->" << static_cast<int>(state);
reconcile("connectionStateChanged");
});
connect(m_coreController->m_appSettingsRepository, &SecureAppSettingsRepository::appsSplitTunnelingEnabledChanged, this,
[reconcile, manager](bool enabled) {
logger.info() << "macos split tunnel: feature toggled ->" << enabled;
if (enabled) {
// Ask for approval right away, while the user is in the settings page.
// userInitiated: an approval left unanswered from an earlier
// run is cleared first, so the install prompt shows up again
// instead of the request going nowhere.
manager->activateExtension(/*userInitiated=*/true);
reconcile("appsSplitTunnelingEnabledChanged");
} else {
// Leave nothing behind in System Settings when the user opts out.
manager->disableFeature();
}
});
connect(m_coreController->m_appSettingsRepository, &SecureAppSettingsRepository::appsChanged, this,
[reconcile](AppsRouteMode mode) {
logger.debug() << "macos split tunnel: app list changed, mode=" << static_cast<int>(mode);
reconcile("appsChanged");
});
connect(m_coreController->m_appSettingsRepository, &SecureAppSettingsRepository::appsRouteModeChanged, this,
[reconcile](AppsRouteMode mode) {
logger.debug() << "macos split tunnel: route mode changed ->" << static_cast<int>(mode);
reconcile("appsRouteModeChanged");
});
logger.info() << "macos split tunnel handler installed";
#else
(void)this;
#endif
}
@@ -41,6 +41,7 @@ private:
void initIosSettingsHandler();
void initNotificationHandler();
void initUpdateFoundHandler();
void initMacosSplitTunnelHandler();
CoreController* m_coreController;
};
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
<key>CFBundleGetInfoString</key>
<string>${MACOSX_BUNDLE_INFO_STRING}</string>
<key>CFBundleIconFile</key>
<string>${MACOSX_BUNDLE_ICON_FILE}</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>
<key>CFBundleName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>CSResourcesFileMapped</key>
<true/>
@AMN_MACOS_MIN_VERSION_ENTRY@ <key>NSHighResolutionCapable</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSSystemExtensionUsageDescription</key>
<string>AmneziaVPN uses a system extension to exclude selected apps from the VPN tunnel.</string>
</dict>
</plist>
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.application-identifier</key>
<string>@BUILD_VPN_DEVELOPMENT_TEAM@.@BUILD_OSX_APP_IDENTIFIER@</string>
<key>com.apple.developer.team-identifier</key>
<string>@BUILD_VPN_DEVELOPMENT_TEAM@</string>
<key>com.apple.developer.system-extension.install</key>
<true/>
<key>com.apple.developer.networking.networkextension</key>
<array>
<string>app-proxy-provider-systemextension</string>
</array>
<key>com.apple.developer.networking.vpn.api</key>
<array>
<string>allow-vpn</string>
</array>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.application-identifier</key>
<string>@BUILD_VPN_DEVELOPMENT_TEAM@.@CLIENT_MACOS_ST_BUNDLE_ID@</string>
<key>com.apple.developer.team-identifier</key>
<string>@BUILD_VPN_DEVELOPMENT_TEAM@</string>
<key>com.apple.developer.networking.networkextension</key>
<array>
<string>app-proxy-provider-systemextension</string>
</array>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,104 @@
#ifndef AMNEZIA_SPLIT_TUNNEL_APP_POLICY_H
#define AMNEZIA_SPLIT_TUNNEL_APP_POLICY_H
#import <Foundation/Foundation.h>
/*! Route mode sent by the host app in the "mode" key. */
typedef NS_ENUM(NSInteger, STRouteMode) {
/*! Unknown/unset - the provider claims nothing and lets the system route. */
STRouteModeUnknown = 0,
/*! "except": listed apps bypass the tunnel, everything else stays in it. */
STRouteModeExcept,
/*! "only": listed apps stay in the tunnel, everything else bypasses it. */
STRouteModeOnly,
};
FOUNDATION_EXPORT STRouteMode STRouteModeFromString(NSString *value);
FOUNDATION_EXPORT const char *STRouteModeName(STRouteMode mode);
/*! What the provider should do with a flow. */
typedef NS_ENUM(NSInteger, STFlowDecision) {
/*! Return NO from handleNewFlow - the system routes it, i.e. into the
* tunnel, since the VPN owns the default route in both modes. */
STFlowDecisionSystem = 0,
/*! Claim the flow and re-open it on the physical interface. */
STFlowDecisionBypass,
};
@interface STAppEntry : NSObject
@property (nonatomic, copy) NSString *bundleId;
@property (nonatomic, copy) NSString *path;
@end
/*!
* Decides, per flow, whether it must be pulled out of the tunnel.
*
* Both modes leave the VPN's default route alone and differ only in which side
* of the list gets claimed:
*
* except: listed -> Bypass, everything else -> System (tunnel)
* only: listed -> System (tunnel), everything else -> Bypass
*
* "only" therefore claims almost every flow on the machine, which makes the
* self-exclusion below mandatory: without it the provider would claim its own
* relay sockets and the traffic of the VPN helpers (tun2socks, amneziawg-go,
* openvpn, AmneziaVPN-service) and recurse into itself.
*
* Thread safety: all properties are atomic and hold immutable values;
* replaceApps:/setMode: publish a new snapshot that readers on arbitrary flow
* queues observe consistently. Never mutate the array returned by `apps`.
*/
@interface STAppPolicy : NSObject
@property (atomic, copy, readonly) NSArray<STAppEntry *> *apps;
@property (atomic, assign) STRouteMode mode;
/*! Bundle id prefix of our own app family, e.g. "org.amnezia.AmneziaVPN".
* Matches the app, this extension and any dotted sub-identifier. */
@property (atomic, copy) NSString *selfBundleIdPrefix;
/*! Path of the host app bundle. Covers the bundled helper executables, which
* carry their own signing identifiers. */
@property (atomic, copy) NSString *selfAppPath;
- (void)replaceApps:(NSArray<STAppEntry *> *)apps;
/*! YES when "only" mode has everything it needs to run safely. */
- (BOOL)isSelfExclusionUsable;
/*! Why a flow got its decision. Kept as a cheap enum rather than a formatted
* string: the verdict is computed for every single flow, and in "only" mode
* that is every connection on the machine. The log line is rendered from this
* only when it will actually be emitted. */
typedef NS_ENUM(NSInteger, STMatchKind) {
STMatchKindModeUnknown = 0,
STMatchKindSelf,
STMatchKindUnsafeOnlyMode,
STMatchKindListed,
STMatchKindNotListed,
};
typedef struct {
STFlowDecision decision;
STMatchKind kind;
/*! Index in the app list; meaningful only for STMatchKindListed. */
NSUInteger index;
/*! YES when the match was on the path rather than the bundle id. */
BOOL matchedByPath;
/*! Size of the list the verdict was taken against. */
NSUInteger listCount;
} STFlowVerdict;
/*! YES when the executable path still has to be resolved for this flow, i.e.
* the signing identifier alone cannot settle it. Resolving the path goes
* through SecCodeCopyGuestWithAttributes, so it is worth skipping. */
- (BOOL)needsPathForSigningId:(NSString *)signingId;
/*! Allocation-free; call this on every flow. */
- (STFlowVerdict)verdictForSigningId:(NSString *)signingId path:(NSString *)path;
@end
/*! Renders a verdict for the log. Call only when the line is really emitted. */
FOUNDATION_EXPORT NSString *STDescribeVerdict(STFlowVerdict verdict);
#endif
@@ -0,0 +1,209 @@
#import "AppPolicy.h"
#import "Utils.h"
STRouteMode STRouteModeFromString(NSString *value)
{
if ([value isKindOfClass:[NSString class]]) {
if ([value isEqualToString:@"except"]) {
return STRouteModeExcept;
}
if ([value isEqualToString:@"only"]) {
return STRouteModeOnly;
}
}
return STRouteModeUnknown;
}
const char *STRouteModeName(STRouteMode mode)
{
switch (mode) {
case STRouteModeExcept: return "except";
case STRouteModeOnly: return "only";
case STRouteModeUnknown:
default: return "unknown";
}
}
@implementation STAppEntry
- (NSString *)description
{
return [NSString stringWithFormat:@"<STAppEntry bundleId=%@ path=%@>", self.bundleId ?: @"", self.path ?: @""];
}
@end
@interface STAppPolicy ()
@property (atomic, copy, readwrite) NSArray<STAppEntry *> *apps;
@end
@implementation STAppPolicy
- (instancetype)init
{
self = [super init];
if (self) {
_apps = @[];
_mode = STRouteModeUnknown;
_selfBundleIdPrefix = @"";
_selfAppPath = @"";
}
return self;
}
- (void)replaceApps:(NSArray<STAppEntry *> *)apps
{
NSArray<STAppEntry *> *snapshot = [apps copy] ?: @[];
self.apps = snapshot;
STLogInfo("policy: replaceApps count=%{public}lu mode=%{public}s",
(unsigned long)snapshot.count, STRouteModeName(self.mode));
NSUInteger i = 0;
for (STAppEntry *app in snapshot) {
STLogInfo("policy: [%{public}lu] bundleId=%{public}@ path=%{public}@",
(unsigned long)i, app.bundleId ?: @"", app.path ?: @"");
++i;
}
}
- (BOOL)isSelfExclusionUsable
{
return self.selfBundleIdPrefix.length > 0 || self.selfAppPath.length > 0;
}
/*! Our own app, this extension, and every helper shipped inside the app bundle
* (AmneziaVPN-service, tun2socks, amneziawg-go, openvpn). Their traffic must
* never be claimed, or "only" mode would relay the tunnel through itself. */
- (BOOL)isSelfSigningId:(NSString *)signingId path:(NSString *)path
{
NSString *prefix = self.selfBundleIdPrefix;
if (prefix.length > 0 && signingId.length > 0) {
if ([signingId isEqualToString:prefix]
|| [signingId hasPrefix:[prefix stringByAppendingString:@"."]]) {
return YES;
}
}
NSString *appPath = self.selfAppPath;
if (appPath.length > 0 && path.length > 0) {
NSString *dir = [appPath hasSuffix:@"/"] ? appPath : [appPath stringByAppendingString:@"/"];
if ([path isEqualToString:appPath] || [path hasPrefix:dir]) {
return YES;
}
}
return NO;
}
- (BOOL)matchesList:(NSString *)signingId
path:(NSString *)path
index:(NSUInteger *)outIndex
byPath:(BOOL *)outByPath
{
NSArray<STAppEntry *> *snapshot = self.apps;
NSUInteger index = 0;
for (STAppEntry *app in snapshot) {
if (signingId.length > 0 && app.bundleId.length > 0) {
if ([signingId isEqualToString:app.bundleId]
|| [signingId hasPrefix:[app.bundleId stringByAppendingString:@"."]]) {
if (outIndex != NULL) { *outIndex = index; }
if (outByPath != NULL) { *outByPath = NO; }
return YES;
}
}
if (path.length > 0 && app.path.length > 0) {
NSString *prefix = [app.path hasSuffix:@"/"] ? app.path : [app.path stringByAppendingString:@"/"];
if ([path isEqualToString:app.path] || [path hasPrefix:prefix]) {
if (outIndex != NULL) { *outIndex = index; }
if (outByPath != NULL) { *outByPath = YES; }
return YES;
}
}
++index;
}
return NO;
}
- (BOOL)needsPathForSigningId:(NSString *)signingId
{
if (signingId.length == 0) {
return YES;
}
// Our own family is recognised by the identifier prefix alone.
NSString *prefix = self.selfBundleIdPrefix;
if (prefix.length > 0
&& ([signingId isEqualToString:prefix] || [signingId hasPrefix:[prefix stringByAppendingString:@"."]])) {
return NO;
}
// A list entry that carries a bundle id can match without the path; entries
// that only carry a path cannot.
for (STAppEntry *app in self.apps) {
if (app.bundleId.length > 0
&& ([signingId isEqualToString:app.bundleId]
|| [signingId hasPrefix:[app.bundleId stringByAppendingString:@"."]])) {
return NO;
}
if (app.path.length > 0) {
return YES;
}
}
return NO;
}
- (STFlowVerdict)verdictForSigningId:(NSString *)signingId path:(NSString *)path
{
STFlowVerdict verdict = { STFlowDecisionSystem, STMatchKindModeUnknown, 0, NO, 0 };
const STRouteMode mode = self.mode;
verdict.listCount = self.apps.count;
if (mode == STRouteModeUnknown) {
return verdict;
}
// Never touch our own traffic. In "except" mode this is merely tidy; in
// "only" mode it is what stops the provider from relaying itself.
if ([self isSelfSigningId:signingId path:path]) {
verdict.kind = STMatchKindSelf;
return verdict;
}
// "only" mode claims everything that is not listed, so without a usable
// self-exclusion it would capture its own sockets. Refuse instead.
if (mode == STRouteModeOnly && ![self isSelfExclusionUsable]) {
verdict.kind = STMatchKindUnsafeOnlyMode;
return verdict;
}
NSUInteger index = 0;
BOOL byPath = NO;
const BOOL matched = [self matchesList:signingId path:path index:&index byPath:&byPath];
verdict.kind = matched ? STMatchKindListed : STMatchKindNotListed;
verdict.index = index;
verdict.matchedByPath = byPath;
if (mode == STRouteModeExcept) {
verdict.decision = matched ? STFlowDecisionBypass : STFlowDecisionSystem;
} else {
verdict.decision = matched ? STFlowDecisionSystem : STFlowDecisionBypass;
}
return verdict;
}
@end
NSString *STDescribeVerdict(STFlowVerdict verdict)
{
switch (verdict.kind) {
case STMatchKindModeUnknown:
return @"mode is unknown";
case STMatchKindSelf:
return @"own process, never proxied";
case STMatchKindUnsafeOnlyMode:
return @"only mode without self-exclusion data, refusing to claim anything";
case STMatchKindListed:
return [NSString stringWithFormat:@"listed [%lu] matched by %s",
(unsigned long)verdict.index,
verdict.matchedByPath ? "path" : "bundleId"];
case STMatchKindNotListed:
default:
return [NSString stringWithFormat:@"not listed among %lu entries", (unsigned long)verdict.listCount];
}
}
@@ -0,0 +1,77 @@
cmake_minimum_required(VERSION 3.25.0 FATAL_ERROR)
set(PROJECT "AmneziaVPNSplitTunnel")
project(${PROJECT})
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/Info.plist.in
${CMAKE_CURRENT_BINARY_DIR}/Info.plist
@ONLY
)
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/AmneziaVPNSplitTunnel.entitlements.in
${CMAKE_CURRENT_BINARY_DIR}/AmneziaVPNSplitTunnel.entitlements
@ONLY
)
set(CLIENT_MACOS_ST_ENTITLEMENTS_PATH
${CMAKE_CURRENT_BINARY_DIR}/AmneziaVPNSplitTunnel.entitlements
CACHE FILEPATH "Entitlements for the macOS split-tunnel system extension" FORCE)
add_executable(${PROJECT} MACOSX_BUNDLE
main.mm
TransparentProxyProvider.mm
FlowTCP.mm
FlowUDP.mm
AppPolicy.mm
Settings.mm
Utils.mm
)
set_target_properties(${PROJECT} PROPERTIES
BUNDLE TRUE
BUNDLE_EXTENSION systemextension
MACOSX_BUNDLE TRUE
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_BINARY_DIR}/Info.plist
MACOSX_BUNDLE_BUNDLE_NAME "${PROJECT}"
MACOSX_BUNDLE_GUI_IDENTIFIER "${CLIENT_MACOS_ST_BUNDLE_ID}"
MACOSX_BUNDLE_SHORT_VERSION_STRING "${APP_MAJOR_VERSION}"
MACOSX_BUNDLE_BUNDLE_VERSION "${CLIENT_MACOS_ST_BUNDLE_VERSION}"
MACOSX_BUNDLE_COPYRIGHT "AmneziaVPN"
OUTPUT_NAME "${CLIENT_MACOS_ST_BUNDLE_ID}"
)
set_source_files_properties(
main.mm
TransparentProxyProvider.mm
FlowTCP.mm
FlowUDP.mm
AppPolicy.mm
Settings.mm
Utils.mm
PROPERTIES
COMPILE_FLAGS "-fobjc-arc"
)
find_library(ST_FW_FOUNDATION Foundation REQUIRED)
find_library(ST_FW_NETWORK_EXTENSION NetworkExtension REQUIRED)
find_library(ST_FW_NETWORK Network REQUIRED)
find_library(ST_FW_SECURITY Security REQUIRED)
target_link_libraries(${PROJECT} PRIVATE
${ST_FW_FOUNDATION}
${ST_FW_NETWORK_EXTENSION}
${ST_FW_NETWORK}
${ST_FW_SECURITY}
)
target_include_directories(${PROJECT} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_compile_definitions(${PROJECT} PRIVATE
"CLIENT_MACOS_ST_BUNDLE_ID=\"${CLIENT_MACOS_ST_BUNDLE_ID}\""
)
install(DIRECTORY "$<TARGET_BUNDLE_DIR:${PROJECT}>/"
DESTINATION "${CMAKE_INSTALL_BINDIR}/${CLIENT_APPLICATION_NAME}.app/Contents/Library/SystemExtensions/${CLIENT_MACOS_ST_BUNDLE_ID}.systemextension"
COMPONENT AmneziaVPN
USE_SOURCE_PERMISSIONS
)
@@ -0,0 +1,19 @@
#ifndef AMNEZIA_SPLIT_TUNNEL_FLOW_TCP_H
#define AMNEZIA_SPLIT_TUNNEL_FLOW_TCP_H
#import <Network/Network.h>
#import <NetworkExtension/NetworkExtension.h>
@interface FlowTCP : NSObject
/*! Takes ownership of `flow` and proxies it out of `interface`.
* `flowId` only correlates log lines. */
+ (void)handleFlow:(NEAppProxyTCPFlow *)flow interface:(nw_interface_t)interface flowId:(uint64_t)flowId;
/*! Tears down every live session. Called when the proxy stops, so the
* registry does not keep finished sessions alive across restarts. */
+ (void)closeAll;
@end
#endif
@@ -0,0 +1,374 @@
#import "FlowTCP.h"
#import "Utils.h"
#import <os/log.h>
namespace {
/*! Stop reading from the app once this many bytes are waiting to be written to
* the remote, and resume once the backlog drops below the low-water mark.
* Without this the relay would read as fast as the app can produce. */
const uint64_t kSendHighWater = 256 * 1024;
const uint64_t kSendLowWater = 64 * 1024;
} // namespace
@interface FlowTCP ()
@property (atomic) NEAppProxyTCPFlow *flow;
@property (atomic) nw_connection_t connection;
@property (atomic) BOOL closed;
@property (atomic) uint64_t flowId;
@property (atomic) uint64_t bytesOut;
@property (atomic) uint64_t bytesIn;
@property (atomic) BOOL flowEofSeen;
/*! Every callback of this session runs here, so one slow flow cannot stall the
* others. All the fields below are owned by this queue. */
@property (nonatomic) dispatch_queue_t queue;
@property (nonatomic) uint64_t pendingSendBytes;
@property (nonatomic) BOOL readPaused;
@property (nonatomic) NSMutableArray<NSData *> *writeBacklog;
@property (nonatomic) BOOL writeInFlight;
- (void)closeWithError:(NSError *)error stage:(NSString *)stage;
@property (nonatomic) BOOL remoteEofSeen;
@end
/*! Registry keeping sessions alive while they are running.
* MUST only be touched on STUtils.stateQueue. */
static NSMutableSet<FlowTCP *> *TCPSessionsLocked(void)
{
static NSMutableSet<FlowTCP *> *sessions;
static dispatch_once_t once;
dispatch_once(&once, ^{
sessions = [NSMutableSet set];
});
return sessions;
}
@implementation FlowTCP
+ (void)handleFlow:(NEAppProxyTCPFlow *)flow interface:(nw_interface_t)interface flowId:(uint64_t)flowId
{
FlowTCP *session = [[FlowTCP alloc] init];
session.flow = flow;
session.flowId = flowId;
session.writeBacklog = [NSMutableArray array];
char label[64];
snprintf(label, sizeof(label), "org.amnezia.split-tunnel.tcp.%llu", (unsigned long long)flowId);
session.queue = dispatch_queue_create(label, DISPATCH_QUEUE_SERIAL);
dispatch_sync([STUtils stateQueue], ^{
[TCPSessionsLocked() addObject:session];
});
[STStats tcpOpened];
[session startWithInterface:interface];
}
- (void)startWithInterface:(nw_interface_t)interface
{
const uint64_t fid = self.flowId;
nw_endpoint_t remote = [self copyRemoteEndpoint];
if (remote == NULL) {
STLogError("tcp[%{public}llu]: missing or unusable remote endpoint, dropping flow", fid);
[self closeWithError:nil stage:@"no-remote"];
return;
}
STLogDebug("tcp[%{public}llu]: connecting to %{public}s:%{public}u via %{public}s",
fid,
nw_endpoint_get_hostname(remote) ?: "?",
(unsigned)nw_endpoint_get_port(remote),
interface != NULL ? (nw_interface_get_name(interface) ?: "?") : "(default)");
nw_parameters_t params = nw_parameters_create_secure_tcp(NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION);
if (interface != NULL) {
nw_parameters_require_interface(params, interface);
} else {
STLogError("tcp[%{public}llu]: no interface pinned - the bypass may leak back into the tunnel", fid);
}
self.connection = nw_connection_create(remote, params);
__weak FlowTCP *weakSelf = self;
void (^opened)(NSError *) = ^(NSError *error) {
FlowTCP *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
if (error != nil) {
STLogError("tcp[%{public}llu]: open flow failed: %{public}@", fid, error);
[strongSelf closeWithError:error stage:@"open-flow"];
return;
}
[strongSelf startConnection];
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (@available(macOS 15.0, *)) {
[self.flow openWithLocalFlowEndpoint:nil completionHandler:opened];
} else {
[self.flow openWithLocalEndpoint:nil completionHandler:opened];
}
#pragma clang diagnostic pop
}
- (nw_endpoint_t)copyRemoteEndpoint
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NWEndpoint *endpoint = self.flow.remoteEndpoint;
#pragma clang diagnostic pop
if (![endpoint isKindOfClass:[NWHostEndpoint class]]) {
STLogError("tcp[%{public}llu]: remote endpoint is %{public}@, expected NWHostEndpoint",
self.flowId, [endpoint class]);
return NULL;
}
NWHostEndpoint *host = (NWHostEndpoint *)endpoint;
return [STUtils copyEndpointFromHost:host.hostname port:host.port];
}
- (void)startConnection
{
const uint64_t fid = self.flowId;
__weak FlowTCP *weakSelf = self;
nw_connection_set_queue(self.connection, self.queue);
nw_connection_set_state_changed_handler(self.connection, ^(nw_connection_state_t state, nw_error_t error) {
FlowTCP *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
NSError *nsError = [STUtils errorFromNWError:error];
STLogDebug("tcp[%{public}llu]: state=%{public}s error=%{public}@",
fid, [STUtils connectionStateName:state], nsError ?: @"nil");
if (state == nw_connection_state_waiting) {
// "waiting" with no error means the system found no usable path for
// the interface this flow is pinned to; the path itself says why.
STLogInfo("tcp[%{public}llu]: waiting - %{public}@",
fid, [STUtils describeConnectionPath:strongSelf.connection]);
}
if (state == nw_connection_state_ready) {
STLogDebug("tcp[%{public}llu]: connection ready, starting relay", fid);
[strongSelf copyFlowToConnection];
[strongSelf copyConnectionToFlow];
} else if (state == nw_connection_state_failed) {
STLogError("tcp[%{public}llu]: failed - %{public}@",
fid, [STUtils describeConnectionPath:strongSelf.connection]);
STLogError("tcp[%{public}llu]: connection failed: %{public}@", fid, nsError ?: @"nil");
[strongSelf closeWithError:nsError stage:@"conn-failed"];
} else if (state == nw_connection_state_cancelled) {
[strongSelf closeWithError:nsError stage:@"conn-cancelled"];
}
});
nw_connection_start(self.connection);
}
#pragma mark - app -> remote
/*! Issues one read. The next read is started as soon as this one returns, i.e.
* without waiting for the send to complete - the send is what has to cross the
* network, and waiting for it turned the relay into stop-and-wait. Ordering is
* still guaranteed: sends on one connection are delivered in the order issued. */
- (void)copyFlowToConnection
{
const uint64_t fid = self.flowId;
__weak FlowTCP *weakSelf = self;
[self.flow readDataWithCompletionHandler:^(NSData *data, NSError *error) {
FlowTCP *strongSelf = weakSelf;
if (strongSelf == nil || strongSelf.closed) {
return;
}
dispatch_async(strongSelf.queue, ^{
FlowTCP *self2 = weakSelf;
if (self2 == nil || self2.closed) {
return;
}
if (error != nil) {
STLogError("tcp[%{public}llu]: flow read failed: %{public}@", fid, error);
[self2 closeWithError:error stage:@"flow-read"];
return;
}
if (data == nil) {
[self2 closeWithError:nil stage:@"flow-read-nil"];
return;
}
if (data.length == 0) {
// The app half-closed its side. Propagate a real FIN and keep
// reading the response - do NOT cancel the connection here.
self2.flowEofSeen = YES;
STLogDebug("tcp[%{public}llu]: app half-closed after %{public}llu bytes out, sending FIN",
fid, self2.bytesOut);
nw_connection_send(self2.connection, NULL, NW_CONNECTION_FINAL_MESSAGE_CONTEXT, true,
^(nw_error_t sendError) {
NSError *nsError = [STUtils errorFromNWError:sendError];
if (nsError != nil) {
STLogError("tcp[%{public}llu]: FIN send failed: %{public}@", fid, nsError);
}
});
return;
}
const uint64_t length = data.length;
self2.bytesOut = self2.bytesOut + length;
self2.pendingSendBytes += length;
dispatch_data_t payload = dispatch_data_create(data.bytes, data.length, self2.queue,
DISPATCH_DATA_DESTRUCTOR_DEFAULT);
nw_connection_send(self2.connection, payload, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true,
^(nw_error_t sendError) {
FlowTCP *inner = weakSelf;
if (inner == nil || inner.closed) {
return;
}
NSError *nsError = [STUtils errorFromNWError:sendError];
if (nsError != nil) {
STLogError("tcp[%{public}llu]: remote send failed: %{public}@", fid, nsError);
[inner closeWithError:nsError stage:@"remote-send"];
return;
}
inner.pendingSendBytes -= MIN(inner.pendingSendBytes, length);
if (inner.readPaused && inner.pendingSendBytes <= kSendLowWater) {
inner.readPaused = NO;
STLogDebug("tcp[%{public}llu]: resuming reads, backlog %{public}llu",
fid, inner.pendingSendBytes);
[inner copyFlowToConnection];
}
});
if (self2.pendingSendBytes >= kSendHighWater) {
self2.readPaused = YES;
STLogDebug("tcp[%{public}llu]: pausing reads, backlog %{public}llu",
fid, self2.pendingSendBytes);
} else {
[self2 copyFlowToConnection];
}
});
}];
}
#pragma mark - remote -> app
/*! Same idea in the other direction: the next receive is issued immediately and
* the writes to the flow are drained through a backlog, because NEAppProxyFlow
* allows only one outstanding write. */
- (void)copyConnectionToFlow
{
const uint64_t fid = self.flowId;
__weak FlowTCP *weakSelf = self;
nw_connection_receive(self.connection, 1, UINT32_MAX,
^(dispatch_data_t content, nw_content_context_t context, bool isComplete, nw_error_t error) {
(void)context;
FlowTCP *strongSelf = weakSelf;
if (strongSelf == nil || strongSelf.closed) {
return;
}
NSError *nsError = [STUtils errorFromNWError:error];
if (nsError != nil) {
STLogError("tcp[%{public}llu]: remote receive failed: %{public}@", fid, nsError);
[strongSelf closeWithError:nsError stage:@"remote-receive"];
return;
}
NSData *data = [STUtils dataFromDispatchData:content];
if (data.length > 0) {
strongSelf.bytesIn = strongSelf.bytesIn + data.length;
[strongSelf.writeBacklog addObject:data];
[strongSelf drainWriteBacklog];
}
if (isComplete) {
STLogDebug("tcp[%{public}llu]: remote finished the stream", fid);
strongSelf.remoteEofSeen = YES;
[strongSelf drainWriteBacklog];
return;
}
[strongSelf copyConnectionToFlow];
});
}
- (void)drainWriteBacklog
{
if (self.writeInFlight || self.closed) {
return;
}
if (self.writeBacklog.count == 0) {
if (self.remoteEofSeen) {
[self closeWithError:nil stage:@"remote-eof"];
}
return;
}
NSData *chunk = self.writeBacklog.firstObject;
[self.writeBacklog removeObjectAtIndex:0];
self.writeInFlight = YES;
const uint64_t fid = self.flowId;
__weak FlowTCP *weakSelf = self;
[self.flow writeData:chunk withCompletionHandler:^(NSError *writeError) {
FlowTCP *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
dispatch_async(strongSelf.queue, ^{
FlowTCP *self2 = weakSelf;
if (self2 == nil) {
return;
}
self2.writeInFlight = NO;
if (writeError != nil) {
STLogError("tcp[%{public}llu]: flow write failed: %{public}@", fid, writeError);
[self2 closeWithError:writeError stage:@"flow-write"];
return;
}
[self2 drainWriteBacklog];
});
}];
}
+ (void)closeAll
{
__block NSArray<FlowTCP *> *live = nil;
dispatch_sync([STUtils stateQueue], ^{
live = [TCPSessionsLocked() allObjects];
});
if (live.count > 0) {
STLogInfo("tcp: closing %{public}lu live session(s) on stop", (unsigned long)live.count);
}
for (FlowTCP *session in live) {
[session closeWithError:nil stage:@"proxy-stopped"];
}
}
#pragma mark - teardown
- (void)closeWithError:(NSError *)error stage:(NSString *)stage
{
// Keep ourselves alive: removing from the registry may drop the last reference.
FlowTCP *keepAlive = self;
@synchronized(keepAlive) {
if (keepAlive.closed) {
return;
}
keepAlive.closed = YES;
}
STLogDebug("tcp[%{public}llu]: closing at %{public}@ out=%{public}llu in=%{public}llu error=%{public}@",
keepAlive.flowId, stage ?: @"?", keepAlive.bytesOut, keepAlive.bytesIn, error ?: @"nil");
[keepAlive.flow closeReadWithError:error];
[keepAlive.flow closeWriteWithError:error];
nw_connection_t connection = keepAlive.connection;
if (connection != NULL) {
nw_connection_cancel(connection);
keepAlive.connection = NULL;
}
[STStats tcpClosedWithOut:keepAlive.bytesOut in:keepAlive.bytesIn];
dispatch_async([STUtils stateQueue], ^{
[TCPSessionsLocked() removeObject:keepAlive];
});
}
@end
@@ -0,0 +1,19 @@
#ifndef AMNEZIA_SPLIT_TUNNEL_FLOW_UDP_H
#define AMNEZIA_SPLIT_TUNNEL_FLOW_UDP_H
#import <Network/Network.h>
#import <NetworkExtension/NetworkExtension.h>
@interface FlowUDP : NSObject
/*! Takes ownership of `flow` and proxies its datagrams out of `interface`.
* `flowId` only correlates log lines. */
+ (void)handleFlow:(NEAppProxyUDPFlow *)flow interface:(nw_interface_t)interface flowId:(uint64_t)flowId;
/*! Tears down every live session. Called when the proxy stops, so the
* registry does not keep finished sessions alive across restarts. */
+ (void)closeAll;
@end
#endif
@@ -0,0 +1,336 @@
#import "FlowUDP.h"
#import "Utils.h"
#import <os/log.h>
@interface FlowUDP ()
@property (atomic) NEAppProxyUDPFlow *flow;
@property (atomic) nw_interface_t interface;
@property (atomic) BOOL closed;
@property (atomic) uint64_t flowId;
@property (atomic) uint64_t datagramsOut;
@property (atomic) uint64_t datagramsIn;
/*! Guarded by STUtils.stateQueue. */
@property (nonatomic) NSMutableDictionary<NSString *, nw_connection_t> *connections;
/*! Per-session queue for the remote connections, so one flow cannot stall the
* others. Previously every connection of every flow shared the main queue. */
@property (nonatomic) dispatch_queue_t queue;
- (void)closeWithError:(NSError *)error stage:(NSString *)stage;
@end
/*! Registry keeping sessions alive while they are running.
* MUST only be touched on STUtils.stateQueue. */
static NSMutableSet<FlowUDP *> *UDPSessionsLocked(void)
{
static NSMutableSet<FlowUDP *> *sessions;
static dispatch_once_t once;
dispatch_once(&once, ^{
sessions = [NSMutableSet set];
});
return sessions;
}
@implementation FlowUDP
+ (void)handleFlow:(NEAppProxyUDPFlow *)flow interface:(nw_interface_t)interface flowId:(uint64_t)flowId
{
FlowUDP *session = [[FlowUDP alloc] init];
session.flow = flow;
session.interface = interface;
session.flowId = flowId;
session.connections = [NSMutableDictionary dictionary];
char label[64];
snprintf(label, sizeof(label), "org.amnezia.split-tunnel.udp.%llu", (unsigned long long)flowId);
session.queue = dispatch_queue_create(label, DISPATCH_QUEUE_SERIAL);
[STStats udpOpened];
dispatch_sync([STUtils stateQueue], ^{
[UDPSessionsLocked() addObject:session];
STLogDebug("udp[%{public}llu]: registered, %{public}lu live udp sessions",
flowId, (unsigned long)UDPSessionsLocked().count);
});
[session start];
}
- (void)start
{
const uint64_t fid = self.flowId;
STLogInfo("udp[%{public}llu]: opening flow, pinned if=%{public}s", fid,
self.interface != NULL ? (nw_interface_get_name(self.interface) ?: "?") : "(default)");
if (self.interface == NULL) {
STLogError("udp[%{public}llu]: no interface pinned - the bypass may leak back into the tunnel", fid);
}
__weak FlowUDP *weakSelf = self;
void (^opened)(NSError *) = ^(NSError *error) {
FlowUDP *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
if (error != nil) {
STLogError("udp[%{public}llu]: open flow failed: %{public}@", fid, error);
[strongSelf closeWithError:error stage:@"open-flow"];
return;
}
STLogDebug("udp[%{public}llu]: flow opened", fid);
[strongSelf readDatagrams];
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (@available(macOS 15.0, *)) {
[self.flow openWithLocalFlowEndpoint:nil completionHandler:opened];
} else {
[self.flow openWithLocalEndpoint:nil completionHandler:opened];
}
#pragma clang diagnostic pop
}
- (NSString *)keyForEndpoint:(NWHostEndpoint *)endpoint
{
return [NSString stringWithFormat:@"%@:%@", endpoint.hostname, endpoint.port];
}
#pragma mark - app -> remote
- (void)readDatagrams
{
const uint64_t fid = self.flowId;
__weak FlowUDP *weakSelf = self;
[self.flow readDatagramsWithCompletionHandler:^(NSArray<NSData *> *datagrams, NSArray<NWEndpoint *> *remoteEndpoints, NSError *error) {
FlowUDP *strongSelf = weakSelf;
if (strongSelf == nil || strongSelf.closed) {
return;
}
if (error != nil) {
STLogError("udp[%{public}llu]: flow read failed: %{public}@", fid, error);
[strongSelf closeWithError:error stage:@"flow-read"];
return;
}
if (datagrams.count == 0) {
STLogInfo("udp[%{public}llu]: flow reported end of datagrams", fid);
[strongSelf closeWithError:nil stage:@"flow-eof"];
return;
}
const NSUInteger count = MIN(datagrams.count, remoteEndpoints.count);
if (datagrams.count != remoteEndpoints.count) {
STLogError("udp[%{public}llu]: datagram/endpoint count mismatch %{public}lu vs %{public}lu",
fid, (unsigned long)datagrams.count, (unsigned long)remoteEndpoints.count);
}
STLogDebug("udp[%{public}llu]: app -> remote batch of %{public}lu datagrams", fid, (unsigned long)count);
for (NSUInteger i = 0; i < count; i++) {
NWEndpoint *endpoint = remoteEndpoints[i];
if (![endpoint isKindOfClass:[NWHostEndpoint class]]) {
STLogError("udp[%{public}llu]: endpoint[%{public}lu] is %{public}@, skipped",
fid, (unsigned long)i, [endpoint class]);
continue;
}
[strongSelf sendDatagram:datagrams[i] toHost:(NWHostEndpoint *)endpoint];
}
[strongSelf readDatagrams];
}];
}
/*! Returns the connection for `host`, creating and starting it if needed.
* All access to the connection map happens on STUtils.stateQueue. */
- (nw_connection_t)connectionForHost:(NWHostEndpoint *)host
{
const uint64_t fid = self.flowId;
NSString *key = [self keyForEndpoint:host];
__block nw_connection_t result = NULL;
__block BOOL created = NO;
dispatch_sync([STUtils stateQueue], ^{
if (self.closed) {
return;
}
result = self.connections[key];
if (result != NULL) {
return;
}
nw_endpoint_t remote = [STUtils copyEndpointFromHost:host.hostname port:host.port];
if (remote == NULL) {
STLogError("udp[%{public}llu]: cannot build endpoint for %{public}@", fid, key);
return;
}
nw_parameters_t params = nw_parameters_create_secure_udp(NW_PARAMETERS_DISABLE_PROTOCOL,
NW_PARAMETERS_DEFAULT_CONFIGURATION);
if (self.interface != NULL) {
nw_parameters_require_interface(params, self.interface);
}
result = nw_connection_create(remote, params);
self.connections[key] = result;
created = YES;
STLogInfo("udp[%{public}llu]: new remote connection %{public}@ (%{public}lu open)",
fid, key, (unsigned long)self.connections.count);
});
if (!created || result == NULL) {
return result;
}
__weak FlowUDP *weakSelf = self;
nw_connection_t connection = result;
nw_connection_set_queue(connection, self.queue);
nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t error) {
FlowUDP *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
NSError *nsError = [STUtils errorFromNWError:error];
STLogDebug("udp[%{public}llu]: %{public}@ state=%{public}s error=%{public}@",
fid, key, [STUtils connectionStateName:state], nsError ?: @"nil");
if (state == nw_connection_state_waiting || state == nw_connection_state_failed) {
// "waiting" with no error means the system found no usable path for
// the interface this flow is pinned to; the path itself says why.
STLogInfo("udp[%{public}llu]: %{public}@ %{public}s - %{public}@",
fid, key, [STUtils connectionStateName:state],
[STUtils describeConnectionPath:connection]);
}
if (state == nw_connection_state_ready) {
[strongSelf receiveFromConnection:connection host:host key:key];
} else if (state == nw_connection_state_failed || state == nw_connection_state_cancelled) {
if (state == nw_connection_state_failed) {
STLogError("udp[%{public}llu]: %{public}@ failed: %{public}@", fid, key, nsError ?: @"nil");
}
[strongSelf forgetConnectionForKey:key cancel:(state == nw_connection_state_failed)];
}
});
nw_connection_start(connection);
return connection;
}
- (void)forgetConnectionForKey:(NSString *)key cancel:(BOOL)cancel
{
const uint64_t fid = self.flowId;
dispatch_async([STUtils stateQueue], ^{
nw_connection_t connection = self.connections[key];
if (connection == NULL) {
return;
}
[self.connections removeObjectForKey:key];
if (cancel) {
nw_connection_cancel(connection);
}
STLogDebug("udp[%{public}llu]: dropped remote connection %{public}@ (%{public}lu left)",
fid, key, (unsigned long)self.connections.count);
});
}
- (void)sendDatagram:(NSData *)datagram toHost:(NWHostEndpoint *)host
{
const uint64_t fid = self.flowId;
nw_connection_t connection = [self connectionForHost:host];
if (connection == NULL) {
STLogError("udp[%{public}llu]: no connection for %{public}@:%{public}@, datagram dropped",
fid, host.hostname, host.port);
return;
}
self.datagramsOut = self.datagramsOut + 1;
STLogDebug("udp[%{public}llu]: app -> %{public}@:%{public}@ %{public}lu bytes (total out %{public}llu)",
fid, host.hostname, host.port, (unsigned long)datagram.length, self.datagramsOut);
dispatch_data_t payload = dispatch_data_create(datagram.bytes, datagram.length, self.queue,
DISPATCH_DATA_DESTRUCTOR_DEFAULT);
nw_connection_send(connection, payload, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t sendError) {
NSError *nsError = [STUtils errorFromNWError:sendError];
if (nsError != nil) {
STLogError("udp[%{public}llu]: send to %{public}@:%{public}@ failed: %{public}@",
fid, host.hostname, host.port, nsError);
}
});
}
#pragma mark - remote -> app
- (void)receiveFromConnection:(nw_connection_t)connection host:(NWHostEndpoint *)host key:(NSString *)key
{
const uint64_t fid = self.flowId;
__weak FlowUDP *weakSelf = self;
nw_connection_receive(connection, 1, UINT32_MAX,
^(dispatch_data_t content, nw_content_context_t context, bool isComplete, nw_error_t error) {
(void)context;
FlowUDP *strongSelf = weakSelf;
if (strongSelf == nil || strongSelf.closed) {
return;
}
NSError *nsError = [STUtils errorFromNWError:error];
if (nsError != nil) {
STLogError("udp[%{public}llu]: receive from %{public}@ failed: %{public}@",
fid, key, nsError);
[strongSelf forgetConnectionForKey:key cancel:YES];
return;
}
if (content != NULL) {
NSData *data = [STUtils dataFromDispatchData:content];
strongSelf.datagramsIn = strongSelf.datagramsIn + 1;
STLogDebug("udp[%{public}llu]: %{public}@ -> app %{public}lu bytes (total in %{public}llu)",
fid, key, (unsigned long)data.length, strongSelf.datagramsIn);
[strongSelf.flow writeDatagrams:@[ data ]
sentByEndpoints:@[ host ]
completionHandler:^(NSError *writeError) {
if (writeError != nil) {
STLogError("udp[%{public}llu]: flow write failed: %{public}@",
fid, writeError);
}
}];
}
if (isComplete) {
STLogDebug("udp[%{public}llu]: %{public}@ marked complete", fid, key);
[strongSelf forgetConnectionForKey:key cancel:YES];
return;
}
[strongSelf receiveFromConnection:connection host:host key:key];
});
}
+ (void)closeAll
{
__block NSArray<FlowUDP *> *live = nil;
dispatch_sync([STUtils stateQueue], ^{
live = [UDPSessionsLocked() allObjects];
});
if (live.count > 0) {
STLogInfo("udp: closing %{public}lu live session(s) on stop", (unsigned long)live.count);
}
for (FlowUDP *session in live) {
[session closeWithError:nil stage:@"proxy-stopped"];
}
}
#pragma mark - teardown
- (void)closeWithError:(NSError *)error stage:(NSString *)stage
{
FlowUDP *keepAlive = self;
@synchronized(keepAlive) {
if (keepAlive.closed) {
return;
}
keepAlive.closed = YES;
}
STLogInfo("udp[%{public}llu]: closing at %{public}@ out=%{public}llu in=%{public}llu error=%{public}@",
keepAlive.flowId, stage ?: @"?", keepAlive.datagramsOut, keepAlive.datagramsIn, error ?: @"nil");
[keepAlive.flow closeReadWithError:error];
[keepAlive.flow closeWriteWithError:error];
[STStats udpClosedWithOut:keepAlive.datagramsOut in:keepAlive.datagramsIn];
dispatch_async([STUtils stateQueue], ^{
for (nw_connection_t connection in keepAlive.connections.allValues) {
nw_connection_cancel(connection);
}
[keepAlive.connections removeAllObjects];
[UDPSessionsLocked() removeObject:keepAlive];
STLogDebug("udp[%{public}llu]: unregistered, %{public}lu live udp sessions",
keepAlive.flowId, (unsigned long)UDPSessionsLocked().count);
});
}
@end
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundleExecutable</key>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundlePackageType</key>
<string>SYSX</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>LSMinimumSystemVersion</key>
<string>12.0</string>
<key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>NSSystemExtensionUsageDescription</key>
<string>AmneziaVPN uses a system extension to exclude selected apps from the VPN tunnel.</string>
<key>NetworkExtension</key>
<dict>
<key>NEProviderClasses</key>
<dict>
<key>com.apple.networkextension.app-proxy</key>
<string>TransparentProxyProvider</string>
</dict>
</dict>
</dict>
</plist>
@@ -0,0 +1,27 @@
#ifndef AMNEZIA_SPLIT_TUNNEL_SETTINGS_H
#define AMNEZIA_SPLIT_TUNNEL_SETTINGS_H
#import "AppPolicy.h"
#import <Foundation/Foundation.h>
#import <NetworkExtension/NetworkExtension.h>
/*!
* Configuration pushed from the host app, either through the start options or
* through a provider message.
*
* Thread safety: `vpnServer` is an atomic copy property and `policy` publishes
* immutable snapshots, so readers on flow queues never see a torn state.
*/
@interface STSettings : NSObject
@property (nonatomic, readonly) STAppPolicy *policy;
@property (atomic, copy, readonly) NSString *vpnServer;
/*! Returns YES when the dictionary was understood and applied. */
- (BOOL)applyDictionary:(NSDictionary *)dict source:(NSString *)source;
- (NSArray<NENetworkRule *> *)excludedNetworkRules;
@end
#endif
@@ -0,0 +1,169 @@
#import "Settings.h"
#import "Utils.h"
@interface STSettings ()
@property (atomic, copy, readwrite) NSString *vpnServer;
@end
@implementation STSettings
- (instancetype)init
{
self = [super init];
if (self) {
_policy = [[STAppPolicy alloc] init];
_vpnServer = @"";
}
return self;
}
- (BOOL)applyDictionary:(NSDictionary *)dict source:(NSString *)source
{
NSString *where = source.length > 0 ? source : @"?";
if (![dict isKindOfClass:[NSDictionary class]]) {
STLogError("settings[%{public}@]: payload is not a dictionary (%{public}@)", where, [dict class]);
return NO;
}
STLogInfo("settings[%{public}@]: applying keys=%{public}@", where, dict.allKeys ?: @[]);
const STRouteMode mode = STRouteModeFromString(dict[@"mode"]);
self.policy.mode = mode;
STLogInfo("settings[%{public}@]: mode raw=%{public}@ parsed=%{public}s",
where, dict[@"mode"] ?: @"(nil)", STRouteModeName(mode));
if (mode == STRouteModeUnknown) {
STLogError("settings[%{public}@]: unknown mode, the provider will not claim any flow", where);
}
// Self-exclusion data. Mandatory for "only" mode, where everything that is
// not listed gets claimed - including, without this, our own relay sockets
// and the traffic of the bundled VPN helpers.
id selfBundleId = dict[@"selfBundleId"];
if ([selfBundleId isKindOfClass:[NSString class]]) {
self.policy.selfBundleIdPrefix = selfBundleId;
}
id selfAppPath = dict[@"selfAppPath"];
if ([selfAppPath isKindOfClass:[NSString class]]) {
self.policy.selfAppPath = selfAppPath;
}
STLogInfo("settings[%{public}@]: self exclusion bundleIdPrefix=%{public}@ appPath=%{public}@",
where, self.policy.selfBundleIdPrefix ?: @"", self.policy.selfAppPath ?: @"");
if (mode == STRouteModeOnly && ![self.policy isSelfExclusionUsable]) {
STLogError("settings[%{public}@]: only mode requires selfBundleId/selfAppPath - refusing to claim "
"any flow, otherwise the provider would relay its own traffic", where);
}
id server = dict[@"vpnServer"];
if ([server isKindOfClass:[NSString class]]) {
self.vpnServer = [server copy];
STLogInfo("settings[%{public}@]: vpnServer=%{public}@ (ipv4=%{public}d ipv6=%{public}d)",
where, self.vpnServer,
(int)[STUtils isIPv4Address:self.vpnServer], (int)[STUtils isIPv6Address:self.vpnServer]);
if (self.vpnServer.length == 0) {
STLogError("settings[%{public}@]: vpnServer is empty - the VPN endpoint will not be excluded "
"from the proxy rules", where);
} else if (![STUtils isIPv4Address:self.vpnServer] && ![STUtils isIPv6Address:self.vpnServer]) {
STLogError("settings[%{public}@]: vpnServer %{public}@ is not a literal IP address - no exclude "
"rule will be generated for it", where, self.vpnServer);
}
} else if (server != nil) {
STLogError("settings[%{public}@]: vpnServer is not a string (%{public}@)", where, [server class]);
}
id apps = dict[@"apps"];
if (![apps isKindOfClass:[NSArray class]]) {
STLogError("settings[%{public}@]: apps missing or not an array (%{public}@)", where, [apps class]);
return NO;
}
STLogInfo("settings[%{public}@]: apps count=%{public}lu", where, (unsigned long)[apps count]);
NSMutableArray<STAppEntry *> *entries = [NSMutableArray array];
NSUInteger i = 0;
for (id item in (NSArray *)apps) {
if (![item isKindOfClass:[NSDictionary class]]) {
STLogError("settings[%{public}@]: apps[%{public}lu] is not a dictionary (%{public}@)",
where, (unsigned long)i, [item class]);
++i;
continue;
}
STAppEntry *entry = [[STAppEntry alloc] init];
id bundleId = item[@"bundleId"];
id path = item[@"path"];
if ([bundleId isKindOfClass:[NSString class]]) {
entry.bundleId = bundleId;
}
if ([path isKindOfClass:[NSString class]]) {
entry.path = path;
}
STLogInfo("settings[%{public}@]: apps[%{public}lu] bundleId=%{public}@ path=%{public}@",
where, (unsigned long)i, entry.bundleId ?: @"", entry.path ?: @"");
if (entry.bundleId.length > 0 || entry.path.length > 0) {
[entries addObject:entry];
} else {
STLogError("settings[%{public}@]: apps[%{public}lu] has neither bundleId nor path, skipped",
where, (unsigned long)i);
}
++i;
}
[self.policy replaceApps:entries];
return YES;
}
- (NENetworkRule *)ruleForHost:(NSString *)host prefix:(NSUInteger)prefix
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NWHostEndpoint *endpoint = [NWHostEndpoint endpointWithHostname:host port:@"0"];
return [[NENetworkRule alloc] initWithRemoteNetwork:endpoint
remotePrefix:prefix
localNetwork:nil
localPrefix:0
protocol:NENetworkRuleProtocolAny
direction:NETrafficDirectionOutbound];
#pragma clang diagnostic pop
}
- (NSArray<NENetworkRule *> *)excludedNetworkRules
{
NSArray<NSArray *> *specs = @[
@[ @"127.0.0.0", @8 ],
@[ @"10.0.0.0", @8 ],
@[ @"172.16.0.0", @12 ],
@[ @"192.168.0.0", @16 ],
@[ @"169.254.0.0", @16 ],
// RFC 6598 carrier-grade NAT. VPN tunnels commonly address their
// gateway and resolver here (100.64.0.1). Claiming these flows pushes
// them out of the physical interface, where the address does not exist,
// and every lookup then waits for a timeout.
@[ @"100.64.0.0", @10 ],
@[ @"::1", @128 ],
@[ @"fc00::", @7 ],
@[ @"fe80::", @10 ],
];
NSMutableArray<NENetworkRule *> *rules = [NSMutableArray array];
for (NSArray *spec in specs) {
NSString *host = spec[0];
NSUInteger prefix = [spec[1] unsignedIntegerValue];
[rules addObject:[self ruleForHost:host prefix:prefix]];
STLogInfo("settings: exclude rule %{public}@/%{public}lu", host, (unsigned long)prefix);
}
NSString *server = self.vpnServer;
if ([STUtils isIPv4Address:server]) {
[rules addObject:[self ruleForHost:server prefix:32]];
STLogInfo("settings: exclude rule %{public}@/32 (vpn server, ipv4)", server);
} else if ([STUtils isIPv6Address:server]) {
[rules addObject:[self ruleForHost:server prefix:128]];
STLogInfo("settings: exclude rule %{public}@/128 (vpn server, ipv6)", server);
} else {
STLogError("settings: no exclude rule for the VPN server (value=%{public}@)", server ?: @"");
}
STLogInfo("settings: %{public}lu exclude rules total", (unsigned long)rules.count);
return rules;
}
@end
@@ -0,0 +1,9 @@
#ifndef AMNEZIA_SPLIT_TUNNEL_TRANSPARENT_PROXY_PROVIDER_H
#define AMNEZIA_SPLIT_TUNNEL_TRANSPARENT_PROXY_PROVIDER_H
#import <NetworkExtension/NetworkExtension.h>
@interface TransparentProxyProvider : NETransparentProxyProvider
@end
#endif
@@ -0,0 +1,366 @@
#import "TransparentProxyProvider.h"
#import "FlowTCP.h"
#import "FlowUDP.h"
#import "Settings.h"
#import "Utils.h"
#import <Network/Network.h>
#import <os/log.h>
#import <unistd.h>
namespace {
const char *StopReasonName(NEProviderStopReason reason)
{
switch (reason) {
case NEProviderStopReasonNone: return "none";
case NEProviderStopReasonUserInitiated: return "userInitiated";
case NEProviderStopReasonProviderFailed: return "providerFailed";
case NEProviderStopReasonNoNetworkAvailable: return "noNetworkAvailable";
case NEProviderStopReasonUnrecoverableNetworkChange: return "unrecoverableNetworkChange";
case NEProviderStopReasonProviderDisabled: return "providerDisabled";
case NEProviderStopReasonAuthenticationCanceled: return "authenticationCanceled";
case NEProviderStopReasonConfigurationFailed: return "configurationFailed";
case NEProviderStopReasonIdleTimeout: return "idleTimeout";
case NEProviderStopReasonConfigurationDisabled: return "configurationDisabled";
case NEProviderStopReasonConfigurationRemoved: return "configurationRemoved";
case NEProviderStopReasonSuperceded: return "superceded";
case NEProviderStopReasonUserLogout: return "userLogout";
case NEProviderStopReasonUserSwitch: return "userSwitch";
case NEProviderStopReasonConnectionFailed: return "connectionFailed";
case NEProviderStopReasonSleep: return "sleep";
case NEProviderStopReasonAppUpdate: return "appUpdate";
default: return "unknown";
}
}
/*! Cap on the "first time we saw this app" log set, so a long-running proxy
* cannot grow it without bound. */
const NSUInteger kSeenSigningIdsLimit = 512;
} // namespace
@interface TransparentProxyProvider ()
/*! Written by the path monitor (main queue), read from flow queues. */
@property (atomic) nw_interface_t physicalInterface;
@end
@implementation TransparentProxyProvider {
STSettings *_settings;
nw_path_monitor_t _pathMonitor;
/*! Guarded by STUtils.stateQueue. */
NSMutableSet<NSString *> *_seenSigningIds;
/*! Periodic relay summary, so a long session leaves a trace even when the
* per-flow lines are at debug level. */
dispatch_source_t _statsTimer;
}
- (instancetype)init
{
self = [super init];
if (self) {
_settings = [[STSettings alloc] init];
_seenSigningIds = [NSMutableSet set];
STLogInfo("provider: init pid=%{public}d uid=%{public}d gid=%{public}d",
(int)getpid(), (int)getuid(), (int)getgid());
}
return self;
}
#pragma mark - Logging
- (void)applyLogSettings:(NSDictionary *)options
{
id debugFlag = options[@"logDebug"];
if ([debugFlag respondsToSelector:@selector(boolValue)]) {
[STFileLog setDebugEnabled:[debugFlag boolValue]];
}
id dir = options[@"logDir"];
if ([dir isKindOfClass:[NSString class]] && [dir length] > 0) {
[STFileLog configureWithDirectory:dir];
STLogInfo("provider: file logging directory=%{public}@ debug=%{public}d",
dir, (int)[STFileLog isDebugEnabled]);
} else {
os_log(STUtils.log, "provider: no logDir in the options, file logging stays off "
"(os_log still works)");
}
}
- (void)startStatsTimer
{
if (_statsTimer != nil) {
return;
}
_statsTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, [STUtils stateQueue]);
dispatch_source_set_timer(_statsTimer, dispatch_time(DISPATCH_TIME_NOW, 60 * NSEC_PER_SEC),
60 * NSEC_PER_SEC, 5 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_statsTimer, ^{
STLogInfo("provider: relay stats: %{public}@", [STStats summary]);
});
dispatch_resume(_statsTimer);
STLogDebug("provider: stats ticker started (every 60s)");
}
- (void)stopStatsTimer
{
if (_statsTimer != nil) {
dispatch_source_cancel(_statsTimer);
_statsTimer = nil;
}
}
#pragma mark - Physical interface tracking
- (void)startPathMonitor
{
if (_pathMonitor != NULL) {
STLogDebug("provider: path monitor already running");
return;
}
STLogInfo("provider: starting path monitor");
_pathMonitor = nw_path_monitor_create();
nw_path_monitor_set_queue(_pathMonitor, dispatch_get_main_queue());
__weak TransparentProxyProvider *weakSelf = self;
nw_path_monitor_set_update_handler(_pathMonitor, ^(nw_path_t path) {
TransparentProxyProvider *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
const nw_path_status_t status = nw_path_get_status(path);
__block nw_interface_t found = NULL;
nw_path_enumerate_interfaces(path, ^bool(nw_interface_t interface) {
const nw_interface_type_t type = nw_interface_get_type(interface);
STLogDebug("provider: path interface name=%{public}s type=%{public}d",
nw_interface_get_name(interface) ?: "?", (int)type);
if (found == NULL && (type == nw_interface_type_wifi || type == nw_interface_type_wired)) {
found = interface;
}
return true;
});
nw_interface_t previous = strongSelf.physicalInterface;
const char *previousName = previous != NULL ? (nw_interface_get_name(previous) ?: "?") : "(none)";
const char *foundName = found != NULL ? (nw_interface_get_name(found) ?: "?") : "(none)";
strongSelf.physicalInterface = found;
STLogInfo("provider: path update status=%{public}d physical %{public}s -> %{public}s",
(int)status, previousName, foundName);
if (found == NULL) {
STLogError("provider: no wifi/wired interface available - excluded apps will fall back "
"into the tunnel until one appears");
}
});
nw_path_monitor_start(_pathMonitor);
}
- (void)stopPathMonitor
{
if (_pathMonitor != NULL) {
STLogInfo("provider: cancelling path monitor");
nw_path_monitor_cancel(_pathMonitor);
_pathMonitor = NULL;
}
self.physicalInterface = NULL;
}
#pragma mark - Lifecycle
- (void)startProxyWithOptions:(NSDictionary *)options completionHandler:(void (^)(NSError *))completionHandler
{
// Before anything else: a system extension runs as root and cannot find the
// user's Documents folder, so the host app hands us the directory.
[self applyLogSettings:options];
STLogInfo("provider: startProxy options=%{public}@", options ?: @{});
if (options == nil) {
STLogError("provider: startProxy called without options - the app list is empty, nothing will be excluded");
}
[_settings applyDictionary:options source:@"startProxy"];
[self startPathMonitor];
[self startStatsTimer];
NETransparentProxyNetworkSettings *settings =
[[NETransparentProxyNetworkSettings alloc] initWithTunnelRemoteAddress:@"127.0.0.1"];
// Wildcard include: both endpoints nil. An explicit ::/0 NWHostEndpoint drops the whole ruleset.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NENetworkRule *allOutbound = [[NENetworkRule alloc] initWithRemoteNetwork:nil
remotePrefix:0
localNetwork:nil
localPrefix:0
protocol:NENetworkRuleProtocolAny
direction:NETrafficDirectionOutbound];
#pragma clang diagnostic pop
settings.includedNetworkRules = @[ allOutbound ];
settings.excludedNetworkRules = [_settings excludedNetworkRules];
STLogInfo("provider: applying network settings included=%{public}lu excluded=%{public}lu",
(unsigned long)settings.includedNetworkRules.count,
(unsigned long)settings.excludedNetworkRules.count);
[self setTunnelNetworkSettings:settings completionHandler:^(NSError *error) {
if (error != nil) {
STLogError("provider: setTunnelNetworkSettings failed: %{public}@", error);
} else {
STLogInfo("provider: setTunnelNetworkSettings ok, proxy is live");
}
completionHandler(error);
}];
}
- (void)stopProxyWithReason:(NEProviderStopReason)reason completionHandler:(void (^)(void))completionHandler
{
STLogInfo("provider: stopProxy reason=%{public}s (%{public}d)", StopReasonName(reason), (int)reason);
STLogInfo("provider: final relay stats: %{public}@", [STStats summary]);
[self stopStatsTimer];
[self stopPathMonitor];
// Without this the registries keep every still-open session alive, and the
// counters keep reporting them as active across proxy restarts.
[FlowTCP closeAll];
[FlowUDP closeAll];
dispatch_sync([STUtils stateQueue], ^{
STLogInfo("provider: clearing %{public}lu remembered signing ids",
(unsigned long)self->_seenSigningIds.count);
[self->_seenSigningIds removeAllObjects];
});
completionHandler();
}
- (void)handleAppMessage:(NSData *)messageData completionHandler:(void (^)(NSData *))completionHandler
{
STLogInfo("provider: handleAppMessage %{public}lu bytes", (unsigned long)messageData.length);
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:messageData options:0 error:&error];
BOOL ok = NO;
if (error == nil && [json isKindOfClass:[NSDictionary class]]) {
[self applyLogSettings:json];
ok = [_settings applyDictionary:json source:@"appMessage"];
} else {
STLogError("provider: handleAppMessage parse failed: %{public}@", error);
}
if (completionHandler != nil) {
NSDictionary *reply = @{ @"ok" : @(ok) };
NSData *replyData = [NSJSONSerialization dataWithJSONObject:reply options:0 error:NULL];
completionHandler(replyData);
}
}
#pragma mark - Flow handling
- (void)noteFirstSightOfSigningId:(NSString *)sid path:(NSString *)path
{
if (sid.length == 0) {
return;
}
dispatch_async([STUtils stateQueue], ^{
if ([self->_seenSigningIds containsObject:sid]) {
return;
}
if (self->_seenSigningIds.count >= kSeenSigningIdsLimit) {
STLogDebug("provider: seen-ids cache full (%{public}lu), resetting",
(unsigned long)self->_seenSigningIds.count);
[self->_seenSigningIds removeAllObjects];
}
[self->_seenSigningIds addObject:sid];
STLogInfo("provider: first flow from sid=%{public}@ path=%{public}@", sid, path ?: @"");
});
}
- (BOOL)proxyFlow:(NEAppProxyFlow *)flow
{
const uint64_t flowId = [STUtils nextFlowId];
NSString *sid = flow.metaData.sourceAppSigningIdentifier;
// Resolving the audit token goes through the code-signing machinery, which is
// far from free. Skip it when the signing identifier alone already decides.
NSString *path = [_settings.policy needsPathForSigningId:sid]
? [STUtils pathFromAuditTokenData:flow.metaData.sourceAppAuditToken]
: nil;
const char *kind = [flow isKindOfClass:[NEAppProxyTCPFlow class]]
? "tcp"
: ([flow isKindOfClass:[NEAppProxyUDPFlow class]] ? "udp" : "other");
[self noteFirstSightOfSigningId:sid path:path];
const STRouteMode mode = _settings.policy.mode;
const STFlowVerdict verdict = [_settings.policy verdictForSigningId:sid path:path];
// Log the rare side of the decision at info level and the common side at
// debug, so neither mode floods the log: "except" claims few flows, "only"
// claims nearly all of them. The reason string is rendered only when the
// line is really emitted - verdictForSigningId itself allocates nothing.
const BOOL bypassIsRare = (mode != STRouteModeOnly);
if (verdict.decision != STFlowDecisionBypass) {
if (!bypassIsRare || os_log_type_enabled(STUtils.log, OS_LOG_TYPE_DEBUG)) {
NSString *reason = STDescribeVerdict(verdict);
if (bypassIsRare) {
STLogDebug("flow[%{public}llu] %{public}s sid=%{public}@ -> tunnel (%{public}@)",
flowId, kind, sid ?: @"", reason);
} else {
STLogInfo("flow[%{public}llu] %{public}s sid=%{public}@ path=%{public}@ -> tunnel (%{public}@)",
flowId, kind, sid ?: @"", path ?: @"", reason);
}
}
[STStats flowSentToTunnel];
return NO;
}
nw_interface_t physical = self.physicalInterface;
if (physical == NULL) {
STLogError("flow[%{public}llu] %{public}s sid=%{public}@ should leave the tunnel (%{public}@) but no "
"physical interface is available - leaving it to the system, so it goes through the tunnel",
flowId, kind, sid ?: @"", STDescribeVerdict(verdict));
return NO;
}
if (bypassIsRare) {
STLogInfo("flow[%{public}llu] %{public}s bypass sid=%{public}@ path=%{public}@ if=%{public}s (%{public}@)",
flowId, kind, sid ?: @"", path ?: @"", nw_interface_get_name(physical) ?: "?",
STDescribeVerdict(verdict));
} else if (os_log_type_enabled(STUtils.log, OS_LOG_TYPE_DEBUG)) {
STLogDebug("flow[%{public}llu] %{public}s bypass sid=%{public}@ if=%{public}s (%{public}@)",
flowId, kind, sid ?: @"", nw_interface_get_name(physical) ?: "?",
STDescribeVerdict(verdict));
}
if ([flow isKindOfClass:[NEAppProxyTCPFlow class]]) {
[FlowTCP handleFlow:(NEAppProxyTCPFlow *)flow interface:physical flowId:flowId];
return YES;
}
if ([flow isKindOfClass:[NEAppProxyUDPFlow class]]) {
[FlowUDP handleFlow:(NEAppProxyUDPFlow *)flow interface:physical flowId:flowId];
return YES;
}
STLogError("flow[%{public}llu] unsupported flow class %{public}@ - leaving it to the system",
flowId, [flow class]);
return NO;
}
- (BOOL)handleNewFlow:(NEAppProxyFlow *)flow
{
return [self proxyFlow:flow];
}
// Kept for macOS < 15; the system prefers the nw_endpoint_t variant below when
// it is available. Overriding a deprecated method is intentional here.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (BOOL)handleNewUDPFlow:(NEAppProxyUDPFlow *)flow initialRemoteEndpoint:(NWEndpoint *)remoteEndpoint
{
STLogDebug("provider: handleNewUDPFlow (legacy) remote=%{public}@", remoteEndpoint);
return [self proxyFlow:flow];
}
#pragma clang diagnostic pop
- (BOOL)handleNewUDPFlow:(NEAppProxyUDPFlow *)flow initialRemoteFlowEndpoint:(nw_endpoint_t)remoteEndpoint
API_AVAILABLE(macos(15.0))
{
STLogDebug("provider: handleNewUDPFlow (flow endpoint) remote=%{public}s",
remoteEndpoint != NULL ? (nw_endpoint_get_hostname(remoteEndpoint) ?: "?") : "(null)");
return [self proxyFlow:flow];
}
@end
+88
View File
@@ -0,0 +1,88 @@
#ifndef AMNEZIA_SPLIT_TUNNEL_UTILS_H
#define AMNEZIA_SPLIT_TUNNEL_UTILS_H
#import <Foundation/Foundation.h>
#import <Network/Network.h>
#import <dispatch/dispatch.h>
#import <os/log.h>
typedef NS_ENUM(NSInteger, STLogLevel) {
STLogLevelDebug = 0,
STLogLevelInfo,
STLogLevelError,
};
/*!
* Every log line goes to two places:
*
* - os_log, under the extension's bundle identifier as the subsystem, so
* `log stream --predicate 'subsystem == "..."'` keeps working;
* - a plain text file next to the app and service logs, so the whole picture
* can be collected from one folder.
*
* The file is only opened once the host app tells the extension where to write:
* a system extension runs as root, so it cannot derive the user's Documents
* folder on its own. The directory arrives in the start options as "logDir".
*
* Format strings use os_log syntax (%{public}@ and friends). For the file the
* annotations are stripped and the line is rendered with NSString formatting.
* Nothing is rendered at all when neither sink would accept the level, so the
* per-flow debug lines stay cheap while debug logging is off.
*/
FOUNDATION_EXPORT void STLogWrite(STLogLevel level, const char *fmt, ...);
#define STLogInfo(fmt, ...) STLogWrite(STLogLevelInfo, fmt, ##__VA_ARGS__)
#define STLogDebug(fmt, ...) STLogWrite(STLogLevelDebug, fmt, ##__VA_ARGS__)
#define STLogError(fmt, ...) STLogWrite(STLogLevelError, fmt, ##__VA_ARGS__)
@interface STFileLog : NSObject
/*! Opens <directory>/AmneziaVPNSplitTunnel_root/AmneziaVPNSplitTunnel.log.
* Safe to call repeatedly with the same directory - it is a no-op then. */
+ (void)configureWithDirectory:(NSString *)directory;
/*! Whether this level would be written to the file. */
+ (BOOL)acceptsLevel:(STLogLevel)level;
/*! Turns the per-read/per-datagram chatter on. Off by default. */
+ (void)setDebugEnabled:(BOOL)enabled;
+ (BOOL)isDebugEnabled;
+ (NSString *)currentPath;
@end
@interface STUtils : NSObject
+ (os_log_t)log;
/*! Serial queue guarding every shared mutable container in the extension
* (flow registries, the "seen signing ids" set). */
+ (dispatch_queue_t)stateQueue;
+ (NSString *)pathFromAuditTokenData:(NSData *)tokenData;
+ (nw_endpoint_t)copyEndpointFromHost:(NSString *)host port:(NSString *)port;
+ (BOOL)isIPv4Address:(NSString *)value;
+ (BOOL)isIPv6Address:(NSString *)value;
+ (NSData *)dataFromDispatchData:(dispatch_data_t)content;
+ (const char *)connectionStateName:(nw_connection_state_t)state;
/*! Why the system says a connection cannot proceed: path status, the reason it
* is unsatisfied, and the interfaces the path does offer. A connection pinned
* to a physical interface sits in "waiting" with a nil error when NECP has no
* usable path for it, and the error alone never says which of those it is. */
+ (NSString *)describeConnectionPath:(nw_connection_t)connection;
+ (NSError *)errorFromNWError:(nw_error_t)error;
+ (uint64_t)nextFlowId;
@end
/*! Cumulative relay counters, reported periodically by the provider. */
@interface STStats : NSObject
+ (void)tcpOpened;
+ (void)tcpClosedWithOut:(uint64_t)out in:(uint64_t)in;
+ (void)udpOpened;
+ (void)udpClosedWithOut:(uint64_t)out in:(uint64_t)in;
+ (void)flowSentToTunnel;
/*! One line summarising everything seen so far. */
+ (NSString *)summary;
@end
#endif
+578
View File
@@ -0,0 +1,578 @@
#import "Utils.h"
#import <Security/Security.h>
#import <arpa/inet.h>
#import <errno.h>
#import <fcntl.h>
#import <os/log.h>
#import <stdarg.h>
#import <stdatomic.h>
#import <string.h>
#import <sys/stat.h>
#import <unistd.h>
namespace {
/*! Roll the file over once it passes this size; one previous file is kept. */
const off_t kMaxLogFileSize = 32 * 1024 * 1024;
/*! Keep at most this many files from previous launches, newest first. */
const NSUInteger kMaxLogFiles = 10;
const char *LevelName(STLogLevel level)
{
switch (level) {
case STLogLevelDebug: return "DEBUG";
case STLogLevelInfo: return "INFO";
case STLogLevelError:
default: return "ERROR";
}
}
os_log_type_t OsLogType(STLogLevel level)
{
switch (level) {
case STLogLevelDebug: return OS_LOG_TYPE_DEBUG;
case STLogLevelInfo: return OS_LOG_TYPE_DEFAULT;
case STLogLevelError:
default: return OS_LOG_TYPE_ERROR;
}
}
/*! os_log accepts "%{public}@"; NSString formatting does not. Drop the
* "{...}" modifier that follows a '%' so the same call sites can feed both. */
NSString *StripOsLogModifiers(const char *fmt)
{
NSMutableString *out = [NSMutableString stringWithCapacity:strlen(fmt)];
for (const char *p = fmt; *p != '\0'; ++p) {
if (*p == '%' && *(p + 1) == '{') {
const char *close = strchr(p + 1, '}');
if (close != NULL) {
[out appendString:@"%"];
p = close;
continue;
}
}
[out appendFormat:@"%c", *p];
}
return out;
}
/*! The wall clock as the log renders it. Taken when the line is produced, not
* when it reaches the file, so buffered lines keep their real time. */
NSString *FormatTimestamp(NSDate *when)
{
static NSDateFormatter *formatter;
static dispatch_once_t once;
dispatch_once(&once, ^{
formatter = [[NSDateFormatter alloc] init];
// en_US_POSIX or the user's 12-hour locale turns HH into "2:16 PM".
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
formatter.timeZone = [NSTimeZone localTimeZone];
});
return [formatter stringFromDate:when];
}
/*! One timestamp per process, so every launch gets its own file and rotation
* keeps writing to the file this run started with. Shape matches the app and
* the service logs: AmneziaVPNSplitTunnel_2026-09-15_15-01-26.534.log */
NSString *LaunchStamp(void)
{
static NSString *stamp;
static dispatch_once_t once;
dispatch_once(&once, ^{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// en_US_POSIX, otherwise a 12-hour locale turns HH into "3 PM".
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"yyyy-MM-dd_HH-mm-ss.SSS";
formatter.timeZone = [NSTimeZone localTimeZone];
stamp = [formatter stringFromDate:[NSDate date]];
});
return stamp;
}
/*! A file per launch would grow without bound; keep the newest ones and drop
* the rest. Rotated ".log.1" files sort next to their parent and are counted
* with it, which is fine - they age out together. */
void PruneOldLogs(NSString *dir, NSString *keepPath)
{
NSFileManager *fm = [NSFileManager defaultManager];
NSArray<NSString *> *names = [fm contentsOfDirectoryAtPath:dir error:nil];
if (names == nil) {
return;
}
NSMutableArray<NSString *> *logs = [NSMutableArray array];
for (NSString *name in names) {
if (![name hasPrefix:@"AmneziaVPNSplitTunnel_"]) {
continue;
}
NSString *path = [dir stringByAppendingPathComponent:name];
if (![path isEqualToString:keepPath]) {
[logs addObject:path];
}
}
if (logs.count <= kMaxLogFiles) {
return;
}
[logs sortUsingSelector:@selector(compare:)];
const NSUInteger excess = logs.count - kMaxLogFiles;
for (NSUInteger i = 0; i < excess; ++i) {
[fm removeItemAtPath:logs[i] error:nil];
}
os_log(STUtils.log, "file log: pruned %{public}lu old file(s) in %{public}@",
(unsigned long)excess, dir);
}
} // namespace
#pragma mark - STFileLog
@implementation STFileLog
static dispatch_queue_t FileQueue(void)
{
static dispatch_queue_t queue;
static dispatch_once_t once;
dispatch_once(&once, ^{
queue = dispatch_queue_create("org.amnezia.split-tunnel.log", DISPATCH_QUEUE_SERIAL);
});
return queue;
}
/*! Owned by FileQueue(). */
static int g_fd = -1;
static NSString *g_path = nil;
static NSString *g_directory = nil;
static _Atomic bool g_debugEnabled = false;
static _Atomic bool g_fileOpen = false;
/*! Everything the extension logs before the host hands it a directory - the
* pid/uid/gid line and the result of joining group amnvpn among it - would
* otherwise reach os_log only, which is exactly the part of the startup that
* has to be readable in the file. Hold those lines until the file opens.
* Debug lines are not buffered: they arrive in the thousands and would push
* the interesting ones out of a bounded buffer. */
static NSMutableArray<NSString *> *g_pending = nil;
static NSUInteger g_pendingDropped = 0;
static _Atomic bool g_buffering = true;
static const NSUInteger kMaxPendingLines = 512;
+ (void)setDebugEnabled:(BOOL)enabled
{
atomic_store_explicit(&g_debugEnabled, enabled ? true : false, memory_order_relaxed);
}
+ (BOOL)isDebugEnabled
{
return atomic_load_explicit(&g_debugEnabled, memory_order_relaxed) ? YES : NO;
}
+ (BOOL)acceptsLevel:(STLogLevel)level
{
if (!atomic_load_explicit(&g_fileOpen, memory_order_relaxed)) {
// Not open yet: keep the non-debug startup lines for the flush.
return atomic_load_explicit(&g_buffering, memory_order_relaxed)
&& level != STLogLevelDebug;
}
if (level == STLogLevelDebug) {
return [self isDebugEnabled];
}
return YES;
}
+ (NSString *)currentPath
{
__block NSString *path = nil;
dispatch_sync(FileQueue(), ^{
path = g_path;
});
return path;
}
+ (void)openLocked
{
if (g_fd >= 0 || g_directory.length == 0) {
return;
}
// Matches the layout the app and the service already use: a per-process
// subfolder, with the _root suffix because the extension runs as root.
NSString *dir = [g_directory stringByAppendingPathComponent:@"AmneziaVPNSplitTunnel_root"];
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:dir
withIntermediateDirectories:YES
attributes:nil
error:&error]) {
os_log_error(STUtils.log, "file log: cannot create %{public}@: %{public}@", dir, error);
return;
}
NSString *name = [NSString stringWithFormat:@"AmneziaVPNSplitTunnel_%@.log", LaunchStamp()];
NSString *path = [dir stringByAppendingPathComponent:name];
const int fd = open(path.fileSystemRepresentation, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd < 0) {
os_log_error(STUtils.log, "file log: cannot open %{public}@: errno=%{public}d %{public}s",
path, errno, strerror(errno));
return;
}
g_fd = fd;
g_path = path;
atomic_store_explicit(&g_fileOpen, true, memory_order_relaxed);
atomic_store_explicit(&g_buffering, false, memory_order_relaxed);
os_log(STUtils.log, "file log: writing to %{public}@", path);
PruneOldLogs(dir, path);
if (g_pendingDropped > 0) {
[self writeLineLocked:[NSString stringWithFormat:@"%@ [ERROR] file log: %lu buffered "
@"line(s) dropped before the file opened\n",
FormatTimestamp([NSDate date]),
(unsigned long)g_pendingDropped]];
g_pendingDropped = 0;
}
for (NSString *line in g_pending) {
[self writeLineLocked:line];
}
[g_pending removeAllObjects];
}
+ (void)rotateIfNeededLocked
{
if (g_fd < 0) {
return;
}
struct stat st;
if (fstat(g_fd, &st) != 0 || st.st_size < kMaxLogFileSize) {
return;
}
NSString *previous = [g_path stringByAppendingPathExtension:@"1"];
[[NSFileManager defaultManager] removeItemAtPath:previous error:nil];
[[NSFileManager defaultManager] moveItemAtPath:g_path toPath:previous error:nil];
close(g_fd);
g_fd = -1;
atomic_store_explicit(&g_fileOpen, false, memory_order_relaxed);
[self openLocked];
}
+ (void)configureWithDirectory:(NSString *)directory
{
if (directory.length == 0) {
os_log_error(STUtils.log, "file log: empty directory, file logging stays off");
return;
}
dispatch_async(FileQueue(), ^{
if ([g_directory isEqualToString:directory] && g_fd >= 0) {
return;
}
if (g_fd >= 0) {
close(g_fd);
g_fd = -1;
atomic_store_explicit(&g_fileOpen, false, memory_order_relaxed);
}
g_directory = [directory copy];
[self openLocked];
});
}
+ (void)writeLineLocked:(NSString *)line
{
NSData *data = [line dataUsingEncoding:NSUTF8StringEncoding];
const char *bytes = (const char *)data.bytes;
size_t remaining = data.length;
while (remaining > 0) {
const ssize_t written = write(g_fd, bytes, remaining);
if (written <= 0) {
if (errno == EINTR) {
continue;
}
os_log_error(STUtils.log, "file log: write failed errno=%{public}d", errno);
break;
}
bytes += written;
remaining -= (size_t)written;
}
}
+ (void)appendLevel:(STLogLevel)level message:(NSString *)message
{
NSString *copy = [message copy];
NSDate *when = [NSDate date];
dispatch_async(FileQueue(), ^{
NSString *line = [NSString stringWithFormat:@"%@ [%s] %@\n",
FormatTimestamp(when), LevelName(level), copy];
if (g_fd < 0) {
if (!atomic_load_explicit(&g_buffering, memory_order_relaxed)) {
return;
}
if (g_pending == nil) {
g_pending = [NSMutableArray arrayWithCapacity:kMaxPendingLines];
}
if (g_pending.count >= kMaxPendingLines) {
[g_pending removeObjectAtIndex:0];
++g_pendingDropped;
}
[g_pending addObject:line];
return;
}
[self rotateIfNeededLocked];
if (g_fd < 0) {
return;
}
[self writeLineLocked:line];
});
}
@end
#pragma mark - STLogWrite
void STLogWrite(STLogLevel level, const char *fmt, ...)
{
const os_log_type_t type = OsLogType(level);
const BOOL toOsLog = os_log_type_enabled(STUtils.log, type);
const BOOL toFile = [STFileLog acceptsLevel:level];
if (!toOsLog && !toFile) {
return;
}
va_list args;
va_start(args, fmt);
NSString *message = [[NSString alloc] initWithFormat:StripOsLogModifiers(fmt) arguments:args];
va_end(args);
if (toOsLog) {
os_log_with_type(STUtils.log, type, "%{public}@", message);
}
if (toFile) {
[STFileLog appendLevel:level message:message];
}
}
#pragma mark - STStats
@implementation STStats
static _Atomic uint64_t g_tcpOpened = 0;
static _Atomic uint64_t g_tcpClosed = 0;
static _Atomic uint64_t g_udpOpened = 0;
static _Atomic uint64_t g_udpClosed = 0;
static _Atomic uint64_t g_bytesOut = 0;
static _Atomic uint64_t g_bytesIn = 0;
static _Atomic uint64_t g_toTunnel = 0;
+ (void)tcpOpened { atomic_fetch_add_explicit(&g_tcpOpened, 1, memory_order_relaxed); }
+ (void)udpOpened { atomic_fetch_add_explicit(&g_udpOpened, 1, memory_order_relaxed); }
+ (void)flowSentToTunnel { atomic_fetch_add_explicit(&g_toTunnel, 1, memory_order_relaxed); }
+ (void)tcpClosedWithOut:(uint64_t)out in:(uint64_t)in
{
atomic_fetch_add_explicit(&g_tcpClosed, 1, memory_order_relaxed);
atomic_fetch_add_explicit(&g_bytesOut, out, memory_order_relaxed);
atomic_fetch_add_explicit(&g_bytesIn, in, memory_order_relaxed);
}
+ (void)udpClosedWithOut:(uint64_t)out in:(uint64_t)in
{
atomic_fetch_add_explicit(&g_udpClosed, 1, memory_order_relaxed);
atomic_fetch_add_explicit(&g_bytesOut, out, memory_order_relaxed);
atomic_fetch_add_explicit(&g_bytesIn, in, memory_order_relaxed);
}
+ (NSString *)summary
{
const uint64_t tcpOpened = atomic_load_explicit(&g_tcpOpened, memory_order_relaxed);
const uint64_t tcpClosed = atomic_load_explicit(&g_tcpClosed, memory_order_relaxed);
const uint64_t udpOpened = atomic_load_explicit(&g_udpOpened, memory_order_relaxed);
const uint64_t udpClosed = atomic_load_explicit(&g_udpClosed, memory_order_relaxed);
return [NSString stringWithFormat:
@"tcp active=%llu total=%llu | udp active=%llu total=%llu | left to the tunnel=%llu | "
@"relayed out=%llu KiB in=%llu KiB",
tcpOpened - tcpClosed, tcpOpened,
udpOpened - udpClosed, udpOpened,
atomic_load_explicit(&g_toTunnel, memory_order_relaxed),
atomic_load_explicit(&g_bytesOut, memory_order_relaxed) / 1024,
atomic_load_explicit(&g_bytesIn, memory_order_relaxed) / 1024];
}
@end
#pragma mark - STUtils
@implementation STUtils
+ (os_log_t)log
{
static os_log_t logger;
static dispatch_once_t once;
dispatch_once(&once, ^{
#ifdef CLIENT_MACOS_ST_BUNDLE_ID
logger = os_log_create(CLIENT_MACOS_ST_BUNDLE_ID, "proxy");
#else
logger = os_log_create("org.amnezia.AmneziaVPN.network-extension", "proxy");
#endif
});
return logger;
}
+ (dispatch_queue_t)stateQueue
{
static dispatch_queue_t queue;
static dispatch_once_t once;
dispatch_once(&once, ^{
queue = dispatch_queue_create("org.amnezia.split-tunnel.state", DISPATCH_QUEUE_SERIAL);
});
return queue;
}
+ (uint64_t)nextFlowId
{
static _Atomic uint64_t counter = 0;
return atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed) + 1;
}
+ (NSData *)dataFromDispatchData:(dispatch_data_t)content
{
if (content == NULL) {
return nil;
}
NSMutableData *data = [NSMutableData data];
dispatch_data_apply(content, ^bool(dispatch_data_t region, size_t offset, const void *buffer, size_t size) {
(void)region;
(void)offset;
[data appendBytes:buffer length:size];
return true;
});
return data;
}
+ (NSString *)pathFromAuditTokenData:(NSData *)tokenData
{
if (tokenData.length != sizeof(audit_token_t)) {
STLogDebug("pathFromAuditToken: unexpected token length %{public}lu (want %{public}lu)",
(unsigned long)tokenData.length, (unsigned long)sizeof(audit_token_t));
return nil;
}
NSDictionary *attributes = @{ (__bridge NSString *)kSecGuestAttributeAudit : tokenData };
SecCodeRef code = NULL;
OSStatus status = SecCodeCopyGuestWithAttributes(NULL, (__bridge CFDictionaryRef)attributes, kSecCSDefaultFlags, &code);
if (status != errSecSuccess || code == NULL) {
STLogDebug("pathFromAuditToken SecCodeCopyGuest status=%{public}d", (int)status);
return nil;
}
CFURLRef url = NULL;
status = SecCodeCopyPath(code, kSecCSDefaultFlags, &url);
CFRelease(code);
if (status != errSecSuccess || url == NULL) {
STLogDebug("pathFromAuditToken SecCodeCopyPath status=%{public}d", (int)status);
return nil;
}
NSString *path = [(__bridge NSURL *)url path];
CFRelease(url);
return path;
}
+ (nw_endpoint_t)copyEndpointFromHost:(NSString *)host port:(NSString *)port
{
if (host.length == 0 || port.length == 0) {
STLogError("copyEndpointFromHost: empty host=%{public}@ port=%{public}@", host ?: @"", port ?: @"");
return NULL;
}
return nw_endpoint_create_host(host.UTF8String, port.UTF8String);
}
+ (BOOL)isIPv4Address:(NSString *)value
{
if (value.length == 0) {
return NO;
}
struct in_addr addr;
return inet_pton(AF_INET, value.UTF8String, &addr) == 1;
}
+ (BOOL)isIPv6Address:(NSString *)value
{
if (value.length == 0) {
return NO;
}
struct in6_addr addr;
return inet_pton(AF_INET6, value.UTF8String, &addr) == 1;
}
+ (NSString *)describeConnectionPath:(nw_connection_t)connection
{
if (connection == NULL) {
return @"path=(no connection)";
}
nw_path_t path = nw_connection_copy_current_path(connection);
if (path == NULL) {
return @"path=(none yet)";
}
const char *status = "?";
switch (nw_path_get_status(path)) {
case nw_path_status_invalid: status = "invalid"; break;
case nw_path_status_satisfied: status = "satisfied"; break;
case nw_path_status_unsatisfied: status = "unsatisfied"; break;
case nw_path_status_satisfiable: status = "satisfiable"; break;
}
// The reason only carries meaning for an unsatisfied path; on a satisfied
// one it still reads "not-available", which is pure noise in the log.
const char *reason = "n/a";
if (nw_path_get_status(path) == nw_path_status_unsatisfied) {
if (@available(macOS 11.0, *)) {
switch (nw_path_get_unsatisfied_reason(path)) {
case nw_path_unsatisfied_reason_not_available: reason = "not-available"; break;
case nw_path_unsatisfied_reason_cellular_denied: reason = "cellular-denied"; break;
case nw_path_unsatisfied_reason_wifi_denied: reason = "wifi-denied"; break;
case nw_path_unsatisfied_reason_local_network_denied: reason = "local-network-denied"; break;
default: reason = "none"; break;
}
} else {
reason = "?";
}
}
NSMutableArray<NSString *> *interfaces = [NSMutableArray array];
nw_path_enumerate_interfaces(path, ^bool(nw_interface_t interface) {
[interfaces addObject:[NSString stringWithFormat:@"%s(type=%d)",
nw_interface_get_name(interface) ?: "?",
(int)nw_interface_get_type(interface)]];
return true;
});
return [NSString stringWithFormat:@"path=%s reason=%s expensive=%d constrained=%d ifs=[%@]",
status, reason,
(int)nw_path_is_expensive(path),
(int)nw_path_is_constrained(path),
[interfaces componentsJoinedByString:@", "]];
}
+ (const char *)connectionStateName:(nw_connection_state_t)state
{
switch (state) {
case nw_connection_state_invalid: return "invalid";
case nw_connection_state_waiting: return "waiting";
case nw_connection_state_preparing: return "preparing";
case nw_connection_state_ready: return "ready";
case nw_connection_state_failed: return "failed";
case nw_connection_state_cancelled: return "cancelled";
default: return "unknown";
}
}
+ (NSError *)errorFromNWError:(nw_error_t)error
{
if (error == NULL) {
return nil;
}
return CFBridgingRelease(nw_error_copy_cf_error(error));
}
@end
+55
View File
@@ -0,0 +1,55 @@
#import <Foundation/Foundation.h>
#import <NetworkExtension/NetworkExtension.h>
#import "TransparentProxyProvider.h"
#import "Utils.h"
#import <errno.h>
#import <grp.h>
#import <string.h>
#import <sys/types.h>
#import <unistd.h>
/*!
* The extension runs as root. It also joins the "amnvpn" group so that the pf
* anchor amn.320.allowExcludedApps ("pass out ... group amnvpn") lets the
* bypassed traffic through while the kill switch is armed.
*/
static void JoinAmnvpnGroup(void)
{
struct group *grp = getgrnam("amnvpn");
if (grp == NULL) {
STLogError("main: group 'amnvpn' not found (errno=%{public}d %{public}s) - bypass traffic will be "
"blocked whenever the kill switch is armed",
errno, strerror(errno));
return;
}
if (setgid(grp->gr_gid) != 0) {
STLogError("main: setgid(%{public}d) failed: errno=%{public}d %{public}s",
(int)grp->gr_gid, errno, strerror(errno));
return;
}
STLogInfo("main: joined group amnvpn gid=%{public}d", (int)grp->gr_gid);
}
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
@autoreleasepool {
NSBundle *bundle = [NSBundle mainBundle];
STLogInfo("main: starting %{public}@ version=%{public}@ (%{public}@) pid=%{public}d uid=%{public}d",
bundle.bundleIdentifier ?: @"?",
bundle.infoDictionary[@"CFBundleShortVersionString"] ?: @"?",
bundle.infoDictionary[@"CFBundleVersion"] ?: @"?",
(int)getpid(), (int)getuid());
JoinAmnvpnGroup();
[TransparentProxyProvider class];
STLogInfo("main: entering system extension mode");
[NEProvider startSystemExtensionMode];
dispatch_main();
}
return 0;
}
@@ -46,7 +46,8 @@ namespace {
#include <QDir>
#include <QStandardPaths>
// Read-only rules bundled with the application.
// Read-only rules bundled with the application: Contents/MacOS/pf inside the
// bundle, the same sibling layout when started from the build tree.
#define ResourceDir (qApp->applicationDirPath() + "/pf")
// Writable location that does NOT live inside the signed bundle. Using a
@@ -92,6 +93,11 @@ void MacOSFirewall::installRootAnchors()
{
logger.info() << "Installing PF root anchors";
// When these fail the kernel silently keeps whatever anchors a previous run
// left behind: the kill switch and the split-tunnel pass rule then do
// nothing, while the log still reports every anchor as "ON".
const QString rootRules = QStringLiteral("%1/%2.conf").arg(ResourceDir, kRootAnchor);
// Append our NAT anchors by reading back and re-applying NAT rules only
auto insertNatAnchors = QStringLiteral(
"( "
@@ -101,7 +107,9 @@ void MacOSFirewall::installRootAnchors()
R"(echo 'load anchor "%4" from "%5/%6.conf"'; )" // Load the PIA anchors from file
") | pfctl -N -f -").arg(kRootAnchor, kRootAnchor, kRootAnchor, kRootAnchor, ResourceDir, kRootAnchor);
execute(insertNatAnchors);
if (execute(insertNatAnchors) != 0) {
logger.error() << "failed to load the PF translation anchors from" << rootRules;
}
// Append our filter anchor by reading back and re-applying filter rules
// only. pfctl -sr also includes scrub rules, but these will be ignored
@@ -112,7 +120,10 @@ void MacOSFirewall::installRootAnchors()
R"(echo 'anchor "%2/*"'; )" // PIA's filter anchors
R"(echo 'load anchor "%3" from "%4/%5.conf"'; )" // Load the PIA anchors from file
" ) | pfctl -R -f -").arg(kRootAnchor, kRootAnchor, kRootAnchor, ResourceDir, kRootAnchor);
execute(insertFilterAnchor);
if (execute(insertFilterAnchor) != 0) {
logger.error() << "failed to load the PF filter anchors from" << rootRules
<< "- sub-anchors listed there will not be evaluated";
}
}
void MacOSFirewall::install()
@@ -171,7 +182,11 @@ bool MacOSFirewall::isRootAnchorLoaded()
void MacOSFirewall::enableAnchor(const QString& anchor)
{
execute(QStringLiteral("if pfctl -q -a '%1/%2' -s rules 2> /dev/null | grep -q . ; then echo '%2: ON' ; else echo '%2: OFF -> ON' ; pfctl -q -a '%1/%2' -F all -f '%3/%1.%2.conf' ; fi").arg(kRootAnchor, anchor, ResourceDir));
// The file is only read when the anchor is empty, so rules left in the
// kernel by an earlier run survive a change to the .conf. Print what is
// actually resident in that case - otherwise "ON" says nothing about which
// rules are in force.
execute(QStringLiteral("if pfctl -q -a '%1/%2' -s rules 2> /dev/null | grep -q . ; then echo '%2: ON (kept, rules already in the kernel):' ; pfctl -q -a '%1/%2' -s rules ; else echo '%2: OFF -> ON' ; pfctl -q -a '%1/%2' -F all -f '%3/%1.%2.conf' ; fi").arg(kRootAnchor, anchor, ResourceDir));
}
void MacOSFirewall::disableAnchor(const QString& anchor)
@@ -47,11 +47,14 @@ MacosRouteMonitor::MacosRouteMonitor(const QString& ifname, QObject* parent)
// Grab the default routes at startup.
rtmFetchRoutes(AF_INET);
rtmFetchRoutes(AF_INET6);
syncPhysicalScopedDefaults();
}
MacosRouteMonitor::~MacosRouteMonitor() {
MZ_COUNT_DTOR(MacosRouteMonitor);
flushExclusionRoutes();
flushPhysicalScopedDefaults();
if (m_rtsock >= 0) {
close(m_rtsock);
}
@@ -256,6 +259,7 @@ void MacosRouteMonitor::handleRtmUpdate(const struct rt_msghdr* rtm,
// Update the exclusion routes with the new default route.
logger.debug() << "Updating default route via" << ifname
<< addrToString(addrlist[1]);
syncPhysicalScopedDefaults();
for (const IPAddress& prefix : m_exclusionRoutes) {
if (prefix.address().protocol() == protocol) {
logger.debug() << "Updating exclusion route to"
@@ -265,6 +269,65 @@ void MacosRouteMonitor::handleRtmUpdate(const struct rt_msghdr* rtm,
}
}
bool MacosRouteMonitor::syncPhysicalScopedDefault(int family,
const QByteArray& gateway,
unsigned int ifindex) {
unsigned int& scoped =
(family == AF_INET) ? m_scopedIfindexIpv4 : m_scopedIfindexIpv6;
// No physical default to mirror, or it points at the tunnel itself.
if (ifindex == 0 || ifindex == m_ifindex || gateway.isEmpty()) {
return false;
}
if (scoped == ifindex) {
return true; // already in place and pointing at the right interface
}
const IPAddress anywhere =
(family == AF_INET) ? IPAddress(QHostAddress(QHostAddress::AnyIPv4), 0)
: IPAddress(QHostAddress(QHostAddress::AnyIPv6), 0);
// A scope change means the old route is stale; drop it before adding.
if (scoped != 0) {
rtmSendRoute(RTM_DELETE, anywhere, scoped, nullptr, RTF_IFSCOPE);
scoped = 0;
}
if (!rtmSendRoute(RTM_ADD, anywhere, ifindex, gateway.constData(),
RTF_IFSCOPE)) {
logger.error() << "Failed to add the interface-scoped default route via"
<< ifindex
<< "- traffic bound to the physical interface will have no "
"route while the tunnel is up";
return false;
}
scoped = ifindex;
logger.debug() << "Added interface-scoped default route via index" << ifindex
<< addrToString(gateway);
return true;
}
void MacosRouteMonitor::syncPhysicalScopedDefaults() {
syncPhysicalScopedDefault(AF_INET, m_defaultGatewayIpv4,
m_defaultIfindexIpv4);
syncPhysicalScopedDefault(AF_INET6, m_defaultGatewayIpv6,
m_defaultIfindexIpv6);
}
void MacosRouteMonitor::flushPhysicalScopedDefaults() {
if (m_scopedIfindexIpv4 != 0) {
rtmSendRoute(RTM_DELETE, IPAddress(QHostAddress(QHostAddress::AnyIPv4), 0),
m_scopedIfindexIpv4, nullptr, RTF_IFSCOPE);
m_scopedIfindexIpv4 = 0;
}
if (m_scopedIfindexIpv6 != 0) {
rtmSendRoute(RTM_DELETE, IPAddress(QHostAddress(QHostAddress::AnyIPv6), 0),
m_scopedIfindexIpv6, nullptr, RTF_IFSCOPE);
m_scopedIfindexIpv6 = 0;
}
}
void MacosRouteMonitor::handleIfaceInfo(const struct if_msghdr* ifm,
const QByteArray& payload) {
QStringList list;
@@ -32,6 +32,20 @@ class MacosRouteMonitor final : public QObject {
bool deleteExclusionRoute(const IPAddress& prefix);
void flushExclusionRoutes();
/*! Keeps an interface-scoped default route pointing at the physical
* interface while the tunnel owns the routing table.
*
* The tunnel claims traffic with the 0.0.0.0/1 + 128.0.0.0/1 pair, which
* beats the physical default on prefix length. The physical default stays
* in the table but is not scoped, so "route -n get -ifscope en0" answers
* "not in table" and anything bound to the physical interface - curl
* --interface, and every flow the split-tunnel extension pushes back out -
* gets "No network route". macOS builds this scoped route itself for VPNs
* that go through NEVPNManager; a tunnel that routes on its own has to do
* it. */
void syncPhysicalScopedDefaults();
void flushPhysicalScopedDefaults();
private:
void handleRtmDelete(const struct rt_msghdr* msg, const QByteArray& payload);
void handleRtmUpdate(const struct rt_msghdr* msg, const QByteArray& payload);
@@ -50,11 +64,17 @@ class MacosRouteMonitor final : public QObject {
static QString addrToString(const struct sockaddr* sa);
static QString addrToString(const QByteArray& data);
bool syncPhysicalScopedDefault(int family, const QByteArray& gateway,
unsigned int ifindex);
QList<IPAddress> m_exclusionRoutes;
QByteArray m_defaultGatewayIpv4;
QByteArray m_defaultGatewayIpv6;
unsigned int m_defaultIfindexIpv4 = 0;
unsigned int m_defaultIfindexIpv6 = 0;
/*! Interface the scoped default currently points at, 0 when there is none. */
unsigned int m_scopedIfindexIpv4 = 0;
unsigned int m_scopedIfindexIpv6 = 0;
QString m_ifname;
unsigned int m_ifindex = 0;
@@ -519,4 +519,5 @@ void WireguardUtilsMacos::applyFirewallRules(FirewallParams& params)
MacOSFirewall::setAnchorEnabled(QStringLiteral("300.allowLAN"), true);
MacOSFirewall::setAnchorEnabled(QStringLiteral("310.blockDNS"), true);
MacOSFirewall::setAnchorTable(QStringLiteral("310.blockDNS"), true, QStringLiteral("dnsaddr"), params.dnsServers);
MacOSFirewall::setAnchorEnabled(QStringLiteral("320.allowExcludedApps"), true);
}
@@ -0,0 +1,15 @@
#ifndef MACOSAPPINFO_H
#define MACOSAPPINFO_H
#include <QString>
#include "core/utils/commonStructs.h"
class MacOSAppInfo
{
public:
static bool fillFromPath(const QString &appPath, amnezia::InstalledAppInfo &info);
static QString pickApplication();
};
#endif
@@ -0,0 +1,132 @@
#include "macosAppInfo.h"
#import <AppKit/AppKit.h>
#import <Foundation/Foundation.h>
#import <Security/Security.h>
#include <QFileInfo>
#include <QString>
#include "logger.h"
namespace {
Logger logger("MacOSAppInfo");
QString QStr(NSString *value)
{
return value != nil ? QString::fromNSString(value) : QStringLiteral("(nil)");
}
/*! Designated requirement of the bundle, logged so a mismatch between the
* picked app and the flows we later see can be diagnosed. */
QString DesignatedRequirement(NSString *path)
{
NSURL *url = [NSURL fileURLWithPath:path];
SecStaticCodeRef code = NULL;
OSStatus status = SecStaticCodeCreateWithPath((__bridge CFURLRef)url, kSecCSDefaultFlags, &code);
if (status != errSecSuccess || code == NULL) {
return QStringLiteral("<SecStaticCodeCreateWithPath failed: %1>").arg(status);
}
SecRequirementRef requirement = NULL;
status = SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, &requirement);
CFRelease(code);
if (status != errSecSuccess || requirement == NULL) {
return QStringLiteral("<SecCodeCopyDesignatedRequirement failed: %1>").arg(status);
}
CFStringRef text = NULL;
status = SecRequirementCopyString(requirement, kSecCSDefaultFlags, &text);
CFRelease(requirement);
if (status != errSecSuccess || text == NULL) {
return QStringLiteral("<SecRequirementCopyString failed: %1>").arg(status);
}
const QString result = QString::fromCFString(text);
CFRelease(text);
return result;
}
} // namespace
bool MacOSAppInfo::fillFromPath(const QString &appPath, amnezia::InstalledAppInfo &info)
{
logger.debug() << "fillFromPath:" << appPath;
if (appPath.isEmpty()) {
logger.error() << "fillFromPath: empty path";
return false;
}
NSString *path = appPath.toNSString();
NSBundle *bundle = [NSBundle bundleWithPath:path];
if (bundle == nil) {
logger.error() << "fillFromPath: no NSBundle at" << appPath
<< "- only .app bundles can be excluded";
return false;
}
info.appPath = appPath;
info.packageName = QStr(bundle.bundleIdentifier);
if (bundle.bundleIdentifier == nil) {
info.packageName.clear();
logger.error() << "fillFromPath:" << appPath
<< "has no CFBundleIdentifier - matching will fall back to the executable path";
}
NSString *displayName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (displayName.length == 0) {
displayName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
}
if (displayName.length > 0) {
info.appName = QString::fromNSString(displayName);
} else {
info.appName = QFileInfo(appPath).completeBaseName();
logger.debug() << "fillFromPath: no CFBundleDisplayName/CFBundleName, using file name"
<< info.appName;
}
logger.info() << "picked app name=" << info.appName
<< "bundleId=" << info.packageName
<< "path=" << info.appPath
<< "executable=" << QStr(bundle.executablePath)
<< "version=" << QStr([bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]);
logger.debug() << "designated requirement:" << DesignatedRequirement(path);
const bool ok = !info.packageName.isEmpty() || !info.appPath.isEmpty();
if (!ok) {
logger.error() << "fillFromPath: neither bundle id nor path could be determined for" << appPath;
}
return ok;
}
QString MacOSAppInfo::pickApplication()
{
logger.debug() << "pickApplication: opening panel";
NSOpenPanel *panel = [NSOpenPanel openPanel];
panel.canChooseFiles = YES;
panel.canChooseDirectories = NO;
panel.allowsMultipleSelection = NO;
panel.treatsFilePackagesAsDirectories = NO;
panel.directoryURL = [NSURL fileURLWithPath:@"/Applications"];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
panel.allowedFileTypes = @[ @"app" ];
#pragma clang diagnostic pop
panel.title = @"Select Application";
const NSModalResponse response = [panel runModal];
if (response != NSModalResponseOK) {
logger.debug() << "pickApplication: cancelled (response=" << (long)response << ")";
return {};
}
NSURL *url = panel.URL;
if (url == nil) {
logger.error() << "pickApplication: panel returned OK but no URL";
return {};
}
const QString path = QString::fromNSString(url.path);
logger.info() << "pickApplication: selected" << path;
return path;
}
@@ -0,0 +1,138 @@
#ifndef MACOSSPLITTUNNELMANAGER_H
#define MACOSSPLITTUNNELMANAGER_H
#include <QByteArray>
#include <QObject>
#include <QString>
#include <QVector>
#include "core/utils/commonStructs.h"
#include "core/utils/routeModes.h"
/*!
* Drives the macOS split-tunnel system extension:
* - registers/unregisters the extension,
* - owns the NETransparentProxyManager configuration,
* - starts/stops the transparent proxy and pushes the app list into it.
*
* Only used by the Developer ID (.pkg) build; the App Store build (MACOS_NE)
* never compiles this file.
*
* Threading: the public methods must be called from the Qt main thread.
* NetworkExtension completion handlers can run on arbitrary queues, so every
* signal is re-posted to this object's thread before being emitted.
*
* State machine. reconcile() is the only entry point that decides anything; it
* is idempotent, so callers may fire it on every connection state change:
*
* desired (shouldRun) x actual (m_proxyStatus) -> action
* true, not running -> activate extension (once), then startProxy
* true, running, same opts -> nothing
* true, running, new opts -> sendProviderMessage
* false, running -> stopProxy
* false, not running -> nothing
*/
class MacOSSplitTunnelManager : public QObject
{
Q_OBJECT
public:
static MacOSSplitTunnelManager *instance();
/*! Submits an activation request. Pass userInitiated when the user just
* switched the feature on: a pending approval that the user never answered
* is then cleared first, so macOS offers the install prompt again instead
* of silently sitting on the old request. */
void activateExtension(bool userInitiated = false);
/*! Brings the proxy in line with the desired state. Cheap and idempotent. */
void reconcile(bool vpnConnected, bool splitTunnelEnabled, amnezia::AppsRouteMode mode,
const QVector<amnezia::InstalledAppInfo> &apps, const QString &vpnServer);
/*! Switches the feature off without uninstalling anything: the proxy is
* stopped and the NE configuration is disabled, so the extension keeps its
* row in System Settings -> Network Extensions with the toggle off and the
* user is never asked to approve it again. Call when the user switches app
* split tunneling off. */
void disableFeature();
/*! Removes every trace: stops the proxy, deletes the saved NE configuration
* and unregisters the system extension. Only for an actual uninstall - a
* plain off/on cycle must use disableFeature(). */
void uninstallFeature();
/*! Asks the system for the extension's real state and emits
* extensionStateChanged. Cheap; safe to call on startup and whenever the
* UI needs to show what System Settings shows. */
void refreshExtensionState();
signals:
/*! macOS is waiting for the user to approve the extension in
* System Settings -> General -> Login Items & Extensions. */
void needsUserApproval();
/*! The extension was approved and registered. */
void extensionActivated();
/*! The transparent proxy actually reached the running state. */
void proxyStarted();
void proxyStopped();
void errorOccurred(const QString &message);
/*! What the system reports about the extension. "installed" means macOS has
* it registered, "enabled" is the toggle the user sees in System Settings
* -> General -> Login Items & Extensions -> Network Extensions. */
void extensionStateChanged(bool installed, bool enabled, bool awaitingApproval);
private:
explicit MacOSSplitTunnelManager(QObject *parent = nullptr);
struct DesiredState
{
bool valid = false;
bool shouldRun = false;
amnezia::AppsRouteMode mode = amnezia::AppsRouteMode::VpnAllExceptApps;
QVector<amnezia::InstalledAppInfo> apps;
QString vpnServer;
};
void startProxy();
void stopProxy();
/*! Disables the saved NE configuration, keeping it in System Settings. */
void setConfigurationEnabled(bool enabled, void (^completion)(void));
void removeConfiguration(void (^completion)(void));
/*! Unregisters the extension - the API equivalent of
* "systemextensionsctl uninstall <team> <bundle id>". With
* reactivateAfterwards the activation request is submitted again once the
* removal completes, which is what clears a stuck approval. */
void deactivateExtension(bool reactivateAfterwards = false);
void onExtensionStateKnown(bool installed, bool enabled, bool awaitingApproval);
QByteArray optionsJson(const QVector<amnezia::InstalledAppInfo> &apps, const QString &vpnServer,
amnezia::AppsRouteMode mode) const;
/*! Emits a signal on this object's thread, whatever queue we are on. */
void postError(const QString &message);
void postNeedsApproval();
void postActivated();
void onExtensionActivated();
/*! Called from the NEVPNStatusDidChangeNotification observer. */
void onProxyStatusChanged(int status);
/*! True only while an activation request is in flight, so a second one is
* not submitted on top of it. Cleared when the request finishes either way
* - the lasting state lives in m_extensionInstalled/m_extensionEnabled. */
bool m_activationRequested = false;
bool m_extensionActivated = false;
/*! Last state reported by the system extension properties request. */
bool m_extensionInstalled = false;
bool m_extensionEnabled = false;
bool m_extensionAwaitingApproval = false;
/*! Mirrors NEVPNStatus; -1 until the configuration has been loaded once. */
int m_proxyStatus = -1;
bool m_tearingDown = false;
/*! Logged once per session instead of on every reconcile. */
bool m_warnedAboutEmptyServer = false;
DesiredState m_desired;
QByteArray m_appliedOptions;
};
#endif
@@ -0,0 +1,910 @@
#include "macosSplitTunnelManager.h"
#import <Foundation/Foundation.h>
#import <NetworkExtension/NetworkExtension.h>
#import <SystemExtensions/SystemExtensions.h>
#include <QDir>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMetaObject>
#include <QStandardPaths>
#include "logger.h"
namespace {
Logger logger("MacOSSplitTunnelManager");
NSString *ProviderBundleId()
{
#ifdef CLIENT_MACOS_ST_BUNDLE_ID
return @CLIENT_MACOS_ST_BUNDLE_ID;
#else
return @"org.amnezia.AmneziaVPN.network-extension";
#endif
}
QString QStr(NSString *value)
{
return value != nil ? QString::fromNSString(value) : QStringLiteral("(nil)");
}
QString ErrorDump(NSError *error)
{
if (error == nil) {
return QStringLiteral("nil");
}
return QStringLiteral("%1 code=%2 desc=%3")
.arg(QStr(error.domain))
.arg(error.code)
.arg(QStr(error.localizedDescription));
}
const char *VpnStatusName(NEVPNStatus status)
{
switch (status) {
case NEVPNStatusInvalid: return "Invalid";
case NEVPNStatusDisconnected: return "Disconnected";
case NEVPNStatusConnecting: return "Connecting";
case NEVPNStatusConnected: return "Connected";
case NEVPNStatusReasserting: return "Reasserting";
case NEVPNStatusDisconnecting: return "Disconnecting";
default: return "Unknown";
}
}
const char *RequestResultName(OSSystemExtensionRequestResult result)
{
switch (result) {
case OSSystemExtensionRequestCompleted: return "completed";
case OSSystemExtensionRequestWillCompleteAfterReboot: return "willCompleteAfterReboot";
default: return "unknown";
}
}
void LogApps(const char *where, const QVector<amnezia::InstalledAppInfo> &apps)
{
logger.debug() << where << "apps count=" << apps.size();
for (int i = 0; i < apps.size(); ++i) {
const auto &app = apps.at(i);
logger.debug() << where << " [" << i << "]"
<< "name=" << app.appName
<< "bundleId=" << app.packageName
<< "path=" << app.appPath;
}
}
void LogHostBundle()
{
NSBundle *bundle = [NSBundle mainBundle];
logger.debug() << "host bundle path=" << QStr(bundle.bundlePath) << "id=" << QStr(bundle.bundleIdentifier);
NSString *sysexDir = [bundle.bundlePath stringByAppendingPathComponent:@"Contents/Library/SystemExtensions"];
NSArray<NSString *> *entries = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sysexDir error:nil];
if (entries == nil) {
logger.error() << "host has no Contents/Library/SystemExtensions directory at" << QStr(sysexDir)
<< "- activation will fail with 'extension not found'";
return;
}
if (entries.count != 1) {
logger.error() << "expected exactly one system extension bundle, found" << entries.count
<< "- a stale bundle claiming the same identifier makes sysextd fail";
}
for (NSString *entry in entries) {
NSBundle *sysex = [NSBundle bundleWithPath:[sysexDir stringByAppendingPathComponent:entry]];
logger.debug() << " sysex" << QStr(entry)
<< "id=" << QStr(sysex.bundleIdentifier)
<< "version=" << QStr(sysex.infoDictionary[@"CFBundleVersion"]);
}
}
/*! Where the extension writes its own log file.
*
* The extension runs as root, so NSHomeDirectory() there is /var/root and it
* cannot find the user's folder on its own - the path has to travel in the
* start options. We create the directory here, from the user's process, so it
* ends up owned by the user rather than by root. */
QString SplitTunnelLogDirectory()
{
const QString base = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
if (base.isEmpty()) {
logger.error() << "cannot resolve the Documents directory, the extension will not write a log file";
return {};
}
const QString dir = base + QStringLiteral("/AmneziaVPN");
if (!QDir().mkpath(dir)) {
logger.error() << "cannot create the log directory" << dir;
return {};
}
return dir;
}
NSDictionary *OptionsDictionary(const QByteArray &json)
{
if (json.isEmpty()) {
logger.error() << "OptionsDictionary: empty json";
return @{};
}
NSData *data = [NSData dataWithBytes:json.constData() length:static_cast<NSUInteger>(json.size())];
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error != nil || ![object isKindOfClass:[NSDictionary class]]) {
logger.error() << "OptionsDictionary: bad json:" << ErrorDump(error);
return @{};
}
return object;
}
} // namespace
#pragma mark - OSSystemExtensionRequest delegate
@interface AmneziaSTExtensionDelegate : NSObject <OSSystemExtensionRequestDelegate>
@property (nonatomic, copy) void (^onNeedsApproval)(void);
@property (nonatomic, copy) void (^onFinished)(BOOL ok, NSString *message);
@property (nonatomic, copy) void (^onProperties)(BOOL found, BOOL enabled, BOOL awaitingApproval);
@end
@implementation AmneziaSTExtensionDelegate
- (OSSystemExtensionReplacementAction)request:(OSSystemExtensionRequest *)request
actionForReplacingExtension:(OSSystemExtensionProperties *)existing
withExtension:(OSSystemExtensionProperties *)ext
{
(void)request;
logger.info() << "sysex: replacing" << QStr(existing.bundleIdentifier) << "v" << QStr(existing.bundleVersion)
<< "with" << QStr(ext.bundleIdentifier) << "v" << QStr(ext.bundleVersion);
return OSSystemExtensionReplacementActionReplace;
}
- (void)requestNeedsUserApproval:(OSSystemExtensionRequest *)request
{
(void)request;
logger.info() << "sysex: waiting for user approval in System Settings";
if (self.onNeedsApproval) {
self.onNeedsApproval();
}
}
- (void)request:(OSSystemExtensionRequest *)request didFailWithError:(NSError *)error
{
(void)request;
logger.error() << "sysex: request failed:" << ErrorDump(error);
// A properties request for an extension macOS does not know about fails
// instead of returning an empty list; that is the "not installed" answer.
if (self.onProperties) {
self.onProperties(NO, NO, NO);
return;
}
if (self.onFinished) {
self.onFinished(NO, error.localizedDescription);
}
}
- (void)request:(OSSystemExtensionRequest *)request
foundProperties:(NSArray<OSSystemExtensionProperties *> *)properties API_AVAILABLE(macos(12.0))
{
(void)request;
BOOL found = NO;
BOOL enabled = NO;
BOOL awaiting = NO;
int uninstalling = 0;
for (OSSystemExtensionProperties *item in properties) {
if (item.isUninstalling) {
// Records left by previous deactivations. macOS only drops them on
// reboot, and they pile up one per off/on cycle.
++uninstalling;
continue;
}
found = YES;
enabled = enabled || item.isEnabled;
awaiting = awaiting || item.isAwaitingUserApproval;
logger.info() << "sysex properties: v" << QStr(item.bundleVersion) << "enabled=" << (item.isEnabled ? 1 : 0)
<< "awaitingApproval=" << (item.isAwaitingUserApproval ? 1 : 0);
}
if (uninstalling > 0) {
logger.warning() << "sysex properties:" << uninstalling
<< "copies are waiting to uninstall on reboot; macOS may refuse to show the "
"approval row until the machine is restarted";
}
if (!found) {
logger.info() << "sysex properties: the extension is not installed";
}
if (self.onProperties) {
self.onProperties(found, enabled, awaiting);
}
}
- (void)request:(OSSystemExtensionRequest *)request didFinishWithResult:(OSSystemExtensionRequestResult)result
{
(void)request;
logger.info() << "sysex: request finished result=" << RequestResultName(result);
if (result == OSSystemExtensionRequestWillCompleteAfterReboot) {
logger.info() << "sysex: the extension will only become active after a reboot";
}
if (self.onFinished) {
self.onFinished(YES, nil);
}
}
@end
static AmneziaSTExtensionDelegate *g_activationDelegate = nil;
static AmneziaSTExtensionDelegate *g_deactivationDelegate = nil;
static AmneziaSTExtensionDelegate *g_propertiesDelegate = nil;
/*! The NE configuration is loaded once and cached, so reconcile() does not pay
* for an async loadAllFromPreferences round trip on every connection state
* change, and so we can keep a status observer attached to its connection. */
static NETransparentProxyManager *g_proxyManager = nil;
static id g_statusObserver = nil;
#pragma mark - MacOSSplitTunnelManager
MacOSSplitTunnelManager *MacOSSplitTunnelManager::instance()
{
static MacOSSplitTunnelManager *s_instance = new MacOSSplitTunnelManager(nullptr);
return s_instance;
}
MacOSSplitTunnelManager::MacOSSplitTunnelManager(QObject *parent) : QObject(parent)
{
logger.info() << "created, provider bundle id =" << QStr(ProviderBundleId());
// Ask the system what it already has before anything decides to install.
refreshExtensionState();
}
void MacOSSplitTunnelManager::postError(const QString &message)
{
logger.error() << "reporting error to UI:" << message;
QMetaObject::invokeMethod(this, [this, message]() { emit errorOccurred(message); }, Qt::QueuedConnection);
}
void MacOSSplitTunnelManager::postNeedsApproval()
{
QMetaObject::invokeMethod(this, [this]() { emit needsUserApproval(); }, Qt::QueuedConnection);
}
void MacOSSplitTunnelManager::postActivated()
{
QMetaObject::invokeMethod(this, [this]() { emit extensionActivated(); }, Qt::QueuedConnection);
}
QByteArray MacOSSplitTunnelManager::optionsJson(const QVector<amnezia::InstalledAppInfo> &apps,
const QString &vpnServer,
amnezia::AppsRouteMode mode) const
{
QJsonArray appsJson;
for (const auto &app : apps) {
QJsonObject entry;
entry.insert(QStringLiteral("bundleId"), app.packageName);
entry.insert(QStringLiteral("path"), app.appPath);
appsJson.append(entry);
}
QJsonObject root;
root.insert(QStringLiteral("mode"),
mode == amnezia::AppsRouteMode::VpnOnlyForwardApps ? QStringLiteral("only")
: QStringLiteral("except"));
root.insert(QStringLiteral("apps"), appsJson);
root.insert(QStringLiteral("vpnServer"), vpnServer);
// Self-exclusion. In "only" mode the extension claims every flow that is not
// listed, so it must be able to recognise our own processes - the app, this
// extension, and the helpers shipped inside the bundle (AmneziaVPN-service,
// tun2socks, amneziawg-go, openvpn) - or it would relay its own sockets.
NSBundle *bundle = [NSBundle mainBundle];
root.insert(QStringLiteral("selfBundleId"), QStr(bundle.bundleIdentifier));
root.insert(QStringLiteral("selfAppPath"), QStr(bundle.bundlePath));
// File logging for the extension. It writes into
// <logDir>/AmneziaVPNSplitTunnel_root/AmneziaVPNSplitTunnel.log, next to the app
// and service logs.
const QString logDir = SplitTunnelLogDirectory();
root.insert(QStringLiteral("logDir"), logDir);
#ifdef QT_NO_DEBUG
// Release: lifecycle only. Flip to true to get the per-read chatter.
root.insert(QStringLiteral("logDebug"), false);
#else
root.insert(QStringLiteral("logDebug"), true);
#endif
return QJsonDocument(root).toJson(QJsonDocument::Compact);
}
#pragma mark - System extension registration
void MacOSSplitTunnelManager::refreshExtensionState()
{
if (@available(macOS 12.0, *)) {
g_propertiesDelegate = [[AmneziaSTExtensionDelegate alloc] init];
g_propertiesDelegate.onProperties = ^(BOOL found, BOOL enabled, BOOL awaiting) {
const bool installedCopy = found ? true : false;
const bool enabledCopy = enabled ? true : false;
const bool awaitingCopy = awaiting ? true : false;
QMetaObject::invokeMethod(
this,
[this, installedCopy, enabledCopy, awaitingCopy]() {
onExtensionStateKnown(installedCopy, enabledCopy, awaitingCopy);
},
Qt::QueuedConnection);
};
OSSystemExtensionRequest *request =
[OSSystemExtensionRequest propertiesRequestForExtension:ProviderBundleId()
queue:dispatch_get_main_queue()];
request.delegate = g_propertiesDelegate;
[[OSSystemExtensionManager sharedManager] submitRequest:request];
} else {
// Before macOS 12 there is no way to ask; assume whatever this process
// did itself is the truth.
onExtensionStateKnown(m_extensionActivated, m_extensionActivated, false);
}
}
void MacOSSplitTunnelManager::onExtensionStateKnown(bool installed, bool enabled, bool awaitingApproval)
{
const bool changed = installed != m_extensionInstalled || enabled != m_extensionEnabled
|| awaitingApproval != m_extensionAwaitingApproval;
m_extensionInstalled = installed;
m_extensionEnabled = enabled;
m_extensionAwaitingApproval = awaitingApproval;
// The system is the authority: an extension macOS still has registered does
// not need another activation request, and one it dropped does.
m_extensionActivated = installed && enabled;
if (!installed) {
m_activationRequested = false;
}
logger.info() << "extension state: installed=" << installed << "enabled=" << enabled
<< "awaitingApproval=" << awaitingApproval;
if (changed) {
emit extensionStateChanged(installed, enabled, awaitingApproval);
}
}
void MacOSSplitTunnelManager::activateExtension(bool userInitiated)
{
if (@available(macOS 11.0, *)) {
if (m_extensionInstalled && m_extensionEnabled) {
logger.info() << "activateExtension: already installed and enabled, nothing to do";
m_extensionActivated = true;
return;
}
if (m_activationRequested) {
logger.debug() << "activateExtension: a request is already in flight";
return;
}
if (userInitiated && m_extensionAwaitingApproval) {
// An approval the user never answered keeps the record in
// "activated waiting for user" forever, and a fresh activation
// request on top of it produces no prompt at all. Removing the
// record first is what "systemextensionsctl uninstall" does by
// hand, and it makes macOS offer the install again.
logger.info() << "activateExtension: an unanswered approval is pending; removing it first so "
"macOS offers the install again";
deactivateExtension(/*reactivateAfterwards=*/true);
return;
}
if (m_extensionInstalled && !m_extensionEnabled) {
logger.info() << "activateExtension: installed but switched off in System Settings; "
"re-activating so macOS re-enables it";
}
logger.info() << "activateExtension: submitting request for" << QStr(ProviderBundleId());
LogHostBundle();
m_activationRequested = true;
g_activationDelegate = [[AmneziaSTExtensionDelegate alloc] init];
g_activationDelegate.onNeedsApproval = ^{
this->postNeedsApproval();
};
g_activationDelegate.onFinished = ^(BOOL ok, NSString *message) {
this->m_activationRequested = false;
if (ok) {
QMetaObject::invokeMethod(this, [this]() { onExtensionActivated(); }, Qt::QueuedConnection);
} else {
this->postError(QStr(message));
}
};
OSSystemExtensionRequest *request =
[OSSystemExtensionRequest activationRequestForExtension:ProviderBundleId()
queue:dispatch_get_main_queue()];
request.delegate = g_activationDelegate;
[[OSSystemExtensionManager sharedManager] submitRequest:request];
} else {
logger.error() << "activateExtension: macOS 11.0 or newer is required";
postError(tr("Split tunneling requires macOS 11 or newer"));
}
}
void MacOSSplitTunnelManager::onExtensionActivated()
{
m_extensionActivated = true;
logger.info() << "extension is registered; desired.shouldRun=" << m_desired.shouldRun;
postActivated();
// The request only says macOS accepted it; the toggle state comes from the
// properties request.
refreshExtensionState();
// A first-run activation completes long after reconcile() asked for the
// proxy, so start it now instead of waiting for the next state change.
if (m_desired.valid && m_desired.shouldRun) {
logger.info() << "starting the proxy that was pending on approval";
startProxy();
}
}
void MacOSSplitTunnelManager::deactivateExtension(bool reactivateAfterwards)
{
if (@available(macOS 11.0, *)) {
// macOS knows about the extension even when this process never
// registered it - a record left pending by an earlier run is exactly
// the case we have to clear - so go by what the properties request
// reported, not by what this process did.
if (!m_activationRequested && !m_extensionActivated && !m_extensionInstalled) {
logger.info() << "deactivateExtension: nothing registered, skipping";
if (reactivateAfterwards) {
activateExtension();
}
return;
}
logger.info() << "deactivateExtension: submitting request for" << QStr(ProviderBundleId())
<< "reactivateAfterwards=" << reactivateAfterwards;
g_deactivationDelegate = [[AmneziaSTExtensionDelegate alloc] init];
g_deactivationDelegate.onNeedsApproval = ^{
logger.info() << "deactivateExtension: waiting for user approval";
};
g_deactivationDelegate.onFinished = ^(BOOL ok, NSString *message) {
if (ok) {
logger.info() << "deactivateExtension: done";
} else {
// Not surfaced to the UI: the user asked to turn the feature
// off, and a failure to unregister does not affect them.
logger.error() << "deactivateExtension failed:" << QStr(message);
}
if (!reactivateAfterwards) {
return;
}
// The record is gone, so the next activation request produces a
// fresh install prompt. Back on the Qt thread: the state this
// touches belongs to it.
QMetaObject::invokeMethod(
this,
[this]() {
m_extensionInstalled = false;
m_extensionEnabled = false;
m_extensionAwaitingApproval = false;
logger.info() << "deactivateExtension: re-submitting the activation request";
activateExtension();
},
Qt::QueuedConnection);
};
OSSystemExtensionRequest *request =
[OSSystemExtensionRequest deactivationRequestForExtension:ProviderBundleId()
queue:dispatch_get_main_queue()];
request.delegate = g_deactivationDelegate;
[[OSSystemExtensionManager sharedManager] submitRequest:request];
m_activationRequested = false;
m_extensionActivated = false;
}
}
#pragma mark - NE configuration cache
namespace {
/*! Loads (or creates) the NETransparentProxyManager for our provider exactly
* once, caches it in g_proxyManager and calls back on the main queue. */
void WithProxyManager(void (^completion)(NETransparentProxyManager *manager, NSError *error))
{
if (g_proxyManager != nil) {
completion(g_proxyManager, nil);
return;
}
NSString *bundleId = ProviderBundleId();
[NETransparentProxyManager loadAllFromPreferencesWithCompletionHandler:^(NSArray<NETransparentProxyManager *> *managers,
NSError *loadError) {
if (loadError != nil) {
logger.error() << "loadAllFromPreferences failed:" << ErrorDump(loadError);
completion(nil, loadError);
return;
}
logger.debug() << "loadAllFromPreferences:" << (managers != nil ? (int)managers.count : 0) << "configuration(s)";
for (NETransparentProxyManager *item in managers) {
NETunnelProviderProtocol *proto = (NETunnelProviderProtocol *)item.protocolConfiguration;
if ([proto isKindOfClass:[NETunnelProviderProtocol class]]
&& [proto.providerBundleIdentifier isEqualToString:bundleId]) {
logger.debug() << "reusing the existing configuration, status="
<< VpnStatusName(item.connection.status);
g_proxyManager = item;
break;
}
}
if (g_proxyManager == nil) {
logger.info() << "creating a new NETransparentProxyManager";
g_proxyManager = [[NETransparentProxyManager alloc] init];
}
completion(g_proxyManager, nil);
}];
}
} // namespace
void MacOSSplitTunnelManager::onProxyStatusChanged(int status)
{
const NEVPNStatus previous = static_cast<NEVPNStatus>(m_proxyStatus);
const NEVPNStatus current = static_cast<NEVPNStatus>(status);
if (m_proxyStatus == status) {
return;
}
m_proxyStatus = status;
logger.info() << "proxy status" << (m_proxyStatus < 0 ? "(unknown)" : VpnStatusName(previous))
<< "->" << VpnStatusName(current);
if (current == NEVPNStatusConnected) {
QMetaObject::invokeMethod(this, [this]() { emit proxyStarted(); }, Qt::QueuedConnection);
return;
}
if (current == NEVPNStatusDisconnected) {
QMetaObject::invokeMethod(this, [this]() { emit proxyStopped(); }, Qt::QueuedConnection);
if (m_desired.valid && m_desired.shouldRun && !m_tearingDown) {
// We asked for it to run and it went down on its own.
logger.error() << "the proxy stopped while it was supposed to be running";
postError(tr("The split tunneling extension stopped unexpectedly"));
}
}
}
#pragma mark - Reconcile
void MacOSSplitTunnelManager::reconcile(bool vpnConnected, bool splitTunnelEnabled, amnezia::AppsRouteMode mode,
const QVector<amnezia::InstalledAppInfo> &apps, const QString &vpnServer)
{
const bool modeSupported = mode == amnezia::AppsRouteMode::VpnAllExceptApps
|| mode == amnezia::AppsRouteMode::VpnOnlyForwardApps;
const bool shouldRun = vpnConnected && splitTunnelEnabled && modeSupported && !apps.isEmpty();
const QByteArray options = optionsJson(apps, vpnServer, mode);
const bool desiredChanged = !m_desired.valid || m_desired.shouldRun != shouldRun
|| options != optionsJson(m_desired.apps, m_desired.vpnServer, m_desired.mode);
m_desired.valid = true;
m_desired.shouldRun = shouldRun;
m_desired.mode = mode;
m_desired.apps = apps;
m_desired.vpnServer = vpnServer;
const bool proxyRunning = m_proxyStatus == NEVPNStatusConnected || m_proxyStatus == NEVPNStatusConnecting;
if (!desiredChanged && shouldRun == proxyRunning) {
logger.debug() << "reconcile: no change (shouldRun=" << shouldRun
<< "status=" << (m_proxyStatus < 0 ? "unknown" : VpnStatusName(static_cast<NEVPNStatus>(m_proxyStatus)))
<< ")";
return;
}
logger.info() << "reconcile: vpnConnected=" << vpnConnected
<< "splitEnabled=" << splitTunnelEnabled
<< "mode=" << (mode == amnezia::AppsRouteMode::VpnOnlyForwardApps ? "only" : "except")
<< "apps=" << apps.size()
<< "extensionActivated=" << m_extensionActivated
<< "proxyStatus=" << (m_proxyStatus < 0 ? "unknown" : VpnStatusName(static_cast<NEVPNStatus>(m_proxyStatus)))
<< "=> shouldRun=" << shouldRun;
LogApps("reconcile", apps);
if (splitTunnelEnabled && !modeSupported) {
logger.error() << "reconcile: unsupported route mode" << static_cast<int>(mode)
<< "- the proxy stays off";
}
if (shouldRun && mode == amnezia::AppsRouteMode::VpnOnlyForwardApps) {
logger.info() << "reconcile: include mode claims every flow that is not listed, so all traffic "
"except the listed apps is relayed through the extension";
}
if (shouldRun && vpnServer.isEmpty() && !m_warnedAboutEmptyServer) {
m_warnedAboutEmptyServer = true;
logger.info() << "reconcile: vpnServer is empty, the VPN endpoint will not get its own exclude rule "
"(expected for API configs; harmless, the proxy only claims listed apps)";
}
if (!shouldRun) {
stopProxy();
return;
}
activateExtension();
if (!m_extensionActivated) {
logger.info() << "reconcile: extension is not registered yet, the proxy will start once it is";
return;
}
startProxy();
}
#pragma mark - Start / stop
void MacOSSplitTunnelManager::startProxy()
{
if (@available(macOS 11.0, *)) {
const QByteArray json = optionsJson(m_desired.apps, m_desired.vpnServer, m_desired.mode);
const bool optionsChanged = (json != m_appliedOptions);
NSDictionary *options = OptionsDictionary(json);
NSData *messageData = [NSData dataWithBytes:json.constData() length:static_cast<NSUInteger>(json.size())];
NSString *bundleId = ProviderBundleId();
logger.info() << "startProxy: apps=" << m_desired.apps.size() << "optionsChanged=" << optionsChanged
<< "extension log dir=" << SplitTunnelLogDirectory() + QStringLiteral("/AmneziaVPNSplitTunnel_root");
logger.debug() << "startProxy: options =" << QString::fromUtf8(json);
WithProxyManager(^(NETransparentProxyManager *manager, NSError *loadError) {
if (manager == nil) {
this->postError(QStr(loadError.localizedDescription));
return;
}
const NEVPNStatus status = manager.connection.status;
this->onProxyStatusChanged(static_cast<int>(status));
// Already up with the same configuration: nothing to do.
if (status == NEVPNStatusConnected && !optionsChanged) {
logger.info() << "startProxy: already running with the same options";
return;
}
// Already up, new app list: push it without restarting the tunnel.
if (status == NEVPNStatusConnected) {
logger.info() << "startProxy: running, pushing the new app list as a provider message";
NETunnelProviderSession *session = (NETunnelProviderSession *)manager.connection;
if ([session isKindOfClass:[NETunnelProviderSession class]]) {
NSError *sendError = nil;
if ([session sendProviderMessage:messageData returnError:&sendError responseHandler:^(NSData *response) {
logger.debug() << "startProxy: provider acknowledged"
<< (response != nil ? (int)response.length : -1) << "bytes";
}]) {
this->m_appliedOptions = json;
return;
}
logger.error() << "startProxy: sendProviderMessage failed, restarting:" << ErrorDump(sendError);
}
}
if (status == NEVPNStatusConnecting) {
logger.info() << "startProxy: already connecting, letting it finish";
return;
}
NETunnelProviderProtocol *protocol = [[NETunnelProviderProtocol alloc] init];
protocol.providerBundleIdentifier = bundleId;
protocol.serverAddress = @"AmneziaVPN Split Tunnel";
protocol.providerConfiguration = options;
manager.protocolConfiguration = protocol;
manager.localizedDescription = @"AmneziaVPN Split Tunnel";
manager.enabled = YES;
[manager saveToPreferencesWithCompletionHandler:^(NSError *saveError) {
if (saveError != nil) {
logger.error() << "startProxy: saveToPreferences failed:" << ErrorDump(saveError);
this->postError(QStr(saveError.localizedDescription));
return;
}
// Reload so the connection object refers to the saved configuration.
[manager loadFromPreferencesWithCompletionHandler:^(NSError *reloadError) {
if (reloadError != nil) {
logger.error() << "startProxy: reload failed:" << ErrorDump(reloadError);
this->postError(QStr(reloadError.localizedDescription));
return;
}
// Attach the status observer once, after the connection object is final.
if (g_statusObserver == nil) {
g_statusObserver = [[NSNotificationCenter defaultCenter]
addObserverForName:NEVPNStatusDidChangeNotification
object:manager.connection
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NEVPNConnection *conn = (NEVPNConnection *)note.object;
this->onProxyStatusChanged(static_cast<int>(conn.status));
}];
logger.debug() << "startProxy: status observer attached";
}
NSError *startError = nil;
const BOOL started = [manager.connection startVPNTunnelWithOptions:options
andReturnError:&startError];
this->m_appliedOptions = started ? json : QByteArray();
logger.info() << "startProxy: startVPNTunnel started=" << started
<< "error=" << ErrorDump(startError);
if (!started) {
this->postError(startError != nil ? QStr(startError.localizedDescription)
: QStringLiteral("startVPNTunnel returned NO"));
}
}];
}];
});
} else {
logger.error() << "startProxy: macOS 11.0 or newer is required";
}
}
void MacOSSplitTunnelManager::stopProxy()
{
if (@available(macOS 11.0, *)) {
// Nothing has ever been loaded or started: no round trip needed.
if (g_proxyManager == nil && m_proxyStatus < 0 && m_appliedOptions.isEmpty()) {
logger.debug() << "stopProxy: no configuration in use, nothing to stop";
return;
}
m_appliedOptions.clear();
WithProxyManager(^(NETransparentProxyManager *manager, NSError *loadError) {
if (manager == nil) {
logger.error() << "stopProxy: cannot load the configuration:" << ErrorDump(loadError);
return;
}
const NEVPNStatus status = manager.connection.status;
this->onProxyStatusChanged(static_cast<int>(status));
if (status == NEVPNStatusDisconnected || status == NEVPNStatusInvalid) {
logger.debug() << "stopProxy: already" << VpnStatusName(status);
return;
}
logger.info() << "stopProxy: stopping, status was" << VpnStatusName(status);
[manager.connection stopVPNTunnel];
});
}
}
void MacOSSplitTunnelManager::removeConfiguration(void (^completion)(void))
{
if (@available(macOS 11.0, *)) {
if (g_proxyManager == nil) {
logger.debug() << "removeConfiguration: nothing loaded";
completion();
return;
}
NETransparentProxyManager *manager = g_proxyManager;
logger.info() << "removeConfiguration: removing the saved NE configuration";
[manager removeFromPreferencesWithCompletionHandler:^(NSError *removeError) {
if (removeError != nil) {
logger.error() << "removeConfiguration failed:" << ErrorDump(removeError);
} else {
logger.info() << "removeConfiguration: removed";
}
if (g_statusObserver != nil) {
[[NSNotificationCenter defaultCenter] removeObserver:g_statusObserver];
g_statusObserver = nil;
}
g_proxyManager = nil;
this->m_proxyStatus = -1;
completion();
}];
} else {
completion();
}
}
void MacOSSplitTunnelManager::disableFeature()
{
logger.info() << "disableFeature: stopping the proxy and disabling the configuration "
"(the extension stays installed)";
m_tearingDown = true;
m_desired = DesiredState {};
m_appliedOptions.clear();
if (@available(macOS 11.0, *)) {
if (g_proxyManager == nil && m_proxyStatus < 0) {
// Nothing was ever configured in this process; there may still be a
// saved configuration from an earlier run, so load it and turn it
// off rather than assuming there is nothing to do.
logger.debug() << "disableFeature: nothing running here, disabling any saved configuration";
}
WithProxyManager(^(NETransparentProxyManager *manager, NSError *loadError) {
if (manager == nil) {
logger.debug() << "disableFeature: no saved configuration:" << ErrorDump(loadError);
this->m_tearingDown = false;
this->refreshExtensionState();
return;
}
if (manager.connection.status != NEVPNStatusDisconnected
&& manager.connection.status != NEVPNStatusInvalid) {
logger.info() << "disableFeature: stopping the proxy, status was"
<< VpnStatusName(manager.connection.status);
[manager.connection stopVPNTunnel];
}
this->setConfigurationEnabled(false, ^{
this->m_tearingDown = false;
this->refreshExtensionState();
});
});
} else {
m_tearingDown = false;
}
}
void MacOSSplitTunnelManager::uninstallFeature()
{
logger.info() << "uninstallFeature: tearing down (stop -> remove configuration -> unregister)";
m_tearingDown = true;
m_desired = DesiredState {};
m_appliedOptions.clear();
if (@available(macOS 11.0, *)) {
// Sequential on purpose: removing the configuration while the tunnel is
// still stopping, or unregistering before the configuration is gone,
// leaves entries behind in System Settings.
if (g_proxyManager == nil && m_proxyStatus < 0) {
logger.debug() << "uninstallFeature: nothing was running";
deactivateExtension();
m_tearingDown = false;
return;
}
WithProxyManager(^(NETransparentProxyManager *manager, NSError *loadError) {
if (manager != nil && manager.connection.status != NEVPNStatusDisconnected
&& manager.connection.status != NEVPNStatusInvalid) {
logger.info() << "uninstallFeature: stopping the proxy, status was"
<< VpnStatusName(manager.connection.status);
[manager.connection stopVPNTunnel];
}
this->removeConfiguration(^{
this->deactivateExtension();
this->m_tearingDown = false;
});
});
} else {
m_tearingDown = false;
}
}
void MacOSSplitTunnelManager::setConfigurationEnabled(bool enabled, void (^completion)(void))
{
if (@available(macOS 11.0, *)) {
if (g_proxyManager == nil) {
logger.debug() << "setConfigurationEnabled: nothing loaded";
if (completion) {
completion();
}
return;
}
if (g_proxyManager.protocolConfiguration == nil) {
// WithProxyManager hands out a blank manager when preferences hold
// no configuration for us. Saving that one fails with "Missing
// protocol", and there is nothing to disable anyway.
logger.debug() << "setConfigurationEnabled: no saved configuration, nothing to disable";
if (completion) {
completion();
}
return;
}
if (g_proxyManager.enabled == (enabled ? YES : NO)) {
logger.debug() << "setConfigurationEnabled: already" << enabled;
if (completion) {
completion();
}
return;
}
logger.info() << "setConfigurationEnabled:" << enabled;
g_proxyManager.enabled = enabled ? YES : NO;
[g_proxyManager saveToPreferencesWithCompletionHandler:^(NSError *saveError) {
if (saveError != nil) {
logger.error() << "setConfigurationEnabled failed:" << ErrorDump(saveError);
} else {
logger.info() << "setConfigurationEnabled: saved";
}
if (completion) {
completion();
}
}];
} else if (completion) {
completion();
}
}
@@ -5,6 +5,15 @@
#include "core/utils/errorCodes.h"
#include "core/utils/routeModes.h"
#include "core/utils/commonStructs.h"
#include "logger.h"
#if defined(Q_OS_MACOS) && !defined(MACOS_NE)
#include "platforms/macos/splittunnel/macosAppInfo.h"
#endif
namespace {
Logger logger("AppSplitTunnelingUi");
}
AppSplitTunnelingUiController::AppSplitTunnelingUiController(AppSplitTunnelingController* appSplitTunnelingController,
AppSplitTunnelingModel* appSplitTunnelingModel,
@@ -18,12 +27,21 @@ AppSplitTunnelingUiController::AppSplitTunnelingUiController(AppSplitTunnelingCo
void AppSplitTunnelingUiController::addApp(const QString &appPath)
{
logger.debug() << "addApp path=" << appPath;
amnezia::InstalledAppInfo appInfo { "", "", appPath };
if (!appPath.isEmpty()) {
QFileInfo fileInfo(appPath);
appInfo.appName = fileInfo.fileName();
}
#if defined(Q_OS_MACOS) && !defined(MACOS_NE)
const bool filled = MacOSAppInfo::fillFromPath(appPath, appInfo);
logger.debug() << "fillFromPath ok=" << filled
<< "name=" << appInfo.appName
<< "bundleId=" << appInfo.packageName
<< "path=" << appInfo.appPath;
#endif
if (m_appSplitTunnelingController->addApp(appInfo)) {
emit finished(tr("Application added: %1").arg(appInfo.appName));
} else {
@@ -44,6 +62,7 @@ void AppSplitTunnelingUiController::removeApp(const int index)
{
auto modelIndex = m_appSplitTunnelingModel->index(index);
auto appPath = m_appSplitTunnelingModel->data(modelIndex, AppSplitTunnelingModel::Roles::AppPathRole).toString();
logger.info() << "removeApp index=" << index << "path=" << appPath;
m_appSplitTunnelingController->removeApp(index);
QFileInfo fileInfo(appPath);
@@ -52,12 +71,19 @@ void AppSplitTunnelingUiController::removeApp(const int index)
void AppSplitTunnelingUiController::toggleSplitTunneling(bool enabled)
{
logger.debug() << "toggleSplitTunneling" << enabled
<< "routeMode=" << static_cast<int>(m_appSplitTunnelingController->getRouteMode())
<< "apps=" << m_appSplitTunnelingController->getApps().size();
// The system extension is activated / torn down by CoreSignalHandlers, which
// listens on SecureAppSettingsRepository::appsSplitTunnelingEnabledChanged.
m_appSplitTunnelingController->toggleSplitTunneling(enabled);
emit isSplitTunnelingEnabledChanged();
}
void AppSplitTunnelingUiController::setRouteMode(int routeMode)
{
logger.info() << "setRouteMode" << routeMode
<< "(was" << static_cast<int>(m_appSplitTunnelingController->getRouteMode()) << ")";
m_appSplitTunnelingController->setRouteMode(static_cast<amnezia::AppsRouteMode>(routeMode));
emit routeModeChanged();
}
@@ -74,6 +100,16 @@ bool AppSplitTunnelingUiController::isSplitTunnelingEnabled() const
void AppSplitTunnelingUiController::updateModel()
{
m_appSplitTunnelingModel->updateModel(m_appSplitTunnelingController->getApps());
const auto apps = m_appSplitTunnelingController->getApps();
logger.debug() << "updateModel apps=" << apps.size();
m_appSplitTunnelingModel->updateModel(apps);
}
#if defined(Q_OS_MACOS) && !defined(MACOS_NE)
QString AppSplitTunnelingUiController::pickMacosApp()
{
return MacOSAppInfo::pickApplication();
}
#endif
@@ -34,6 +34,10 @@ public slots:
void updateModel();
#if defined(Q_OS_MACOS) && !defined(MACOS_NE)
QString pickMacosApp();
#endif
signals:
void routeModeChanged();
void isSplitTunnelingEnabledChanged();
@@ -11,7 +11,7 @@ import "../Config"
DrawerType2 {
id: root
property bool isAppSplitTinnelingEnabled: Qt.platform.os === "windows" || Qt.platform.os === "android"
property bool isAppSplitTinnelingEnabled: Qt.platform.os === "windows" || Qt.platform.os === "android" || (Qt.platform.os === "osx" && !IsMacOsNeBuild)
anchors.fill: parent
expandedHeight: parent.height * 0.9
@@ -38,6 +38,8 @@ PageType {
property int allExceptApps: 2
}
property bool isMacosAppSplitTunnel: Qt.platform.os === "osx" && !IsMacOsNeBuild
property list<QtObject> routeModesModel: [
onlyForwardApps,
allExceptApps
@@ -111,7 +113,7 @@ PageType {
headerText: qsTr("Mode")
enabled: (Qt.platform.os === "android") && root.pageEnabled
enabled: (Qt.platform.os === "android" || root.isMacosAppSplitTunnel) && root.pageEnabled
listView: ListViewWithRadioButtonType {
rootWidth: root.width
@@ -156,6 +158,18 @@ PageType {
visible: (Qt.platform.os === "windows") && root.pageEnabled
}
WarningType {
Layout.fillWidth: true
Layout.topMargin: 8
Layout.leftMargin: 16
Layout.rightMargin: 16
textString: qsTr("Safari and other WebKit apps cannot be split on macOS — their traffic comes from com.apple.WebKit.Networking, not from the app itself.")
iconPath: "qrc:/images/controls/alert-circle.svg"
visible: root.isMacosAppSplitTunnel && root.pageEnabled
}
}
ListViewType {
@@ -259,6 +273,11 @@ PageType {
}
} else if (Qt.platform.os === "android"){
installedAppDrawer.openTriggered()
} else if (root.isMacosAppSplitTunnel) {
var macosApp = AppSplitTunnelingController.pickMacosApp()
if (macosApp !== "") {
AppSplitTunnelingController.addApp(macosApp)
}
}
PageController.showBusyIndicator(false)
@@ -12,7 +12,7 @@ import "../Config"
PageType {
id: root
property bool isAppSplitTinnelingEnabled: Qt.platform.os === "windows" || Qt.platform.os === "android"
property bool isAppSplitTinnelingEnabled: Qt.platform.os === "windows" || Qt.platform.os === "android" || (Qt.platform.os === "osx" && !IsMacOsNeBuild)
BackButtonType {
id: backButton
+9
View File
@@ -45,6 +45,11 @@ file(TO_CMAKE_PATH "${_AMNEZIA_WIX_PATCH_CLOSE_APP}" _AMNEZIA_W
list(APPEND CPACK_WIX_PATCH_FILE "${_AMNEZIA_WIX_PATCH_SERVICE_CMAKE}" "${_AMNEZIA_WIX_PATCH_CLOSE_APP_CMAKE}")
list(APPEND CPACK_WIX_EXTENSIONS "WixToolset.Util.wixext")
if(APPLE AND NOT IOS AND NOT MACOS_NE)
set(CPACK_AMNEZIA_MACOS_APP_ENTITLEMENTS "${CLIENT_MACOS_APP_DEVELOPERID_ENTITLEMENTS_PATH}")
set(CPACK_AMNEZIA_MACOS_ST_ENTITLEMENTS "${CLIENT_MACOS_ST_ENTITLEMENTS_PATH}")
endif()
# === CPack productbuild generator settings ===
set(CPACK_PRODUCTBUILD_IDENTIFIER org.amneziavpn)
set(CPACK_PREFLIGHT_AMNEZIAVPN_SCRIPT ${CMAKE_SOURCE_DIR}/deploy/data/macos/post_uninstall.sh)
@@ -90,6 +95,10 @@ if (APPLE AND NOT IOS AND NOT MACOS_NE)
DESTINATION "AmneziaVPN.app/Contents/Resources"
COMPONENT AmneziaVPN
)
install(DIRECTORY ${CMAKE_SOURCE_DIR}/deploy/data/macos/pf
DESTINATION "AmneziaVPN.app/Contents/MacOS"
COMPONENT AmneziaVPN
)
endif()
include(CPackIFW)
+9
View File
@@ -15,3 +15,12 @@ if(NOT CODESIGN_INSTALLER_KEYCHAIN)
endif()
set(CPACK_PRODUCTBUILD_KEYCHAIN_PATH "${CODESIGN_INSTALLER_KEYCHAIN}")
set(CPACK_PKGBUILD_KEYCHAIN_PATH "${CODESIGN_INSTALLER_KEYCHAIN}")
# Set in cmake/CPack.cmake before include(CPack); keep them if this file is the
# only CPack config the pre-build script sees.
if(NOT CPACK_AMNEZIA_MACOS_APP_ENTITLEMENTS)
set(CPACK_AMNEZIA_MACOS_APP_ENTITLEMENTS "$ENV{CPACK_AMNEZIA_MACOS_APP_ENTITLEMENTS}")
endif()
if(NOT CPACK_AMNEZIA_MACOS_ST_ENTITLEMENTS)
set(CPACK_AMNEZIA_MACOS_ST_ENTITLEMENTS "$ENV{CPACK_AMNEZIA_MACOS_ST_ENTITLEMENTS}")
endif()
+60 -4
View File
@@ -7,6 +7,12 @@ endif()
if(NOT DEFINED CODESIGN_KEYCHAIN)
set(CODESIGN_KEYCHAIN "$ENV{CODESIGN_KEYCHAIN}")
endif()
if(NOT DEFINED CODESIGN_APP_PROVISION_PROFILE)
set(CODESIGN_APP_PROVISION_PROFILE "$ENV{CODESIGN_APP_PROVISION_PROFILE}")
endif()
if(NOT DEFINED CODESIGN_ST_PROVISION_PROFILE)
set(CODESIGN_ST_PROVISION_PROFILE "$ENV{CODESIGN_ST_PROVISION_PROFILE}")
endif()
if(WIN32)
file(GLOB_RECURSE BINARIES
@@ -29,7 +35,11 @@ if(APPLE)
file(GLOB_RECURSE dylibs "${CPACK_TEMPORARY_DIRECTORY}/*.dylib")
set(bundle ${all_subdirs})
list(FILTER bundle INCLUDE REGEX [[.*\.app$]])
list(FILTER bundle INCLUDE REGEX [[/AmneziaVPN\.app$]])
list(LENGTH bundle bundle_count)
if(NOT bundle_count EQUAL 1)
message(FATAL_ERROR "Expected one AmneziaVPN.app in the package staging dir, found ${bundle_count}")
endif()
list(GET bundle 0 bundle)
file(GLOB_RECURSE execs "${bundle}/Contents/MacOS/*")
@@ -39,11 +49,57 @@ if(APPLE)
list(FILTER service_exec INCLUDE REGEX [[AmneziaVPN-service$]])
set(other_execs ${execs})
list(FILTER other_execs EXCLUDE REGEX [[AmneziaVPN$|AmneziaVPN-service$]])
list(FILTER other_execs EXCLUDE REGEX [[/pf/]])
list(APPEND files "${frameworks}" "${dylibs}" "${other_execs}" "${service_exec}" "${client_exec}" "${bundle}")
set(sysexts ${all_subdirs})
list(FILTER sysexts INCLUDE REGEX [[.*\.systemextension$]])
list(APPEND inner_files "${frameworks}" "${dylibs}" "${other_execs}" "${service_exec}" "${client_exec}")
list(FILTER inner_files EXCLUDE REGEX "^$")
if (CODESIGN_SIGNATURE)
if(NOT sysexts)
message(FATAL_ERROR "macOS package is missing the split-tunnel .systemextension bundle")
endif()
if(NOT EXISTS "${CPACK_AMNEZIA_MACOS_APP_ENTITLEMENTS}")
message(FATAL_ERROR "Host entitlements file is missing: ${CPACK_AMNEZIA_MACOS_APP_ENTITLEMENTS}")
endif()
if(NOT EXISTS "${CPACK_AMNEZIA_MACOS_ST_ENTITLEMENTS}")
message(FATAL_ERROR "Split-tunnel entitlements file is missing: ${CPACK_AMNEZIA_MACOS_ST_ENTITLEMENTS}")
endif()
if(NOT CODESIGN_APP_PROVISION_PROFILE OR NOT EXISTS "${CODESIGN_APP_PROVISION_PROFILE}")
message(FATAL_ERROR "Set CODESIGN_APP_PROVISION_PROFILE to the host Developer ID provisioning profile")
endif()
if(NOT CODESIGN_ST_PROVISION_PROFILE OR NOT EXISTS "${CODESIGN_ST_PROVISION_PROFILE}")
message(FATAL_ERROR "Set CODESIGN_ST_PROVISION_PROFILE to the split-tunnel Developer ID provisioning profile")
endif()
execute_process(
COMMAND ${CMAKE_COMMAND} -E copy
"${CODESIGN_APP_PROVISION_PROFILE}"
"${bundle}/Contents/embedded.provisionprofile"
RESULT_VARIABLE _amn_copy_app_profile
)
if(NOT _amn_copy_app_profile EQUAL 0)
message(FATAL_ERROR "Failed to copy host provisioning profile into ${bundle}")
endif()
foreach(sysex IN LISTS sysexts)
execute_process(
COMMAND ${CMAKE_COMMAND} -E copy
"${CODESIGN_ST_PROVISION_PROFILE}"
"${sysex}/Contents/embedded.provisionprofile"
RESULT_VARIABLE _amn_copy_st_profile
)
if(NOT _amn_copy_st_profile EQUAL 0)
message(FATAL_ERROR "Failed to copy split-tunnel provisioning profile into ${sysex}")
endif()
endforeach()
if (files AND CODESIGN_SIGNATURE)
include(${CMAKE_CURRENT_LIST_DIR}/util/codesign.cmake)
codesign_sign_files("${files}" "${CODESIGN_SIGNATURE}" "${CODESIGN_KEYCHAIN}")
if (inner_files)
codesign_sign_files("${inner_files}" "${CODESIGN_SIGNATURE}" "${CODESIGN_KEYCHAIN}")
endif()
codesign_sign_files("${sysexts}" "${CODESIGN_SIGNATURE}" "${CODESIGN_KEYCHAIN}" "${CPACK_AMNEZIA_MACOS_ST_ENTITLEMENTS}")
codesign_sign_files("${bundle}" "${CODESIGN_SIGNATURE}" "${CODESIGN_KEYCHAIN}" "${CPACK_AMNEZIA_MACOS_APP_ENTITLEMENTS}")
endif()
endif()
+4
View File
@@ -13,6 +13,10 @@ function(codesign_sign_files files signature keychain)
--sign "${signature}"
)
if(ARGC GREATER 3 AND ARGV3)
list(APPEND args --entitlements "${ARGV3}")
endif()
if(keychain)
list(APPEND args --keychain "${keychain}")
endif()
@@ -1,2 +0,0 @@
# Rules are set at runtime
@@ -0,0 +1,7 @@
# Bypass traffic sourced by the split-tunnel system extension (gid amnvpn).
#
# Numbered 320 on purpose: it has to win over 250.blockIPv6 and 310.blockDNS,
# which the WireGuard path enables while the kill switch is armed. pf is
# last-match-wins, so an earlier anchor would be overridden by those two and
# excluded apps would lose IPv6 and direct DNS.
pass out proto { tcp, udp } group amnvpn flags any no state
+1 -1
View File
@@ -6,11 +6,11 @@ anchor "000.allowLoopback"
anchor "100.blockAll"
anchor "110.allowNets"
anchor "120.blockNets"
anchor "150.allowExcludedApps"
anchor "200.allowVPN"
anchor "250.blockIPv6"
anchor "290.allowDHCP"
anchor "300.allowLAN"
anchor "310.blockDNS"
anchor "320.allowExcludedApps"
anchor "350.allowHnsd"
anchor "400.allowPIA"
+23
View File
@@ -34,6 +34,29 @@ if launchctl list "${APP_NAME}-service" &> /dev/null; then
fi
sudo rm -f "$LAUNCH_DAEMONS_PLIST_NAME"
# ---------------- Split-tunnel system extension ------------------------------
# Must run while the bundle is still on disk: systemextensionsctl resolves the
# extension through its host app.
ST_BUNDLE_ID="org.amnezia.AmneziaVPN.network-extension"
ST_TEAM_ID="X7UJ388FXK"
if command -v systemextensionsctl >/dev/null 2>&1; then
if systemextensionsctl list 2>/dev/null | grep -q "$ST_BUNDLE_ID"; then
echo "Removing split-tunnel system extension $ST_BUNDLE_ID"
if ! sudo systemextensionsctl uninstall "$ST_TEAM_ID" "$ST_BUNDLE_ID"; then
echo "Could not remove the system extension automatically."
echo "Remove it manually in System Settings > General > Login Items & Extensions > Network Extensions."
fi
else
echo "No split-tunnel system extension registered"
fi
fi
# The "AmneziaVPN Split Tunnel" entry in System Settings > Network belongs to
# the NetworkExtension preferences and can only be removed by the app itself
# (it does so when app split tunneling is switched off). If one is left over,
# remove it from System Settings > Network.
# Remove the entire application bundle
sudo rm -rf "$APP_PATH"
+1
View File
@@ -426,6 +426,7 @@ bool KillSwitch::enableKillSwitch(const QJsonObject &configStr, int vpnAdapterIn
MacOSFirewall::setAnchorEnabled(QStringLiteral("310.blockDNS"), true);
MacOSFirewall::setAnchorTable(QStringLiteral("310.blockDNS"), true, QStringLiteral("dnsaddr"), dnsServers);
MacOSFirewall::setAnchorEnabled(QStringLiteral("320.allowExcludedApps"), true);
MacOSFirewall::setAnchorEnabled(QStringLiteral("400.allowPIA"), true);
#endif
return true;