Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove libcrypto (use tutasdk RSA impl for iOS/Android) #7344

Merged
merged 4 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
app-ios/libcrypto.xcframework/** linguist-generated
app-ios/tutanota/Sources/Offline/sqlite3.* linguist-vendored
libs/* linguist-vendored
4 changes: 2 additions & 2 deletions .github/workflows/swift-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ env:

jobs:
test-swift:
runs-on: macos-13 # macos 14 is ARM only and our tests don't run on ARM simulators due to libcrypto
runs-on: macos-14

permissions:
actions: none
Expand Down Expand Up @@ -55,7 +55,7 @@ jobs:
cargo --version
rustc --version
- name: Add rust target
run: rustup target add x86_64-apple-ios # aarch64-apple-ios-sim
run: rustup target add aarch64-apple-ios-sim
- name: Lint
working-directory: ./app-ios
run: ./lint.sh lint:check
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,8 @@ class CompatibilityTest {
for (testData in testData.rsaEncryptionTests) {
val publicKeyJSON = hexToPublicKey(testData.publicKey)
val encryptedResult: ByteArray = crypto.rsaEncrypt(publicKeyJSON, hexToBytes(testData.input).wrap(), hexToBytes(testData.seed).wrap()).data
//String hexResult = bytesToHex(encryptedResultBytes);
//assertEquals(testData.getResult(), hexResult);
//cannot compare encrypted test data because default android implementation ignores randomizer
val hexResult = bytesToHex(encryptedResult)
assertEquals(testData.result, hexResult)
val plainText = crypto.rsaDecrypt(hexToPrivateKey(testData.privateKey), encryptedResult.wrap()).data
assertEquals(testData.input, bytesToHex(plainText))
val plainTextFromTestData = crypto.rsaDecrypt(hexToPrivateKey(testData.privateKey), hexToBytes(testData.result).wrap()).data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,8 @@ import kotlinx.coroutines.withContext
import org.apache.commons.io.IOUtils
import org.apache.commons.io.input.BoundedInputStream
import java.io.*
import java.math.BigInteger
import java.security.*
import java.security.interfaces.RSAPrivateCrtKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.InvalidKeySpecException
import java.security.spec.MGF1ParameterSpec
import java.security.spec.RSAPrivateKeySpec
import java.security.spec.RSAPublicKeySpec
import java.util.*
import javax.crypto.*
import javax.crypto.spec.IvParameterSpec
Expand All @@ -38,7 +32,6 @@ class AndroidNativeCryptoFacade(
const val AES_BLOCK_SIZE_BYTES = 16
val FIXED_IV = ByteArray(AES_BLOCK_SIZE_BYTES).apply { fill(0x88.toByte()) }
const val RSA_KEY_LENGTH_IN_BITS = 2048
const val RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"
const val RSA_PUBLIC_EXPONENT = 65537

/**
Expand Down Expand Up @@ -195,69 +188,34 @@ class AndroidNativeCryptoFacade(
seed: DataWrapper,
): DataWrapper {
try {
return this.rsaEncrypt(
javaPublicKey(publicKey),
return de.tutao.tutasdk.rsaEncryptWithPublicKeyComponents(
data.data,
seed.data
seed.data,
publicKey.modulus,
publicKey.publicExponent.toUInt()
).wrap()
} catch (e: InvalidKeySpecException) {
} catch (e: de.tutao.tutasdk.RsaException) {
// These types of errors can happen and that's okay, they should be handled gracefully.
throw CryptoError(e)
}
}

/**
* Encrypts an aes key with RSA to a byte array.
*/
@Throws(CryptoError::class)
fun rsaEncrypt(publicKey: PublicKey, data: ByteArray, random: ByteArray): ByteArray {
randomizer.setSeed(random)
return rsaEncrypt(data, publicKey, randomizer)
}

@Throws(CryptoError::class)
private fun rsaEncrypt(data: ByteArray, publicKey: PublicKey, randomizer: SecureRandom): ByteArray {
return try {
val cipher = Cipher.getInstance(RSA_ALGORITHM)
cipher.init(Cipher.ENCRYPT_MODE, publicKey, OAEP_PARAMETER_SPEC, randomizer)
cipher.doFinal(data)
} catch (e: BadPaddingException) {
throw CryptoError(e)
} catch (e: IllegalBlockSizeException) {
throw CryptoError(e)
} catch (e: InvalidKeyException) {
throw CryptoError(e)
}
}

