Skip to content

Commit

Permalink
restored and corrected some code
Browse files Browse the repository at this point in the history
  • Loading branch information
Velin92 committed Sep 27, 2024
1 parent 598ece7 commit f0f87bc
Show file tree
Hide file tree
Showing 6 changed files with 328 additions and 0 deletions.
12 changes: 12 additions & 0 deletions MatrixSDK.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,10 @@
A0A2397A295202930001F722 /* MXAggregatedPollsUpdater.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0A23978295202930001F722 /* MXAggregatedPollsUpdater.swift */; };
A0B1217F295306F700E704C2 /* MXAggregatedPollsUpdaterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0B1217E295306F700E704C2 /* MXAggregatedPollsUpdaterTests.swift */; };
A0B12180295306F700E704C2 /* MXAggregatedPollsUpdaterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0B1217E295306F700E704C2 /* MXAggregatedPollsUpdaterTests.swift */; };
A71E55322CA6FEBD00B06B17 /* MXKeyBackupPassword.h in Headers */ = {isa = PBXBuildFile; fileRef = A71E55302CA6FEBC00B06B17 /* MXKeyBackupPassword.h */; settings = {ATTRIBUTES = (Public, ); }; };
A71E55332CA6FEBD00B06B17 /* MXKeyBackupPassword.h in Headers */ = {isa = PBXBuildFile; fileRef = A71E55302CA6FEBC00B06B17 /* MXKeyBackupPassword.h */; settings = {ATTRIBUTES = (Public, ); }; };
A71E55342CA6FEBD00B06B17 /* MXKeyBackupPassword.m in Sources */ = {isa = PBXBuildFile; fileRef = A71E55312CA6FEBC00B06B17 /* MXKeyBackupPassword.m */; };
A71E55352CA6FEBD00B06B17 /* MXKeyBackupPassword.m in Sources */ = {isa = PBXBuildFile; fileRef = A71E55312CA6FEBC00B06B17 /* MXKeyBackupPassword.m */; };
A759E23D2C98EE7D002429A8 /* MXCrypto.m in Sources */ = {isa = PBXBuildFile; fileRef = A759E23C2C98EE7D002429A8 /* MXCrypto.m */; };
A759E23E2C98EE7D002429A8 /* MXCrypto.m in Sources */ = {isa = PBXBuildFile; fileRef = A759E23C2C98EE7D002429A8 /* MXCrypto.m */; };
A75CAD692A9796DE00F06072 /* MXWellKnownAuthentication.m in Sources */ = {isa = PBXBuildFile; fileRef = A75CAD682A9796DE00F06072 /* MXWellKnownAuthentication.m */; };
Expand Down Expand Up @@ -2483,6 +2487,8 @@
9274AFE71EE580240009BEB6 /* MXCallKitAdapter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MXCallKitAdapter.m; sourceTree = "<group>"; };
A0A23978295202930001F722 /* MXAggregatedPollsUpdater.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXAggregatedPollsUpdater.swift; sourceTree = "<group>"; };
A0B1217E295306F700E704C2 /* MXAggregatedPollsUpdaterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXAggregatedPollsUpdaterTests.swift; sourceTree = "<group>"; };
A71E55302CA6FEBC00B06B17 /* MXKeyBackupPassword.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MXKeyBackupPassword.h; sourceTree = "<group>"; };
A71E55312CA6FEBC00B06B17 /* MXKeyBackupPassword.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MXKeyBackupPassword.m; sourceTree = "<group>"; };
A759E23C2C98EE7D002429A8 /* MXCrypto.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MXCrypto.m; sourceTree = "<group>"; };
A75CAD682A9796DE00F06072 /* MXWellKnownAuthentication.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MXWellKnownAuthentication.m; sourceTree = "<group>"; };
A75CAD6B2A97970500F06072 /* MXWellKnownAuthentication.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MXWellKnownAuthentication.h; sourceTree = "<group>"; };
Expand Down Expand Up @@ -3941,6 +3947,8 @@
32BBAE642178E99100D85F46 /* KeyBackup */ = {
isa = PBXGroup;
children = (
A71E55302CA6FEBC00B06B17 /* MXKeyBackupPassword.h */,
A71E55312CA6FEBC00B06B17 /* MXKeyBackupPassword.m */,
EDE70DC628DA22E200099736 /* Engine */,
32BBAE652178E99100D85F46 /* Data */,
32BBAE722179CF4000D85F46 /* MXKeyBackup.h */,
Expand Down Expand Up @@ -5741,6 +5749,7 @@
3A23A741256D322C00B9D00F /* MXAes.h in Headers */,
EC0B943D271DB68F00B4D440 /* MXVoidRoomSummaryStore.h in Headers */,
32BBAE6D2178E99100D85F46 /* MXKeyBackupVersion.h in Headers */,
A71E55322CA6FEBD00B06B17 /* MXKeyBackupPassword.h in Headers */,
323547D82226D5D600F15F94 /* MXWellKnownBaseConfig.h in Headers */,
32A151461DAF7C0C00400192 /* MXDeviceInfo.h in Headers */,
EC8A53A925B1BC77004E0802 /* MXCallRejectEventContent.h in Headers */,
Expand Down Expand Up @@ -6133,6 +6142,7 @@
EC60EDBD265CFE8600B39A4E /* MXRoomSyncAccountData.h in Headers */,
B14EF32B2397E90400758AF0 /* MXBackgroundModeHandler.h in Headers */,
B14EF32C2397E90400758AF0 /* MXRoomPredecessorInfo.h in Headers */,
A71E55332CA6FEBD00B06B17 /* MXKeyBackupPassword.h in Headers */,
B14EF32D2397E90400758AF0 /* MXCallStack.h in Headers */,
B14EF32E2397E90400758AF0 /* MXMediaLoader.h in Headers */,
ECDA763A27B6B74C000C48CF /* MXCapabilities.h in Headers */,
Expand Down Expand Up @@ -6647,6 +6657,7 @@
327E9ABD2284521C00A98BC1 /* MXEventUnsignedData.m in Sources */,
32AF9286240EA2430008A0FD /* MXSecretShareRequest.m in Sources */,
ED5C754428B3E80300D24E85 /* MXLogObjcWrapper.m in Sources */,
A71E55342CA6FEBD00B06B17 /* MXKeyBackupPassword.m in Sources */,
ED47CB6D28523995004FD755 /* MXCryptoV2.swift in Sources */,
ED463ECB29B0B75800957941 /* EventEncryptionAlgorithm+String.swift in Sources */,
ED37834929C9B6E700A449DA /* MXEventDecryptionDecoration.swift in Sources */,
Expand Down Expand Up @@ -7272,6 +7283,7 @@
B14EF2072397E90400758AF0 /* MXAutoDiscovery.m in Sources */,
ED5C754528B3E80300D24E85 /* MXLogObjcWrapper.m in Sources */,
ED47CB6E28523995004FD755 /* MXCryptoV2.swift in Sources */,
A71E55352CA6FEBD00B06B17 /* MXKeyBackupPassword.m in Sources */,
ED463ECC29B0B75800957941 /* EventEncryptionAlgorithm+String.swift in Sources */,
EDF154E2296C203E004D7FFE /* MXCryptoMachineStore.swift in Sources */,
ED37834A29C9B6E700A449DA /* MXEventDecryptionDecoration.swift in Sources */,
Expand Down
50 changes: 50 additions & 0 deletions MatrixSDK/Crypto/KeyBackup/MXKeyBackupPassword.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

/**
Utility to compute a backup private key from a password and vice-versa.
*/
@interface MXKeyBackupPassword : NSObject

/**
Compute a private key from a password.
@param password the password to use.
@param salt the salt used to generate the private key.
@param iterations number of key derivations done on the generated private key.
@param error the output error.
@return a private key.
*/
+ (nullable NSData *)generatePrivateKeyWithPassword:(NSString*)password salt:(NSString * _Nullable *_Nonnull)salt iterations:(NSUInteger*)iterations error:(NSError * _Nullable *)error;

/**
Retrieve a private key from {password, salt, iterations}
@param password the password used to generated the private key.
@param salt the salt.
@param iterations number of key derivations
@param error the output error
@return a private key.
*/
+ (nullable NSData *)retrievePrivateKeyWithPassword:(NSString*)password salt:(NSString*)salt iterations:(NSUInteger)iterations error:(NSError * _Nullable *)error;

@end

NS_ASSUME_NONNULL_END
100 changes: 100 additions & 0 deletions MatrixSDK/Crypto/KeyBackup/MXKeyBackupPassword.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#import "MXKeyBackupPassword.h"

#import "MXTools.h"
#import "MXCryptoConstants.h"

#import <Security/Security.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonKeyDerivation.h>

#pragma mark - Constants

static NSUInteger const kSaltLength = 32;
static NSUInteger const kDefaultIterations = 500000;


@implementation MXKeyBackupPassword

+ (NSData *)generatePrivateKeyWithPassword:(NSString *)password salt:(NSString *__autoreleasing *)salt iterations:(NSUInteger *)iterations error:(NSError *__autoreleasing _Nullable *)error
{
*salt = [[MXTools generateSecret] substringWithRange:NSMakeRange(0, kSaltLength)];
*iterations = kDefaultIterations;

NSData *privateKey = [self deriveKey:password salt:*salt iterations:kDefaultIterations error:error];

return privateKey;
}

+ (NSData *)retrievePrivateKeyWithPassword:(NSString *)password salt:(NSString *)salt iterations:(NSUInteger)iterations error:(NSError *__autoreleasing _Nullable *)error
{
return [self deriveKey:password salt:salt iterations:iterations error:error];
}


#pragma mark - Private methods

/**
Compute a private key by deriving a password and a salt strings.
@param password the password.
@param salt the salt.
@param iterations number of derivations.
@param error the output error.
@return a private key.
*/
+ (nullable NSData *)deriveKey:(NSString*)password salt:(NSString*)salt iterations:(NSUInteger)iterations error:(NSError *__autoreleasing _Nullable *)error
{
NSDate *startDate = [NSDate date];

NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSData *saltData = [salt dataUsingEncoding:NSUTF8StringEncoding];

NSMutableData *derivedKey = [NSMutableData dataWithLength: 32];

int result = CCKeyDerivationPBKDF(kCCPBKDF2,
passwordData.bytes,
passwordData.length,
saltData.bytes,
saltData.length,
kCCPRFHmacAlgSHA512,
(uint)iterations,
derivedKey.mutableBytes,
derivedKey.length);

MXLogDebug(@"[MXKeyBackupPassword] deriveKey: %tu iterations took %.0fms", iterations, [[NSDate date] timeIntervalSinceDate:startDate] * 1000);

if (result != kCCSuccess)
{
derivedKey = nil;

if (*error)
{
*error = [NSError errorWithDomain:MXKeyBackupErrorDomain
code:MXKeyBackupErrorCannotDeriveKeyCode
userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:@"CCKeyDerivationPBKDF fails: %@", @(result)]
}];
}
}

return derivedKey;
}

