2021-08-23 19:47:07 +02:00
import { MasterKeyEntity } from './types' ;
2023-07-27 17:05:56 +02:00
import Logger from '@joplin/utils/Logger' ;
2021-08-23 19:47:07 +02:00
import shim from '../../shim' ;
import Setting from '../../models/Setting' ;
import MasterKey from '../../models/MasterKey' ;
import BaseItem from '../../models/BaseItem' ;
import JoplinError from '../../JoplinError' ;
import { getActiveMasterKeyId , setActiveMasterKeyId } from '../synchronizer/syncInfoUtils' ;
const { padLeft } = require ( '../../string-utils.js' ) ;
2017-12-12 01:52:42 +02:00
2021-08-30 15:15:35 +02:00
const logger = Logger . create ( 'EncryptionService' ) ;
2021-01-22 19:41:11 +02:00
function hexPad ( s : string , length : number ) {
2017-12-13 20:57:40 +02:00
return padLeft ( s , length , '0' ) ;
}
2021-06-20 17:29:35 +02:00
export function isValidHeaderIdentifier ( id : string , ignoreTooLongLength = false ) {
if ( ! id ) return false ;
if ( ! ignoreTooLongLength && id . length !== 5 ) return false ;
return /JED\d\d/ . test ( id ) ;
}
2021-08-12 17:54:10 +02:00
interface DecryptedMasterKey {
updatedTime : number ;
plainText : string ;
}
2021-10-03 17:00:49 +02:00
export interface EncryptionCustomHandler {
context? : any ;
encrypt ( context : any , hexaBytes : string , password : string ) : Promise < string > ;
decrypt ( context : any , hexaBytes : string , password : string ) : Promise < string > ;
}
export enum EncryptionMethod {
SJCL = 1 ,
SJCL2 = 2 ,
SJCL3 = 3 ,
SJCL4 = 4 ,
SJCL1a = 5 ,
Custom = 6 ,
2023-06-10 20:19:27 +02:00
SJCL1b = 7 ,
2021-10-03 17:00:49 +02:00
}
export interface EncryptOptions {
encryptionMethod? : EncryptionMethod ;
2023-06-30 11:30:29 +02:00
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
2021-10-03 17:00:49 +02:00
onProgress? : Function ;
encryptionHandler? : EncryptionCustomHandler ;
masterKeyId? : string ;
}
2021-01-22 19:41:11 +02:00
export default class EncryptionService {
public static instance_ : EncryptionService = null ;
public static fsDriver_ : any = null ;
// 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.
private chunkSize_ = 5000 ;
2021-08-12 17:54:10 +02:00
private decryptedMasterKeys_ : Record < string , DecryptedMasterKey > = { } ;
2023-08-14 19:26:49 +02:00
public defaultEncryptionMethod_ = EncryptionMethod . SJCL1a ; // public because used in tests
2021-10-03 17:00:49 +02:00
private defaultMasterKeyEncryptionMethod_ = EncryptionMethod . SJCL4 ;
2021-01-22 19:41:11 +02:00
private headerTemplates_ = {
// Template version 1
1 : {
// Fields are defined as [name, valueSize, valueType]
fields : [ [ 'encryptionMethod' , 2 , 'int' ] , [ 'masterKeyId' , 32 , 'hex' ] ] ,
} ,
} ;
public static instance() {
2017-12-14 02:23:32 +02:00
if ( this . instance_ ) return this . instance_ ;
this . instance_ = new EncryptionService ( ) ;
return this . instance_ ;
}
2021-10-03 17:00:49 +02:00
public get defaultMasterKeyEncryptionMethod() {
return this . defaultMasterKeyEncryptionMethod_ ;
}
2023-03-06 16:22:01 +02:00
public loadedMasterKeysCount() {
2021-08-12 17:54:10 +02:00
return Object . keys ( this . decryptedMasterKeys_ ) . length ;
2017-12-14 02:23:32 +02:00
}
2023-03-06 16:22:01 +02:00
public chunkSize() {
2017-12-13 20:57:40 +02:00
return this . chunkSize_ ;
}
2023-03-06 16:22:01 +02:00
public defaultEncryptionMethod() {
2017-12-13 20:57:40 +02:00
return this . defaultEncryptionMethod_ ;
}
2023-03-06 16:22:01 +02:00
public setActiveMasterKeyId ( id : string ) {
2021-08-12 17:54:10 +02:00
setActiveMasterKeyId ( id ) ;
2017-12-13 20:57:40 +02:00
}
2023-03-06 16:22:01 +02:00
public activeMasterKeyId() {
2021-08-12 17:54:10 +02:00
const id = getActiveMasterKeyId ( ) ;
if ( ! id ) {
2021-01-22 19:41:11 +02:00
const error : any = 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.' ) ;
2017-12-17 21:51:45 +02:00
error . code = 'noActiveMasterKey' ;
throw error ;
}
2021-08-12 17:54:10 +02:00
return id ;
2017-12-13 20:57:40 +02:00
}
2021-08-12 17:54:10 +02:00
public isMasterKeyLoaded ( masterKey : MasterKeyEntity ) {
const d = this . decryptedMasterKeys_ [ masterKey . id ] ;
if ( ! d ) return false ;
return d . updatedTime === masterKey . updated_time ;
2017-12-14 20:53:08 +02:00
}
2021-08-12 17:54:10 +02:00
public async loadMasterKey ( model : MasterKeyEntity , password : string , 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' ) ;
2021-08-30 15:15:35 +02:00
logger . info ( ` Loading master key: ${ model . id } . Make active: ` , makeActive ) ;
2021-08-12 17:54:10 +02:00
this . decryptedMasterKeys_ [ model . id ] = {
2021-10-03 17:00:49 +02:00
plainText : await this . decryptMasterKeyContent ( model , password ) ,
2021-08-12 17:54:10 +02:00
updatedTime : model.updated_time ,
} ;
2021-08-30 15:15:35 +02:00
2017-12-13 20:57:40 +02:00
if ( makeActive ) this . setActiveMasterKeyId ( model . id ) ;
}
2023-03-06 16:22:01 +02:00
public unloadMasterKey ( model : MasterKeyEntity ) {
2021-08-12 17:54:10 +02:00
delete this . decryptedMasterKeys_ [ model . id ] ;
2017-12-13 20:57:40 +02:00
}
2023-03-06 16:22:01 +02:00
public loadedMasterKey ( id : string ) {
2021-08-12 17:54:10 +02:00
if ( ! this . decryptedMasterKeys_ [ id ] ) {
2021-01-22 19:41:11 +02:00
const error : any = 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 ;
}
2021-08-12 17:54:10 +02:00
return this . decryptedMasterKeys_ [ id ] ;
2017-12-13 20:57:40 +02:00
}
2023-03-06 16:22:01 +02:00
public loadedMasterKeyIds() {
2021-08-12 17:54:10 +02:00
return Object . keys ( this . decryptedMasterKeys_ ) ;
2017-12-14 21:39:13 +02:00
}
2023-03-06 16:22:01 +02:00
public fsDriver() {
2017-12-12 01:52:42 +02:00
if ( ! EncryptionService . fsDriver_ ) throw new Error ( 'EncryptionService.fsDriver_ not set!' ) ;
return EncryptionService . fsDriver_ ;
}
2023-03-06 16:22:01 +02:00
public sha256 ( string : 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 ) ;
}
2023-03-06 16:22:01 +02:00
public async generateApiToken() {
2021-04-07 20:27:16 +02:00
return await this . randomHexString ( 64 ) ;
}
2021-10-03 17:00:49 +02:00
private async randomHexString ( byteCount : number ) {
2021-01-22 19:41:11 +02:00
const bytes : any [ ] = 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
}
2021-10-03 17:00:49 +02:00
public masterKeysThatNeedUpgrading ( masterKeys : MasterKeyEntity [ ] ) {
return MasterKey . allWithoutEncryptionMethod ( masterKeys , [ this . defaultMasterKeyEncryptionMethod_ , EncryptionMethod . Custom ] ) ;
2020-03-13 19:42:50 +02:00
}
2021-10-03 17:00:49 +02:00
public async reencryptMasterKey ( model : MasterKeyEntity , decryptionPassword : string , encryptionPassword : string , decryptOptions : EncryptOptions = null , encryptOptions : EncryptOptions = null ) : Promise < MasterKeyEntity > {
2020-03-13 19:42:50 +02:00
const newEncryptionMethod = this . defaultMasterKeyEncryptionMethod_ ;
2021-10-03 17:00:49 +02:00
const plainText = await this . decryptMasterKeyContent ( model , decryptionPassword , decryptOptions ) ;
const newContent = await this . encryptMasterKeyContent ( newEncryptionMethod , plainText , encryptionPassword , encryptOptions ) ;
2020-03-13 19:42:50 +02:00
return { . . . model , . . . newContent } ;
}
2021-10-03 17:00:49 +02:00
public async encryptMasterKeyContent ( encryptionMethod : EncryptionMethod , hexaBytes : string , password : string , options : EncryptOptions = null ) : Promise < MasterKeyEntity > {
options = { . . . options } ;
if ( encryptionMethod === null ) encryptionMethod = this . defaultMasterKeyEncryptionMethod_ ;
if ( options . encryptionHandler ) {
return {
checksum : '' ,
encryption_method : EncryptionMethod.Custom ,
content : await options . encryptionHandler . encrypt ( options . encryptionHandler . context , hexaBytes , password ) ,
} ;
} else {
return {
// Checksum is not necessary since decryption will already fail if data is invalid
checksum : encryptionMethod === EncryptionMethod . SJCL2 ? this . sha256 ( hexaBytes ) : '' ,
encryption_method : encryptionMethod ,
content : await this . encrypt ( encryptionMethod , password , hexaBytes ) ,
} ;
}
2020-03-13 19:42:50 +02:00
}
2021-10-03 17:00:49 +02:00
private async generateMasterKeyContent_ ( password : string , options : EncryptOptions = null ) {
2023-06-01 13:02:36 +02:00
options = { encryptionMethod : this.defaultMasterKeyEncryptionMethod_ , . . . options } ;
2020-01-23 00:01:58 +02:00
2021-01-22 19:41:11 +02:00
const bytes : any [ ] = 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
2021-10-03 17:00:49 +02:00
return this . encryptMasterKeyContent ( options . encryptionMethod , hexaBytes , password , options ) ;
2017-12-12 20:41:02 +02:00
}
2021-10-03 17:00:49 +02:00
public async generateMasterKey ( password : string , options : EncryptOptions = null ) {
2020-01-23 00:01:58 +02:00
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' ) ;
2022-04-13 13:18:38 +02:00
model . hasBeenUsed = false ;
2020-01-23 00:01:58 +02:00
return model ;
}
2021-10-03 17:00:49 +02:00
public async decryptMasterKeyContent ( model : MasterKeyEntity , password : string , options : EncryptOptions = null ) : Promise < string > {
options = options || { } ;
if ( model . encryption_method === EncryptionMethod . Custom ) {
if ( ! options . encryptionHandler ) throw new Error ( 'Master key was encrypted using a custom method, but no encryptionHandler is provided' ) ;
return options . encryptionHandler . decrypt ( options . encryptionHandler . context , model . content , password ) ;
}
2017-12-14 02:23:32 +02:00
const plainText = await this . decrypt ( model . encryption_method , password , model . content ) ;
2021-10-03 17:00:49 +02:00
if ( model . encryption_method === EncryptionMethod . SJCL2 ) {
2020-03-13 19:42:50 +02:00
const checksum = this . sha256 ( plainText ) ;
if ( checksum !== model . checksum ) throw new Error ( 'Could not decrypt master key (checksum failed)' ) ;
}
2021-08-12 17:54:10 +02:00
2017-12-12 20:41:02 +02:00
return plainText ;
}
2021-08-30 15:15:35 +02:00
public async checkMasterKeyPassword ( model : MasterKeyEntity , password : string ) {
2017-12-14 21:39:13 +02:00
try {
2021-10-03 17:00:49 +02:00
await this . decryptMasterKeyContent ( model , password ) ;
2017-12-14 21:39:13 +02:00
} catch ( error ) {
return false ;
}
return true ;
}
2021-08-30 15:15:35 +02:00
private wrapSjclError ( sjclError : any ) {
2020-03-06 21:11:51 +02:00
const error = new Error ( sjclError . message ) ;
error . stack = sjclError . stack ;
return error ;
}
2021-10-03 17:00:49 +02:00
public async encrypt ( method : EncryptionMethod , key : string , plainText : string ) : Promise < string > {
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 ;
2023-06-10 20:19:27 +02:00
const handlers : Record < EncryptionMethod , ( ) = > string > = {
// 2020-01-23: Deprecated and no longer secure due to the use og OCB2 mode - do not use.
[ EncryptionMethod . SJCL ] : ( ) = > {
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 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
ks : 128 , // Key size - "128 bits should be secure enough"
ts : 64 , // ???
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.
// "adata":"", // Associated Data - not needed?
cipher : 'aes' ,
} ) ;
} catch ( error ) {
throw this . wrapSjclError ( error ) ;
}
} ,
2020-03-06 21:11:51 +02:00
2023-06-10 20:19:27 +02:00
// 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
// 2023-06-10: Deprecated in favour of SJCL1b
[ EncryptionMethod . SJCL1a ] : ( ) = > {
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 , // ???
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 ) {
throw this . wrapSjclError ( error ) ;
}
} ,
2017-12-12 20:41:02 +02:00
2023-06-10 20:19:27 +02:00
// 2023-06-10: Changed AES-128 to AES-256 per TheQuantumPhysicist's suggestions
// https://github.com/laurent22/joplin/issues/7686
[ EncryptionMethod . SJCL1b ] : ( ) = > {
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 : 256 , // Key size - "256-bit is the golden standard that we should follow."
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 ) {
throw this . wrapSjclError ( error ) ;
}
} ,
2017-12-12 20:41:02 +02:00
2023-06-10 20:19:27 +02:00
// 2020-01-23: Deprecated - see above.
// Was used to encrypt master keys
[ EncryptionMethod . SJCL2 ] : ( ) = > {
try {
return sjcl . json . encrypt ( key , plainText , {
v : 1 ,
iter : 10000 ,
ks : 256 ,
ts : 64 ,
mode : 'ocb2' ,
cipher : 'aes' ,
} ) ;
} catch ( error ) {
throw this . wrapSjclError ( error ) ;
}
} ,
2020-01-23 00:01:58 +02:00
2023-06-10 20:19:27 +02:00
// Don't know why we have this - it's not used anywhere. It must be
// kept however, in case some note somewhere is encrypted using this
// method.
[ EncryptionMethod . SJCL3 ] : ( ) = > {
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 ) {
throw this . wrapSjclError ( error ) ;
}
} ,
// Same as above but more secure (but slower) to encrypt master keys
[ EncryptionMethod . SJCL4 ] : ( ) = > {
try {
return sjcl . json . encrypt ( key , plainText , {
v : 1 ,
iter : 10000 ,
ks : 256 ,
ts : 64 ,
mode : 'ccm' ,
cipher : 'aes' ,
} ) ;
} catch ( error ) {
throw this . wrapSjclError ( error ) ;
}
} ,
[ EncryptionMethod . Custom ] : ( ) = > {
// This is handled elsewhere but as a sanity check, throw an exception
throw new Error ( 'Custom encryption method is not supported here' ) ;
} ,
} ;
2020-01-23 00:01:58 +02:00
2023-06-10 20:19:27 +02:00
return handlers [ method ] ( ) ;
2017-12-12 01:52:42 +02:00
}
2023-03-06 16:22:01 +02:00
public async decrypt ( method : EncryptionMethod , key : string , cipherText : string ) {
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 ) ;
2023-06-10 20:19:27 +02:00
if ( method === EncryptionMethod . SJCL1a || method === EncryptionMethod . SJCL1b ) {
2020-03-06 21:11:51 +02:00
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
}
}
2023-03-06 16:22:01 +02:00
private async encryptAbstract_ ( source : any , destination : any , options : EncryptOptions = null ) {
2023-06-01 13:02:36 +02:00
options = { encryptionMethod : this.defaultEncryptionMethod ( ) , . . . options } ;
2018-06-25 19:14:57 +02:00
2020-01-23 00:01:58 +02:00
const method = options . encryptionMethod ;
2021-10-03 17:00:49 +02:00
const masterKeyId = options . masterKeyId ? options.masterKeyId : this.activeMasterKeyId ( ) ;
2021-08-12 17:54:10 +02:00
const masterKeyPlainText = this . loadedMasterKey ( masterKeyId ) . plainText ;
2017-12-13 20:57:40 +02:00
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
}
}
2023-03-06 16:22:01 +02:00
private async decryptAbstract_ ( source : any , destination : any , options : EncryptOptions = null ) {
2018-06-25 19:14:57 +02:00
if ( ! options ) options = { } ;
2021-01-22 19:41:11 +02:00
const header : any = await this . decodeHeaderSource_ ( source ) ;
2021-08-12 17:54:10 +02:00
const masterKeyPlainText = this . loadedMasterKey ( header . masterKeyId ) . plainText ;
2017-12-13 20:57:40 +02:00
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
}
2023-03-06 16:22:01 +02:00
private stringReader_ ( string : string , sync = false ) {
2017-12-18 21:54:03 +02:00
const reader = {
index : 0 ,
2021-01-22 19:41:11 +02:00
read : function ( size : number ) {
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
2023-03-06 16:22:01 +02:00
private stringWriter_() {
2021-01-22 19:41:11 +02:00
const output : any = {
2017-12-18 21:54:03 +02:00
data : [ ] ,
2021-01-22 19:41:11 +02:00
append : async function ( data : any ) {
2017-12-18 21:54:03 +02:00
output . data . push ( data ) ;
} ,
result : function ( ) {
return output . data . join ( '' ) ;
} ,
close : function ( ) { } ,
} ;
return output ;
2017-12-13 20:57:40 +02:00
}
2023-03-06 16:22:01 +02:00
private async fileReader_ ( path : string , encoding : any ) {
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 ,
2021-01-22 19:41:11 +02:00
read : async ( size : number ) = > {
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
2023-03-06 16:22:01 +02:00
private async fileWriter_ ( path : string , encoding : any ) {
2017-12-18 21:54:03 +02:00
return {
2021-01-22 19:41:11 +02:00
append : async ( data : any ) = > {
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 ( ) { } ,
} ;
}
2021-10-03 17:00:49 +02:00
public async encryptString ( plainText : any , options : EncryptOptions = null ) : Promise < string > {
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 ( ) ;
}
2021-10-03 17:00:49 +02:00
public async decryptString ( cipherText : any , options : EncryptOptions = null ) : Promise < string > {
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 ( '' ) ;
}
2023-03-06 16:22:01 +02:00
public async encryptFile ( srcPath : string , destPath : string , options : EncryptOptions = 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 ) {
2021-01-22 19:41:11 +02:00
await 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
}
2023-03-06 16:22:01 +02:00
public async decryptFile ( srcPath : string , destPath : string , options : EncryptOptions = 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 ) {
2021-01-22 19:41:11 +02:00
await 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
}
2023-03-06 16:22:01 +02:00
public headerTemplate ( version : number ) {
2021-01-22 19:41:11 +02:00
const r = ( this . headerTemplates_ as any ) [ 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
}
2023-03-06 16:22:01 +02:00
public encodeHeader_ ( header : any ) {
2017-12-13 20:57:40 +02:00
// 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
}
2023-03-06 16:22:01 +02:00
public async decodeHeaderString ( cipherText : any ) {
2020-01-23 00:01:58 +02:00
const source = this . stringReader_ ( cipherText ) ;
return this . decodeHeaderSource_ ( source ) ;
}
2023-03-06 16:22:01 +02:00
private async decodeHeaderSource_ ( source : any ) {
2020-01-23 00:01:58 +02:00
const identifier = await source . read ( 5 ) ;
2021-06-20 17:29:35 +02:00
if ( ! isValidHeaderIdentifier ( identifier ) ) throw new JoplinError ( ` Invalid encryption identifier. Data is not actually encrypted? ID was: ${ identifier } ` , 'invalidIdentifier' ) ;
2020-01-23 00:01:58 +02:00
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 ) ;
}
2023-03-06 16:22:01 +02:00
public decodeHeaderBytes_ ( headerHexaBytes : any ) {
2021-01-22 19:41:11 +02:00
const reader : any = this . stringReader_ ( headerHexaBytes , true ) ;
2017-12-20 21:14:27 +02:00
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
2021-01-22 19:41:11 +02:00
const output : any = { } ;
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
}
2023-03-06 16:22:01 +02:00
public isValidEncryptionMethod ( method : EncryptionMethod ) {
2023-06-10 20:19:27 +02:00
return [ EncryptionMethod . SJCL , EncryptionMethod . SJCL1a , EncryptionMethod . SJCL1b , EncryptionMethod . SJCL2 , EncryptionMethod . SJCL3 , EncryptionMethod . SJCL4 ] . indexOf ( method ) >= 0 ;
2020-01-23 00:01:58 +02:00
}
2023-03-06 16:22:01 +02:00
public async itemIsEncrypted ( item : any ) {
2017-12-04 21:01:56 +02:00
if ( ! item ) throw new Error ( 'No item' ) ;
const ItemClass = BaseItem . itemClass ( item ) ;
if ( ! ItemClass . encryptionSupported ( ) ) return false ;
2021-06-20 17:29:35 +02:00
return item . encryption_applied && isValidHeaderIdentifier ( item . encryption_cipher_text , true ) ;
2017-12-04 21:01:56 +02:00
}
2023-03-06 16:22:01 +02:00
public async fileIsEncrypted ( path : string ) {
2017-12-04 21:01:56 +02:00
const handle = await this . fsDriver ( ) . open ( path , 'r' ) ;
const headerIdentifier = await this . fsDriver ( ) . readFileChunk ( handle , 5 , 'ascii' ) ;
await this . fsDriver ( ) . close ( handle ) ;
2021-06-20 17:29:35 +02:00
return isValidHeaderIdentifier ( headerIdentifier ) ;
2017-12-04 21:01:56 +02:00
}
2017-12-12 01:52:42 +02:00
}