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

Passphrase Support for e2e backups #786

Merged
merged 6 commits into from
Nov 21, 2018
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
4 changes: 2 additions & 2 deletions spec/unit/crypto/backup.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ describe("MegolmBackup", function() {
client._http.authedRequest = function() {
return Promise.resolve(KEY_BACKUP_DATA);
};
return client.restoreKeyBackups(
return client.restoreKeyBackupWithRecoveryKey(
"EsTc LW2K PGiF wKEA 3As5 g5c4 BXwk qeeJ ZJV8 Q9fu gUMN UE4d",
ROOM_ID,
SESSION_ID,
Expand All @@ -458,7 +458,7 @@ describe("MegolmBackup", function() {
},
});
};
return client.restoreKeyBackups(
return client.restoreKeyBackupWithRecoveryKey(
"EsTc LW2K PGiF wKEA 3As5 g5c4 BXwk qeeJ ZJV8 Q9fu gUMN UE4d",
).then(() => {
return megolmDecryption.decryptEvent(ENCRYPTED_EVENT);
Expand Down
63 changes: 45 additions & 18 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ import RoomList from './crypto/RoomList';
import Crypto from './crypto';
import { isCryptoAvailable } from './crypto';
import { encodeRecoveryKey, decodeRecoveryKey } from './crypto/recoverykey';
import { keyForNewBackup, keyForExistingBackup } from './crypto/backup_password';
import { randomString } from './randomstring';

// Disable warnings for now: we use deprecated bluebird functions
// and need to migrate, but they spam the console with warnings.
Expand Down Expand Up @@ -860,22 +862,36 @@ MatrixClient.prototype.disableKeyBackup = function() {
* Set up the data required to create a new backup version. The backup version
* will not be created and enabled until createKeyBackupVersion is called.
*
* @returns {object} Object that can be passed to createKeyBackupVersion and
* @param {string} password Passphrase string that can be entered by the user
* when restoring the backup as an alternative to entering the recovery key.
* Optional.
*
* @returns {Promise<object>} Object that can be passed to createKeyBackupVersion and
* additionally has a 'recovery_key' member with the user-facing recovery key string.
*/
MatrixClient.prototype.prepareKeyBackupVersion = function() {
MatrixClient.prototype.prepareKeyBackupVersion = async function(password) {
if (this._crypto === null) {
throw new Error("End-to-end encryption disabled");
}

const decryption = new global.Olm.PkDecryption();
try {
const publicKey = decryption.generate_key();
let publicKey;
const authData = {};
if (password) {
const keyInfo = await keyForNewBackup(password);
publicKey = decryption.init_with_private_key(keyInfo.key);
authData.private_key_salt = keyInfo.salt;
authData.private_key_iterations = keyInfo.iterations;
} else {
publicKey = decryption.generate_key();
}

authData.public_key = publicKey;

return {
algorithm: olmlib.MEGOLM_BACKUP_ALGORITHM,
auth_data: {
public_key: publicKey,
},
auth_data: authData,
recovery_key: encodeRecoveryKey(decryption.get_private_key()),
};
} finally {
Expand Down Expand Up @@ -992,8 +1008,28 @@ MatrixClient.prototype.isValidRecoveryKey = function(recoveryKey) {
}
};

MatrixClient.prototype.restoreKeyBackups = function(
MatrixClient.prototype.restoreKeyBackupWithPassword = async function(
password, targetRoomId, targetSessionId, version,
) {
const backupInfo = await this.getKeyBackupVersion();

const privKey = await keyForExistingBackup(backupInfo, password);
return this._restoreKeyBackup(
privKey, targetRoomId, targetSessionId, version,
);
};

MatrixClient.prototype.restoreKeyBackupWithRecoveryKey = function(
recoveryKey, targetRoomId, targetSessionId, version,
) {
const privKey = decodeRecoveryKey(recoveryKey);
return this._restoreKeyBackup(
privKey, targetRoomId, targetSessionId, version,
);
};

MatrixClient.prototype._restoreKeyBackup = function(
privKey, targetRoomId, targetSessionId, version,
) {
if (this._crypto === null) {
throw new Error("End-to-end encryption disabled");
Expand All @@ -1003,11 +1039,9 @@ MatrixClient.prototype.restoreKeyBackups = function(

const path = this._makeKeyBackupPath(targetRoomId, targetSessionId, version);

// FIXME: see the FIXME in createKeyBackupVersion
const privkey = decodeRecoveryKey(recoveryKey);
const decryption = new global.Olm.PkDecryption();
try {
decryption.init_with_private_key(privkey);
decryption.init_with_private_key(privKey);
} catch(e) {
decryption.free();
throw e;
Expand Down Expand Up @@ -3829,14 +3863,7 @@ MatrixClient.prototype.getEventMapper = function() {
* @return {string} A new client secret
*/
MatrixClient.prototype.generateClientSecret = function() {
let ret = "";
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (let i = 0; i < 32; i++) {
ret += chars.charAt(Math.floor(Math.random() * chars.length));
}

return ret;
return randomString(32);
};

/** */
Expand Down
81 changes: 81 additions & 0 deletions src/crypto/backup_password.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
Copyright 2018 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 { randomString } from '../randomstring';

const DEFAULT_ITERATIONS = 500000;

export async function keyForExistingBackup(backupData, password) {
if (!global.Olm) {
throw new Error("Olm is not available");
}

const authData = backupData.auth_data;

if (!authData.private_key_salt || !authData.private_key_iterations) {
throw new Error(
"Salt and/or iterations not found: " +
"this backup cannot be restored with a passphrase",
);
}

return await deriveKey(
password, backupData.auth_data.private_key_salt,
backupData.auth_data.private_key_iterations,
);
}

export async function keyForNewBackup(password) {
if (!global.Olm) {
throw new Error("Olm is not available");
}

const salt = randomString(32);

const key = await deriveKey(password, salt, DEFAULT_ITERATIONS);

return { key, salt, iterations: DEFAULT_ITERATIONS };
}

async function deriveKey(password, salt, iterations) {
const subtleCrypto = global.crypto.subtle;
const TextEncoder = global.TextEncoder;
if (!subtleCrypto || !TextEncoder) {
// TODO: Implement this for node
throw new Error("Password-based backup is not avaiable on this platform");
}

const key = await subtleCrypto.importKey(
'raw',
new TextEncoder().encode(password),
{name: 'PBKDF2'},
false,
['deriveBits'],
);

const keybits = await subtleCrypto.deriveBits(
{
name: 'PBKDF2',
salt: new TextEncoder().encode(salt),
iterations: iterations,
hash: 'SHA-512',
},
key,
global.Olm.PRIVATE_KEY_LENGTH * 8,
);

return new Uint8Array(keybits);
}
26 changes: 26 additions & 0 deletions src/randomstring.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
Copyright 2018 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.
*/

export function randomString(len) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fwiw there's libraries for this if we want to avoid maintaining this sort of thing. https://www.npmjs.com/package/random-string for example

let ret = "";
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (let i = 0; i < len; ++i) {
ret += chars.charAt(Math.floor(Math.random() * chars.length));
}

return ret;
}