@end
53 changes: 53 additions & 0 deletions MatrixSDK/Crypto/Recovery/MXRecoveryService.h
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,44 @@ typedef NS_ENUM(NSInteger, MXRecoveryServiceErrorCode)

#pragma mark - Backup to recovery

/**
Create a recovery and store secrets there.
It will send keys from the local storage to the recovery on the homeserver.
Those keys are sent encrypted thanks to SSSS that implements this recovery.
@param secrets secrets ids to store in the recovery. Nil for all self.supportedSecrets.
@param privateKey a private key used to generate the recovery key to encrypt keys.
@param createServicesBackups YES to create backups for associated services. Only keyBackup is supported.
@param success A block object called when the operation succeeds.
@param failure A block object called when the operation fails.
*/
- (void)createRecoveryForSecrets:(nullable NSArray<NSString*>*)secrets
withPrivateKey:(NSData*)privateKey
createServicesBackups:(BOOL)createServicesBackups
success:(void (^)(MXSecretStorageKeyCreationInfo *keyCreationInfo))success
failure:(void (^)(NSError *error))failure;

/**
Create a recovery and store secrets there.
It will send keys from the local storage to the recovery on the homeserver.
Those keys are sent encrypted thanks to SSSS that implements this recovery.
@param secrets secrets ids to store in the recovery. Nil for all self.supportedSecrets.
@param passphrase a passphrase used to generate the recovery key to encrypt keys. Nil will generate it.
@param createServicesBackups YES to create backups for associated services. Only keyBackup is supported.
@param success A block object called when the operation succeeds.
@param failure A block object called when the operation fails.
*/
- (void)createRecoveryForSecrets:(nullable NSArray<NSString*>*)secrets
withPassphrase:(nullable NSString*)passphrase
createServicesBackups:(BOOL)createServicesBackups
success:(void (^)(MXSecretStorageKeyCreationInfo *keyCreationInfo))success
failure:(void (^)(NSError *error))failure;

/**
Update secrets to the existing recovery.
Expand Down Expand Up @@ -184,6 +222,21 @@ typedef NS_ENUM(NSInteger, MXRecoveryServiceErrorCode)
*/
- (nullable NSData*)privateKeyFromRecoveryKey:(NSString*)recoveryKey error:(NSError**)error;

/**
Convert a passphrase into the private key.
This method is supposed to take time to avoid brut force attacks.
@param passphrase the passphrase
@param success A block object called when the operation succeeds.
@param failure A block object called when the operation fails.
*/
- (void)privateKeyFromPassphrase:(NSString*)passphrase
success:(void (^)(NSData *privateKey))success
failure:(void (^)(NSError *error))failure;


@end

NS_ASSUME_NONNULL_END
Loading

0 comments on commit f0f87bc

Please sign in to comment.