2014-01-12 08:32:13 +01:00
|
|
|
//TODO: Stolen from MDN (copyright...)
|
|
|
|
function b64ToUint6 (nChr) {
|
|
|
|
|
|
|
|
return nChr > 64 && nChr < 91 ?
|
|
|
|
nChr - 65
|
|
|
|
: nChr > 96 && nChr < 123 ?
|
|
|
|
nChr - 71
|
|
|
|
: nChr > 47 && nChr < 58 ?
|
|
|
|
nChr + 4
|
|
|
|
: nChr === 43 ?
|
|
|
|
62
|
|
|
|
: nChr === 47 ?
|
|
|
|
63
|
|
|
|
:
|
|
|
|
0;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
function base64DecToArr (sBase64, nBlocksSize) {
|
|
|
|
var
|
|
|
|
sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
|
2014-01-22 07:23:41 +01:00
|
|
|
nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2;
|
|
|
|
var aBBytes = new ArrayBuffer(nOutLen);
|
|
|
|
var taBytes = new Uint8Array(aBBytes);
|
2014-01-12 08:32:13 +01:00
|
|
|
|
|
|
|
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
|
|
|
|
nMod4 = nInIdx & 3;
|
|
|
|
nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
|
|
|
|
if (nMod4 === 3 || nInLen - nInIdx === 1) {
|
|
|
|
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
|
|
|
|
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
|
|
|
|
}
|
|
|
|
nUint24 = 0;
|
|
|
|
}
|
|
|
|
}
|
2014-01-22 07:23:41 +01:00
|
|
|
return aBBytes;
|
2014-01-12 08:32:13 +01:00
|
|
|
}
|
|
|
|
|
2014-03-05 02:31:15 +01:00
|
|
|
/* Base64 string to array encoding */
|
|
|
|
|
|
|
|
function uint6ToB64 (nUint6) {
|
|
|
|
|
|
|
|
return nUint6 < 26 ?
|
|
|
|
nUint6 + 65
|
|
|
|
: nUint6 < 52 ?
|
|
|
|
nUint6 + 71
|
|
|
|
: nUint6 < 62 ?
|
|
|
|
nUint6 - 4
|
|
|
|
: nUint6 === 62 ?
|
|
|
|
43
|
|
|
|
: nUint6 === 63 ?
|
|
|
|
47
|
|
|
|
:
|
|
|
|
65;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
function base64EncArr (aBytes) {
|
|
|
|
|
|
|
|
var nMod3, sB64Enc = "";
|
|
|
|
|
|
|
|
for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
|
|
|
|
nMod3 = nIdx % 3;
|
|
|
|
//if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
|
|
|
|
nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
|
|
|
|
if (nMod3 === 2 || aBytes.length - nIdx === 1) {
|
|
|
|
sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));
|
|
|
|
nUint24 = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sB64Enc.replace(/A(?=A$|$)/g, "=");
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2014-01-12 08:32:13 +01:00
|
|
|
/*********************************
|
|
|
|
*** Type conversion utilities ***
|
|
|
|
*********************************/
|
2014-01-15 08:46:05 +01:00
|
|
|
// Strings/arrays
|
2014-03-06 22:44:59 +01:00
|
|
|
//TODO: Throw all this shit in favor of consistent types
|
2014-01-12 15:07:13 +01:00
|
|
|
var StaticByteBufferProto = new dcodeIO.ByteBuffer().__proto__;
|
2014-01-22 07:23:41 +01:00
|
|
|
var StaticArrayBufferProto = new ArrayBuffer().__proto__;
|
2014-03-06 19:18:11 +01:00
|
|
|
var StaticUint8ArrayProto = new Uint8Array().__proto__;
|
|
|
|
var StaticWordArrayProto = CryptoJS.lib.WordArray.create('').__proto__;
|
2014-01-12 08:32:13 +01:00
|
|
|
function getString(thing) {
|
2014-03-06 19:18:11 +01:00
|
|
|
if (thing === Object(thing)) {
|
|
|
|
if (thing.__proto__ == StaticUint8ArrayProto)
|
|
|
|
return String.fromCharCode.apply(null, thing);
|
|
|
|
if (thing.__proto__ == StaticArrayBufferProto)
|
|
|
|
return getString(new Uint8Array(thing));
|
|
|
|
if (thing.__proto__ == StaticByteBufferProto)
|
|
|
|
return thing.toString("binary");
|
|
|
|
if (thing.__proto__ == StaticWordArrayProto)
|
|
|
|
return thing.toString(CryptoJS.enc.Latin1);
|
|
|
|
}
|
2014-01-12 08:32:13 +01:00
|
|
|
return thing;
|
|
|
|
}
|
|
|
|
|
2014-03-05 02:31:15 +01:00
|
|
|
function getStringable(thing) {
|
|
|
|
return (typeof thing == "string" || typeof thing == "number" ||
|
2014-03-06 19:18:11 +01:00
|
|
|
(thing === Object(thing) &&
|
|
|
|
(thing.__proto__ == StaticArrayBufferProto ||
|
|
|
|
thing.__proto__ == StaticUint8ArrayProto ||
|
|
|
|
thing.__proto__ == StaticByteBufferProto ||
|
|
|
|
thing.__proto__ == StaticWordArrayProto)));
|
2014-03-05 02:31:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function toArrayBuffer(thing) {
|
2014-03-06 19:18:11 +01:00
|
|
|
//TODO: Optimize this for specific cases
|
2014-03-05 02:31:15 +01:00
|
|
|
if (thing === undefined)
|
|
|
|
return undefined;
|
2014-03-06 22:44:59 +01:00
|
|
|
if (thing === Object(thing) && thing.__proto__ == StaticArrayBufferProto)
|
|
|
|
return thing;
|
2014-03-05 02:31:15 +01:00
|
|
|
if (!getStringable(thing))
|
|
|
|
throw "Tried to convert a non-stringable thing of type " + typeof thing + " to an array buffer";
|
|
|
|
var str = getString(thing);
|
|
|
|
var res = new ArrayBuffer(str.length);
|
|
|
|
var uint = new Uint8Array(res);
|
|
|
|
for (var i = 0; i < str.length; i++)
|
|
|
|
uint[i] = str.charCodeAt(i);
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
function ensureStringed(thing) {
|
|
|
|
if (getStringable(thing))
|
|
|
|
return getString(thing);
|
|
|
|
else if (thing instanceof Array) {
|
|
|
|
var res = [];
|
|
|
|
for (var i = 0; i < thing.length; i++)
|
|
|
|
res[i] = ensureStringed(thing);
|
|
|
|
return res;
|
|
|
|
} else if (thing === Object(thing)) {
|
|
|
|
var res = {};
|
|
|
|
for (key in thing)
|
|
|
|
res[key] = ensureStringed(thing[key]);
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
throw "unsure of how to jsonify object of type " + typeof thing;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
function jsonThing(thing) {
|
|
|
|
return JSON.stringify(ensureStringed(thing));
|
|
|
|
}
|
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
function getArrayBuffer(string) {
|
2014-01-12 08:32:13 +01:00
|
|
|
return base64DecToArr(btoa(string));
|
|
|
|
}
|
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
function base64ToArrayBuffer(string) {
|
2014-01-12 08:32:13 +01:00
|
|
|
return base64DecToArr(string);
|
|
|
|
}
|
|
|
|
|
2014-01-15 08:46:05 +01:00
|
|
|
// Protobuf decodingA
|
|
|
|
//TODO: throw on missing fields everywhere
|
2014-01-22 04:28:35 +01:00
|
|
|
var IncomingPushMessageProtobuf = dcodeIO.ProtoBuf.loadProtoFile("protos/IncomingPushMessageSignal.proto").build("textsecure.IncomingPushMessageSignal");
|
2014-01-15 08:46:05 +01:00
|
|
|
function decodeIncomingPushMessageProtobuf(string) {
|
|
|
|
return IncomingPushMessageProtobuf.decode(btoa(string));
|
|
|
|
}
|
|
|
|
|
2014-01-22 04:28:35 +01:00
|
|
|
var PushMessageContentProtobuf = dcodeIO.ProtoBuf.loadProtoFile("protos/IncomingPushMessageSignal.proto").build("textsecure.PushMessageContent");
|
2014-01-17 07:08:33 +01:00
|
|
|
function decodePushMessageContentProtobuf(string) {
|
2014-01-15 08:46:05 +01:00
|
|
|
return PushMessageContentProtobuf.decode(btoa(string));
|
|
|
|
}
|
|
|
|
|
2014-01-22 04:28:35 +01:00
|
|
|
var WhisperMessageProtobuf = dcodeIO.ProtoBuf.loadProtoFile("protos/WhisperTextProtocol.proto").build("textsecure.WhisperMessage");
|
2014-01-15 08:46:05 +01:00
|
|
|
function decodeWhisperMessageProtobuf(string) {
|
|
|
|
return WhisperMessageProtobuf.decode(btoa(string));
|
|
|
|
}
|
|
|
|
|
2014-01-22 04:28:35 +01:00
|
|
|
var PreKeyWhisperMessageProtobuf = dcodeIO.ProtoBuf.loadProtoFile("protos/WhisperTextProtocol.proto").build("textsecure.PreKeyWhisperMessage");
|
2014-01-15 08:46:05 +01:00
|
|
|
function decodePreKeyWhisperMessageProtobuf(string) {
|
|
|
|
return PreKeyWhisperMessageProtobuf.decode(btoa(string));
|
|
|
|
}
|
|
|
|
|
2014-01-22 04:28:35 +01:00
|
|
|
var KeyExchangeMessageProtobuf = dcodeIO.ProtoBuf.loadProtoFile("protos/WhisperTextProtocol.proto").build("textsecure.KeyExchangeMessage");
|
2014-01-15 08:46:05 +01:00
|
|
|
function decodeKeyExchangeMessageProtobuf(string) {
|
|
|
|
return KeyExchangeMessageProtobuf.decode(btoa(string));
|
2014-01-12 08:32:13 +01:00
|
|
|
}
|
|
|
|
|
2014-01-15 08:46:05 +01:00
|
|
|
// Number formatting
|
2014-01-12 08:32:13 +01:00
|
|
|
function getNumberFromString(string) {
|
|
|
|
return string.split(".")[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
function getEncodedNumber(number) {
|
|
|
|
var split = number.split(".");
|
|
|
|
if (split.length > 1) {
|
|
|
|
if (split[1] == 1)
|
|
|
|
return split[0];
|
|
|
|
else
|
|
|
|
return number;
|
|
|
|
} else
|
|
|
|
return number;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getDeviceId(encodedNumber) {
|
|
|
|
var split = encodedNumber.split(".");
|
|
|
|
if (split.length > 1)
|
|
|
|
return split[1];
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2014-01-15 08:46:05 +01:00
|
|
|
// Other
|
|
|
|
|
2014-01-12 15:42:05 +01:00
|
|
|
function timestampToHumanReadable(timestamp) {
|
|
|
|
var date = new Date();
|
|
|
|
date.setTime(timestamp*1000);
|
|
|
|
return date.toUTCString();
|
|
|
|
}
|
|
|
|
|
2014-01-15 08:46:05 +01:00
|
|
|
function objectContainsKeys(object) {
|
|
|
|
var count = 0;
|
|
|
|
for (key in object) {
|
|
|
|
count++;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
return count != 0;
|
|
|
|
}
|
|
|
|
|
2014-01-10 08:48:05 +01:00
|
|
|
/************************************************
|
|
|
|
*** Utilities to store data in local storage ***
|
|
|
|
************************************************/
|
2014-01-17 07:08:33 +01:00
|
|
|
var storage = {};
|
|
|
|
|
2014-01-10 08:48:05 +01:00
|
|
|
storage.putEncrypted = function(key, value) {
|
|
|
|
//TODO
|
2014-01-12 15:07:13 +01:00
|
|
|
if (value === undefined)
|
|
|
|
throw "Tried to store undefined";
|
2014-03-05 02:31:15 +01:00
|
|
|
localStorage.setItem("e" + key, jsonThing(value));
|
2014-01-10 08:48:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
storage.getEncrypted = function(key, defaultValue) {
|
|
|
|
//TODO
|
|
|
|
var value = localStorage.getItem("e" + key);
|
|
|
|
if (value === null)
|
|
|
|
return defaultValue;
|
2014-01-12 09:49:46 +01:00
|
|
|
return JSON.parse(value);
|
2014-01-10 08:48:05 +01:00
|
|
|
}
|
|
|
|
|
2014-01-15 08:46:05 +01:00
|
|
|
storage.removeEncrypted = function(key) {
|
|
|
|
//TODO
|
|
|
|
}
|
|
|
|
|
2014-01-10 08:48:05 +01:00
|
|
|
storage.putUnencrypted = function(key, value) {
|
2014-01-12 15:07:13 +01:00
|
|
|
if (value === undefined)
|
|
|
|
throw "Tried to store undefined";
|
2014-03-05 02:31:15 +01:00
|
|
|
localStorage.setItem("u" + key, jsonThing(value));
|
2014-01-10 08:48:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
storage.getUnencrypted = function(key, defaultValue) {
|
|
|
|
var value = localStorage.getItem("u" + key);
|
|
|
|
if (value === null)
|
|
|
|
return defaultValue;
|
2014-01-12 09:49:46 +01:00
|
|
|
return JSON.parse(value);
|
2014-01-10 08:48:05 +01:00
|
|
|
}
|
|
|
|
|
2014-01-15 08:46:05 +01:00
|
|
|
storage.removeUnencrypted = function(key) {
|
|
|
|
//TODO
|
|
|
|
}
|
|
|
|
|
2014-01-12 15:07:13 +01:00
|
|
|
function registrationDone() {
|
|
|
|
storage.putUnencrypted("registration_done", "");
|
2014-01-17 07:08:33 +01:00
|
|
|
//TODO: Fix dirty hack:
|
|
|
|
chrome.runtime.reload();
|
2014-01-12 15:07:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function isRegistrationDone() {
|
|
|
|
return storage.getUnencrypted("registration_done") !== undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getMessageMap() {
|
|
|
|
return storage.getEncrypted("messageMap", {});
|
|
|
|
}
|
|
|
|
|
|
|
|
function storeMessage(outgoingMessageSignal) {
|
|
|
|
var messageMap = getMessageMap();
|
|
|
|
var conversation = messageMap[outgoingMessageSignal.source]; //TODO: Also support Group message IDs here
|
|
|
|
if (conversation === undefined) {
|
|
|
|
conversation = []
|
|
|
|
messageMap[outgoingMessageSignal.source] = conversation;
|
|
|
|
}
|
2014-01-12 15:07:30 +01:00
|
|
|
|
2014-01-12 15:07:13 +01:00
|
|
|
conversation[conversation.length] = { message: getString(outgoingMessageSignal.message),
|
|
|
|
destinations: outgoingMessageSignal.destinations,
|
|
|
|
sender: outgoingMessageSignal.source,
|
|
|
|
timestamp: outgoingMessageSignal.timestamp.div(dcodeIO.Long.fromNumber(1000)).toNumber() };
|
|
|
|
storage.putEncrypted("messageMap", messageMap);
|
|
|
|
chrome.runtime.sendMessage(conversation[conversation.length - 1]);
|
|
|
|
}
|
|
|
|
|
2014-01-13 02:52:58 +01:00
|
|
|
function getDeviceObject(encodedNumber) {
|
|
|
|
return storage.getEncrypted("deviceObject" + getEncodedNumber(encodedNumber));
|
|
|
|
}
|
|
|
|
|
|
|
|
function getDeviceIdListFromNumber(number) {
|
|
|
|
return storage.getEncrypted("deviceIdList" + getNumberFromString(number), []);
|
|
|
|
}
|
|
|
|
|
|
|
|
function addDeviceIdForNumber(number, deviceId) {
|
|
|
|
var deviceIdList = getDeviceIdListFromNumber(getNumberFromString(number));
|
|
|
|
for (var i = 0; i < deviceIdList.length; i++) {
|
|
|
|
if (deviceIdList[i] == deviceId)
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
deviceIdList[deviceIdList.length] = deviceId;
|
|
|
|
storage.putEncrypted("deviceIdList" + getNumberFromString(number), deviceIdList);
|
|
|
|
}
|
|
|
|
|
|
|
|
// throws "Identity key mismatch"
|
|
|
|
function saveDeviceObject(deviceObject) {
|
|
|
|
var existing = getDeviceObject(deviceObject.encodedNumber);
|
|
|
|
if (existing === undefined)
|
|
|
|
existing = {encodedNumber: getEncodedNumber(deviceObject.encodedNumber)};
|
|
|
|
for (key in deviceObject) {
|
|
|
|
if (key == "encodedNumber")
|
|
|
|
continue;
|
|
|
|
|
|
|
|
if (key == "identityKey" && deviceObject.identityKey != deviceObject.identityKey)
|
|
|
|
throw "Identity key mismatch";
|
|
|
|
|
|
|
|
existing[key] = deviceObject[key];
|
|
|
|
}
|
|
|
|
storage.putEncrypted("deviceObject" + getEncodedNumber(deviceObject.encodedNumber), existing);
|
|
|
|
addDeviceIdForNumber(deviceObject.encodedNumber, getDeviceId(deviceObject.encodedNumber));
|
|
|
|
}
|
|
|
|
|
|
|
|
function getDeviceObjectListFromNumber(number) {
|
|
|
|
var deviceObjectList = [];
|
|
|
|
var deviceIdList = getDeviceIdListFromNumber(number);
|
|
|
|
for (var i = 0; i < deviceIdList.length; i++)
|
|
|
|
deviceObjectList[deviceObjectList.length] = getDeviceObject(getNumberFromString(number) + "." + deviceIdList[i]);
|
|
|
|
return deviceObjectList;
|
|
|
|
}
|
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
/**********************
|
|
|
|
*** NaCL Interface ***
|
|
|
|
**********************/
|
|
|
|
var onLoadCallbacks = [];
|
|
|
|
var naclLoaded = 0;
|
|
|
|
function registerOnLoadFunction(func) {
|
|
|
|
if (naclLoaded)
|
|
|
|
func();
|
|
|
|
onLoadCallbacks[onLoadCallbacks.length] = func;
|
|
|
|
}
|
|
|
|
|
|
|
|
var naclMessageNextId = 0;
|
|
|
|
var naclMessageIdCallbackMap = {};
|
|
|
|
function moduleDidLoad() {
|
|
|
|
common.hideModule();
|
|
|
|
naclLoaded = 1;
|
|
|
|
for (var i = 0; i < onLoadCallbacks.length; i++)
|
|
|
|
onLoadCallbacks[i]();
|
|
|
|
onLoadCallbacks = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
function handleMessage(message) {
|
|
|
|
naclMessageIdCallbackMap[message.data.call_id](message.data);
|
|
|
|
}
|
|
|
|
|
|
|
|
function postNaclMessage(message, callback) {
|
|
|
|
naclMessageIdCallbackMap[naclMessageNextId] = callback;
|
2014-03-05 02:31:15 +01:00
|
|
|
var pass = { command: message.command };
|
|
|
|
pass.call_id = naclMessageNextId++;
|
|
|
|
if (message["priv"] !== undefined) {
|
|
|
|
pass.priv = toArrayBuffer(message.priv);
|
|
|
|
if (pass.priv.byteLength != 32)
|
|
|
|
throw "Invalid NACL Message";
|
|
|
|
}
|
|
|
|
if (message["pub"] !== undefined) {
|
|
|
|
var pub = toArrayBuffer(message.pub);
|
|
|
|
var pubView = new Uint8Array(pub);
|
|
|
|
if (pub.byteLength == 33 && pubView[0] == 5) {
|
|
|
|
pass.pub = new ArrayBuffer(32);
|
|
|
|
var pubCopy = new Uint8Array(pass.pub);
|
|
|
|
for (var i = 0; i < 32; i++)
|
|
|
|
pubCopy[i] = pubView[i+1];
|
|
|
|
} else if (pub.byteLength == 32)
|
|
|
|
pass.pub = pub;
|
|
|
|
else
|
|
|
|
throw "Invalid NACL Message";
|
|
|
|
}
|
|
|
|
common.naclModule.postMessage(pass);
|
2014-01-22 07:23:41 +01:00
|
|
|
}
|
|
|
|
|
2014-01-12 08:32:13 +01:00
|
|
|
/*******************************************
|
|
|
|
*** Utilities to manage keys/randomness ***
|
|
|
|
*******************************************/
|
|
|
|
function getRandomBytes(size) {
|
|
|
|
//TODO: Better random (https://www.grc.com/r&d/js.htm?)
|
|
|
|
try {
|
2014-01-22 07:23:41 +01:00
|
|
|
var buffer = new ArrayBuffer(size);
|
|
|
|
var array = new Uint8Array(buffer);
|
2014-01-12 08:32:13 +01:00
|
|
|
window.crypto.getRandomValues(array);
|
2014-01-22 07:23:41 +01:00
|
|
|
return buffer;
|
2014-01-12 08:32:13 +01:00
|
|
|
} catch (err) {
|
|
|
|
//TODO: ummm...wat?
|
2014-01-15 08:46:05 +01:00
|
|
|
throw err;
|
2014-01-12 08:32:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-06 22:44:59 +01:00
|
|
|
var crypto_tests = {};
|
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
(function(crypto, $, undefined) {
|
2014-01-22 07:23:41 +01:00
|
|
|
var createNewKeyPair = function(callback) {
|
2014-01-22 04:28:35 +01:00
|
|
|
var privKey = getRandomBytes(32);
|
2014-01-22 07:23:41 +01:00
|
|
|
postNaclMessage({command: "bytesToPriv", priv: privKey}, function(message) {
|
|
|
|
postNaclMessage({command: "privToPub", priv: message.res}, function(message) {
|
2014-03-05 02:31:15 +01:00
|
|
|
var origPub = new Uint8Array(message.res);
|
|
|
|
var pub = new ArrayBuffer(33);
|
|
|
|
var pubWithPrefix = new Uint8Array(pub);
|
|
|
|
for (var i = 0; i < 32; i++)
|
|
|
|
pubWithPrefix[i+1] = origPub[i];
|
|
|
|
pubWithPrefix[0] = 5;
|
2014-01-22 07:23:41 +01:00
|
|
|
callback({ pubKey: message.res, privKey: privKey });
|
|
|
|
});
|
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var crypto_storage = {};
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
crypto_storage.getNewPubKeySTORINGPrivKey = function(keyName, callback) {
|
|
|
|
createNewKeyPair(function(keyPair) {
|
|
|
|
storage.putEncrypted("25519Key" + keyName, keyPair);
|
|
|
|
callback(keyPair.pubKey);
|
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto_storage.getStoredPubKey = function(keyName) {
|
2014-03-05 02:31:15 +01:00
|
|
|
return toArrayBuffer(storage.getEncrypted("25519Key" + keyName, { pubKey: undefined }).pubKey);
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto_storage.getStoredKeyPair = function(keyName) {
|
2014-03-05 02:31:15 +01:00
|
|
|
var res = storage.getEncrypted("25519Key" + keyName);
|
|
|
|
if (res === undefined)
|
|
|
|
return undefined;
|
|
|
|
return { pubKey: toArrayBuffer(res.pubKey), privKey: toArrayBuffer(res.privKey) };
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto_storage.getAndRemoveStoredKeyPair = function(keyName) {
|
|
|
|
var keyPair = this.getStoredKeyPair(keyName);
|
|
|
|
storage.removeEncrypted("25519Key" + keyName);
|
|
|
|
return keyPair;
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto_storage.getAndRemovePreKeyPair = function(keyId) {
|
|
|
|
return this.getAndRemoveStoredKeyPair("preKey" + keyId);
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto_storage.getIdentityPrivKey = function() {
|
|
|
|
return this.getStoredKeyPair("identityKey").privKey;
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto_storage.saveSession = function(encodedNumber, session) {
|
|
|
|
storage.putEncrypted("session" + getEncodedNumber(encodedNumber), session);
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto_storage.getSession = function(encodedNumber) {
|
|
|
|
return storage.getEncrypted("session" + getEncodedNumber(encodedNumber));
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
/*****************************
|
|
|
|
*** Internal Crypto stuff ***
|
|
|
|
*****************************/
|
2014-03-06 19:18:11 +01:00
|
|
|
//TODO: Think about replacing CryptoJS stuff with optional NaCL-based implementations
|
|
|
|
// Probably means all of the low-level crypto stuff here needs pulled out into its own file
|
2014-01-22 08:37:14 +01:00
|
|
|
var ECDHE = function(pubKey, privKey, callback) {
|
|
|
|
postNaclMessage({command: "ECDHE", priv: privKey, pub: pubKey}, function(message) {
|
|
|
|
callback(message.res);
|
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-03-06 19:18:11 +01:00
|
|
|
var HMACSHA256 = function(input, key) {
|
2014-03-06 22:44:59 +01:00
|
|
|
//TODO: Waaayyyy less type conversion here (probably just means replacing CryptoJS)
|
2014-03-06 19:18:11 +01:00
|
|
|
return CryptoJS.HmacSHA256(
|
2014-03-06 20:01:23 +01:00
|
|
|
CryptoJS.lib.WordArray.create(toArrayBuffer(input)),
|
|
|
|
CryptoJS.enc.Latin1.parse(getString(key)))
|
|
|
|
.toString(CryptoJS.enc.Latin1);
|
2014-03-06 19:18:11 +01:00
|
|
|
}
|
|
|
|
|
2014-03-06 22:44:59 +01:00
|
|
|
crypto_tests.HKDF = function(input, salt, info) {
|
|
|
|
// Specific implementation of RFC 5869 that only returns exactly 64 bytes
|
|
|
|
var PRK = HMACSHA256(input, salt);
|
|
|
|
|
|
|
|
var infoString = getString(info);
|
2014-03-08 05:13:53 +01:00
|
|
|
// TextSecure implements a slightly tweaked version of RFC 5869: the 0 and 1 should be 1 and 2 here
|
|
|
|
var T1 = HMACSHA256(infoString + String.fromCharCode(0), PRK);
|
|
|
|
var T2 = HMACSHA256(getString(T1) + infoString + String.fromCharCode(1), PRK);
|
2014-03-06 22:44:59 +01:00
|
|
|
|
|
|
|
return [ T1, T2 ];
|
|
|
|
}
|
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var HKDF = function(input, salt, info) {
|
2014-03-06 22:44:59 +01:00
|
|
|
// HKDF for TextSecure has a bit of additional handling - salts always end up being 32 bytes
|
2014-03-06 19:18:11 +01:00
|
|
|
if (salt == '') {
|
2014-03-06 22:44:59 +01:00
|
|
|
salt = new ArrayBuffer(32);
|
|
|
|
var uintKey = new Uint8Array(salt);
|
2014-03-06 19:18:11 +01:00
|
|
|
for (var i = 0; i < 32; i++)
|
|
|
|
uintKey[i] = 0;
|
2014-03-06 22:44:59 +01:00
|
|
|
}
|
2014-03-06 19:18:11 +01:00
|
|
|
|
2014-03-06 22:44:59 +01:00
|
|
|
salt = toArrayBuffer(salt);
|
|
|
|
|
|
|
|
if (salt.byteLength != 32)
|
2014-03-06 19:18:11 +01:00
|
|
|
throw "Got salt of incorrect length";
|
|
|
|
|
2014-03-06 22:44:59 +01:00
|
|
|
return crypto_tests.HKDF(input, salt, info);
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
|
|
|
|
2014-03-06 20:01:23 +01:00
|
|
|
var decryptPaddedAES = function(ciphertext, key, iv) {
|
2014-03-06 19:18:11 +01:00
|
|
|
//TODO: Waaayyyy less type conversion here (probably just means replacing CryptoJS)
|
2014-03-08 05:13:53 +01:00
|
|
|
return CryptoJS.AES.decrypt(btoa(getString(ciphertext)),
|
2014-03-06 19:18:11 +01:00
|
|
|
CryptoJS.enc.Latin1.parse(getString(key)),
|
|
|
|
{iv: CryptoJS.enc.Latin1.parse(getString(iv))})
|
2014-03-08 05:13:53 +01:00
|
|
|
.toString(CryptoJS.enc.Latin1);
|
2014-03-06 19:18:11 +01:00
|
|
|
}
|
|
|
|
|
2014-03-08 05:13:53 +01:00
|
|
|
var decryptAESCTR = function(ciphertext, key, counter) {
|
|
|
|
return CryptoJS.AES.decrypt(btoa(getString(ciphertext)),
|
|
|
|
CryptoJS.enc.Latin1.parse(getString(key)),
|
|
|
|
{mode: CryptoJS.mode.CTR, iv: CryptoJS.enc.Latin1.parse(""), padding: CryptoJS.pad.NoPadding})
|
|
|
|
.toString(CryptoJS.enc.Latin1);
|
|
|
|
}
|
|
|
|
|
|
|
|
var verifyMACWithVersionByte = function(data, key, mac, version) {
|
|
|
|
if (version === undefined)
|
|
|
|
version = 1;
|
|
|
|
|
|
|
|
var calculated_mac = HMACSHA256(String.fromCharCode(version) + getString(data), key);
|
2014-03-06 20:01:23 +01:00
|
|
|
var macString = getString(mac);
|
|
|
|
|
|
|
|
if (calculated_mac.substring(0, macString.length) != macString)
|
|
|
|
throw "Bad MAC";
|
|
|
|
}
|
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
/******************************
|
|
|
|
*** Ratchet implementation ***
|
|
|
|
******************************/
|
2014-01-22 08:37:14 +01:00
|
|
|
var initSession = function(isInitiator, theirIdentityPubKey, ourEphemeralPrivKey, theirEphemeralPubKey, callback) {
|
2014-01-17 07:08:33 +01:00
|
|
|
var ourIdentityPrivKey = crypto_storage.getIdentityPrivKey();
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 08:37:14 +01:00
|
|
|
var sharedSecret;
|
|
|
|
ECDHE(theirEphemeralPubKey, ourIdentityPrivKey, function(ecRes) {
|
2014-03-06 22:44:59 +01:00
|
|
|
sharedSecret = getString(ecRes);
|
2014-01-22 08:37:14 +01:00
|
|
|
|
|
|
|
function finishInit() {
|
|
|
|
ECDHE(theirEphemeralPubKey, ourEphemeralPrivKey, function(ecRes) {
|
2014-03-06 22:44:59 +01:00
|
|
|
sharedSecret += getString(ecRes);
|
2014-01-22 08:37:14 +01:00
|
|
|
|
|
|
|
var masterKey = HKDF(sharedSecret, '', "WhisperText");
|
|
|
|
callback({ rootKey: masterKey[0], chainKey: masterKey[1] });
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isInitiator) {
|
|
|
|
ECDHE(theirIdentityPubKey, ourEphemeralPrivKey, function(ecRes) {
|
2014-03-06 22:44:59 +01:00
|
|
|
sharedSecret = sharedSecret + getString(ecRes);
|
2014-01-22 08:37:14 +01:00
|
|
|
finishInit();
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
ECDHE(theirIdentityPubKey, ourEphemeralPrivKey, function(ecRes) {
|
2014-03-06 22:44:59 +01:00
|
|
|
sharedSecret = getString(ecRes) + sharedSecret;
|
2014-01-22 08:37:14 +01:00
|
|
|
finishInit();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 08:37:14 +01:00
|
|
|
var initSessionFromPreKeyWhisperMessage = function(encodedNumber, message, callback) {
|
2014-01-17 07:08:33 +01:00
|
|
|
//TODO: Check remote identity key matches known-good key
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-03-05 02:31:15 +01:00
|
|
|
var preKeyPair = crypto_storage.getAndRemovePreKeyPair(message.preKeyId);
|
2014-01-17 07:08:33 +01:00
|
|
|
if (preKeyPair === undefined)
|
|
|
|
throw "Missing preKey for PreKeyWhisperMessage";
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 08:37:14 +01:00
|
|
|
initSession(false, message.identityKey, preKeyPair.privKey, message.baseKey, function(firstRatchet) {
|
|
|
|
var session = {currentRatchet: { rootKey: firstRatchet.rootKey, ephemeralKeyPair: preKeyPair,
|
|
|
|
lastRemoteEphemeralKey: message.baseKey },
|
|
|
|
oldRatchetList: []
|
|
|
|
};
|
2014-03-06 05:17:09 +01:00
|
|
|
session[getString(preKeyPair.pubKey)] = { messageKeys: {}, chainKey: { counter: -1, key: firstRatchet.chainKey } };
|
|
|
|
// This isnt an actual ratchet, its just here to make maybeStepRatchet work
|
|
|
|
session[getString(message.baseKey)] = { messageKeys: {}, chainKey: { counter: 0xffffffff, key: '' } };
|
2014-03-05 02:31:15 +01:00
|
|
|
crypto_storage.saveSession(encodedNumber, session);
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 08:37:14 +01:00
|
|
|
callback();
|
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var fillMessageKeys = function(chain, counter) {
|
|
|
|
var messageKeys = chain.messageKeys;
|
|
|
|
var key = chain.chainKey.key;
|
|
|
|
for (var i = chain.chainKey.counter; i < counter; i++) {
|
2014-03-08 05:13:53 +01:00
|
|
|
messageKeys[i + 1] = HMACSHA256(String.fromCharCode(1), key);
|
|
|
|
key = HMACSHA256(String.fromCharCode(2), key);
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
|
|
|
chain.chainKey.key = key;
|
|
|
|
chain.chainKey.counter = counter;
|
2014-01-15 08:46:05 +01:00
|
|
|
}
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
var maybeStepRatchet = function(session, remoteKey, previousCounter, callback) {
|
2014-03-05 02:31:15 +01:00
|
|
|
if (session[getString(remoteKey)] !== undefined) //TODO: null???
|
2014-01-17 07:08:33 +01:00
|
|
|
return;
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var ratchet = session.currentRatchet;
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-03-05 02:31:15 +01:00
|
|
|
var previousRatchet = session[getString(ratchet.lastRemoteEphemeralKey)];
|
2014-01-17 07:08:33 +01:00
|
|
|
fillMessageKeys(previousRatchet, previousCounter);
|
|
|
|
if (!objectContainsKeys(previousRatchet.messageKeys))
|
2014-03-05 02:31:15 +01:00
|
|
|
delete session[getString(ratchet.lastRemoteEphemeralKey)];
|
2014-01-17 07:08:33 +01:00
|
|
|
else
|
|
|
|
session.oldRatchetList[session.oldRatchetList.length] = { added: new Date().getTime(), ephemeralKey: ratchet.lastRemoteEphemeralKey };
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
delete session[ratchet.ephemeralKeyPair.pubKey];
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 08:37:14 +01:00
|
|
|
ECDHE(remoteKey, ratchet.ephemeralKeyPair.privKey, function(sharedSecret) {
|
|
|
|
var masterKey = HKDF(sharedSecret, ratchet.rootKey, "WhisperRatchet");
|
2014-03-06 05:17:09 +01:00
|
|
|
session[getString(remoteKey)] = { messageKeys: {}, chainKey: { counter: -1, key: masterKey[1] } };
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 08:37:14 +01:00
|
|
|
createNewKeyPair(function(keyPair) {
|
|
|
|
ratchet.ephemeralKeyPair = keyPair;
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-03-06 05:17:09 +01:00
|
|
|
ECDHE(remoteKey, ratchet.ephemeralKeyPair.privKey, function(sharedSecret) {
|
|
|
|
masterKey = HKDF(sharedSecret, masterKey[0], "WhisperRatchet");
|
|
|
|
ratchet.rootKey = masterKey[0];
|
|
|
|
session[getString(ratchet.ephemeralKeyPair.pubKey)] = { messageKeys: {}, chainKey: { counter: -1, key: masterKey[1] } };
|
2014-01-22 07:23:41 +01:00
|
|
|
|
2014-03-06 05:17:09 +01:00
|
|
|
ratchet.lastRemoteEphemeralKey = remoteKey;
|
|
|
|
callback();
|
|
|
|
});
|
2014-01-22 08:37:14 +01:00
|
|
|
});
|
2014-01-22 07:23:41 +01:00
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var doDecryptWhisperMessage = function(ciphertext, mac, messageKey, counter) {
|
|
|
|
//TODO keys swapped?
|
2014-03-06 19:18:11 +01:00
|
|
|
var keys = HKDF(messageKey, '', "WhisperMessageKeys");
|
2014-01-17 07:08:33 +01:00
|
|
|
verifyMACWithVersionByte(ciphertext, keys[0], mac);
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
return AES_CTR_NOPADDING(keys[1], CTR = counter, ciphertext);
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
// returns decrypted protobuf
|
2014-01-22 07:23:41 +01:00
|
|
|
var decryptWhisperMessage = function(encodedNumber, messageBytes, callback) {
|
2014-01-17 07:08:33 +01:00
|
|
|
var session = crypto_storage.getSession(encodedNumber);
|
|
|
|
if (session === undefined)
|
|
|
|
throw "No session currently open with " + encodedNumber;
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-03-05 02:31:15 +01:00
|
|
|
if (messageBytes[0] != String.fromCharCode((2 << 4) | 2))
|
2014-01-17 07:08:33 +01:00
|
|
|
throw "Bad version number on WhisperMessage";
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var messageProto = messageBytes.substring(1, messageBytes.length - 8);
|
|
|
|
var mac = messageBytes.substring(messageBytes.length - 8, messageBytes.length);
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var message = decodeWhisperMessageProtobuf(messageProto);
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-03-06 22:44:59 +01:00
|
|
|
maybeStepRatchet(session, message.ephemeralKey, message.previousCounter, function() {
|
2014-01-22 07:23:41 +01:00
|
|
|
var chain = session[getString(message.ephemeralKey)];
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
fillMessageKeys(chain, message.counter);
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-03-08 05:13:53 +01:00
|
|
|
var keys = HKDF(chain.messageKeys[message.counter], '', "WhisperMessageKeys");
|
|
|
|
verifyMACWithVersionByte(messageProto, keys[1], mac, (2 << 4) | 2);
|
|
|
|
|
|
|
|
var plaintext = decryptAESCTR(message.ciphertext, keys[0], message.counter);
|
2014-01-22 07:23:41 +01:00
|
|
|
delete chain.messageKeys[message.counter];
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-03-08 05:13:53 +01:00
|
|
|
//TODO: removeOldChains(session);
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
crypto_storage.saveSession(encodedNumber, session);
|
2014-03-08 05:13:53 +01:00
|
|
|
callback(decodePushMessageContentProtobuf(plaintext));
|
2014-01-22 07:23:41 +01:00
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
/*************************
|
|
|
|
*** Public crypto API ***
|
|
|
|
*************************/
|
|
|
|
// Decrypts message into a raw string
|
|
|
|
crypto.decryptWebsocketMessage = function(message) {
|
|
|
|
var signaling_key = storage.getEncrypted("signaling_key"); //TODO: in crypto_storage
|
2014-03-06 20:01:23 +01:00
|
|
|
var aes_key = signaling_key.substring(0, 32);
|
|
|
|
var mac_key = signaling_key.substring(32, 32 + 20);
|
2014-01-17 07:08:33 +01:00
|
|
|
|
2014-03-06 19:18:11 +01:00
|
|
|
var decodedMessage = new Uint8Array(base64DecToArr(getString(message)));
|
|
|
|
if (decodedMessage[0] != 1)
|
|
|
|
throw "Got bad version number: " + decodedMessage[0];
|
|
|
|
|
2014-03-06 20:01:23 +01:00
|
|
|
var iv = decodedMessage.subarray(1, 1 + 16);
|
2014-01-17 07:08:33 +01:00
|
|
|
var ciphertext = decodedMessage.subarray(1 + 16, decodedMessage.length - 10);
|
2014-03-06 20:01:23 +01:00
|
|
|
var ivAndCipherText = decodedMessage.subarray(1, decodedMessage.length - 10);
|
|
|
|
var mac = decodedMessage.subarray(decodedMessage.length - 10, decodedMessage.length);
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-03-06 20:01:23 +01:00
|
|
|
verifyMACWithVersionByte(ivAndCipherText, mac_key, mac);
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-03-06 20:01:23 +01:00
|
|
|
return decryptPaddedAES(ciphertext, aes_key, iv);
|
2014-01-15 08:46:05 +01:00
|
|
|
}
|
2014-01-12 08:32:13 +01:00
|
|
|
|
2014-01-22 07:23:41 +01:00
|
|
|
crypto.handleIncomingPushMessageProto = function(proto, callback) {
|
2014-01-17 07:08:33 +01:00
|
|
|
switch(proto.type) {
|
|
|
|
case 0: //TYPE_MESSAGE_PLAINTEXT
|
2014-01-22 07:23:41 +01:00
|
|
|
callback(decodePushMessageContentProtobuf(getString(proto.message)));
|
2014-01-17 07:08:33 +01:00
|
|
|
break;
|
|
|
|
case 1: //TYPE_MESSAGE_CIPHERTEXT
|
2014-01-22 07:23:41 +01:00
|
|
|
decryptWhisperMessage(proto.source, getString(proto.message), function(result) { callback(result); });
|
2014-01-17 07:08:33 +01:00
|
|
|
break;
|
|
|
|
case 3: //TYPE_MESSAGE_PREKEY_BUNDLE
|
2014-03-05 02:31:15 +01:00
|
|
|
if (proto.message.readUint8() != (2 << 4 | 2))
|
|
|
|
throw "Bad version byte";
|
2014-01-17 07:08:33 +01:00
|
|
|
var preKeyProto = decodePreKeyWhisperMessageProtobuf(getString(proto.message));
|
2014-01-22 08:37:14 +01:00
|
|
|
initSessionFromPreKeyWhisperMessage(proto.source, preKeyProto, function() {
|
|
|
|
decryptWhisperMessage(proto.source, getString(preKeyProto.message), function(result) { callback(result); });
|
|
|
|
});
|
2014-01-17 07:08:33 +01:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
crypto.encryptMessageFor = function(deviceObject, message) {
|
|
|
|
return message + " encrypted to " + deviceObject.encodedNumber + " with relay " + deviceObject.relay +
|
|
|
|
" with identityKey " + deviceObject.identityKey + " and public key " + deviceObject.publicKey; //TODO
|
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
var GENERATE_KEYS_KEYS_GENERATED = 100;
|
2014-01-22 07:23:41 +01:00
|
|
|
crypto.generateKeys = function(callback) {
|
2014-01-17 07:08:33 +01:00
|
|
|
var identityKey = crypto_storage.getStoredPubKey("identityKey");
|
2014-01-22 07:23:41 +01:00
|
|
|
var identityKeyCalculated = function(pubKey) {
|
|
|
|
identityKey = pubKey;
|
|
|
|
|
|
|
|
var firstKeyId = storage.getEncrypted("maxPreKeyId", -1) + 1;
|
|
|
|
storage.putEncrypted("maxPreKeyId", firstKeyId + GENERATE_KEYS_KEYS_GENERATED);
|
|
|
|
|
|
|
|
if (firstKeyId > 16777000)
|
|
|
|
throw "You crazy motherfucker";
|
|
|
|
|
|
|
|
var keys = {};
|
|
|
|
keys.keys = [];
|
|
|
|
var keysLeft = GENERATE_KEYS_KEYS_GENERATED;
|
|
|
|
for (var i = firstKeyId; i < firstKeyId + GENERATE_KEYS_KEYS_GENERATED; i++) {
|
|
|
|
crypto_storage.getNewPubKeySTORINGPrivKey("preKey" + i, function(pubKey) {
|
|
|
|
keys.keys[i] = {keyId: i, publicKey: pubKey, identityKey: identityKey};
|
|
|
|
keysLeft--;
|
|
|
|
if (keysLeft == 0) {
|
|
|
|
// 0xFFFFFF == 16777215
|
|
|
|
keys.lastResortKey = {keyId: 16777215, publicKey: crypto_storage.getStoredPubKey("preKey16777215"), identityKey: identityKey};//TODO: Rotate lastResortKey
|
|
|
|
if (keys.lastResortKey.publicKey === undefined) {
|
|
|
|
crypto_storage.getNewPubKeySTORINGPrivKey("preKey16777215", function(pubKey) {
|
|
|
|
keys.lastResortKey.publicKey = pubKey;
|
|
|
|
callback(keys);
|
|
|
|
});
|
|
|
|
} else
|
|
|
|
callback(keys);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2014-01-17 07:08:33 +01:00
|
|
|
if (identityKey === undefined)
|
2014-01-22 07:23:41 +01:00
|
|
|
crypto_storage.getNewPubKeySTORINGPrivKey("identityKey", function(pubKey) { identityKeyCalculated(pubKey); });
|
|
|
|
else
|
|
|
|
identityKeyCalculated(pubKey);
|
2014-01-17 07:08:33 +01:00
|
|
|
}
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-17 07:08:33 +01:00
|
|
|
}( window.crypto = window.crypto || {}, jQuery ));
|
2014-01-15 08:46:05 +01:00
|
|
|
|
2014-01-10 08:48:05 +01:00
|
|
|
/************************************************
|
|
|
|
*** Utilities to communicate with the server ***
|
|
|
|
************************************************/
|
|
|
|
var URL_BASE = "http://textsecure-test.herokuapp.com";
|
|
|
|
var URL_CALLS = {};
|
2014-01-17 07:08:33 +01:00
|
|
|
URL_CALLS['accounts'] = "/v1/accounts";
|
2014-01-12 08:32:13 +01:00
|
|
|
URL_CALLS['devices'] = "/v1/devices";
|
|
|
|
URL_CALLS['keys'] = "/v1/keys";
|
|
|
|
URL_CALLS['push'] = "/v1/messagesocket";
|
2014-01-12 09:49:46 +01:00
|
|
|
URL_CALLS['messages'] = "/v1/messages/";
|
2014-01-10 08:48:05 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* REQUIRED PARAMS:
|
|
|
|
* call: URL_CALLS entry
|
|
|
|
* httpType: POST/GET/PUT/etc
|
|
|
|
* OPTIONAL PARAMS:
|
2014-01-12 08:32:13 +01:00
|
|
|
* success_callback: function(response object) called on success
|
|
|
|
* error_callback: function(http status code = -1 or != 200) called on failure
|
2014-01-10 08:48:05 +01:00
|
|
|
* urlParameters: crap appended to the url (probably including a leading /)
|
|
|
|
* user: user name to be sent in a basic auth header
|
2014-01-12 08:32:13 +01:00
|
|
|
* password: password to be sent in a basic auth headerA
|
|
|
|
* do_auth: alternative to user/password where user/password are figured out automagically
|
2014-01-10 08:48:05 +01:00
|
|
|
* jsonData: JSON data sent in the request body
|
|
|
|
*/
|
|
|
|
function doAjax(param) {
|
|
|
|
if (param.urlParameters === undefined)
|
|
|
|
param.urlParameters = "";
|
2014-01-12 08:32:13 +01:00
|
|
|
if (param.do_auth) {
|
|
|
|
param.user = storage.getUnencrypted("number_id");
|
|
|
|
param.password = storage.getEncrypted("password");
|
|
|
|
}
|
2014-01-10 08:48:05 +01:00
|
|
|
$.ajax(URL_BASE + URL_CALLS[param.call] + param.urlParameters, {
|
|
|
|
type: param.httpType,
|
2014-03-05 02:31:15 +01:00
|
|
|
data: jsonThing(param.jsonData),
|
2014-01-12 08:32:13 +01:00
|
|
|
contentType: 'application/json; charset=utf-8',
|
|
|
|
dataType: 'json',
|
2014-01-10 08:48:05 +01:00
|
|
|
beforeSend: function(xhr) {
|
|
|
|
if (param.user !== undefined && param.password !== undefined)
|
2014-01-12 08:32:13 +01:00
|
|
|
xhr.setRequestHeader("Authorization", "Basic " + btoa(getString(param.user) + ":" + getString(param.password)));
|
2014-01-10 08:48:05 +01:00
|
|
|
},
|
|
|
|
success: function(response, textStatus, jqXHR) {
|
2014-01-12 08:32:13 +01:00
|
|
|
if (param.success_callback !== undefined)
|
|
|
|
param.success_callback(response);
|
2014-01-10 08:48:05 +01:00
|
|
|
},
|
|
|
|
error: function(jqXHR, textStatus, errorThrown) {
|
|
|
|
var code = jqXHR.status;
|
2014-01-17 07:08:47 +01:00
|
|
|
if (code == 200) {// happens sometimes when we get no response (TODO: Fix server to return 204? instead)
|
2014-01-17 07:08:33 +01:00
|
|
|
if (param.success_callback !== undefined)
|
|
|
|
param.success_callback(null);
|
|
|
|
return;
|
|
|
|
}
|
2014-01-10 08:48:05 +01:00
|
|
|
if (code > 999 || code < 100)
|
|
|
|
code = -1;
|
2014-01-12 08:32:13 +01:00
|
|
|
if (param.error_callback !== undefined)
|
|
|
|
param.error_callback(code);
|
2014-01-10 08:48:05 +01:00
|
|
|
},
|
|
|
|
cache: false
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2014-01-12 09:49:46 +01:00
|
|
|
// message_callback(decoded_protobuf) (use decodeMessage(proto))
|
2014-01-12 08:32:13 +01:00
|
|
|
function subscribeToPush(message_callback) {
|
|
|
|
var user = storage.getUnencrypted("number_id");
|
|
|
|
var password = storage.getEncrypted("password");
|
|
|
|
var request = { url: URL_BASE + URL_CALLS['push'] + "/?user=%2B" + getString(user).substring(1) + "&password=" + getString(password),
|
|
|
|
method: 'GET',
|
|
|
|
fallbackMethod: 'GET',
|
2014-01-11 08:58:58 +01:00
|
|
|
transport: 'websocket',
|
2014-01-12 08:32:13 +01:00
|
|
|
fallbackTransport: 'websocket',
|
2014-01-11 08:58:58 +01:00
|
|
|
logLevel: 'debug', //TODO
|
2014-01-12 08:32:13 +01:00
|
|
|
trackMessageLength: false,
|
|
|
|
//data: "user=" + getString(user) + "&password=" + getString(password),
|
|
|
|
onOpen: function(response) {
|
2014-01-11 08:58:58 +01:00
|
|
|
console.log('Connected to server using ' + response.transport);
|
|
|
|
},
|
2014-01-12 08:32:13 +01:00
|
|
|
onMessage: function(response) {
|
|
|
|
try {
|
|
|
|
// Some bug in Atmosphere.js is forcing trackMessageLength to true
|
|
|
|
var message = JSON.parse(response.responseBody.split("|")[1]);
|
|
|
|
} catch (e) {
|
|
|
|
console.log('Error parsing server JSON message: ' + response.responseBody.split("|")[1]);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2014-01-15 08:46:05 +01:00
|
|
|
var proto;
|
2014-01-11 08:58:58 +01:00
|
|
|
try {
|
2014-01-15 08:46:05 +01:00
|
|
|
var plaintext = crypto.decryptWebsocketMessage(message.message);
|
|
|
|
var proto = decodeIncomingPushMessageProtobuf(plaintext);
|
|
|
|
// After this point, a) decoding errors are not the server's fault, and
|
|
|
|
// b) we should handle them gracefully and tell the user they received an invalid message
|
2014-01-12 08:42:41 +01:00
|
|
|
|
|
|
|
doAjax({call: 'push', httpType: 'PUT', urlParameters: '/' + message.id, do_auth: true});
|
2014-01-11 08:58:58 +01:00
|
|
|
} catch (e) {
|
2014-01-12 08:32:13 +01:00
|
|
|
console.log("Error decoding message: " + e);
|
2014-01-15 08:46:05 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2014-01-22 07:23:41 +01:00
|
|
|
crypto.handleIncomingPushMessageProto(proto, function(decrypted) {
|
|
|
|
message_callback(decrypted);
|
|
|
|
}); // Decrypts/decodes/fills in fields/etc
|
2014-01-15 08:46:05 +01:00
|
|
|
} catch (e) {
|
|
|
|
//TODO: Tell the user decryption failed
|
2014-01-11 08:58:58 +01:00
|
|
|
}
|
|
|
|
},
|
2014-01-12 08:32:13 +01:00
|
|
|
onError: function(response) {
|
2014-01-11 08:58:58 +01:00
|
|
|
console.log('Server is down :(');
|
|
|
|
//TODO: GUI
|
|
|
|
}};
|
|
|
|
$.atmosphere.subscribe(request);
|
|
|
|
}
|
|
|
|
|
2014-01-12 08:32:13 +01:00
|
|
|
// success_callback(identity_key), error_callback(error_msg)
|
|
|
|
function getKeysForNumber(number, success_callback, error_callback) {
|
|
|
|
doAjax({call: 'keys', httpType: 'GET', do_auth: true, urlParameters: "/" + getNumberFromString(number) + "?multikeys",
|
|
|
|
success_callback: function(response) {
|
|
|
|
for (var i = 0; i < response.length; i++) {
|
|
|
|
try {
|
|
|
|
saveDeviceObject({
|
|
|
|
encodedNumber: number + "." + response[i].deviceId,
|
|
|
|
identityKey: response[i].identityKey,
|
|
|
|
publicKey: response[i].publicKey
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
error_callback(e);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
success_callback(response[0].identityKey);
|
|
|
|
}, error_callback: function(code) {
|
|
|
|
error_callback("Error making HTTP request: " + code);
|
|
|
|
}
|
|
|
|
});
|
2014-01-10 08:48:05 +01:00
|
|
|
}
|
|
|
|
|
2014-01-12 08:32:13 +01:00
|
|
|
// success_callback(server success/failure map), error_callback(error_msg)
|
|
|
|
function sendMessageToDevices(deviceObjectList, message, success_callback, error_callback) {
|
|
|
|
if (message.type === undefined)
|
|
|
|
message.type = 0; //TODO: Change to 1 for ciphertext instead of plaintext
|
2014-01-10 08:48:05 +01:00
|
|
|
|
2014-01-12 08:32:13 +01:00
|
|
|
var jsonData = [];
|
|
|
|
for (var i = 0; i < deviceObjectList.legnth; i++) {
|
|
|
|
jsonData[jsonData.length] = {
|
|
|
|
type: message.type,
|
|
|
|
destination: deviceObjectList[i].encodedNumber,
|
2014-01-13 02:52:58 +01:00
|
|
|
body: encryptMessageFor(deviceObjectList[i], message.message), //TODO: Protobuf?
|
2014-01-12 08:32:13 +01:00
|
|
|
relay: deviceObjectList[i].relay,
|
|
|
|
timestamp: new Date().getTime()
|
|
|
|
};
|
|
|
|
}
|
|
|
|
doAjax({call: 'messages', httpType: 'POST', do_auth: true, jsonData: jsonData,
|
|
|
|
success_callback: function(result) {
|
2014-01-13 02:52:58 +01:00
|
|
|
if (result.missingDeviceIds.length > 0) {
|
|
|
|
var responsesLeft = result.missingDeviceIds.length;
|
|
|
|
var errorThrown = 0;
|
|
|
|
for (var i = 0; i < result.missingDeviceIds.length; i++) {
|
|
|
|
getKeysForNumber(result.missingDeviceIds[i], function(identity_key) {
|
|
|
|
responsesLeft--;
|
|
|
|
if (responsesLeft == 0 && errorThrown == 0)
|
|
|
|
sendMessageToDevices(deviceObjectList, message, success_callback, error_callback);
|
|
|
|
}, function(error_msg) {
|
|
|
|
errorThrown++;
|
|
|
|
if (errorThrown == 1)
|
|
|
|
error_callback("Failed to retreive new device keys for number " + result.missingDeviceIds[i]);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
success_callback(result);
|
|
|
|
}
|
2014-01-12 08:32:13 +01:00
|
|
|
}, error_callback: function(code) {
|
|
|
|
error_callback("Failed to conect to data channel: " + code);
|
|
|
|
}
|
|
|
|
});
|
2014-01-10 08:48:05 +01:00
|
|
|
}
|
|
|
|
|
2014-01-12 08:32:13 +01:00
|
|
|
// success_callback(success/failure map, see second-to-last line), error_callback(error_msg)
|
|
|
|
function sendMessageToNumbers(numbers, message, success_callback, error_callback) {
|
|
|
|
var deviceObjectList = [];
|
2014-01-13 02:52:58 +01:00
|
|
|
|
|
|
|
var deviceDatasMissing = 0;
|
|
|
|
var loopDone = 0;
|
|
|
|
var errorThrown = 0;
|
2014-01-12 08:32:13 +01:00
|
|
|
for (var i = 0; i < numbers.length; i++) {
|
|
|
|
var devicesForNumber = getDeviceObjectListFromNumber(numbers[i]);
|
|
|
|
for (var j = 0; j < devicesForNumber.length; j++)
|
|
|
|
deviceObjectList[deviceObjectList.length] = devicesForNumber[j];
|
2014-01-13 02:52:58 +01:00
|
|
|
|
|
|
|
if (devicesForNumber.length == 0) {
|
|
|
|
deviceDatasMissing++;
|
|
|
|
getKeysForNumber(numbers[i], function(identity_key) {
|
|
|
|
deviceDatasMissing--;
|
|
|
|
if (deviceDatasMissing == 0 && loopDone && errorThrown == 0)
|
|
|
|
sendMessageToNumbers(numbers, message, success_callback, error_callback);
|
|
|
|
}, function(error_msg) {
|
|
|
|
errorThrown++;
|
|
|
|
if (errorThrown == 1)
|
|
|
|
error_callback("Failed to retreive new device keys for number " + numbers[i]);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (deviceDatasMissing > 0 || errorThrown > 0) {
|
|
|
|
loopDone = 1;
|
|
|
|
return;
|
2014-01-12 08:32:13 +01:00
|
|
|
}
|
|
|
|
return sendMessageToDevices(deviceObjectList, message, function(result) {
|
|
|
|
var successNumbers = {};
|
|
|
|
var failureNumbers = {};
|
|
|
|
for (var i = 0; i < result.success; i++)
|
|
|
|
successNumbers[getNumberFromString(result.success[i])] = 1;
|
|
|
|
for (var i = 0; i < result.failure; i++)
|
|
|
|
failureNumbers[getNumberFromString(result.success[i])] = 1;
|
2014-01-10 08:48:05 +01:00
|
|
|
|
2014-01-12 08:32:13 +01:00
|
|
|
success_callback({success: successNumbers, failure: failureNumbers});
|
|
|
|
}, error_callback);
|
|
|
|
}
|
|
|
|
|
|
|
|
function requestIdentityPrivKeyFromMasterDevice(number, identityKey) {
|
2014-01-12 09:49:46 +01:00
|
|
|
sendMessageToDevices([getDeviceObject(getNumberFromString(number)) + ".1"],
|
|
|
|
{message: "Identity Key request"}, function() {}, function() {});//TODO
|
2014-01-10 08:48:05 +01:00
|
|
|
}
|
2014-01-22 07:23:41 +01:00
|
|
|
|