From 6db08bce4b9df0bef3581d737c1d2aab4c3a0bcb Mon Sep 17 00:00:00 2001 From: Max Goedjen Date: Sun, 7 Nov 2021 14:29:53 -0800 Subject: [PATCH] Switch to monotonic time. --- SecretKit/SecureEnclave/SecureEnclaveStore.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/SecretKit/SecureEnclave/SecureEnclaveStore.swift b/SecretKit/SecureEnclave/SecureEnclaveStore.swift index 0c25f9b..b3d727d 100644 --- a/SecretKit/SecureEnclave/SecureEnclaveStore.swift +++ b/SecretKit/SecureEnclave/SecureEnclaveStore.swift @@ -144,7 +144,7 @@ extension SecureEnclave { newContext.localizedCancelTitle = "Deny" newContext.localizedReason = "unlock secret \"\(secret.name)\"" newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometricsOrWatch, localizedReason: newContext.localizedReason) { [weak self] success, _ in - let context = PersistentAuthenticationContext(secret: secret, context: newContext, expiration: Date(timeIntervalSinceNow: duration)) + let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration) self?.persistedAuthenticationContexts[secret] = context } } @@ -241,11 +241,18 @@ extension SecureEnclave { let secret: Secret let context: LAContext - // TODO: monotonic time instead of Date() to prevent people setting the clock back. - let expiration: Date + // Monotonic time instead of Date() to prevent people setting the clock back. + let expiration: UInt64 + + init(secret: Secret, context: LAContext, duration: TimeInterval) { + self.secret = secret + self.context = context + let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: UnitDuration.nanoseconds).value + self.expiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds) + } var valid: Bool { - Date() < expiration + clock_gettime_nsec_np(CLOCK_MONOTONIC) < expiration } }