-
Notifications
You must be signed in to change notification settings - Fork 389
/
Copy pathWgAdapter.swift
169 lines (140 loc) · 5.12 KB
/
WgAdapter.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
//
// WgAdapter.swift
// PacketTunnel
//
// Created by pronebird on 29/08/2023.
// Copyright © 2023 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadLogging
import MullvadTypes
import NetworkExtension
import PacketTunnelCore
import WireGuardKit
struct WgAdapter: TunnelAdapterProtocol {
let logger = Logger(label: "WgAdapter")
let adapter: WireGuardAdapter
init(packetTunnelProvider: NEPacketTunnelProvider) {
let wgGoLogger = Logger(label: "WireGuard")
adapter = WireGuardAdapter(
with: packetTunnelProvider,
shouldHandleReasserting: false,
logHandler: { logLevel, string in
wgGoLogger.log(level: logLevel.loggerLevel, "\(string)")
}
)
}
func start(configuration: TunnelAdapterConfiguration) async throws {
let wgConfig = configuration.asWgConfig
do {
try await adapter.stop()
try await adapter.start(tunnelConfiguration: wgConfig)
} catch WireGuardAdapterError.invalidState {
try await adapter.start(tunnelConfiguration: wgConfig)
}
let tunAddresses = wgConfig.interface.addresses.map { $0.address }
// TUN addresses can be empty when adapter is configured for blocked state.
if !tunAddresses.isEmpty {
logIfDeviceHasSameIP(than: tunAddresses)
}
}
func stop() async throws {
try await adapter.stop()
}
private func logIfDeviceHasSameIP(than addresses: [IPAddress]) {
let sameIPv4 = IPv4Address("10.127.255.254")
let sameIPv6 = IPv6Address("fc00:bbbb:bbbb:bb01:ffff:ffff:ffff:ffff")
let hasIPv4SameAddress = addresses.compactMap { $0 as? IPv4Address }
.contains { $0 == sameIPv4 }
let hasIPv6SameAddress = addresses.compactMap { $0 as? IPv6Address }
.contains { $0 == sameIPv6 }
let isUsingSameIP = (hasIPv4SameAddress || hasIPv6SameAddress) ? "" : "NOT "
logger.debug("Same IP is \(isUsingSameIP)being used")
}
}
extension WgAdapter: TunnelDeviceInfoProtocol {
var interfaceName: String? {
return adapter.interfaceName
}
func getStats() throws -> WgStats {
var result: String?
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
adapter.getRuntimeConfiguration { string in
result = string
dispatchGroup.leave()
}
guard case .success = dispatchGroup.wait(wallTimeout: .now() + 1) else { throw StatsError.timeout }
guard let result else { throw StatsError.nilValue }
guard let newStats = WgStats(from: result) else { throw StatsError.parse }
return newStats
}
enum StatsError: LocalizedError {
case timeout, nilValue, parse
var errorDescription: String? {
switch self {
case .timeout:
return "adapter.getRuntimeConfiguration() timeout."
case .nilValue:
return "Received nil string for stats."
case .parse:
return "Couldn't parse stats."
}
}
}
}
private extension TunnelAdapterConfiguration {
var asWgConfig: TunnelConfiguration {
var interfaceConfig = InterfaceConfiguration(privateKey: privateKey)
interfaceConfig.addresses = interfaceAddresses
interfaceConfig.dns = dns.map { DNSServer(address: $0) }
interfaceConfig.listenPort = 0
var peers: [PeerConfiguration] = []
if let peer {
var peerConfig = PeerConfiguration(publicKey: peer.publicKey)
peerConfig.endpoint = peer.endpoint.wgEndpoint
peerConfig.allowedIPs = allowedIPs
peers.append(peerConfig)
}
return TunnelConfiguration(
name: nil,
interface: interfaceConfig,
peers: peers
)
}
}
private extension AnyIPEndpoint {
var wgEndpoint: Endpoint {
switch self {
case let .ipv4(endpoint):
return Endpoint(host: .ipv4(endpoint.ip), port: .init(integerLiteral: endpoint.port))
case let .ipv6(endpoint):
return Endpoint(host: .ipv6(endpoint.ip), port: .init(integerLiteral: endpoint.port))
}
}
}
private extension WgStats {
init?(from string: String) {
var bytesReceived: UInt64?
var bytesSent: UInt64?
string.enumerateLines { line, stop in
if bytesReceived == nil, let value = parseValue("rx_bytes=", in: line) {
bytesReceived = value
} else if bytesSent == nil, let value = parseValue("tx_bytes=", in: line) {
bytesSent = value
}
if bytesReceived != nil, bytesSent != nil {
stop = true
}
}
guard let bytesReceived, let bytesSent else {
return nil
}
self.init(bytesReceived: bytesReceived, bytesSent: bytesSent)
}
}
@inline(__always) private func parseValue(_ prefixKey: String, in line: String) -> UInt64? {
guard line.hasPrefix(prefixKey) else { return nil }
let value = line.dropFirst(prefixKey.count)
return UInt64(value)
}