5 func modifiedInPast(hours: Int) -> Bool {
6 guard let modifiedDate = self.modified else {
10 let dateLimit = Date(timeIntervalSinceNow: -60 * 60 * TimeInterval(hours))
11 return modifiedDate.compare(dateLimit) == ComparisonResult.orderedDescending
14 func modifiedDate() -> String {
15 guard let modifiedDate = self.modified else {
19 let dateFormatter = ISO8601DateFormatter()
20 return dateFormatter.string(from: modifiedDate)
23 func asTPMachineID() -> TPMachineID {
24 return TPMachineID(machineID: self.machineID ?? "unknown",
25 status: TPMachineIDStatus(rawValue: UInt(self.status)) ?? .unknown,
26 modified: self.modified ?? Date())
30 // You get two days of grace before you're removed
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 })
40 let allowedMachineIDs = container.allowedMachineIDs as? Set<String> ?? Set()
41 let missingIDs = allowedMachineIDs.filter { !knownMachineIDs.contains($0) }
43 missingIDs.forEach { id in
44 let mid = MachineMO(context: moc)
46 mid.seenOnFullList = true
47 mid.status = Int64(TPMachineIDStatus.allowed.rawValue)
49 container.addToMachines(mid)
52 container.allowedMachineIDs = Set<String>() as NSSet
55 internal static func onqueueUpgradeMachineIDSetToUseStatus(container: ContainerMO, moc: NSManagedObjectContext) {
56 let knownMachineMOs = container.machines as? Set<MachineMO> ?? Set()
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
62 knownMachineMOs.forEach { mo in
64 mo.status = Int64(TPMachineIDStatus.allowed.rawValue)
66 mo.status = Int64(TPMachineIDStatus.disallowed.rawValue)
73 func enforceIDMSListChanges(knownMachines: Set<MachineMO>) -> Bool {
74 if self.containerMO.honorIDMSListChanges == "YES"{
76 } else if self.containerMO.honorIDMSListChanges == "NO" {
78 } else if self.containerMO.honorIDMSListChanges == "UNKNOWN" && knownMachines.isEmpty {
80 } else if self.containerMO.honorIDMSListChanges == "UNKNOWN" && !knownMachines.isEmpty {
87 func setAllowedMachineIDs(_ allowedMachineIDs: Set<String>, honorIDMSListChanges: Bool, reply: @escaping (Bool, Error?) -> Void) {
89 let reply: (Bool, Error?) -> Void = {
90 os_log("setAllowedMachineIDs complete: %{public}@", log: tplogTrace, type: .info, traceError($1))
91 self.semaphore.signal()
95 os_log("Setting allowed machine IDs: %{public}@", log: tplogDebug, type: .default, allowedMachineIDs)
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.
100 self.moc.performAndWait {
102 var differences = false
103 self.containerMO.honorIDMSListChanges = honorIDMSListChanges ? "YES" : "NO"
105 var knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
106 let knownMachineIDs = Set(knownMachines.compactMap { $0.machineID })
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)
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))
117 os_log("Machine ID newly retrusted: %{public}@", log: tplogDebug, type: .default, String(describing: machine.machineID))
120 machine.status = Int64(TPMachineIDStatus.allowed.rawValue)
121 machine.seenOnFullList = true
122 machine.modified = Date()
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))
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))
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()
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))
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()
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))
173 self.containerMO.addToMachines(machine)
174 knownMachines.insert(machine)
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)
192 self.containerMO.addToMachines(machine)
196 os_log("Believe we're in a demo account, not enforcing IDMS list", log: tplogDebug, type: .default)
199 // We no longer use allowed machine IDs.
200 self.containerMO.allowedMachineIDs = NSSet()
204 reply(differences, nil)
206 os_log("Error setting machine ID list: %{public}@", log: tplogDebug, type: .default, (error as CVarArg?) ?? "no error")
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()
220 os_log("Adding allowed machine IDs: %{public}@", log: tplogDebug, type: .default, machineIDs)
222 self.moc.performAndWait {
224 var knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
225 let knownMachineIDs = Set(knownMachines.compactMap { $0.machineID })
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))
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)
249 knownMachines.insert(machine)
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()
269 os_log("Removing allowed machine IDs: %{public}@", log: tplogDebug, type: .default, machineIDs)
271 self.moc.performAndWait {
273 var knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
274 let knownMachineIDs = Set(knownMachines.compactMap { $0.machineID })
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))
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)
298 knownMachines.insert(machine)
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()
318 os_log("Fetching allowed machine IDs", log: tplogDebug, type: .default)
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 }
324 reply(Set(allowedMachineIDs), nil)
328 func onqueueMachineIDAllowedByIDMS(machineID: String) -> Bool {
330 // For Demo accounts, if the list is entirely empty, then everything is allowed
331 let knownMachines = containerMO.machines as? Set<MachineMO> ?? Set()
333 if !self.enforceIDMSListChanges(knownMachines: knownMachines) {
334 os_log("not enforcing idms list changes; allowing %{public}@", log: tplogDebug, type: .debug, machineID)
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 {
343 os_log("machineID %{public}@ not explicitly allowed: %{public}@", log: tplogDebug, type: .debug, machineID, mo)
348 // Didn't find it? reject.
349 os_log("machineID %{public}@ not found on list", log: tplogDebug, type: .debug, machineID)
353 func onqueueCurrentMIDList() -> TPMachineIDList {
354 let machines = containerMO.machines as? Set<MachineMO> ?? Set()
355 return TPMachineIDList(entries: machines.map { $0.asTPMachineID() })
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.
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.)
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.
368 let machines = containerMO.machines as? Set<MachineMO> ?? Set()
369 let knownMachineIDs = Set(machines.compactMap { $0.machineID })
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 })
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)
385 self.containerMO.addToMachines(machine)
388 os_log("Not enforcing IDMS list changes", log: tplogDebug, type: .default)
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)
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 {
402 if self.containerMO.honorIDMSListChanges == "UNKNOWN" {
406 let unknownMOs = (containerMO.machines as? Set<MachineMO> ?? Set()).filter { $0.status == TPMachineIDStatus.unknown.rawValue }
407 let outdatedMOs = unknownMOs.filter { !$0.modifiedInPast(hours: cutoffHours) }
409 return !outdatedMOs.isEmpty