diff options
| author | Andrej Mihajlov <and@mullvad.net> | 2021-02-11 15:25:23 +0100 |
|---|---|---|
| committer | Andrej Mihajlov <and@mullvad.net> | 2021-02-11 15:25:23 +0100 |
| commit | dd3e78031ce76d00d91ddc5f90f1099a8b90a749 (patch) | |
| tree | 8da37718b9d34519b2d7a6453fc5c2f82047de1a | |
| parent | fa70eca85e749aa0d0f775f11f10062938ac3145 (diff) | |
| parent | 26c520de95cd47777a2660b52c53fba65ad27909 (diff) | |
| download | mullvadvpn-dd3e78031ce76d00d91ddc5f90f1099a8b90a749.tar.xz mullvadvpn-dd3e78031ce76d00d91ddc5f90f1099a8b90a749.zip | |
Merge branch 'wireguard-kit'
35 files changed, 292 insertions, 1705 deletions
diff --git a/.travis.yml b/.travis.yml index c6977b4f90..6071ee8f5d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -80,10 +80,10 @@ matrix: # iOS - language: swift - osx_image: xcode11.3 + osx_image: xcode12.2 xcode_project: ios/MullvadVPN.xcodeproj xcode_scheme: MullvadVPNTests - xcode_destination: platform=iOS Simulator,OS=13.3,name=iPhone 8 + xcode_destination: platform=iOS Simulator,OS=14.2,name=iPhone 8 # Daemon - macOS - language: rust diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 798252a4dc..08a49bb671 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -23,6 +23,8 @@ Line wrap the file at 100 chars. Th ## [Unreleased] +### Changed +- Migrate to WireGuardKit framework. ## [2020.5] - 2020-11-04 ### Fixed diff --git a/ios/MullvadVPN.xcodeproj/project.pbxproj b/ios/MullvadVPN.xcodeproj/project.pbxproj index f6d62ada42..29b107b020 100644 --- a/ios/MullvadVPN.xcodeproj/project.pbxproj +++ b/ios/MullvadVPN.xcodeproj/project.pbxproj @@ -58,7 +58,6 @@ 582BB1B1229569620055B6EF /* CustomNavigationBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 582BB1B0229569620055B6EF /* CustomNavigationBar.swift */; }; 582BB1B3229574F40055B6EF /* SettingsAccountCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 582BB1B2229574F40055B6EF /* SettingsAccountCell.swift */; }; 582BB1B52295780F0055B6EF /* AccountExpiry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 582BB1B42295780F0055B6EF /* AccountExpiry.swift */; }; - 58341D9D2507826300D2BB19 /* IPAddressRangeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58341D9C2507826300D2BB19 /* IPAddressRangeTests.swift */; }; 5835B7CC233B76CB0096D79F /* TunnelManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5835B7CB233B76CB0096D79F /* TunnelManager.swift */; }; 583BC70724FE4DC500C9DE04 /* Optional+DispatchQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 583BC70624FE4DC400C9DE04 /* Optional+DispatchQueue.swift */; }; 583BC70824FE4DC500C9DE04 /* Optional+DispatchQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 583BC70624FE4DC400C9DE04 /* Optional+DispatchQueue.swift */; }; @@ -71,11 +70,13 @@ 584E96BC240FD4DA00D3334F /* Location.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58A1AA8623F43901009F7EA6 /* Location.swift */; }; 584E96BD240FD4DA00D3334F /* Location.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58A1AA8623F43901009F7EA6 /* Location.swift */; }; 584E96BE240FD4DB00D3334F /* Location.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58A1AA8623F43901009F7EA6 /* Location.swift */; }; + 5850366825A47AC700A43E93 /* IPAddressRange+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5850366725A47AC700A43E93 /* IPAddressRange+Codable.swift */; }; + 5850367F25A481D800A43E93 /* IPAddressRange+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5850366725A47AC700A43E93 /* IPAddressRange+Codable.swift */; }; + 5850368C25A49E2200A43E93 /* PrivateKeyWithMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B35322BB87C4003C19AD /* PrivateKeyWithMetadata.swift */; }; + 5850368D25A49E2200A43E93 /* PrivateKeyWithMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B35322BB87C4003C19AD /* PrivateKeyWithMetadata.swift */; }; 58561C99239A5D1500BD6B5E /* IPEndpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58561C98239A5D1500BD6B5E /* IPEndpoint.swift */; }; 58561C9A239A5D1500BD6B5E /* IPEndpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58561C98239A5D1500BD6B5E /* IPEndpoint.swift */; }; - 5857F22F24C8404C00CF6F47 /* MullvadRest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58CB0EDF24B86751001EF0D8 /* MullvadRest.swift */; }; 5857F23024C843ED00CF6F47 /* ChainedError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58F840B12464491D0044E708 /* ChainedError.swift */; }; - 5857F23324C8442800CF6F47 /* IPAddressRange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B34E22BB7AC0003C19AD /* IPAddressRange.swift */; }; 5857F23424C8443700CF6F47 /* AsyncOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58E973DD24850EB600096F90 /* AsyncOperation.swift */; }; 5857F23524C8444E00CF6F47 /* InputOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 580EE21A24B3236900F9D8A1 /* InputOperation.swift */; }; 5857F23624C8445300CF6F47 /* OutputOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 580EE21D24B3237F00F9D8A1 /* OutputOperation.swift */; }; @@ -92,14 +93,11 @@ 585834F824D2BC1F00A8AF56 /* Logging in Frameworks */ = {isa = PBXBuildFile; productRef = 585834F724D2BC1F00A8AF56 /* Logging */; }; 585834FC24D2BC9500A8AF56 /* Logging in Frameworks */ = {isa = PBXBuildFile; productRef = 585834FB24D2BC9500A8AF56 /* Logging */; }; 585FE2F124E1365400439C50 /* LogStreamer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 585FE2F024E1365400439C50 /* LogStreamer.swift */; }; - 5860F1C223A785C600CEA666 /* WireguardDevice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5860F1C123A785C600CEA666 /* WireguardDevice.swift */; }; - 5860F1C423A8D25F00CEA666 /* WireguardConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5860F1C323A8D25F00CEA666 /* WireguardConfiguration.swift */; }; 5862805422428EF100F5A6E1 /* TranslucentButtonBlurView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5862805322428EF100F5A6E1 /* TranslucentButtonBlurView.swift */; }; 5868585524054096000B8131 /* AppButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5868585424054096000B8131 /* AppButton.swift */; }; 586AA296234B696B00502875 /* WireguardAssociatedAddresses.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58B8743122B25A7600015324 /* WireguardAssociatedAddresses.swift */; }; 586BD68322B7BBD800BB7F9F /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 586BD68222B7BBD800BB7F9F /* NetworkExtension.framework */; }; 586BD68422B7BBE400BB7F9F /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 586BD68222B7BBD800BB7F9F /* NetworkExtension.framework */; }; - 58723E7522A54CB2009837F5 /* libwg-go.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 58723E7422A54C63009837F5 /* libwg-go.a */; }; 5873884D239E6D7E00E96C4E /* EmbeddedViewContainerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5873884C239E6D7E00E96C4E /* EmbeddedViewContainerView.swift */; }; 587425C12299833500CA2045 /* RootContainerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 587425C02299833500CA2045 /* RootContainerViewController.swift */; }; 5877153023981F7B001F8237 /* WireguardKeysViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5877152F23981F7B001F8237 /* WireguardKeysViewController.swift */; }; @@ -112,6 +110,9 @@ 587AD7CA2342283900E93A53 /* Account.swift in Sources */ = {isa = PBXBuildFile; fileRef = 587AD7C92342283900E93A53 /* Account.swift */; }; 587CBFE322807F530028DED3 /* UIColor+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 587CBFE222807F530028DED3 /* UIColor+Helpers.swift */; }; 588534BF246193D90018B744 /* AutomaticKeyRotationManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 588534BD246193C00018B744 /* AutomaticKeyRotationManager.swift */; }; + 58871D1825D5359B002297FA /* MullvadRest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58CB0EDF24B86751001EF0D8 /* MullvadRest.swift */; }; + 58871D1E25D535A3002297FA /* WireGuardKit in Frameworks */ = {isa = PBXBuildFile; productRef = 58871D1D25D535A3002297FA /* WireGuardKit */; }; + 58871D2325D535D2002297FA /* IPAddressRange+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5850366725A47AC700A43E93 /* IPAddressRange+Codable.swift */; }; 5888AD7F2279B6BF0051EB06 /* RelayStatusIndicatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5888AD7E2279B6BF0051EB06 /* RelayStatusIndicatorView.swift */; }; 5888AD83227B11080051EB06 /* SelectLocationCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5888AD82227B11080051EB06 /* SelectLocationCell.swift */; }; 5888AD87227B17950051EB06 /* SelectLocationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5888AD86227B17950051EB06 /* SelectLocationViewController.swift */; }; @@ -150,6 +151,8 @@ 58BA692F23E99F5B009DC256 /* Locking.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BA692D23E99EFF009DC256 /* Locking.swift */; }; 58BA693123EADA6A009DC256 /* SimulatorTunnelProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BA693023EADA6A009DC256 /* SimulatorTunnelProvider.swift */; }; 58BA693223EAE1AE009DC256 /* SimulatorTunnelProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BA693023EADA6A009DC256 /* SimulatorTunnelProvider.swift */; }; + 58BA791B2578F092006FAEA0 /* WireGuardKit in Frameworks */ = {isa = PBXBuildFile; productRef = 58BA791A2578F092006FAEA0 /* WireGuardKit */; }; + 58BA7947257901A5006FAEA0 /* WireGuardKit in Frameworks */ = {isa = PBXBuildFile; productRef = 58BA7946257901A5006FAEA0 /* WireGuardKit */; }; 58BFA5C622A7C97F00A6173D /* RelayCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BFA5C522A7C97F00A6173D /* RelayCache.swift */; }; 58BFA5C722A7C97F00A6173D /* RelayCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BFA5C522A7C97F00A6173D /* RelayCache.swift */; }; 58BFA5CC22A7CE1F00A6173D /* ApplicationConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BFA5CB22A7CE1F00A6173D /* ApplicationConfiguration.swift */; }; @@ -158,14 +161,8 @@ 58C3B06724EA768100C0348E /* LogStreamerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C3B06624EA768100C0348E /* LogStreamerViewController.swift */; }; 58C3B06924EAA25000C0348E /* StringStreamIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C3B06824EAA25000C0348E /* StringStreamIterator.swift */; }; 58C4CB0124EBE5A700A22D49 /* LogEntryParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C4CB0024EBE5A700A22D49 /* LogEntryParser.swift */; }; - 58C6B34F22BB7AC0003C19AD /* IPAddressRange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B34E22BB7AC0003C19AD /* IPAddressRange.swift */; }; - 58C6B35122BB7CFD003C19AD /* IPAddressRange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B34E22BB7AC0003C19AD /* IPAddressRange.swift */; }; - 58C6B35422BB87C4003C19AD /* WireguardPrivateKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B35322BB87C4003C19AD /* WireguardPrivateKey.swift */; }; - 58C6B35522BB87C4003C19AD /* WireguardPrivateKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B35322BB87C4003C19AD /* WireguardPrivateKey.swift */; }; 58C6B35E22BBBFE3003C19AD /* Data+HexCoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B35D22BBBFE3003C19AD /* Data+HexCoding.swift */; }; 58C6B35F22BBBFE3003C19AD /* Data+HexCoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B35D22BBBFE3003C19AD /* Data+HexCoding.swift */; }; - 58C6B36122C0EC82003C19AD /* AnyIPEndpoint+DNS64.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B36022C0EC82003C19AD /* AnyIPEndpoint+DNS64.swift */; }; - 58C6B36722C106FC003C19AD /* WireguardCommand.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C6B36622C106FC003C19AD /* WireguardCommand.swift */; }; 58CB0EE024B86751001EF0D8 /* MullvadRest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58CB0EDF24B86751001EF0D8 /* MullvadRest.swift */; }; 58CB0EE124B86751001EF0D8 /* MullvadRest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58CB0EDF24B86751001EF0D8 /* MullvadRest.swift */; }; 58CC40EF24A601900019D96E /* ObserverList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58CC40EE24A601900019D96E /* ObserverList.swift */; }; @@ -190,10 +187,6 @@ 58E6771F24ADFE7800AA26E7 /* SettingsNavigationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58E6771E24ADFE7800AA26E7 /* SettingsNavigationController.swift */; }; 58F19E35228C15BA00C7710B /* SpinnerActivityIndicatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58F19E34228C15BA00C7710B /* SpinnerActivityIndicatorView.swift */; }; 58F3C0962492617E003E76BE /* AsyncOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58E973DD24850EB600096F90 /* AsyncOperation.swift */; }; - 58F3C099249B978C003E76BE /* x25519.c in Sources */ = {isa = PBXBuildFile; fileRef = 58F3C098249B978C003E76BE /* x25519.c */; }; - 58F3C09A249B9852003E76BE /* x25519.c in Sources */ = {isa = PBXBuildFile; fileRef = 58F3C098249B978C003E76BE /* x25519.c */; }; - 58F3C09C249B99DD003E76BE /* Curve25519.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58F3C09B249B99DD003E76BE /* Curve25519.swift */; }; - 58F3C09D249B99DD003E76BE /* Curve25519.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58F3C09B249B99DD003E76BE /* Curve25519.swift */; }; 58F3C0A0249BBF1E003E76BE /* DiffableDataSources in Frameworks */ = {isa = PBXBuildFile; productRef = 58F3C09F249BBF1E003E76BE /* DiffableDataSources */; }; 58F3C0A4249CB069003E76BE /* HeaderBarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58F3C0A3249CB069003E76BE /* HeaderBarView.swift */; }; 58F3C0A624A50157003E76BE /* relays.json in Resources */ = {isa = PBXBuildFile; fileRef = 58F3C0A524A50155003E76BE /* relays.json */; }; @@ -221,6 +214,13 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 5841E04225D53BCC00D989F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 58CE5E58224146200008646E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 58FBDA9722A519BC00EB69A3; + remoteInfo = WireGuardGoBridge; + }; 58CE5E7F224146470008646E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 58CE5E58224146200008646E /* Project object */; @@ -289,24 +289,21 @@ 582BB1B0229569620055B6EF /* CustomNavigationBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomNavigationBar.swift; sourceTree = "<group>"; }; 582BB1B2229574F40055B6EF /* SettingsAccountCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAccountCell.swift; sourceTree = "<group>"; }; 582BB1B42295780F0055B6EF /* AccountExpiry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountExpiry.swift; sourceTree = "<group>"; }; - 58341D9C2507826300D2BB19 /* IPAddressRangeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IPAddressRangeTests.swift; sourceTree = "<group>"; }; 5835B7CB233B76CB0096D79F /* TunnelManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TunnelManager.swift; sourceTree = "<group>"; }; 583BC70624FE4DC400C9DE04 /* Optional+DispatchQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Optional+DispatchQueue.swift"; sourceTree = "<group>"; }; 5840250022B1124600E4CFEC /* IPAddress+Codable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IPAddress+Codable.swift"; sourceTree = "<group>"; }; 5840250322B11AB700E4CFEC /* MullvadEndpoint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MullvadEndpoint.swift; sourceTree = "<group>"; }; 5845F841236CBACD00B2D93C /* PacketTunnelIpc.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PacketTunnelIpc.swift; sourceTree = "<group>"; }; 584B26F3237434D00073B10E /* RelaySelectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RelaySelectorTests.swift; sourceTree = "<group>"; }; + 5850366725A47AC700A43E93 /* IPAddressRange+Codable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IPAddressRange+Codable.swift"; sourceTree = "<group>"; }; 58561C98239A5D1500BD6B5E /* IPEndpoint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IPEndpoint.swift; sourceTree = "<group>"; }; 5857F24224C8662600CF6F47 /* SelectLocationHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SelectLocationHeaderView.swift; sourceTree = "<group>"; }; 5857F24624C882D700CF6F47 /* SelectLocationNavigationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SelectLocationNavigationController.swift; sourceTree = "<group>"; }; 585FE2F024E1365400439C50 /* LogStreamer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogStreamer.swift; sourceTree = "<group>"; }; - 5860F1C123A785C600CEA666 /* WireguardDevice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WireguardDevice.swift; sourceTree = "<group>"; }; - 5860F1C323A8D25F00CEA666 /* WireguardConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WireguardConfiguration.swift; sourceTree = "<group>"; }; 5862805322428EF100F5A6E1 /* TranslucentButtonBlurView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TranslucentButtonBlurView.swift; sourceTree = "<group>"; }; 5866F39B2243B82D00168AE5 /* MullvadVPN.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = MullvadVPN.entitlements; sourceTree = "<group>"; }; 5868585424054096000B8131 /* AppButton.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppButton.swift; sourceTree = "<group>"; }; 586BD68222B7BBD800BB7F9F /* NetworkExtension.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = NetworkExtension.framework; path = System/Library/Frameworks/NetworkExtension.framework; sourceTree = SDKROOT; }; - 58723E7422A54C63009837F5 /* libwg-go.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libwg-go.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 5873884C239E6D7E00E96C4E /* EmbeddedViewContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmbeddedViewContainerView.swift; sourceTree = "<group>"; }; 587425C02299833500CA2045 /* RootContainerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootContainerViewController.swift; sourceTree = "<group>"; }; 5877152F23981F7B001F8237 /* WireguardKeysViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WireguardKeysViewController.swift; sourceTree = "<group>"; }; @@ -348,11 +345,8 @@ 58C3B06624EA768100C0348E /* LogStreamerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogStreamerViewController.swift; sourceTree = "<group>"; }; 58C3B06824EAA25000C0348E /* StringStreamIterator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringStreamIterator.swift; sourceTree = "<group>"; }; 58C4CB0024EBE5A700A22D49 /* LogEntryParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogEntryParser.swift; sourceTree = "<group>"; }; - 58C6B34E22BB7AC0003C19AD /* IPAddressRange.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IPAddressRange.swift; sourceTree = "<group>"; }; - 58C6B35322BB87C4003C19AD /* WireguardPrivateKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WireguardPrivateKey.swift; sourceTree = "<group>"; }; + 58C6B35322BB87C4003C19AD /* PrivateKeyWithMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivateKeyWithMetadata.swift; sourceTree = "<group>"; }; 58C6B35D22BBBFE3003C19AD /* Data+HexCoding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Data+HexCoding.swift"; sourceTree = "<group>"; }; - 58C6B36022C0EC82003C19AD /* AnyIPEndpoint+DNS64.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AnyIPEndpoint+DNS64.swift"; sourceTree = "<group>"; }; - 58C6B36622C106FC003C19AD /* WireguardCommand.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WireguardCommand.swift; sourceTree = "<group>"; }; 58CB0EDF24B86751001EF0D8 /* MullvadRest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MullvadRest.swift; sourceTree = "<group>"; }; 58CC40EE24A601900019D96E /* ObserverList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObserverList.swift; sourceTree = "<group>"; }; 58CCA00F224249A1004F3011 /* ConnectViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectViewController.swift; sourceTree = "<group>"; }; @@ -382,9 +376,6 @@ 58E973DD24850EB600096F90 /* AsyncOperation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncOperation.swift; sourceTree = "<group>"; }; 58ECD29123F178FD004298B6 /* Screenshots.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Screenshots.xcconfig; sourceTree = "<group>"; }; 58F19E34228C15BA00C7710B /* SpinnerActivityIndicatorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpinnerActivityIndicatorView.swift; sourceTree = "<group>"; }; - 58F3C097249B978C003E76BE /* x25519.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = x25519.h; sourceTree = "<group>"; }; - 58F3C098249B978C003E76BE /* x25519.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = x25519.c; sourceTree = "<group>"; }; - 58F3C09B249B99DD003E76BE /* Curve25519.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Curve25519.swift; sourceTree = "<group>"; }; 58F3C0A3249CB069003E76BE /* HeaderBarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HeaderBarView.swift; sourceTree = "<group>"; }; 58F3C0A524A50155003E76BE /* relays.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = relays.json; sourceTree = "<group>"; }; 58F7D30E250FA12E0097BE4E /* AnyIPEndpoint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnyIPEndpoint.swift; sourceTree = "<group>"; }; @@ -408,6 +399,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 58871D1E25D535A3002297FA /* WireGuardKit in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -417,6 +409,7 @@ files = ( 585834F824D2BC1F00A8AF56 /* Logging in Frameworks */, 58F3C0A0249BBF1E003E76BE /* DiffableDataSources in Frameworks */, + 58BA7947257901A5006FAEA0 /* WireGuardKit in Frameworks */, 586BD68422B7BBE400BB7F9F /* NetworkExtension.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -427,7 +420,7 @@ files = ( 585834FC24D2BC9500A8AF56 /* Logging in Frameworks */, 586BD68322B7BBD800BB7F9F /* NetworkExtension.framework in Frameworks */, - 58723E7522A54CB2009837F5 /* libwg-go.a in Frameworks */, + 58BA791B2578F092006FAEA0 /* WireGuardKit in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -491,7 +484,6 @@ 58B0A2A1238EE67E00BC001D /* MullvadVPNTests */ = { isa = PBXGroup; children = ( - 58341D9C2507826300D2BB19 /* IPAddressRangeTests.swift */, 582AE3112440CA0D00E6733A /* AccountTokenInputTests.swift */, 58B0A2A4238EE67E00BC001D /* Info.plist */, 584B26F3237434D00073B10E /* RelaySelectorTests.swift */, @@ -518,7 +510,6 @@ 58CE5E61224146200008646E /* Products */ = { isa = PBXGroup; children = ( - 58723E7422A54C63009837F5 /* libwg-go.a */, 58CE5E60224146200008646E /* MullvadVPN.app */, 58CE5E79224146470008646E /* PacketTunnel.appex */, 58B0A2A0238EE67E00BC001D /* MullvadVPNTests.xctest */, @@ -552,7 +543,6 @@ 58D9AF6A2501111800B6FAB5 /* ConnectViewController.xib */, 58A99ED2240014A0006599E9 /* ConsentViewController.swift */, 58AB9DEB2501040C006C5526 /* ConsentViewController.xib */, - 58F3C09B249B99DD003E76BE /* Curve25519.swift */, 5896AE83246D5889005B36CB /* CustomDateComponentsFormatting.swift */, 582BB1B0229569620055B6EF /* CustomNavigationBar.swift */, 58C6B35D22BBBFE3003C19AD /* Data+HexCoding.swift */, @@ -563,7 +553,6 @@ 58FD5BF32428C67600112C88 /* InAppPurchaseButton.swift */, 58CE5E6F224146210008646E /* Info.plist */, 5840250022B1124600E4CFEC /* IPAddress+Codable.swift */, - 58C6B34E22BB7AC0003C19AD /* IPAddressRange.swift */, 58561C98239A5D1500BD6B5E /* IPEndpoint.swift */, 58FAEDF6245088E100CB0F5B /* Keychain.swift */, 58FAEDEB245059F000CB0F5B /* KeychainAttributes.swift */, @@ -619,9 +608,7 @@ 58B8743122B25A7600015324 /* WireguardAssociatedAddresses.swift */, 5877152F23981F7B001F8237 /* WireguardKeysViewController.swift */, 58B9814D24FEA70D00C0D59E /* WireguardKeysViewController.xib */, - 58C6B35322BB87C4003C19AD /* WireguardPrivateKey.swift */, - 58F3C098249B978C003E76BE /* x25519.c */, - 58F3C097249B978C003E76BE /* x25519.h */, + 58C6B35322BB87C4003C19AD /* PrivateKeyWithMetadata.swift */, ); path = MullvadVPN; sourceTree = "<group>"; @@ -630,15 +617,12 @@ isa = PBXGroup; children = ( 58F7D30E250FA12E0097BE4E /* AnyIPEndpoint.swift */, - 58C6B36022C0EC82003C19AD /* AnyIPEndpoint+DNS64.swift */, 58CE5E7D224146470008646E /* Info.plist */, 58FBDAA422A52BDA00EB69A3 /* PacketTunnel-Bridging-Header.h */, 58CE5E7E224146470008646E /* PacketTunnel.entitlements */, 58CE5E7B224146470008646E /* PacketTunnelProvider.swift */, 58B8743722B25EAB00015324 /* PacketTunnelSettingsGenerator.swift */, - 58C6B36622C106FC003C19AD /* WireguardCommand.swift */, - 5860F1C123A785C600CEA666 /* WireguardDevice.swift */, - 5860F1C323A8D25F00CEA666 /* WireguardConfiguration.swift */, + 5850366725A47AC700A43E93 /* IPAddressRange+Codable.swift */, ); path = PacketTunnel; sourceTree = "<group>"; @@ -679,7 +663,7 @@ buildPhases = ( ); buildToolPath = /usr/bin/make; - buildWorkingDirectory = "$(PROJECT_DIR)/wireguard-go-bridge"; + buildWorkingDirectory = "$BUILD_DIR/../../SourcePackages/checkouts/wireguard-apple/Sources/WireGuardKitGo"; dependencies = ( ); name = WireGuardGoBridge; @@ -700,8 +684,12 @@ buildRules = ( ); dependencies = ( + 5841E04325D53BCC00D989F7 /* PBXTargetDependency */, ); name = MullvadVPNTests; + packageProductDependencies = ( + 58871D1D25D535A3002297FA /* WireGuardKit */, + ); productName = MullvadVPNTests; productReference = 58B0A2A0238EE67E00BC001D /* MullvadVPNTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; @@ -725,6 +713,7 @@ packageProductDependencies = ( 58F3C09F249BBF1E003E76BE /* DiffableDataSources */, 585834F724D2BC1F00A8AF56 /* Logging */, + 58BA7946257901A5006FAEA0 /* WireGuardKit */, ); productName = MullvadVPN; productReference = 58CE5E60224146200008646E /* MullvadVPN.app */; @@ -747,6 +736,7 @@ name = PacketTunnel; packageProductDependencies = ( 585834FB24D2BC9500A8AF56 /* Logging */, + 58BA791A2578F092006FAEA0 /* WireGuardKit */, ); productName = PacketTunnel; productReference = 58CE5E79224146470008646E /* PacketTunnel.appex */; @@ -825,6 +815,7 @@ packageReferences = ( 58F3C09E249BBF1E003E76BE /* XCRemoteSwiftPackageReference "DiffableDataSources" */, 585834F624D2BC1F00A8AF56 /* XCRemoteSwiftPackageReference "swift-log" */, + 58BA79192578F092006FAEA0 /* XCRemoteSwiftPackageReference "wireguard-apple" */, ); productRefGroup = 58CE5E61224146200008646E /* Products */; projectDirPath = ""; @@ -897,7 +888,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "exec make -C \"$PROJECT_DIR/wireguard-go-bridge\" version-header\n"; + shellScript = "exec make -C \"$BUILD_DIR/../../SourcePackages/checkouts/wireguard-apple/Sources/WireGuardKitGo\" version-header\n"; showEnvVarsInLog = 0; }; 58FBDAA922A52D9B00EB69A3 /* Extract wireguard-go Version */ = { @@ -916,7 +907,8 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "exec make -C \"$PROJECT_DIR/wireguard-go-bridge\" version-header\n"; + shellScript = "exec make -C \"$BUILD_DIR/../../SourcePackages/checkouts/wireguard-apple/Sources/WireGuardKitGo\" version-header\n"; + showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ @@ -930,13 +922,10 @@ 582AE3132440CA2700E6733A /* AccountTokenInput.swift in Sources */, 5857F23724C8446400CF6F47 /* AssociatedValue.swift in Sources */, 5857F23B24C8448600CF6F47 /* OperationProtocol.swift in Sources */, - 5857F22F24C8404C00CF6F47 /* MullvadRest.swift in Sources */, 58B0A2AA238EE6A900BC001D /* RelaySelector.swift in Sources */, - 58341D9D2507826300D2BB19 /* IPAddressRangeTests.swift in Sources */, 5857F23924C8446A00CF6F47 /* AnyOperationObserver.swift in Sources */, 5896AE86246D6AD8005B36CB /* CustomDateComponentsFormattingTests.swift in Sources */, 5807E2C3243203E700F5FF30 /* String+Split.swift in Sources */, - 5857F23324C8442800CF6F47 /* IPAddressRange.swift in Sources */, 5896AE82246ACE84005B36CB /* KeychainReturn.swift in Sources */, 58B0A2A8238EE68200BC001D /* RelaySelectorTests.swift in Sources */, 584E96BE240FD4DB00D3334F /* Location.swift in Sources */, @@ -959,6 +948,8 @@ 58A8BE81239FBE62006B74AC /* IPEndpoint.swift in Sources */, 5896AE7F246ACE76005B36CB /* Keychain.swift in Sources */, 5857F23C24C8449500CF6F47 /* OperationObserver.swift in Sources */, + 58871D1825D5359B002297FA /* MullvadRest.swift in Sources */, + 58871D2325D535D2002297FA /* IPAddressRange+Codable.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -983,8 +974,8 @@ 582BB1B1229569620055B6EF /* CustomNavigationBar.swift in Sources */, 588D2FE3248AC27F00E313F7 /* AsyncOperation.swift in Sources */, 5877153023981F7B001F8237 /* WireguardKeysViewController.swift in Sources */, + 5850367F25A481D800A43E93 /* IPAddressRange+Codable.swift in Sources */, 58FAEDEF245069C700CB0F5B /* KeychainAttributes.swift in Sources */, - 58C6B35422BB87C4003C19AD /* WireguardPrivateKey.swift in Sources */, 58CB0EE024B86751001EF0D8 /* MullvadRest.swift in Sources */, 580EE20924B3224200F9D8A1 /* RetryOperation.swift in Sources */, 582AE3102440A6CA00E6733A /* AccountTokenInput.swift in Sources */, @@ -1002,7 +993,6 @@ 5840250422B11AB700E4CFEC /* MullvadEndpoint.swift in Sources */, 58CC40EF24A601900019D96E /* ObserverList.swift in Sources */, 58CCA01822426713004F3011 /* AccountViewController.swift in Sources */, - 58F3C099249B978C003E76BE /* x25519.c in Sources */, 5868585524054096000B8131 /* AppButton.swift in Sources */, 5845F842236CBACD00B2D93C /* PacketTunnelIpc.swift in Sources */, 58781CC922AE7CA8009B9D8E /* RelayConstraints.swift in Sources */, @@ -1010,8 +1000,7 @@ 581503A124D6F01F00C9C50E /* LogRotation.swift in Sources */, 580EE20F24B322E700F9D8A1 /* TransformOperation.swift in Sources */, 58B8743222B25A7600015324 /* WireguardAssociatedAddresses.swift in Sources */, - 58C6B34F22BB7AC0003C19AD /* IPAddressRange.swift in Sources */, - 58F3C09C249B99DD003E76BE /* Curve25519.swift in Sources */, + 5850368C25A49E2200A43E93 /* PrivateKeyWithMetadata.swift in Sources */, 58DF28A52417CB4B00E836B0 /* AppStorePaymentManager.swift in Sources */, 580EE22124B3240100F9D8A1 /* TransformOperationObserver.swift in Sources */, 582BB1AF229566420055B6EF /* SettingsCell.swift in Sources */, @@ -1072,18 +1061,17 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 5860F1C423A8D25F00CEA666 /* WireguardConfiguration.swift in Sources */, - 58F3C09D249B99DD003E76BE /* Curve25519.swift in Sources */, 58CB0EE124B86751001EF0D8 /* MullvadRest.swift in Sources */, 580EE21F24B3237F00F9D8A1 /* OutputOperation.swift in Sources */, + 5850366825A47AC700A43E93 /* IPAddressRange+Codable.swift in Sources */, 58F7D310250FA12E0097BE4E /* AnyIPEndpoint.swift in Sources */, 580EE20224B321DB00F9D8A1 /* OperationProtocol.swift in Sources */, 58FAEE0224533ABB00CB0F5B /* KeychainMatchLimit.swift in Sources */, 58FAEE0324533ABE00CB0F5B /* KeychainReturn.swift in Sources */, 58BFA5CD22A7CE1F00A6173D /* ApplicationConfiguration.swift in Sources */, + 5850368D25A49E2200A43E93 /* PrivateKeyWithMetadata.swift in Sources */, 580EE20724B3222400F9D8A1 /* ExclusivityController.swift in Sources */, 58F840B02464382C0044E708 /* KeychainItemRevision.swift in Sources */, - 58C6B35122BB7CFD003C19AD /* IPAddressRange.swift in Sources */, 587AD7C723421D8600E93A53 /* TunnelSettings.swift in Sources */, 58F3C0962492617E003E76BE /* AsyncOperation.swift in Sources */, 580EE22924B3289300F9D8A1 /* AssociatedValue.swift in Sources */, @@ -1093,15 +1081,12 @@ 580EE21924B3235100F9D8A1 /* AnyOperationObserver.swift in Sources */, 580EE21324B322FC00F9D8A1 /* ResultOperation.swift in Sources */, 58CE5E7C224146470008646E /* PacketTunnelProvider.swift in Sources */, - 58F3C09A249B9852003E76BE /* x25519.c in Sources */, 58FAEDF1245069CA00CB0F5B /* KeychainAttributes.swift in Sources */, 586AA296234B696B00502875 /* WireguardAssociatedAddresses.swift in Sources */, 58BA692F23E99F5B009DC256 /* Locking.swift in Sources */, 58B8743B22B788D200015324 /* PacketTunnelSettingsGenerator.swift in Sources */, - 5860F1C223A785C600CEA666 /* WireguardDevice.swift in Sources */, 580EE21624B3231200F9D8A1 /* OperationBlockObserver.swift in Sources */, 58CC40F024A602780019D96E /* ObserverList.swift in Sources */, - 58C6B35522BB87C4003C19AD /* WireguardPrivateKey.swift in Sources */, 581503A724D6F4AE00C9C50E /* Logging.swift in Sources */, 58FAEE0424533AC000CB0F5B /* KeychainClass.swift in Sources */, 58AEEF6C2344A49D00C9BBD5 /* TunnelSettingsManager.swift in Sources */, @@ -1116,10 +1101,8 @@ 5815039E24D6ECE600C9C50E /* TextFileOutputStream.swift in Sources */, 584E96BD240FD4DA00D3334F /* Location.swift in Sources */, 58FAEDF8245088E100CB0F5B /* Keychain.swift in Sources */, - 58C6B36122C0EC82003C19AD /* AnyIPEndpoint+DNS64.swift in Sources */, 58F840B32464491D0044E708 /* ChainedError.swift in Sources */, 580EE20A24B3224200F9D8A1 /* RetryOperation.swift in Sources */, - 58C6B36722C106FC003C19AD /* WireguardCommand.swift in Sources */, 58561C9A239A5D1500BD6B5E /* IPEndpoint.swift in Sources */, 580EE22524B3243100F9D8A1 /* AsyncBlockOperation.swift in Sources */, 580EE20D24B3225F00F9D8A1 /* DelayOperation.swift in Sources */, @@ -1146,6 +1129,11 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 5841E04325D53BCC00D989F7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 58FBDA9722A519BC00EB69A3 /* WireGuardGoBridge */; + targetProxy = 5841E04225D53BCC00D989F7 /* PBXContainerItemProxy */; + }; 58CE5E80224146470008646E /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 58CE5E78224146470008646E /* PacketTunnel */; @@ -1352,6 +1340,7 @@ CODE_SIGN_STYLE = Manual; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = CKG9MXH72F; + ENABLE_BITCODE = NO; INFOPLIST_FILE = MullvadVPN/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( @@ -1380,6 +1369,7 @@ CODE_SIGN_STYLE = Manual; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = CKG9MXH72F; + ENABLE_BITCODE = NO; INFOPLIST_FILE = MullvadVPN/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( @@ -1592,6 +1582,14 @@ version = 1.4.0; }; }; + 58BA79192578F092006FAEA0 /* XCRemoteSwiftPackageReference "wireguard-apple" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://git.zx2c4.com/wireguard-apple"; + requirement = { + kind = exactVersion; + version = "1.0.12-22"; + }; + }; 58F3C09E249BBF1E003E76BE /* XCRemoteSwiftPackageReference "DiffableDataSources" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/ra1028/DiffableDataSources.git"; @@ -1613,6 +1611,21 @@ package = 585834F624D2BC1F00A8AF56 /* XCRemoteSwiftPackageReference "swift-log" */; productName = Logging; }; + 58871D1D25D535A3002297FA /* WireGuardKit */ = { + isa = XCSwiftPackageProductDependency; + package = 58BA79192578F092006FAEA0 /* XCRemoteSwiftPackageReference "wireguard-apple" */; + productName = WireGuardKit; + }; + 58BA791A2578F092006FAEA0 /* WireGuardKit */ = { + isa = XCSwiftPackageProductDependency; + package = 58BA79192578F092006FAEA0 /* XCRemoteSwiftPackageReference "wireguard-apple" */; + productName = WireGuardKit; + }; + 58BA7946257901A5006FAEA0 /* WireGuardKit */ = { + isa = XCSwiftPackageProductDependency; + package = 58BA79192578F092006FAEA0 /* XCRemoteSwiftPackageReference "wireguard-apple" */; + productName = WireGuardKit; + }; 58F3C09F249BBF1E003E76BE /* DiffableDataSources */ = { isa = XCSwiftPackageProductDependency; package = 58F3C09E249BBF1E003E76BE /* XCRemoteSwiftPackageReference "DiffableDataSources" */; diff --git a/ios/MullvadVPN.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/MullvadVPN.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index e49461b65b..16dde9781a 100644 --- a/ios/MullvadVPN.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/ios/MullvadVPN.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -27,6 +27,15 @@ "revision": "173f567a2dfec11d74588eea82cecea555bdc0bc", "version": "1.4.0" } + }, + { + "package": "WireGuardKit", + "repositoryURL": "https://git.zx2c4.com/wireguard-apple", + "state": { + "branch": null, + "revision": "c4f79beb8d23078393451d1173f3b9342c6ea66e", + "version": "1.0.12-22" + } } ] }, diff --git a/ios/MullvadVPN/AutomaticKeyRotationManager.swift b/ios/MullvadVPN/AutomaticKeyRotationManager.swift index a6c7466ba8..3d7321c68c 100644 --- a/ios/MullvadVPN/AutomaticKeyRotationManager.swift +++ b/ios/MullvadVPN/AutomaticKeyRotationManager.swift @@ -8,6 +8,7 @@ import Foundation import Logging +import WireGuardKit /// A private key rotation retry interval on failure (in seconds) private let kRetryIntervalOnFailure = 300 @@ -18,8 +19,7 @@ private let kRotationInterval = 4 /// A struct describing the key rotation result struct KeyRotationResult { var isNew: Bool - var creationDate: Date - var publicKey: WireguardPublicKey + var publicKeyWithMetadata: PublicKeyWithMetadata } class AutomaticKeyRotationManager { @@ -129,14 +129,13 @@ class AutomaticKeyRotationManager { let currentPrivateKey = keychainEntry.tunnelSettings.interface.privateKey if Self.shouldRotateKey(creationDate: currentPrivateKey.creationDate) { - let result = makeReplaceKeyTask(accountToken: keychainEntry.accountToken, oldPublicKey: currentPrivateKey.publicKey) { (result) in + let result = makeReplaceKeyTask(accountToken: keychainEntry.accountToken, oldPublicKey: currentPrivateKey.privateKey.publicKey) { (result) in let result = result.map { (tunnelSettings) -> KeyRotationResult in let newPrivateKey = tunnelSettings.interface.privateKey return KeyRotationResult( isNew: true, - creationDate: newPrivateKey.creationDate, - publicKey: newPrivateKey.publicKey + publicKeyWithMetadata: newPrivateKey.publicKeyWithMetadata ) } @@ -155,8 +154,7 @@ class AutomaticKeyRotationManager { } else { let event = KeyRotationResult( isNew: false, - creationDate: currentPrivateKey.creationDate, - publicKey: currentPrivateKey.publicKey + publicKeyWithMetadata: currentPrivateKey.publicKeyWithMetadata ) self.didCompleteKeyRotation(result: .success(event)) @@ -169,15 +167,15 @@ class AutomaticKeyRotationManager { private func makeReplaceKeyTask( accountToken: String, - oldPublicKey: WireguardPublicKey, + oldPublicKey: PublicKey, completionHandler: @escaping (Result<TunnelSettings, Error>) -> Void) -> Result<URLSessionDataTask, RestError> { - let newPrivateKey = WireguardPrivateKey() + let newPrivateKeyWithMetadata = PrivateKeyWithMetadata() let payload = TokenPayload( token: accountToken, payload: ReplaceWireguardKeyRequest( - old: oldPublicKey.rawRepresentation, - new: newPrivateKey.publicKey.rawRepresentation + old: oldPublicKey.rawValue, + new: newPrivateKeyWithMetadata.privateKey.publicKey.rawValue ) ) @@ -191,17 +189,17 @@ class AutomaticKeyRotationManager { ipv6Address: response.ipv6Address ) - return self.updateTunnelSettings(privateKey: newPrivateKey, addresses: addresses) + return self.updateTunnelSettings(privateKeyWithMetadata: newPrivateKeyWithMetadata, addresses: addresses) } completionHandler(updateResult) } } } - private func updateTunnelSettings(privateKey: WireguardPrivateKey, addresses: WireguardAssociatedAddresses) -> Result<TunnelSettings, Error> { + private func updateTunnelSettings(privateKeyWithMetadata: PrivateKeyWithMetadata, addresses: WireguardAssociatedAddresses) -> Result<TunnelSettings, Error> { let updateResult = TunnelSettingsManager.update(searchTerm: .persistentReference(self.persistentKeychainReference)) { (tunnelSettings) in - tunnelSettings.interface.privateKey = privateKey + tunnelSettings.interface.privateKey = privateKeyWithMetadata tunnelSettings.interface.addresses = [ addresses.ipv4Address, addresses.ipv6Address @@ -224,7 +222,7 @@ class AutomaticKeyRotationManager { } } - if let rotationDate = Self.nextRotation(creationDate: event.creationDate) { + if let rotationDate = Self.nextRotation(creationDate: event.publicKeyWithMetadata.creationDate) { let interval = rotationDate.timeIntervalSinceNow logger.info("Next private key rotation on \(rotationDate)") diff --git a/ios/MullvadVPN/ConnectViewController.swift b/ios/MullvadVPN/ConnectViewController.swift index c78cd57c22..4ec1d0e979 100644 --- a/ios/MullvadVPN/ConnectViewController.swift +++ b/ios/MullvadVPN/ConnectViewController.swift @@ -91,7 +91,7 @@ class ConnectViewController: UIViewController, RootContainment, TunnelObserver, } } - func tunnelPublicKeyDidChange(publicKey: WireguardPublicKey?) { + func tunnelPublicKeyDidChange(publicKeyWithMetadata: PublicKeyWithMetadata?) { // no-op } diff --git a/ios/MullvadVPN/Curve25519.swift b/ios/MullvadVPN/Curve25519.swift deleted file mode 100644 index 228329b3e5..0000000000 --- a/ios/MullvadVPN/Curve25519.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// Curve25519.swift -// MullvadVPN -// -// Created by pronebird on 18/06/2020. -// Copyright © 2020 Mullvad VPN AB. All rights reserved. -// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. -// - -import Foundation - -struct Curve25519 { - - static let keyLength: Int = 32 - - static func generatePrivateKey() -> Data { - var privateKey = [UInt8](repeating: 0, count: keyLength) - privateKey.withUnsafeMutableBufferPointer { (ptr) in - curve25519_generate_private_key(ptr.baseAddress!) - } - return Data(privateKey) - } - - static func generatePublicKey(fromPrivateKey privateKey: Data) -> Data { - assert(privateKey.count == Self.keyLength) - - var publicKey = [UInt8](repeating: 0, count: keyLength) - privateKey.withUnsafeBytes { (privateKeyBytes) in - let privateKeyBytesPointer = privateKeyBytes.bindMemory(to: UInt8.self) - - publicKey.withUnsafeMutableBufferPointer { (publicKeyPointer) in - curve25519_derive_public_key( - publicKeyPointer.baseAddress!, - privateKeyBytesPointer.baseAddress! - ) - } - } - - return Data(publicKey) - } -} diff --git a/ios/MullvadVPN/IPAddressRange.swift b/ios/MullvadVPN/IPAddressRange.swift deleted file mode 100644 index 712dc4d39e..0000000000 --- a/ios/MullvadVPN/IPAddressRange.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// IPAddressRange.swift -// MullvadVPN -// -// Created by pronebird on 20/06/2019. -// Copyright © 2019 Mullvad VPN AB. All rights reserved. -// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. -// - -import Foundation -import Network - -/// A struct describing an IP address range -struct IPAddressRange { - let address: IPAddress - let networkPrefixLength: UInt8 - - init(address: IPAddress, networkPrefixLength: UInt8) { - self.address = address - self.networkPrefixLength = min(networkPrefixLength, address.maxNetworkPrefixLength) - } - - init(string: String) throws { - let separatorIndex = string.lastIndex(of: "/") ?? string.endIndex - let prefixStartIndex = string.index(separatorIndex, offsetBy: 1, limitedBy: string.endIndex) - - let prefixSubstring = prefixStartIndex.flatMap { string[$0...] } - var prefix: UInt8? - if let prefixSubstring = prefixSubstring { - if let parsedPrefix = UInt8(prefixSubstring) { - prefix = parsedPrefix - } else { - throw IPAddressRangeParseError.parsePrefix(String(prefixSubstring)) - } - } - - let addressString = String(string[..<separatorIndex]) - if let ipv4Address = IPv4Address(addressString) { - self = IPAddressRange( - address: ipv4Address, - networkPrefixLength: prefix ?? ipv4Address.maxNetworkPrefixLength - ) - } else if let ipv6Address = IPv6Address(addressString) { - self = IPAddressRange( - address: ipv6Address, - networkPrefixLength: prefix ?? ipv6Address.maxNetworkPrefixLength - ) - } else { - throw IPAddressRangeParseError.parseAddress(addressString) - } - } -} - -extension IPAddressRange: Equatable { - static func == (lhs: IPAddressRange, rhs: IPAddressRange) -> Bool { - return lhs.address.rawValue == rhs.address.rawValue && - lhs.networkPrefixLength == rhs.networkPrefixLength - } -} - -extension IPAddressRange: Hashable { - func hash(into hasher: inout Hasher) { - hasher.combine(address.rawValue) - hasher.combine(networkPrefixLength) - } -} - -extension IPAddressRange: CustomStringConvertible { - var description: String { - return "\(address)/\(networkPrefixLength)" - } -} - -private extension IPv4Address { - var maxNetworkPrefixLength: UInt8 { - return 32 - } -} - -private extension IPv6Address { - var maxNetworkPrefixLength: UInt8 { - return 128 - } -} - -private extension IPAddress { - var maxNetworkPrefixLength: UInt8 { - if let ipv4Address = self as? IPv4Address { - return ipv4Address.maxNetworkPrefixLength - } else if let ipv6Address = self as? IPv6Address { - return ipv6Address.maxNetworkPrefixLength - } else { - fatalError() - } - } -} - -extension IPAddressRange: Codable { - func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - try container.encode("\(self)") - } - - init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - let value = try container.decode(String.self) - - do { - self = try IPAddressRange(string: value) - } catch { - let context = DecodingError.Context( - codingPath: container.codingPath, - debugDescription: "Invalid IPAddressRange representation", - underlyingError: error) - throw DecodingError.dataCorrupted(context) - } - } -} - -enum IPAddressRangeParseError: LocalizedError, Equatable { - /// A failure to parse the IP address - case parseAddress(String) - - /// A failure to parse the network prefix - case parsePrefix(String) - - var errorDescription: String? { - switch self { - case .parseAddress(let addressString): - return "Failure to parse the IP address: \(addressString)" - case .parsePrefix(let prefixString): - return "Failure to parse the network prefix: \(prefixString)" - } - } -} diff --git a/ios/MullvadVPN/MullvadRest.swift b/ios/MullvadVPN/MullvadRest.swift index c28f282c08..b7c4600de2 100644 --- a/ios/MullvadVPN/MullvadRest.swift +++ b/ios/MullvadVPN/MullvadRest.swift @@ -8,6 +8,7 @@ import Foundation import Network +import WireGuardKit /// REST API v1 base URL private let kRestBaseURL = URL(string: "https://api.mullvad.net/app/v1")! diff --git a/ios/MullvadVPN/MullvadVPN-Bridging-Header.h b/ios/MullvadVPN/MullvadVPN-Bridging-Header.h index cd9ddd8174..fcd44b3f57 100644 --- a/ios/MullvadVPN/MullvadVPN-Bridging-Header.h +++ b/ios/MullvadVPN/MullvadVPN-Bridging-Header.h @@ -2,5 +2,4 @@ // Use this file to import your target's public headers that you would like to expose to Swift. // -#include "x25519.h" #include "wireguard-go-version.h" diff --git a/ios/MullvadVPN/Operations/AsyncOperation.swift b/ios/MullvadVPN/Operations/AsyncOperation.swift index 7edd3bbdd4..a369229083 100644 --- a/ios/MullvadVPN/Operations/AsyncOperation.swift +++ b/ios/MullvadVPN/Operations/AsyncOperation.swift @@ -131,7 +131,7 @@ class AsyncOperation: Operation, OperationProtocol { } } -/// This extension exists because Swift has some issues to infer the +/// This extension exists because Swift has some issues with infering the associated type in `OperationObserver` extension OperationProtocol where Self: AsyncOperation { func addObserver<T: OperationObserver>(_ observer: T) where T.OperationType == Self { let transform = TransformOperationObserver<AsyncOperation>(observer) diff --git a/ios/MullvadVPN/WireguardPrivateKey.swift b/ios/MullvadVPN/PrivateKeyWithMetadata.swift index 41bc98f5a9..6714414390 100644 --- a/ios/MullvadVPN/WireguardPrivateKey.swift +++ b/ios/MullvadVPN/PrivateKeyWithMetadata.swift @@ -1,5 +1,5 @@ // -// WireguardPrivateKey.swift +// PrivateKeyWithMetadata.swift // MullvadVPN // // Created by pronebird on 20/06/2019. @@ -7,58 +7,53 @@ // import Foundation +import WireGuardKit -/// A convenience wrapper around the wireguard key -struct WireguardPrivateKey { +/// A struct holding a private WireGuard key with associated metadata +struct PrivateKeyWithMetadata { /// When the key was created let creationDate: Date - /// Private key's raw representation - private(set) var rawRepresentation: Data + /// Private key + let privateKey: PrivateKey - /// Public key - var publicKey: WireguardPublicKey { - WireguardPublicKey( - creationDate: creationDate, - rawRepresentation: Curve25519.generatePublicKey(fromPrivateKey: rawRepresentation) - ) + /// Public key metadata + var publicKeyWithMetadata: PublicKeyWithMetadata { + return PublicKeyWithMetadata(publicKey: privateKey.publicKey, createdAt: creationDate) } /// Initialize the new private key init() { - rawRepresentation = Curve25519.generatePrivateKey() + privateKey = PrivateKey() creationDate = Date() } - /// Load with the existing private key - init?(rawRepresentation: Data, createdAt: Date) { - guard rawRepresentation.count == Curve25519.keyLength else { return nil } - - self.rawRepresentation = rawRepresentation + /// Initialize with the existing private key + init(privateKey: PrivateKey, createdAt: Date) { + self.privateKey = privateKey creationDate = createdAt } } -extension WireguardPrivateKey: Equatable { - static func == (lhs: WireguardPrivateKey, rhs: WireguardPrivateKey) -> Bool { - lhs.rawRepresentation == rhs.rawRepresentation - } -} - -/// A struct holding a public key used for Wireguard with associated metadata -struct WireguardPublicKey: Codable, Equatable { +/// A struct holding a public WireGuard key with associated metadata +struct PublicKeyWithMetadata: Equatable { /// Refers to private key creation date let creationDate: Date - /// Raw public key representation - let rawRepresentation: Data + /// Public key + let publicKey: PublicKey + + init(publicKey: PublicKey, createdAt: Date) { + self.publicKey = publicKey + creationDate = createdAt + } /// Returns a base64 encoded string representation that can be used for displaying the key in /// the user interface func stringRepresentation(maxLength: Int? = nil) -> String { - let base64EncodedKey = rawRepresentation.base64EncodedString() + let base64EncodedKey = publicKey.base64Key if let maxLength = maxLength, maxLength < base64EncodedKey.count { return base64EncodedKey.prefix(maxLength) + "..." @@ -68,7 +63,7 @@ struct WireguardPublicKey: Codable, Equatable { } } -extension WireguardPrivateKey: Codable { +extension PrivateKeyWithMetadata: Codable { private enum CodingKeys: String, CodingKey { case privateKeyData, creationDate @@ -77,23 +72,23 @@ extension WireguardPrivateKey: Codable { func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(rawRepresentation, forKey: .privateKeyData) + try container.encode(privateKey.rawValue, forKey: .privateKeyData) try container.encode(creationDate, forKey: .creationDate) } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let privateKeyBytes = try container.decode(Data.self, forKey: .privateKeyData) - let creationDate = try container.decode(Date.self, forKey: .creationDate) - if let instance = WireguardPrivateKey(rawRepresentation: privateKeyBytes, createdAt: creationDate) { - self = instance - } else { + guard let privateKey = PrivateKey(rawValue: privateKeyBytes) else { throw DecodingError.dataCorruptedError( forKey: CodingKeys.privateKeyData, in: container, debugDescription: "Invalid key data" ) } + + self.privateKey = privateKey + self.creationDate = try container.decode(Date.self, forKey: .creationDate) } } diff --git a/ios/MullvadVPN/TunnelManager.swift b/ios/MullvadVPN/TunnelManager.swift index 412fea9bf5..9909ef6295 100644 --- a/ios/MullvadVPN/TunnelManager.swift +++ b/ios/MullvadVPN/TunnelManager.swift @@ -9,6 +9,7 @@ import Foundation import NetworkExtension import Logging +import WireGuardKit enum MapConnectionStatusError: ChainedError { /// A failure to perform the IPC request because the tunnel IPC is already deallocated @@ -108,7 +109,7 @@ extension TunnelState: CustomStringConvertible, CustomDebugStringConvertible { protocol TunnelObserver: class { func tunnelStateDidChange(tunnelState: TunnelState) - func tunnelPublicKeyDidChange(publicKey: WireguardPublicKey?) + func tunnelPublicKeyDidChange(publicKeyWithMetadata: PublicKeyWithMetadata?) } private class AnyTunnelObserver: WeakObserverBox, TunnelObserver { @@ -125,8 +126,8 @@ private class AnyTunnelObserver: WeakObserverBox, TunnelObserver { self.inner?.tunnelStateDidChange(tunnelState: tunnelState) } - func tunnelPublicKeyDidChange(publicKey: WireguardPublicKey?) { - self.inner?.tunnelPublicKeyDidChange(publicKey: publicKey) + func tunnelPublicKeyDidChange(publicKeyWithMetadata: PublicKeyWithMetadata?) { + self.inner?.tunnelPublicKeyDidChange(publicKeyWithMetadata: publicKeyWithMetadata) } static func == (lhs: AnyTunnelObserver, rhs: AnyTunnelObserver) -> Bool { @@ -256,7 +257,7 @@ class TunnelManager { private var accountToken: String? private var _tunnelState = TunnelState.disconnected - private var _publicKey: WireguardPublicKey? + private var _publicKeyWithMetadata: PublicKeyWithMetadata? private init() {} @@ -284,21 +285,21 @@ class TunnelManager { } /// The last known public key - private(set) var publicKey: WireguardPublicKey? { + private(set) var publicKeyWithMetadata: PublicKeyWithMetadata? { set { stateLock.withCriticalBlock { - guard _publicKey != newValue else { return } + guard _publicKeyWithMetadata != newValue else { return } - _publicKey = newValue + _publicKeyWithMetadata = newValue observerList.forEach { (observer) in - observer.tunnelPublicKeyDidChange(publicKey: newValue) + observer.tunnelPublicKeyDidChange(publicKeyWithMetadata: newValue) } } } get { stateLock.withCriticalBlock { - return _publicKey + return _publicKeyWithMetadata } } } @@ -468,11 +469,11 @@ class TunnelManager { } let interfaceSettings = tunnelSettings.interface - let publicKey = interfaceSettings.privateKey.publicKey + let publicKeyWithMetadata = interfaceSettings.privateKey.publicKeyWithMetadata let saveAccountData = { // Save the last known public key - self.publicKey = publicKey + self.publicKeyWithMetadata = publicKeyWithMetadata self.accountToken = accountToken } @@ -483,7 +484,7 @@ class TunnelManager { } // Push wireguard key if addresses were not received yet - self.pushWireguardKeyAndUpdateSettings(accountToken: accountToken, publicKey: publicKey) { (result) in + self.pushWireguardKeyAndUpdateSettings(accountToken: accountToken, publicKey: publicKeyWithMetadata.publicKey) { (result) in if case .success = result { saveAccountData() } @@ -507,7 +508,7 @@ class TunnelManager { let completeOperation = { self.accountToken = nil - self.publicKey = nil + self.publicKeyWithMetadata = nil finish(.success(())) } @@ -558,8 +559,8 @@ class TunnelManager { let publicKey = keychainEntry.tunnelSettings .interface .privateKey + .publicKeyWithMetadata .publicKey - .rawRepresentation self.removeWireguardKeyFromServer(accountToken: accountToken, publicKey: publicKey) { (result) in switch result { @@ -602,7 +603,7 @@ class TunnelManager { .map { (keychainEntry) -> PublicKeyPayload<TokenPayload<EmptyPayload>> in let publicKey = keychainEntry.tunnelSettings.interface .privateKey - .publicKey.rawRepresentation + .publicKeyWithMetadata.publicKey.rawValue return PublicKeyPayload( pubKey: publicKey, @@ -641,19 +642,19 @@ class TunnelManager { return } - let newPrivateKey = WireguardPrivateKey() - let oldPublicKey = keychainEntry.tunnelSettings.interface + let newPrivateKey = PrivateKeyWithMetadata() + let oldPublicKeyMetadata = keychainEntry.tunnelSettings.interface .privateKey - .publicKey + .publicKeyWithMetadata - self.replaceWireguardKeyAndUpdateSettings(accountToken: accountToken, oldPublicKey: oldPublicKey, newPrivateKey: newPrivateKey) { (result) in + self.replaceWireguardKeyAndUpdateSettings(accountToken: accountToken, oldPublicKey: oldPublicKeyMetadata, newPrivateKey: newPrivateKey) { (result) in guard case .success = result else { finish(result) return } // Save new public key - self.publicKey = newPrivateKey.publicKey + self.publicKeyWithMetadata = newPrivateKey.publicKeyWithMetadata guard let tunnelIpc = self.tunnelIpc else { finish(.success(())) @@ -809,21 +810,21 @@ class TunnelManager { private func loadPublicKey(accountToken: String) { switch TunnelSettingsManager.load(searchTerm: .accountToken(accountToken)) { case .success(let entry): - self.publicKey = entry.tunnelSettings.interface.privateKey.publicKey + self.publicKeyWithMetadata = entry.tunnelSettings.interface.privateKey.publicKeyWithMetadata case .failure(let error): self.logger.error(chainedError: error, message: "Failed to load the public key") - self.publicKey = nil + self.publicKeyWithMetadata = nil } } private func pushWireguardKeyAndUpdateSettings( accountToken: String, - publicKey: WireguardPublicKey, + publicKey: PublicKey, completionHandler: @escaping (Result<(), Error>) -> Void) { - let payload = TokenPayload(token: accountToken, payload: PushWireguardKeyRequest(pubkey: publicKey.rawRepresentation)) + let payload = TokenPayload(token: accountToken, payload: PushWireguardKeyRequest(pubkey: publicKey.rawValue)) let operation = rest.pushWireguardKey().operation(payload: payload) operation.addDidFinishBlockObserver(queue: dispatchQueue) { (operation, result) in @@ -846,8 +847,8 @@ class TunnelManager { operationQueue.addOperation(operation) } - private func removeWireguardKeyFromServer(accountToken: String, publicKey: Data, completionHandler: @escaping (Result<Bool, Error>) -> Void) { - let payload = PublicKeyPayload(pubKey: publicKey, payload: TokenPayload(token: accountToken, payload: EmptyPayload())) + private func removeWireguardKeyFromServer(accountToken: String, publicKey: PublicKey, completionHandler: @escaping (Result<Bool, Error>) -> Void) { + let payload = PublicKeyPayload(pubKey: publicKey.rawValue, payload: TokenPayload(token: accountToken, payload: EmptyPayload())) let operation = rest.deleteWireguardKey().operation(payload: payload) operation.addDidFinishBlockObserver(queue: dispatchQueue) { (operation, result) in @@ -869,15 +870,15 @@ class TunnelManager { private func replaceWireguardKeyAndUpdateSettings( accountToken: String, - oldPublicKey: WireguardPublicKey, - newPrivateKey: WireguardPrivateKey, + oldPublicKey: PublicKeyWithMetadata, + newPrivateKey: PrivateKeyWithMetadata, completionHandler: @escaping (Result<(), Error>) -> Void) { let payload = TokenPayload( token: accountToken, payload: ReplaceWireguardKeyRequest( - old: oldPublicKey.rawRepresentation, - new: newPrivateKey.publicKey.rawRepresentation + old: oldPublicKey.publicKey.rawValue, + new: newPrivateKey.publicKeyWithMetadata.publicKey.rawValue ) ) diff --git a/ios/MullvadVPN/TunnelSettings.swift b/ios/MullvadVPN/TunnelSettings.swift index b7da8df890..750538dd95 100644 --- a/ios/MullvadVPN/TunnelSettings.swift +++ b/ios/MullvadVPN/TunnelSettings.swift @@ -9,10 +9,11 @@ import Foundation import Network import NetworkExtension +import WireGuardKit /// A struct that holds a tun interface configuration struct InterfaceSettings: Codable { - var privateKey = WireguardPrivateKey() + var privateKey = PrivateKeyWithMetadata() var addresses = [IPAddressRange]() } @@ -21,3 +22,4 @@ struct TunnelSettings: Codable { var relayConstraints = RelayConstraints() var interface = InterfaceSettings() } + diff --git a/ios/MullvadVPN/WireguardAssociatedAddresses.swift b/ios/MullvadVPN/WireguardAssociatedAddresses.swift index d98d97cace..bcf14cdd86 100644 --- a/ios/MullvadVPN/WireguardAssociatedAddresses.swift +++ b/ios/MullvadVPN/WireguardAssociatedAddresses.swift @@ -8,6 +8,7 @@ import Foundation import Network +import WireGuardKit struct WireguardAssociatedAddresses: Codable { let ipv4Address: IPAddressRange diff --git a/ios/MullvadVPN/WireguardKeysViewController.swift b/ios/MullvadVPN/WireguardKeysViewController.swift index 8c0ab1f486..618867a8d7 100644 --- a/ios/MullvadVPN/WireguardKeysViewController.swift +++ b/ios/MullvadVPN/WireguardKeysViewController.swift @@ -49,7 +49,7 @@ class WireguardKeysViewController: UIViewController, TunnelObserver { navigationItem.title = NSLocalizedString("WireGuard key", comment: "Navigation title") TunnelManager.shared.addObserver(self) - updatePublicKey(publicKey: TunnelManager.shared.publicKey, animated: false) + updatePublicKeyWithMetadata(publicKeyWithMetadata: TunnelManager.shared.publicKeyWithMetadata, animated: false) startPublicKeyPeriodicUpdate() } @@ -58,9 +58,9 @@ class WireguardKeysViewController: UIViewController, TunnelObserver { let interval = DispatchTimeInterval.seconds(kCreationDateRefreshInterval) let timerSource = DispatchSource.makeTimerSource(queue: .main) timerSource.setEventHandler { [weak self] () -> Void in - let publicKey = TunnelManager.shared.publicKey + let metadata = TunnelManager.shared.publicKeyWithMetadata - self?.updatePublicKey(publicKey: publicKey, animated: true) + self?.updatePublicKeyWithMetadata(publicKeyWithMetadata: metadata, animated: true) } timerSource.schedule(deadline: .now() + interval, repeating: interval) timerSource.activate() @@ -74,27 +74,27 @@ class WireguardKeysViewController: UIViewController, TunnelObserver { // no-op } - func tunnelPublicKeyDidChange(publicKey: WireguardPublicKey?) { + func tunnelPublicKeyDidChange(publicKeyWithMetadata: PublicKeyWithMetadata?) { DispatchQueue.main.async { - self.updatePublicKey(publicKey: publicKey, animated: true) + self.updatePublicKeyWithMetadata(publicKeyWithMetadata: publicKeyWithMetadata, animated: true) } } // MARK: - IBActions @IBAction func copyPublicKey(_ sender: Any) { - guard let publicKey = TunnelManager.shared.publicKey else { return } + guard let metadata = TunnelManager.shared.publicKeyWithMetadata else { return } - UIPasteboard.general.string = publicKey.stringRepresentation() + UIPasteboard.general.string = metadata.stringRepresentation() setPublicKeyTitle( string: NSLocalizedString("COPIED TO PASTEBOARD!", comment: ""), animated: true) let dispatchWork = DispatchWorkItem { [weak self] in - let publicKey = TunnelManager.shared.publicKey + let metadata = TunnelManager.shared.publicKeyWithMetadata - self?.updatePublicKey(publicKey: publicKey, animated: true) + self?.updatePublicKeyWithMetadata(publicKeyWithMetadata: metadata, animated: true) } DispatchQueue.main.asyncAfter(wallDeadline: .now() + .seconds(3), execute: dispatchWork) @@ -127,8 +127,8 @@ class WireguardKeysViewController: UIViewController, TunnelObserver { creationDateLabel.text = formatKeyGenerationElapsedTime(with: creationDate) ?? "-" } - private func updatePublicKey(publicKey: WireguardPublicKey?, animated: Bool) { - if let publicKey = publicKey { + private func updatePublicKeyWithMetadata(publicKeyWithMetadata: PublicKeyWithMetadata?, animated: Bool) { + if let publicKey = publicKeyWithMetadata { let displayKey = publicKey .stringRepresentation(maxLength: kDisplayPublicKeyMaxLength) diff --git a/ios/MullvadVPN/x25519.c b/ios/MullvadVPN/x25519.c deleted file mode 100644 index b77da0b0ea..0000000000 --- a/ios/MullvadVPN/x25519.c +++ /dev/null @@ -1,178 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0+ - * - * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. - * - * Curve25519 ECDH functions, based on TweetNaCl but cleaned up. - */ - -#include <stdint.h> -#include <string.h> -#include <assert.h> -#include <CommonCrypto/CommonRandom.h> - -#include "x25519.h" - -typedef int64_t fe[16]; - -static inline void carry(fe o) -{ - int i; - - for (i = 0; i < 16; ++i) { - o[(i + 1) % 16] += (i == 15 ? 38 : 1) * (o[i] >> 16); - o[i] &= 0xffff; - } -} - -static inline void cswap(fe p, fe q, int b) -{ - int i; - int64_t t, c = ~(b - 1); - - for (i = 0; i < 16; ++i) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -static inline void pack(uint8_t *o, const fe n) -{ - int i, j, b; - fe m, t; - - memcpy(t, n, sizeof(t)); - carry(t); - carry(t); - carry(t); - for (j = 0; j < 2; ++j) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; ++i) { - m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); - m[i - 1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); - b = (m[15] >> 16) & 1; - m[14] &= 0xffff; - cswap(t, m, 1 - b); - } - for (i = 0; i < 16; ++i) { - o[2 * i] = t[i] & 0xff; - o[2 * i + 1] = t[i] >> 8; - } -} - -static inline void unpack(fe o, const uint8_t *n) -{ - int i; - - for (i = 0; i < 16; ++i) - o[i] = n[2 * i] + ((int64_t)n[2 * i + 1] << 8); - o[15] &= 0x7fff; -} - -static inline void add(fe o, const fe a, const fe b) -{ - int i; - - for (i = 0; i < 16; ++i) - o[i] = a[i] + b[i]; -} - -static inline void subtract(fe o, const fe a, const fe b) -{ - int i; - - for (i = 0; i < 16; ++i) - o[i] = a[i] - b[i]; -} - -static inline void multmod(fe o, const fe a, const fe b) -{ - int i, j; - int64_t t[31] = { 0 }; - - for (i = 0; i < 16; ++i) { - for (j = 0; j < 16; ++j) - t[i + j] += a[i] * b[j]; - } - for (i = 0; i < 15; ++i) - t[i] += 38 * t[i + 16]; - memcpy(o, t, sizeof(fe)); - carry(o); - carry(o); -} - -static inline void invert(fe o, const fe i) -{ - fe c; - int a; - - memcpy(c, i, sizeof(c)); - for (a = 253; a >= 0; --a) { - multmod(c, c, c); - if (a != 2 && a != 4) - multmod(c, c, i); - } - memcpy(o, c, sizeof(fe)); -} - -static void curve25519_shared_secret(uint8_t shared_secret[32], const uint8_t private_key[32], const uint8_t public_key[32]) -{ - static const fe a24 = { 0xdb41, 1 }; - uint8_t z[32]; - int64_t r; - int i; - fe a = { 1 }, b, c = { 0 }, d = { 1 }, e, f, x; - - memcpy(z, private_key, sizeof(z)); - - z[31] = (z[31] & 127) | 64; - z[0] &= 248; - - unpack(x, public_key); - memcpy(b, x, sizeof(b)); - - for (i = 254; i >= 0; --i) { - r = (z[i >> 3] >> (i & 7)) & 1; - cswap(a, b, (int)r); - cswap(c, d, (int)r); - add(e, a, c); - subtract(a, a, c); - add(c, b, d); - subtract(b, b, d); - multmod(d, e, e); - multmod(f, a, a); - multmod(a, c, a); - multmod(c, b, e); - add(e, a, c); - subtract(a, a, c); - multmod(b, a, a); - subtract(c, d, f); - multmod(a, c, a24); - add(a, a, d); - multmod(c, c, a); - multmod(a, d, f); - multmod(d, b, x); - multmod(b, e, e); - cswap(a, b, (int)r); - cswap(c, d, (int)r); - } - invert(c, c); - multmod(a, a, c); - pack(shared_secret, a); -} - -void curve25519_derive_public_key(uint8_t public_key[32], const uint8_t private_key[32]) -{ - static const uint8_t basepoint[32] = { 9 }; - - curve25519_shared_secret(public_key, private_key, basepoint); -} - -void curve25519_generate_private_key(uint8_t private_key[32]) -{ - assert(CCRandomGenerateBytes(private_key, 32) == kCCSuccess); - private_key[31] = (private_key[31] & 127) | 64; - private_key[0] &= 248; -} diff --git a/ios/MullvadVPN/x25519.h b/ios/MullvadVPN/x25519.h deleted file mode 100644 index 7d8440dd3d..0000000000 --- a/ios/MullvadVPN/x25519.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef X25519_H -#define X25519_H - -void curve25519_derive_public_key(unsigned char public_key[32], const unsigned char private_key[32]); -void curve25519_generate_private_key(unsigned char private_key[32]); - -#endif diff --git a/ios/MullvadVPNTests/IPAddressRangeTests.swift b/ios/MullvadVPNTests/IPAddressRangeTests.swift deleted file mode 100644 index 37dc3415a2..0000000000 --- a/ios/MullvadVPNTests/IPAddressRangeTests.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// IPAddressRangeTests.swift -// MullvadVPNTests -// -// Created by pronebird on 08/09/2020. -// Copyright © 2020 Mullvad VPN AB. All rights reserved. -// - -import XCTest - -class IPAddressRangeTests: XCTestCase { - - func testParsingValidIPv4AddressRange() throws { - let addr = try IPAddressRange(string: "127.0.0.1/32") - XCTAssertEqual("\(addr)", "127.0.0.1/32") - } - - func testParsingValidIPv6AddressRange() throws { - let addr = try IPAddressRange(string: "::1/128") - XCTAssertEqual("\(addr)", "::1/128") - } - - func testParsingIPv4AddressWithoutNetworkPrefix() throws { - let addr = try IPAddressRange(string: "127.0.0.1") - XCTAssertEqual("\(addr)", "127.0.0.1/32") - } - - func testParsingIPv6AddressWithoutNetworkPrefix() throws { - let addr = try IPAddressRange(string: "::1") - XCTAssertEqual("\(addr)", "::1/128") - } - - func testParsingInvalidIPv4AddressNetworkPrefix() throws { - let addr = try IPAddressRange(string: "127.0.0.1/33") - XCTAssertEqual("\(addr)", "127.0.0.1/32") - } - - func testParsingInvalidIPv6AddressNetworkPrefix() throws { - let addr = try IPAddressRange(string: "::1/129") - XCTAssertEqual("\(addr)", "::1/128") - } - - func testParsingInvalidIPAddress() throws { - XCTAssertThrowsError(try IPAddressRange(string: "1.2.3.4.5/32")) { (error) in - XCTAssertEqual(error as? IPAddressRangeParseError, IPAddressRangeParseError.parseAddress("1.2.3.4.5")) - } - } - - func testParsingEmptyNetworkPrefix() throws { - XCTAssertThrowsError(try IPAddressRange(string: "::1/")) { (error) in - XCTAssertEqual(error as? IPAddressRangeParseError, IPAddressRangeParseError.parsePrefix("")) - } - } -} diff --git a/ios/PacketTunnel/AnyIPEndpoint+DNS64.swift b/ios/PacketTunnel/AnyIPEndpoint+DNS64.swift deleted file mode 100644 index 460d51e95d..0000000000 --- a/ios/PacketTunnel/AnyIPEndpoint+DNS64.swift +++ /dev/null @@ -1,83 +0,0 @@ -// -// AnyIPEndpoint+DNS64.swift -// PacketTunnel -// -// Created by pronebird on 24/06/2019. -// Copyright © 2019 Mullvad VPN AB. All rights reserved. -// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. -// - -import Foundation -import Network - -extension AnyIPEndpoint { - - /// Returns new `AnyIPEndpoint` resolved using DNS64 - /// Reference: https://developer.apple.com/support/ipv6/ - func withResolvedIP() -> Result<AnyIPEndpoint, Error> { - var hints = addrinfo() - hints.ai_family = PF_UNSPEC - hints.ai_socktype = SOCK_DGRAM - hints.ai_protocol = IPPROTO_UDP - hints.ai_flags = AI_DEFAULT - - var result: UnsafeMutablePointer<addrinfo>? - defer { - result.flatMap { freeaddrinfo($0) } - } - - let errorCode = getaddrinfo("\(self.ip)", "\(self.port)", &hints, &result) - if errorCode != 0 { - let userInfo = [ - NSLocalizedDescriptionKey: String(cString: gai_strerror(errorCode)) - ] - let error = NSError(domain: NSPOSIXErrorDomain, code: Int(errorCode), userInfo: userInfo) - - return .failure(error) - } - - let addrInfo = result!.pointee - var endpoint: AnyIPEndpoint - if let ipv4Address = IPv4Address(addrInfo: addrInfo) { - endpoint = .ipv4(IPv4Endpoint(ip: ipv4Address, port: port)) - } else if let ipv6Address = IPv6Address(addrInfo: addrInfo) { - endpoint = .ipv6(IPv6Endpoint(ip: ipv6Address, port: port)) - } else { - fatalError() - } - - return .success(endpoint) - } -} - -extension IPv4Address { - init?(addrInfo: addrinfo) { - guard addrInfo.ai_family == AF_INET else { return nil } - - let addressData = addrInfo.ai_addr.withMemoryRebound(to: sockaddr_in.self, capacity: MemoryLayout<sockaddr_in>.size) { (ptr) -> Data in - return Data(bytes: &ptr.pointee.sin_addr, count: MemoryLayout<in_addr>.size) - } - - if let ipAddress = IPv4Address(addressData) { - self = ipAddress - } else { - return nil - } - } -} - -extension IPv6Address { - init?(addrInfo: addrinfo) { - guard addrInfo.ai_family == AF_INET6 else { return nil } - - let addressData = addrInfo.ai_addr.withMemoryRebound(to: sockaddr_in6.self, capacity: MemoryLayout<sockaddr_in6>.size) { (ptr) -> Data in - return Data(bytes: &ptr.pointee.sin6_addr, count: MemoryLayout<in6_addr>.size) - } - - if let ipAddress = IPv6Address(addressData) { - self = ipAddress - } else { - return nil - } - } -} diff --git a/ios/PacketTunnel/AnyIPEndpoint.swift b/ios/PacketTunnel/AnyIPEndpoint.swift index bacc705a87..cbc8fe81b8 100644 --- a/ios/PacketTunnel/AnyIPEndpoint.swift +++ b/ios/PacketTunnel/AnyIPEndpoint.swift @@ -8,6 +8,7 @@ import Foundation import Network +import WireGuardKit /// A enum describing any IP endpoint enum AnyIPEndpoint: Hashable { @@ -59,3 +60,14 @@ extension AnyIPEndpoint: CustomStringConvertible { } } } + +extension AnyIPEndpoint { + var wgEndpoint: WireGuardKit.Endpoint { + switch self { + case .ipv4(let ipv4Endpoint): + return .init(host: .ipv4(ipv4Endpoint.ip), port: .init(integerLiteral: ipv4Endpoint.port)) + case .ipv6(let ipv6Endpoint): + return .init(host: .ipv6(ipv6Endpoint.ip), port: .init(integerLiteral: ipv6Endpoint.port)) + } + } +} diff --git a/ios/PacketTunnel/IPAddressRange+Codable.swift b/ios/PacketTunnel/IPAddressRange+Codable.swift new file mode 100644 index 0000000000..f571227849 --- /dev/null +++ b/ios/PacketTunnel/IPAddressRange+Codable.swift @@ -0,0 +1,33 @@ +// +// IPAddressRange+Codable.swift +// PacketTunnel +// +// Created by pronebird on 05/01/2021. +// Copyright © 2021 Mullvad VPN AB. All rights reserved. +// + +import Foundation +import WireGuardKit + +extension IPAddressRange: Codable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + try container.encode(self.stringRepresentation) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let value = try container.decode(String.self) + + if let ipAddressRange = IPAddressRange(from: value) { + self = ipAddressRange + } else { + let context = DecodingError.Context( + codingPath: container.codingPath, + debugDescription: "Invalid IPAddressRange representation" + ) + throw DecodingError.dataCorrupted(context) + } + } +} diff --git a/ios/PacketTunnel/PacketTunnel-Bridging-Header.h b/ios/PacketTunnel/PacketTunnel-Bridging-Header.h index 9d77777330..fcd44b3f57 100644 --- a/ios/PacketTunnel/PacketTunnel-Bridging-Header.h +++ b/ios/PacketTunnel/PacketTunnel-Bridging-Header.h @@ -2,6 +2,4 @@ // Use this file to import your target's public headers that you would like to expose to Swift. // -#include "x25519.h" -#include "../wireguard-go-bridge/wireguard.h" #include "wireguard-go-version.h" diff --git a/ios/PacketTunnel/PacketTunnelProvider.swift b/ios/PacketTunnel/PacketTunnelProvider.swift index 784e3fc8fe..28af108148 100644 --- a/ios/PacketTunnel/PacketTunnelProvider.swift +++ b/ios/PacketTunnel/PacketTunnelProvider.swift @@ -10,6 +10,7 @@ import Foundation import Network import NetworkExtension import Logging +import WireGuardKit class PacketTunnelProvider: NEPacketTunnelProvider { @@ -20,6 +21,9 @@ class PacketTunnelProvider: NEPacketTunnelProvider { /// Tunnel provider logger private let logger: Logger + /// WireGuard adapter logger + private let wgAdapterLogger: Logger + /// Current tunnel state private var tunnelState: PacketTunnelState = .disconnected { didSet { @@ -36,6 +40,12 @@ class PacketTunnelProvider: NEPacketTunnelProvider { return operationQueue }() + private lazy var wgAdapter: WireGuardAdapter = { + return WireGuardAdapter(with: self, logHandler: { [weak self] (logLevel, message) in + self?.wgAdapterLogger.log(level: logLevel.loggerLevel, "\(message)") + }) + }() + private lazy var exclusivityController: ExclusivityController<OperationCategory> = { return ExclusivityController(operationQueue: self.operationQueue) }() @@ -44,9 +54,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider { initLoggingSystem(bundleIdentifier: Bundle.main.bundleIdentifier!) logger = Logger(label: "PacketTunnelProvider") - - let wireguardLogger = Logger(label: "WireGuard") - WireguardDevice.setTunnelLogger(wireguardLogger) + wgAdapterLogger = Logger(label: "WireGuard") } // MARK: - Subclass @@ -142,19 +150,11 @@ class PacketTunnelProvider: NEPacketTunnelProvider { self.tunnelState = .connecting(packetTunnelConfig.selectorResult.tunnelConnectionInfo) - self.updateNetworkSettings(packetTunnelConfig: packetTunnelConfig) { (result) in - guard case .success = result else { - self.tunnelState = .disconnected - - completionHandler(result) - return - } - - self.startWireguardDevice(packetFlow: self.packetFlow, configuration: packetTunnelConfig.wireguardConfig) { (result) in - guard case .success(let device) = result else { + self.wgAdapter.start(tunnelConfiguration: packetTunnelConfig.wgTunnelConfig) { (error) in + self.dispatchQueue.async { + if let error = error { self.tunnelState = .disconnected - - completionHandler(result.map { _ in () }) + completionHandler(.failure(.startWireguardAdapter(error))) return } @@ -177,7 +177,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider { RelayCache.shared.startPeriodicUpdates(queue: self.dispatchQueue) { keyRotationManager.startAutomaticRotation(queue: self.dispatchQueue) { let context = PacketTunnelContext( - wireguardDevice: device, + wgAdapter: self.wgAdapter, keyRotationManager: keyRotationManager ) @@ -202,14 +202,16 @@ class PacketTunnelProvider: NEPacketTunnelProvider { RelayCache.shared.stopPeriodicUpdates(queue: self.dispatchQueue) { context.keyRotationManager.stopAutomaticRotation(queue: self.dispatchQueue) { - context.wireguardDevice.stop(queue: self.dispatchQueue) { (result) in - let result = result.mapError({ (error) -> PacketTunnelProviderError in - return .stopWireguardDevice(error) - }) - - self.tunnelState = .disconnected + context.wgAdapter.stop { (error) in + self.dispatchQueue.async { + self.tunnelState = .disconnected - completionHandler(result) + if let error = error { + completionHandler(.failure(.stopWireguardAdapter(error))) + } else { + completionHandler(.success(())) + } + } } } } @@ -237,31 +239,15 @@ class PacketTunnelProvider: NEPacketTunnelProvider { self.tunnelState = .reconnecting(packetTunnelConfig.selectorResult.tunnelConnectionInfo, context) - // Tell the system that the tunnel is about to reconnect with the new endpoint - self.reasserting = true - - let finishReconnecting = { (result: Result<(), PacketTunnelProviderError>) in - switch result { - case .success: - self.tunnelState = .connected(packetTunnelConfig.selectorResult.tunnelConnectionInfo, context) - case .failure: - self.tunnelState = priorTunnelState - } - - // Tell the system that the tunnel has finished reconnecting - self.reasserting = false - - completionHandler(result) - } - - self.updateNetworkSettings(packetTunnelConfig: packetTunnelConfig) { (result) in - guard case .success = result else { - finishReconnecting(result) - return - } - - context.wireguardDevice.setConfiguration(packetTunnelConfig.wireguardConfig, queue: self.dispatchQueue) { (result) in - finishReconnecting(result.mapError { PacketTunnelProviderError.updateWireguardConfiguration($0) }) + context.wgAdapter.update(tunnelConfiguration: packetTunnelConfig.wgTunnelConfig) { (error) in + self.dispatchQueue.async { + if let error = error { + self.tunnelState = priorTunnelState + completionHandler(.failure(.updateWireguardConfiguration(error))) + } else { + self.tunnelState = .connected(packetTunnelConfig.selectorResult.tunnelConnectionInfo, context) + completionHandler(.success(())) + } } } } @@ -298,29 +284,6 @@ class PacketTunnelProvider: NEPacketTunnelProvider { } } - private func updateNetworkSettings(packetTunnelConfig: PacketTunnelConfiguration, completionHandler: @escaping (Result<(), PacketTunnelProviderError>) -> Void) { - let settingsGenerator = PacketTunnelSettingsGenerator( - mullvadEndpoint: packetTunnelConfig.selectorResult.endpoint, - tunnelSettings: packetTunnelConfig.tunnelSettings - ) - - logger.info("Updating network settings...") - - setTunnelNetworkSettings(settingsGenerator.networkSettings()) { (error) in - self.dispatchQueue.async { - if let error = error { - self.logger.error("Cannot update network settings: \(error.localizedDescription)") - - completionHandler(.failure(.setNetworkSettings(error))) - } else { - self.logger.info("Updated network settings") - - completionHandler(.success(())) - } - } - } - } - private func reloadTunnelSettings(completionHandler: @escaping (Result<(), PacketTunnelProviderError>) -> Void) { let operation = AsyncBlockOperation { (finish) in self.doReloadTunnelSettings { (result) in @@ -383,26 +346,6 @@ class PacketTunnelProvider: NEPacketTunnelProvider { } } } - - private func startWireguardDevice(packetFlow: NEPacketTunnelFlow, configuration: WireguardConfiguration, completionHandler: @escaping (Result<WireguardDevice, PacketTunnelProviderError>) -> Void) { - let result = WireguardDevice.fromPacketFlow(packetFlow) - - guard case .success(let device) = result else { - completionHandler(result.mapError { PacketTunnelProviderError.startWireguardDevice($0) }) - return - } - - let tunnelDeviceName = device.getInterfaceName() ?? "unknown" - - logger.info("Tunnel interface is \(tunnelDeviceName)") - - device.start(queue: dispatchQueue, configuration: configuration) { (result) in - let result = result.map { device } - .mapError { PacketTunnelProviderError.startWireguardDevice($0) } - - completionHandler(result) - } - } } enum PacketTunnelProviderError: ChainedError { @@ -425,13 +368,13 @@ enum PacketTunnelProviderError: ChainedError { case setNetworkSettings(Error) /// Failure to start the Wireguard backend - case startWireguardDevice(WireguardDevice.Error) + case startWireguardAdapter(WireGuardAdapterError) /// Failure to stop the Wireguard backend - case stopWireguardDevice(WireguardDevice.Error) + case stopWireguardAdapter(WireGuardAdapterError) /// Failure to update the Wireguard configuration - case updateWireguardConfiguration(Error) + case updateWireguardConfiguration(WireGuardAdapterError) /// IPC handler failure case ipcHandler(PacketTunnelIpcHandler.Error) @@ -456,11 +399,11 @@ enum PacketTunnelProviderError: ChainedError { case .setNetworkSettings: return "Failure to set system network settings" - case .startWireguardDevice: - return "Failure to start the WireGuard device" + case .startWireguardAdapter: + return "Failure to start the WireGuard adapter" - case .stopWireguardDevice: - return "Failure to stop the WireGuard device" + case .stopWireguardAdapter: + return "Failure to stop the WireGuard adapter" case .updateWireguardConfiguration: return "Failure to update the Wireguard configuration" @@ -478,33 +421,37 @@ struct PacketTunnelConfiguration { } extension PacketTunnelConfiguration { - var wireguardConfig: WireguardConfiguration { + + var wgTunnelConfig: TunnelConfiguration { let mullvadEndpoint = selectorResult.endpoint var peers: [AnyIPEndpoint] = [.ipv4(mullvadEndpoint.ipv4Relay)] - if let ipv6Relay = mullvadEndpoint.ipv6Relay { peers.append(.ipv6(ipv6Relay)) } - let wireguardPeers = peers.map { - WireguardPeer( - endpoint: $0, - publicKey: selectorResult.endpoint.publicKey) + let peerConfigs = peers.map { (endpoint) -> PeerConfiguration in + let pubKey = PublicKey(rawValue: selectorResult.endpoint.publicKey)! + var peerConfig = PeerConfiguration(publicKey: pubKey) + peerConfig.endpoint = endpoint.wgEndpoint + peerConfig.allowedIPs = [ + IPAddressRange(from: "0.0.0.0/0")!, + IPAddressRange(from: "::/0")! + ] + return peerConfig } - return WireguardConfiguration( - privateKey: tunnelSettings.interface.privateKey, - peers: wireguardPeers, - allowedIPs: [ - IPAddressRange(address: IPv4Address.any, networkPrefixLength: 0), - IPAddressRange(address: IPv6Address.any, networkPrefixLength: 0) - ] - ) + let dnsServers: [IPAddress] = [mullvadEndpoint.ipv4Gateway, mullvadEndpoint.ipv6Gateway] + var interfaceConfig = InterfaceConfiguration(privateKey: tunnelSettings.interface.privateKey.privateKey) + interfaceConfig.listenPort = 0 + interfaceConfig.dns = dnsServers.map { DNSServer(address: $0) } + interfaceConfig.addresses = tunnelSettings.interface.addresses + + return TunnelConfiguration(name: nil, interface: interfaceConfig, peers: peerConfigs) } } struct PacketTunnelContext { - let wireguardDevice: WireguardDevice + let wgAdapter: WireGuardAdapter let keyRotationManager: AutomaticKeyRotationManager } @@ -603,3 +550,15 @@ extension RelaySelectorResult { } } +extension WireGuardLogLevel { + var loggerLevel: Logger.Level { + switch self { + case .debug: + return .debug + case .info: + return .info + case .error: + return .error + } + } +} diff --git a/ios/PacketTunnel/PacketTunnelSettingsGenerator.swift b/ios/PacketTunnel/PacketTunnelSettingsGenerator.swift index 602b71b9c2..b66ea65aaf 100644 --- a/ios/PacketTunnel/PacketTunnelSettingsGenerator.swift +++ b/ios/PacketTunnel/PacketTunnelSettingsGenerator.swift @@ -10,6 +10,7 @@ import Foundation import Network import NetworkExtension +import WireGuardKit struct PacketTunnelSettingsGenerator { let mullvadEndpoint: MullvadEndpoint diff --git a/ios/PacketTunnel/WireguardCommand.swift b/ios/PacketTunnel/WireguardCommand.swift deleted file mode 100644 index b80f476adf..0000000000 --- a/ios/PacketTunnel/WireguardCommand.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// WireguardCommand.swift -// PacketTunnel -// -// Created by pronebird on 24/06/2019. -// Copyright © 2019 Mullvad VPN AB. All rights reserved. -// - -import Foundation -import Network - -struct WireguardPeer: Hashable { - let endpoint: AnyIPEndpoint - let publicKey: Data -} - -extension WireguardPeer { - - func withResolvedEndpoint() -> Result<WireguardPeer, Error> { - return self.endpoint.withResolvedIP().map { (endpoint) -> WireguardPeer in - return WireguardPeer(endpoint: endpoint, publicKey: self.publicKey) - } - } - -} - -enum WireguardCommand { - case privateKey(WireguardPrivateKey) - case listenPort(UInt16) - case replacePeers - case peer(WireguardPeer) - case replaceAllowedIPs - case allowedIP(IPAddressRange) -} - -extension WireguardCommand { - - func toRawWireguardCommand() -> String { - switch self { - case .privateKey(let privateKey): - let keyString = privateKey.rawRepresentation.hexEncodedString() - - return "private_key=\(keyString)" - - case .listenPort(let port): - return "listen_port=\(port)" - - case .replacePeers: - return "replace_peers=true" - - case .peer(let peer): - let keyString = peer.publicKey.hexEncodedString() - - return ["public_key=\(keyString)", "endpoint=\(peer.endpoint)"] - .joined(separator: "\n") - - case .replaceAllowedIPs: - return "replace_allowed_ips=true" - - case .allowedIP(let ipAddressRange): - return "allowed_ip=\(ipAddressRange)" - } - } - -} - -extension Array where Element == WireguardCommand { - func toRawWireguardConfigString() -> String { - return map { $0.toRawWireguardCommand() } - .joined(separator: "\n") - } -} diff --git a/ios/PacketTunnel/WireguardConfiguration.swift b/ios/PacketTunnel/WireguardConfiguration.swift deleted file mode 100644 index a6a6aae08c..0000000000 --- a/ios/PacketTunnel/WireguardConfiguration.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// WireguardConfiguration.swift -// PacketTunnel -// -// Created by pronebird on 17/12/2019. -// Copyright © 2019 Mullvad VPN AB. All rights reserved. -// - -import Foundation - -/// A struct describing a basic WireGuard configuration -struct WireguardConfiguration { - var privateKey: WireguardPrivateKey - var peers: [WireguardPeer] - var allowedIPs: [IPAddressRange] -} - -extension WireguardConfiguration { - - /// Returns commands suitable for configuring WireGuard - func uapiConfiguration() -> [WireguardCommand] { - var commands: [WireguardCommand] = [ - .privateKey(privateKey), - .listenPort(0) - ] - - commands.append(.replacePeers) - peers.forEach { (peer) in - commands.append(.peer(peer)) - } - - commands.append(.replaceAllowedIPs) - allowedIPs.forEach { (ipAddressRange) in - commands.append(.allowedIP(ipAddressRange)) - } - - return commands - } - - /// Returns commands suitable for updating existing endpoints when roaming between networks - /// (i.e Wi-Fi, cellular) - func endpointUapiConfiguration() -> [WireguardCommand] { - var commands: [WireguardCommand] = [] - - peers.forEach { (peer) in - commands.append(.peer(peer)) - } - - return commands - } - -} diff --git a/ios/PacketTunnel/WireguardDevice.swift b/ios/PacketTunnel/WireguardDevice.swift deleted file mode 100644 index ebbf4896b7..0000000000 --- a/ios/PacketTunnel/WireguardDevice.swift +++ /dev/null @@ -1,418 +0,0 @@ -// -// WireguardDevice.swift -// PacketTunnel -// -// Created by pronebird on 16/12/2019. -// Copyright © 2019 Mullvad VPN AB. All rights reserved. -// - -import Foundation -import NetworkExtension -import Logging - -/// A class describing the `wireguard-go` interactions -/// -/// - Thread safety: -/// This class is thread safe. -class WireguardDevice { - - /// An error type describing the errors returned by `WireguardDevice` - enum Error: ChainedError { - /// A failure to obtain the tunnel device file descriptor - case cannotLocateSocketDescriptor - - /// A failure to start the Wireguard backend - case start(Int32) - - /// A failure that indicates that Wireguard has not been started yet - case notStarted - - /// A failure that indicates that Wireguard has already been started - case alreadyStarted - - /// A failure to resolve an endpoint - case resolveEndpoint(AnyIPEndpoint, Swift.Error) - - var errorDescription: String? { - switch self { - case .cannotLocateSocketDescriptor: - return "Cannot locate the socket file descriptor." - case .start(let wgErrorCode): - return "Failed to start Wireguard. Return code: \(wgErrorCode)" - case .notStarted: - return "Wireguard has not been started yet" - case .alreadyStarted: - return "Wireguard has already been started" - case .resolveEndpoint(let endpoint, _): - return "Failed to resolve the endpoint: \(endpoint)" - } - } - } - - /// A global Wireguard logger - /// It should only be accessed from the `loggingQueue` - private static var tunnelLogger: Logger? - - /// A logger used by WireguardDevice - private let logger = Logger(label: "WireguardDevice") - - /// A private queue used for Wireguard logging - private static let loggingQueue = DispatchQueue( - label: "net.mullvad.vpn.packet-tunnel.wireguard-device.global-logging-queue", - qos: .utility - ) - - /// A private queue used to synchronize access to `WireguardDevice` members - private let workQueue = DispatchQueue( - label: "net.mullvad.vpn.packet-tunnel.wireguard-device.work-queue" - ) - - /// Network routes monitor - private var networkMonitor: NWPathMonitor? - - /// A tunnel device source socket file descriptor - private let tunnelFileDescriptor: Int32 - - /// A wireguard internal handle returned by `wgTurnOn` that's used to associate the calls - /// with the specific Wireguard tunnel. - private var wireguardHandle: Int32? - - /// Active configuration - private var configuration: WireguardConfiguration? - - /// A flag that indicates that the device has started - private var isStarted = false - - /// A flag that indicates whether the last known network path was satisfied - private var isPathSatisfied = true - - /// Returns a Wireguard version - class var version: String { - String(cString: wgVersion()) - } - - /// Set global Wireguard log handler. - /// The given handler is dispatched on a background serial queue. - /// - /// - Thread safety: - /// This function is thread safe - class func setTunnelLogger(_ logger: Logger) { - WireguardDevice.loggingQueue.async { - WireguardDevice.tunnelLogger = logger - } - - wgSetLogger { (level, messagePtr) in - guard let message = messagePtr.map({ String(cString: $0) })? - .trimmingCharacters(in: .newlines) else { return } - let logLevel = WireguardLogLevel(rawValue: level) ?? .debug - - WireguardDevice.loggingQueue.async { - WireguardDevice.tunnelLogger?.log(level: logLevel.loggerLevel, Logger.Message(stringLiteral: message)) - } - } - } - - // MARK: - Initialization - - /// A designated initializer - class func fromPacketFlow(_ packetFlow: NEPacketTunnelFlow) -> Result<WireguardDevice, Error> { - if let fd = packetFlow.value(forKeyPath: "socket.fileDescriptor") as? Int32 { - return .success(.init(tunnelFileDescriptor: fd)) - } else { - return .failure(.cannotLocateSocketDescriptor) - } - } - - /// Private initializer - private init(tunnelFileDescriptor: Int32) { - self.tunnelFileDescriptor = tunnelFileDescriptor - } - - deinit { - networkMonitor?.cancel() - stopWireguardBackend() - } - - // MARK: - Public methods - - func start(queue: DispatchQueue?, configuration: WireguardConfiguration, completionHandler: @escaping (Result<(), Error>) -> Void) { - workQueue.async { - guard !self.isStarted else { - queue.performOnWrappedOrCurrentQueue { - completionHandler(.failure(.alreadyStarted)) - } - return - } - - assert(self.wireguardHandle == nil) - - let resolvedConfiguration = self.resolveConfiguration(configuration) - - switch self.startWireguardBackend(resolvedConfiguration: resolvedConfiguration) { - case .success: - self.isStarted = true - self.isPathSatisfied = true - self.configuration = configuration - - self.startNetworkMonitor() - - queue.performOnWrappedOrCurrentQueue { - completionHandler(.success(())) - } - - case .failure(let error): - queue.performOnWrappedOrCurrentQueue { - completionHandler(.failure(error)) - } - } - } - } - - func stop(queue: DispatchQueue?, completionHandler: @escaping (Result<(), Error>) -> Void) { - workQueue.async { - if self.isStarted { - self.networkMonitor?.cancel() - self.networkMonitor = nil - - self.stopWireguardBackend() - self.isStarted = false - - queue.performOnWrappedOrCurrentQueue { - completionHandler(.success(())) - } - } else { - queue.performOnWrappedOrCurrentQueue { - completionHandler(.failure(.notStarted)) - } - } - } - } - - func setConfiguration(_ newConfiguration: WireguardConfiguration, queue: DispatchQueue?, completionHandler: @escaping (Result<(), Error>) -> Void) { - workQueue.async { - if self.isStarted { - if let handle = self.wireguardHandle { - let resolvedConfiguration = self.resolveConfiguration(newConfiguration) - let commands = resolvedConfiguration.uapiConfiguration() - - Self.setWireguardConfig(handle: handle, commands: commands) - } - - self.configuration = newConfiguration - - queue.performOnWrappedOrCurrentQueue { - completionHandler(.success(())) - } - } else { - queue.performOnWrappedOrCurrentQueue { - completionHandler(.failure(.notStarted)) - } - } - } - } - - func getInterfaceName() -> String? { - var buffer = [UInt8](repeating: 0, count: Int(IFNAMSIZ)) - - return buffer.withUnsafeMutableBufferPointer { (mutableBufferPointer) in - guard let baseAddress = mutableBufferPointer.baseAddress else { return nil } - - var ifnameSize = socklen_t(IFNAMSIZ) - let result = getsockopt( - self.tunnelFileDescriptor, - 2 /* SYSPROTO_CONTROL */, - 2 /* UTUN_OPT_IFNAME */, - baseAddress, - &ifnameSize) - - if result == 0 { - return String(cString: baseAddress) - } else { - return nil - } - } - } - - // MARK: - Private methods - - private func startWireguardBackend(resolvedConfiguration: WireguardConfiguration) -> Result<(), Error> { - assert(self.wireguardHandle == nil) - - let handle = resolvedConfiguration - .uapiConfiguration() - .toRawWireguardConfigString() - .withCString { wgTurnOn($0, self.tunnelFileDescriptor) } - - if handle >= 0 { - self.wireguardHandle = handle - - return .success(()) - } else { - return .failure(.start(handle)) - } - } - - private func stopWireguardBackend() { - guard let handle = self.wireguardHandle else { return } - - wgTurnOff(handle) - self.wireguardHandle = nil - } - - private class func setWireguardConfig(handle: Int32, commands: [WireguardCommand]) { - // Ignore empty payloads - guard !commands.isEmpty else { return } - - _ = commands.toRawWireguardConfigString() - .withCString { wgSetConfig(handle, $0) } - } - - private func resolveConfiguration(_ configuration: WireguardConfiguration) - -> WireguardConfiguration - { - return WireguardConfiguration( - privateKey: configuration.privateKey, - peers: resolvePeers(configuration.peers), - allowedIPs: configuration.allowedIPs - ) - } - - private func resolvePeers(_ peers: [WireguardPeer]) -> [WireguardPeer] { - var newPeers = [WireguardPeer]() - - for peer in peers { - switch resolvePeer(peer) { - case .success(let resolvedPeer): - newPeers.append(resolvedPeer) - case .failure(_): - // Fix me: ignore resolution error and carry on with the last known peer - newPeers.append(peer) - } - } - - return newPeers - } - - private func resolvePeer(_ peer: WireguardPeer) -> Result<WireguardPeer, Error> { - switch peer.withResolvedEndpoint() { - case .success(let resolvedPeer): - if "\(peer.endpoint.ip)" == "\(resolvedPeer.endpoint.ip)" { - logger.info("DNS64: mapped \(resolvedPeer.endpoint.ip) to itself") - } else { - logger.info("DNS64: mapped \(peer.endpoint.ip) to \(resolvedPeer.endpoint.ip)") - } - - return .success(resolvedPeer) - - case .failure(let error): - logger.error("DNS64: Failed to resolve the peer: \(peer.endpoint.ip). Error: \(error.localizedDescription)") - - return .failure(.resolveEndpoint(peer.endpoint, error)) - } - } - - // MARK: - Network monitoring - - private func startNetworkMonitor() { - self.networkMonitor?.cancel() - - let networkMonitor = NWPathMonitor() - networkMonitor.pathUpdateHandler = { [weak self] (path) in - self?.didReceiveNetworkPathUpdate(path: path) - } - networkMonitor.start(queue: workQueue) - self.networkMonitor = networkMonitor - } - - private func didReceiveNetworkPathUpdate(path: Network.NWPath) { - guard self.isStarted else { return } - - self.logger.info("Network change detected. Status: \(path.status), interfaces \(path.availableInterfaces).") - - let oldPathSatisfied = self.isPathSatisfied - let newPathSatisfied = path.status.isSatisfiable - - self.isPathSatisfied = newPathSatisfied - - switch (oldPathSatisfied, newPathSatisfied) { - case (true, false): - self.logger.info("Stop wireguard backend") - self.stopWireguardBackend() - - case (false, true), (true, true): - guard let currentConfiguration = self.configuration else { return } - - self.logger.info("Resolve endpoints") - - let resolvedConfiguration = self.resolveConfiguration(currentConfiguration) - - if let handle = self.wireguardHandle { - let commands = resolvedConfiguration.endpointUapiConfiguration() - Self.setWireguardConfig(handle: handle, commands: commands) - - wgBumpSockets(handle) - } else { - self.logger.info("Start wireguard backend") - - if case .failure(let error) = self.startWireguardBackend(resolvedConfiguration: resolvedConfiguration) { - self.logger.error(chainedError: error, message: "Failed to turn on WireGuard") - } - } - - case (false, false): - // No-op: device remains offline - break - } - } -} - -/// A enum describing Wireguard log levels defined in `api-ios.go` from `wireguard-apple` repository -enum WireguardLogLevel: Int32 { - case debug = 0 - case info = 1 - case error = 2 - - var loggerLevel: Logger.Level { - switch self { - case .debug: - return .debug - case .info: - return .info - case .error: - return .error - } - } -} - -private extension Network.NWPath.Status { - /// Returns `true` if the path is potentially satisfiable - var isSatisfiable: Bool { - switch self { - case .requiresConnection, .satisfied: - return true - case .unsatisfied: - return false - @unknown default: - return true - } - } -} - -extension Network.NWPath.Status: CustomDebugStringConvertible { - public var debugDescription: String { - var output = "NWPath.Status." - - switch self { - case .requiresConnection: - output += "requiresConnection" - case .satisfied: - output += "satisfied" - case .unsatisfied: - output += "unsatisfied" - @unknown default: - output += "unknown" - } - - return output - } -} diff --git a/ios/wireguard-go-bridge/.gitignore b/ios/wireguard-go-bridge/.gitignore deleted file mode 100644 index 5d25f8f5f9..0000000000 --- a/ios/wireguard-go-bridge/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.cache/ -.tmp/ -out/ diff --git a/ios/wireguard-go-bridge/Makefile b/ios/wireguard-go-bridge/Makefile deleted file mode 100644 index 108c58a7ea..0000000000 --- a/ios/wireguard-go-bridge/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0 -# -# Copyright (C) 2018-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. - -# These are generally passed to us by xcode, but we set working defaults for standalone compilation too. -ARCHS ?= arm64 armv7 -SDK_NAME ?= iphoneos -SDKROOT ?= $(shell xcrun --sdk $(SDK_NAME) --show-sdk-path) -CONFIGURATION_BUILD_DIR ?= $(CURDIR)/out -CONFIGURATION_TEMP_DIR ?= $(CURDIR)/.tmp - -export CC ?= clang -LIPO ?= lipo -DESTDIR ?= $(CONFIGURATION_BUILD_DIR) -BUILDDIR ?= $(CONFIGURATION_TEMP_DIR)/wireguard-go-bridge - -CFLAGS_PREFIX := $(if $(DEPLOYMENT_TARGET_CLANG_FLAG_NAME),-$(DEPLOYMENT_TARGET_CLANG_FLAG_NAME)=$($(DEPLOYMENT_TARGET_CLANG_ENV_NAME)),) -Wno-unused-command-line-argument -isysroot $(SDKROOT) -arch -GOARCH_arm64 := arm64 -GOARCH_armv7 := arm -GOARCH_x86_64 := amd64 - -build: $(DESTDIR)/libwg-go.a -version-header: $(DESTDIR)/wireguard-go-version.h - -REAL_GOROOT := $(shell go env GOROOT 2>/dev/null) -export GOROOT := $(BUILDDIR)/goroot -$(GOROOT)/.prepared: - [ -n "$(REAL_GOROOT)" ] - mkdir -p "$(GOROOT)" - rsync -a --delete --exclude=pkg/obj/go-build "$(REAL_GOROOT)/" "$(GOROOT)/" - cat goruntime-*.diff | patch -p1 -f -N -r- -d "$(GOROOT)" - touch "$@" - -define libwg-go-a -$(BUILDDIR)/libwg-go-$(1).a: export CGO_ENABLED := 1 -$(BUILDDIR)/libwg-go-$(1).a: export CGO_CFLAGS := $(CFLAGS_PREFIX) $(ARCH) -$(BUILDDIR)/libwg-go-$(1).a: export CGO_LDFLAGS := $(CFLAGS_PREFIX) $(ARCH) -$(BUILDDIR)/libwg-go-$(1).a: export GOOS := darwin -$(BUILDDIR)/libwg-go-$(1).a: export GOARCH := $(GOARCH_$(1)) -$(BUILDDIR)/libwg-go-$(1).a: $(GOROOT)/.prepared go.mod - go build -tags ios -ldflags=-w -trimpath -v -o "$(BUILDDIR)/libwg-go-$(1).a" -buildmode c-archive - rm -f "$(BUILDDIR)/libwg-go-$(1).h" -endef -$(foreach ARCH,$(ARCHS),$(eval $(call libwg-go-a,$(ARCH)))) - -$(DESTDIR)/wireguard-go-version.h: $(GOROOT)/.prepared go.mod - go list -m golang.zx2c4.com/wireguard | sed -n 's/.*v\([0-9.]*\).*/#define WIREGUARD_GO_VERSION "\1"/p' > "$@" - -$(DESTDIR)/libwg-go.a: $(foreach ARCH,$(ARCHS),$(BUILDDIR)/libwg-go-$(ARCH).a) - @mkdir -vp "$(DESTDIR)" - $(LIPO) -create -output "$@" $^ - -clean: - rm -rf "$(BUILDDIR)" "$(DESTDIR)/libwg-go.a" "$(DESTDIR)/wireguard-go-version.h" - -install: build - -.PHONY: clean build version-header install diff --git a/ios/wireguard-go-bridge/api-ios.go b/ios/wireguard-go-bridge/api-ios.go deleted file mode 100644 index d6eccd8f28..0000000000 --- a/ios/wireguard-go-bridge/api-ios.go +++ /dev/null @@ -1,193 +0,0 @@ -/* SPDX-License-Identifier: MIT - * - * Copyright (C) 2018-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. - */ - -package main - -// #include <stdlib.h> -// #include <sys/types.h> -// static void callLogger(void *func, int level, const char *msg) -// { -// ((void(*)(int, const char *))func)(level, msg); -// } -import "C" - -import ( - "bufio" - "bytes" - "errors" - "golang.org/x/sys/unix" - "golang.zx2c4.com/wireguard/device" - "golang.zx2c4.com/wireguard/tun" - "log" - "math" - "os" - "os/signal" - "runtime" - "strings" - "unsafe" -) - -var loggerFunc unsafe.Pointer -var versionString *C.char - -type CLogger struct { - level C.int -} - -func (l *CLogger) Write(p []byte) (int, error) { - if uintptr(loggerFunc) == 0 { - return 0, errors.New("No logger initialized") - } - message := C.CString(string(p)) - C.callLogger(loggerFunc, l.level, message) - C.free(unsafe.Pointer(message)) - return len(p), nil -} - -type tunnelHandle struct { - *device.Device - *device.Logger -} - -var tunnelHandles = make(map[int32]tunnelHandle) - -func init() { - versionString = C.CString(device.WireGuardGoVersion) - device.RoamingDisabled = true - signals := make(chan os.Signal) - signal.Notify(signals, unix.SIGUSR2) - go func() { - buf := make([]byte, os.Getpagesize()) - for { - select { - case <-signals: - n := runtime.Stack(buf, true) - buf[n] = 0 - if uintptr(loggerFunc) != 0 { - C.callLogger(loggerFunc, 0, (*C.char)(unsafe.Pointer(&buf[0]))) - } - } - } - }() -} - -//export wgEnableRoaming -func wgEnableRoaming(enabled bool) { - device.RoamingDisabled = !enabled -} - -//export wgSetLogger -func wgSetLogger(loggerFn uintptr) { - loggerFunc = unsafe.Pointer(loggerFn) -} - -//export wgTurnOn -func wgTurnOn(settings *C.char, tunFd int32) int32 { - logger := &device.Logger{ - Debug: log.New(&CLogger{level: 0}, "", 0), - Info: log.New(&CLogger{level: 1}, "", 0), - Error: log.New(&CLogger{level: 2}, "", 0), - } - dupTunFd, err := unix.Dup(int(tunFd)) - if err != nil { - logger.Error.Println(err) - return -1 - } - - err = unix.SetNonblock(dupTunFd, true) - if err != nil { - logger.Error.Println(err) - unix.Close(dupTunFd) - return -1 - } - tun, err := tun.CreateTUNFromFile(os.NewFile(uintptr(dupTunFd), "/dev/tun"), 0) - if err != nil { - logger.Error.Println(err) - unix.Close(dupTunFd) - return -1 - } - logger.Info.Println("Attaching to interface") - device := device.NewDevice(tun, logger) - - setError := device.IpcSetOperation(bufio.NewReader(strings.NewReader(C.GoString(settings)))) - if setError != nil { - logger.Error.Println(setError) - unix.Close(dupTunFd) - return -1 - } - - device.Up() - logger.Info.Println("Device started") - - var i int32 - for i = 0; i < math.MaxInt32; i++ { - if _, exists := tunnelHandles[i]; !exists { - break - } - } - if i == math.MaxInt32 { - unix.Close(dupTunFd) - return -1 - } - tunnelHandles[i] = tunnelHandle{device, logger} - return i -} - -//export wgTurnOff -func wgTurnOff(tunnelHandle int32) { - device, ok := tunnelHandles[tunnelHandle] - if !ok { - return - } - delete(tunnelHandles, tunnelHandle) - device.Close() -} - -//export wgSetConfig -func wgSetConfig(tunnelHandle int32, settings *C.char) int64 { - device, ok := tunnelHandles[tunnelHandle] - if !ok { - return 0 - } - err := device.IpcSetOperation(bufio.NewReader(strings.NewReader(C.GoString(settings)))) - if err != nil { - device.Error.Println(err) - return err.ErrorCode() - } - return 0 -} - -//export wgGetConfig -func wgGetConfig(tunnelHandle int32) *C.char { - device, ok := tunnelHandles[tunnelHandle] - if !ok { - return nil - } - settings := new(bytes.Buffer) - writer := bufio.NewWriter(settings) - err := device.IpcGetOperation(writer) - if err != nil { - return nil - } - writer.Flush() - return C.CString(settings.String()) -} - -//export wgBumpSockets -func wgBumpSockets(tunnelHandle int32) { - device, ok := tunnelHandles[tunnelHandle] - if !ok { - return - } - device.BindUpdate() - device.SendKeepalivesToPeersWithCurrentKeypair() -} - -//export wgVersion -func wgVersion() *C.char { - return versionString -} - -func main() {} diff --git a/ios/wireguard-go-bridge/go.mod b/ios/wireguard-go-bridge/go.mod deleted file mode 100644 index eddf20c4e6..0000000000 --- a/ios/wireguard-go-bridge/go.mod +++ /dev/null @@ -1,10 +0,0 @@ -module golang.zx2c4.com/wireguard/ios - -go 1.13 - -require ( - golang.org/x/crypto v0.0.0-20200117160349-530e935923ad // indirect - golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect - golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 - golang.zx2c4.com/wireguard v0.0.20200121 -) diff --git a/ios/wireguard-go-bridge/go.sum b/ios/wireguard-go-bridge/go.sum deleted file mode 100644 index 74b3b2837c..0000000000 --- a/ios/wireguard-go-bridge/go.sum +++ /dev/null @@ -1,22 +0,0 @@ -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc h1:c0o/qxkaO2LF5t6fQrT4b5hzyggAkLLlCUjqfRxd8Q4= -golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200117160349-530e935923ad h1:Jh8cai0fqIK+f6nG0UgPW5wFk8wmiMhM3AyciDBdtQg= -golang.org/x/crypto v0.0.0-20200117160349-530e935923ad/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20191003171128-d98b1b443823 h1:Ypyv6BNJh07T1pUSrehkLemqPKXhus2MkfktJ91kRh4= -golang.org/x/net v0.0.0-20191003171128-d98b1b443823/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa h1:F+8P+gmewFQYRk6JoLQLwjBCTu3mcIURZfNkVweuRKA= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191003212358-c178f38b412c h1:6Zx7DRlKXf79yfxuQ/7GqV3w2y7aDsk6bGg0MzF5RVU= -golang.org/x/sys v0.0.0-20191003212358-c178f38b412c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 h1:1/DFK4b7JH8DmkqhUk48onnSfrPzImPoVxuomtbT2nk= -golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.zx2c4.com/wireguard v0.0.20200121 h1:vcswa5Q6f+sylDfjqyrVNNrjsFUUbPsgAQTBCAg/Qf8= -golang.zx2c4.com/wireguard v0.0.20200121/go.mod h1:P2HsVp8SKwZEufsnezXZA4GRX/T49/HlU7DGuelXsU4= diff --git a/ios/wireguard-go-bridge/goruntime-boottime-over-monotonic.diff b/ios/wireguard-go-bridge/goruntime-boottime-over-monotonic.diff deleted file mode 100644 index 71b4ebf64e..0000000000 --- a/ios/wireguard-go-bridge/goruntime-boottime-over-monotonic.diff +++ /dev/null @@ -1,87 +0,0 @@ -From 04f5695b83cd221e99e9fa6171b57e45177d5ad3 Mon Sep 17 00:00:00 2001 -From: "Jason A. Donenfeld" <Jason@zx2c4.com> -Date: Wed, 27 Feb 2019 05:33:01 +0100 -Subject: [PATCH] runtime: use libc_mach_continuous_time in nanotime on Darwin - -This makes timers account for having expired while a computer was -asleep, which is quite common on mobile devices. Note that -continuous_time absolute_time, except that it takes into account -time spent in suspend. - -Fixes #24595 ---- - src/runtime/sys_darwin.go | 2 +- - src/runtime/sys_darwin_386.s | 2 +- - src/runtime/sys_darwin_amd64.s | 2 +- - src/runtime/sys_darwin_arm.s | 2 +- - src/runtime/sys_darwin_arm64.s | 2 +- - 5 files changed, 5 insertions(+), 5 deletions(-) - -diff --git a/src/runtime/sys_darwin.go b/src/runtime/sys_darwin.go -index 376f76dbc5..a0677a83f6 100644 ---- a/src/runtime/sys_darwin.go -+++ b/src/runtime/sys_darwin.go -@@ -431,7 +431,7 @@ func setNonblock(fd int32) { - //go:cgo_import_dynamic libc_usleep usleep "/usr/lib/libSystem.B.dylib" - - //go:cgo_import_dynamic libc_mach_timebase_info mach_timebase_info "/usr/lib/libSystem.B.dylib" --//go:cgo_import_dynamic libc_mach_absolute_time mach_absolute_time "/usr/lib/libSystem.B.dylib" -+//go:cgo_import_dynamic libc_mach_continuous_time mach_continuous_time "/usr/lib/libSystem.B.dylib" - //go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" - //go:cgo_import_dynamic libc_sigaction sigaction "/usr/lib/libSystem.B.dylib" - //go:cgo_import_dynamic libc_pthread_sigmask pthread_sigmask "/usr/lib/libSystem.B.dylib" -diff --git a/src/runtime/sys_darwin_386.s b/src/runtime/sys_darwin_386.s -index e653c54f61..5a43fcbdc1 100644 ---- a/src/runtime/sys_darwin_386.s -+++ b/src/runtime/sys_darwin_386.s -@@ -199,7 +199,7 @@ TEXT runtime·nanotime_trampoline(SB),NOSPLIT,$0 - PUSHL BP - MOVL SP, BP - SUBL $8+(machTimebaseInfo__size+15)/16*16, SP -- CALL libc_mach_absolute_time(SB) -+ CALL libc_mach_continuous_time(SB) - MOVL 16+(machTimebaseInfo__size+15)/16*16(SP), CX - MOVL AX, 0(CX) - MOVL DX, 4(CX) -diff --git a/src/runtime/sys_darwin_amd64.s b/src/runtime/sys_darwin_amd64.s -index 87c8db8c82..f962f24339 100644 ---- a/src/runtime/sys_darwin_amd64.s -+++ b/src/runtime/sys_darwin_amd64.s -@@ -97,7 +97,7 @@ TEXT runtime·nanotime_trampoline(SB),NOSPLIT,$0 - PUSHQ BP - MOVQ SP, BP - MOVQ DI, BX -- CALL libc_mach_absolute_time(SB) -+ CALL libc_mach_continuous_time(SB) - MOVQ AX, 0(BX) - MOVL timebase<>+machTimebaseInfo_numer(SB), SI - MOVL timebase<>+machTimebaseInfo_denom(SB), DI // atomic read -diff --git a/src/runtime/sys_darwin_arm.s b/src/runtime/sys_darwin_arm.s -index 996f8028a3..5bd34b51be 100644 ---- a/src/runtime/sys_darwin_arm.s -+++ b/src/runtime/sys_darwin_arm.s -@@ -126,7 +126,7 @@ GLOBL timebase<>(SB),NOPTR,$(machTimebaseInfo__size) - - TEXT runtime·nanotime_trampoline(SB),NOSPLIT,$0 - MOVW R0, R8 -- BL libc_mach_absolute_time(SB) -+ BL libc_mach_continuous_time(SB) - MOVW R0, 0(R8) - MOVW R1, 4(R8) - MOVW timebase<>+machTimebaseInfo_numer(SB), R6 -diff --git a/src/runtime/sys_darwin_arm64.s b/src/runtime/sys_darwin_arm64.s -index ac3ca74f63..5e91540f94 100644 ---- a/src/runtime/sys_darwin_arm64.s -+++ b/src/runtime/sys_darwin_arm64.s -@@ -121,7 +121,7 @@ GLOBL timebase<>(SB),NOPTR,$(machTimebaseInfo__size) - - TEXT runtime·nanotime_trampoline(SB),NOSPLIT,$40 - MOVD R0, R19 -- BL libc_mach_absolute_time(SB) -+ BL libc_mach_continuous_time(SB) - MOVD R0, 0(R19) - MOVW timebase<>+machTimebaseInfo_numer(SB), R20 - MOVD $timebase<>+machTimebaseInfo_denom(SB), R21 --- -2.23.0 - diff --git a/ios/wireguard-go-bridge/wireguard.h b/ios/wireguard-go-bridge/wireguard.h deleted file mode 100644 index 5c30ee91bd..0000000000 --- a/ios/wireguard-go-bridge/wireguard.h +++ /dev/null @@ -1,23 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 - * - * Copyright (C) 2018-2019 WireGuard LLC. All Rights Reserved. - */ - -#ifndef WIREGUARD_H -#define WIREGUARD_H - -#include <sys/types.h> -#include <stdint.h> -#include <stdbool.h> - -typedef void(*logger_fn_t)(int level, const char *msg); -extern void wgEnableRoaming(bool enabled); -extern void wgSetLogger(logger_fn_t logger_fn); -extern int wgTurnOn(const char *settings, int32_t tun_fd); -extern void wgTurnOff(int handle); -extern int64_t wgSetConfig(int handle, const char *settings); -extern char *wgGetConfig(int handle); -extern void wgBumpSockets(int handle); -extern const char *wgVersion(); - -#endif |