@Throws(CryptoError::class)
override suspend fun rsaDecrypt(privateKey: RsaPrivateKey, data: DataWrapper): DataWrapper {
try {
return rsaDecrypt(
javaPrivateKey(privateKey),
return de.tutao.tutasdk.rsaDecryptWithPrivateKeyComponents(
data.data,
privateKey.modulus,
privateKey.privateExponent,
privateKey.primeP,
privateKey.primeQ
).wrap()
} catch (e: InvalidKeySpecException) {
} catch (e: de.tutao.tutasdk.RsaException) {
// These types of errors can happen and that's okay, they should be handled gracefully.
throw CryptoError(e)
}
}

@Throws(CryptoError::class)
fun rsaDecrypt(privateKey: PrivateKey, encryptedKey: ByteArray): ByteArray {
return try {
val cipher = Cipher.getInstance(RSA_ALGORITHM)
cipher.init(Cipher.DECRYPT_MODE, privateKey, OAEP_PARAMETER_SPEC, randomizer)
cipher.doFinal(encryptedKey)
} catch (e: BadPaddingException) {
throw CryptoError(e)
} catch (e: InvalidKeyException) {
throw CryptoError(e)
} catch (e: IllegalBlockSizeException) {
throw CryptoError(e)
}
}

@Throws(IOException::class, CryptoError::class)
override suspend fun aesEncryptFile(key: DataWrapper, fileUri: String, iv: DataWrapper): EncryptedFileInfo {
val parsedFileUri = Uri.parse(fileUri)
Expand Down Expand Up @@ -501,43 +459,6 @@ class AndroidNativeCryptoFacade(
}
}

@Throws(InvalidKeySpecException::class)
private fun javaPublicKey(key: RsaPublicKey): PublicKey {
val modulus = BigInteger(key.modulus.base64ToBytes())
val keyFactory = KeyFactory.getInstance("RSA")
return keyFactory.generatePublic(RSAPublicKeySpec(modulus, BigInteger.valueOf(RSA_PUBLIC_EXPONENT.toLong())))
}

@Throws(InvalidKeySpecException::class)
private fun javaPrivateKey(key: RsaPrivateKey): PrivateKey {
val modulus = BigInteger(key.modulus.base64ToBytes())
val privateExponent = BigInteger(key.privateExponent.base64ToBytes())
val keyFactory = KeyFactory.getInstance("RSA")
return keyFactory.generatePrivate(RSAPrivateKeySpec(modulus, privateExponent))
}

private fun BigInteger.toBase64() = toByteArray().toBase64()

private fun PrivateKey(javaKey: RSAPrivateCrtKey) = RsaPrivateKey(
version = 0,
// TODO: is this correct?
keyLength = RSA_KEY_LENGTH_IN_BITS,
modulus = javaKey.modulus.toBase64(),
privateExponent = javaKey.privateExponent.toBase64(),
primeP = javaKey.primeP.toBase64(),
primeQ = javaKey.primeQ.toBase64(),
primeExponentP = javaKey.primeExponentP.toBase64(),
primeExponentQ = javaKey.primeExponentQ.toBase64(),
crtCoefficient = javaKey.crtCoefficient.toBase64(),
)

private fun PublicKey(javaKey: RSAPublicKey) = RsaPublicKey(
version = 0,
keyLength = RSA_KEY_LENGTH_IN_BITS,
modulus = javaKey.modulus.toBase64(),
publicExponent = RSA_PUBLIC_EXPONENT,
)

private fun hasMac(dataLength: Long): Boolean {
return dataLength % 2 == 1L
}
Expand Down
1 change: 0 additions & 1 deletion app-ios/.swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ opt_in_rules:
excluded:
- .idea
- fastlane
- libcrypto.xcframework
- releases
- tutanota.xcodeproj
- tutanota/build
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
#import "Utils/TUTEncodingConverter.h"
#import "Utils/TUTLog.h"
#import "Utils/WebviewHacks.h"
#import "Crypto/TUTCrypto.h"
#include "Offline/sqlite3.h"
#import "argon2.h"

Expand Down
8 changes: 5 additions & 3 deletions app-ios/TutanotaSharedFramework/Crypto/AES.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ private let MAC_IDENTIFIER: [UInt8] = [0x01]
private let TUTAO_FIXED_IV: Data = Data(repeating: 0x88, count: TUTAO_IV_BYTE_SIZE)
private let MAC_TOTAL_OVERHEAD_LENGTH = MAC_DIGEST_LENGTH + MAC_IDENTIFIER.count

public func aesGenerateKey() -> Data { TUTCrypto.generateAES256Key() }
public func aesGenerateKey() -> Data { secureRandomData(ofLength: AES_256_KEY_LENGTH_IN_BITS / 8) }

public func aesGenerateIV() -> Data { secureRandomData(ofLength: TUTAO_IV_BYTE_SIZE) }

/// Decrypt the encrypted data with padding.
///
Expand Down Expand Up @@ -47,7 +49,7 @@ public func aesDecryptKey(_ encryptedKey: Data, withKey key: Data) throws -> Dat
/// - withIV: IV to use
///
/// - Returns: Encrypted cyphertext
public func aesEncryptData(_ data: Data, withKey key: Data, withIV iv: Data = TUTCrypto.generateIv()) throws -> Data {
public func aesEncryptData(_ data: Data, withKey key: Data, withIV iv: Data = aesGenerateIV()) throws -> Data {
try aesEncrypt(data: data, withKey: key, withIV: iv, withPadding: true, withMAC: true)
}

Expand All @@ -65,7 +67,7 @@ public func aesEncryptKey(_ keyToBeEncrypted: Data, withKey key: Data) throws ->
case kCCKeySizeAES128:
let encrypted = try aesEncrypt(data: keyToBeEncrypted, withKey: key, withIV: TUTAO_FIXED_IV, withPadding: false, withMAC: false)
return encrypted[TUTAO_IV_BYTE_SIZE...] // IV is fixed, so we can extract everything after it
case kCCKeySizeAES256: return try aesEncrypt(data: keyToBeEncrypted, withKey: key, withIV: TUTCrypto.generateIv(), withPadding: false, withMAC: true)
case kCCKeySizeAES256: return try aesEncrypt(data: keyToBeEncrypted, withKey: key, withIV: aesGenerateIV(), withPadding: false, withMAC: true)
default: throw TUTErrorFactory.createError(withDomain: TUT_CRYPTO_ERROR, message: "invalid key size \(key.count)")
}
}
Expand Down
4 changes: 4 additions & 0 deletions app-ios/TutanotaSharedFramework/Crypto/Constants.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public let RSA_KEY_LENGTH_IN_BITS = 2048
public let PUBLIC_EXPONENT = 65537
public let TUTAO_IV_BYTE_SIZE = 16
public let AES_256_KEY_LENGTH_IN_BITS = 256
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class CryptoFunctions {

public func aesDecryptKey(_ encryptedKey: Data, withKey key: Data) throws -> Data { try TutanotaSharedFramework.aesDecryptKey(encryptedKey, withKey: key) }

public func aesEncryptData(_ data: Data, withKey key: Data, withIV iv: Data = TUTCrypto.generateIv()) throws -> Data {
public func aesEncryptData(_ data: Data, withKey key: Data, withIV iv: Data = TutanotaSharedFramework.aesGenerateIV()) throws -> Data {
try TutanotaSharedFramework.aesEncryptData(data, withKey: key, withIV: iv)
}

Expand Down
13 changes: 13 additions & 0 deletions app-ios/TutanotaSharedFramework/Crypto/Random.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/// Generate a `Data` containing `ofLength` random bytes.
public func secureRandomData(ofLength length: Int) -> Data { Data(secureRandomBytes(ofLength: length)) }

/// Generate a `UInt8` array containing `ofLength` random bytes.
public func secureRandomBytes(ofLength length: Int) -> [UInt8] {
var bytes = [UInt8](repeating: 0, count: length)
let result = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
if result != errSecSuccess {
// This should absolutely never happen.
fatalError("somehow failed to generate random bytes: \(result)")
}
return bytes
}
11 changes: 0 additions & 11 deletions app-ios/TutanotaSharedFramework/Crypto/TUTBigNum.h

This file was deleted.

16 changes: 0 additions & 16 deletions app-ios/TutanotaSharedFramework/Crypto/TUTBigNum.m

This file was deleted.

72 changes: 0 additions & 72 deletions app-ios/TutanotaSharedFramework/Crypto/TUTCrypto.h

This file was deleted.

Loading
Loading