Skip to content

Commit

Permalink
Add initial NetP controller and provider classes (#1835)
Browse files Browse the repository at this point in the history
Task/Issue URL: https://app.asana.com/0/0/1205043071738197/f
BSK PR: duckduckgo/BrowserServicesKit#418

Description:

Adds the initial classes needed for the PacketTunnelProvider extension and for controlling it from the iOS app along with some configuration. This PR also brings in the NetP iOS compatibility changes needed after some incompatibility was merged.

Note that until we’re ready to release, the extension will remain not embedded in the app and any Network Extension code will be compiler flagged
  • Loading branch information
graeme authored Jul 17, 2023
1 parent 48af018 commit 62aba18
Show file tree
Hide file tree
Showing 5 changed files with 258 additions and 8 deletions.
34 changes: 29 additions & 5 deletions DuckDuckGo.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,9 @@
EE3B226C29DE0FD30082298A /* MockInternalUserStoring.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE3B226A29DE0F110082298A /* MockInternalUserStoring.swift */; };
EE50052E29C369D300AE0773 /* FeatureFlag.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE50052D29C369D300AE0773 /* FeatureFlag.swift */; };
EE50053029C3BA0800AE0773 /* InternalUserStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE50052F29C3BA0800AE0773 /* InternalUserStore.swift */; };
EE8594992A44791C008A6D06 /* NetworkProtectionTunnelController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE8594982A44791C008A6D06 /* NetworkProtectionTunnelController.swift */; };
EE8E568A2A56BCE400F11DCA /* NetworkProtection in Frameworks */ = {isa = PBXBuildFile; productRef = EE8E56892A56BCE400F11DCA /* NetworkProtection */; };
EEEB80A32A421CE600386378 /* NetworkProtectionPacketTunnelProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEEB80A22A421CE600386378 /* NetworkProtectionPacketTunnelProvider.swift */; };
F103073B1E7C91330059FEC7 /* BookmarksDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = F103073A1E7C91330059FEC7 /* BookmarksDataSource.swift */; };
F1075C921E9EF827006BE8A8 /* UserDefaultsExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1075C911E9EF827006BE8A8 /* UserDefaultsExtension.swift */; };
F10E522D1E946F8800CE1253 /* NSAttributedStringExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F10E522C1E946F8800CE1253 /* NSAttributedStringExtension.swift */; };
Expand Down Expand Up @@ -2269,6 +2272,8 @@
EE3B226A29DE0F110082298A /* MockInternalUserStoring.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockInternalUserStoring.swift; sourceTree = "<group>"; };
EE50052D29C369D300AE0773 /* FeatureFlag.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FeatureFlag.swift; sourceTree = "<group>"; };
EE50052F29C3BA0800AE0773 /* InternalUserStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InternalUserStore.swift; sourceTree = "<group>"; };
EE8594982A44791C008A6D06 /* NetworkProtectionTunnelController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkProtectionTunnelController.swift; sourceTree = "<group>"; };
EEEB80A22A421CE600386378 /* NetworkProtectionPacketTunnelProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkProtectionPacketTunnelProvider.swift; sourceTree = "<group>"; };
F103073A1E7C91330059FEC7 /* BookmarksDataSource.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BookmarksDataSource.swift; sourceTree = "<group>"; };
F1075C911E9EF827006BE8A8 /* UserDefaultsExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserDefaultsExtension.swift; sourceTree = "<group>"; };
F10E522C1E946F8800CE1253 /* NSAttributedStringExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSAttributedStringExtension.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -2492,6 +2497,7 @@
1E60989B290009C700A508F9 /* Common in Frameworks */,
1E60989D290011E600A508F9 /* ContentBlocking in Frameworks */,
F486D33425069BBB002D07D7 /* Kingfisher in Frameworks */,
EE8E568A2A56BCE400F11DCA /* NetworkProtection in Frameworks */,
CBC83E3429B631780008E19C /* Configuration in Frameworks */,
98A16C2D28A11D6200A6C003 /* BrowserServicesKit in Frameworks */,
8599690F29D2F1C100DBF9FA /* DDGSync in Frameworks */,
Expand Down Expand Up @@ -2524,6 +2530,7 @@
02025B1429884EA500E694E7 /* DDGObserverFactory.swift */,
02025668298818B200E694E7 /* Info.plist */,
02025669298818B200E694E7 /* PacketTunnelProvider.entitlements */,
EEEB80A22A421CE600386378 /* NetworkProtectionPacketTunnelProvider.swift */,
);
path = PacketTunnelProvider;
sourceTree = "<group>";
Expand Down Expand Up @@ -3472,6 +3479,7 @@
98B001B1251EABB40090EC07 /* InfoPlist.strings */,
85DFEDEB24C7CC7600973FE7 /* iPad */,
F1C5ECFA1E37B15B00C599A4 /* Main */,
EECD94B22A28B8580085C66E /* NetworkProtection */,
85AE668C20971FCA0014CF04 /* Notifications */,
F1C4A70C1E5771F800A6CA1B /* OmniBar */,
F1AE54DB1F0425BB00D9A700 /* Privacy */,
Expand Down Expand Up @@ -4211,6 +4219,14 @@
name = FeatureFlags;
sourceTree = "<group>";
};
EECD94B22A28B8580085C66E /* NetworkProtection */ = {
isa = PBXGroup;
children = (
EE8594982A44791C008A6D06 /* NetworkProtectionTunnelController.swift */,
);
name = NetworkProtection;
sourceTree = "<group>";
};
F1134EA71F3E2B3500B73467 /* Statistics */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -4445,22 +4461,22 @@
isa = PBXGroup;
children = (
4B470ED4299C484B0086EBDC /* AppTrackingProtection */,
CBAA195627BFDD9800A4BD49 /* SmarterEncryption */,
F1CE42A71ECA0A520074A8DF /* Bookmarks */,
837774491F8E1ECE00E17A29 /* ContentBlocker */,
F143C2E61E4A4CD400CFDE3A /* Core.h */,
F143C3141E4A99BE00CFDE3A /* Domain */,
EE50052C29C3692700AE0773 /* FeatureFlags */,
85CA53A724BB342B00A6288C /* Favicons */,
EE50052C29C3692700AE0773 /* FeatureFlags */,
8512BCBF2061B6110085E862 /* global.swift */,
F143C2E71E4A4CD400CFDE3A /* Info.plist */,
98B001AE251EABB40090EC07 /* InfoPlist.strings */,
F18608DE1E5E648100361C30 /* Javascript */,
CBAA195B27C3982A00A4BD49 /* PrivacyFeatures.swift */,
CBAA195627BFDD9800A4BD49 /* SmarterEncryption */,
F1134EA71F3E2B3500B73467 /* Statistics */,
37DF000829F9C3F0002B7D3E /* Sync */,
F143C3191E4A99DD00CFDE3A /* Utilities */,
F143C3311E4A9A6A00CFDE3A /* Web */,
CBAA195B27C3982A00A4BD49 /* PrivacyFeatures.swift */,
);
path = Core;
sourceTree = "<group>";
Expand Down Expand Up @@ -5222,6 +5238,7 @@
4B948E2529DCCDB9002531FA /* Persistence */,
37DF000B29F9CA80002B7D3E /* SyncDataProviders */,
851481872A600EFC00ABC65F /* RemoteMessaging */,
EE8E56892A56BCE400F11DCA /* NetworkProtection */,
);
productName = Core;
productReference = F143C2E41E4A4CD400CFDE3A /* Core.framework */;
Expand Down Expand Up @@ -5716,6 +5733,7 @@
02025AA32988229800E694E7 /* PacketProtocolParser.swift in Sources */,
02025AA42988229800E694E7 /* IPPacket.swift in Sources */,
02025AA72988229800E694E7 /* ConnectSession.swift in Sources */,
EEEB80A32A421CE600386378 /* NetworkProtectionPacketTunnelProvider.swift in Sources */,
02025AA82988229800E694E7 /* HTTPHeader.swift in Sources */,
02025AA92988229800E694E7 /* ProxyServer.swift in Sources */,
4BEF656D2989C2FC00B650CB /* EventType.swift in Sources */,
Expand Down Expand Up @@ -5877,6 +5895,7 @@
85C297042476C1FD0063A335 /* DaxDialogsSettings.swift in Sources */,
8505836F219F424500ED4EDB /* UIViewExtension.swift in Sources */,
8505836E219F424500ED4EDB /* RoundedRectangleView.swift in Sources */,
EE8594992A44791C008A6D06 /* NetworkProtectionTunnelController.swift in Sources */,
1EEF123F2850A68A003DDE57 /* PrivacyInfoContainerView.swift in Sources */,
F4B0B796252CB35700830156 /* OnboardingWidgetsDetailsViewController.swift in Sources */,
CB258D1329A4F24E00DEBA24 /* ConfigurationStore.swift in Sources */,
Expand Down Expand Up @@ -7542,7 +7561,7 @@
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG APP_TRACKING_PROTECTION";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG APP_TRACKING_PROTECTION NETWORK_PROTECTION";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = "$(ARCHS_STANDARD_64_BIT)";
Expand Down Expand Up @@ -8232,7 +8251,7 @@
repositoryURL = "https://github.com/DuckDuckGo/BrowserServicesKit";
requirement = {
kind = exactVersion;
version = 67.0.0;
version = 67.1.0;
};
};
C14882EB27F211A000D59F0C /* XCRemoteSwiftPackageReference "SwiftSoup" */ = {
Expand Down Expand Up @@ -8388,6 +8407,11 @@
package = 98A16C2928A11BDE00A6C003 /* XCRemoteSwiftPackageReference "BrowserServicesKit" */;
productName = Configuration;
};
EE8E56892A56BCE400F11DCA /* NetworkProtection */ = {
isa = XCSwiftPackageProductDependency;
package = 98A16C2928A11BDE00A6C003 /* XCRemoteSwiftPackageReference "BrowserServicesKit" */;
productName = NetworkProtection;
};
F42D541C29DCA40B004C4FF1 /* DesignResourcesKit */ = {
isa = XCSwiftPackageProductDependency;
package = F42D541B29DCA40B004C4FF1 /* XCRemoteSwiftPackageReference "DesignResourcesKit" */;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
"repositoryURL": "https://github.com/DuckDuckGo/BrowserServicesKit",
"state": {
"branch": null,
"revision": "6d215e0f7791d72aeae23ac91c259d58c02502c5",
"version": "67.0.0"
"revision": "84cf076cb8b9b9d733c59a89ee5536296c38a7d2",
"version": "67.1.0"
}
},
{
Expand Down
164 changes: 164 additions & 0 deletions DuckDuckGo/NetworkProtectionTunnelController.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
//
// NetworkProtectionTunnelController.swift
// DuckDuckGo
//
// Copyright © 2023 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation
import Combine
import Core
import UIKit

#if NETWORK_PROTECTION

import NetworkExtension
import NetworkProtection

public protocol NetworkProtectionTunnelControlling {
var status: ConnectionStatus { get }
var statusPublisher: AnyPublisher<ConnectionStatus, Never> { get }
func setState(to enabled: Bool) async throws
}

final class NetworkProtectionTunnelController: NetworkProtectionTunnelControlling {

private let tokenStore = NetworkProtectionKeychainTokenStore(useSystemKeychain: false, errorEvents: nil)
private let connectionObserver = ConnectionStatusObserverThroughSession(platformNotificationCenter: .default,
platformDidWakeNotification: UIApplication.didBecomeActiveNotification)

// MARK: - NetworkProtectionTunnelControlling

@Published var status: ConnectionStatus = .disconnected

var statusPublisher: AnyPublisher<ConnectionStatus, Never> {
connectionObserver.publisher.eraseToAnyPublisher()
}

func setState(to enabled: Bool) async throws {
if enabled {
try await start()
} else {
try await ConnectionSessionUtilities.activeSession()?.stopVPNTunnel()
}
}

/// Starts the VPN connection used for Network Protection
///
private func start() async throws {
let tunnelManager: NETunnelProviderManager

do {
tunnelManager = try await loadOrMakeTunnelManager()
} catch {
throw error
}

switch tunnelManager.connection.status {
case .invalid:
reloadTunnelManager()
try await start()
case .connected:
// Intentional no-op
break
default:
try start(tunnelManager)
}
}

/// Reloads the tunnel manager from preferences.
///
private func reloadTunnelManager() {
internalTunnelManager = nil
}

private func start(_ tunnelManager: NETunnelProviderManager) throws {
var options = [String: NSObject]()

options["activationAttemptId"] = UUID().uuidString as NSString
options["authToken"] = try tokenStore.fetchToken() as NSString?

do {
try tunnelManager.connection.startVPNTunnel(options: options)
} catch {
throw error
}
}

/// The actual storage for our tunnel manager.
///
private var internalTunnelManager: NETunnelProviderManager?

/// The tunnel manager: will try to load if it its not loaded yet, but if one can't be loaded from preferences,
/// a new one will not be created. This is useful for querying the connection state and information without triggering
/// a VPN-access popup to the user.
///
private var tunnelManager: NETunnelProviderManager? {
get async {
guard let tunnelManager = internalTunnelManager else {
let tunnelManager = await loadTunnelManager()
internalTunnelManager = tunnelManager
return tunnelManager
}

return tunnelManager
}
}

private func loadTunnelManager() async -> NETunnelProviderManager? {
try? await NETunnelProviderManager.loadAllFromPreferences().first
}

private func loadOrMakeTunnelManager() async throws -> NETunnelProviderManager {
guard let tunnelManager = await tunnelManager else {
let tunnelManager = NETunnelProviderManager()
try await setupAndSave(tunnelManager)
internalTunnelManager = tunnelManager
return tunnelManager
}

try await setupAndSave(tunnelManager)
return tunnelManager
}

private func setupAndSave(_ tunnelManager: NETunnelProviderManager) async throws {
try await setup(tunnelManager)
try await tunnelManager.saveToPreferences()
try await tunnelManager.loadFromPreferences()
try await tunnelManager.saveToPreferences()
}

/// Setups the tunnel manager if it's not set up already.
///
private func setup(_ tunnelManager: NETunnelProviderManager) async throws {
tunnelManager.localizedDescription = "DuckDuckGo Network Protection"
tunnelManager.isEnabled = true

tunnelManager.protocolConfiguration = {
let protocolConfiguration = NETunnelProviderProtocol()
protocolConfiguration.serverAddress = "127.0.0.1" // Dummy address... the NetP service will take care of grabbing a real server

// always-on
protocolConfiguration.disconnectOnSleep = false

return protocolConfiguration
}()

// reconnect on reboot
tunnelManager.onDemandRules = [NEOnDemandRuleConnect()]
}
}

#endif
2 changes: 1 addition & 1 deletion PacketTunnelProvider/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<key>NSExtensionPointIdentifier</key>
<string>com.apple.networkextension.packet-tunnel</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).AppTrackingProtectionPacketTunnelProvider</string>
<string>$(PRODUCT_MODULE_NAME).NetworkProtectionPacketTunnelProvider</string>
</dict>
</dict>
</plist>
62 changes: 62 additions & 0 deletions PacketTunnelProvider/NetworkProtectionPacketTunnelProvider.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//
// NetworkProtectionPacketTunnelProvider.swift
// DuckDuckGo
//
// Copyright © 2023 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation
import NetworkProtection
import Common

// Initial implementation for initial Network Protection tests. Will be fleshed out with https://app.asana.com/0/1203137811378537/1204630829332227/f
final class NetworkProtectionPacketTunnelProvider: PacketTunnelProvider {

private static var packetTunnelProviderEvents: EventMapping<PacketTunnelProvider.Event> = .init { _, _, _, _ in
}

@objc init() {
super.init(notificationCenter: NotificationCenter.default,
notificationsPresenter: DefaultNotificationPresenter(),
useSystemKeychain: false,
debugEvents: nil,
providerEvents: Self.packetTunnelProviderEvents)
}
}

final class DefaultNotificationPresenter: NetworkProtectionNotificationsPresenter {

func showTestNotification() {
}

func showReconnectedNotification() {
}

func showReconnectingNotification() {
}

func showConnectionFailureNotification() {
}

func showSupersededNotification() {
}
}

// MARK: - NetworkProtectionNotificationPosting

extension NotificationCenter: NetworkProtectionNotificationPosting {
public func post(_ networkProtectionNotification: NetworkProtection.NetworkProtectionNotification, object: String?, log: Common.OSLog) {
}
}

0 comments on commit 62aba18

Please sign in to comment.