2017-12-12 01:52:42 +02:00
const { padLeft } = require ( 'lib/string-utils.js' ) ;
2020-10-09 19:35:46 +02:00
const Logger = require ( 'lib/Logger' ) . default ;
const shim = require ( 'lib/shim' ) . default ;
const Setting = require ( 'lib/models/Setting' ) . default ;
2017-12-14 02:23:32 +02:00
const MasterKey = require ( 'lib/models/MasterKey' ) ;
2017-12-14 23:12:02 +02:00
const BaseItem = require ( 'lib/models/BaseItem' ) ;
2018-04-22 14:33:12 +02:00
const JoplinError = require ( 'lib/JoplinError' ) ;
2017-12-12 01:52:42 +02:00
2017-12-13 20:57:40 +02:00
function hexPad ( s , length ) {
return padLeft ( s , length , '0' ) ;
}
2017-12-12 01:52:42 +02:00
class EncryptionService {
2017-12-13 20:57:40 +02:00
constructor ( ) {
2018-06-25 19:14:57 +02:00
// Note: 1 MB is very slow with Node and probably even worse on mobile.
//
// On mobile the time it takes to decrypt increases exponentially for some reason, so it's important
// to have a relatively small size so as not to freeze the app. For example, on Android 7.1 simulator
// with 4.1 GB RAM, it takes this much to decrypt a block;
//
// 50KB => 1000 ms
// 25KB => 250ms
// 10KB => 200ms
// 5KB => 10ms
//
// So making the block 10 times smaller make it 100 times faster! So for now using 5KB. This can be
// changed easily since the chunk size is incorporated into the encrypted data.
this . chunkSize _ = 5000 ;
2017-12-13 20:57:40 +02:00
this . loadedMasterKeys _ = { } ;
this . activeMasterKeyId _ = null ;
2020-03-06 21:11:51 +02:00
this . defaultEncryptionMethod _ = EncryptionService . METHOD _SJCL _1A ;
2020-03-13 19:42:50 +02:00
this . defaultMasterKeyEncryptionMethod _ = EncryptionService . METHOD _SJCL _4 ;
2018-01-02 22:23:35 +02:00
this . logger _ = new Logger ( ) ;
2017-12-20 21:14:27 +02:00
this . headerTemplates _ = {
2020-01-23 00:01:58 +02:00
// Template version 1
2017-12-20 21:14:27 +02:00
1 : {
2020-01-23 00:01:58 +02:00
// Fields are defined as [name, valueSize, valueType]
2019-07-29 15:43:53 +02:00
fields : [ [ 'encryptionMethod' , 2 , 'int' ] , [ 'masterKeyId' , 32 , 'hex' ] ] ,
2017-12-20 21:14:27 +02:00
} ,
} ;
2017-12-13 20:57:40 +02:00
}
2017-12-14 02:23:32 +02:00
static instance ( ) {
if ( this . instance _ ) return this . instance _ ;
this . instance _ = new EncryptionService ( ) ;
return this . instance _ ;
}
2017-12-14 21:39:13 +02:00
setLogger ( l ) {
this . logger _ = l ;
}
logger ( ) {
return this . logger _ ;
}
2017-12-24 12:23:51 +02:00
async generateMasterKeyAndEnableEncryption ( password ) {
let masterKey = await this . generateMasterKey ( password ) ;
masterKey = await MasterKey . save ( masterKey ) ;
await this . enableEncryption ( masterKey , password ) ;
await this . loadMasterKeysFromSettings ( ) ;
2017-12-26 12:38:53 +02:00
return masterKey ;
2017-12-24 12:23:51 +02:00
}
2017-12-20 21:45:25 +02:00
async enableEncryption ( masterKey , password = null ) {
2017-12-14 21:39:13 +02:00
Setting . setValue ( 'encryption.enabled' , true ) ;
Setting . setValue ( 'encryption.activeMasterKeyId' , masterKey . id ) ;
if ( password ) {
2020-03-14 01:46:14 +02:00
const passwordCache = Setting . value ( 'encryption.passwordCache' ) ;
2019-07-29 15:43:53 +02:00
passwordCache [ masterKey . id ] = password ;
Setting . setValue ( 'encryption.passwordCache' , passwordCache ) ;
2017-12-14 21:39:13 +02:00
}
2017-12-14 23:12:02 +02:00
2017-12-20 21:45:25 +02:00
// Mark only the non-encrypted ones for sync since, if there are encrypted ones,
// it means they come from the sync target and are already encrypted over there.
2017-12-14 23:12:02 +02:00
await BaseItem . markAllNonEncryptedForSync ( ) ;
2017-12-14 21:39:13 +02:00
}
2017-12-20 21:45:25 +02:00
async disableEncryption ( ) {
2018-01-02 21:17:14 +02:00
// Allow disabling encryption even if some items are still encrypted, because whether E2EE is enabled or disabled
// should not affect whether items will enventually be decrypted or not (DecryptionWorker will still work as
// long as there are encrypted items). Also even if decryption is disabled, it's possible that encrypted items
// will still be received via synchronisation.
// const hasEncryptedItems = await BaseItem.hasEncryptedItems();
// if (hasEncryptedItems) throw new Error(_('Encryption cannot currently be disabled because some items are still encrypted. Please wait for all the items to be decrypted and try again.'));
2019-07-29 15:43:53 +02:00
2017-12-20 21:45:25 +02:00
Setting . setValue ( 'encryption.enabled' , false ) ;
// The only way to make sure everything gets decrypted on the sync target is
// to re-sync everything.
await BaseItem . forceSyncAll ( ) ;
}
2017-12-14 02:23:32 +02:00
async loadMasterKeysFromSettings ( ) {
2018-01-02 21:17:14 +02:00
const masterKeys = await MasterKey . all ( ) ;
const passwords = Setting . value ( 'encryption.passwordCache' ) ;
const activeMasterKeyId = Setting . value ( 'encryption.activeMasterKeyId' ) ;
2019-09-19 23:51:18 +02:00
this . logger ( ) . info ( ` Trying to load ${ masterKeys . length } master keys... ` ) ;
2018-01-02 21:17:14 +02:00
for ( let i = 0 ; i < masterKeys . length ; i ++ ) {
2020-03-14 01:46:14 +02:00
const mk = masterKeys [ i ] ;
2018-01-02 21:17:14 +02:00
const password = passwords [ mk . id ] ;
if ( this . isMasterKeyLoaded ( mk . id ) ) continue ;
if ( ! password ) continue ;
try {
2020-01-23 00:01:58 +02:00
await this . loadMasterKey _ ( mk , password , activeMasterKeyId === mk . id ) ;
2018-01-02 21:17:14 +02:00
} catch ( error ) {
2019-09-19 23:51:18 +02:00
this . logger ( ) . warn ( ` Cannot load master key ${ mk . id } . Invalid password? ` , error ) ;
2017-12-14 21:39:13 +02:00
}
2017-12-14 02:23:32 +02:00
}
2018-01-02 21:17:14 +02:00
2019-09-19 23:51:18 +02:00
this . logger ( ) . info ( ` Loaded master keys: ${ this . loadedMasterKeysCount ( ) } ` ) ;
2018-01-02 21:17:14 +02:00
}
loadedMasterKeysCount ( ) {
let output = 0 ;
2020-03-14 01:46:14 +02:00
for ( const n in this . loadedMasterKeys _ ) {
2018-01-02 21:17:14 +02:00
if ( ! this . loadedMasterKeys _ [ n ] ) continue ;
output ++ ;
}
return output ;
2017-12-14 02:23:32 +02:00
}
2017-12-13 20:57:40 +02:00
chunkSize ( ) {
return this . chunkSize _ ;
}
defaultEncryptionMethod ( ) {
return this . defaultEncryptionMethod _ ;
}
setActiveMasterKeyId ( id ) {
this . activeMasterKeyId _ = id ;
}
activeMasterKeyId ( ) {
2017-12-17 21:51:45 +02:00
if ( ! this . activeMasterKeyId _ ) {
const error = new Error ( 'No master key is defined as active. Check this: Either one or more master keys exist but no password was provided for any of them. Or no master key exist. Or master keys and password exist, but none was set as active.' ) ;
error . code = 'noActiveMasterKey' ;
throw error ;
}
2017-12-13 20:57:40 +02:00
return this . activeMasterKeyId _ ;
}
2017-12-14 20:53:08 +02:00
isMasterKeyLoaded ( id ) {
return ! ! this . loadedMasterKeys _ [ id ] ;
}
2020-01-23 00:01:58 +02:00
async loadMasterKey _ ( model , password , makeActive = false ) {
2017-12-13 20:57:40 +02:00
if ( ! model . id ) throw new Error ( 'Master key does not have an ID - save it first' ) ;
2020-01-23 00:01:58 +02:00
this . loadedMasterKeys _ [ model . id ] = await this . decryptMasterKey _ ( model , password ) ;
2017-12-13 20:57:40 +02:00
if ( makeActive ) this . setActiveMasterKeyId ( model . id ) ;
}
unloadMasterKey ( model ) {
delete this . loadedMasterKeys _ [ model . id ] ;
}
2017-12-14 21:39:13 +02:00
unloadAllMasterKeys ( ) {
2020-03-14 01:46:14 +02:00
for ( const id in this . loadedMasterKeys _ ) {
2017-12-14 21:39:13 +02:00
if ( ! this . loadedMasterKeys _ . hasOwnProperty ( id ) ) continue ;
this . unloadMasterKey ( this . loadedMasterKeys _ [ id ] ) ;
}
}
2017-12-13 20:57:40 +02:00
loadedMasterKey ( id ) {
2017-12-14 20:53:08 +02:00
if ( ! this . loadedMasterKeys _ [ id ] ) {
2019-09-19 23:51:18 +02:00
const error = new Error ( ` Master key is not loaded: ${ id } ` ) ;
2017-12-22 20:50:27 +02:00
error . code = 'masterKeyNotLoaded' ;
2017-12-14 20:53:08 +02:00
error . masterKeyId = id ;
throw error ;
}
2017-12-13 20:57:40 +02:00
return this . loadedMasterKeys _ [ id ] ;
}
2017-12-14 21:39:13 +02:00
loadedMasterKeyIds ( ) {
2020-03-14 01:46:14 +02:00
const output = [ ] ;
for ( const id in this . loadedMasterKeys _ ) {
2017-12-14 21:39:13 +02:00
if ( ! this . loadedMasterKeys _ . hasOwnProperty ( id ) ) continue ;
output . push ( id ) ;
}
return output ;
}
2017-12-12 01:52:42 +02:00
fsDriver ( ) {
if ( ! EncryptionService . fsDriver _ ) throw new Error ( 'EncryptionService.fsDriver_ not set!' ) ;
return EncryptionService . fsDriver _ ;
}
2017-12-12 20:41:02 +02:00
sha256 ( string ) {
2017-12-12 23:58:57 +02:00
const sjcl = shim . sjclModule ;
2019-07-29 15:43:53 +02:00
const bitArray = sjcl . hash . sha256 . hash ( string ) ;
2017-12-12 20:41:02 +02:00
return sjcl . codec . hex . fromBits ( bitArray ) ;
}
2019-07-30 09:35:42 +02:00
// async seedSjcl() {
// throw new Error('NOT TESTED');
// // Just putting this here in case it becomes needed
// // Normally seeding random bytes is not needed for our use since
// // we use shim.randomBytes directly to generate master keys.
// const sjcl = shim.sjclModule;
// const randomBytes = await shim.randomBytes(1024 / 8);
// const hexBytes = randomBytes.map(a => {
// return a.toString(16);
// });
// const hexSeed = sjcl.codec.hex.toBits(hexBytes.join(''));
// sjcl.random.addEntropy(hexSeed, 1024, 'shim.randomBytes');
// }
2017-12-13 20:57:40 +02:00
2018-09-28 20:24:57 +02:00
async randomHexString ( byteCount ) {
const bytes = await shim . randomBytes ( byteCount ) ;
2019-07-29 15:43:53 +02:00
return bytes
2020-05-21 10:14:33 +02:00
. map ( a => {
2019-07-29 15:43:53 +02:00
return hexPad ( a . toString ( 16 ) , 2 ) ;
} )
. join ( '' ) ;
2018-09-28 20:24:57 +02:00
}
2020-03-13 19:42:50 +02:00
masterKeysThatNeedUpgrading ( masterKeys ) {
return MasterKey . allWithoutEncryptionMethod ( masterKeys , this . defaultMasterKeyEncryptionMethod _ ) ;
}
async upgradeMasterKey ( model , decryptionPassword ) {
const newEncryptionMethod = this . defaultMasterKeyEncryptionMethod _ ;
const plainText = await this . decryptMasterKey _ ( model , decryptionPassword ) ;
const newContent = await this . encryptMasterKeyContent _ ( newEncryptionMethod , plainText , decryptionPassword ) ;
return { ... model , ... newContent } ;
}
async encryptMasterKeyContent _ ( encryptionMethod , hexaBytes , password ) {
// Checksum is not necessary since decryption will already fail if data is invalid
const checksum = encryptionMethod === EncryptionService . METHOD _SJCL _2 ? this . sha256 ( hexaBytes ) : '' ;
const cipherText = await this . encrypt ( encryptionMethod , password , hexaBytes ) ;
return {
checksum : checksum ,
encryption _method : encryptionMethod ,
content : cipherText ,
} ;
}
2020-01-23 00:01:58 +02:00
async generateMasterKeyContent _ ( password , options = null ) {
options = Object . assign ( { } , {
encryptionMethod : this . defaultMasterKeyEncryptionMethod _ ,
} , options ) ;
2017-12-12 20:41:02 +02:00
const bytes = await shim . randomBytes ( 256 ) ;
2020-05-21 10:14:33 +02:00
const hexaBytes = bytes . map ( a => hexPad ( a . toString ( 16 ) , 2 ) ) . join ( '' ) ;
2017-12-12 20:41:02 +02:00
2020-03-13 19:42:50 +02:00
return this . encryptMasterKeyContent _ ( options . encryptionMethod , hexaBytes , password ) ;
2017-12-12 20:41:02 +02:00
}
2020-01-23 00:01:58 +02:00
async generateMasterKey ( password , options = null ) {
const model = await this . generateMasterKeyContent _ ( password , options ) ;
const now = Date . now ( ) ;
model . created _time = now ;
model . updated _time = now ;
model . source _application = Setting . value ( 'appId' ) ;
return model ;
}
async decryptMasterKey _ ( model , password ) {
2017-12-14 02:23:32 +02:00
const plainText = await this . decrypt ( model . encryption _method , password , model . content ) ;
2020-03-13 19:42:50 +02:00
if ( model . encryption _method === EncryptionService . METHOD _SJCL _2 ) {
const checksum = this . sha256 ( plainText ) ;
if ( checksum !== model . checksum ) throw new Error ( 'Could not decrypt master key (checksum failed)' ) ;
}
2017-12-12 20:41:02 +02:00
return plainText ;
}
2017-12-14 21:39:13 +02:00
async checkMasterKeyPassword ( model , password ) {
try {
2020-01-23 00:01:58 +02:00
await this . decryptMasterKey _ ( model , password ) ;
2017-12-14 21:39:13 +02:00
} catch ( error ) {
return false ;
}
return true ;
}
2020-03-06 21:11:51 +02:00
wrapSjclError ( sjclError ) {
const error = new Error ( sjclError . message ) ;
error . stack = sjclError . stack ;
return error ;
}
2017-12-14 02:23:32 +02:00
async encrypt ( method , key , plainText ) {
2017-12-26 12:38:53 +02:00
if ( ! method ) throw new Error ( 'Encryption method is required' ) ;
if ( ! key ) throw new Error ( 'Encryption key is required' ) ;
2017-12-12 23:58:57 +02:00
const sjcl = shim . sjclModule ;
2020-01-23 00:01:58 +02:00
// 2020-01-23: Deprecated and no longer secure due to the use og OCB2 mode - do not use.
2017-12-12 01:52:42 +02:00
if ( method === EncryptionService . METHOD _SJCL ) {
2017-12-14 21:39:13 +02:00
try {
// Good demo to understand each parameter: https://bitwiseshiftleft.github.io/sjcl/demo/
return sjcl . json . encrypt ( key , plainText , {
v : 1 , // version
2020-01-23 00:01:58 +02:00
iter : 1000 , // Defaults to 1000 in sjcl but since we're running this on mobile devices, use a lower value. Maybe review this after some time. https://security.stackexchange.com/questions/3959/recommended-of-iterations-when-using-pkbdf2-sha256
2017-12-14 21:39:13 +02:00
ks : 128 , // Key size - "128 bits should be secure enough"
ts : 64 , // ???
2019-07-29 15:43:53 +02:00
mode : 'ocb2' , // The cipher mode is a standard for how to use AES and other algorithms to encrypt and authenticate your message. OCB2 mode is slightly faster and has more features, but CCM mode has wider support because it is not patented.
2019-10-09 21:35:13 +02:00
// "adata":"", // Associated Data - not needed?
2019-07-29 15:43:53 +02:00
cipher : 'aes' ,
2017-12-14 21:39:13 +02:00
} ) ;
} catch ( error ) {
2020-03-06 21:11:51 +02:00
throw this . wrapSjclError ( error ) ;
}
}
// 2020-03-06: Added method to fix https://github.com/laurent22/joplin/issues/2591
// Also took the opportunity to change number of key derivations, per Isaac Potoczny's suggestion
if ( method === EncryptionService . METHOD _SJCL _1A ) {
try {
// We need to escape the data because SJCL uses encodeURIComponent to process the data and it only
// accepts UTF-8 data, or else it throws an error. And the notes might occasionally contain
// invalid UTF-8 data. Fixes https://github.com/laurent22/joplin/issues/2591
return sjcl . json . encrypt ( key , escape ( plainText ) , {
v : 1 , // version
iter : 101 , // Since the master key already uses key derivations and is secure, additional iteration here aren't necessary, which will make decryption faster. SJCL enforces an iter strictly greater than 100
ks : 128 , // Key size - "128 bits should be secure enough"
ts : 64 , // ???
2020-03-07 00:33:33 +02:00
mode : 'ccm' , // The cipher mode is a standard for how to use AES and other algorithms to encrypt and authenticate your message. OCB2 mode is slightly faster and has more features, but CCM mode has wider support because it is not patented.
2020-03-06 21:11:51 +02:00
// "adata":"", // Associated Data - not needed?
cipher : 'aes' ,
} ) ;
} catch ( error ) {
throw this . wrapSjclError ( error ) ;
2017-12-14 21:39:13 +02:00
}
2017-12-12 20:41:02 +02:00
}
2020-01-23 00:01:58 +02:00
// 2020-01-23: Deprectated - see above.
// Was used to encrypt master keys
2017-12-12 20:41:02 +02:00
if ( method === EncryptionService . METHOD _SJCL _2 ) {
2017-12-14 21:39:13 +02:00
try {
return sjcl . json . encrypt ( key , plainText , {
v : 1 ,
iter : 10000 ,
ks : 256 ,
ts : 64 ,
2019-07-29 15:43:53 +02:00
mode : 'ocb2' ,
cipher : 'aes' ,
2017-12-14 21:39:13 +02:00
} ) ;
} catch ( error ) {
2020-03-06 21:11:51 +02:00
throw this . wrapSjclError ( error ) ;
2017-12-14 21:39:13 +02:00
}
2017-12-12 01:52:42 +02:00
}
2017-12-12 20:41:02 +02:00
2020-01-23 00:01:58 +02:00
if ( method === EncryptionService . METHOD _SJCL _3 ) {
try {
// Good demo to understand each parameter: https://bitwiseshiftleft.github.io/sjcl/demo/
return sjcl . json . encrypt ( key , plainText , {
v : 1 , // version
iter : 1000 , // Defaults to 1000 in sjcl. Since we're running this on mobile devices we need to be careful it doesn't affect performances too much. Maybe review this after some time. https://security.stackexchange.com/questions/3959/recommended-of-iterations-when-using-pkbdf2-sha256
ks : 128 , // Key size - "128 bits should be secure enough"
ts : 64 , // ???
mode : 'ccm' , // The cipher mode is a standard for how to use AES and other algorithms to encrypt and authenticate your message. OCB2 mode is slightly faster and has more features, but CCM mode has wider support because it is not patented.
// "adata":"", // Associated Data - not needed?
cipher : 'aes' ,
} ) ;
} catch ( error ) {
2020-03-06 21:11:51 +02:00
throw this . wrapSjclError ( error ) ;
2020-01-23 00:01:58 +02:00
}
}
// Same as above but more secure (but slower) to encrypt master keys
if ( method === EncryptionService . METHOD _SJCL _4 ) {
try {
return sjcl . json . encrypt ( key , plainText , {
v : 1 ,
iter : 10000 ,
ks : 256 ,
ts : 64 ,
mode : 'ccm' ,
cipher : 'aes' ,
} ) ;
} catch ( error ) {
2020-03-06 21:11:51 +02:00
throw this . wrapSjclError ( error ) ;
2020-01-23 00:01:58 +02:00
}
}
2019-09-19 23:51:18 +02:00
throw new Error ( ` Unknown encryption method: ${ method } ` ) ;
2017-12-12 01:52:42 +02:00
}
2017-12-14 02:23:32 +02:00
async decrypt ( method , key , cipherText ) {
2017-12-26 12:38:53 +02:00
if ( ! method ) throw new Error ( 'Encryption method is required' ) ;
if ( ! key ) throw new Error ( 'Encryption key is required' ) ;
2017-12-12 23:58:57 +02:00
const sjcl = shim . sjclModule ;
2020-01-23 00:01:58 +02:00
if ( ! this . isValidEncryptionMethod ( method ) ) throw new Error ( ` Unknown decryption method: ${ method } ` ) ;
2019-07-29 15:43:53 +02:00
2020-01-23 00:01:58 +02:00
try {
2020-03-06 21:11:51 +02:00
const output = sjcl . json . decrypt ( key , cipherText ) ;
if ( method === EncryptionService . METHOD _SJCL _1A ) {
return unescape ( output ) ;
} else {
return output ;
}
2020-01-23 00:01:58 +02:00
} catch ( error ) {
// SJCL returns a string as error which means stack trace is missing so convert to an error object here
throw new Error ( error . message ) ;
2017-12-12 01:52:42 +02:00
}
}
2018-06-25 19:14:57 +02:00
async encryptAbstract _ ( source , destination , options = null ) {
2020-01-23 00:01:58 +02:00
options = Object . assign ( { } , {
encryptionMethod : this . defaultEncryptionMethod ( ) ,
} , options ) ;
2018-06-25 19:14:57 +02:00
2020-01-23 00:01:58 +02:00
const method = options . encryptionMethod ;
2017-12-13 20:57:40 +02:00
const masterKeyId = this . activeMasterKeyId ( ) ;
const masterKeyPlainText = this . loadedMasterKey ( masterKeyId ) ;
const header = {
encryptionMethod : method ,
masterKeyId : masterKeyId ,
} ;
2017-12-18 21:54:03 +02:00
await destination . append ( this . encodeHeader _ ( header ) ) ;
2017-12-13 20:57:40 +02:00
2018-06-25 19:14:57 +02:00
let doneSize = 0 ;
2017-12-13 20:57:40 +02:00
while ( true ) {
2017-12-18 21:54:03 +02:00
const block = await source . read ( this . chunkSize _ ) ;
2017-12-13 20:57:40 +02:00
if ( ! block ) break ;
2018-06-25 19:14:57 +02:00
doneSize += this . chunkSize _ ;
if ( options . onProgress ) options . onProgress ( { doneSize : doneSize } ) ;
// Wait for a frame so that the app remains responsive in mobile.
// https://corbt.com/posts/2015/12/22/breaking-up-heavy-processing-in-react-native.html
await shim . waitForFrame ( ) ;
2017-12-14 02:23:32 +02:00
const encrypted = await this . encrypt ( method , masterKeyPlainText , block ) ;
2018-06-25 19:14:57 +02:00
2017-12-18 21:54:03 +02:00
await destination . append ( padLeft ( encrypted . length . toString ( 16 ) , 6 , '0' ) ) ;
await destination . append ( encrypted ) ;
2017-12-13 20:57:40 +02:00
}
}
2018-06-25 19:14:57 +02:00
async decryptAbstract _ ( source , destination , options = null ) {
if ( ! options ) options = { } ;
2020-01-23 00:01:58 +02:00
const header = await this . decodeHeaderSource _ ( source ) ;
2017-12-13 20:57:40 +02:00
const masterKeyPlainText = this . loadedMasterKey ( header . masterKeyId ) ;
2018-06-25 19:14:57 +02:00
let doneSize = 0 ;
2017-12-18 21:54:03 +02:00
while ( true ) {
const lengthHex = await source . read ( 6 ) ;
if ( ! lengthHex ) break ;
2019-09-19 23:51:18 +02:00
if ( lengthHex . length !== 6 ) throw new Error ( ` Invalid block size: ${ lengthHex } ` ) ;
2017-12-18 21:54:03 +02:00
const length = parseInt ( lengthHex , 16 ) ;
2017-12-13 20:57:40 +02:00
if ( ! length ) continue ; // Weird but could be not completely invalid (block of size 0) so continue decrypting
2017-12-18 21:54:03 +02:00
2018-06-25 19:14:57 +02:00
doneSize += length ;
if ( options . onProgress ) options . onProgress ( { doneSize : doneSize } ) ;
await shim . waitForFrame ( ) ;
2017-12-18 21:54:03 +02:00
const block = await source . read ( length ) ;
2017-12-13 20:57:40 +02:00
2017-12-14 02:23:32 +02:00
const plainText = await this . decrypt ( header . encryptionMethod , masterKeyPlainText , block ) ;
2017-12-18 21:54:03 +02:00
await destination . append ( plainText ) ;
2017-12-13 20:57:40 +02:00
}
2017-12-18 21:54:03 +02:00
}
2017-12-20 21:14:27 +02:00
stringReader _ ( string , sync = false ) {
2017-12-18 21:54:03 +02:00
const reader = {
index : 0 ,
2017-12-20 21:14:27 +02:00
read : function ( size ) {
2017-12-18 21:54:03 +02:00
const output = string . substr ( reader . index , size ) ;
reader . index += size ;
2017-12-20 21:14:27 +02:00
return ! sync ? Promise . resolve ( output ) : output ;
2017-12-18 21:54:03 +02:00
} ,
close : function ( ) { } ,
} ;
return reader ;
}
2017-12-13 20:57:40 +02:00
2017-12-18 21:54:03 +02:00
stringWriter _ ( ) {
const output = {
data : [ ] ,
append : async function ( data ) {
output . data . push ( data ) ;
} ,
result : function ( ) {
return output . data . join ( '' ) ;
} ,
close : function ( ) { } ,
} ;
return output ;
2017-12-13 20:57:40 +02:00
}
2017-12-18 21:54:03 +02:00
async fileReader _ ( path , encoding ) {
2017-12-21 21:06:08 +02:00
const handle = await this . fsDriver ( ) . open ( path , 'r' ) ;
2017-12-18 21:54:03 +02:00
const reader = {
handle : handle ,
2020-05-21 10:14:33 +02:00
read : async size => {
2017-12-21 21:06:08 +02:00
return this . fsDriver ( ) . readFileChunk ( reader . handle , size , encoding ) ;
2017-12-18 21:54:03 +02:00
} ,
2018-01-28 19:37:51 +02:00
close : async ( ) => {
await this . fsDriver ( ) . close ( reader . handle ) ;
2017-12-18 21:54:03 +02:00
} ,
} ;
return reader ;
}
2017-12-12 01:52:42 +02:00
2017-12-18 21:54:03 +02:00
async fileWriter _ ( path , encoding ) {
return {
2020-05-21 10:14:33 +02:00
append : async data => {
2017-12-21 21:06:08 +02:00
return this . fsDriver ( ) . appendFile ( path , data , encoding ) ;
2017-12-18 21:54:03 +02:00
} ,
close : function ( ) { } ,
} ;
}
2018-06-25 19:14:57 +02:00
async encryptString ( plainText , options = null ) {
2017-12-18 21:54:03 +02:00
const source = this . stringReader _ ( plainText ) ;
const destination = this . stringWriter _ ( ) ;
2018-06-25 19:14:57 +02:00
await this . encryptAbstract _ ( source , destination , options ) ;
2017-12-18 21:54:03 +02:00
return destination . result ( ) ;
}
2018-06-25 19:14:57 +02:00
async decryptString ( cipherText , options = null ) {
2017-12-18 21:54:03 +02:00
const source = this . stringReader _ ( cipherText ) ;
const destination = this . stringWriter _ ( ) ;
2018-06-25 19:14:57 +02:00
await this . decryptAbstract _ ( source , destination , options ) ;
2017-12-18 21:54:03 +02:00
return destination . data . join ( '' ) ;
}
2018-06-25 19:14:57 +02:00
async encryptFile ( srcPath , destPath , options = null ) {
2017-12-18 21:54:03 +02:00
let source = await this . fileReader _ ( srcPath , 'base64' ) ;
let destination = await this . fileWriter _ ( destPath , 'ascii' ) ;
2017-12-12 01:52:42 +02:00
2018-01-28 19:37:51 +02:00
const cleanUp = async ( ) => {
if ( source ) await source . close ( ) ;
if ( destination ) await destination . close ( ) ;
2019-07-30 09:35:42 +02:00
// eslint-disable-next-line require-atomic-updates
2017-12-18 21:54:03 +02:00
source = null ;
2019-07-30 09:35:42 +02:00
// eslint-disable-next-line require-atomic-updates
2017-12-18 21:54:03 +02:00
destination = null ;
2019-07-29 15:43:53 +02:00
} ;
2017-12-12 01:52:42 +02:00
try {
2017-12-21 21:06:08 +02:00
await this . fsDriver ( ) . unlink ( destPath ) ;
2018-06-25 19:14:57 +02:00
await this . encryptAbstract _ ( source , destination , options ) ;
2017-12-12 01:52:42 +02:00
} catch ( error ) {
cleanUp ( ) ;
2017-12-21 21:06:08 +02:00
await this . fsDriver ( ) . unlink ( destPath ) ;
2017-12-12 01:52:42 +02:00
throw error ;
}
2018-01-28 19:37:51 +02:00
await cleanUp ( ) ;
2017-12-12 01:52:42 +02:00
}
2018-06-25 19:14:57 +02:00
async decryptFile ( srcPath , destPath , options = null ) {
2017-12-18 21:54:03 +02:00
let source = await this . fileReader _ ( srcPath , 'ascii' ) ;
let destination = await this . fileWriter _ ( destPath , 'base64' ) ;
2017-12-12 01:52:42 +02:00
2018-01-28 19:37:51 +02:00
const cleanUp = async ( ) => {
if ( source ) await source . close ( ) ;
if ( destination ) await destination . close ( ) ;
2019-07-30 09:35:42 +02:00
// eslint-disable-next-line require-atomic-updates
2017-12-18 21:54:03 +02:00
source = null ;
2019-07-30 09:35:42 +02:00
// eslint-disable-next-line require-atomic-updates
2017-12-18 21:54:03 +02:00
destination = null ;
2019-07-29 15:43:53 +02:00
} ;
2017-12-12 01:52:42 +02:00
try {
2017-12-21 21:06:08 +02:00
await this . fsDriver ( ) . unlink ( destPath ) ;
2018-06-25 19:14:57 +02:00
await this . decryptAbstract _ ( source , destination , options ) ;
2017-12-12 01:52:42 +02:00
} catch ( error ) {
cleanUp ( ) ;
2017-12-21 21:06:08 +02:00
await this . fsDriver ( ) . unlink ( destPath ) ;
2017-12-12 01:52:42 +02:00
throw error ;
}
2018-01-28 19:37:51 +02:00
await cleanUp ( ) ;
2017-12-12 01:52:42 +02:00
}
2017-12-20 21:14:27 +02:00
headerTemplate ( version ) {
const r = this . headerTemplates _ [ version ] ;
2019-09-19 23:51:18 +02:00
if ( ! r ) throw new Error ( ` Unknown header version: ${ version } ` ) ;
2017-12-20 21:14:27 +02:00
return r ;
2017-12-18 21:54:03 +02:00
}
2017-12-13 20:57:40 +02:00
encodeHeader _ ( header ) {
// Sanity check
2019-09-19 23:51:18 +02:00
if ( header . masterKeyId . length !== 32 ) throw new Error ( ` Invalid master key ID size: ${ header . masterKeyId } ` ) ;
2017-12-13 20:57:40 +02:00
2017-12-20 21:14:27 +02:00
let encryptionMetadata = '' ;
encryptionMetadata += padLeft ( header . encryptionMethod . toString ( 16 ) , 2 , '0' ) ;
encryptionMetadata += header . masterKeyId ;
encryptionMetadata = padLeft ( encryptionMetadata . length . toString ( 16 ) , 6 , '0' ) + encryptionMetadata ;
2019-09-19 23:51:18 +02:00
return ` JED01 ${ encryptionMetadata } ` ;
2017-12-13 20:57:40 +02:00
}
2020-01-23 00:01:58 +02:00
async decodeHeaderString ( cipherText ) {
const source = this . stringReader _ ( cipherText ) ;
return this . decodeHeaderSource _ ( source ) ;
}
async decodeHeaderSource _ ( source ) {
const identifier = await source . read ( 5 ) ;
if ( ! this . isValidHeaderIdentifier ( identifier ) ) throw new JoplinError ( ` Invalid encryption identifier. Data is not actually encrypted? ID was: ${ identifier } ` , 'invalidIdentifier' ) ;
const mdSizeHex = await source . read ( 6 ) ;
const mdSize = parseInt ( mdSizeHex , 16 ) ;
if ( isNaN ( mdSize ) || ! mdSize ) throw new Error ( ` Invalid header metadata size: ${ mdSizeHex } ` ) ;
const md = await source . read ( parseInt ( mdSizeHex , 16 ) ) ;
return this . decodeHeaderBytes _ ( identifier + mdSizeHex + md ) ;
}
decodeHeaderBytes _ ( headerHexaBytes ) {
2017-12-20 21:14:27 +02:00
const reader = this . stringReader _ ( headerHexaBytes , true ) ;
const identifier = reader . read ( 3 ) ;
const version = parseInt ( reader . read ( 2 ) , 16 ) ;
2019-09-19 23:51:18 +02:00
if ( identifier !== 'JED' ) throw new Error ( ` Invalid header (missing identifier): ${ headerHexaBytes . substr ( 0 , 64 ) } ` ) ;
2017-12-20 21:14:27 +02:00
const template = this . headerTemplate ( version ) ;
2017-12-13 20:57:40 +02:00
2019-09-13 00:16:42 +02:00
parseInt ( reader . read ( 6 ) , 16 ) ; // Read the size and move the reader pointer forward
2017-12-13 20:57:40 +02:00
2020-03-14 01:46:14 +02:00
const output = { } ;
2017-12-13 20:57:40 +02:00
2017-12-20 21:14:27 +02:00
for ( let i = 0 ; i < template . fields . length ; i ++ ) {
const m = template . fields [ i ] ;
2019-07-30 09:35:42 +02:00
const name = m [ 0 ] ;
const size = m [ 1 ] ;
2017-12-13 20:57:40 +02:00
const type = m [ 2 ] ;
2019-07-30 09:35:42 +02:00
let v = reader . read ( size ) ;
2017-12-13 20:57:40 +02:00
if ( type === 'int' ) {
v = parseInt ( v , 16 ) ;
} else if ( type === 'hex' ) {
// Already in hexa
} else {
2019-09-19 23:51:18 +02:00
throw new Error ( ` Invalid type: ${ type } ` ) ;
2017-12-13 20:57:40 +02:00
}
2019-07-30 09:35:42 +02:00
output [ name ] = v ;
2017-12-13 20:57:40 +02:00
}
return output ;
2017-12-12 01:52:42 +02:00
}
2017-12-04 21:01:56 +02:00
isValidHeaderIdentifier ( id , ignoreTooLongLength = false ) {
2018-01-26 01:01:18 +02:00
if ( ! id ) return false ;
if ( ! ignoreTooLongLength && id . length !== 5 ) return false ;
2017-12-04 21:01:56 +02:00
return /JED\d\d/ . test ( id ) ;
}
2020-01-23 00:01:58 +02:00
isValidEncryptionMethod ( method ) {
2020-03-06 21:11:51 +02:00
return [ EncryptionService . METHOD _SJCL , EncryptionService . METHOD _SJCL _1A , EncryptionService . METHOD _SJCL _2 , EncryptionService . METHOD _SJCL _3 , EncryptionService . METHOD _SJCL _4 ] . indexOf ( method ) >= 0 ;
2020-01-23 00:01:58 +02:00
}
2017-12-04 21:01:56 +02:00
async itemIsEncrypted ( item ) {
if ( ! item ) throw new Error ( 'No item' ) ;
const ItemClass = BaseItem . itemClass ( item ) ;
if ( ! ItemClass . encryptionSupported ( ) ) return false ;
2018-01-26 01:01:18 +02:00
return item . encryption _applied && this . isValidHeaderIdentifier ( item . encryption _cipher _text , true ) ;
2017-12-04 21:01:56 +02:00
}
async fileIsEncrypted ( path ) {
const handle = await this . fsDriver ( ) . open ( path , 'r' ) ;
const headerIdentifier = await this . fsDriver ( ) . readFileChunk ( handle , 5 , 'ascii' ) ;
await this . fsDriver ( ) . close ( handle ) ;
return this . isValidHeaderIdentifier ( headerIdentifier ) ;
}
2017-12-12 01:52:42 +02:00
}
EncryptionService . METHOD _SJCL = 1 ;
2017-12-12 20:41:02 +02:00
EncryptionService . METHOD _SJCL _2 = 2 ;
2020-01-23 00:01:58 +02:00
EncryptionService . METHOD _SJCL _3 = 3 ;
EncryptionService . METHOD _SJCL _4 = 4 ;
2020-03-06 21:11:51 +02:00
EncryptionService . METHOD _SJCL _1A = 5 ;
2017-12-12 01:52:42 +02:00
EncryptionService . fsDriver _ = null ;
2019-07-29 15:43:53 +02:00
module . exports = EncryptionService ;