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

BLE connexion: popup display rules
Hello, I'm new to CoreBluetooth framework and I want to understand the rules behind Bluetooth connexion popups displayed by iOS. I understood that while developing a BLE Central role application, I have no control over whitch security popup bill be displayed. During my tests with Apple BLE demo project CoreBluetoothLESample, I managed to activate the display of a pairing popup adding .indicateEncryptionRequired option to the characteristic options in the PeripheralViewController class: let transferCharacteristic = CBMutableCharacteristic( type: TransferService.characteristicUUID, properties: [.notify, .writeWithoutResponse, .indicateEncryptionRequired], value: nil, permissions: [.readable, .writeable] ) My question is: Can I find a documentation about pairing popups display rules on central iOS device (just a "Cancel/Pair" popup without PIN check, popup with PIN check, popup asking to enter a PIN, or no popup at all) regarding peripheral security level and/or capabilities (can display a PIN or not) ? Thank you for any help !
0
0
343
Aug ’23
IOS and Private AP Networks with out Internet
We are manufacturers of home security and automation products. Over the last few years, we have become more dependent on app development and mobile devices. We are experiencing an issue that I am hoping to get some guidance on. As part of a new product we are creating, we need to utilize a private Access Point (AP) network generated by our device to configure it to connect to a Wi-Fi network. This network is a straightforward 2.4GHz Wi-Fi network generated from our product's Wi-Fi module. It is IPv4 and utilizes DHCP for a limited number of leases. This network is only temporary and is used solely for configuring the device, similar to the setup of a Wi-Fi repeater. However, we do not have a built-in Web Server; we utilize an app to make the configurations. The issue we are encountering is that iOS seems to take 60 seconds or more to allow local traffic on the AP network once we connect. It establishes the connection quickly and indicates no internet access, which is correct. Then, observing the mobile device, you can see that the "Wi-Fi Icon" does not appear in the status bar at the top of the phone for a prolonged period. During this time, iOS doesn't permit us to discover our device. We broadcast a discovery message on the private AP to prompt our device to respond, allowing us to establish a connection and initiate the configuration. If we attempt discovery during this "verification" period, our app doesn't get a response from the device, leading to confusion for our customers as they are connected to the device that is not responding. My question is: Is there a document or guideline available that we can follow to enhance the functionality of our network with iOS? Is there a way to inform iOS that we are a private AP without internet access? It appears that the time we are waiting corresponds to iOS exhausting its measures to confirm internet connectivity. This seems to isolated to iOS, we are not seeing this with other mobile devices. Any advice or guidance would be greatly appreciated. Thank you, Mike
2
0
336
Aug ’23
Filter content without MDM profile?
Hello! I'm new to iOS development and am developing an app that blocks certain websites. At the moment, I'm thinking of using the Network Extension capability to do the job. From what I have read, in the production version of the app, you'd need to make use of MDM profiles since NE filtering only works on supervised devices. So, I'm here to ask the community if there are better options than using this method. As far as screen time api is concerned, I believe it requires the user to specify which websites they want blocked by themselves using the activity picker so that doesn't quite work for me since i want to allow the app to block groups of websites by itself based on the user's preference. Thanks!
4
1
897
Aug ’23
Captive Network Assistant (CNA) only loading content if cellular data in service
Strange one... We have a WiFi guest portal setup and the CNA pops up as expected upon connecting to the network. It loads the splash page inside the CNA and all is good so far. All domains/URLs that we use within the CNA are allowed/whitelisted before authentication. However, after clicking the Continue button (which performs a POST via the javascript native fetch) and then performs a window.location to the returned URL in the fetch response, it is only redirecting to this new page is there is an active, in service SIM card present. If I turn cellular data off, or remove the SIM, it doesn't redirect to the next page. P.S. If I choose "Cancel" and then "Use Without Internet" and open Safari, visit neverssl.com (which will force a redirect to the splash page) and use the exact same Continue button as above, it works as expected without any requirement for a data connection. What can be making this only work if there is a cellular data connection when the whole point of the CNA is to load all content over the WiFi connection? Also, is there any way to debug or attach a console to the CNA window so that I can actually debug it to see what is happening like you can with Safari windows? Thanks
0
1
367
Aug ’23
Xcode Error : Building a custom peer-to-peer protocol
Unable to launch this sample project. Xcode says it cannot open the file. Building a custom peer-to-peer protocol I'm trying to build iPhone as a mouse. I am not planning on releasing it but more like a practice for myself. I have one other question, how to use a mac app to receive mouse data while it's in background as it's required by my app. Is Background Tasks the right way ? I am planning to use Network framework for networking but there is not much documentation available. Pardon me if it's a basic question.
1
0
821
Aug ’23
Meaning of values Cert
Hi: I'm wondering about what means values s,i from cert object inside the property NSErrorPeerCertificateChainKey and NSErrorPeerCertificateChainKey in an SSLError: NSErrorPeerCertificateChainKey=( "<cert(0x1029c9e00) s: site.com i: Company Services>" I suppose that "i" is the certificate's issuer and "s" is the site, but something is strange here. I make a request to example.com and sometimes example.com does not appear on the certificate chain ... appearing Other sites and issuers not related to the certificate that example.com could have. I think that it is the cause of the error, but if you could explain to me which could be the cause of this strange situation would be nice. Thanks in advance
1
0
584
Aug ’23
How to correctly use the developer ID to implement program distribution
Currently, I have implemented a project that includes network extension and system extension entitlements. When I create the profile using the development method, I get exactly the right entitlement matching. For example: create app id (identifier) create a profile, associate with the corresponding app id, generate the profile and download it locally. In xcode, fill in the corresponding app id in Bundle Identifier, such as com.***.test.app, and fill in the corresponding development profile in Provisioning Profile. At this point I was able to achieve a complete and correct program compiling and running. Now, I want to distribute this app by developer id. According to https://developer.apple.com/developer-id/ , I have several questions remain: I followed this method https://developer.apple.com/help/account/create-certificates/create-developer-id-certificates/ to create a distribution certificate and created two new profiles (distribute- developer id), which is associated with the existing bundle ID (com.***.test.app, com.***.test.extension). But when I import the corresponding provisioning profile in xcode, it shows error: Provisioning profile "***" doesn’t match the entitlement file’s value for the com.apple.developer.networking.networkextension entitlement. But isn't the corresponding entitlement information already selected when the app id is set? Why is the profile of the development type feasible, but the profile of the developer id is not feasible? I have made relevant settings according to this method https://developer.apple.com/documentation/xcode/preparing-your-app-for-distribution/, and I don’t seem to need the hardened runtime and sandbox related content, so I don't have any settings. Maybe apple events in hardened runtime is necessary? Submitting software to apple notarization seems to be a more trustworthy behavior for users, but at this stage I just want to simply implement distribution for program testing, so I chose export in archives-distribute app-developer id, and in the follow-up The same error as in question 1 appeared in the profile selection of the profile: Profile doesn't match the entitlements file's value for the com.apple.developer.networking.networkextension entitlement. So, overall: One is how to create the correct developer id profile? My two entitlements files are as follows: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;com.apple.developer.networking.networkextension&lt;/key&gt; &lt;array&gt; &lt;string&gt;content-filter-provider&lt;/string&gt; &lt;/array&gt; &lt;key&gt;com.apple.developer.system-extension.install&lt;/key&gt; &lt;true/&gt; &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt; &lt;false/&gt; &lt;key&gt;com.apple.security.files.user-selected.read-only&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/plist&gt; &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;com.apple.developer.networking.networkextension&lt;/key&gt; &lt;array&gt; &lt;string&gt;content-filter-provider&lt;/string&gt; &lt;/array&gt; &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt; &lt;false/&gt; &lt;key&gt;com.apple.security.application-groups&lt;/key&gt; &lt;array&gt; &lt;string&gt;$(TeamIdentifierPrefix)com.example.app-group&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt; Second, is Apple notarization necessary?
4
0
955
Aug ’23
Asynchronous socket select returns abnormal values due to network filter.
We have developed a network filter based on the Network extension framework in macOS. However, we have found that after blocking a network, the poll socket value still returns as 1, which causes some applications to run abnormally. We return dropVerdict in the callback handleNewFlow We simulated the process of an application initiating a network request. Create an asynchronous socket. sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); exit(EXIT_FAILURE); } int flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); connect server // Connect to the server ret = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (ret < 0) { NSLog(@"connect, errno:%d, err str:%s.", errno, strerror(errno)); } we found the connect return -1, errno return EINPROGRESS, means operation now in progress. poll socket int timeout = 5000; // 5 seconds struct pollfd fds[MAX_EVENTS]; fds[0].fd = sockfd; fds[0].events = POLLIN; ret = poll(fds, 1, timeout) return 1, means the number of descriptors that are ready for I/O. We believe it is unreasonable for poll to return 1 after network disruption, which leads to abnormal application processing.
1
0
282
Aug ’23
Local Network Privacy FAQ-16
This post is part of the Local Network Privacy FAQ. On a small fraction of devices my app fails to present the local network privacy alert. What’s going on? I most commonly see this in apps with code that specifically targets the Wi-Fi interface. If that code fails, the app might end up targeting the wrong interface. If that interface is not subject to local network privacy, the system never presents the local network privacy alert. IMPORTANT A common cause of this failure is the assumption that en0 is the iPhone’s Wi-Fi interface. While that’s true on most devices, this is not a valid assumption. BSD interface names are not considered API on Apple platforms. Code that makes that assumption will fail in hard-to-reproduce circumstances. If you encounter a problem like this, check whether your code has a hard-coded en0. If it does, see Extra-ordinary Networking for ideas about how to fix it. Back to the FAQ
0
0
420
Aug ’23
Implementing NWProtocolFramerImplementation in ObjC / C
Hi Everyone, Seeing that most of the resources out there are 'primarily' geared towards supporting swift, some of us such as myself still fancy Objective-C. I am currently working on a network project and I'm considering writing my own framer to just get a feel for how it works but I'm seriously running into issues with how to do this. for example: how would I begin doing this in C final class FrProtocol:NWProtocolFramerImplementation{ } which requires creating a definition passing in the class itself NWProtocolFramer.Definition(implementation: FRProtocol.self) I had a look at framer_options.h and although I see some of the functions that need to be implemented when conforming to the above said protocol. It's confusing to say the least how to begin. It would be nice to have samples that are written for Objective-C. Any help would be most appreciated.
2
0
386
Aug ’23
How to decide addresses for NEIPv4Settings, NEIPv6Settings of NEPacketTunnelNetworkSettings
Hi, This is how we create ipv4Settings, then we add includedRoutes, excludedRoutes. let ipv4Settings = NEIPv4Settings(addresses: addresses, subnetMasks: subnetMask) In my case, Packet Tunnel Provider reads the packet like this - packetFlow.readPacketObjects, sends packets to C++ module which takes care of sending it to wireguard tunnel, returns packet back to Packet Tunnel Provider for writing. C++ Module does everything related to wireguard tunnel. As per my understanding, any unique private ipv4, ipv6 address should be fine for creating NEIPv4Settings, NEIPv6Settings. is that correct? or is there anything else i need to consider for setting Utun addresses as of now i have harcoded it to 10.10.10.10/32 and 2001:db8::/128, will it cause any problem?
5
0
732
Aug ’23
How to track down cause of SSL Errors - NSURLErrorDomain Code=-1200
I've noticed that our apps get these errors with some regular occurrence: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made. I suspect the issue may be because of misconfigured VPNs. But is there any way to get more details about the cause of these SSL failures? If it's an issue with certificate validation or something, it would be great to get the certificate seen at the time of the error as sometimes a simple retry ends up working. I'm not doing anything particularly special network-wise... using standard URLSession with the default configuration. I have tried implementing URLSessionDelegate.urlSession(:didBecomeInvalidWithError:) and URLSessionDelegate.urlSession(:didReceive:completionHandler:) to see if I could get more details, but nothing.
3
0
905
Aug ’23
ExcludeLocalNetworks
Hello, Regarding this explanation If this property is YES, the system excludes network connections to hosts on the local network — such as AirPlay, AirDrop, and CarPlay — but only when the includeAllNetworks or enforceRoutes property is also YES. So my question is the local network here only meaning AirPlay, AirDrop, and CarPlay? Is the pings to local LAN IP still working? What is the exactly the local network definition here? Is it based on the interface or the IPs? For example, somehow we connects to a wifi which assigned a public IP. After VPN is connected with tunnel all mode, we set includeAllNetworks and excludeLocalNetworks flag, will the traffic originally goes through wlan interface goes through utun interface? Or it will keep going through wlan interface?
0
0
304
Sep ’23
Intercepting DNS query in PacketTunnelProvider for blocking domains
Hi, I have developed a VPN application with PacketTunnelProvider that connects to the OpenVPN server. It works perfectly fine. Now I have the following requirements. The user should be able to block a particular domain, such as "example.com" while staying connected to the VPN server. For the above requirement, I need to capture the DNS request for facebook.com and see if it is in the block list provided by the user and block the DNS request. I don't have to have multiple network extensions, I need to handle it from one Packettunnel provider that is already handling OpenVPN connection. Can anyone help me here with this use case?
3
0
499
Sep ’23
UDP listener only receives one packet and show Errors
I have an issue where my iPhone app needs to listen for a UDP packet and print that data to the screen. UDP packets are sent by a PC connecting to a Wifi router and my Iphone is also connecting to it and listening on the correct port. When running the App, it works at the first moment and receives the first UDP packet co, but after receiving the first packet, it stops receiving more and I see errors in the logs. These errors only appear when I test directly on the Iphone receiving packets through the router's wifi network with ip: 192.168.0.1. When I run through the simulator using localhost (127.0.0.1 ) the errors do not appear and I receive all packages correctly. Code for UDP listener: class UDPConecct: ObservableObject { var listener: NWListener? var connection: NWConnection? var queue = DispatchQueue.global(qos: .userInitiated) /// New data will be place in this variable to be received by observers @Published private(set) public var messageReceived: Data? /// When there is an active listening NWConnection this will be `true` @Published private(set) public var isReady: Bool = false /// Default value `true`, this will become false if the UDPListener ceases listening for any reason @Published public var listening: Bool = true var port: NWEndpoint.Port @Published var receivedWords: [Float64] = [] @Published var isCaptureStarted = false //@Published var udpPacket: UDP_Packet? /// A convenience init using Int instead of NWEndpoint.Port convenience init(on port: Int) { self.init(on: NWEndpoint.Port(integerLiteral: NWEndpoint.Port.IntegerLiteralType(port))) } /// Use this init or the one that takes an Int to start the listener init(on port: NWEndpoint.Port) { self.port = port let params = NWParameters.udp params.allowFastOpen = true self.listener = try? NWListener(using: params, on: port) self.listener?.stateUpdateHandler = { update in switch update { case .ready: self.isReady = true print("Listener connected to port \(port)") case .failed, .cancelled: // Announce we are no longer able to listen self.listening = false self.isReady = false print("Listener disconnected from port \(port)") default: print("Listener connecting to port \(port)...") } } self.listener?.newConnectionHandler = { connection in print("Listener receiving new message") self.createConnection(connection: connection) } self.listener?.start(queue: self.queue) } func createConnection(connection: NWConnection) { self.connection = connection self.connection?.stateUpdateHandler = { (newState) in switch (newState) { case .ready: print("Listener ready to receive message - \(connection)") self.receive() case .cancelled, .failed: print("Listener failed to receive message - \(connection)") // Cancel the listener, something went wrong self.listener?.cancel() // Announce we are no longer able to listen self.listening = false default: print("Listener waiting to receive message - \(connection)") } } self.connection?.start(queue: .global()) } func receive() { self.connection?.receiveMessage { data, context, isComplete, error in if let unwrappedError = error { print("Error: NWError received in \(#function) - \(unwrappedError)") return } guard isComplete, let data = data else { print("Error: Received nil Data with context - \(String(describing: context))") return } self.handleCapturedData(data) if self.listening { print("escutando") self.receive() } } } func handleCapturedData(_ data: Data) { print("quantidade de dados", data.count) var value: [Float64] = [] if data.count % 2 != 0 { let startOffset = 1 let length = (data.count-1)/2 let range = startOffset..&lt;startOffset+length // Fatiando o Data Recebido via UDP usando o intervalo let slicedData = data.subdata(in: range) print("dados cortados:", slicedData) for i in stride(from: 0, to: slicedData.count, by: 8) { let startIndex = i let endIndex = min(i + 8, slicedData.count) let subarray = Array(slicedData[startIndex..&lt;endIndex]) let floatValue = subarray.withUnsafeBytes { $0.load(as: Float64.self) } value.append(floatValue) } print("Dados Recebidos", value) self.receivedWords = value } else { let startIndex = 14 let endIndex = data.count - 2 let relevantData = Array(data[startIndex..&lt;endIndex]) // Iterar sobre os dados de 16 bits e convertê-los para Double for i in stride(from: 0, to: relevantData.count, by: 2) { let byte1 = relevantData[i] let byte2 = relevantData[i + 1] let wordValue = UInt16(byte1) &lt;&lt; 8 | UInt16(byte2) let doubleValue = Double(wordValue) value.append(doubleValue) } self.receivedWords = value print("Dados Recebidos 2", value) } } func cancel() { self.listening = false self.isCaptureStarted = false self.connection?.cancel() } }
6
0
646
Sep ’23
Get executable path from audit token provided by NEFilterDataProvider
I'm using this code to get the path of an executable from the audit token provided in NEFilterDataProvider.handleNewFlow(_:), forwarded from the Network Extension to the main app via IPC: private func securePathFromAuditToken(_ auditToken: Data) throws -> String? { let secFlags = SecCSFlags() var secCode: SecCode? var status = SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributeAudit: auditToken] as CFDictionary, secFlags, &secCode) guard let secCode = secCode else { throw SecError(status) } var secStaticCode: SecStaticCode? status = SecCodeCopyStaticCode(secCode, secFlags, &secStaticCode) guard let secStaticCode = secStaticCode else { throw SecError(status) } var url: CFURL? status = SecCodeCopyPath(secStaticCode, secFlags, &url) guard let url = url as URL? else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } return nil } But it seems that some processes like trustd, rapportd, nsurlsessiond and timed have a non-nil path. For these executables I have to resort to this code, which I have read is not as secure: private func insecurePathFromAuditToken(_ auditToken: Data) throws -> String? { if auditToken.count == MemoryLayout<audit_token_t>.size { let pid = auditToken.withUnsafeBytes { buffer in audit_token_to_pid(buffer.baseAddress!.assumingMemoryBound(to: audit_token_t.self).pointee) } let pathbuf = UnsafeMutablePointer<Int8>.allocate(capacity: Int(PROC_PIDPATHINFO_SIZE)) defer { pathbuf.deallocate() } let ret = proc_pidpath(pid, pathbuf, UInt32(PROC_PIDPATHINFO_SIZE)) if ret <= 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } return String(cString: pathbuf) } return nil } This seems to happen with both NEFilterFlow.sourceAppAuditToken and sourceProcessAuditToken. Is this expected? Can it really be that some executables shipped with macOS are not signed?
1
0
465
Sep ’23
Route not deleted after 'setTunnelNetworkSettings:nil'
We have a packettunnelprovider which we are using for intercepting IP packets. We define includeroutes while setting tunnel using 'setTunnelNetworkSettings'. But later when we want to disable packet interception, we want to do it from packettunnelprovider extension itself by reseting tunnel settings, for which we set 'NETunnelNetworkSettings' to nil in setTunnelNetworkSettings call. This deletes most of the routes added by includeroutes but few are always left out. % ifconfig utun3 utun3: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1300 options=6463<RXCSUM,TXCSUM,TSO4,TSO6,CHANNEL_IO,PARTIAL_CSUM,ZEROINVERT_CSUM> % netstat -rn -f inet | grep utun3 11.99/24 link#25 UCS utun3 269.254 link#25 UCS utun3 192.168.0 link#25 UCS utun3 Code which we use to reset packet tunnel: [g_PacketTunnelProvider setTunnelNetworkSettings:nil completionHandler:^(NSError * _Nullable errorNE) { if (errorNE != nil) { // handle error } else { // handle success } }]; Can you please help in what could be the reason behind it? Note: I am aware that VPN can be disabled from provider app, but I want to handle this in packettunnelprovider extension by resetting 'NETunnelNetworkSettings'.
5
0
678
Sep ’23
WPA3-Personal with the WAC POSIX Server
I am developing a WAC enabled Airplay device that cannot be added to WPA3-Personal networks using iOS or macOS. Neither macOS (AirPort Utility) nor iOS (Wi-Fi Settings) allow me to select the WPA3-Personal network despite being on this same WPA3-Personal network. My device supports WPA3-Personal. Using non-Apple on-boarding methods are successful with WPA3-Personal networks. Is there something I'm missing in my implementation of the WAC for supporting WPA3-Personal?
1
0
426
Sep ’23