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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
|
//
// AutomaticKeyRotationManager.swift
// MullvadVPN
//
// Created by pronebird on 05/05/2020.
// Copyright © 2020 Mullvad VPN AB. All rights reserved.
//
import Combine
import Foundation
import os
/// A private key rotation retry interval on failure (in seconds)
private let kRetryIntervalOnFailure = 300
/// A private key rotation interval (in days)
private let kRotationInterval = 4
class AutomaticKeyRotationManager {
enum Error: Swift.Error {
/// An RPC failure
case rpc(MullvadRpc.Error)
/// A failure to read the tunnel configuration
case readTunnelConfiguration(TunnelConfigurationManager.Error)
/// A failure to update tunnel configuration
case updateTunnelConfiguration(TunnelConfigurationManager.Error)
var localizedDescription: String {
switch self {
case .rpc(let error):
return "Rpc error: \(error.localizedDescription)"
case .readTunnelConfiguration(let error):
return "Read configuration error: \(error.localizedDescription)"
case .updateTunnelConfiguration(let error):
return "Update configuration error: \(error.localizedDescription)"
}
}
}
struct KeyRotationEvent {
var isNew: Bool
var creationDate: Date
var publicKey: WireguardPublicKey
}
private let rpc = MullvadRpc.withEphemeralURLSession()
private let persistentKeychainReference: Data
private var rotateKeySubscriber: AnyCancellable?
/// A dispatch queue used for synchronization
private let dispatchQueue = DispatchQueue(label: "net.mullvad.vpn.key-manager", qos: .background)
/// A timer source used to schedule a delayed key rotation
private var timerSource: DispatchSourceTimer?
/// Internal lock used for access synchronization to public members of this class
private let lock = NSLock()
/// Internal variable indicating that the key rotation has already started
private var isAutomaticRotationEnabled = false
/// A variable backing the `eventHandler` public property
private var _eventHandler: ((KeyRotationEvent) -> Void)?
/// An event handler that's invoked when key rotation occurred
var eventHandler: ((KeyRotationEvent) -> Void)? {
get {
lock.withCriticalBlock {
self._eventHandler
}
}
set {
lock.withCriticalBlock {
self._eventHandler = newValue
}
}
}
init(persistentKeychainReference: Data) {
self.persistentKeychainReference = persistentKeychainReference
}
func startAutomaticRotation() {
dispatchQueue.async {
guard !self.isAutomaticRotationEnabled else { return }
os_log(.default, log: tunnelProviderLog, "Start automatic key rotation")
self.isAutomaticRotationEnabled = true
self.performKeyRotation()
}
}
func stopAutomaticRotation() {
dispatchQueue.async {
guard self.isAutomaticRotationEnabled else { return }
os_log(.default, log: tunnelProviderLog, "Stop automatic key rotation")
self.isAutomaticRotationEnabled = false
self.rotateKeySubscriber?.cancel()
self.timerSource?.cancel()
}
}
private func performKeyRotation() {
rotateKeySubscriber = tryRotatingPrivateKey()
.receive(on: dispatchQueue)
.sink(receiveCompletion: { [weak self] (completion) in
guard let self = self else { return }
switch completion {
case .finished:
break
case .failure(let error):
os_log(.error, log: tunnelProviderLog,
"Failed to rotate the private key: %{public}s. Retry in %d seconds.",
error.localizedDescription,
kRetryIntervalOnFailure)
self.scheduleRetry(wallDeadline: .now() + .seconds(kRetryIntervalOnFailure))
}
}) { [weak self] (keyRotationEvent) in
guard let self = self else { return }
if keyRotationEvent.isNew {
os_log(.default, log: tunnelProviderLog, "Finished private key rotation")
self.eventHandler?(keyRotationEvent)
}
if let rotationDate = Self.nextRotation(creationDate: keyRotationEvent.creationDate) {
let interval = rotationDate.timeIntervalSinceNow
os_log(.default, log: tunnelProviderLog,
"Next private key rotation on %{public}s", "\(rotationDate)")
self.scheduleRetry(wallDeadline: .now() + .seconds(Int(interval)))
} else {
os_log(.error, log: tunnelProviderLog,
"Failed to compute the next private rotation date. Retry in %d seconds.")
self.scheduleRetry(wallDeadline: .now() + .seconds(kRetryIntervalOnFailure))
}
}
}
private func scheduleRetry(wallDeadline: DispatchWallTime) {
let timerSource = DispatchSource.makeTimerSource(queue: dispatchQueue)
timerSource.setEventHandler { [weak self] in
self?.performKeyRotation()
}
timerSource.schedule(wallDeadline: wallDeadline)
timerSource.activate()
self.timerSource = timerSource
}
private func tryRotatingPrivateKey() -> AnyPublisher<KeyRotationEvent, Error> {
return TunnelConfigurationManager
.load(searchTerm: .persistentReference(persistentKeychainReference))
.mapError { .readTunnelConfiguration($0) }
.publisher
.flatMap { (keychainEntry) -> AnyPublisher<KeyRotationEvent, Error> in
let currentPrivateKey = keychainEntry.tunnelConfiguration.interface.privateKey
if Self.shouldRotateKey(creationDate: currentPrivateKey.creationDate) {
return self.replaceWireguardKey(
accountToken: keychainEntry.accountToken,
oldPublicKey: currentPrivateKey.publicKey
).map({ (newTunnelConfiguration) -> KeyRotationEvent in
let newPrivateKey = newTunnelConfiguration.interface.privateKey
return KeyRotationEvent(
isNew: true,
creationDate: newPrivateKey.creationDate,
publicKey: newPrivateKey.publicKey
)
}).eraseToAnyPublisher()
} else {
let result = KeyRotationEvent(
isNew: false,
creationDate: currentPrivateKey.creationDate,
publicKey: currentPrivateKey.publicKey
)
return Result.Publisher(result).eraseToAnyPublisher()
}
}.eraseToAnyPublisher()
}
private func replaceWireguardKey(accountToken: String, oldPublicKey: WireguardPublicKey)
-> AnyPublisher<TunnelConfiguration, Error>
{
let newPrivateKey = WireguardPrivateKey()
return rpc.replaceWireguardKey(
accountToken: accountToken,
oldPublicKey: oldPublicKey.rawRepresentation,
newPublicKey: newPrivateKey.publicKey.rawRepresentation)
.mapError { .rpc($0) }
.flatMap { (addresses) in
TunnelConfigurationManager
.update(searchTerm: .persistentReference(self.persistentKeychainReference))
{ (tunnelConfiguration) in
tunnelConfiguration.interface.privateKey = newPrivateKey
tunnelConfiguration.interface.addresses = [
addresses.ipv4Address,
addresses.ipv6Address
]
}
.mapError { .updateTunnelConfiguration($0) }
.publisher
}.eraseToAnyPublisher()
}
class func nextRotation(creationDate: Date) -> Date? {
return Calendar.current.date(byAdding: .day, value: kRotationInterval, to: creationDate)
}
class func shouldRotateKey(creationDate: Date) -> Bool {
return nextRotation(creationDate: creationDate)
.map { $0 <= Date() } ?? false
}
}
|