]> git.saurik.com Git - apple/security.git/blob - keychain/TrustedPeersHelper/Container_MachineIDs.swift
Security-59306.101.1.tar.gz
[apple/security.git] / keychain / TrustedPeersHelper / Container_MachineIDs.swift
1 import CoreData
2 import Foundation
3
4 extension MachineMO {
5 func modifiedInPast(hours: Int) -> Bool {
6 guard let modifiedDate = self.modified else {
7 return false
8 }
9
10 let dateLimit = Date(timeIntervalSinceNow: -60 * 60 * TimeInterval(hours))
11 return modifiedDate.compare(dateLimit) == ComparisonResult.orderedDescending
12 }
13
14 func modifiedDate() -> String {
15 guard let modifiedDate = self.modified else {
16 return "unknown"
17 }
18
19 let dateFormatter = ISO8601DateFormatter()
20 return dateFormatter.string(from: modifiedDate)
21 }
22
23 func asTPMachineID() -> TPMachineID {
24 return TPMachineID(machineID: self.machineID ?? "unknown",
25 status: TPMachineIDStatus(rawValue: UInt(self.status)) ?? .unknown,
26 modified: self.modified ?? Date())
27 }
28 }
29
30 // You get two days of grace before you're removed
31 let cutoffHours = 48
32
33 extension Container {
34 // CoreData suggests not using heavyweight migrations, so we have two locations to store the machine ID list.
35 // Perform our own migration from the no-longer-used field.
36 internal static func onqueueUpgradeMachineIDSetToModel(container: ContainerMO, moc: NSManagedObjectContext) {
37 let knownMachineMOs = container.machines as? Set<MachineMO> ?? Set()
38 let knownMachineIDs = Set(knownMachineMOs.compactMap { $0.machineID })
39
40 let allowedMachineIDs = container.allowedMachineIDs as? Set<String> ?? Set()
41 let missingIDs = allowedMachineIDs.filter { !knownMachineIDs.contains($0) }
42
43 missingIDs.forEach { id in
44 let mid = MachineMO(context: moc)
45 mid.machineID = id
46 mid.seenOnFullList = true
47 mid.status = Int64(TPMachineIDStatus.allowed.rawValue)
48 mid.modified = Date()
49 container.addToMachines(mid)
50 }
51
52 container.allowedMachineIDs = Set<String>() as NSSet
53 }
54
55 internal static func onqueueUpgradeMachineIDSetToUseStatus(container: ContainerMO, moc: NSManagedObjectContext) {
56 let knownMachineMOs = container.machines as? Set<MachineMO> ?? Set()
57
58 // Once we run this upgrade, we will set the allowed bool to false, since it's unused.
59 // Therefore, if we have a single record with "allowed" set, we haven't run the upgrade.
60 let runUpgrade = !knownMachineMOs.filter { $0.allowed }.isEmpty
61 if runUpgrade {
62 knownMachineMOs.forEach { mo in
63 if mo.allowed {
64 mo.status = Int64(TPMachineIDStatus.allowed.rawValue)
65 } else {
66 mo.status = Int64(TPMachineIDStatus.disallowed.rawValue)
67 }
68 mo.allowed = false
69 }
70 }
71 }
72
73 func enforceIDMSListChanges(knownMachines: Set<MachineMO>) -> Bool {
74 if self.containerMO.honorIDMSListChanges == "YES"{
75 return true
76 } else if self.containerMO.honorIDMSListChanges == "NO" {
77 return false
78 } else if self.containerMO.honorIDMSListChanges == "UNKNOWN" && knownMachines.isEmpty {
79 return false
80 } else if self.containerMO.honorIDMSListChanges == "UNKNOWN" && !knownMachines.isEmpty {
81 return true
82 } else {
83 return true
84 }
85 }
86
87 func setAllowedMachineIDs(_ allowedMachineIDs: Set<String>, honorIDMSListChanges: Bool, reply: @escaping (Bool, Error?) -> Void) {
88 self.semaphore.wait()
89 let reply: (Bool, Error?) -> Void = {
90 os_log("setAllowedMachineIDs complete: %{public}@", log: tplogTrace, type: .info, traceError($1))
91 self.semaphore.signal()
92 reply($0, $1)
93 }
94
95 os_log("Setting allowed machine IDs: %{public}@", log: tplogDebug, type: .default, allowedMachineIDs)
96
97 // Note: we currently ignore any machineIDs that are set in the model, but never appeared on the
98 // Trusted Devices list. We should give them a grace period (1wk?) then kick them out.
99
100 self.moc.performAndWait {
101 do {
102 var differences = false
103 self.containerMO.honorIDMSListChanges = honorIDMSListChanges ? "YES" : "NO"
104
105 var knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
106 let knownMachineIDs = Set(knownMachines.compactMap { $0.machineID })
107
108 knownMachines.forEach { machine in
109 guard let mid = machine.machineID else {
110 os_log("Machine has no ID: %{public}@", log: tplogDebug, type: .default, machine)
111 return
112 }
113 if allowedMachineIDs.contains(mid) {
114 if machine.status == TPMachineIDStatus.allowed.rawValue {
115 os_log("Machine ID still trusted: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
116 } else {
117 os_log("Machine ID newly retrusted: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
118 differences = true
119 }
120 machine.status = Int64(TPMachineIDStatus.allowed.rawValue)
121 machine.seenOnFullList = true
122 machine.modified = Date()
123 } else {
124 // This machine ID is not on the list. What, if anything, should be done?
125 if machine.status == TPMachineIDStatus.allowed.rawValue {
126 // IDMS sometimes has list consistency issues. So, if we see a device 'disappear' from the list, it may or may not
127 // actually have disappered: we may have received an 'add' push and then fetched the list too quickly.
128 // To hack around this, we track whether we've seen the machine on the full list yet. If we haven't, this was likely
129 // the result of an 'add' push, and will be given 48 hours of grace before being removed.
130 if machine.seenOnFullList {
131 machine.status = Int64(TPMachineIDStatus.disallowed.rawValue)
132 machine.modified = Date()
133 os_log("Newly distrusted machine ID: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
134 differences = true
135
136 } else {
137 if machine.modifiedInPast(hours: cutoffHours) {
138 os_log("Allowed-but-unseen machine ID isn't on full list, last modified %{public}@, ignoring: %{public}@", log: tplogDebug, type: .default, machine.modifiedDate(), String(describing: machine.machineID))
139 } else {
140 os_log("Allowed-but-unseen machine ID isn't on full list, last modified %{public}@, distrusting: %{public}@", log: tplogDebug, type: .default, machine.modifiedDate(), String(describing: machine.machineID))
141 machine.status = Int64(TPMachineIDStatus.disallowed.rawValue)
142 machine.modified = Date()
143 differences = true
144 }
145 }
146
147 } else if machine.status == TPMachineIDStatus.unknown.rawValue {
148 if machine.modifiedInPast(hours: cutoffHours) {
149 os_log("Unknown machine ID last modified %{public}@; leaving unknown: %{public}@", log: tplogDebug, type: .default, machine.modifiedDate(), String(describing: machine.machineID))
150 } else {
151 os_log("Unknown machine ID last modified %{public}@; distrusting: %{public}@", log: tplogDebug, type: .default, machine.modifiedDate(), String(describing: machine.machineID))
152 machine.status = Int64(TPMachineIDStatus.disallowed.rawValue)
153 machine.modified = Date()
154 differences = true
155 }
156 }
157 }
158 }
159
160 // Do we need to create any further objects?
161 allowedMachineIDs.forEach { machineID in
162 if !knownMachineIDs.contains(machineID) {
163 // We didn't know about this machine before; it's newly trusted!
164 let machine = MachineMO(context: self.moc)
165 machine.machineID = machineID
166 machine.container = containerMO
167 machine.seenOnFullList = true
168 machine.modified = Date()
169 machine.status = Int64(TPMachineIDStatus.allowed.rawValue)
170 os_log("Newly trusted machine ID: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
171 differences = true
172
173 self.containerMO.addToMachines(machine)
174 knownMachines.insert(machine)
175 }
176 }
177
178 if self.enforceIDMSListChanges(knownMachines: knownMachines) {
179 // Are there any machine IDs in the model that aren't in the list? If so, add them as "unknown"
180 let modelMachineIDs = self.model.allMachineIDs()
181 modelMachineIDs.forEach { peerMachineID in
182 if !knownMachineIDs.contains(peerMachineID) && !allowedMachineIDs.contains(peerMachineID) {
183 os_log("Peer machineID is unknown, beginning grace period: %{public}@", log: tplogDebug, type: .default, peerMachineID)
184 let machine = MachineMO(context: self.moc)
185 machine.machineID = peerMachineID
186 machine.container = containerMO
187 machine.seenOnFullList = false
188 machine.modified = Date()
189 machine.status = Int64(TPMachineIDStatus.unknown.rawValue)
190 differences = true
191
192 self.containerMO.addToMachines(machine)
193 }
194 }
195 } else {
196 os_log("Believe we're in a demo account, not enforcing IDMS list", log: tplogDebug, type: .default)
197 }
198
199 // We no longer use allowed machine IDs.
200 self.containerMO.allowedMachineIDs = NSSet()
201
202 try self.moc.save()
203
204 reply(differences, nil)
205 } catch {
206 os_log("Error setting machine ID list: %{public}@", log: tplogDebug, type: .default, (error as CVarArg?) ?? "no error")
207 reply(false, error)
208 }
209 }
210 }
211
212 func addAllow(_ machineIDs: [String], reply: @escaping (Error?) -> Void) {
213 self.semaphore.wait()
214 let reply: (Error?) -> Void = {
215 os_log("addAllow complete: %{public}@", log: tplogTrace, type: .info, traceError($0))
216 self.semaphore.signal()
217 reply($0)
218 }
219
220 os_log("Adding allowed machine IDs: %{public}@", log: tplogDebug, type: .default, machineIDs)
221
222 self.moc.performAndWait {
223 do {
224 var knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
225 let knownMachineIDs = Set(knownMachines.compactMap { $0.machineID })
226
227 // We treat an add push as authoritative (even though we should really confirm it with a full list fetch).
228 // We can get away with this as we're using this list as a deny-list, and if we accidentally don't deny someone fast enough, that's okay.
229 machineIDs.forEach { machineID in
230 if knownMachineIDs.contains(machineID) {
231 knownMachines.forEach { machine in
232 if machine.machineID == machineID {
233 machine.status = Int64(TPMachineIDStatus.allowed.rawValue)
234 machine.modified = Date()
235 os_log("Continue to trust machine ID: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
236 }
237 }
238
239 } else {
240 let machine = MachineMO(context: self.moc)
241 machine.machineID = machineID
242 machine.container = containerMO
243 machine.seenOnFullList = false
244 machine.modified = Date()
245 machine.status = Int64(TPMachineIDStatus.allowed.rawValue)
246 os_log("Newly trusted machine ID: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
247 self.containerMO.addToMachines(machine)
248
249 knownMachines.insert(machine)
250 }
251 }
252
253 try self.moc.save()
254 reply(nil)
255 } catch {
256 reply(error)
257 }
258 }
259 }
260
261 func removeAllow(_ machineIDs: [String], reply: @escaping (Error?) -> Void) {
262 self.semaphore.wait()
263 let reply: (Error?) -> Void = {
264 os_log("removeAllow complete: %{public}@", log: tplogTrace, type: .info, traceError($0))
265 self.semaphore.signal()
266 reply($0)
267 }
268
269 os_log("Removing allowed machine IDs: %{public}@", log: tplogDebug, type: .default, machineIDs)
270
271 self.moc.performAndWait {
272 do {
273 var knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
274 let knownMachineIDs = Set(knownMachines.compactMap { $0.machineID })
275
276 // This is an odd approach: we'd like to confirm that this MID was actually removed (and not just a delayed push).
277 // So, let's set the status to "unknown", and its modification date to the distant past.
278 // The next time we fetch the full list, we'll confirm the removal (or, if the removal push was spurious, re-add the MID as trusted).
279 machineIDs.forEach { machineID in
280 if knownMachineIDs.contains(machineID) {
281 knownMachines.forEach { machine in
282 if machine.machineID == machineID {
283 machine.status = Int64(TPMachineIDStatus.unknown.rawValue)
284 machine.modified = Date.distantPast
285 os_log("Now suspicious of machine ID: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
286 }
287 }
288
289 } else {
290 let machine = MachineMO(context: self.moc)
291 machine.machineID = machineID
292 machine.container = containerMO
293 machine.status = Int64(TPMachineIDStatus.unknown.rawValue)
294 machine.modified = Date.distantPast
295 os_log("Suspicious of new machine ID: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
296 self.containerMO.addToMachines(machine)
297
298 knownMachines.insert(machine)
299 }
300 }
301
302 try self.moc.save()
303 reply(nil)
304 } catch {
305 reply(error)
306 }
307 }
308 }
309
310 func fetchAllowedMachineIDs(reply: @escaping (Set<String>?, Error?) -> Void) {
311 self.semaphore.wait()
312 let reply: (Set<String>?, Error?) -> Void = {
313 os_log("fetchAllowedMachineIDs complete: %{public}@", log: tplogTrace, type: .info, traceError($1))
314 self.semaphore.signal()
315 reply($0, $1)
316 }
317
318 os_log("Fetching allowed machine IDs", log: tplogDebug, type: .default)
319
320 self.moc.performAndWait {
321 let knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
322 let allowedMachineIDs = knownMachines.filter { $0.status == Int64(TPMachineIDStatus.allowed.rawValue) }.compactMap { $0.machineID }
323
324 reply(Set(allowedMachineIDs), nil)
325 }
326 }
327
328 func onqueueMachineIDAllowedByIDMS(machineID: String) -> Bool {
329
330 // For Demo accounts, if the list is entirely empty, then everything is allowed
331 let knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
332
333 if !self.enforceIDMSListChanges(knownMachines: knownMachines) {
334 os_log("not enforcing idms list changes; allowing %{public}@", log: tplogDebug, type: .debug, machineID)
335 return true
336 }
337
338 // Note: this function rejects grey devices: machineIDs that are neither allowed nor disallowed
339 for mo in knownMachines where mo.machineID == machineID {
340 if mo.status == TPMachineIDStatus.allowed.rawValue {
341 return true
342 } else {
343 os_log("machineID %{public}@ not explicitly allowed: %{public}@", log: tplogDebug, type: .debug, machineID, mo)
344 return false
345 }
346 }
347
348 // Didn't find it? reject.
349 os_log("machineID %{public}@ not found on list", log: tplogDebug, type: .debug, machineID)
350 return false
351 }
352
353 func onqueueCurrentMIDList() -> TPMachineIDList {
354 let machines = containerMO.machines as? Set<MachineMO> ?? Set()
355 return TPMachineIDList(entries: machines.map { $0.asTPMachineID() })
356 }
357
358 func onqueueUpdateMachineIDListFromModel(dynamicInfo: TPPeerDynamicInfo) {
359 // This function is intended to be called once the model is in a steady state of adds and deletes.
360 //
361 // First, we should ensure that we've written down the MIDs of all trusted peers. That way, if they
362 // aren't on the MID list now, we'll start the timer for them to be removed if they never make it.
363 // (But! don't do this if we think this is a Demo account. Those don't have a list, and we shouldn't make one.)
364
365 // Second, we should remove all disallowed MIDs, as those values have been used.
366 // We don't want to automatically kick out new peers if they rejoin with the same MID.
367
368 let machines = containerMO.machines as? Set<MachineMO> ?? Set()
369 let knownMachineIDs = Set(machines.compactMap { $0.machineID })
370
371 // Peers trust themselves. So if the ego peer is in Octagon, its machineID will be in this set
372 let trustedMachineIDs = Set(dynamicInfo.includedPeerIDs.compactMap { self.model.peer(withID: $0)?.permanentInfo.machineID })
373
374 // if this account is not a demo account...
375 if self.enforceIDMSListChanges(knownMachines: machines) {
376 for peerMachineID in trustedMachineIDs.subtracting(knownMachineIDs) {
377 os_log("Peer machineID is unknown, beginning grace period: %{public}@", log: tplogDebug, type: .default, peerMachineID)
378 let machine = MachineMO(context: self.moc)
379 machine.machineID = peerMachineID
380 machine.container = self.containerMO
381 machine.seenOnFullList = false
382 machine.modified = Date()
383 machine.status = Int64(TPMachineIDStatus.unknown.rawValue)
384
385 self.containerMO.addToMachines(machine)
386 }
387 } else {
388 os_log("Not enforcing IDMS list changes", log: tplogDebug, type: .default)
389 }
390
391 for mo in (machines) where mo.status == TPMachineIDStatus.disallowed.rawValue {
392 os_log("Dropping knowledge of machineID %{public}@", log: tplogDebug, type: .debug, String(describing: mo.machineID))
393 self.containerMO.removeFromMachines(mo)
394 }
395 }
396
397 // Computes if a full list fetch would be 'useful'
398 // Useful means that there's an unknown MID whose modification date is before the cutoff
399 // A full list fetch would either confirm it as 'untrusted' or make it trusted again
400 func onqueueFullIDMSListWouldBeHelpful() -> Bool {
401
402 if self.containerMO.honorIDMSListChanges == "UNKNOWN" {
403 return true
404 }
405
406 let unknownMOs = (containerMO.machines as? Set<MachineMO> ?? Set()).filter { $0.status == TPMachineIDStatus.unknown.rawValue }
407 let outdatedMOs = unknownMOs.filter { !$0.modifiedInPast(hours: cutoffHours) }
408
409 return !outdatedMOs.isEmpty
410 }
411 }