Hi, I am working on the app for some basic concept, I would like to intercept both DNS and IP connections. I succeeded in intercepting DNS using NEDNSProxyProvider, however I seem to have some troubles with IPConnections using NEFilterDataProvider.
First thing, I have three targets in my app. For some reason, when I run DNS Proxy Extension target it doesn't ask me to choose the app for target run, and after the application if launched, it correctly intercepts DNS traffic and inits NEDNSProxyManager
ps: all logs are correctly displayed for NEFilterDataProvider
However, when I try to run Filter Data Extension target with Content Filter capability, it asks me to choose the app for run. Even tho I checked the Build Settings and those are identical to DNS Proxy Extension target.
And finally, when I run main target it still inits NEDNSProxyManager properly and the NEFilterManager returns this warning
-[NEFilterManager saveToPreferencesWithCompletionHandler:]_block_invoke_3: failed to save the new configuration: (null)
I tried to log the configuration and compared to some code samples, but I can't identify the problem.
I'd very grateful if somebody could suggest where the problems might be (targets builds difference & NEFilterManager config)
I will attach a sample of code where I add configuration to my NEFilterManager
// MARK: - FilterDataManager
final class FilterDataManager: NSObject, ObservableObject {
// MARK: - Properties
private let manager = NEFilterManager.shared()
private let filterName = "Data Filter"
@Published
private(set) var isEnabled: Bool? = nil
// MARK: - Singleton
static let shared = FilterDataManager()
// Cancellables set
private var subs: Set<AnyCancellable> = []
private override init() {
super.init()
enable()
manager.isEnabledPublisher()
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] isEnabled in
self?.setIsEnabled(isEnabled)
})
.store(in: &subs)
}
// MARK: - Filter Configurations
func enable() {
manager.updateConfiguration { [unowned self] manager in
manager.localizedDescription = filterName
manager.providerConfiguration = createFilterProviderConfiguration()
manager.isEnabled = true
} completion: { result in
guard case let .failure(error) = result else { return }
Log("Filter enable failed: \(error)", prefix: "[Filter]")
}
}
private func createFilterProviderConfiguration() -> NEFilterProviderConfiguration {
let configuration = NEFilterProviderConfiguration()
configuration.organization = "***"
configuration.filterBrowsers = true
configuration.filterSockets = true
return configuration
}
func disable() {
Log("Will disable filter", prefix: "[Filter]")
manager.updateConfiguration { manager in
manager.isEnabled = false
} completion: { result in
guard case let .failure(error) = result else { return }
Log("Filter enable failed: \(error)")
}
}
private func setIsEnabled(_ isEnabled: Bool) {
guard self.isEnabled != isEnabled else { return }
self.isEnabled = isEnabled
Log("Filter \(isEnabled ? "enabled" : "disabled")", prefix: "[Filter]")
}
}
```Swift
extension NEFilterManager {
// MARK: - NEFilterManager config update
func updateConfiguration(_ body: @escaping (NEFilterManager) -> Void, completion: @escaping (Result<Void, Error>) -> Void) {
loadFromPreferences { [unowned self] error in
if let error,
let filterError = FilterError(error) {
completion(.failure(filterError))
return
}
body(self)
saveToPreferences { (error) in
if let error,
let filterError = FilterError(error) {
completion(.failure(filterError))
return
}
completion(.success(()))
}
}
}
// MARK: - Publisher enabling
func isEnabledPublisher() -> AnyPublisher<Bool, Never> {
NotificationCenter.default
.publisher(for: NSNotification.Name.NEFilterConfigurationDidChange)
.compactMap { [weak self] notification in
guard let self else { return nil }
return self.isEnabled
}
.eraseToAnyPublisher()
}
}
// MARK: - FilterError
@available(iOS 8.0, *)
enum FilterError: Error {
/// The Filter configuration is invalid
case configurationInvalid
/// The Filter configuration is not enabled.
case configurationDisabled
/// The Filter configuration needs to be loaded.
case configurationStale
/// The Filter configuration cannot be removed.
case configurationCannotBeRemoved
/// Permission denied to modify the configuration
case configurationPermissionDenied
/// Internal error occurred while managing the configuration
case configurationInternalError
case unknown
init?(_ error: Error) {
switch error {
case let error as NSError:
switch NEFilterManagerError(rawValue: error.code) {
case .configurationInvalid:
self = .configurationInvalid
return
case .configurationDisabled:
self = .configurationDisabled
return
case .configurationStale:
self = .configurationStale
return
case .configurationCannotBeRemoved:
self = .configurationCannotBeRemoved
return
case .some(.configurationPermissionDenied):
self = .configurationPermissionDenied
return
case .some(.configurationInternalError):
self = .configurationInternalError
return
case .none:
return nil
@unknown default:
break
}
default:
break
}
assertionFailure("Invalid error \(error)")
return nil
}
}
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.
Post
Replies
Boosts
Views
Activity
I can't seem to find the answer anywhere online and through vendor support channels. Is it possible to trigger per-app VPN on unmanaged apps by leveraging the safari/browser domain whitelist on a user enrolment type device?
According to this document from Apple, it seems like it's possible. https://developer.apple.com/documentation/devicemanagement/applayervpn?changes=latest_minor
However it is missing the context as to which enrolment type is available on.
Folks,
I’m trying (for tests of third party hardware) to set up a very simple ‘UDP parrot’. It receives a packet, and returns it to the source with a '*' prefixed.
Can’t get it work. The following code works like a charm on FreeBSD, but won’t work on MacOS:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/errno.h>
#include <string.h>
int main(int argc, const char * argv[]) {
struct sockaddr_in myAddr;
struct sockaddr_in rmtAddr;
socklen_t rmtAddrLength;
char buffer [2048];
char src [256];
printf ("Opening socket…\n");
int sock;
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
printf("Cannot open UDP socket. Bailing!\n");
return -1;
}
int opt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
myAddr.sin_family = AF_INET;
myAddr.sin_addr.s_addr = INADDR_ANY;
myAddr.sin_port = htons(5522);
if (bind(sock, (struct sockaddr *) &myAddr, sizeof(myAddr))) {
printf ("Error binding socket -> %d\n", errno);
return -1;
}
printf ("Listening…\n");
while (1) {
ssize_t dataLength = recvfrom(sock, buffer + 1, sizeof(buffer) - 1,
0, (struct sockaddr *)& rmtAddr, & rmtAddrLength);
printf ("Received %zd bytes: %s\n", dataLength, buffer);
printf ("addrLength: %d\n", rmtAddrLength);
inet_ntop(AF_INET, & rmtAddr.sin_addr, src, sizeof(src));
printf("From %s port %d\n", src, ntohs (rmtAddr.sin_port));
if (! strncmp (buffer + 1, "STOP", 4)) {
sendto (sock, "Terminated\n", 11, 0,
(struct sockaddr *)& rmtAddr, sizeof(rmtAddr));
break;}
buffer [0] = '*';
dataLength = sendto(sock, buffer, dataLength + 1, 0,
(struct sockaddr *)& rmtAddr, sizeof(rmtAddr));
}
return 0;
}
The problem is, the rmtAddr structure, which is supposed to contain the IP address of the remote sender, well, does not. I always get 1.0.0.0 instead. As I said before, I have no such problem with the exact same code on FreeBSD. Also, rmtAddrLength, which is 8 on FreeBSD, is 16 on MacOS apparently.
I've dumped the memory starting at &rmtAddr and did not see a hint of a possible IP address.
Any idea what could be wrong?
Thanks !
V.
Why is it normal to use IJKPlayer to play rtsp real-time stream preview black screen when opening mobile traffic on some mobile phones, and cut into flight mode?
Whether mobile traffic affects local network access?
Hello!
I am part of a research team who need advice on how to track and intercept network requests from a device.
More specifically, we are interested in collecting the websites the research participants have tried to access. We want something like what YouGov does with their Pulse App.
Also, is it possible to implement this without having to rely on an external server that acts as a intermediary?
How do we achieve this? We'd appreciate a detailed response with helpful links to how to implement it. Thank you very much for your time.
hi,all
readBytes: An NSData object containing the data to filter. For non-UDP/TCP flows, since the data may optionally include the IP header, readBytes includes a 4-byte NEFilterDataAttribute field preceding the user data. Your handler must examine the NEFilterDataAttribute field and handle the data accordingly.
the param above in method handleInboundDataFromFlow:readBytesStartOffset:readBytes:
i assume it contains a 4-byte NEFilterDataAttribute field preceding the user data all the time,
is it normal that i get a NEFilterDataAttribute: 1099782776645(and some other very big number)
const NEFilterDataAttribute* dataAttr = readBytes.bytes;
NSLog(@"NEFilterDataAttribute: %ld",*dataAttr);
and after the initial 4 bytes, if the offset param is 0, can i assume that UDP/TCP or IP packet headers can be extracted from the data?
Hello,
We would like to track the open sockets on the machine. we don't want to use a constantly running thread that polls the open sockets (such as by using sysctlbyname) since it sometimes will miss short-lived sockets.
After some research we decided to implement a content filter (NEFilterDataProvider) that pass-through every socket flow.
However, as we see and read in the forum, all previously opened sockets are disconnected once the filter is applied, which is an undesired thing for users using a VPN that will disconnect as well.
We would like to know if there is a better way to track all sockets, preferably in an event-driven way, or, to prevent the existing sockets from disconnecting if we use the filter or other network extension.
Hi, I am trying to make a simple note taking app that users can draw something on pdfview with apple pencil.
(I used PDFKit, PencilKit for the code.)
I followed the instruction code of WWDC22's "What's new in PDFKit." - "overlayProvider"
(so you can see the code at the video.) I was able to draw something each view of pdf page.
But the issue was, the resolution of overlayview or subview of pdfview is low.
As far as I know, the pkcanvasview draws vertor-based drawings. So I never thought the image or the lines I draw will be that blurry.
Is this buggy or is this the normal thing? (+ I added a uibutton as subview of pdfview and the button also looks blurry.)
I even tried to scale up the all the subviews when the subviews' layout is done, using contentScaleFactor.
PKCanvasView inherits UIScrollView, so I enlarged the frame of pkcanvas view and fixed the scale to below 1.0. If the pkcanvasview looks blurry and that is because somewhat zoomed in wrong way, zooming out should be the solution. But, didn't work. Still blurry.
and any other stuff like changing frame or size.
So, anyone having same problem with me, or anyone can give me any solution.
Please help me. I wish this is bug thing that can be fixed in any moment.
-> This image is little bit zoomed in. but the drawing is blurry.
and this is the normal pkcanvasview drawing, just subview of view(of VC).
I'm creating an app that uses broadcasts using sockets.
But there's something strange about it.
It is possible to send packets from other platforms like mac and windows and receive them in iOS, but it's impossible to receive packets from iOS in other platforms.
iOS -> Other (OK)
Other -> iOS (Not OK)
If ios app send packet, it can't receive any bytes in other platforms.
Communication between iOS devices is no problem, and there is no problem between other platforms too.
For example, iPhone apps and iPad apps can communicate, and Macbook and Windows can communicate in the same way.
However, iPhone and mac cannot communicate.
I use UDP, ipv6, Broadcast, address: ff02::1, port: 14001
What is wrong with sending from the ios to another platform?
Hi All,
Please excuse my relatively basic question but I am new to swift programming and I am battling with a project.
I currently have an app that receives data from an Arduino using ble and displays the data as an integer. I used this medium article From Arduino programming to iOS App development as a guide for most of the functionality but changed the sensor data being sent to better suit my project requirements.
Based on the link above, I have all of the bluetooth handling in PeripheralUseCase.swift file and then I have the ConnectView file for the display:
@ObservedObject var viewModel: ConnectViewModel
@Environment(\.dismiss) var dismiss
@State var isToggleOn: Bool = false
@State var isPeripheralReady: Bool = false
@State var lastPressure: Int = 0
var body: some View {
VStack {
Text(viewModel.connectedPeripheral.name ?? "Unknown")
.font(.title)
ZStack {
CardView()
VStack {
Text("Surface")
HStack {
Button("Flats") {
viewModel.flats()
}
.disabled(!isPeripheralReady)
.buttonStyle(.borderedProminent)
Button("FlatPoint") {
viewModel.flatPoint()
}
.disabled(!isPeripheralReady)
.buttonStyle(.borderedProminent)
Button("Points") {
viewModel.points()
}
.disabled(!isPeripheralReady)
.buttonStyle(.borderedProminent)
}
}
}
ZStack {
CardView()
VStack {
Text("\(lastPressure) kPa")
.font(.largeTitle)
HStack {
Spacer()
.frame(alignment: .trailing)
Toggle("Notify", isOn: $isToggleOn)
.disabled(!isPeripheralReady)
Spacer()
.frame(alignment: .trailing)
}
}
}
Spacer()
.frame(maxHeight:.infinity)
Button {
dismiss()
} label: {
Text("Disconnect")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.padding(.horizontal)
}
.onChange(of: isToggleOn) { newValue in
if newValue == true {
viewModel.startNotifyPressure()
} else {
viewModel.stopNotifyPressure()
}
let startTime = Date().timeIntervalSince1970
}
.onReceive(viewModel.$state) { state in
switch state {
case .ready:
isPeripheralReady = true
case let .Pressure(temp):
lastPressure = temp
default:
print("Not handled")
}
}
}
}
struct PeripheralView_Previews: PreviewProvider {
final class FakeUseCase: PeripheralUseCaseProtocol {
var peripheral: Peripheral?
var onWriteLedState: ((Bool) -> Void)?
var onReadPressure: ((Int) -> Void)?
var onPeripheralReady: (() -> Void)?
var onError: ((Error) -> Void)?
func writeLedState(isOn: String) {}
func readPressure() {
onReadPressure?(25)
}
func notifyPressure(_ isOn: Bool) {}
}
static var viewModel = {
ConnectViewModel(useCase: FakeUseCase(),
connectedPeripheral: .init(name: "iOSArduinoBoard"))
}()
static var previews: some View {
ConnectView(viewModel: viewModel, isPeripheralReady: true)
}
}
struct CardView: View {
var body: some View {
RoundedRectangle(cornerRadius: 16, style: .continuous)
.shadow(color: Color(white: 0.5, opacity: 0.2), radius: 6)
.foregroundColor(.init(uiColor: .secondarySystemBackground))
}
}
With the associated View Model:
@Published var state = State.idle
var useCase: PeripheralUseCaseProtocol
let connectedPeripheral: Peripheral
init(useCase: PeripheralUseCaseProtocol,
connectedPeripheral: Peripheral) {
self.useCase = useCase
self.useCase.peripheral = connectedPeripheral
self.connectedPeripheral = connectedPeripheral
self.setCallbacks()
}
private func setCallbacks() {
useCase.onPeripheralReady = { [weak self] in
self?.state = .ready
}
useCase.onReadPressure = { [weak self] value in
self?.state = .Pressure(value)
}
useCase.onWriteLedState = { [weak self] value in
self?.state = .ledState(value)
}
useCase.onError = { error in
print("Error \(error)")
}
}
func startNotifyPressure() {
useCase.notifyPressure(true)
}
func stopNotifyPressure() {
useCase.notifyPressure(false)
}
func readPressure() {
useCase.readPressure()
}
func flats() {
useCase.writeLedState(isOn: "1")
}
func flatPoint() {
useCase.writeLedState(isOn: "2")
}
func points() {
useCase.writeLedState(isOn: "3")
}
}
extension ConnectViewModel {
enum State {
case idle
case ready
case Pressure(Int)
case ledState(Bool)
}
}
What I am now trying to do is plot the data that is received from the Arduino in a line graph as it is received. Preferably the graph will scroll with time as well.
I got an error message in Xcode related to provisioning profiles and entitlements. Specifically, it appears Xcode encountered an issue with the provisioning profile I'm trying to use.
The error message states that the provisioning profile named "iOS Team Provisioning Profile" doesn't include the entitlement com.apple.developer.networking.HotspotHelper.
Multiple CBPeripheralManager startAdvertising broadcast
CBCentralManager can search the first CBPeripheralManager broadcast
but
CBCentralManager can search the second CBPeripheralManager broadcast .
first CBPeripheralManager broadcast is still not stop .
I am encountering an issue while using the SystemConfiguration framework to detect IPv4 address changes and active interfaces on macOS. Specifically, I'm facing difficulties when the interface switches from one network to another.
When connected to a network with a Captive Portal enabled, I'm unable to retrieve the active interface using the stored key State:/Network/Global/IPv4. The output I receive is:
No such key
However, when I attempt to retrieve interface information using scutil --nwi, the output is as follows:
IPv4 network interface information
No IPv4 states found
REACH : flags 0x00000000 (Not Reachable)
IPv6 network interface information
No IPv6 states found
REACH : flags 0x00000000 (Not Reachable)
Network interfaces: en0
Despite this output, the interface en0 is active and has a valid IPv4 address:
when checking through ifconfig:
en0:flags=8b63<UP,BROADCAST,SMART,RUNNING,PROMISC,ALLMULTI,SIMPLEX,MULTICAST> mtu 1500
options=6460<TSO4,TSO6,CHANNEL_IO,PARTIAL_CSUM,ZEROINVERT_CSUM>
ether bc:d0:74:07:2a:33
inet6 fe80::412:ec:40df:4211%en0 prefixlen 64 secured scopeid 0x12
inet 10.42.0.5 netmask 0xffffff00 broadcast 10.42.0.255
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
It's evident that the interface is active and has a valid IPv4 address, but the retrieval methods using SystemConfiguration framework are not providing the expected output. I'm seeking assistance in resolving this discrepancy and accurately detecting active interfaces on macOS. Any insights or suggestions would be greatly appreciated. Thank you.
I'm wondering if there's a way to capture the SSL/TLS key log / ephemeral keys from Safari for troubleshooting like there is for Firefox & Chrome by setting the SSLKEYLOGFILE environment variable.
I'm troubleshooting an issue where Safari doesn't load certain CSS and JPEG elements on the first load, but when hitting refresh, those same elements load fine. Clearing the cache or using "disable caches" in the network tab of the inspector will cause the elements to fail to load again. Safari shows that it received a header, but no content. Wireshark shows four TCP/RST packets coming from the client / Safari. The same site loads without issue every time using Firefox or Chromium.
I'm hoping that someone knows how to capture the TLS session keys from Safari so I can look deeper into the packet capture and figure out if Safari is incorrectly parsing the server's response or if there is some subtle corruption in the response that Safari rejects, but other browsers accept.
So, does anyone know how to capture the raw data transfer or TLS session keys from Safari?
Thank you!
Is it possible to mock the behavior of NWPathMonitor for a specific app?
The scenario I want to support
I've created an app called RocketSim, a developer tool for Xcode's Simulator. I've already created Airplane mode, which disables networking calls from URLSession from a specific bundle identifier app installed on the Simulator.
Now, I want to support blocking NWPathMonitor as well. I believe the Simulator uses macOS's NWPathMonitor and does not use any specific HTTP request or similar to determine the reachability state.
Is there a way I can make NWPathMonitor return unsatisfied when my 'airplane mode' is turned on? Potentially using a Network Extension?
Hello,
I develop an iOS game with Unreal Engine 5. My game works perfectly well in the Editor on my mac and on Android, but on iOS somehow once the app in installed, it cannot connect to our game server through WebSocket with a wss URL.
wss being a secured connection I don't see what the issue is, but it looks like it's being blocked by Apple ? No issue communicating with Rest API with our server thought. I have done that so far :
In App ID profile I enabled Custom Networks and Push Notification, set up a SSL certificate. Here is my change in the .plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>MyApp</string>
</array>
</dict>
</array>
<key>NSCameraUsageDescription</key>
<string>We don't and cannot use the Camera at all but UnrealEngine integrates SDK for games using camera</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsForMedia</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSAllowsLocalNetworking</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>myapp.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSRequiresCertificateTransparency</key>
<true/>
</dict>
</dict>
</dict>
Thanks in advance,
Hi Team,
Im trying to disable the option to change the status of the Transparent Proxy enable/disable but there is no API which works in NETransparentProxyManager.
Could you suggest, how to disable the option to change the status of the Transparent Proxy enable/disable? We want to disable it so that no one can modify it from the settings.
This option is coming in Network -> Vpn & Filters
I observed that some other providers disabled it in the "Network -> VPN & Filters" settings.
Since the Multipeer Connectivity framework no longer supports Bluetooth.
(https://developer.apple.com/forums/thread/749346)
Why does its official documentation still mention "In iOS, the framework uses infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks for the underlying transport." ?(https://developer.apple.com/documentation/multipeerconnectivity)
What is the purpose of using Bluetooth personal area networks for the underlying transport?
I am having crash on com.apple.network.connections randomly. I couldn't reproduce in my local, but I keep seen in my Firebase.
Thanks in advance.
stacktrace_0.txt
stacktrace_1.txt
Hello,
I am trying to develop an app , using Flutter. My app has its own database which it contains the customer info such as name, address and phone number. I need to get the caller's phone number then I use the phone number and search in my database and if the phone# exist in our DB , I extract customer info and show it on pop up screen. How can I get the phone number of the person who is calling? i tried this, it didnt work:
let networkInfo = CTTelephonyNetworkInfo()
guard let carrier = networkInfo.serviceSubscriberCellularProviders?.first?.value else {
return nil
}
return carrier.mobileNetworkCode
Is there any way to get caller's number while he/she is calling?
Thanks
P.