PLATFORM AND VERSION
macOS
Development environment: Xcode 15.0, macOS 15.0.1
Run-time configuration: macOS 15.0.1
DESCRIPTION OF PROBLEM
We are currently developing a macOS app using the NEFilterDataProvider in the Network Extension framework, and we've encountered an issue regarding hostname resolution that we would like your guidance on.
In our implementation, we need to drop network flows based on the hostname. The app successfully receives the remoteHostname or remoteEndpoint.hostname for browsers such as Safari and Mozilla Firefox. However, for other browsers like Chrome, Opera Mini, Arc, Brave, and Edge, we only receive the IP address instead of the hostname.
We are particularly looking for a way to retrieve the hostname for all browsers to apply our filtering logic consistently. Could you please advise whether there is any additional configuration or API we can use to ensure that we receive hostnames for these browsers as well? Alternatively, is this a limitation of the browsers themselves, and should we expect to only receive IP addresses for certain cases?
STEPS TO REPRODUCE
For Chrome, Brave, Edge, and Arc browsers you won't receive the hostname in NEFilterFlow.
Using the same sample project provided in WWDC 2019 https://developer.apple.com/documentation/networkextension/filtering_network_traffic
import NetworkExtension
import os.log
import Network
/**
The FilterDataProvider class handles connections that match the installed rules by prompting
the user to allow or deny the connections.
*/
class FilterDataProvider: NEFilterDataProvider {
// MARK: NEFilterDataProvider
override func startFilter(completionHandler: @escaping (Error?) -> Void) {
completionHandler(nil)
}
override func stopFilter(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
completionHandler()
}
override func handleNewFlow(_ flow: NEFilterFlow) -> NEFilterNewFlowVerdict {
guard let socketFlow = flow as? NEFilterSocketFlow,
let remoteEndpoint = socketFlow.remoteEndpoint as? NWHostEndpoint,
let localEndpoint = socketFlow.localEndpoint as? NWHostEndpoint else {
return .allow()
}
var hostName: String? = nil
// Attempt to use the URL host for native apps (e.g., Safari)
if let url = socketFlow.url {
hostName = url.host
os_log("URL-based Host: %@", hostName ?? "No host found")
}
// Fallback: Use remote hostname for third-party browsers like Chrome
if hostName == nil {
if #available(macOS 11.0, *), let remoteHostname = socketFlow.remoteHostname {
hostName = remoteHostname
os_log("Remote Hostname: %@", hostName ?? "No hostname found")
} else {
hostName = remoteEndpoint.hostname
os_log("IP-based Hostname: %@", hostName ?? "No hostname found")
}
}
let flowInfo = [
FlowInfoKey.localPort.rawValue: localEndpoint.port,
FlowInfoKey.remoteAddress.rawValue: remoteEndpoint.hostname,
FlowInfoKey.hostName.rawValue: hostName ?? "No host found"
]
// Ask the app to prompt the user
let prompted = IPCConnection.shared.promptUser(aboutFlow: flowInfo, rawFlow: flow) { allow in
let userVerdict: NEFilterNewFlowVerdict = allow ? .allow() : .drop()
self.resumeFlow(flow, with: userVerdict)
}
guard prompted else {
return .allow()
}
return .pause()
}
// Helper function to check if a string is an IP address
func isIPAddress(_ hostName: String) -> Bool {
var sin = sockaddr_in()
var sin6 = sockaddr_in6()
if hostName.withCString({ inet_pton(AF_INET, $0, &sin.sin_addr) }) == 1 {
return true
} else if hostName.withCString({ inet_pton(AF_INET6, $0, &sin6.sin6_addr) }) == 1 {
return true
}
return false
}
}
Networking
RSS for tagExplore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi
I just encountered an reachability detection problem by calling SCNetworkReachabilityGetFlags function in iOS 16.
what did I do:
on device iPhone 12, iOS 16.1.1, turn on Airplane Mode, call SCNetworkReachabilityGetFlags, got flags = kSCNetworkReachabilityFlagsTransientConnection | kSCNetworkReachabilityFlagsReachable
on device iPhone 7, iOS 14.5.1, turn on Airplane Mode, call SCNetworkReachabilityGetFlags, got flags = 0
what I expect:
I'm expecting SCNetworkReachabilityGetFlags on my iOS 16.1 device behave same as my iOS 14.5 device, returning flags = 0. It's inappropriate returning kSCNetworkReachabilityFlagsReachable in this case.
Thank you!
Hello everyone I'm new to swift and I can't quite figure it out yet:(
I am developing a simple online game for mac os that involves two players connected to the same WIFI. I need to constantly receive information from the server and I don't understand how to implement it. If I call the receive function indefinitely, then my program freezes. I realized that this should happen asynchronously, but that's just how my program understands when a package came from the server. I understand that I need a delegate or handler, but I don't understand how to do it. Please help me to add the receive function and everything that is necessary for it
import Foundation
import Network
enum CustomErrors: Error {
case DataError
case NetworkError
case DecoderError
case InvalidAddress
}
class TapperConnection: ObservableObject {
private var _serverAlive = false
private var connection: NWConnection!
private var serverPort: UInt16 = 20001
private var serverIp: String = "127.0.0.1"
private var _myDeviceName = Host.current().localizedName ?? ""
@Published var messageDc: [HostData] = []
@Published var messageLobby: [HostData] = []
@Published var messageState: GameData = GameData()
private var buffer = 2048
private var _inputData = ""
private var _outputData = ""
private var _myIp = ""
private var isServer = false
private var isClient = false
var myIp: String {
return _myIp
}
var myDeviceName: String {
return _myDeviceName
}
private func getMyIp() -> String? {
var address: String?
var ifaddr: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return nil }
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
let name = String(cString: interface.ifa_name)
if name == "en0" || name == "en2" || name == "en3" || name == "en4" || name == "pdp_ip0" || name == "pdp_ip1" || name == "pdp_ip2" || name == "pdp_ip3" {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
private func isValidIP(_ ip: String) -> Bool {
let regex = try! NSRegularExpression(pattern: "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
return regex.firstMatch(in: ip, range: NSRange(location: 0, length: ip.utf16.count)) != nil
}
@Sendable
private func updateServerState(to state: NWConnection.State) {
switch state {
case .setup:
_serverAlive = true
case .waiting:
_serverAlive = true
case .ready:
_serverAlive = true
case .failed:
_serverAlive = false
case .cancelled:
_serverAlive = false
case .preparing:
_serverAlive = false
default:
_serverAlive = false
}
}
func createConnection() throws {
let ip = getMyIp()
if ip != nil {
serverIp = ip!
_myIp = ip!
} else {
throw CustomErrors.NetworkError
}
isServer = true
do {
try connectToServer()
} catch {
throw CustomErrors.NetworkError
}
}
func createConnection(ip: String) throws {
if isValidIP(ip) {
serverIp = ip
} else {
throw CustomErrors.InvalidAddress
}
let _ip = getMyIp()
if _ip != nil {
_myIp = _ip!
} else {
throw CustomErrors.NetworkError
}
isClient = true
do {
try connectToServer()
} catch {
throw CustomErrors.NetworkError
}
}
private func connectToServer() throws {
if isServer {
// ...............
// run server exec
// ...............
}
let _params = NWParameters(dtls: nil, udp: .init())
_params.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host(_myIp), port: 20002)
connection = NWConnection(host: NWEndpoint.Host(serverIp), port: NWEndpoint.Port(rawValue: serverPort)!, using: _params)
connection.stateUpdateHandler = updateServerState(to:)
connection.start(queue: .global())
while !_serverAlive {}
do {
try send(message: "im:\(_myDeviceName)")
receive()
} catch {
print("Error sending disconnect message: \(error)")
}
}
func closeConnection() {
do {
try send(message: "dc:\(_myDeviceName)")
} catch {
print("Error sending disconnect message: \(error)")
}
_serverAlive = false
connection.cancel()
}
func send(message: String) throws {
var error = false
connection.send(content: message.data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ NWError in
if NWError == nil {
print("Data was sent!")
} else {
error = true
}
})))
if error {
throw CustomErrors.NetworkError
}
}
func receive() {
self.connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { data, _, isComplete, _ in
if isComplete {
if data != nil {
let response: String = String(decoding: data!, as: UTF8.self)
var decodeData: Any
var messageType: MessageType
(decodeData, messageType) = try! Decoder.decodeMessage(response)
switch messageType {
case MessageType.lobby:
self.messageLobby = decodeData as! [HostData]
case MessageType.state:
self.messageState = decodeData as! GameData
case MessageType.dc:
self.messageDc = decodeData as! [HostData]
}
}
self.receive()
}
}
}
}
I have tests where I connect to NEPacketTunnelProvider. I run tests with circleci and fastlane, on self hosted intel and arm macs. I updated macs from macOS 13 to macOS 14 and the tests on arm stopped connecting, while the same tests on intel kept working as usual. Moreover, I noticed the tests don't work when run from circleci and fastlane. If I cancel the job and click "connect" myself on the app that stayed hanging from the cancelled tests, the connection will succeed. But if the tests are running, the connection will fails. Running the tests from xcode succeeds too.
These are the logs from the tunnel. Could you suggest me where to dig? Or maybe you can see the issue from the logs?
Tunnel logs when they fail
Could anyone teach me how to ask iOS 18 to have a prompt during set-up process of a new APP if user accidentally turns off Local Network ?
With little knowledge on C++, but help from ChatGPT, I am trying to write a plugin for OBS.
I would like to include a bonjour service in the plugin. I assume that the framework is already present on every Mac, but I don't know where it resides, and how to #include it.
Anyone can help me here?
Thanks in advance
https://developer.apple.com/forums/thread/735862?login=true
Hello Team,
I want to know if there's a way to uninstall System Extension without prompting the user for authorisation.
These are ways I found to uninstall System Extension
The deactivationRequest api prompts the user for uninstalling System extension.
If I use Apple script to drag and drop the application[which is embedded with System Extension] to trash also prompts the user.
The only workaround that doesn't prompt is by disabling SIP and using the systemextensionsctl uninstall command.
I want to know if there's any other solution that can uninstall System Extension without prompting the user for authorisation.
Thanks!
Topic:
App & System Services
SubTopic:
Networking
Tags:
System Extensions
Network Extension
Device Management
I’m developing an app designed for hospital environments, where public internet access may not be available. The app includes two components: the main app and a Local Connectivity Extension. Both rely on persistent TCP socket connections to communicate with a local server.
We’re observing a recurring issue where the extension’s socket becomes unresponsive every 1–3 hours, but only when the device is on the lock screen, even if the main app remains in the foreground.
When the screen is not locked, the connection is stable and no disconnections occur.
❗ Issue Details:
• What’s going on: The extension sends a keep-alive ping packet every second, and the server replies with a pong and a system time packet.
• The bug: The server stops receiving keep alive packets from the extension.
• On the server, we detect about 30 second gap on the server, a gap that shows no packets were received by the extension. This was confirmed via server logs and Wireshark).
• On the extension, from our logs there was no gap in sending packets. From it’s perspective, all packets were sent with no error.
• Because no packet are being received by the server, no packets will be sent to the extension. Eventually the server closes the connection due to keep-alive timeout.
• FYI we log when the NEAppPushProvider subclass sleeps and it did NOT go to sleep while we were debugging.
🧾 Example Logs:
Extension log:
2025-03-24 18:34:48.808 sendKeepAliveRequest()
2025-03-24 18:34:49.717 sendKeepAliveRequest()
2025-03-24 18:34:50.692 sendKeepAliveRequest()
... // continuous sending of the ping packet to the server, no problems here
2025-03-24 18:35:55.063 sendKeepAliveRequest()
2025-03-24 18:35:55.063 keepAliveTimer IS TIME OUT... in CoreService. // this is triggered because we did not receive any packets from the server
2025-03-24 18:34:16.298 No keep-alive received for 16 seconds... connection ID=95b3... // this shows that there has been no packets being received by the extension
...
2025-03-24 18:34:30.298 Connection timed out on keep-alive. connection ID=95b3... // eventually closes due to no packets being received
2025-03-24 18:34:30.298 Remote Subsystem Disconnected {name=iPhone|Replica-Ext|...}
✅ Observations:
• The extension process continues running and logging keep-alive attempts.
• However, network traffic stops reaching the server, and no inbound packets are received by the extension.
• It looks like the socket becomes silently suspended or frozen, without being properly closed or throwing an error.
❓Questions:
• Do you know why this might happen within a Local Connectivity Extension, especially under foreground conditions and locked ?
• Is there any known system behavior that might cause the socket to be suspended or blocked in this way after running for a few hours?
Any insights or recommendations would be greatly appreciated.
Thank you!
I have read the other most relevant posts on this topic here and here. However, the situations described in these posts are different. My app is just a regular Mach-O bundle with a single executable that is launched by the user from the Finder. I've read the Local Network Privacy FAQ and TN3179 carefully and these also doesn't cover the problem described below, which is being reported to me by several of my users.
The problem is that some days after giving Local Network permission to my app, without having changed anything, local network connections will spontaneously start failing with EHOSTUNREACH, indicating that it is being blocked by macOS. This typically happens after a Mac reboot. Toggling off/on the Local Network permission for my app will get it working again, until the next time it fails.
My users who are reporting this have stated that they are running macOS Sonoma 15.2, with only a single version/copy of my app installed.
I've tried, and failed, to reproduce this in a VM with a clean 15.2 system, but maybe this is due to the relatively short duration of my testing (days rather than weeks).
I know there isn't much to go on here, and it may be tempting to put this down to misreporting. After all, the vast majority of my users aren't reporting this, and I can't reproduce it. But, I have received enough similar reports at this point that it's starting to feel like a macOS bug.
Is anyone else seeing this? If there is anything that anyone can suggest - either modifications in my app, or anything that my users can do on their side - this would be very much appreciated!
Many thanks,
Ben
Hi, I am working on a case in our organisation where hundreds if not a thousand wireless network clients are affected by regular, usually 30 sometimes 60 minute sometime they are unnoticeable but often people having meetings notice that a lot.
We excluded wireless network configuration issue since disconnections happens to clients both connected to Cisco and Ubiquiti Access Points.
WLC logs mostly show EAP timeout errors - clients are getting disauthenticated and authenticated back - usually without any action needed - but the meeting is being interrupted.
What I found in Macbook logs with sudo log show [options] is the main reason of network disconnection:
2025-02-04 14:16:31.219192+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[DPSQuickRecoveryRecommendationEngine updateTimeSincePreviousTriggerForStudy:msgKey:dictKey:]::913:msgkey:WFAAWDWASDS_symptomsDnsTimeSincePreviousTriggerMinutes dictKey:dps_lastSymptomsDpsTrigger previous_TS:(null) current_TS:Tue Feb 4 14:16:31 2025 difference:0
2025-02-04 14:16:31.219704+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[DPSQuickRecoveryRecommendationEngine updateScreenState]::198:DPS Fast Reset Recommendation Engine: (screenON & foreGrnd traffic) is DETECTED
2025-02-04 14:16:31.219713+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[DPSQuickRecoveryRecommendationEngine recommendSymptomsDpsRecovery:symptomsDnsStats:awdlState:currentSymptomsCondition:isLANPingSuccessful:appUsage:averageCCA:]::966:PeerDiagnostics: Data not received from peerDiagnostics
2025-02-04 14:16:31.219714+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[DPSQuickRecoveryRecommendationEngine checkForPriorityNetwork]::256:Priority Network Check Disabled: NO IsPriorityNetwork: YES
2025-02-04 14:16:31.219732+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[DPSQuickRecoveryRecommendationEngine isResetAllowedForKey:forPrefSelector:]::330:key:symptomsDps_lastScreenOnRecoveryWD previousWD_TS:(null) currentWD_TS:Tue Feb 4 14:16:31 2025 recommendation:YES
2025-02-04 14:16:31.219735+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[DPSQuickRecoveryRecommendationEngine updateSymptomsDPSRecoveryWDStatsForKey:]::210:Added key: symptomsDps_numRecommendedScreenOnRecoveryWD value:1 dict:(null)
2025-02-04 14:16:31.219737+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[DPSQuickRecoveryRecommendationEngine recommendSymptomsDpsRecovery:symptomsDnsStats:awdlState:currentSymptomsCondition:isLANPingSuccessful:appUsage:averageCCA:]::1023:PeerDiagnostics: Recommendation for DNS Symptoms Recovery: Reassoc
Do you guys have any idea where can I see that DNS symptoms?
I can also see some reading like:
2025-02-04 14:16:31.219169+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[WAEngine gatherConsecutiveDatapathReadings:forProcessToken:andReply:]_block_invoke::4235:DNS Symptoms pre-decision check:: Associated:YES Primary:YES isCaptive:NO isValidDnsConfig:YES
2025-02-04 14:16:31.219169+0100 0xc01342 Default 0x0 86459 0 wifianalyticsd: [com.apple.wifi.analytics:Default] -[WAEngine gatherConsecutiveDatapathReadings:forProcessToken:andReply:]_block_invoke::4238:SDNS: WiFi Not Primary - setting suppressedReason kSymptomsDnsWiFiInterfaceNotPrimary
WiFi Not Primary - how if this is my only interface? - I removed all other
Killing and disabling wifianalyticsd does not help - the process is being spawned by launchd on airportd request:
2025-02-04 08:54:11.903825+0100 0xb85274 Default 0x0 627 0 airportd: (WiFiAnalytics) [com.apple.wifi.analytics:Default] -[WAClient _establishDaemonConnection]_block_invoke::1057:XPC: establishing connection to daemon with token ending in: <private>...
2025-02-04 08:54:11.907779+0100 0xb8504a Default 0x0 627 0 airportd: (IO80211) [com.apple.WiFiManager:] Info: <airport[627]> -[dpsManager submitDpsSymptom:isCriticalApp:]_block_invoke:
2025-02-04 08:54:11.907943+0100 0xb8504a Default 0x0 627 0 airportd: (IO80211) -[dpsManager submitDpsSymptom:isCriticalApp:]_block_invoke: Error preparing DPSNotification for submission: Error Domain=com.apple.wifi.analytics.errordomain Code=9014 "WAErrorCodeDaemonContactTimeout" UserInfo={NSLocalizedFailureReason=WAErrorCodeDaemonContactTimeout}, or null WAMessageAWD
2025-02-04 08:54:11.908055+0100 0xb8504a Default 0x0 627 0 airportd: (IO80211) [com.apple.WiFiManager:] <airport[627]> -[dpsManager submitDpsSymptom:isCriticalApp:]_block_invoke: Error preparing DPSNotification for submission: Error Domain=com.apple.wifi.analytics.errordomain Code=9014 "WAErrorCodeDaemonContactTimeout" UserInfo={NSLocalizedFailureReason=WAErrorCodeDaemonContactTimeout}, or null WAMessageAWD
2025-02-04 08:54:11.910453+0100 0xb85274 Default 0x0 627 0 airportd: (libxpc.dylib) [com.apple.xpc:connection] [0x80fe64640] activating connection: mach=true listener=false peer=false name=com.apple.wifianalyticsd
2025-02-04 08:54:11.911105+0100 0xb85382 Default 0x0 1 0 launchd: [system/com.apple.wifianalyticsd:] internal event: WILL_SPAWN, code = 0
2025-02-04 08:54:11.911229+0100 0xb85382 Default 0x0 1 0 launchd: [system/com.apple.wifianalyticsd:] service state: spawn scheduled
2025-02-04 08:54:11.911233+0100 0xb85382 Default 0x0 1 0 launchd: [system/com.apple.wifianalyticsd:] service state: spawning
2025-02-04 08:54:11.911384+0100 0xb85382 Default 0x0 1 0 launchd: [system/com.apple.wifianalyticsd:] launching: ipc (mach)
2025-02-04 08:54:11.920272+0100 0xb85382 Default 0x0 1 0 launchd: [system/com.apple.wifianalyticsd [86459]:] xpcproxy spawned with pid 86459
Do you guys have any idea what is the cause of this behaviour?
Or how to disable wifianalyticsd process for good?
Topic:
App & System Services
SubTopic:
Networking
iOS devices are failing to launch WebSheet (i.e. captive portal mini browser) when auto-join is used to connect to Hotspot 2.0 SSID with a captive portal. Logs captured from the device & RADIUS show that the device associates to the SSID, but does not launch the WebSheet due to the error, "Unable to launch WebSheet because this network has become captive". Afterwards the device may send an EAPOL Logoff request to the Access Point & disconnect from the network.
If manually selecting the SSID from Settings > Wi-Fi, then the same device will log It's a manual join so no further checks required, remain associated to the SSID & launch the captive portal browser which is able to load the captive browser.
info 17:28:35.298531-0500 configd device setup is completed
info 17:28:35.298566-0500 configd Unable to launch WebSheet because this network has become captive, blacklisting network [HS2_Captive_Test]
info 17:28:35.298604-0500 configd Removing FF981347-FDFA-45FD-82D9-88BA0426C0A3
default 17:28:35.298641-0500 configd __BUILTIN__: PresentUI result Temporary Failure (6)
default 17:28:35.298677-0500 configd CNPluginHandler en0: Failure (__BUILTIN__)
default 17:28:35.298716-0500 configd Temporarily disabling (blacklisting) HS2_Captive_Test
Websheet should only be launched when the device is captive. Why wouldWebSheet fail to launch when the device is captive?
Hello. I would like to develop an application that sends SSH commands via my phone to the server. I know that applications of this type exist, but they are not suitable for my use as a blind person who uses a screen reader. I hope you can help me find libraries that will assist me in development, or ready-made, open-source projects that I can develop and modify if necessary. Thank you in advance.
Topic:
App & System Services
SubTopic:
Networking
I have implemented SSL pinning by following this article https://developer.apple.com/news/?id=g9ejcf8y , however pen testing team was able to bypass SSL pinning using Objection & Frida tools.
I am using URLSession for API calls. I used Xcode 16. My app's minimum iOS deployment version is 16 onwards.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSPinnedDomains</key>
<dict>
<key>*.mydomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSPinnedCAIdentities</key>
<array>
<dict>
<key>SPKI-SHA256-BASE64</key>
<string>my SHA256 key</string>
</dict>
</array>
</dict>
</dict>
</dict>
Could anyone suggest how to mitigate this bypass mechanism?
I am currently developing a custom-protocol VPN application for iOS using PacketTunnelProvider. I have also integrated an HTTP proxy service, which is launched via a dylib.
The overall flow is as follows:
App -> VPN TUN -> Local HTTP Proxy -> External Network
I have a question:
I am capturing all traffic, and normally, requests sent out by the HTTP proxy are also captured again by the VPN. However, when I send requests using createUdpSession in my code, they are not being captured by the virtual interface (TUN).
What could be the reason for this?
override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
let tunnelNetworkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "192.168.18.0")
tunnelNetworkSettings.mtu=1400
let ipv4Settings = NEIPv4Settings(addresses: ["192.169.10.10"], subnetMasks: ["255.255.255.0"])
ipv4Settings.includedRoutes=[NEIPv4Route.default()]
ipv4Settings.excludedRoutes = [NEIPv4Route(destinationAddress: "10.0.0.0", subnetMask: "255.0.0.0"),
NEIPv4Route(destinationAddress: "172.16.0.0", subnetMask: "255.240.0.0"),
NEIPv4Route(destinationAddress: "192.168.0.0", subnetMask: "255.255.0.0"),
NEIPv4Route(destinationAddress:"127.0.0.0", subnetMask: "255.0.0.0"),
]
tunnelNetworkSettings.ipv4Settings = ipv4Settings
// Configure proxy settings
let proxySettings = NEProxySettings()
proxySettings.httpEnabled = true
proxySettings.httpServer = NEProxyServer(address: "127.0.0.1", port: 7890)
proxySettings.httpsEnabled = true
proxySettings.httpsServer = NEProxyServer(address: "127.0.0.1", port: 7890)
proxySettings.excludeSimpleHostnames = true
proxySettings.exceptionList=["localhost","127.0.0.1"]
tunnelNetworkSettings.proxySettings = proxySettings
setTunnelNetworkSettings(tunnelNetworkSettings) { [weak self] error in
if error != nil {
completionHandler(error)
return
}
completionHandler(nil)
let stack = TUNInterface(packetFlow: self!.packetFlow)
RawScoketFactory.TunnelProvider=self
stack.register(stack: UDPDirectStack())
stack.register(stack: TCPDirectStack())
stack.start()
}
}
NWUdpSession.swift
//
// NWUDPSocket.swift
// supervpn
//
// Created by TobbyQuinn on 2025/2/3.
//
import Foundation
import NetworkExtension
import CocoaLumberjack
public protocol NWUDPSocketDelegate: AnyObject{
func didReceive(data:Data,from:NWUDPSocket)
func didCancel(socket:NWUDPSocket)
}
public class NWUDPSocket:NSObject{
private let session:NWUDPSession
private let timeout:Int
private var pendingWriteData: [Data] = []
private var writing = false
private let queue:DispatchQueue=QueueFactory.getQueue()
public weak var delegate:NWUDPSocketDelegate?
public init?(host:String,port:UInt16,timeout:Int=Opt.UDPSocketActiveTimeout){
guard let udpSession = RawScoketFactory.TunnelProvider?.createUDPSession(to: NWHostEndpoint(hostname: host, port: "\(port)"), from: nil) else{
return nil
}
session = udpSession
self.timeout=timeout
super.init()
session.addObserver(self, forKeyPath: #keyPath(NWUDPSession.state),options: [.new], context: nil)
session.setReadHandler({ dataArray, error in
self.queueCall{
guard error == nil, let dataArray = dataArray else {
print("Error when reading from remote server or connection reset")
return
}
for data in dataArray{
self.delegate?.didReceive(data: data, from: self)
}
}
}, maxDatagrams: 32)
}
/**
Send data to remote.
- parameter data: The data to send.
*/
public func write(data: Data) {
pendingWriteData.append(data)
checkWrite()
}
public func disconnect() {
session.cancel()
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard keyPath == "state" else {
return
}
switch session.state {
case .cancelled:
queueCall {
self.delegate?.didCancel(socket: self)
}
case .ready:
checkWrite()
default:
break
}
}
private func checkWrite() {
guard session.state == .ready else {
return
}
guard !writing else {
return
}
guard pendingWriteData.count > 0 else {
return
}
writing = true
session.writeMultipleDatagrams(self.pendingWriteData) {_ in
self.queueCall {
self.writing = false
self.checkWrite()
}
}
self.pendingWriteData.removeAll(keepingCapacity: true)
}
private func queueCall(block:@escaping ()->Void){
queue.async {
block()
}
}
deinit{
session.removeObserver(self, forKeyPath: #keyPath(NWUDPSession.state))
}
}
We are trying to connect to Webdav.
The file server is in the same network.
So when we try to connect, the local network permission pop-up is displayed.
If the input information is incorrect in the first login attempt when this permission pop-up is displayed,
After that, even after fixing the normal connection, we cannot connect or log in with the message "NSURLErrorDomain Code=-1009", "Internet connection is offline."
This symptom seems to persist even after rebooting or deleting and deleting the app in the actual distributed app.
If you re-debug while debugging Xcode, you can connect normally.
(If you do not re-debug, it fails even if you enter the connection information normally.)
And it affects local connection, so you cannot connect to any local network server such as SMB or FTP.
Also, you cannot browse the server list within the local network. (SMB)
Is there a way to initialize the local network status within the app to improve this phenomenon?
I tried turning Airplane mode ON/OFF, turning Wi-Fi ON/OFF, and turning local network permissions ON/OFF, but it did not work.
Also, this phenomenon seems to be a Sandbox for each app.
When connecting to the same local server from an app installed on the same iPhone/iPad device, the above phenomenon does not occur if the first connection is successful.
** Summary **
If you fail to connect to a server on your local network,
then you will continue to fail to connect to the local server.
This happens even when local network permissions are allowed.
The error message is NSURLErrorDomain Code=-1009
The current device is an iPhone device running iOS 18.1.1.
Could anyone tell me how to detect status of Local Network for iOS 18+ systems ?
My code makes an iPhone use the CBCentralManager to talk to devices peripherals over core bluetooth.
After attempting a connect to a peripheral device, I get a didConnect callback on CBCentralManagerDelegate.
After this I initiate discovery of services using:
peripheral.discoverServices([CBUUID(nsuuid: serviceUUID)])
Since I am only interested in discovering my service of interest and not the others to speed up time to the actual sending of data.
This also gives me the didDiscoverServices callback without error prints in which I do the following:
guard let services = peripheral.services, !services.isEmpty else {
print("Empty services")
centralManager.cancelPeripheralConnection(peripheral)
return
}
And for next steps
if let serviceOfInterest = services.first(where: {$0.uuid == CBUUID(nsuuid: serviceUUID)}) { //double check for service we want
initiateDiscoverCharacteristics(peripheral: peripheral, service: serviceOfInterest)
}
Below is what initiateDiscoverCharacteristics() does. I basically only tries to discover certain characteristics of the selected service:
peripheral.discoverCharacteristics(
[CBUUID(nsuuid: readUUID),
CBUUID(nsuuid: writeUUID)],
for: serviceOfInterest)
For this also we get the didDiscoverCharacteristicsFor callback without error prints.
Here in this callback however we were not doing the serviceOfInterest check to see that we are getting the callback for the service we expect, since our understanding was that we will get didDiscoverCharacteristicsFor callback for the characteristics on the serviceOfInterest because that is what peripheral.discoverCharacteristics() was initiated for.
When we go ahead to write some data/subscribe for notify/read data we have 2 guard statements for services and characteristics of a particular service.
The first guard below passes:
if(peripheral.services == nil) {
print("services yet to be discovered \(peripheral.identifier.uuidString)")
return
}
However the second guard below fails:
let serviceOfInterest = peripheral.services?.first(where: {$0.uuid == CBUUID(nsuuid: serviceUUID})
if((serviceOfInterest?.characteristics == nil) || (serviceOfInterest?.characteristics == [])) {
print("characteristics yet to be discovered \(peripheral.identifier.uuidString)")
return
}
First of all, does the iPhone go ahead and discover other characteristics and services separately even when we explicitly mention the service and the characteristics it should discover?
Now if you say yes and that it maybe the reason of our bug because we didn't do a check for serviceOfInterest in didDiscoverCharacteristicsFor callback, then I have another question.
Why don't we get a second/third print in didDiscoverCharacteristicsFor callback signifying that more characteristics were discovered?
The peripheral device just disconnects after a set timeout (peripheral device used in our testing does this if we are not communicating with it for a certain amount of time).
This issue is extremely rare. We have seen it only twice in our customer base. Both the instances were on the same iPhone 15 Pro. Once a few months back and once recently. Currently, this iPhone is having iOS version 18.1.1 running on it.
We're experiencing an issue with Local Network Permission. When trying to connect to a socket, the Local Network Permission alert pops up. To trigger the permission request at the start of the app, we used the following code to ask for permission and receive a callback on whether it's granted. However, this approach doesn't always trigger the permission alert, or it gets automatically dismissed after 30 seconds, only to reappear later. What could be causing this inconsistent behavior?
func checkLocalNetworkPermission(_ completed: Optional<(Bool) -> Void> = .none) {
DispatchQueue.global(qos: .userInitiated).async {
let hostName = ProcessInfo.processInfo.hostName
let isGranted = hostName.contains(".local")
if let completed {
DispatchQueue.main.async {
completed(isGranted)
}
}
}
}
I'm currently working on an iOS app where I need to trigger an API call as soon as applicationWillResignActive is called. The method is designed to save user data and sync certain settings before the app transitions to the background. However, I'm experiencing issues where the API call is not consistently being triggered within this method.
Does applicationWillResignActive not fully warrant an api call?
Topic:
App & System Services
SubTopic:
Networking
I created a self signed CA and use it to generate/sign a client cert using openssl. Then I use the self signed client cert to do TLS client authentication with my server (which also uses the self signed CA). The issue I have is when I validate the self signed CA, by calling SecTrustEvaluateAsyncWithError, it always complains this error “'DigiCert Global Root G3' certificate is not trusted". However that CA (DigiCert Global Root G3) is not my self signed CA (my CA is 'MQTTSampleCA' and I attached a dump of the my CA cert in the PR in the end of this post), so I'm confused why the API keeps complaining that CA. After some researching, I see that is a well known CA so I download its cert from https://www.digicert.com/kb/digicert-root-certificates.htm, install and trust it on my iOS device, but that doesn't help and I still get the same error. I provide all the repro steps in this PR: https://github.com/liumiaojq/EmCuTeeTee/pull/1, including how I generate the certs and the source codes of a test app that I used to do cert validation. I appreciate if anyone can share insights how to resolve this error.