cossacklabs / themis

Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.
https://www.cossacklabs.com/themis
Apache License 2.0
1.88k stars 143 forks source link

Silent Error When Decrypting >=148Kb base64 strings in React Native #1056

Open adamblvck opened 2 months ago

adamblvck commented 2 months ago

Describe the bug

Decryption in React Native, specifically tested on iOS, has trouble decrypting files larger than 148Kb. I'm using Expo. To have Themis React Native work in this environment, a dev build is needed. It worked on Expo SDK 46 (2 years ago), on SDK 49, SDK 50 and now SDK 51 it seems to be able to encrypt rather large files, but not able to decrypt them.

In #994 @djaffer mentions a similar issue. React Native Encryption functions seem to work for files even 120Mb in size, but decryption fails for files >=148Kb in size. For files >=10Mb I get regex stack errors, which might be a React Native limitation.

To Reproduce

Start a fresh SDK 51 installation, install themis, create an EAS build, and launch the app. For your information, Expo SDK 51 runs:

Next define a dummy generator in App.js:

function getdummy(mbytes) {
    // Calculate the number of bytes
    const bytes = mbytes * 1000000;

    // Calculate the length of the base64 string
    // (4 base64 characters represent 3 bytes)
    const base64Length = Math.ceil(bytes / 3) * 4;

    // Generate a random string of the calculated length
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < base64Length; i++) {
            result += characters.charAt(Math.floor(Math.random() * characters.length));
    }

    return result;
}

Then have a simple function test the encryption as follows, invoked after a button click, or on load of the app:

function testDecrypt = () => {
    try {
        const dummy = getdummy(0.145);
        console.log("DUMMY", dummy.length, dummy.slice(0,20));

        const encrypted64 = await secureCellSealWithSymmetricKeyEncrypt64(userPair.priv, dummy);
        console.log("ENCRYPTED", encrypted64.length, encrypted64.slice(0,20));

        const decrypted64 = await secureCellSealWithSymmetricKeyDecrypt64(userPair.priv, encrypted64);
        console.log("DECRYPTED", decrypted64.length, decrypted64.slice(0,20));

        console.log("THEY'RE THE SAME", dummy == decrypted64)
    } catch (error) {
        console.log("MASSIVE ERROR", error);
    }
}

I'm getting the following output for a 140 Kb size:

 LOG  DUMMY 186668 lASDSbaVW2t1qlkwenxg
 LOG  ENCRYPTED 248892 qCKtk0zbO30++uXklq/X
 LOG  DECRYPTED 186668 lASDSbaVW2t1qlkwenxg
 LOG  THEY'RE THE SAME true

For a 145 Kb size, I get a silence error in the bridge:

 LOG  DUMMY 266668 B3TmzBzd20Thk8QDKEHr
 LOG  ENCRYPTED 355560 bdfTmNvOufF1JEDv7FOQ
 LOG  MASSIVE ERROR [Error: Exception in HostFunction: Malformed calls from JS: field sizes are different.

[[121,80],[10,0],[[1759,100,1725019047524,false]],6350]]

We can debug which host functions bugged out by defining a findModuleByModuleAndMethodIds function, then looking them up for processes 121.80 and 80.0:

// bridge debugging
if (global.__fbBatchedBridge) {
    const origMessageQueue = global.__fbBatchedBridge;
    const modules = origMessageQueue._remoteModuleTable;
    const methods = origMessageQueue._remoteMethodTable;
    global.findModuleByModuleAndMethodIds = (moduleId, methodId) => {
      console.log(`The problematic line code is in: ${modules[moduleId]}.${methods[moduleId][methodId]}`)
    }
}

global.findModuleByModuleAndMethodIds(121, 10);
global.findModuleByModuleAndMethodIds(80, 0);

Which returns the following two possible functions having no parameters passed over the bridge:

 LOG  The problematic line code is in: Themis.secureCellSealWithSymmetricKeyEncrypt64
 LOG  The problematic line code is in: Timing.createTimer

I've found that this type of silent error happens with any decryption, whereas it doesn't happen at the encryption stage. For a 10Mbyte string, encryption works, decryption fails with a max regex stack depth error:

 LOG  DUMMY 13333336 gpPnBQloMKtC4uiFQmym
 LOG  ENCRYPTED 17777784 fG3//XnUadHaNx5qrp20
 LOG  MASSIVE ERROR [RangeError: Maximum regex stack depth reached]

Have less than 10Mbyte chunks is something that I can easily live with, but to encrypt and decrypt files into chunks of less than 150Kb feels like a bridge overhead.

Expected behavior Two years ago, I was able to decrypt files up to 10Mbyte in size in React Native. Themis Nodejs implementation doesn't suffer from this limitation.

Environment (please complete the following information):

Additional context

If any additional context is required, please share away. Generally I would like to know if this perhaps has to do with the new architecture of React Native 18?

vixentael commented 2 months ago

Thank you for such detailed issue, we will take a look

adamblvck commented 2 months ago

A little update from my side: switching the js engine from hermes to jsc, allows encryption and decryption of messages up to 1.5Mbytes in size. This is, as I can remember, what I've been working with a few years back.

So even though this slightly increases the odd max-cap, I must state that the react-native community and major react-native SDKs support hermes as their goto engine. Most important rn libraries like timezone, animations, and native libraries use hermes. Some adopt their libraries to the new React architecture which solves all previous bridge issues. For Themis this would mean lightning fast encryption.

Thank you for looking into the issue!