Networking

RSS for tag

Explore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.

Networking Documentation

Post

Replies

Boosts

Views

Activity

Network is not working when upload smb using NEFilterDataProvider in macOS
Network is not working when over 50MB size file upload smb using NEFilterDataProvider in macOS The event received through NEFilterDataProvider is returned immediately without doing any other work. override func handleNewFlow(_ flow: NEFilterFlow) -> NEFilterNewFlowVerdict { guard let socketFlow = flow as? NEFilterSocketFlow, let auditToken = socketFlow.sourceAppAuditToken, let remoteEndpoint = socketFlow.remoteEndpoint as? NWHostEndpoint, let localEndpoint = socketFlow.localEndpoint as? NWHostEndpoint else { return .allow() } return .filterDataVerdict(withFilterInbound: true, peekInboundBytes: Int.max, filterOutbound: true, peekOutboundBytes: Int.max) } override func handleInboundData(from flow: NEFilterFlow, readBytesStartOffset offset: Int, readBytes: Data) -> NEFilterDataVerdict { guard let socketFlow = flow as? NEFilterSocketFlow, let auditToken = socketFlow.sourceAppAuditToken, let remoteEndpoint = socketFlow.remoteEndpoint as? NWHostEndpoint, let localEndpoint = socketFlow.localEndpoint as? NWHostEndpoint else { return .allow() } return NEFilterDataVerdict(passBytes: readBytes.count, peekBytes: Int.max) } override func handleOutboundData(from flow: NEFilterFlow, readBytesStartOffset offset: Int, readBytes: Data) -> NEFilterDataVerdict { guard let socketFlow = flow as? NEFilterSocketFlow, let auditToken = socketFlow.sourceAppAuditToken, let remoteEndpoint = socketFlow.remoteEndpoint as? NWHostEndpoint, let localEndpoint = socketFlow.localEndpoint as? NWHostEndpoint else { return .allow() } return NEFilterDataVerdict(passBytes: readBytes.count, peekBytes: Int.max) } override func handleInboundDataComplete(for flow: NEFilterFlow) -> NEFilterDataVerdict { guard let socketFlow = flow as? NEFilterSocketFlow, let auditToken = socketFlow.sourceAppAuditToken, let remoteEndpoint = socketFlow.remoteEndpoint as? NWHostEndpoint, let localEndpoint = socketFlow.localEndpoint as? NWHostEndpoint else { return .allow() } return .allow() } override func handleOutboundDataComplete(for flow: NEFilterFlow) -> NEFilterDataVerdict { guard let socketFlow = flow as? NEFilterSocketFlow, let auditToken = socketFlow.sourceAppAuditToken, let remoteEndpoint = socketFlow.remoteEndpoint as? NWHostEndpoint, let localEndpoint = socketFlow.localEndpoint as? NWHostEndpoint else { return .allow() } return .allow() } how can i fix it?
1
0
64
16h
Content filter providers seem to block all requests during startup on iOS 16 or 17
Hi, Consider a content filter app that allows most requests. While running, it handles requests and determine what to do. It does not affect any request while it is not running. However, during startup, it seems to block all requests, on iOS 16 or 17. On iOS 15, the behavior is bit different. Show the picture below: Questions Is this the expected behavior? Is this documented? Steps to reproduce Create content filter app with filter data provider with lengthy startup, something like the following: import NetworkExtension class FilterDataProvider: NEFilterDataProvider { override func startFilter(completionHandler: @escaping ((any Error)?) -> Void) { Task { try await Task.sleep(nanoseconds: 10 * 1_000_000_000) completionHandler(nil) } } override func stopFilter(with reason: NEProviderStopReason) async {} override func handleNewFlow(_ flow: NEFilterFlow) -> NEFilterNewFlowVerdict { guard let url: String = flow.url?.absoluteString else { return .allow() } if url.contains("example.net/") { return .drop() } if url.contains("example.org/") { exit(42) } return .allow() } } Install the app on a supervised iPhone or iPad. Install a WebContentFilter profile. Wait for the content filter to start. You can check the status in Settings > General > VPN & Device Management > Content Filter. Open Safari app. Request http://example.net/ and confirm that it is blocked. Request the other URLs and confirm that it is allowed. Request http://example.org. It kills the filter data provider. Request some URLs quickly. Background to the questions We offer a content filter app that might be stopped during the device sleeps. When a non-our-app’s push notification is received, the device wakes up, and the content filter starts up. Then the push notification seems to be lost. It is observed on iOS 16 and 17, not on iOS 15.
1
0
65
1d
filtering network data in multi thread
Hello, I need to implement filtering network data which is based on Network Extension (network content filter) Let's say I have rule which leads to monitoring several data flows in parallel. Are there any way to handle each data flow in separate thread? (number of threads is equal to number of analyzed flow) If one flow is paused by pauseVerdict, will the filter data provider recieve new data chunks in handleInboundDataFromFlow for other flows? Are there any possibility to change data flow on a fly? Thank you in advance.
3
0
88
1d
WiFi network setting won’t accept http proxy in iOS 18 beta 4
I am attempting to enter proxy settings under the settings for a WiFi network. I have triple checked the credentials and for whatever reason the settings wont save. I have attempted forgetting the wifi network and reconnecting, resetting all network settings, and even wiping the phone and starting over from scratch. The phone simply will not accept the setting. I have tried it on my MacStudio and an iPad and the settings saved the first time. What am I missing here? I am union iOS 18 beta 4
1
0
101
1d
Support for P2P Connectivity and Network Requests in the Background
We are currently developing an application that runs in the background and continuously scans for other nearby devices via peer-to-peer networking. Generally, the high-level goals are: Scan for nearby devices while the app is in the background state. We only need to discover devices that are also running our app. Read a small token of data from each peer device found (no need for full-duplex connection) Submit this token to our server via a background network request On Android we have demonstrated this functionality using both Bluetooth LE and WifiDirect service discovery, and background operation is easily achieved with Android services. We are currently trying to expand our application to support cross-platform compatibility between IOS and Android, including IOS<-->IOS and IOS<-->Android discovery (in the background). Is there a way to achieve this desired functionality on IOS?
2
0
89
1d
local iOS Zeroconf Device vs. iOS simulator Zeroconf Visual Studio
Hello, I am not exactly sure this is the right place to ask this since it involves Microsoft's Visual Studio, but because the problem I am having involves iOS I figured I would anyway. Info: I am trying to develop a cross-platform application using .NET Maui in Visual Studio. I am on a Windows machine pairing to a mac with Xcode installed, so I can build for iOS. My local device is an iPhone 13 running on iOS Version 17.5.1. The simulators I am using in Visual Studio are all iOS Version 17+. I am using the .NET NuGet package Zeroconf which should work for both iOS and Android (Repo:https://github.com/novotnyllc/Zeroconf). I also believe I have given the correct permissions for iOS in my Info.plist. Problem: The problem I am coming across is that when I build and run my application in one of the installed iOS Simulators and I go to scan for local devices it is able to come back with 80-100 devices that we want to find, but when I build and run it on my local device it comes back with nothing found. I had searched for similar problems that other people were having and found that iOS 17+ has some potential problems when it comes to searching for devices. Is this true? If someone can help me solve this issue between the simulator and local device I would greatly appreciate it. If there is any other information that I can give to help with solving this problem please let me know. Thanks! Discovery Code: TimeSpan scanTime = TimeSpan.FromMilliseconds(2000); int retries = 4; int retryDelayMilliseconds = 2000; Action<IZeroconfHost> callback = null; CancellationToken cancellationToken = default; System.Net.NetworkInformation.NetworkInterface[] arrayofnics = NetworkInterface.GetAllNetworkInterfaces(); int index = 0; for (int i = 0; i < arrayofnics.Length; i++) { // en0 is for iOS 0 is for android. if (arrayofnics[i].Description.Equals("en0") || arrayofnics[i].Description.Equals("0")) { index = i; break; } } System.Net.NetworkInformation.NetworkInterface wifi = arrayofnics[index]; System.Net.NetworkInformation.NetworkInterface[] netInterfacesToSendRequestOn = { wifi }; IReadOnlyList<IZeroconfHost> results = null; IReadOnlyList<string> domains; var browseDomains = await ZeroconfResolver.BrowseDomainsAsync(); domains = browseDomains.Select(g => g.Key).ToList(); results = await ZeroconfResolver.ResolveAsync("_http._tcp.local.", scanTime, retries, retryDelayMilliseconds, callback, cancellationToken, netInterfacesToSendRequestOn); Info.plist: <key>NSLocalNetworkUsageDescription</key> <string>This app requires local network access to discover devices.</string> <key>NSBonjourServices</key> <array> <string>_ipspeaker._tcp.local</string> <string>_ipspeaker._tcp.local.</string> <string>_ipspeaker._tcp.</string> <string>_http._tcp.local.</string> <string>_http._tcp.</string> </array>
3
0
124
2d
Sample projects of NEFilterProvider use IPC but the documentation says that it blocks IPC
The sample project Filtering Network Traffic uses IPC (NSXPCConnection etc.) to send data from the network extension to the app, but the documentation for NEFilterProvider says The sandbox prevents the Filter Data Provider extension from moving network content outside of its address space by blocking all network access, IPC, and disk write operations. Since my network extension forwards all network traffic to the app so that the user can see it, I was wondering when the app isn’t running and the user shuts down the machine, if the network extension could write the flows it wasn’t able to forward to the app to disk, so that it could read them on the next successful connection to the app. Then almost by accident I read again the documentation and according to the quoted passage a network extension cannot write to disk, but it also cannot use IPC. Is NSXPCConnection not considered IPC, or could the statement that it cannot write to disk be false as well?
3
0
77
2d
Content Filter remoteEndpoint from Chrome
I've developed a network content filter extension for macOS. When overriding the handleNewFlow method, I want to examine the hostname for the given flow. I can do this for browsers like Safari, Firefox, and DuckDuckGo using flow.url?.host (WebKit flows) or (flow as? NEFilterSocketFlow)?.remoteHostname (Firefox flows). However, for Google Chrome, these properties return nil, and I only get an outgoing IP address using socketFlow.remoteEndpoint as? NWHostEndpoint. How can I retrieve the outgoing domain for flows from Google Chrome? I've tried resolving the IP to a domain name, but in most cases, I'm unable to retrieve the domain name using the following functions I found on forum posts: func reverseDNS(ip: String) -> String { var results: UnsafeMutablePointer<addrinfo>? = nil defer { if let results = results { freeaddrinfo(results) } } let error = getaddrinfo(ip, nil, nil, &results) if (error != 0) { NSLog("Unable to reverse ip: \(ip)") return ip } for addrinfo in sequence(first: results, next: { $0?.pointee.ai_next }) { guard let pointee = addrinfo?.pointee else { NSLog("Unable to reverse ip: \(ip)") return ip } let hname = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST)) defer { hname.deallocate() } let error = getnameinfo(pointee.ai_addr, pointee.ai_addrlen, hname, socklen_t(NI_MAXHOST), nil, 0, 0) if (error != 0) { continue } return String(cString: hname) } return ip } func resolveIP(_ ipAddress: String) -> String? { var hints = addrinfo( ai_flags: AI_NUMERICHOST, ai_family: AF_UNSPEC, ai_socktype: SOCK_STREAM, ai_protocol: 0, ai_addrlen: 0, ai_canonname: nil, ai_addr: nil, ai_next: nil ) var res: UnsafeMutablePointer<addrinfo>? = nil let status = getaddrinfo(ipAddress, nil, &hints, &res) guard status == 0, let result = res else { print("Error: \(String(cString: gai_strerror(status)))") return nil } var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if let addr = result.pointee.ai_addr { let addrLen = socklen_t(result.pointee.ai_addrlen) if getnameinfo(addr, addrLen, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, 0) == 0 { freeaddrinfo(res) return String(cString: hostBuffer) } } freeaddrinfo(res) return nil } I know that Little Snitch can block and display domain name requests using a content filter, even in Google Chrome, so I'm certain it's possible. However, I'm unsure how to accomplish this. Can anyone assist me in resolving IP addresses to hostnames for most IP addresses, or in obtaining the hostnames directly from the flow on macOS?
1
0
78
3d
NETransparentProxyProvider excludedRules limit?
I have this in my start code: for p in [4500] + Array(3478...3497) + Array(16384...16387) + Array(16393...16402) { // According to the documentation, I *should* be able to // use "" for the hostname, and prefix:0, but it complained // about the prefix length, so we use the top bit for ipv4 // and ipv6. let port = "\(p)" os_log(.debug, log: Self.log, "Setting up to exclude port %{public}s", port) let host_1 = NWHostEndpoint(hostname:"0.0.0.0", port: port) let host_2 = NWHostEndpoint(hostname:"255.0.0.0", port: port) let host_3 = NWHostEndpoint(hostname:"0::0", port: port) let host_4 = NWHostEndpoint(hostname:"ffff::0", port: port) for host in [host_1, host_3] { let udpPortRule = NENetworkRule(destinationNetwork: host, prefix:1, protocol: .UDP) excludeRules.append(udpPortRule) } } settings.excludedNetworkRules = excludeRules This produces the log message 2024-07-23 11:16:38.335649+0100 0x901984 Debug 0x0 20686 0 com.kithrup.SimpleTPP.Provider: [com.kithrup:Provider] Setting up to exclude port 3483 Later on, when running, I log the new flows in handleNewUDPFlow(:,initialRemoteEndpoint:), and it produces 2024-07-23 11:17:05.712055+0100 0x901984 Debug 0x0 20686 0 com.kithrup.SimpleTPP.Provider: [com.kithrup:Provider] handleNewUDPFlow(_:initialRemoteEndpoint:): new UDP flow for host 17.252.13.7:3483 app com.apple.identityservicesd So port 3483 is definitely in the excludedRules array, but it's not being excluded. (All of this is because I still can't figure out why FaceTime isn't working with us.)
5
0
86
3d
Checking SIM Status on iPhone
I am developing an iOS application. In that i should show a status of their cellular provider such as Active, Inactive, or sim not available. Which also includes physical and eSim. I used Telephony.CTcarrier. One thing its deprecated and another case iOS 15 and below, even if i put my device in Airplane mode still its returning the carrierName and NetworkCode. Is there any specific API to retrieve these realtime data? TIA
4
0
126
3d
QUIC Network framework interoperability
We would like to understand/double check if it is possible to use QUIC in Swift via Network framework as the client along with some other QUIC solution on the server (ex. s2n-quic, quiche, msquic, etc..) which won't be a macOS server. If that interoperability is indeed possible, the NWConnectionGroup won't be an approach we could use IMO, since probably we will need to develop that from scratch on both sides. Thanks in advance.
3
0
144
3d
Where are 'socketfilterfw' changes being stored in macOS 15?
With the recent change to socketfilterfw in macOS 15 we can no longer check if the application firewall is enabled or not via a plist. This is significant in our app because we rely on the NSFilePresenter interface to monitor the plist to alert our app whenever a user changes their firewall settings. Removing the plist is a breaking change for us. Can you please advise either some new location on disk for us to monitor, or if there is another way to observe this setting? We would ideally rather not have to poll 'socketfilterfw' on an interval. Thanks!
2
0
127
4d
L4 Per-App VPN is not working with iOS 18 Beta
We are not seeing any traffic from iOS to App-Proxy extension. We have a Safari domains specified in the per App App Proxy VPN configuration which is pushed to our device. When we tap on the safari and start loading one of these domains, safari will not load any websites with these domains. But if we load any other websites with any other domain, the websites are loaded properly. But the same behavior works fine and app receives traffic on iOS 17.5.1 and older iOS versions. The issue is observed only on iOS 18 Beta versions.
4
0
169
4d
No TCP connections to IPs in the local network
I am developing an app which heavily relies on TCP device to device connections in the local network. The devices (multiple iPhones 13) are connected through a common consumer wifi router and act as server and client simultaneously. My problem is that 2 out of 3 iPhones can't establish outgoing TCP connections. However, they can act as server and accept incoming connections. All devices have the same iOS version (17.5.1) and access to Local Network is granted in the Privacy & Security settings. All devices have IPs in the range 192.168.x.x and the correct subnet is set. Safari can connect to IPs in the local network but not my app. The wifi network does not provide access to internet. Mobile data is turned off on all devices. As the error is happening out in the field, I cannot reproduce it under controlled conditions. What settings (beside not granting access to Local Network) may block outgoing connections to local IPs? What configurations of the app (e.g. entries in Info.plist) may result in or fix this behaviour?
2
0
128
4d
SwiftUI URLRequest Warning: "Connection has no local endpoint"
I have a simple SwiftUI application that sends a URLRequest as shown in the code snippet below: import SwiftUI @main struct GOGODemoApp: App { var body: some Scene { WindowGroup { MyView() } } } struct MyView: View { var body: some View { Button("Click") { sendHTTPRequest(to: "https://www.google.com") { code, err in print("Finished, code: \(code ?? -1), err: \(String(describing: err))") } } } } func sendHTTPRequest(to urlString: String, completion: @escaping (Int?, Error?) -&gt; Void) { guard let url = URL(string: urlString) else { completion(nil, NSError(domain: "InvalidURL", code: 0, userInfo: nil)) return } let task = URLSession.shared.dataTask(with: url) { _, resp, error in if let httpResponse = resp as? HTTPURLResponse { completion(httpResponse.statusCode, error) } else { completion(-1, error) } } task.resume() } However, Xcode prints the following warning messages: nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint Finished, code: 200, err: nil What does the warning 'Connection has no local endpoint' mean? Thank you for your assistance!
1
0
115
6d
Local Network Access Permission
We provide software that our customers deploy on their employee work computers to secure sensitive data. We have a daemon which could connect to an on-premise web-server for certain functionality. In Mac OS 15 beta we see that there is a local network access permission dialog that comes up sometimes, and it requires a permission to be provided under the Privacy &amp; Security section of the system preferences. We have seen the local network access permission would pop up only when both Server and Client are residing in the same private network range (eg 172.16.x.x. in our case.) When the same server is accessed from a Sequoia machine over a VPN from external network, the local network access permission does NOT pop up. But note in this case, the Sequoia machine has an IP in the 10.x.y.z range, whereas the server is at 172.16.x.y. We have the following questions: In our setup with Macs connecting to a web-server, what conditions can trigger the local network prompt? In particular, do both the client and server need to be in the same private subnet range for the prompt to be shown? Is it possible that a user at home, working on a Sequoia machine, connecting over VPN to an on-prem server, would trigger this prompt? If so, we would submit this is not expected, as a VPN is not really a local network. Is there an MDM way of automatically providing the permission, so that the prompt is suppressed? In general, is there a programmatic way of providing this permission during installation ? if yes how can we do it. How do we stop users from disabling the permission incase the user has admin rights?
6
7
165
1w
NEIKEv2Provider connection disconnects and includeAllNetworks
Hi all, I'm working on deploying a VPN for users of our enterprise app, using the built-in IKEv2 provider (configured either by a configuration profile or an app). I'm struggling to get the user experience right and was curious to hear if the behaviors I'm observing have been seen by other developers. The main behavior I am observing is that the client tends to randomly disconnect, and it does not attempt to reconnect. This is particularly problematic when paired with the includeAllNetworks option. Paired with includeAllNetworks: The device does not attempt to reconnect the tunnel Once the tunnel disconnects, onDemandRules don't seem to evaluate. Even if a NEOnDemandRuleConnect rule matches the current network, the connection does not reestablish. All network traffic remains blocked on both WiFi and Cellular (rendering any network-dependent app unusable) until the user intervenes and toggles the connection in the Settings app This seems like a problematic user experience and I would be surprised if this is by design. As for the disconnects themselves, I have had a hard time correlating them to any particular network condition or protocol behavior. I've seen a connection drop after as little as 10 minutes and stay up for over 16 hours (including while the device roamed from WiFi to Cellular networks and in and out of connectivity). We confirmed with server logs that the clients were able to successfully re-key both the IKE SA and CHILD SAs. I had difficulty retrieving system logs from iOS, but on macOS I was able to observe this error from NEIKEv2Provider that lined up with one of the disconnect events: "Internal: Initiate MOBIKE failed to migrate child SAs" (server logs showed a successful rekey exchange at the same time). Thanks, Lucas
2
0
76
1w
Fragment large size data sent and received using NSKeyedArchiver.archivedData in GameCenter
Trying to send and receive data in the GameCenter environment using the following methods: func sendData(dictionaryWithData dictionary: Dictionary&lt;String, Any&gt;,toPeer targetPeers: [GKPlayer]) { guard let match = self.match else { return } do { let dataToSend = try NSKeyedArchiver.archivedData(withRootObject: dictionary, requiringSecureCoding: false) try match.send(dataToSend, to: targetPeers, dataMode: .reliable) } catch { #if DEBUG print("CONNECTION MANAGER SEND DATA ERROR") #endif } } public func match(_ theMatch: GKMatch,didReceive data: Data,forRecipient recipient: GKPlayer,fromRemotePlayer player: GKPlayer) { if match != theMatch { return } DispatchQueue.main.async { do { guard let message = NSDictionary.unsecureUnarchived(from: data) as? Dictionary&lt;String, Any&gt; else {return} ... &lt;CODE&gt; ... } ///Source: https://stackoverflow.com/questions/51487622/unarchive-array-with-nskeyedunarchiver-unarchivedobjectofclassfrom static func unsecureUnarchived(from data: Data) -&gt; Self? { do { let unarchiver = try NSKeyedUnarchiver(forReadingFrom: data) unarchiver.requiresSecureCoding = false let obj = unarchiver.decodeObject(of: self, forKey: NSKeyedArchiveRootObjectKey) if let error = unarchiver.error { print("Error:\(error)") } return obj } catch { print("Error:\(error)") } return nil } Everything works great until the data exceeds 87K (which, I understand, is the limit for exchanging data in GameCenter). The data is not sent and gives the following error: Async message[1FCA0D11-05DE-47D0-9714-983C8023F5C1] send error: FailedToSendData: , InternalError: reliable, maxPayloadSizeExceeded Interesting enough, I do not have this problem when using MCSession, as follows, even if data exceeds 87K: func sendData(dictionaryWithData dictionary: Dictionary&lt;String, Any&gt;, toPeer targetPeers: [MCPeerID]) { do { let dataToSend = try NSKeyedArchiver.archivedData(withRootObject: dictionary, requiringSecureCoding: false) try session.send(dataToSend, toPeers: targetPeers, with: MCSessionSendDataMode.reliable) } catch { #if DEBUG print("CONNECTION MANAGER SEND DATA ERROR") #endif } } I have been doing research and found that I need to fragment data and send and receive it in packages. But I could not find a good explanation how to do it. Any help would be appreciated!
5
0
136
1w
How to deal with the traffic from NEPacketTunnelProvider?
My requirement is to create a App and all the traffic from this App will be forwarded to relay servers(only implement socks5 protocol), the relay server then forward the traffic to the destination server. I have tried the two plans below: A. I tried the NEAppProxyProvider but it seemed to work only under MDM, MDM looks like very complex , so I gave it up. Actually this way is more appropraite for me. B. the other way is NEPacketTunnelProvider. I have figured out a common solution, steps: config the routes for NEPacketTunnelProvider get the fd from packetFlow start a tun2socks service to forward the traffic from the fd。 Sadly the way gettting the traffic from the fd is not recommened by apple official. so the only way to deal with the traffic is handling the packets. may be steps: parse the packet modify the packet write the packet back ... it seems even more complex than plan A,Besides, we have multiple relay servers, if there is a whole request we can make sure all this request data is forwarded by a same relay server, But if there is a packet, may be god can tell which relay server it should go to. We have implemented the same functionality in Android devices. can you help me to find out which way is better in iOS devices? I will be appreciated if you can provide more advice. Thanks.
1
0
152
1w