Prevent potential rapid update checks using monotonic clock (2.x) (#2002)

This commit is contained in:
Zorg authored and GitHub committed 2021-11-07 17:20:19 -08:00
1 parent 011a7dbb36
commit c53ed49e5e
7 files changed
+150 -41

No files matched your search

+3 -1
View File
@@ -279,12 +279,14 @@ SU_EXPORT @interface SPUUpdater : NSObject
/**
Appropriately schedules or cancels the update checking timer according to the preferences for time interval and automatic checks.
If you change the `updateCheckInterval` or `automaticallyChecksForUpdates` properties, the update cycle will be reset automatically after a short delay.
The update cycle is also started automatically after the updater is started. In these cases, this method should not be called directly.
This call does not change the date of the next check, but only the internal timer.
*/
- (void)resetUpdateCycle;
/**
The system profile information that is sent when checking for updates.
*/
+71 -19
View File
@@ -62,6 +62,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
@property (nonatomic) BOOL showingPermissionRequest;
@property (nonatomic, copy) NSDate *updateLastCheckedDate;
@property (nonatomic) NSTimeInterval lastMonotonicUpdateCheckTime;
@property (nonatomic) BOOL loggedATSWarning;
@property (nonatomic) BOOL loggedNoSecureKeyWarning;
@@ -87,6 +88,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
@synthesize canCheckForUpdates = _canCheckForUpdates;
@synthesize showingPermissionRequest = _showingPermissionRequest;
@synthesize updateLastCheckedDate = _updateLastCheckedDate;
@synthesize lastMonotonicUpdateCheckTime = _lastMonotonicUpdateCheckTime;
@synthesize loggedATSWarning = _loggedATSWarning;
@synthesize loggedNoSecureKeyWarning = _loggedNoSecureKeyWarning;
@@ -402,7 +404,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
// We start the update checks and register as observer for changes after the prompt finishes
} else {
// We check if the user's said they want updates, or they haven't said anything, and the default is set to checking.
[self scheduleNextUpdateCheckFiringImmediately:NO usingCurrentTime:YES];
[self scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:YES];
}
}
@@ -422,17 +424,27 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
return [self updateLastCheckedDate];
}
- (NSTimeInterval)currentMonotonicTimeInterval
{
// This is monotonic system time while the system is not asleep
return [[NSProcessInfo processInfo] systemUptime];
}
- (void)updateLastUpdateCheckDate
{
[self willChangeValueForKey:NSStringFromSelector(@selector((lastUpdateCheckDate)))];
// We use an intermediate property for last update check date due to https://github.com/sparkle-project/Sparkle/pull/1135
[self setUpdateLastCheckedDate:[NSDate date]];
[self.host setObject:[self updateLastCheckedDate] forUserDefaultsKey:SULastCheckTimeKey];
self.lastMonotonicUpdateCheckTime = [self currentMonotonicTimeInterval];
[self didChangeValueForKey:NSStringFromSelector(@selector((lastUpdateCheckDate)))];
}
// Note this method is never called when sessionInProgress is YES
- (void)scheduleNextUpdateCheckFiringImmediately:(BOOL)firingImmediately usingCurrentTime:(BOOL)usingCurrentTime
- (void)scheduleNextUpdateCheckFiringImmediately:(BOOL)firingImmediately usingCurrentDate:(BOOL)usingCurrentDate
{
[self.updaterTimer invalidate];
@@ -479,34 +491,74 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
// This callback is asynchronous, so the timer may be set. Invalidate to make sure it isn't.
[self.updaterTimer invalidate];
NSTimeInterval intervalSinceCheck;
if (usingCurrentTime) {
NSTimeInterval dateIntervalSinceCheck;
NSTimeInterval minimumMonotonicEnforcedDelay;
if (usingCurrentDate) {
// How long has it been since last we checked for an update?
NSDate *lastCheckDate = [self lastUpdateCheckDate];
if (!lastCheckDate) { lastCheckDate = [NSDate distantPast]; }
intervalSinceCheck = [[NSDate date] timeIntervalSinceDate:lastCheckDate];
if (intervalSinceCheck < 0) {
NSTimeInterval wallTimeInterval = [[NSDate date] timeIntervalSinceDate:lastCheckDate];
if (wallTimeInterval < 0) {
// Last update check date is in the future and bogus, so reset it to current date
[self updateLastUpdateCheckDate];
intervalSinceCheck = 0;
// And assume a full update interval is needed
dateIntervalSinceCheck = 0;
minimumMonotonicEnforcedDelay = SUMinimumMonotonicUpdateCheckInterval;
} else {
// Check the monotonic clock for an enforced minimum delay
NSTimeInterval lastMonotonicUpdateCheckTime = self.lastMonotonicUpdateCheckTime;
if (lastMonotonicUpdateCheckTime <= 0) {
// When the updater is first started, the last monotonic time may not have been updated yet.
// In this case there is no enforced minimum delay.
minimumMonotonicEnforcedDelay = 0;
} else {
// Compute an enforced minimum delay based on elapsed monotonic time
// The elapsed monotonic time is more stable than wall time interval and does not include the
// amount of time while the system is asleep
NSTimeInterval currentMonotonicTime = [self currentMonotonicTimeInterval];
NSTimeInterval elapsedMonotonicTime = (currentMonotonicTime - lastMonotonicUpdateCheckTime);
if (elapsedMonotonicTime < SUMinimumMonotonicUpdateCheckInterval) {
minimumMonotonicEnforcedDelay = (SUMinimumMonotonicUpdateCheckInterval - elapsedMonotonicTime);
} else {
minimumMonotonicEnforcedDelay = 0;
}
}
dateIntervalSinceCheck = wallTimeInterval;
}
} else {
intervalSinceCheck = 0;
// Without using the current date, we assume a full update interval is needed
dateIntervalSinceCheck = 0;
minimumMonotonicEnforcedDelay = SUMinimumMonotonicUpdateCheckInterval;
}
if (updateCheckInterval < SUMinimumUpdateCheckInterval) {
updateCheckInterval = SUMinimumUpdateCheckInterval;
}
// Now we want to figure out how long until we check again.
if (updateCheckInterval < SUMinimumUpdateCheckInterval)
updateCheckInterval = SUMinimumUpdateCheckInterval;
if (intervalSinceCheck < updateCheckInterval) {
NSTimeInterval delayUntilCheck = (updateCheckInterval - intervalSinceCheck); // It hasn't been long enough.
if ([self.delegate respondsToSelector:@selector(updater:willScheduleUpdateCheckAfterDelay:)]) {
[self.delegate updater:self willScheduleUpdateCheckAfterDelay:delayUntilCheck];
}
[self.updaterTimer startAndFireAfterDelay:delayUntilCheck];
NSTimeInterval wallDelayUntilCheck;
if (dateIntervalSinceCheck < updateCheckInterval) {
// It hasn't been long enough.
wallDelayUntilCheck = (updateCheckInterval - dateIntervalSinceCheck);
} else {
wallDelayUntilCheck = 0;
}
// Now compute delay with enforced minimum delay requirement
// The minimum delay (based on monotonic clock) is an extra layer of defense to prevent too frequent update checks
// in case the wall clock is not working properly (eg from too many system wake events, system date changes, NTP..)
NSTimeInterval finalDelayUntilCheck = MAX(wallDelayUntilCheck, minimumMonotonicEnforcedDelay);
if (finalDelayUntilCheck <= 0) {
// We're overdue! Run one now.
[self checkForUpdatesInBackground];
} else {
if ([self.delegate respondsToSelector:@selector(updater:willScheduleUpdateCheckAfterDelay:)]) {
[self.delegate updater:self willScheduleUpdateCheckAfterDelay:finalDelayUntilCheck];
}
[self.updaterTimer startTimerWithWallTimeDelay:wallDelayUntilCheck monotonicTimeDelay:minimumMonotonicEnforcedDelay];
}
});
}
@@ -688,7 +740,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
// Ensure the delegate doesn't start a new session when being notified of the previous one ending
if (!strongSelf.sessionInProgress) {
if (shouldScheduleNextUpdateCheck) {
[strongSelf scheduleNextUpdateCheckFiringImmediately:NO usingCurrentTime:NO];
[strongSelf scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:NO];
} else {
SULog(SULogLevelDefault, @"Disabling scheduled updates..");
}
@@ -739,7 +791,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
// Ensure the delegate doesn't start a new session when being notified of the previous one ending
if (!strongSelf.sessionInProgress) {
[strongSelf scheduleNextUpdateCheckFiringImmediately:shouldShowUpdateImmediately usingCurrentTime:NO];
[strongSelf scheduleNextUpdateCheckFiringImmediately:shouldShowUpdateImmediately usingCurrentDate:NO];
}
}
}];
@@ -784,7 +836,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification
if (!self.sessionInProgress) {
[self cancelNextUpdateCycle];
[self scheduleNextUpdateCheckFiringImmediately:NO usingCurrentTime:YES];
[self scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:YES];
}
}
+1 -1
View File
@@ -366,7 +366,7 @@ SU_EXPORT extern NSString *const SUSystemProfilerPreferredLanguageKey;
Automatic update checks need to be enabled for this to trigger.
@param delay The delay in seconds until the next scheduled update will occur.
@param delay The delay in seconds until the next scheduled update will occur. This is an approximation and may vary due to system state.
@param updater The updater instance.
*/
+1 -1
View File
@@ -22,7 +22,7 @@ NS_ASSUME_NONNULL_BEGIN
- (instancetype)initWithDelegate:(id<SPUUpdaterTimerDelegate>)delegate;
- (void)startAndFireAfterDelay:(NSTimeInterval)delay;
- (void)startTimerWithWallTimeDelay:(NSTimeInterval)wallDelayUntilCheck monotonicTimeDelay:(NSTimeInterval)minimumEnforcedDelay;
- (void)invalidate;
+67 -17
View File
@@ -15,14 +15,16 @@
@interface SPUUpdaterTimer ()
@property (nonatomic, readonly, weak) id<SPUUpdaterTimerDelegate> delegate;
@property (nonatomic) dispatch_source_t source;
@property (nonatomic) dispatch_source_t wallTimeSource;
@property (nonatomic) dispatch_source_t monotonicTimeSource;
@end
@implementation SPUUpdaterTimer
@synthesize delegate = _delegate;
@synthesize source = _source;
@synthesize wallTimeSource = _wallTimeSource;
@synthesize monotonicTimeSource = _monotonicTimeSource;
- (instancetype)initWithDelegate:(id<SPUUpdaterTimerDelegate>)delegate
{
@@ -33,28 +35,76 @@
return self;
}
- (void)startAndFireAfterDelay:(NSTimeInterval)delay
- (void)startTimerWithWallTimeDelay:(NSTimeInterval)wallTimeDelay monotonicTimeDelay:(NSTimeInterval)monotonicTimeDelay
{
self.source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
// We use the wall time instead of cpu time for our dispatch timer
// So eg if the computer sleeps we want to include that time spent in our timer
dispatch_time_t timeToFire = dispatch_walltime(NULL, (int64_t)(delay * NSEC_PER_SEC));
dispatch_source_set_timer(self.source, timeToFire, DISPATCH_TIME_FOREVER, SULeewayUpdateCheckInterval * NSEC_PER_SEC);
__weak __typeof__(self) weakSelf = self;
dispatch_source_set_event_handler(self.source, ^{
[weakSelf.delegate updaterTimerDidFire];
});
// When timersFired reaches 2, both wall/monotonic timers have been fired, and the delegate is ready to receive the notification
__block uint8_t timersFired = 0;
dispatch_resume(self.source);
if (wallTimeDelay <= 0) {
timersFired++;
self.wallTimeSource = nil;
} else {
// We use the wall time instead of cpu time for a large date interval
// So eg if the computer sleeps we want to include that time spent in our timer
self.wallTimeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_time_t wallTime = dispatch_walltime(NULL, (int64_t)(wallTimeDelay * NSEC_PER_SEC));
dispatch_source_set_timer(self.wallTimeSource, wallTime, DISPATCH_TIME_FOREVER, SULeewayWallUpdateCheckInterval * NSEC_PER_SEC);
dispatch_source_set_event_handler(self.wallTimeSource, ^{
timersFired++;
if (timersFired > 1) {
[weakSelf.delegate updaterTimerDidFire];
}
});
}
if (monotonicTimeDelay <= 0) {
timersFired++;
self.monotonicTimeSource = nil;
} else {
// We also use monotonic time to enforce a minimum delay interval
// This ensures we don't fire the wall clock based timer too frequently if the real clock changes
self.monotonicTimeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_time_t monotonicTime = dispatch_time(DISPATCH_TIME_NOW , (int64_t)(monotonicTimeDelay * NSEC_PER_SEC));
dispatch_source_set_timer(self.monotonicTimeSource, monotonicTime, DISPATCH_TIME_FOREVER, SULeewayMonotonicUpdateCheckInterval * NSEC_PER_SEC);
dispatch_source_set_event_handler(self.monotonicTimeSource, ^{
timersFired++;
if (timersFired > 1) {
[weakSelf.delegate updaterTimerDidFire];
}
});
}
// Have both timers already ran? (this should be unlikely)
if (timersFired > 1) {
[self.delegate updaterTimerDidFire];
} else {
// Resume available timers
if (self.wallTimeSource != nil) {
dispatch_resume(self.wallTimeSource);
}
if (self.monotonicTimeSource != nil) {
dispatch_resume(self.monotonicTimeSource);
}
}
}
- (void)invalidate
{
if (self.source != nil) {
dispatch_source_cancel(self.source);
self.source = nil;
if (self.wallTimeSource != nil) {
dispatch_source_cancel(self.wallTimeSource);
self.wallTimeSource = nil;
}
if (self.monotonicTimeSource != nil) {
dispatch_source_cancel(self.monotonicTimeSource);
self.monotonicTimeSource = nil;
}
}
+3 -1
View File
@@ -19,7 +19,9 @@
extern const NSTimeInterval SUDefaultUpdatePermissionPromptInterval;
extern const NSTimeInterval SUMinimumUpdateCheckInterval;
extern const NSTimeInterval SUDefaultUpdateCheckInterval;
extern const uint64_t SULeewayUpdateCheckInterval;
extern const NSTimeInterval SUMinimumMonotonicUpdateCheckInterval;
extern const uint64_t SULeewayWallUpdateCheckInterval;
extern const uint64_t SULeewayMonotonicUpdateCheckInterval;
extern const NSTimeInterval SUImpatientUpdateCheckInterval;
extern NSString *const SUBundleIdentifier;
+4 -1
View File
@@ -18,8 +18,11 @@
// Define some minimum intervals to avoid DoS-like checking attacks
const NSTimeInterval SUMinimumUpdateCheckInterval = DEBUG ? 60 : (60 * 60);
const NSTimeInterval SUDefaultUpdateCheckInterval = DEBUG ? 60 : (60 * 60 * 24);
const NSTimeInterval SUMinimumMonotonicUpdateCheckInterval = DEBUG ? 30 : (60 * 5);
// The amount of time the system can defer our update check (for improved performance)
const uint64_t SULeewayUpdateCheckInterval = DEBUG ? 1 : 15;
const uint64_t SULeewayWallUpdateCheckInterval = DEBUG ? 1 : 60;
const uint64_t SULeewayMonotonicUpdateCheckInterval = DEBUG ? 1 : 5;
// If the update has already been automatically downloaded, we normally don't want to bug the user about the update
// However if the user has gone a very long time without quitting an application, we will bug them