From 60769a3d174b2461ced18a8e9eeec8f87a5c8e57 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Sun, 28 Oct 2018 12:18:04 -0600 Subject: [PATCH 01/16] Exception wrap SessionCipher for Swift --- Podfile | 4 +-- Podfile.lock | 24 +++++++------ Pods | 2 +- .../src/Messages/OWSMessageDecrypter.m | 19 ++++++----- .../src/Messages/OWSMessageSender.m | 34 ++++++++++--------- 5 files changed, 45 insertions(+), 38 deletions(-) diff --git a/Podfile b/Podfile index 228be5bb6..d969776a1 100644 --- a/Podfile +++ b/Podfile @@ -5,7 +5,7 @@ use_frameworks! def shared_pods # OWS Pods - pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', testspecs: ["Tests"] + pod 'SignalCoreKit', git: 'git@github.com:signalapp/SignalCoreKit-Private.git', branch: 'mkirk/wrap-exceptions', testspecs: ["Tests"] # pod 'SignalCoreKit', path: '../SignalCoreKit', testspecs: ["Tests"] # pod 'SQLCipher', path: '../sqlcipher2' pod 'SQLCipher', :git => 'https://github.com/sqlcipher/sqlcipher.git', :commit => 'd5c2bec' @@ -19,7 +19,7 @@ def shared_pods pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit', testspecs: ["Tests"] # pod 'Curve25519Kit', path: '../Curve25519Kit', testspecs: ["Tests"] # TODO: Use public repo. - pod 'SignalMetadataKit', git: 'https://github.com/signalapp/SignalMetadataKit', testspecs: ["Tests"] + pod 'SignalMetadataKit', git: 'git@github.com:signalapp/SignalMetadataKit', branch: 'mkirk/wrap-exceptions', testspecs: ["Tests"] # pod 'SignalMetadataKit', path: '../SignalMetadataKit', testspecs: ["Tests"] pod 'SignalServiceKit', path: '.', testspecs: ["Tests"] pod 'GRKOpenSSLFramework', git: 'https://github.com/signalapp/GRKOpenSSLFramework' diff --git a/Podfile.lock b/Podfile.lock index f9479ae58..b74e75f15 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -192,10 +192,10 @@ DEPENDENCIES: - Mantle - PureLayout - Reachability - - SignalCoreKit (from `https://github.com/signalapp/SignalCoreKit.git`) - - SignalCoreKit/Tests (from `https://github.com/signalapp/SignalCoreKit.git`) - - SignalMetadataKit (from `https://github.com/signalapp/SignalMetadataKit`) - - SignalMetadataKit/Tests (from `https://github.com/signalapp/SignalMetadataKit`) + - "SignalCoreKit (from `git@github.com:signalapp/SignalCoreKit-Private.git`, branch `mkirk/wrap-exceptions`)" + - "SignalCoreKit/Tests (from `git@github.com:signalapp/SignalCoreKit-Private.git`, branch `mkirk/wrap-exceptions`)" + - "SignalMetadataKit (from `git@github.com:signalapp/SignalMetadataKit`, branch `mkirk/wrap-exceptions`)" + - "SignalMetadataKit/Tests (from `git@github.com:signalapp/SignalMetadataKit`, branch `mkirk/wrap-exceptions`)" - SignalServiceKit (from `.`) - SignalServiceKit/Tests (from `.`) - SocketRocket (from `https://github.com/signalapp/SocketRocket.git`, branch `mkirk/handle-sec-err`) @@ -229,9 +229,11 @@ EXTERNAL SOURCES: HKDFKit: :git: https://github.com/signalapp/HKDFKit.git SignalCoreKit: - :git: https://github.com/signalapp/SignalCoreKit.git + :branch: mkirk/wrap-exceptions + :git: "git@github.com:signalapp/SignalCoreKit-Private.git" SignalMetadataKit: - :git: https://github.com/signalapp/SignalMetadataKit + :branch: mkirk/wrap-exceptions + :git: "git@github.com:signalapp/SignalMetadataKit" SignalServiceKit: :path: "." SocketRocket: @@ -258,11 +260,11 @@ CHECKOUT OPTIONS: :commit: 8b8326cd50bc488663a3d3743f1a92b90f4d85b4 :git: https://github.com/signalapp/HKDFKit.git SignalCoreKit: - :commit: ff0b95770520133b83a4bd7b26bc2c90b51abc4d - :git: https://github.com/signalapp/SignalCoreKit.git + :commit: df8d9528eb5e7e161ea04393a0d7972cd8539c14 + :git: "git@github.com:signalapp/SignalCoreKit-Private.git" SignalMetadataKit: - :commit: 90f3dee7122ff13061770c496001135ba90b71e3 - :git: https://github.com/signalapp/SignalMetadataKit + :commit: 07326a8ebb8e207bbe0e08fc6cd1d4979acc83d6 + :git: "git@github.com:signalapp/SignalMetadataKit" SocketRocket: :commit: 9f9563a83cd8960503074aa8de72206f83fb7a69 :git: https://github.com/signalapp/SocketRocket.git @@ -296,6 +298,6 @@ SPEC CHECKSUMS: YapDatabase: b418a4baa6906e8028748938f9159807fd039af4 YYImage: 1e1b62a9997399593e4b9c4ecfbbabbf1d3f3b54 -PODFILE CHECKSUM: 820287bc7925d7c20e02a02923976c60b1f5386b +PODFILE CHECKSUM: 794d0aeb047ca81b7c697f99e43b6f80ea4ce585 COCOAPODS: 1.5.3 diff --git a/Pods b/Pods index 3b101143e..c4a845a4d 160000 --- a/Pods +++ b/Pods @@ -1 +1 @@ -Subproject commit 3b101143e57b34fbef613c365c9ee2e29bd25d16 +Subproject commit c4a845a4d93934555baf8335c65b2510a926322b diff --git a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m index 7a956ceaa..972002d41 100644 --- a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m +++ b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m @@ -26,6 +26,7 @@ #import #import #import +#import #import #import @@ -378,7 +379,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes // plaintextData may be nil for some envelope types. NSData *_Nullable plaintextData = - [[cipher decrypt:cipherMessage protocolContext:transaction] removePadding]; + [[cipher try_decrypt:cipherMessage protocolContext:transaction] removePadding]; OWSMessageDecryptResult *result = [OWSMessageDecryptResult resultWithEnvelopeData:envelopeData plaintextData:plaintextData source:envelope.source @@ -448,13 +449,15 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes } SMKDecryptResult *_Nullable decryptResult = - [cipher decryptMessageWithCertificateValidator:certificateValidator - cipherTextData:encryptedData - timestamp:serverTimestamp - localRecipientId:localRecipientId - localDeviceId:localDeviceId - protocolContext:transaction - error:&error]; + [cipher trywrapped_decryptMessageWithCertificateValidator:certificateValidator + cipherTextData:encryptedData + timestamp:serverTimestamp + localRecipientId:localRecipientId + localDeviceId:localDeviceId + protocolContext:transaction + error:&error]; + SCKRaiseIfExceptionWrapperError(error); + if (error || !decryptResult) { if ([error.domain isEqualToString:@"SignalMetadataKit.SMKSecretSessionCipherError"] && error.code == SMKSecretSessionCipherErrorSelfSentMessage) { diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index 9f8769425..ee3a9c929 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -50,6 +50,7 @@ #import #import #import +#import #import #import #import @@ -1450,10 +1451,10 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; [self.dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { @try { - messageDict = [self encryptedMessageForMessageSend:messageSend - deviceId:deviceId - plainText:plainText - transaction:transaction]; + messageDict = [self try_encryptedMessageForMessageSend:messageSend + deviceId:deviceId + plainText:plainText + transaction:transaction]; } @catch (NSException *exception) { encryptionException = exception; } @@ -1612,10 +1613,10 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; } // NOTE: This method uses exceptions for control flow. -- (NSDictionary *)encryptedMessageForMessageSend:(OWSMessageSend *)messageSend - deviceId:(NSNumber *)deviceId - plainText:(NSData *)plainText - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (NSDictionary *)try_encryptedMessageForMessageSend:(OWSMessageSend *)messageSend + deviceId:(NSNumber *)deviceId + plainText:(NSData *)plainText + transaction:(YapDatabaseReadWriteTransaction *)transaction { OWSAssertDebug(messageSend); OWSAssertDebug(deviceId); @@ -1658,17 +1659,18 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; OWSRaiseException(@"SecretSessionCipherFailure", @"Can't create secret session cipher."); } - serializedMessage = [secretCipher encryptMessageWithRecipientId:recipientId - deviceId:deviceId.intValue - paddedPlaintext:[plainText paddedMessageBody] - senderCertificate:messageSend.senderCertificate - protocolContext:transaction - error:&error]; + serializedMessage = [secretCipher trywrapped_encryptMessageWithRecipientId:recipientId + deviceId:deviceId.intValue + paddedPlaintext:[plainText paddedMessageBody] + senderCertificate:messageSend.senderCertificate + protocolContext:transaction + error:&error]; + SCKRaiseIfExceptionWrapperError(error); messageType = TSUnidentifiedSenderMessageType; } else { // This may throw an exception. id encryptedMessage = - [cipher encryptMessage:[plainText paddedMessageBody] protocolContext:transaction]; + [cipher try_encryptMessage:[plainText paddedMessageBody] protocolContext:transaction]; serializedMessage = encryptedMessage.serialized; messageType = [self messageTypeForCipherMessage:encryptedMessage]; } @@ -1680,7 +1682,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; device:[deviceId intValue] content:serializedMessage isSilent:isSilent - registrationId:[cipher remoteRegistrationId:transaction]]; + registrationId:[cipher try_remoteRegistrationId:transaction]]; NSError *error; NSDictionary *jsonDict = [MTLJSONAdapter JSONDictionaryFromModel:messageParams error:&error]; From 1482c600b460735c5ab049c94ecd4e26b37c2e8b Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 09:57:34 -0600 Subject: [PATCH 02/16] Exception wrap PreKeyWhisperMessage for Swift --- .../TSInvalidIdentityKeyReceivingErrorMessage.m | 4 ++-- SignalServiceKit/src/Messages/OWSMessageDecrypter.m | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m index fac35fbdd..19987c1d1 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m @@ -112,7 +112,7 @@ NS_ASSUME_NONNULL_BEGIN } } -- (nullable NSData *)newIdentityKey +- (nullable NSData *)try_newIdentityKey { if (!self.envelope) { OWSLogError(@"Error message had no envelope data to extract key from"); @@ -130,7 +130,7 @@ NS_ASSUME_NONNULL_BEGIN return nil; } - PreKeyWhisperMessage *message = [[PreKeyWhisperMessage alloc] initWithData:pkwmData]; + PreKeyWhisperMessage *message = [[PreKeyWhisperMessage alloc] init_try_withData:pkwmData]; return [message.identityKey removeKeyType]; } diff --git a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m index 972002d41..759f9f92e 100644 --- a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m +++ b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m @@ -229,7 +229,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes return; } case SSKProtoEnvelopeTypePrekeyBundle: { - [self decryptPreKeyBundle:envelope + [self try_decryptPreKeyBundle:envelope envelopeData:envelopeData successBlock:^(OWSMessageDecryptResult *result, YapDatabaseReadWriteTransaction *transaction) { OWSLogDebug(@"decrypted pre-key whisper message"); @@ -318,10 +318,10 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes failureBlock:failureBlock]; } -- (void)decryptPreKeyBundle:(SSKProtoEnvelope *)envelope - envelopeData:(NSData *)envelopeData - successBlock:(DecryptSuccessBlock)successBlock - failureBlock:(void (^)(NSError *_Nullable error))failureBlock +- (void)try_decryptPreKeyBundle:(SSKProtoEnvelope *)envelope + envelopeData:(NSData *)envelopeData + successBlock:(DecryptSuccessBlock)successBlock + failureBlock:(void (^)(NSError *_Nullable error))failureBlock { OWSAssertDebug(envelope); OWSAssertDebug(envelopeData); @@ -335,7 +335,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes envelopeData:envelopeData cipherTypeName:@"PreKey Bundle" cipherMessageBlock:^(NSData *encryptedData) { - return [[PreKeyWhisperMessage alloc] initWithData:encryptedData]; + return [[PreKeyWhisperMessage alloc] init_try_withData:encryptedData]; } successBlock:successBlock failureBlock:failureBlock]; From 8d823193f11f8b3d87da64b28830e0ffc401b78f Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 10:29:44 -0600 Subject: [PATCH 03/16] Exception wrap WhisperMessage for Swift --- SignalServiceKit/src/Messages/OWSMessageDecrypter.m | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m index 759f9f92e..d24721100 100644 --- a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m +++ b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m @@ -212,7 +212,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes switch (envelope.type) { case SSKProtoEnvelopeTypeCiphertext: { - [self decryptSecureMessage:envelope + [self try_decryptSecureMessage:envelope envelopeData:envelopeData successBlock:^(OWSMessageDecryptResult *result, YapDatabaseReadWriteTransaction *transaction) { OWSLogDebug(@"decrypted secure message."); @@ -298,10 +298,10 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes failureBlock(); } -- (void)decryptSecureMessage:(SSKProtoEnvelope *)envelope - envelopeData:(NSData *)envelopeData - successBlock:(DecryptSuccessBlock)successBlock - failureBlock:(void (^)(NSError *_Nullable error))failureBlock +- (void)try_decryptSecureMessage:(SSKProtoEnvelope *)envelope + envelopeData:(NSData *)envelopeData + successBlock:(DecryptSuccessBlock)successBlock + failureBlock:(void (^)(NSError *_Nullable error))failureBlock { OWSAssertDebug(envelope); OWSAssertDebug(envelopeData); @@ -312,7 +312,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes envelopeData:envelopeData cipherTypeName:@"Secure Message" cipherMessageBlock:^(NSData *encryptedData) { - return [[WhisperMessage alloc] initWithData:encryptedData]; + return [[WhisperMessage alloc] init_try_withData:encryptedData]; } successBlock:successBlock failureBlock:failureBlock]; From b622b3a0202913f4be143d13e8e50a2728a8529f Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 10:56:01 -0600 Subject: [PATCH 04/16] Exception wrap TSDerivedSecrets for Swift --- SignalServiceKit/src/Messages/OWSMessageSender.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index ee3a9c929..7a0d79707 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -1547,7 +1547,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; deviceId:[deviceId intValue]]; [self.dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { @try { - [builder processPrekeyBundle:bundle protocolContext:transaction]; + [builder try_processPrekeyBundle:bundle protocolContext:transaction]; } @catch (NSException *caughtException) { exception = caughtException; } From 5f5ec9b82ade82a1e285b34fdb379e82e4576442 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 12:11:06 -0600 Subject: [PATCH 05/16] ExceptionWrap loadPreKey --- .../Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m | 2 +- .../AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m | 2 +- .../tests/Storage/TSStoragePreKeyStoreTests.m | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m index b5622c48f..41e83f7da 100644 --- a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m +++ b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m @@ -49,7 +49,7 @@ } } -- (PreKeyRecord *)loadPreKey:(int)preKeyId +- (PreKeyRecord *)try_loadPreKey:(int)preKeyId { PreKeyRecord *preKeyRecord = [self.dbReadConnection preKeyRecordForKey:[self keyFromInt:preKeyId] inCollection:OWSPrimaryStoragePreKeyStoreCollection]; diff --git a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m index 48eef0a75..423cd3e7a 100644 --- a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m +++ b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m @@ -36,7 +36,7 @@ NSString *const OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId = @"currentSigne generatedAt:[NSDate date]]; } -- (SignedPreKeyRecord *)loadSignedPrekey:(int)signedPreKeyId +- (SignedPreKeyRecord *)try_loadSignedPrekey:(int)signedPreKeyId { SignedPreKeyRecord *preKeyRecord = [self.dbReadConnection signedPreKeyRecordForKey:[self keyFromInt:signedPreKeyId] diff --git a/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m b/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m index ad98a0a33..906daaa2a 100644 --- a/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m +++ b/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m @@ -35,10 +35,10 @@ PreKeyRecord *lastPreKeyRecord = [generatedKeys lastObject]; PreKeyRecord *firstPreKeyRecord = [generatedKeys firstObject]; - XCTAssert([[[OWSPrimaryStorage sharedManager] loadPreKey:lastPreKeyRecord.Id].keyPair.publicKey + XCTAssert([[[OWSPrimaryStorage sharedManager] try_loadPreKey:lastPreKeyRecord.Id].keyPair.publicKey isEqualToData:lastPreKeyRecord.keyPair.publicKey]); - XCTAssert([[[OWSPrimaryStorage sharedManager] loadPreKey:firstPreKeyRecord.Id].keyPair.publicKey + XCTAssert([[[OWSPrimaryStorage sharedManager] try_loadPreKey:firstPreKeyRecord.Id].keyPair.publicKey isEqualToData:firstPreKeyRecord.keyPair.publicKey]); } @@ -56,8 +56,8 @@ [[OWSPrimaryStorage sharedManager] removePreKey:lastPreKeyRecord.Id]; - XCTAssertThrows([[OWSPrimaryStorage sharedManager] loadPreKey:lastPreKeyRecord.Id]); - XCTAssertNoThrow([[OWSPrimaryStorage sharedManager] loadPreKey:firstPreKeyRecord.Id]); + XCTAssertThrows([[OWSPrimaryStorage sharedManager] try_loadPreKey:lastPreKeyRecord.Id]); + XCTAssertNoThrow([[OWSPrimaryStorage sharedManager] try_loadPreKey:firstPreKeyRecord.Id]); } @end From 3a6aafc454b05873ec5e03e6bad7b953af584bb5 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 14:29:09 -0600 Subject: [PATCH 06/16] Swift Exception wrap NSData+keyVersionByte --- .../Models/OWSDeviceProvisioningURLParser.h | 8 ++++--- .../Models/OWSDeviceProvisioningURLParser.m | 6 ++++- .../ConversationViewController.m | 4 +++- SignalMessaging/utils/ThreadUtil.m | 16 ++++++++----- SignalServiceKit/src/Contacts/TSThread.m | 8 +++++-- .../TSInvalidIdentityKeyErrorMessage.h | 6 ++--- .../TSInvalidIdentityKeyErrorMessage.m | 4 ++-- ...SInvalidIdentityKeyReceivingErrorMessage.m | 6 ++--- .../TSInvalidIdentityKeySendingErrorMessage.m | 8 +++---- .../src/Messages/OWSBatchMessageProcessor.m | 6 ++--- .../src/Messages/OWSIdentityManager.h | 4 ++-- .../src/Messages/OWSIdentityManager.m | 6 ++--- .../src/Messages/OWSMessageManager.h | 6 ++--- .../src/Messages/OWSMessageManager.m | 24 +++++++++---------- .../src/Messages/OWSMessageSender.m | 2 +- .../Network/API/SignalServiceProfile.swift | 11 +++++++-- 16 files changed, 74 insertions(+), 51 deletions(-) diff --git a/Signal/src/Models/OWSDeviceProvisioningURLParser.h b/Signal/src/Models/OWSDeviceProvisioningURLParser.h index 319a717cd..22758bbc8 100644 --- a/Signal/src/Models/OWSDeviceProvisioningURLParser.h +++ b/Signal/src/Models/OWSDeviceProvisioningURLParser.h @@ -1,12 +1,14 @@ -// Copyright © 2016 Open Whisper Systems. All rights reserved. +// +// Copyright (c) 2018 Open Whisper Systems. All rights reserved. +// NS_ASSUME_NONNULL_BEGIN @interface OWSDeviceProvisioningURLParser : NSObject @property (readonly, getter=isValid) BOOL valid; -@property (nonatomic, readonly) NSString *ephemeralDeviceId; -@property (nonatomic, readonly) NSData *publicKey; +@property (nonatomic, readonly, nullable) NSString *ephemeralDeviceId; +@property (nonatomic, readonly, nullable) NSData *publicKey; - (instancetype)initWithProvisioningURL:(NSString *)provisioningURL; diff --git a/Signal/src/Models/OWSDeviceProvisioningURLParser.m b/Signal/src/Models/OWSDeviceProvisioningURLParser.m index 41aebc6ab..3710b5d09 100644 --- a/Signal/src/Models/OWSDeviceProvisioningURLParser.m +++ b/Signal/src/Models/OWSDeviceProvisioningURLParser.m @@ -26,7 +26,11 @@ NSString *const OWSQueryItemNameEncodedPublicKeyKey = @"pub_key"; _ephemeralDeviceId = queryItem.value; } else if ([queryItem.name isEqualToString:OWSQueryItemNameEncodedPublicKeyKey]) { NSString *encodedPublicKey = queryItem.value; - _publicKey = [[NSData dataFromBase64String:encodedPublicKey] removeKeyType]; + @try { + _publicKey = [[NSData dataFromBase64String:encodedPublicKey] try_removeKeyType]; + } @catch (NSException *exception) { + OWSFailDebug(@"exception: %@", exception); + } } else { OWSLogWarn(@"Unkown query item in provisioning string: %@", queryItem.name); } diff --git a/Signal/src/ViewControllers/ConversationView/ConversationViewController.m b/Signal/src/ViewControllers/ConversationView/ConversationViewController.m index 15d8d3cc9..d7fa7a29f 100644 --- a/Signal/src/ViewControllers/ConversationView/ConversationViewController.m +++ b/Signal/src/ViewControllers/ConversationView/ConversationViewController.m @@ -1901,7 +1901,9 @@ typedef enum : NSUInteger { // but there will be some legacy ones in the wild, behind which await // as-of-yet-undecrypted messages if ([errorMessage isKindOfClass:[TSInvalidIdentityKeyReceivingErrorMessage class]]) { - [errorMessage acceptNewIdentityKey]; + // Deliberately crash if the user fails to explicitly accept the new identity + // key. In practice we haven't been creating these messags in over a year. + [errorMessage try_acceptNewIdentityKey]; } }]; [actionSheetController addAction:acceptSafetyNumberAction]; diff --git a/SignalMessaging/utils/ThreadUtil.m b/SignalMessaging/utils/ThreadUtil.m index 4d9029050..a961bae2a 100644 --- a/SignalMessaging/utils/ThreadUtil.m +++ b/SignalMessaging/utils/ThreadUtil.m @@ -631,13 +631,17 @@ NS_ASSUME_NONNULL_BEGIN continue; } - NSData *_Nullable newIdentityKey = safetyNumberChange.newIdentityKey; - if (newIdentityKey == nil) { - OWSFailDebug(@"Safety number change was missing it's new identity key."); - continue; - } + @try { + NSData *_Nullable newIdentityKey = [safetyNumberChange try_newIdentityKey]; + if (newIdentityKey == nil) { + OWSFailDebug(@"Safety number change was missing it's new identity key."); + continue; + } - [missingUnseenSafetyNumberChanges addObject:newIdentityKey]; + [missingUnseenSafetyNumberChanges addObject:newIdentityKey]; + } @catch (NSException *exception) { + OWSFailDebug(@"exception: %@", exception); + } } // Count the de-duplicated "blocking" safety number changes and all diff --git a/SignalServiceKit/src/Contacts/TSThread.m b/SignalServiceKit/src/Contacts/TSThread.m index fe839afb2..975a5bac2 100644 --- a/SignalServiceKit/src/Contacts/TSThread.m +++ b/SignalServiceKit/src/Contacts/TSThread.m @@ -248,8 +248,12 @@ ConversationColorName const kConversationColorName_Default = ConversationColorNa [self enumerateInteractionsUsingBlock:^(TSInteraction *interaction) { if ([interaction isKindOfClass:[TSInvalidIdentityKeyReceivingErrorMessage class]]) { TSInvalidIdentityKeyReceivingErrorMessage *error = (TSInvalidIdentityKeyReceivingErrorMessage *)interaction; - if ([[error newIdentityKey] isEqualToData:key]) { - [errorMessages addObject:(TSInvalidIdentityKeyReceivingErrorMessage *)interaction]; + @try { + if ([[error try_newIdentityKey] isEqualToData:key]) { + [errorMessages addObject:(TSInvalidIdentityKeyReceivingErrorMessage *)interaction]; + } + } @catch (NSException *exception) { + OWSFailDebug(@"exception: %@", exception); } } }]; diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h index 2ef76e8ad..e81acb66d 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h @@ -1,5 +1,5 @@ // -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. +// Copyright (c) 2018 Open Whisper Systems. All rights reserved. // #import "TSErrorMessage.h" @@ -10,8 +10,8 @@ NS_ASSUME_NONNULL_BEGIN @interface TSInvalidIdentityKeyErrorMessage : TSErrorMessage -- (void)acceptNewIdentityKey; -- (nullable NSData *)newIdentityKey; +- (void)try_acceptNewIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); +- (nullable NSData *)try_newIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - (NSString *)theirSignalId; @end diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m index 78fbbcc30..301cfe900 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m @@ -8,12 +8,12 @@ NS_ASSUME_NONNULL_BEGIN @implementation TSInvalidIdentityKeyErrorMessage -- (void)acceptNewIdentityKey +- (void)try_acceptNewIdentityKey { OWSAbstractMethod(); } -- (nullable NSData *)newIdentityKey +- (nullable NSData *)try_newIdentityKey { OWSAbstractMethod(); return nil; diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m index 19987c1d1..ccc55a8bd 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m @@ -81,7 +81,7 @@ NS_ASSUME_NONNULL_BEGIN return _envelope; } -- (void)acceptNewIdentityKey +- (void)try_acceptNewIdentityKey { OWSAssertIsOnMainThread(); @@ -90,7 +90,7 @@ NS_ASSUME_NONNULL_BEGIN return; } - NSData *_Nullable newKey = [self newIdentityKey]; + NSData *_Nullable newKey = [self try_newIdentityKey]; if (!newKey) { OWSFailDebug(@"Couldn't extract identity key to accept"); return; @@ -131,7 +131,7 @@ NS_ASSUME_NONNULL_BEGIN } PreKeyWhisperMessage *message = [[PreKeyWhisperMessage alloc] init_try_withData:pkwmData]; - return [message.identityKey removeKeyType]; + return [message.identityKey try_removeKeyType]; } - (NSString *)theirSignalId diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m index 01e4d179c..6e955bb90 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m @@ -45,13 +45,13 @@ NSString *TSInvalidRecipientKey = @"TSInvalidRecipientKey"; return self; } -- (void)acceptNewIdentityKey +- (void)try_acceptNewIdentityKey { // Shouldn't really get here, since we're no longer creating blocking SN changes. // But there may still be some old unaccepted SN errors in the wild that need to be accepted. OWSFailDebug(@"accepting new identity key is deprecated."); - NSData *_Nullable newIdentityKey = self.newIdentityKey; + NSData *_Nullable newIdentityKey = [self try_newIdentityKey]; if (!newIdentityKey) { OWSFailDebug(@"newIdentityKey is unexpectedly nil. Bad Prekey bundle?: %@", self.preKeyBundle); return; @@ -60,9 +60,9 @@ NSString *TSInvalidRecipientKey = @"TSInvalidRecipientKey"; [[OWSIdentityManager sharedManager] saveRemoteIdentity:newIdentityKey recipientId:self.recipientId]; } -- (nullable NSData *)newIdentityKey +- (nullable NSData *)try_newIdentityKey { - return [self.preKeyBundle.identityKey removeKeyType]; + return [self.preKeyBundle.identityKey try_removeKeyType]; } - (NSString *)theirSignalId diff --git a/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m b/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m index df04ac7ff..697040c99 100644 --- a/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m +++ b/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m @@ -403,9 +403,9 @@ NSString *const OWSMessageContentJobFinderExtensionGroup = @"OWSMessageContentJo if (!envelope) { reportFailure(transaction); } else { - [self.messageManager processEnvelope:envelope - plaintextData:job.plaintextData - transaction:transaction]; + [self.messageManager try_processEnvelope:envelope + plaintextData:job.plaintextData + transaction:transaction]; } } @catch (NSException *exception) { OWSFailDebug(@"Received an invalid envelope: %@", exception.debugDescription); diff --git a/SignalServiceKit/src/Messages/OWSIdentityManager.h b/SignalServiceKit/src/Messages/OWSIdentityManager.h index 838de61d9..7f1c5c060 100644 --- a/SignalServiceKit/src/Messages/OWSIdentityManager.h +++ b/SignalServiceKit/src/Messages/OWSIdentityManager.h @@ -60,8 +60,8 @@ extern const NSUInteger kStoredIdentityKeyLength; - (nullable OWSRecipientIdentity *)untrustedIdentityForSendingToRecipientId:(NSString *)recipientId; // This method can be called from any thread. -- (void)processIncomingSyncMessage:(SSKProtoVerified *)verified - transaction:(YapDatabaseReadWriteTransaction *)transaction; +- (void)try_processIncomingSyncMessage:(SSKProtoVerified *)verified + transaction:(YapDatabaseReadWriteTransaction *)transaction; - (BOOL)saveRemoteIdentity:(NSData *)identityKey recipientId:(NSString *)recipientId; diff --git a/SignalServiceKit/src/Messages/OWSIdentityManager.m b/SignalServiceKit/src/Messages/OWSIdentityManager.m index 590209bdf..25ab45230 100644 --- a/SignalServiceKit/src/Messages/OWSIdentityManager.m +++ b/SignalServiceKit/src/Messages/OWSIdentityManager.m @@ -678,8 +678,8 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa [transaction removeObjectForKey:recipientId inCollection:OWSIdentityManager_QueuedVerificationStateSyncMessages]; } -- (void)processIncomingSyncMessage:(SSKProtoVerified *)verified - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)try_processIncomingSyncMessage:(SSKProtoVerified *)verified + transaction:(YapDatabaseReadWriteTransaction *)transaction { OWSAssertDebug(verified); OWSAssertDebug(transaction); @@ -696,7 +696,7 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa rawIdentityKey); return; } - NSData *identityKey = [rawIdentityKey removeKeyType]; + NSData *identityKey = [rawIdentityKey try_removeKeyType]; switch (verified.state) { case SSKProtoVerifiedStateDefault: diff --git a/SignalServiceKit/src/Messages/OWSMessageManager.h b/SignalServiceKit/src/Messages/OWSMessageManager.h index 0e7cd51e4..fc8e2a43a 100644 --- a/SignalServiceKit/src/Messages/OWSMessageManager.h +++ b/SignalServiceKit/src/Messages/OWSMessageManager.h @@ -19,9 +19,9 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)initWithPrimaryStorage:(OWSPrimaryStorage *)primaryStorage NS_DESIGNATED_INITIALIZER; // processEnvelope: can be called from any thread. -- (void)processEnvelope:(SSKProtoEnvelope *)envelope - plaintextData:(NSData *_Nullable)plaintextData - transaction:(YapDatabaseReadWriteTransaction *)transaction; +- (void)try_processEnvelope:(SSKProtoEnvelope *)envelope + plaintextData:(NSData *_Nullable)plaintextData + transaction:(YapDatabaseReadWriteTransaction *)transaction; // This should be invoked by the main app when the app is ready. - (void)startObserving; diff --git a/SignalServiceKit/src/Messages/OWSMessageManager.m b/SignalServiceKit/src/Messages/OWSMessageManager.m index 514d5c3d2..ae3583e74 100644 --- a/SignalServiceKit/src/Messages/OWSMessageManager.m +++ b/SignalServiceKit/src/Messages/OWSMessageManager.m @@ -212,9 +212,9 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - message handling -- (void)processEnvelope:(SSKProtoEnvelope *)envelope - plaintextData:(NSData *_Nullable)plaintextData - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)try_processEnvelope:(SSKProtoEnvelope *)envelope + plaintextData:(NSData *_Nullable)plaintextData + transaction:(YapDatabaseReadWriteTransaction *)transaction { if (!envelope) { OWSFailDebug(@"Missing envelope."); @@ -256,7 +256,7 @@ NS_ASSUME_NONNULL_BEGIN OWSFailDebug(@"missing decrypted data for envelope: %@", [self descriptionForEnvelope:envelope]); return; } - [self handleEnvelope:envelope plaintextData:plaintextData transaction:transaction]; + [self try_handleEnvelope:envelope plaintextData:plaintextData transaction:transaction]; break; case SSKProtoEnvelopeTypeReceipt: OWSAssertDebug(!plaintextData); @@ -345,9 +345,9 @@ NS_ASSUME_NONNULL_BEGIN } } -- (void)handleEnvelope:(SSKProtoEnvelope *)envelope - plaintextData:(NSData *)plaintextData - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)try_handleEnvelope:(SSKProtoEnvelope *)envelope + plaintextData:(NSData *)plaintextData + transaction:(YapDatabaseReadWriteTransaction *)transaction { if (!envelope) { OWSFailDebug(@"Missing envelope."); @@ -395,7 +395,7 @@ NS_ASSUME_NONNULL_BEGIN OWSLogInfo(@"handling content: ", [self descriptionForContent:contentProto]); if (contentProto.syncMessage) { - [self handleIncomingEnvelope:envelope withSyncMessage:contentProto.syncMessage transaction:transaction]; + [self try_handleIncomingEnvelope:envelope withSyncMessage:contentProto.syncMessage transaction:transaction]; [[OWSDeviceManager sharedManager] setHasReceivedSyncMessage]; } else if (contentProto.dataMessage) { @@ -745,9 +745,9 @@ NS_ASSUME_NONNULL_BEGIN }]; } -- (void)handleIncomingEnvelope:(SSKProtoEnvelope *)envelope - withSyncMessage:(SSKProtoSyncMessage *)syncMessage - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)try_handleIncomingEnvelope:(SSKProtoEnvelope *)envelope + withSyncMessage:(SSKProtoSyncMessage *)syncMessage + transaction:(YapDatabaseReadWriteTransaction *)transaction { if (!envelope) { OWSFailDebug(@"Missing envelope."); @@ -862,7 +862,7 @@ NS_ASSUME_NONNULL_BEGIN transaction:transaction]; } else if (syncMessage.verified) { OWSLogInfo(@"Received verification state for %@", syncMessage.verified.destination); - [self.identityManager processIncomingSyncMessage:syncMessage.verified transaction:transaction]; + [self.identityManager try_processIncomingSyncMessage:syncMessage.verified transaction:transaction]; } else { OWSLogWarn(@"Ignoring unsupported sync message."); } diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index 7a0d79707..a31e35d7b 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -888,7 +888,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; return nil; } - NSData *newIdentityKey = [newIdentityKeyWithVersion removeKeyType]; + NSData *newIdentityKey = [newIdentityKeyWithVersion try_removeKeyType]; [self.identityManager saveRemoteIdentity:newIdentityKey recipientId:recipient.recipientId]; return nil; diff --git a/SignalServiceKit/src/Network/API/SignalServiceProfile.swift b/SignalServiceKit/src/Network/API/SignalServiceProfile.swift index 4d79540c4..e1175884f 100644 --- a/SignalServiceKit/src/Network/API/SignalServiceProfile.swift +++ b/SignalServiceKit/src/Network/API/SignalServiceProfile.swift @@ -32,8 +32,15 @@ public class SignalServiceProfile: NSObject { guard identityKeyWithType.count == kIdentityKeyLength else { throw ValidationError.invalidIdentityKey(description: "malformed identity key \(identityKeyWithType.hexadecimalString) with decoded length: \(identityKeyWithType.count)") } - // `removeKeyType` is an objc category method only on NSData, so temporarily cast. - self.identityKey = (identityKeyWithType as NSData).removeKeyType() as Data + do { + // `removeKeyType` is an objc category method only on NSData, so temporarily cast. + self.identityKey = try (identityKeyWithType as NSData).removeKeyType() as Data + } catch { + // `removeKeyType` throws an SCKExceptionWrapperError, which, typically should + // be unwrapped by any objc code calling this method. + owsFailDebug("identify key had unexpected format") + throw ValidationError.invalidIdentityKey(description: "malformed identity key \(identityKeyWithType.hexadecimalString) with data: \(identityKeyWithType)") + } self.profileNameEncrypted = try params.optionalBase64EncodedData(key: "name") From 9d2731c9b8b23438db7c19e22abeb3766251636f Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 15:08:25 -0600 Subject: [PATCH 07/16] exception auditing OWSRaiseException --- .../environment/migrations/OWSDatabaseMigration.m | 5 +++-- SignalServiceKit/src/Account/TSAccountManager.m | 2 +- SignalServiceKit/src/Contacts/CDSSigningCertificate.m | 3 +-- SignalServiceKit/src/Messages/OWSMessageSender.m | 11 ++++------- 4 files changed, 9 insertions(+), 12 deletions(-) diff --git a/SignalMessaging/environment/migrations/OWSDatabaseMigration.m b/SignalMessaging/environment/migrations/OWSDatabaseMigration.m index 1a7c7702f..75fc94aed 100644 --- a/SignalMessaging/environment/migrations/OWSDatabaseMigration.m +++ b/SignalMessaging/environment/migrations/OWSDatabaseMigration.m @@ -40,7 +40,8 @@ NS_ASSUME_NONNULL_BEGIN + (NSString *)migrationId { - OWSRaiseException(NSInternalInconsistencyException, @"Must override %@ in subclass", NSStringFromSelector(_cmd)); + OWSAbstractMethod(); + return @""; } + (NSString *)collection @@ -51,7 +52,7 @@ NS_ASSUME_NONNULL_BEGIN - (void)runUpWithTransaction:(YapDatabaseReadWriteTransaction *)transaction { - OWSRaiseException(NSInternalInconsistencyException, @"Must override %@ in subclass", NSStringFromSelector(_cmd)); + OWSAbstractMethod(); } - (void)runUpWithCompletion:(OWSDatabaseMigrationCompletion)completion diff --git a/SignalServiceKit/src/Account/TSAccountManager.m b/SignalServiceKit/src/Account/TSAccountManager.m index 5b1af082b..c1c8dcb40 100644 --- a/SignalServiceKit/src/Account/TSAccountManager.m +++ b/SignalServiceKit/src/Account/TSAccountManager.m @@ -159,7 +159,7 @@ NSString *const TSAccountManager_NeedsAccountAttributesUpdateKey = @"TSAccountMa NSString *phoneNumber = self.phoneNumberAwaitingVerification; if (!phoneNumber) { - OWSRaiseException(@"RegistrationFail", @"Internal Corrupted State"); + OWSFail(@"phonNumber was unexpectedly nil"); } [self storeLocalNumber:phoneNumber]; diff --git a/SignalServiceKit/src/Contacts/CDSSigningCertificate.m b/SignalServiceKit/src/Contacts/CDSSigningCertificate.m index 16e78c3fd..448b4d92c 100644 --- a/SignalServiceKit/src/Contacts/CDSSigningCertificate.m +++ b/SignalServiceKit/src/Contacts/CDSSigningCertificate.m @@ -213,8 +213,7 @@ NS_ASSUME_NONNULL_BEGIN // We need to use an Intel certificate as the anchor for IAS verification. NSData *_Nullable anchorCertificate = [self certificateDataForService:@"ias-root"]; if (!anchorCertificate) { - OWSFailDebug(@"could not load anchor certificate."); - OWSRaiseException(@"OWSSignalService_CouldNotLoadCertificate", @"%s", __PRETTY_FUNCTION__); + OWSFail(@"could not load anchor certificate."); } else { anchorCertificates = @[ anchorCertificate ]; } diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index a31e35d7b..6d87671b5 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -839,7 +839,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; NSArray *deviceMessages; @try { - deviceMessages = [self deviceMessagesForMessageSendUnsafe:messageSend]; + deviceMessages = [self try_deviceMessagesForMessageSendUnsafe:messageSend]; } @catch (NSException *exception) { if ([exception.name isEqualToString:UntrustedIdentityKeyException]) { // This *can* happen under normal usage, but it should happen relatively rarely. @@ -1407,8 +1407,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; [self sendMessageToRecipient:messageSend]; } -// NOTE: This method uses exceptions for control flow. -- (NSArray *)deviceMessagesForMessageSendUnsafe:(OWSMessageSend *)messageSend +- (NSArray *)try_deviceMessagesForMessageSendUnsafe:(OWSMessageSend *)messageSend { OWSAssertDebug(messageSend.message); OWSAssertDebug(messageSend.recipient); @@ -1444,7 +1443,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; @try { // This may involve blocking network requests, so we do it _before_ // we open a transaction. - [self ensureRecipientHasSessionForMessageSend:messageSend deviceId:deviceId]; + [self try_ensureRecipientHasSessionForMessageSend:messageSend deviceId:deviceId]; __block NSDictionary *messageDict; __block NSException *encryptionException; @@ -1486,9 +1485,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; return [messagesArray copy]; } -// NOTE: This method uses exceptions for control flow. -- (void)ensureRecipientHasSessionForMessageSend:(OWSMessageSend *)messageSend - deviceId:(NSNumber *)deviceId +- (void)try_ensureRecipientHasSessionForMessageSend:(OWSMessageSend *)messageSend deviceId:(NSNumber *)deviceId { OWSAssertDebug(messageSend); OWSAssertDebug(deviceId); From c686e766b165a32244a0f608a3fbb5c365b7a419 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 15:16:56 -0600 Subject: [PATCH 08/16] Exception audit, fail directly where intended --- .../src/Network/API/Requests/TSRequest.m | 4 ++-- .../src/Network/OWSCensorshipConfiguration.m | 6 ++---- .../src/Security/OWSHTTPSecurityPolicy.m | 2 +- SignalServiceKit/src/Storage/OWSPrimaryStorage.m | 5 +---- SignalServiceKit/src/Storage/OWSStorage.m | 16 ++++------------ SignalServiceKit/src/Util/UIImage+OWS.m | 3 ++- 6 files changed, 12 insertions(+), 24 deletions(-) diff --git a/SignalServiceKit/src/Network/API/Requests/TSRequest.m b/SignalServiceKit/src/Network/API/Requests/TSRequest.m index b3efd0723..e253706f7 100644 --- a/SignalServiceKit/src/Network/API/Requests/TSRequest.m +++ b/SignalServiceKit/src/Network/API/Requests/TSRequest.m @@ -30,7 +30,7 @@ - (instancetype)init { - OWSRaiseException(NSInternalInconsistencyException, @"You must use the initWithURL: method"); + OWSFail(@"You must use the initWithURL: method"); return nil; } @@ -41,7 +41,7 @@ cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval { - OWSRaiseException(NSInternalInconsistencyException, @"You must use the initWithURL method"); + OWSFail(@"You must use the initWithURL: method"); return nil; } diff --git a/SignalServiceKit/src/Network/OWSCensorshipConfiguration.m b/SignalServiceKit/src/Network/OWSCensorshipConfiguration.m index 943ff7a87..3ddbea908 100644 --- a/SignalServiceKit/src/Network/OWSCensorshipConfiguration.m +++ b/SignalServiceKit/src/Network/OWSCensorshipConfiguration.m @@ -152,13 +152,11 @@ NSString *const OWSCensorshipConfiguration_DefaultFrontingHost = OWSCensorshipCo NSError *error; NSData *certData = [self certificateDataWithName:certName error:&error]; if (error) { - OWSLogError(@"reading data for certificate: %@ failed with error: %@", certName, error); - OWSRaiseException(@"OWSSignalService_UnableToReadCertificate", @"%@", error.description); + OWSFail(@"reading data for certificate: %@ failed with error: %@", certName, error); } if (!certData) { - OWSLogError(@"No data for certificate: %@", certName); - OWSRaiseException(@"OWSSignalService_UnableToReadCertificate", @"%@", error.description); + OWSFail(@"reading data for certificate: %@ failed with error: %@", certName, error); } [certificates addObject:certData]; } diff --git a/SignalServiceKit/src/Security/OWSHTTPSecurityPolicy.m b/SignalServiceKit/src/Security/OWSHTTPSecurityPolicy.m index ad358de61..40a518705 100644 --- a/SignalServiceKit/src/Security/OWSHTTPSecurityPolicy.m +++ b/SignalServiceKit/src/Security/OWSHTTPSecurityPolicy.m @@ -43,7 +43,7 @@ NSString *path = [bundle pathForResource:service ofType:@"cer"]; if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { - OWSRaiseException(@"Missing server certificate", @"Missing signing certificate for service %@", service); + OWSFail(@"Missing signing certificate for service %@", service); } NSData *certificateData = [NSData dataWithContentsOfFile:path]; diff --git a/SignalServiceKit/src/Storage/OWSPrimaryStorage.m b/SignalServiceKit/src/Storage/OWSPrimaryStorage.m index b7000f0f7..982a721af 100644 --- a/SignalServiceKit/src/Storage/OWSPrimaryStorage.m +++ b/SignalServiceKit/src/Storage/OWSPrimaryStorage.m @@ -28,8 +28,6 @@ NSString *const OWSUIDatabaseConnectionWillUpdateExternallyNotification = @"OWSU NSString *const OWSUIDatabaseConnectionDidUpdateExternallyNotification = @"OWSUIDatabaseConnectionDidUpdateExternallyNotification"; NSString *const OWSUIDatabaseConnectionNotificationsKey = @"OWSUIDatabaseConnectionNotificationsKey"; -NSString *const OWSPrimaryStorageExceptionName_CouldNotCreateDatabaseDirectory - = @"TSStorageManagerExceptionName_CouldNotCreateDatabaseDirectory"; void VerifyRegistrationsForPrimaryStorage(OWSStorage *storage) { @@ -252,8 +250,7 @@ void VerifyRegistrationsForPrimaryStorage(OWSStorage *storage) NSString *databaseDirPath = [[OWSFileSystem appSharedDataDirectoryPath] stringByAppendingPathComponent:@"database"]; if (![OWSFileSystem ensureDirectoryExists:databaseDirPath]) { - OWSRaiseException( - OWSPrimaryStorageExceptionName_CouldNotCreateDatabaseDirectory, @"Could not create new database directory"); + OWSFail(@"Could not create new database directory"); } return databaseDirPath; } diff --git a/SignalServiceKit/src/Storage/OWSStorage.m b/SignalServiceKit/src/Storage/OWSStorage.m index 285a0f210..597e51d45 100644 --- a/SignalServiceKit/src/Storage/OWSStorage.m +++ b/SignalServiceKit/src/Storage/OWSStorage.m @@ -26,12 +26,6 @@ NS_ASSUME_NONNULL_BEGIN NSString *const StorageIsReadyNotification = @"StorageIsReadyNotification"; - -NSString *const OWSStorageExceptionName_DatabasePasswordInaccessibleWhileBackgrounded - = @"OWSStorageExceptionName_DatabasePasswordInaccessibleWhileBackgrounded"; -NSString *const OWSStorageExceptionName_DatabasePasswordUnwritable - = @"OWSStorageExceptionName_DatabasePasswordUnwritable"; -NSString *const OWSStorageExceptionName_NoDatabase = @"OWSStorageExceptionName_NoDatabase"; NSString *const OWSResetStorageNotification = @"OWSResetStorageNotification"; static NSString *keychainService = @"TSKeyChainService"; @@ -330,7 +324,7 @@ NSString *const kNSUserDefaults_DatabaseExtensionVersionMap = @"kNSUserDefaults_ // Sleep to give analytics events time to be delivered. [NSThread sleepForTimeInterval:15.0f]; - OWSRaiseException(OWSStorageExceptionName_NoDatabase, @"Failed to initialize database."); + OWSFail(@"Failed to initialize database."); } } } @@ -503,8 +497,7 @@ NSString *const kNSUserDefaults_DatabaseExtensionVersionMap = @"kNSUserDefaults_ { YapDatabaseConnection *dbConnection = self.database.newConnection; if (!dbConnection) { - OWSRaiseException( - @"OWSStorageExceptionName_CouldNotOpenConnection", @"Storage could not open new database connection."); + OWSFail(@"Storage could not open new database connection."); } return dbConnection; } @@ -862,7 +855,7 @@ NSString *const kNSUserDefaults_DatabaseExtensionVersionMap = @"kNSUserDefaults_ // Presumably this happened in response to a push notification. It's possible that the keychain is corrupted // but it could also just be that the user hasn't yet unlocked their device since our password is // kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly - OWSRaiseException(OWSStorageExceptionName_DatabasePasswordInaccessibleWhileBackgrounded, @"%@", errorDescription); + OWSFail(@"%@", errorDescription); } + (void)deleteDBKeys @@ -925,8 +918,7 @@ NSString *const kNSUserDefaults_DatabaseExtensionVersionMap = @"kNSUserDefaults_ // Sleep to give analytics events time to be delivered. [NSThread sleepForTimeInterval:15.0f]; - OWSRaiseException( - OWSStorageExceptionName_DatabasePasswordUnwritable, @"Setting keychain value failed with error: %@", error); + OWSFail(@"Setting keychain value failed with error: %@", error); } else { OWSLogWarn(@"Successfully set new keychain value."); } diff --git a/SignalServiceKit/src/Util/UIImage+OWS.m b/SignalServiceKit/src/Util/UIImage+OWS.m index 8619cbeed..69c78784f 100644 --- a/SignalServiceKit/src/Util/UIImage+OWS.m +++ b/SignalServiceKit/src/Util/UIImage+OWS.m @@ -138,7 +138,8 @@ break; default: - OWSRaiseException(NSInternalInconsistencyException, @"Invalid image orientation"); + OWSFailDebug(@"Invalid image orientation"); + return nil; } ///////////////////////////////////////////////////////////////////////////// From c4f8975308fb03d574a510eaa3b54dea47daf0c4 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 21:26:40 -0600 Subject: [PATCH 09/16] Swift Exception wrap Curve25519 --- .../src/Contacts/ContactDiscoveryService.m | 4 +- .../src/Devices/OWSProvisioningCipher.m | 10 ++--- .../src/Messages/OWSMessageSender.m | 2 +- .../src/Messages/UD/OWSUDManager.swift | 37 ++++++++++--------- .../OWSPrimaryStorage+SignedPreKeyStore.m | 18 ++++++--- 5 files changed, 39 insertions(+), 32 deletions(-) diff --git a/SignalServiceKit/src/Contacts/ContactDiscoveryService.m b/SignalServiceKit/src/Contacts/ContactDiscoveryService.m index 922ecbdf6..c0d8dec35 100644 --- a/SignalServiceKit/src/Contacts/ContactDiscoveryService.m +++ b/SignalServiceKit/src/Contacts/ContactDiscoveryService.m @@ -83,9 +83,9 @@ NSErrorDomain const ContactDiscoveryServiceErrorDomain = @"SignalServiceKit.Cont NSData *ephemeralToStatic; @try { ephemeralToEphemeral = - [Curve25519 generateSharedSecretFromPublicKey:self.serverEphemeralPublic andKeyPair:self.keyPair]; + [Curve25519 try_generateSharedSecretFromPublicKey:self.serverEphemeralPublic andKeyPair:self.keyPair]; ephemeralToStatic = - [Curve25519 generateSharedSecretFromPublicKey:self.serverStaticPublic andKeyPair:self.keyPair]; + [Curve25519 try_generateSharedSecretFromPublicKey:self.serverStaticPublic andKeyPair:self.keyPair]; } @catch (NSException *exception) { OWSFailDebug(@"could not generate shared secrets: %@", exception); return NO; diff --git a/SignalServiceKit/src/Devices/OWSProvisioningCipher.m b/SignalServiceKit/src/Devices/OWSProvisioningCipher.m index 2541e4fb9..8f6746d85 100644 --- a/SignalServiceKit/src/Devices/OWSProvisioningCipher.m +++ b/SignalServiceKit/src/Devices/OWSProvisioningCipher.m @@ -54,11 +54,7 @@ NS_ASSUME_NONNULL_BEGIN - (nullable NSData *)encrypt:(NSData *)dataToEncrypt { @try { - // Exceptions can be thrown in a number of places in encryptUnsafe, e.g.: - // - // * Curve25519's generateSharedSecretFromPublicKey. - // * [HKDFKit deriveKey]. - return [self encryptUnsafe:dataToEncrypt]; + return [self try_encryptWithData:dataToEncrypt]; } @catch (NSException *exception) { OWSFailDebug(@"exception: %@ of type: %@ with reason: %@, user info: %@.", exception.description, @@ -69,10 +65,10 @@ NS_ASSUME_NONNULL_BEGIN } } -- (nullable NSData *)encryptUnsafe:(NSData *)dataToEncrypt +- (nullable NSData *)try_encryptWithData:(NSData *)dataToEncrypt { NSData *sharedSecret = - [Curve25519 generateSharedSecretFromPublicKey:self.theirPublicKey andKeyPair:self.ourKeyPair]; + [Curve25519 try_generateSharedSecretFromPublicKey:self.theirPublicKey andKeyPair:self.ourKeyPair]; NSData *infoData = [@"TextSecure Provisioning Message" dataUsingEncoding:NSASCIIStringEncoding]; NSData *nullSalt = [[NSMutableData dataWithLength:32] copy]; diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index 6d87671b5..a56d1361b 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -479,7 +479,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; failure:(RetryableFailureHandler)failure { [self.udManager - ensureSenderCertificateObjCWithSuccess:^(SMKSenderCertificate *senderCertificate) { + trywrapped_ensureSenderCertificateWithSuccess:^(SMKSenderCertificate *senderCertificate) { dispatch_async([OWSDispatch sendingQueue], ^{ [self sendMessageToService:message senderCertificate:senderCertificate success:success failure:failure]; }); diff --git a/SignalServiceKit/src/Messages/UD/OWSUDManager.swift b/SignalServiceKit/src/Messages/UD/OWSUDManager.swift index 22ab6a428..f4d6a7af9 100644 --- a/SignalServiceKit/src/Messages/UD/OWSUDManager.swift +++ b/SignalServiceKit/src/Messages/UD/OWSUDManager.swift @@ -65,7 +65,7 @@ private func string(forUnidentifiedAccessMode mode: UnidentifiedAccessMode) -> S // We use completion handlers instead of a promise so that message sending // logic can access the strongly typed certificate data. @objc - func ensureSenderCertificateObjC(success:@escaping (SMKSenderCertificate) -> Void, + func trywrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, failure:@escaping (Error) -> Void) // MARK: Unrestricted Access @@ -109,7 +109,9 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { guard TSAccountManager.isRegistered() else { return } - self.ensureSenderCertificate().retainUntilComplete() + + // Any error is silently ignored on startup. + self.trywrapped_ensureSenderCertificate().retainUntilComplete() } NotificationCenter.default.addObserver(self, selector: #selector(registrationStateDidChange), @@ -121,7 +123,8 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { func registrationStateDidChange() { AssertIsOnMainThread() - ensureSenderCertificate().retainUntilComplete() + // Any error is silently ignored + trywrapped_ensureSenderCertificate().retainUntilComplete() } // MARK: - @@ -263,12 +266,12 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { #if DEBUG @objc - public func hasSenderCertificate() -> Bool { - return senderCertificate() != nil + public func trywrapped_hasSenderCertificate() -> Bool { + return trywrapped_senderCertificate() != nil } #endif - private func senderCertificate() -> SMKSenderCertificate? { + private func trywrapped_senderCertificate() -> SMKSenderCertificate? { guard let certificateData = dbConnection.object(forKey: senderCertificateKey(), inCollection: kUDCollection) as? Data else { return nil } @@ -276,7 +279,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { do { let certificate = try SMKSenderCertificate.parse(data: certificateData) - guard isValidCertificate(certificate) else { + guard trywrapped_isValidCertificate(certificate) else { Logger.warn("Current sender certificate is not valid.") return nil } @@ -297,10 +300,10 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } @objc - public func ensureSenderCertificateObjC(success:@escaping (SMKSenderCertificate) -> Void, - failure:@escaping (Error) -> Void) { + public func trywrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, + failure:@escaping (Error) -> Void) { firstly { - ensureSenderCertificate() + trywrapped_ensureSenderCertificate() }.map { certificate in success(certificate) }.catch { error in @@ -308,15 +311,15 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { }.retainUntilComplete() } - public func ensureSenderCertificate() -> Promise { + public func trywrapped_ensureSenderCertificate() -> Promise { // If there is a valid cached sender certificate, use that. - if let certificate = senderCertificate() { + if let certificate = trywrapped_senderCertificate() { return Promise.value(certificate) } // Try to obtain a new sender certificate. return firstly { - requestSenderCertificate() + trywrapped_requestSenderCertificate() }.map { (certificateData: Data, certificate: SMKSenderCertificate) in // Cache the current sender certificate. @@ -326,13 +329,13 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } } - private func requestSenderCertificate() -> Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { + private func trywrapped_requestSenderCertificate() -> Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { return firstly { SignalServiceRestClient().requestUDSenderCertificate() }.map { certificateData -> (certificateData: Data, certificate: SMKSenderCertificate) in let certificate = try SMKSenderCertificate.parse(data: certificateData) - guard self.isValidCertificate(certificate) else { + guard self.trywrapped_isValidCertificate(certificate) else { throw OWSUDError.invalidData(description: "Invalid sender certificate returned by server") } @@ -340,7 +343,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } } - private func isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { + private func trywrapped_isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { // Ensure that the certificate will not expire in the next hour. // We want a threshold long enough to ensure that any outgoing message // sends will complete before the expiration. @@ -348,7 +351,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { let anHourFromNowMs = nowMs + kHourInMs do { - try certificateValidator.validate(senderCertificate: certificate, validationTime: anHourFromNowMs) + try certificateValidator.trywrapped_validate(senderCertificate: certificate, validationTime: anHourFromNowMs) return true } catch { OWSLogger.error("Invalid certificate") diff --git a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m index 423cd3e7a..2e7394cd1 100644 --- a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m +++ b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m @@ -29,11 +29,19 @@ NSString *const OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId = @"currentSigne // Signed prekey ids must be > 0. int preKeyId = 1 + arc4random_uniform(INT32_MAX - 1); ECKeyPair *_Nullable identityKeyPair = [[OWSIdentityManager sharedManager] identityKeyPair]; - return [[SignedPreKeyRecord alloc] - initWithId:preKeyId - keyPair:keyPair - signature:[Ed25519 sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair] - generatedAt:[NSDate date]]; + OWSAssert(identityKeyPair); + @try { + return [[SignedPreKeyRecord alloc] + initWithId:preKeyId + keyPair:keyPair + signature:[Ed25519 try_sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair] + generatedAt:[NSDate date]]; + } @catch (NSException *exception) { + // try_sign only throws when the data to sign is empty or `keyPair`. + // Neither of which should happen. + OWSFail(@"exception: %@", exception); + return nil; + } } - (SignedPreKeyRecord *)try_loadSignedPrekey:(int)signedPreKeyId From 8544c86427bbd6251c275ea5ec8cf9957003d66c Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 22:12:21 -0600 Subject: [PATCH 10/16] Swift Exception wrap HKDFKit --- SignalServiceKit/src/Contacts/ContactDiscoveryService.m | 2 +- SignalServiceKit/src/Devices/OWSProvisioningCipher.m | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/SignalServiceKit/src/Contacts/ContactDiscoveryService.m b/SignalServiceKit/src/Contacts/ContactDiscoveryService.m index c0d8dec35..b20b678a1 100644 --- a/SignalServiceKit/src/Contacts/ContactDiscoveryService.m +++ b/SignalServiceKit/src/Contacts/ContactDiscoveryService.m @@ -101,7 +101,7 @@ NSErrorDomain const ContactDiscoveryServiceErrorDomain = @"SignalServiceKit.Cont NSData *_Nullable derivedMaterial; @try { derivedMaterial = - [HKDFKit deriveKey:masterSecret info:nil salt:publicKeys outputSize:(int)kAES256_KeyByteLength * 2]; + [HKDFKit try_deriveKey:masterSecret info:nil salt:publicKeys outputSize:(int)kAES256_KeyByteLength * 2]; } @catch (NSException *exception) { OWSFailDebug(@"could not derive service key: %@", exception); return NO; diff --git a/SignalServiceKit/src/Devices/OWSProvisioningCipher.m b/SignalServiceKit/src/Devices/OWSProvisioningCipher.m index 8f6746d85..451f84714 100644 --- a/SignalServiceKit/src/Devices/OWSProvisioningCipher.m +++ b/SignalServiceKit/src/Devices/OWSProvisioningCipher.m @@ -72,7 +72,7 @@ NS_ASSUME_NONNULL_BEGIN NSData *infoData = [@"TextSecure Provisioning Message" dataUsingEncoding:NSASCIIStringEncoding]; NSData *nullSalt = [[NSMutableData dataWithLength:32] copy]; - NSData *derivedSecret = [HKDFKit deriveKey:sharedSecret info:infoData salt:nullSalt outputSize:64]; + NSData *derivedSecret = [HKDFKit try_deriveKey:sharedSecret info:infoData salt:nullSalt outputSize:64]; NSData *cipherKey = [derivedSecret subdataWithRange:NSMakeRange(0, 32)]; NSData *macKey = [derivedSecret subdataWithRange:NSMakeRange(32, 32)]; if (cipherKey.length != 32) { From e09a1814452fe3157087ee82c9831cd7cd91055b Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Mon, 29 Oct 2018 22:17:25 -0600 Subject: [PATCH 11/16] SQUASHME review podfile changes --- Podfile | 4 ++-- Podfile.lock | 24 +++++++++++------------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/Podfile b/Podfile index d969776a1..228be5bb6 100644 --- a/Podfile +++ b/Podfile @@ -5,7 +5,7 @@ use_frameworks! def shared_pods # OWS Pods - pod 'SignalCoreKit', git: 'git@github.com:signalapp/SignalCoreKit-Private.git', branch: 'mkirk/wrap-exceptions', testspecs: ["Tests"] + pod 'SignalCoreKit', git: 'https://github.com/signalapp/SignalCoreKit.git', testspecs: ["Tests"] # pod 'SignalCoreKit', path: '../SignalCoreKit', testspecs: ["Tests"] # pod 'SQLCipher', path: '../sqlcipher2' pod 'SQLCipher', :git => 'https://github.com/sqlcipher/sqlcipher.git', :commit => 'd5c2bec' @@ -19,7 +19,7 @@ def shared_pods pod 'Curve25519Kit', git: 'https://github.com/signalapp/Curve25519Kit', testspecs: ["Tests"] # pod 'Curve25519Kit', path: '../Curve25519Kit', testspecs: ["Tests"] # TODO: Use public repo. - pod 'SignalMetadataKit', git: 'git@github.com:signalapp/SignalMetadataKit', branch: 'mkirk/wrap-exceptions', testspecs: ["Tests"] + pod 'SignalMetadataKit', git: 'https://github.com/signalapp/SignalMetadataKit', testspecs: ["Tests"] # pod 'SignalMetadataKit', path: '../SignalMetadataKit', testspecs: ["Tests"] pod 'SignalServiceKit', path: '.', testspecs: ["Tests"] pod 'GRKOpenSSLFramework', git: 'https://github.com/signalapp/GRKOpenSSLFramework' diff --git a/Podfile.lock b/Podfile.lock index b74e75f15..f9479ae58 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -192,10 +192,10 @@ DEPENDENCIES: - Mantle - PureLayout - Reachability - - "SignalCoreKit (from `git@github.com:signalapp/SignalCoreKit-Private.git`, branch `mkirk/wrap-exceptions`)" - - "SignalCoreKit/Tests (from `git@github.com:signalapp/SignalCoreKit-Private.git`, branch `mkirk/wrap-exceptions`)" - - "SignalMetadataKit (from `git@github.com:signalapp/SignalMetadataKit`, branch `mkirk/wrap-exceptions`)" - - "SignalMetadataKit/Tests (from `git@github.com:signalapp/SignalMetadataKit`, branch `mkirk/wrap-exceptions`)" + - SignalCoreKit (from `https://github.com/signalapp/SignalCoreKit.git`) + - SignalCoreKit/Tests (from `https://github.com/signalapp/SignalCoreKit.git`) + - SignalMetadataKit (from `https://github.com/signalapp/SignalMetadataKit`) + - SignalMetadataKit/Tests (from `https://github.com/signalapp/SignalMetadataKit`) - SignalServiceKit (from `.`) - SignalServiceKit/Tests (from `.`) - SocketRocket (from `https://github.com/signalapp/SocketRocket.git`, branch `mkirk/handle-sec-err`) @@ -229,11 +229,9 @@ EXTERNAL SOURCES: HKDFKit: :git: https://github.com/signalapp/HKDFKit.git SignalCoreKit: - :branch: mkirk/wrap-exceptions - :git: "git@github.com:signalapp/SignalCoreKit-Private.git" + :git: https://github.com/signalapp/SignalCoreKit.git SignalMetadataKit: - :branch: mkirk/wrap-exceptions - :git: "git@github.com:signalapp/SignalMetadataKit" + :git: https://github.com/signalapp/SignalMetadataKit SignalServiceKit: :path: "." SocketRocket: @@ -260,11 +258,11 @@ CHECKOUT OPTIONS: :commit: 8b8326cd50bc488663a3d3743f1a92b90f4d85b4 :git: https://github.com/signalapp/HKDFKit.git SignalCoreKit: - :commit: df8d9528eb5e7e161ea04393a0d7972cd8539c14 - :git: "git@github.com:signalapp/SignalCoreKit-Private.git" + :commit: ff0b95770520133b83a4bd7b26bc2c90b51abc4d + :git: https://github.com/signalapp/SignalCoreKit.git SignalMetadataKit: - :commit: 07326a8ebb8e207bbe0e08fc6cd1d4979acc83d6 - :git: "git@github.com:signalapp/SignalMetadataKit" + :commit: 90f3dee7122ff13061770c496001135ba90b71e3 + :git: https://github.com/signalapp/SignalMetadataKit SocketRocket: :commit: 9f9563a83cd8960503074aa8de72206f83fb7a69 :git: https://github.com/signalapp/SocketRocket.git @@ -298,6 +296,6 @@ SPEC CHECKSUMS: YapDatabase: b418a4baa6906e8028748938f9159807fd039af4 YYImage: 1e1b62a9997399593e4b9c4ecfbbabbf1d3f3b54 -PODFILE CHECKSUM: 794d0aeb047ca81b7c697f99e43b6f80ea4ce585 +PODFILE CHECKSUM: 820287bc7925d7c20e02a02923976c60b1f5386b COCOAPODS: 1.5.3 From cb9aa6304ccf4992bdc5b908ffb025e805db2346 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Tue, 30 Oct 2018 09:21:26 -0600 Subject: [PATCH 12/16] find -E . -type f -regex ".*\.(m|h)" -exec sed -i "" -e "s/try_/throws_/" {} \; --- .../Models/OWSDeviceProvisioningURLParser.m | 2 +- .../ConversationViewController.m | 2 +- SignalMessaging/utils/ThreadUtil.m | 2 +- .../src/Contacts/ContactDiscoveryService.m | 6 ++-- SignalServiceKit/src/Contacts/TSThread.m | 2 +- .../src/Devices/OWSProvisioningCipher.m | 8 ++--- .../TSInvalidIdentityKeyErrorMessage.h | 4 +-- .../TSInvalidIdentityKeyErrorMessage.m | 4 +-- ...SInvalidIdentityKeyReceivingErrorMessage.m | 10 +++--- .../TSInvalidIdentityKeySendingErrorMessage.m | 8 ++--- .../src/Messages/OWSBatchMessageProcessor.m | 6 ++-- .../src/Messages/OWSIdentityManager.h | 4 +-- .../src/Messages/OWSIdentityManager.m | 6 ++-- .../src/Messages/OWSMessageDecrypter.m | 26 +++++++-------- .../src/Messages/OWSMessageManager.h | 6 ++-- .../src/Messages/OWSMessageManager.m | 26 ++++++++------- .../src/Messages/OWSMessageSender.m | 32 +++++++++---------- .../OWSPrimaryStorage+PreKeyStore.m | 2 +- .../OWSPrimaryStorage+SignedPreKeyStore.m | 6 ++-- .../tests/Storage/TSStoragePreKeyStoreTests.m | 8 ++--- 20 files changed, 86 insertions(+), 84 deletions(-) diff --git a/Signal/src/Models/OWSDeviceProvisioningURLParser.m b/Signal/src/Models/OWSDeviceProvisioningURLParser.m index 3710b5d09..3ae5d8665 100644 --- a/Signal/src/Models/OWSDeviceProvisioningURLParser.m +++ b/Signal/src/Models/OWSDeviceProvisioningURLParser.m @@ -27,7 +27,7 @@ NSString *const OWSQueryItemNameEncodedPublicKeyKey = @"pub_key"; } else if ([queryItem.name isEqualToString:OWSQueryItemNameEncodedPublicKeyKey]) { NSString *encodedPublicKey = queryItem.value; @try { - _publicKey = [[NSData dataFromBase64String:encodedPublicKey] try_removeKeyType]; + _publicKey = [[NSData dataFromBase64String:encodedPublicKey] throws_removeKeyType]; } @catch (NSException *exception) { OWSFailDebug(@"exception: %@", exception); } diff --git a/Signal/src/ViewControllers/ConversationView/ConversationViewController.m b/Signal/src/ViewControllers/ConversationView/ConversationViewController.m index d7fa7a29f..a5067d467 100644 --- a/Signal/src/ViewControllers/ConversationView/ConversationViewController.m +++ b/Signal/src/ViewControllers/ConversationView/ConversationViewController.m @@ -1903,7 +1903,7 @@ typedef enum : NSUInteger { if ([errorMessage isKindOfClass:[TSInvalidIdentityKeyReceivingErrorMessage class]]) { // Deliberately crash if the user fails to explicitly accept the new identity // key. In practice we haven't been creating these messags in over a year. - [errorMessage try_acceptNewIdentityKey]; + [errorMessage throws_acceptNewIdentityKey]; } }]; [actionSheetController addAction:acceptSafetyNumberAction]; diff --git a/SignalMessaging/utils/ThreadUtil.m b/SignalMessaging/utils/ThreadUtil.m index a961bae2a..a25363a29 100644 --- a/SignalMessaging/utils/ThreadUtil.m +++ b/SignalMessaging/utils/ThreadUtil.m @@ -632,7 +632,7 @@ NS_ASSUME_NONNULL_BEGIN } @try { - NSData *_Nullable newIdentityKey = [safetyNumberChange try_newIdentityKey]; + NSData *_Nullable newIdentityKey = [safetyNumberChange throws_newIdentityKey]; if (newIdentityKey == nil) { OWSFailDebug(@"Safety number change was missing it's new identity key."); continue; diff --git a/SignalServiceKit/src/Contacts/ContactDiscoveryService.m b/SignalServiceKit/src/Contacts/ContactDiscoveryService.m index b20b678a1..757fb1dd1 100644 --- a/SignalServiceKit/src/Contacts/ContactDiscoveryService.m +++ b/SignalServiceKit/src/Contacts/ContactDiscoveryService.m @@ -83,9 +83,9 @@ NSErrorDomain const ContactDiscoveryServiceErrorDomain = @"SignalServiceKit.Cont NSData *ephemeralToStatic; @try { ephemeralToEphemeral = - [Curve25519 try_generateSharedSecretFromPublicKey:self.serverEphemeralPublic andKeyPair:self.keyPair]; + [Curve25519 throws_generateSharedSecretFromPublicKey:self.serverEphemeralPublic andKeyPair:self.keyPair]; ephemeralToStatic = - [Curve25519 try_generateSharedSecretFromPublicKey:self.serverStaticPublic andKeyPair:self.keyPair]; + [Curve25519 throws_generateSharedSecretFromPublicKey:self.serverStaticPublic andKeyPair:self.keyPair]; } @catch (NSException *exception) { OWSFailDebug(@"could not generate shared secrets: %@", exception); return NO; @@ -101,7 +101,7 @@ NSErrorDomain const ContactDiscoveryServiceErrorDomain = @"SignalServiceKit.Cont NSData *_Nullable derivedMaterial; @try { derivedMaterial = - [HKDFKit try_deriveKey:masterSecret info:nil salt:publicKeys outputSize:(int)kAES256_KeyByteLength * 2]; + [HKDFKit throws_deriveKey:masterSecret info:nil salt:publicKeys outputSize:(int)kAES256_KeyByteLength * 2]; } @catch (NSException *exception) { OWSFailDebug(@"could not derive service key: %@", exception); return NO; diff --git a/SignalServiceKit/src/Contacts/TSThread.m b/SignalServiceKit/src/Contacts/TSThread.m index 975a5bac2..4d046f132 100644 --- a/SignalServiceKit/src/Contacts/TSThread.m +++ b/SignalServiceKit/src/Contacts/TSThread.m @@ -249,7 +249,7 @@ ConversationColorName const kConversationColorName_Default = ConversationColorNa if ([interaction isKindOfClass:[TSInvalidIdentityKeyReceivingErrorMessage class]]) { TSInvalidIdentityKeyReceivingErrorMessage *error = (TSInvalidIdentityKeyReceivingErrorMessage *)interaction; @try { - if ([[error try_newIdentityKey] isEqualToData:key]) { + if ([[error throws_newIdentityKey] isEqualToData:key]) { [errorMessages addObject:(TSInvalidIdentityKeyReceivingErrorMessage *)interaction]; } } @catch (NSException *exception) { diff --git a/SignalServiceKit/src/Devices/OWSProvisioningCipher.m b/SignalServiceKit/src/Devices/OWSProvisioningCipher.m index 451f84714..aac5b6499 100644 --- a/SignalServiceKit/src/Devices/OWSProvisioningCipher.m +++ b/SignalServiceKit/src/Devices/OWSProvisioningCipher.m @@ -54,7 +54,7 @@ NS_ASSUME_NONNULL_BEGIN - (nullable NSData *)encrypt:(NSData *)dataToEncrypt { @try { - return [self try_encryptWithData:dataToEncrypt]; + return [self throws_encryptWithData:dataToEncrypt]; } @catch (NSException *exception) { OWSFailDebug(@"exception: %@ of type: %@ with reason: %@, user info: %@.", exception.description, @@ -65,14 +65,14 @@ NS_ASSUME_NONNULL_BEGIN } } -- (nullable NSData *)try_encryptWithData:(NSData *)dataToEncrypt +- (nullable NSData *)throws_encryptWithData:(NSData *)dataToEncrypt { NSData *sharedSecret = - [Curve25519 try_generateSharedSecretFromPublicKey:self.theirPublicKey andKeyPair:self.ourKeyPair]; + [Curve25519 throws_generateSharedSecretFromPublicKey:self.theirPublicKey andKeyPair:self.ourKeyPair]; NSData *infoData = [@"TextSecure Provisioning Message" dataUsingEncoding:NSASCIIStringEncoding]; NSData *nullSalt = [[NSMutableData dataWithLength:32] copy]; - NSData *derivedSecret = [HKDFKit try_deriveKey:sharedSecret info:infoData salt:nullSalt outputSize:64]; + NSData *derivedSecret = [HKDFKit throws_deriveKey:sharedSecret info:infoData salt:nullSalt outputSize:64]; NSData *cipherKey = [derivedSecret subdataWithRange:NSMakeRange(0, 32)]; NSData *macKey = [derivedSecret subdataWithRange:NSMakeRange(32, 32)]; if (cipherKey.length != 32) { diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h index e81acb66d..2f4f5ff08 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.h @@ -10,8 +10,8 @@ NS_ASSUME_NONNULL_BEGIN @interface TSInvalidIdentityKeyErrorMessage : TSErrorMessage -- (void)try_acceptNewIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (nullable NSData *)try_newIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); +- (void)throws_acceptNewIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); +- (nullable NSData *)throws_newIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - (NSString *)theirSignalId; @end diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m index 301cfe900..239461875 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyErrorMessage.m @@ -8,12 +8,12 @@ NS_ASSUME_NONNULL_BEGIN @implementation TSInvalidIdentityKeyErrorMessage -- (void)try_acceptNewIdentityKey +- (void)throws_acceptNewIdentityKey { OWSAbstractMethod(); } -- (nullable NSData *)try_newIdentityKey +- (nullable NSData *)throws_newIdentityKey { OWSAbstractMethod(); return nil; diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m index ccc55a8bd..7fa210fa9 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeyReceivingErrorMessage.m @@ -81,7 +81,7 @@ NS_ASSUME_NONNULL_BEGIN return _envelope; } -- (void)try_acceptNewIdentityKey +- (void)throws_acceptNewIdentityKey { OWSAssertIsOnMainThread(); @@ -90,7 +90,7 @@ NS_ASSUME_NONNULL_BEGIN return; } - NSData *_Nullable newKey = [self try_newIdentityKey]; + NSData *_Nullable newKey = [self throws_newIdentityKey]; if (!newKey) { OWSFailDebug(@"Couldn't extract identity key to accept"); return; @@ -112,7 +112,7 @@ NS_ASSUME_NONNULL_BEGIN } } -- (nullable NSData *)try_newIdentityKey +- (nullable NSData *)throws_newIdentityKey { if (!self.envelope) { OWSLogError(@"Error message had no envelope data to extract key from"); @@ -130,8 +130,8 @@ NS_ASSUME_NONNULL_BEGIN return nil; } - PreKeyWhisperMessage *message = [[PreKeyWhisperMessage alloc] init_try_withData:pkwmData]; - return [message.identityKey try_removeKeyType]; + PreKeyWhisperMessage *message = [[PreKeyWhisperMessage alloc] init_throws_withData:pkwmData]; + return [message.identityKey throws_removeKeyType]; } - (NSString *)theirSignalId diff --git a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m index 6e955bb90..3b5a47b2d 100644 --- a/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m +++ b/SignalServiceKit/src/Messages/InvalidKeyMessages/TSInvalidIdentityKeySendingErrorMessage.m @@ -45,13 +45,13 @@ NSString *TSInvalidRecipientKey = @"TSInvalidRecipientKey"; return self; } -- (void)try_acceptNewIdentityKey +- (void)throws_acceptNewIdentityKey { // Shouldn't really get here, since we're no longer creating blocking SN changes. // But there may still be some old unaccepted SN errors in the wild that need to be accepted. OWSFailDebug(@"accepting new identity key is deprecated."); - NSData *_Nullable newIdentityKey = [self try_newIdentityKey]; + NSData *_Nullable newIdentityKey = [self throws_newIdentityKey]; if (!newIdentityKey) { OWSFailDebug(@"newIdentityKey is unexpectedly nil. Bad Prekey bundle?: %@", self.preKeyBundle); return; @@ -60,9 +60,9 @@ NSString *TSInvalidRecipientKey = @"TSInvalidRecipientKey"; [[OWSIdentityManager sharedManager] saveRemoteIdentity:newIdentityKey recipientId:self.recipientId]; } -- (nullable NSData *)try_newIdentityKey +- (nullable NSData *)throws_newIdentityKey { - return [self.preKeyBundle.identityKey try_removeKeyType]; + return [self.preKeyBundle.identityKey throws_removeKeyType]; } - (NSString *)theirSignalId diff --git a/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m b/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m index 697040c99..49f05fc88 100644 --- a/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m +++ b/SignalServiceKit/src/Messages/OWSBatchMessageProcessor.m @@ -403,9 +403,9 @@ NSString *const OWSMessageContentJobFinderExtensionGroup = @"OWSMessageContentJo if (!envelope) { reportFailure(transaction); } else { - [self.messageManager try_processEnvelope:envelope - plaintextData:job.plaintextData - transaction:transaction]; + [self.messageManager throws_processEnvelope:envelope + plaintextData:job.plaintextData + transaction:transaction]; } } @catch (NSException *exception) { OWSFailDebug(@"Received an invalid envelope: %@", exception.debugDescription); diff --git a/SignalServiceKit/src/Messages/OWSIdentityManager.h b/SignalServiceKit/src/Messages/OWSIdentityManager.h index 7f1c5c060..2d487487d 100644 --- a/SignalServiceKit/src/Messages/OWSIdentityManager.h +++ b/SignalServiceKit/src/Messages/OWSIdentityManager.h @@ -60,8 +60,8 @@ extern const NSUInteger kStoredIdentityKeyLength; - (nullable OWSRecipientIdentity *)untrustedIdentityForSendingToRecipientId:(NSString *)recipientId; // This method can be called from any thread. -- (void)try_processIncomingSyncMessage:(SSKProtoVerified *)verified - transaction:(YapDatabaseReadWriteTransaction *)transaction; +- (void)throws_processIncomingSyncMessage:(SSKProtoVerified *)verified + transaction:(YapDatabaseReadWriteTransaction *)transaction; - (BOOL)saveRemoteIdentity:(NSData *)identityKey recipientId:(NSString *)recipientId; diff --git a/SignalServiceKit/src/Messages/OWSIdentityManager.m b/SignalServiceKit/src/Messages/OWSIdentityManager.m index 25ab45230..ece948c88 100644 --- a/SignalServiceKit/src/Messages/OWSIdentityManager.m +++ b/SignalServiceKit/src/Messages/OWSIdentityManager.m @@ -678,8 +678,8 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa [transaction removeObjectForKey:recipientId inCollection:OWSIdentityManager_QueuedVerificationStateSyncMessages]; } -- (void)try_processIncomingSyncMessage:(SSKProtoVerified *)verified - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)throws_processIncomingSyncMessage:(SSKProtoVerified *)verified + transaction:(YapDatabaseReadWriteTransaction *)transaction { OWSAssertDebug(verified); OWSAssertDebug(transaction); @@ -696,7 +696,7 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa rawIdentityKey); return; } - NSData *identityKey = [rawIdentityKey try_removeKeyType]; + NSData *identityKey = [rawIdentityKey throws_removeKeyType]; switch (verified.state) { case SSKProtoVerifiedStateDefault: diff --git a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m index d24721100..04d203a6c 100644 --- a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m +++ b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m @@ -212,7 +212,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes switch (envelope.type) { case SSKProtoEnvelopeTypeCiphertext: { - [self try_decryptSecureMessage:envelope + [self throws_decryptSecureMessage:envelope envelopeData:envelopeData successBlock:^(OWSMessageDecryptResult *result, YapDatabaseReadWriteTransaction *transaction) { OWSLogDebug(@"decrypted secure message."); @@ -229,7 +229,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes return; } case SSKProtoEnvelopeTypePrekeyBundle: { - [self try_decryptPreKeyBundle:envelope + [self throws_decryptPreKeyBundle:envelope envelopeData:envelopeData successBlock:^(OWSMessageDecryptResult *result, YapDatabaseReadWriteTransaction *transaction) { OWSLogDebug(@"decrypted pre-key whisper message"); @@ -298,10 +298,10 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes failureBlock(); } -- (void)try_decryptSecureMessage:(SSKProtoEnvelope *)envelope - envelopeData:(NSData *)envelopeData - successBlock:(DecryptSuccessBlock)successBlock - failureBlock:(void (^)(NSError *_Nullable error))failureBlock +- (void)throws_decryptSecureMessage:(SSKProtoEnvelope *)envelope + envelopeData:(NSData *)envelopeData + successBlock:(DecryptSuccessBlock)successBlock + failureBlock:(void (^)(NSError *_Nullable error))failureBlock { OWSAssertDebug(envelope); OWSAssertDebug(envelopeData); @@ -312,16 +312,16 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes envelopeData:envelopeData cipherTypeName:@"Secure Message" cipherMessageBlock:^(NSData *encryptedData) { - return [[WhisperMessage alloc] init_try_withData:encryptedData]; + return [[WhisperMessage alloc] init_throws_withData:encryptedData]; } successBlock:successBlock failureBlock:failureBlock]; } -- (void)try_decryptPreKeyBundle:(SSKProtoEnvelope *)envelope - envelopeData:(NSData *)envelopeData - successBlock:(DecryptSuccessBlock)successBlock - failureBlock:(void (^)(NSError *_Nullable error))failureBlock +- (void)throws_decryptPreKeyBundle:(SSKProtoEnvelope *)envelope + envelopeData:(NSData *)envelopeData + successBlock:(DecryptSuccessBlock)successBlock + failureBlock:(void (^)(NSError *_Nullable error))failureBlock { OWSAssertDebug(envelope); OWSAssertDebug(envelopeData); @@ -335,7 +335,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes envelopeData:envelopeData cipherTypeName:@"PreKey Bundle" cipherMessageBlock:^(NSData *encryptedData) { - return [[PreKeyWhisperMessage alloc] init_try_withData:encryptedData]; + return [[PreKeyWhisperMessage alloc] init_throws_withData:encryptedData]; } successBlock:successBlock failureBlock:failureBlock]; @@ -379,7 +379,7 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes // plaintextData may be nil for some envelope types. NSData *_Nullable plaintextData = - [[cipher try_decrypt:cipherMessage protocolContext:transaction] removePadding]; + [[cipher throws_decrypt:cipherMessage protocolContext:transaction] removePadding]; OWSMessageDecryptResult *result = [OWSMessageDecryptResult resultWithEnvelopeData:envelopeData plaintextData:plaintextData source:envelope.source diff --git a/SignalServiceKit/src/Messages/OWSMessageManager.h b/SignalServiceKit/src/Messages/OWSMessageManager.h index fc8e2a43a..fb274d060 100644 --- a/SignalServiceKit/src/Messages/OWSMessageManager.h +++ b/SignalServiceKit/src/Messages/OWSMessageManager.h @@ -19,9 +19,9 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)initWithPrimaryStorage:(OWSPrimaryStorage *)primaryStorage NS_DESIGNATED_INITIALIZER; // processEnvelope: can be called from any thread. -- (void)try_processEnvelope:(SSKProtoEnvelope *)envelope - plaintextData:(NSData *_Nullable)plaintextData - transaction:(YapDatabaseReadWriteTransaction *)transaction; +- (void)throws_processEnvelope:(SSKProtoEnvelope *)envelope + plaintextData:(NSData *_Nullable)plaintextData + transaction:(YapDatabaseReadWriteTransaction *)transaction; // This should be invoked by the main app when the app is ready. - (void)startObserving; diff --git a/SignalServiceKit/src/Messages/OWSMessageManager.m b/SignalServiceKit/src/Messages/OWSMessageManager.m index ae3583e74..06a2a5213 100644 --- a/SignalServiceKit/src/Messages/OWSMessageManager.m +++ b/SignalServiceKit/src/Messages/OWSMessageManager.m @@ -212,9 +212,9 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - message handling -- (void)try_processEnvelope:(SSKProtoEnvelope *)envelope - plaintextData:(NSData *_Nullable)plaintextData - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)throws_processEnvelope:(SSKProtoEnvelope *)envelope + plaintextData:(NSData *_Nullable)plaintextData + transaction:(YapDatabaseReadWriteTransaction *)transaction { if (!envelope) { OWSFailDebug(@"Missing envelope."); @@ -256,7 +256,7 @@ NS_ASSUME_NONNULL_BEGIN OWSFailDebug(@"missing decrypted data for envelope: %@", [self descriptionForEnvelope:envelope]); return; } - [self try_handleEnvelope:envelope plaintextData:plaintextData transaction:transaction]; + [self throws_handleEnvelope:envelope plaintextData:plaintextData transaction:transaction]; break; case SSKProtoEnvelopeTypeReceipt: OWSAssertDebug(!plaintextData); @@ -345,9 +345,9 @@ NS_ASSUME_NONNULL_BEGIN } } -- (void)try_handleEnvelope:(SSKProtoEnvelope *)envelope - plaintextData:(NSData *)plaintextData - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)throws_handleEnvelope:(SSKProtoEnvelope *)envelope + plaintextData:(NSData *)plaintextData + transaction:(YapDatabaseReadWriteTransaction *)transaction { if (!envelope) { OWSFailDebug(@"Missing envelope."); @@ -395,7 +395,9 @@ NS_ASSUME_NONNULL_BEGIN OWSLogInfo(@"handling content: ", [self descriptionForContent:contentProto]); if (contentProto.syncMessage) { - [self try_handleIncomingEnvelope:envelope withSyncMessage:contentProto.syncMessage transaction:transaction]; + [self throws_handleIncomingEnvelope:envelope + withSyncMessage:contentProto.syncMessage + transaction:transaction]; [[OWSDeviceManager sharedManager] setHasReceivedSyncMessage]; } else if (contentProto.dataMessage) { @@ -745,9 +747,9 @@ NS_ASSUME_NONNULL_BEGIN }]; } -- (void)try_handleIncomingEnvelope:(SSKProtoEnvelope *)envelope - withSyncMessage:(SSKProtoSyncMessage *)syncMessage - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (void)throws_handleIncomingEnvelope:(SSKProtoEnvelope *)envelope + withSyncMessage:(SSKProtoSyncMessage *)syncMessage + transaction:(YapDatabaseReadWriteTransaction *)transaction { if (!envelope) { OWSFailDebug(@"Missing envelope."); @@ -862,7 +864,7 @@ NS_ASSUME_NONNULL_BEGIN transaction:transaction]; } else if (syncMessage.verified) { OWSLogInfo(@"Received verification state for %@", syncMessage.verified.destination); - [self.identityManager try_processIncomingSyncMessage:syncMessage.verified transaction:transaction]; + [self.identityManager throws_processIncomingSyncMessage:syncMessage.verified transaction:transaction]; } else { OWSLogWarn(@"Ignoring unsupported sync message."); } diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index a56d1361b..31581c74f 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -839,7 +839,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; NSArray *deviceMessages; @try { - deviceMessages = [self try_deviceMessagesForMessageSendUnsafe:messageSend]; + deviceMessages = [self throws_deviceMessagesForMessageSendUnsafe:messageSend]; } @catch (NSException *exception) { if ([exception.name isEqualToString:UntrustedIdentityKeyException]) { // This *can* happen under normal usage, but it should happen relatively rarely. @@ -888,7 +888,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; return nil; } - NSData *newIdentityKey = [newIdentityKeyWithVersion try_removeKeyType]; + NSData *newIdentityKey = [newIdentityKeyWithVersion throws_removeKeyType]; [self.identityManager saveRemoteIdentity:newIdentityKey recipientId:recipient.recipientId]; return nil; @@ -1407,7 +1407,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; [self sendMessageToRecipient:messageSend]; } -- (NSArray *)try_deviceMessagesForMessageSendUnsafe:(OWSMessageSend *)messageSend +- (NSArray *)throws_deviceMessagesForMessageSendUnsafe:(OWSMessageSend *)messageSend { OWSAssertDebug(messageSend.message); OWSAssertDebug(messageSend.recipient); @@ -1443,17 +1443,17 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; @try { // This may involve blocking network requests, so we do it _before_ // we open a transaction. - [self try_ensureRecipientHasSessionForMessageSend:messageSend deviceId:deviceId]; + [self throws_ensureRecipientHasSessionForMessageSend:messageSend deviceId:deviceId]; __block NSDictionary *messageDict; __block NSException *encryptionException; [self.dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { @try { - messageDict = [self try_encryptedMessageForMessageSend:messageSend - deviceId:deviceId - plainText:plainText - transaction:transaction]; + messageDict = [self throws_encryptedMessageForMessageSend:messageSend + deviceId:deviceId + plainText:plainText + transaction:transaction]; } @catch (NSException *exception) { encryptionException = exception; } @@ -1485,7 +1485,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; return [messagesArray copy]; } -- (void)try_ensureRecipientHasSessionForMessageSend:(OWSMessageSend *)messageSend deviceId:(NSNumber *)deviceId +- (void)throws_ensureRecipientHasSessionForMessageSend:(OWSMessageSend *)messageSend deviceId:(NSNumber *)deviceId { OWSAssertDebug(messageSend); OWSAssertDebug(deviceId); @@ -1544,7 +1544,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; deviceId:[deviceId intValue]]; [self.dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { @try { - [builder try_processPrekeyBundle:bundle protocolContext:transaction]; + [builder throws_processPrekeyBundle:bundle protocolContext:transaction]; } @catch (NSException *caughtException) { exception = caughtException; } @@ -1610,10 +1610,10 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; } // NOTE: This method uses exceptions for control flow. -- (NSDictionary *)try_encryptedMessageForMessageSend:(OWSMessageSend *)messageSend - deviceId:(NSNumber *)deviceId - plainText:(NSData *)plainText - transaction:(YapDatabaseReadWriteTransaction *)transaction +- (NSDictionary *)throws_encryptedMessageForMessageSend:(OWSMessageSend *)messageSend + deviceId:(NSNumber *)deviceId + plainText:(NSData *)plainText + transaction:(YapDatabaseReadWriteTransaction *)transaction { OWSAssertDebug(messageSend); OWSAssertDebug(deviceId); @@ -1667,7 +1667,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; } else { // This may throw an exception. id encryptedMessage = - [cipher try_encryptMessage:[plainText paddedMessageBody] protocolContext:transaction]; + [cipher throws_encryptMessage:[plainText paddedMessageBody] protocolContext:transaction]; serializedMessage = encryptedMessage.serialized; messageType = [self messageTypeForCipherMessage:encryptedMessage]; } @@ -1679,7 +1679,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; device:[deviceId intValue] content:serializedMessage isSilent:isSilent - registrationId:[cipher try_remoteRegistrationId:transaction]]; + registrationId:[cipher throws_remoteRegistrationId:transaction]]; NSError *error; NSDictionary *jsonDict = [MTLJSONAdapter JSONDictionaryFromModel:messageParams error:&error]; diff --git a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m index 41e83f7da..5035b4383 100644 --- a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m +++ b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+PreKeyStore.m @@ -49,7 +49,7 @@ } } -- (PreKeyRecord *)try_loadPreKey:(int)preKeyId +- (PreKeyRecord *)throws_loadPreKey:(int)preKeyId { PreKeyRecord *preKeyRecord = [self.dbReadConnection preKeyRecordForKey:[self keyFromInt:preKeyId] inCollection:OWSPrimaryStoragePreKeyStoreCollection]; diff --git a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m index 2e7394cd1..3c2f9318c 100644 --- a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m +++ b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m @@ -34,17 +34,17 @@ NSString *const OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId = @"currentSigne return [[SignedPreKeyRecord alloc] initWithId:preKeyId keyPair:keyPair - signature:[Ed25519 try_sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair] + signature:[Ed25519 throws_sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair] generatedAt:[NSDate date]]; } @catch (NSException *exception) { - // try_sign only throws when the data to sign is empty or `keyPair`. + // throws_sign only throws when the data to sign is empty or `keyPair`. // Neither of which should happen. OWSFail(@"exception: %@", exception); return nil; } } -- (SignedPreKeyRecord *)try_loadSignedPrekey:(int)signedPreKeyId +- (SignedPreKeyRecord *)throws_loadSignedPrekey:(int)signedPreKeyId { SignedPreKeyRecord *preKeyRecord = [self.dbReadConnection signedPreKeyRecordForKey:[self keyFromInt:signedPreKeyId] diff --git a/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m b/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m index 906daaa2a..d87c0f475 100644 --- a/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m +++ b/SignalServiceKit/tests/Storage/TSStoragePreKeyStoreTests.m @@ -35,10 +35,10 @@ PreKeyRecord *lastPreKeyRecord = [generatedKeys lastObject]; PreKeyRecord *firstPreKeyRecord = [generatedKeys firstObject]; - XCTAssert([[[OWSPrimaryStorage sharedManager] try_loadPreKey:lastPreKeyRecord.Id].keyPair.publicKey + XCTAssert([[[OWSPrimaryStorage sharedManager] throws_loadPreKey:lastPreKeyRecord.Id].keyPair.publicKey isEqualToData:lastPreKeyRecord.keyPair.publicKey]); - XCTAssert([[[OWSPrimaryStorage sharedManager] try_loadPreKey:firstPreKeyRecord.Id].keyPair.publicKey + XCTAssert([[[OWSPrimaryStorage sharedManager] throws_loadPreKey:firstPreKeyRecord.Id].keyPair.publicKey isEqualToData:firstPreKeyRecord.keyPair.publicKey]); } @@ -56,8 +56,8 @@ [[OWSPrimaryStorage sharedManager] removePreKey:lastPreKeyRecord.Id]; - XCTAssertThrows([[OWSPrimaryStorage sharedManager] try_loadPreKey:lastPreKeyRecord.Id]); - XCTAssertNoThrow([[OWSPrimaryStorage sharedManager] try_loadPreKey:firstPreKeyRecord.Id]); + XCTAssertThrows([[OWSPrimaryStorage sharedManager] throws_loadPreKey:lastPreKeyRecord.Id]); + XCTAssertNoThrow([[OWSPrimaryStorage sharedManager] throws_loadPreKey:firstPreKeyRecord.Id]); } @end From 3bef78335d0dcfd3e5885f42fe744b7902d5140f Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Tue, 30 Oct 2018 09:28:01 -0600 Subject: [PATCH 13/16] find -E . -type f -regex ".*\.(m|h|swift)" -exec sed -i "" -e "s/trywrapped_/throwswrapped_/g" {} \; --- .../src/Messages/OWSMessageDecrypter.m | 14 ++++---- .../src/Messages/OWSMessageSender.m | 14 ++++---- .../src/Messages/UD/OWSUDManager.swift | 32 +++++++++---------- 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m index 04d203a6c..960069cc7 100644 --- a/SignalServiceKit/src/Messages/OWSMessageDecrypter.m +++ b/SignalServiceKit/src/Messages/OWSMessageDecrypter.m @@ -449,13 +449,13 @@ NSError *EnsureDecryptError(NSError *_Nullable error, NSString *fallbackErrorDes } SMKDecryptResult *_Nullable decryptResult = - [cipher trywrapped_decryptMessageWithCertificateValidator:certificateValidator - cipherTextData:encryptedData - timestamp:serverTimestamp - localRecipientId:localRecipientId - localDeviceId:localDeviceId - protocolContext:transaction - error:&error]; + [cipher throwswrapped_decryptMessageWithCertificateValidator:certificateValidator + cipherTextData:encryptedData + timestamp:serverTimestamp + localRecipientId:localRecipientId + localDeviceId:localDeviceId + protocolContext:transaction + error:&error]; SCKRaiseIfExceptionWrapperError(error); if (error || !decryptResult) { diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index 31581c74f..ed0cd9095 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -479,7 +479,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; failure:(RetryableFailureHandler)failure { [self.udManager - trywrapped_ensureSenderCertificateWithSuccess:^(SMKSenderCertificate *senderCertificate) { + throwswrapped_ensureSenderCertificateWithSuccess:^(SMKSenderCertificate *senderCertificate) { dispatch_async([OWSDispatch sendingQueue], ^{ [self sendMessageToService:message senderCertificate:senderCertificate success:success failure:failure]; }); @@ -1656,12 +1656,12 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; OWSRaiseException(@"SecretSessionCipherFailure", @"Can't create secret session cipher."); } - serializedMessage = [secretCipher trywrapped_encryptMessageWithRecipientId:recipientId - deviceId:deviceId.intValue - paddedPlaintext:[plainText paddedMessageBody] - senderCertificate:messageSend.senderCertificate - protocolContext:transaction - error:&error]; + serializedMessage = [secretCipher throwswrapped_encryptMessageWithRecipientId:recipientId + deviceId:deviceId.intValue + paddedPlaintext:[plainText paddedMessageBody] + senderCertificate:messageSend.senderCertificate + protocolContext:transaction + error:&error]; SCKRaiseIfExceptionWrapperError(error); messageType = TSUnidentifiedSenderMessageType; } else { diff --git a/SignalServiceKit/src/Messages/UD/OWSUDManager.swift b/SignalServiceKit/src/Messages/UD/OWSUDManager.swift index f4d6a7af9..680ba5d17 100644 --- a/SignalServiceKit/src/Messages/UD/OWSUDManager.swift +++ b/SignalServiceKit/src/Messages/UD/OWSUDManager.swift @@ -65,7 +65,7 @@ private func string(forUnidentifiedAccessMode mode: UnidentifiedAccessMode) -> S // We use completion handlers instead of a promise so that message sending // logic can access the strongly typed certificate data. @objc - func trywrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, + func throwswrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, failure:@escaping (Error) -> Void) // MARK: Unrestricted Access @@ -111,7 +111,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } // Any error is silently ignored on startup. - self.trywrapped_ensureSenderCertificate().retainUntilComplete() + self.throwswrapped_ensureSenderCertificate().retainUntilComplete() } NotificationCenter.default.addObserver(self, selector: #selector(registrationStateDidChange), @@ -124,7 +124,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { AssertIsOnMainThread() // Any error is silently ignored - trywrapped_ensureSenderCertificate().retainUntilComplete() + throwswrapped_ensureSenderCertificate().retainUntilComplete() } // MARK: - @@ -266,12 +266,12 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { #if DEBUG @objc - public func trywrapped_hasSenderCertificate() -> Bool { - return trywrapped_senderCertificate() != nil + public func throwswrapped_hasSenderCertificate() -> Bool { + return throwswrapped_senderCertificate() != nil } #endif - private func trywrapped_senderCertificate() -> SMKSenderCertificate? { + private func throwswrapped_senderCertificate() -> SMKSenderCertificate? { guard let certificateData = dbConnection.object(forKey: senderCertificateKey(), inCollection: kUDCollection) as? Data else { return nil } @@ -279,7 +279,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { do { let certificate = try SMKSenderCertificate.parse(data: certificateData) - guard trywrapped_isValidCertificate(certificate) else { + guard throwswrapped_isValidCertificate(certificate) else { Logger.warn("Current sender certificate is not valid.") return nil } @@ -300,10 +300,10 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } @objc - public func trywrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, + public func throwswrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, failure:@escaping (Error) -> Void) { firstly { - trywrapped_ensureSenderCertificate() + throwswrapped_ensureSenderCertificate() }.map { certificate in success(certificate) }.catch { error in @@ -311,15 +311,15 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { }.retainUntilComplete() } - public func trywrapped_ensureSenderCertificate() -> Promise { + public func throwswrapped_ensureSenderCertificate() -> Promise { // If there is a valid cached sender certificate, use that. - if let certificate = trywrapped_senderCertificate() { + if let certificate = throwswrapped_senderCertificate() { return Promise.value(certificate) } // Try to obtain a new sender certificate. return firstly { - trywrapped_requestSenderCertificate() + throwswrapped_requestSenderCertificate() }.map { (certificateData: Data, certificate: SMKSenderCertificate) in // Cache the current sender certificate. @@ -329,13 +329,13 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } } - private func trywrapped_requestSenderCertificate() -> Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { + private func throwswrapped_requestSenderCertificate() -> Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { return firstly { SignalServiceRestClient().requestUDSenderCertificate() }.map { certificateData -> (certificateData: Data, certificate: SMKSenderCertificate) in let certificate = try SMKSenderCertificate.parse(data: certificateData) - guard self.trywrapped_isValidCertificate(certificate) else { + guard self.throwswrapped_isValidCertificate(certificate) else { throw OWSUDError.invalidData(description: "Invalid sender certificate returned by server") } @@ -343,7 +343,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } } - private func trywrapped_isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { + private func throwswrapped_isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { // Ensure that the certificate will not expire in the next hour. // We want a threshold long enough to ensure that any outgoing message // sends will complete before the expiration. @@ -351,7 +351,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { let anHourFromNowMs = nowMs + kHourInMs do { - try certificateValidator.trywrapped_validate(senderCertificate: certificate, validationTime: anHourFromNowMs) + try certificateValidator.throwswrapped_validate(senderCertificate: certificate, validationTime: anHourFromNowMs) return true } catch { OWSLogger.error("Invalid certificate") From 3d9cd4f4ede5b9a95ab3034617ddcdace5ee9153 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Tue, 30 Oct 2018 09:41:43 -0600 Subject: [PATCH 14/16] CR: comments and code clarity --- .../ConversationView/ConversationViewController.m | 2 +- SignalServiceKit/src/Account/TSAccountManager.m | 2 +- SignalServiceKit/src/Messages/OWSMessageSender.m | 1 - .../OWSPrimaryStorage+SignedPreKeyStore.m | 13 +++++++------ 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Signal/src/ViewControllers/ConversationView/ConversationViewController.m b/Signal/src/ViewControllers/ConversationView/ConversationViewController.m index a5067d467..142ba0cad 100644 --- a/Signal/src/ViewControllers/ConversationView/ConversationViewController.m +++ b/Signal/src/ViewControllers/ConversationView/ConversationViewController.m @@ -1902,7 +1902,7 @@ typedef enum : NSUInteger { // as-of-yet-undecrypted messages if ([errorMessage isKindOfClass:[TSInvalidIdentityKeyReceivingErrorMessage class]]) { // Deliberately crash if the user fails to explicitly accept the new identity - // key. In practice we haven't been creating these messags in over a year. + // key. In practice we haven't been creating these messages in over a year. [errorMessage throws_acceptNewIdentityKey]; } }]; diff --git a/SignalServiceKit/src/Account/TSAccountManager.m b/SignalServiceKit/src/Account/TSAccountManager.m index c1c8dcb40..01b124339 100644 --- a/SignalServiceKit/src/Account/TSAccountManager.m +++ b/SignalServiceKit/src/Account/TSAccountManager.m @@ -159,7 +159,7 @@ NSString *const TSAccountManager_NeedsAccountAttributesUpdateKey = @"TSAccountMa NSString *phoneNumber = self.phoneNumberAwaitingVerification; if (!phoneNumber) { - OWSFail(@"phonNumber was unexpectedly nil"); + OWSFail(@"phoneNumber was unexpectedly nil"); } [self storeLocalNumber:phoneNumber]; diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index ed0cd9095..87b625094 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -1609,7 +1609,6 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; }) retainUntilComplete]; } -// NOTE: This method uses exceptions for control flow. - (NSDictionary *)throws_encryptedMessageForMessageSend:(OWSMessageSend *)messageSend deviceId:(NSNumber *)deviceId plainText:(NSData *)plainText diff --git a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m index 3c2f9318c..bc9be2751 100644 --- a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m +++ b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SignedPreKeyStore.m @@ -30,14 +30,15 @@ NSString *const OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId = @"currentSigne int preKeyId = 1 + arc4random_uniform(INT32_MAX - 1); ECKeyPair *_Nullable identityKeyPair = [[OWSIdentityManager sharedManager] identityKeyPair]; OWSAssert(identityKeyPair); + @try { - return [[SignedPreKeyRecord alloc] - initWithId:preKeyId - keyPair:keyPair - signature:[Ed25519 throws_sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair] - generatedAt:[NSDate date]]; + NSData *signature = [Ed25519 throws_sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair]; + return [[SignedPreKeyRecord alloc] initWithId:preKeyId + keyPair:keyPair + signature:signature + generatedAt:[NSDate date]]; } @catch (NSException *exception) { - // throws_sign only throws when the data to sign is empty or `keyPair`. + // throws_sign only throws when the data to sign is empty or `keyPair` is nil. // Neither of which should happen. OWSFail(@"exception: %@", exception); return nil; From 1dea927a3f5ba0a0caf41dca7b7b5dd5b18a4c42 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Tue, 30 Oct 2018 10:05:06 -0600 Subject: [PATCH 15/16] Remove some usage of throwswrapped_ in udmanager since we don't need to propogate the wrapped exception anyway. --- .../src/Messages/OWSMessageSender.m | 2 +- .../src/Messages/UD/OWSUDManager.swift | 34 +++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index 87b625094..81b6953f3 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -479,7 +479,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; failure:(RetryableFailureHandler)failure { [self.udManager - throwswrapped_ensureSenderCertificateWithSuccess:^(SMKSenderCertificate *senderCertificate) { + ensureSenderCertificateWithSuccess:^(SMKSenderCertificate *senderCertificate) { dispatch_async([OWSDispatch sendingQueue], ^{ [self sendMessageToService:message senderCertificate:senderCertificate success:success failure:failure]; }); diff --git a/SignalServiceKit/src/Messages/UD/OWSUDManager.swift b/SignalServiceKit/src/Messages/UD/OWSUDManager.swift index 680ba5d17..ce6686121 100644 --- a/SignalServiceKit/src/Messages/UD/OWSUDManager.swift +++ b/SignalServiceKit/src/Messages/UD/OWSUDManager.swift @@ -65,8 +65,8 @@ private func string(forUnidentifiedAccessMode mode: UnidentifiedAccessMode) -> S // We use completion handlers instead of a promise so that message sending // logic can access the strongly typed certificate data. @objc - func throwswrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, - failure:@escaping (Error) -> Void) + func ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, + failure:@escaping (Error) -> Void) // MARK: Unrestricted Access @@ -111,7 +111,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } // Any error is silently ignored on startup. - self.throwswrapped_ensureSenderCertificate().retainUntilComplete() + self.ensureSenderCertificate().retainUntilComplete() } NotificationCenter.default.addObserver(self, selector: #selector(registrationStateDidChange), @@ -124,7 +124,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { AssertIsOnMainThread() // Any error is silently ignored - throwswrapped_ensureSenderCertificate().retainUntilComplete() + ensureSenderCertificate().retainUntilComplete() } // MARK: - @@ -266,12 +266,12 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { #if DEBUG @objc - public func throwswrapped_hasSenderCertificate() -> Bool { - return throwswrapped_senderCertificate() != nil + public func hasSenderCertificate() -> Bool { + return senderCertificate() != nil } #endif - private func throwswrapped_senderCertificate() -> SMKSenderCertificate? { + private func senderCertificate() -> SMKSenderCertificate? { guard let certificateData = dbConnection.object(forKey: senderCertificateKey(), inCollection: kUDCollection) as? Data else { return nil } @@ -279,7 +279,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { do { let certificate = try SMKSenderCertificate.parse(data: certificateData) - guard throwswrapped_isValidCertificate(certificate) else { + guard isValidCertificate(certificate) else { Logger.warn("Current sender certificate is not valid.") return nil } @@ -300,10 +300,10 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } @objc - public func throwswrapped_ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, - failure:@escaping (Error) -> Void) { + public func ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, + failure:@escaping (Error) -> Void) { firstly { - throwswrapped_ensureSenderCertificate() + ensureSenderCertificate() }.map { certificate in success(certificate) }.catch { error in @@ -311,15 +311,15 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { }.retainUntilComplete() } - public func throwswrapped_ensureSenderCertificate() -> Promise { + public func ensureSenderCertificate() -> Promise { // If there is a valid cached sender certificate, use that. - if let certificate = throwswrapped_senderCertificate() { + if let certificate = senderCertificate() { return Promise.value(certificate) } // Try to obtain a new sender certificate. return firstly { - throwswrapped_requestSenderCertificate() + requestSenderCertificate() }.map { (certificateData: Data, certificate: SMKSenderCertificate) in // Cache the current sender certificate. @@ -329,13 +329,13 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } } - private func throwswrapped_requestSenderCertificate() -> Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { + private func requestSenderCertificate() -> Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { return firstly { SignalServiceRestClient().requestUDSenderCertificate() }.map { certificateData -> (certificateData: Data, certificate: SMKSenderCertificate) in let certificate = try SMKSenderCertificate.parse(data: certificateData) - guard self.throwswrapped_isValidCertificate(certificate) else { + guard self.isValidCertificate(certificate) else { throw OWSUDError.invalidData(description: "Invalid sender certificate returned by server") } @@ -343,7 +343,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager { } } - private func throwswrapped_isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { + private func isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { // Ensure that the certificate will not expire in the next hour. // We want a threshold long enough to ensure that any outgoing message // sends will complete before the expiration. From 86066a37d5cc6f96ce935755ac322870378fd28d Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Tue, 30 Oct 2018 11:28:58 -0600 Subject: [PATCH 16/16] update pods for exception wrapping --- Podfile.lock | 12 ++++++------ Pods | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Podfile.lock b/Podfile.lock index f9479ae58..e284a4cd9 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -246,22 +246,22 @@ EXTERNAL SOURCES: CHECKOUT OPTIONS: AxolotlKit: - :commit: f43a65b456c43d1f5cad621ef108b4e18a70c17f + :commit: 66b38e23b4e980cbddc94980f5bd0d1211d9184a :git: https://github.com/signalapp/SignalProtocolKit.git Curve25519Kit: - :commit: 14effe344be35f5d9f5597a2fd56824f78a4067d + :commit: 9e5663baf4c2c7cb68ac4c0beb0423383c19a7fe :git: https://github.com/signalapp/Curve25519Kit GRKOpenSSLFramework: :commit: b799c27e7927e5304ec1e4ad53c6d33c6fd1cae7 :git: https://github.com/signalapp/GRKOpenSSLFramework HKDFKit: - :commit: 8b8326cd50bc488663a3d3743f1a92b90f4d85b4 + :commit: 3e0c2371d125f2d3db26daa498d5d436961b1795 :git: https://github.com/signalapp/HKDFKit.git SignalCoreKit: - :commit: ff0b95770520133b83a4bd7b26bc2c90b51abc4d + :commit: b60dc7d58dfc93ca6eafbb3ea5300c6d67ebc69a :git: https://github.com/signalapp/SignalCoreKit.git SignalMetadataKit: - :commit: 90f3dee7122ff13061770c496001135ba90b71e3 + :commit: d6b0186cc5b15019e85c375bce3bf78e7a7fc162 :git: https://github.com/signalapp/SignalMetadataKit SocketRocket: :commit: 9f9563a83cd8960503074aa8de72206f83fb7a69 @@ -277,7 +277,7 @@ SPEC CHECKSUMS: AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 AxolotlKit: bb02741a93400b915df1be3365ad13d3768b0103 CocoaLumberjack: db7cc9e464771f12054c22ff6947c5a58d43a0fd - Curve25519Kit: 2b2e55cfa2a72f1152d2733a3058d94cc87f37c3 + Curve25519Kit: b3e77b7152ebe95fee2b3fb6c955449492bc14f7 GRKOpenSSLFramework: 8a3735ad41e7dc1daff460467bccd32ca5d6ae3e HKDFKit: 3b6dbbb9d59c221cc6c52c3aa915700cbf24e376 libPhoneNumber-iOS: e444379ac18bbfbdefad571da735b2cd7e096caa diff --git a/Pods b/Pods index c4a845a4d..5821eb8e9 160000 --- a/Pods +++ b/Pods @@ -1 +1 @@ -Subproject commit c4a845a4d93934555baf8335c65b2510a926322b +Subproject commit 5821eb8e9fd9f76fbdbedd3402892c185e65c48e