aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift
blob: 8cc07d2a8720f819c8a0f64c1573179c5fe7ab59 (plain) (blame)
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// SPDX-License-Identifier: MIT
// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved.

import Foundation
import Network
import NetworkExtension
import os.log

class PacketTunnelProvider: NEPacketTunnelProvider {

    private let dispatchQueue = DispatchQueue(label: "PacketTunnel", qos: .utility)

    private var handle: Int32?
    private var networkMonitor: NWPathMonitor?
    private var ifname: String?
    private var packetTunnelSettingsGenerator: PacketTunnelSettingsGenerator?

    deinit {
        networkMonitor?.cancel()
    }

    override func startTunnel(options: [String: NSObject]?, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
        dispatchQueue.async {
            let activationAttemptId = options?["activationAttemptId"] as? String
            let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId)

            guard let tunnelProviderProtocol = self.protocolConfiguration as? NETunnelProviderProtocol,
                let tunnelConfiguration = tunnelProviderProtocol.asTunnelConfiguration() else {
                    errorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
                    startTunnelCompletionHandler(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
                    return
            }

            self.configureLogger()
            #if os(macOS)
            wgEnableRoaming(true)
            #endif

            wg_log(.info, message: "Starting tunnel from the " + (activationAttemptId == nil ? "OS directly, rather than the app" : "app"))

            let endpoints = tunnelConfiguration.peers.map { $0.endpoint }
            guard let resolvedEndpoints = DNSResolver.resolveSync(endpoints: endpoints) else {
                errorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure)
                startTunnelCompletionHandler(PacketTunnelProviderError.dnsResolutionFailure)
                return
            }
            assert(endpoints.count == resolvedEndpoints.count)

            self.packetTunnelSettingsGenerator = PacketTunnelSettingsGenerator(tunnelConfiguration: tunnelConfiguration, resolvedEndpoints: resolvedEndpoints)

            self.setTunnelNetworkSettings(self.packetTunnelSettingsGenerator!.generateNetworkSettings()) { error in
                self.dispatchQueue.async {
                    if let error = error {
                        wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)")
                        errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings)
                        startTunnelCompletionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings)
                    } else {
                        self.networkMonitor = NWPathMonitor()
                        self.networkMonitor!.pathUpdateHandler = { [weak self] path in
                            self?.pathUpdate(path: path)
                        }
                        self.networkMonitor!.start(queue: self.dispatchQueue)

                        let fileDescriptor = (self.packetFlow.value(forKeyPath: "socket.fileDescriptor") as? Int32) ?? -1
                        if fileDescriptor < 0 {
                            wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor")
                            errorNotifier.notify(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
                            startTunnelCompletionHandler(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
                            return
                        }

                        self.ifname = Self.getInterfaceName(fileDescriptor: fileDescriptor)
                        wg_log(.info, message: "Tunnel interface is \(self.ifname ?? "unknown")")

                        let handle = self.packetTunnelSettingsGenerator!.uapiConfiguration()
                            .withCString { return wgTurnOn($0, fileDescriptor) }
                        if handle < 0 {
                            wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(handle)")
                            errorNotifier.notify(PacketTunnelProviderError.couldNotStartBackend)
                            startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartBackend)
                            return
                        }
                        self.handle = handle
                        startTunnelCompletionHandler(nil)
                    }
                }
            }
        }
    }

    override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
        dispatchQueue.async {
            self.networkMonitor?.cancel()
            self.networkMonitor = nil

            ErrorNotifier.removeLastErrorFile()

            wg_log(.info, staticMessage: "Stopping tunnel")
            if let handle = self.handle {
                wgTurnOff(handle)
            }
            completionHandler()

            #if os(macOS)
            // HACK: This is a filthy hack to work around Apple bug 32073323 (dup'd by us as 47526107).
            // Remove it when they finally fix this upstream and the fix has been rolled out to
            // sufficient quantities of users.
            exit(0)
            #endif
        }
    }

    override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {
        dispatchQueue.async {
            guard let completionHandler = completionHandler else { return }
            guard let handle = self.handle else {
                completionHandler(nil)
                return
            }

            if messageData.count == 1 && messageData[0] == 0 {
                if let settings = wgGetConfig(handle) {
                    let data = String(cString: settings).data(using: .utf8)!
                    completionHandler(data)
                    free(settings)
                } else {
                    completionHandler(nil)
                }
            } else {
                completionHandler(nil)
            }
        }
    }

    private class func getInterfaceName(fileDescriptor: Int32) -> String? {
        var ifnameBytes = [CChar](repeating: 0, count: Int(IF_NAMESIZE))

        return ifnameBytes.withUnsafeMutableBufferPointer { bufferPointer -> String? in
            guard let baseAddress = bufferPointer.baseAddress else { return nil }

            var ifnameSize = socklen_t(bufferPointer.count)
            let result = getsockopt(
                fileDescriptor,
                2 /* SYSPROTO_CONTROL */,
                2 /* UTUN_OPT_IFNAME */,
                baseAddress, &ifnameSize
            )

            if result == 0 {
                return String(cString: baseAddress)
            } else {
                return nil
            }
        }
    }

    private func configureLogger() {
        Logger.configureGlobal(tagged: "NET", withFilePath: FileManager.logFileURL?.path)
        wgSetLogger { level, msgC in
            guard let msgC = msgC else { return }
            let logType: OSLogType
            switch level {
            case 0:
                logType = .debug
            case 1:
                logType = .info
            case 2:
                logType = .error
            default:
                logType = .default
            }
            wg_log(logType, message: String(cString: msgC))
        }
    }

    private func pathUpdate(path: Network.NWPath) {
        guard let handle = handle else { return }
        wg_log(.debug, message: "Network change detected with \(path.status) route and interface order \(path.availableInterfaces)")

        #if os(iOS)
        if let packetTunnelSettingsGenerator = packetTunnelSettingsGenerator {
            _ = packetTunnelSettingsGenerator.endpointUapiConfiguration()
                .withCString { return wgSetConfig(handle, $0) }
        }
        #endif
        wgBumpSockets(handle)
    }
}