-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
359 lines (311 loc) · 15.1 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- To test this, run `python -m SimpleHTTPServer` then open http://localhost:8000/ -->
<!-- https://github.com/signalapp/libsignal-protocol-javascript
This library doesn't seem to like being imported, so we just include it as a
script tag and let it set up its global variables. -->
<script src="./libsignal-protocol/libsignal-protocol.js"></script>
<script type="module">
import init, * as spake2 from './spake2/spake2_wasm.js';
const password = 'supersecret';
const APP_ID = 'backchannel/app/mailbox/v1';
const KEY_CONFIRMATION = new TextEncoder().encode(APP_ID);
const HMAC_LENGTH = 32; // SHA-256
const IV_LENGTH = 16; // 128 bits
const PRE_KEY_ID = 1; // our protocol only generates one pre-key
const INITIAL_MESSAGE = new TextEncoder().encode('backchannel v1 initial message');
// In the standard use of the Signal protocol, recipientId is a phone number.
// Need to check what purpose it has. We can probably just make it a constant.
const SIGNAL_ADDRESS = new libsignal.SignalProtocolAddress('recipient', 1);
// Returns true if the two byte arrays have the same content.
function compareByteArrays(arr1, arr2) {
if (!(arr1 instanceof Uint8Array)) arr1 = new Uint8Array(arr1);
if (!(arr2 instanceof Uint8Array)) arr2 = new Uint8Array(arr2);
if (arr1.byteLength !== arr2.byteLength) return false;
for (let i = 0; i < arr1.byteLength; i++) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
class Peer {
// Generates the SPAKE2 message to send to the other peer
async step1(password) {
// Start the SPAKE2 protocol
this.spakeState = spake2.start(APP_ID, password);
this.sentSpakeMsg = spake2.msg(this.spakeState);
return this.sentSpakeMsg;
}
// Receives the SPAKE2 message and returns a key setup message to send to the other peer
async step2(message) {
// If both peers had the same password and there was no person-in-the-middle
// attack, then both peers will have the same secret here. But we don't yet
// know whether that is the case or not.
this.spakeSecret = spake2.finish(this.spakeState, message);
this.receivedSpakeMsg = message;
// Generate the Signal key material
const registrationId = libsignal.KeyHelper.generateRegistrationId();
const identityKeyPair = await libsignal.KeyHelper.generateIdentityKeyPair();
const preKey = await libsignal.KeyHelper.generatePreKey(PRE_KEY_ID);
const signedPreKey = await libsignal.KeyHelper.generateSignedPreKey(identityKeyPair, PRE_KEY_ID);
this.store = new SignalProtocolStore();
this.store.put('registrationId', registrationId);
this.store.put('identityKey', identityKeyPair);
this.store.storePreKey(PRE_KEY_ID, preKey.keyPair);
this.store.storeSignedPreKey(PRE_KEY_ID, signedPreKey.keyPair);
// Make a message containing the various bits of Signal key material we need to send.
const plaintext = new Uint8Array(6 + identityKeyPair.pubKey.byteLength +
preKey.keyPair.pubKey.byteLength + signedPreKey.keyPair.pubKey.byteLength +
signedPreKey.signature.byteLength);
plaintext[0] = registrationId & 0xff; // The registrationId is always 16 bits
plaintext[1] = registrationId >> 8;
plaintext[2] = identityKeyPair.pubKey.byteLength;
plaintext[3] = preKey.keyPair.pubKey.byteLength;
plaintext[4] = signedPreKey.keyPair.pubKey.byteLength;
plaintext[5] = signedPreKey.signature.byteLength;
let offset = 6;
plaintext.set(new Uint8Array(identityKeyPair.pubKey), offset);
offset += identityKeyPair.pubKey.byteLength;
plaintext.set(new Uint8Array(preKey.keyPair.pubKey), offset);
offset += preKey.keyPair.pubKey.byteLength;
plaintext.set(new Uint8Array(signedPreKey.keyPair.pubKey), offset);
offset += signedPreKey.keyPair.pubKey.byteLength;
plaintext.set(new Uint8Array(signedPreKey.signature), offset);
// Encrypt the Signal key material with the key that is shared (if all went well)
const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH));
const key = await window.crypto.subtle.importKey('raw', this.spakeSecret, 'AES-GCM', true, ['encrypt']);
const ciphertext = await window.crypto.subtle.encrypt({name: 'AES-GCM', iv}, key, plaintext);
// Since AES-GCM does not provide random key robustness -- it is not a committing
// encryption scheme, see https://soatok.blog/2020/05/13/why-aes-gcm-sucks/ -- we
// also generate a HMAC commitment to check both peers have derived the same secret.
const hmacKey = await window.crypto.subtle.importKey('raw', this.spakeSecret, {name: 'HMAC', hash: 'SHA-256'}, true, ['sign']);
const hmac = await window.crypto.subtle.sign('HMAC', hmacKey, KEY_CONFIRMATION);
if (hmac.byteLength !== HMAC_LENGTH) throw new Error('bad HMAC length');
// Concatenate HMAC, IV and ciphertext into the message to send
const result = new Uint8Array(HMAC_LENGTH + IV_LENGTH + ciphertext.byteLength);
result.set(new Uint8Array(hmac), 0);
result.set(iv, HMAC_LENGTH);
result.set(new Uint8Array(ciphertext), HMAC_LENGTH + IV_LENGTH);
return result;
}
async step3(message) {
// Check the HMAC. This will fail if the passwords didn't match or if
// someone interfered with our packets.
const hmacKey = await window.crypto.subtle.importKey('raw', this.spakeSecret, {name: 'HMAC', hash: 'SHA-256'}, true, ['verify']);
const hmac = message.subarray(0, HMAC_LENGTH);
const success = await window.crypto.subtle.verify('HMAC', hmacKey, hmac, KEY_CONFIRMATION);
if (success !== true) {
throw new Error('SPAKE2 handshake failed: wrong password or someone interfered with communication');
}
// Decrypt the message. This should fail only if the message was corrupted.
const iv = message.subarray(HMAC_LENGTH, HMAC_LENGTH + IV_LENGTH);
const ciphertext = message.subarray(HMAC_LENGTH + IV_LENGTH);
const key = await window.crypto.subtle.importKey('raw', this.spakeSecret, 'AES-GCM', true, ['decrypt']);
const plaintext = await window.crypto.subtle.decrypt({name: 'AES-GCM', iv}, key, ciphertext);
// If we got to this point, decryption succeeded, which means the password
// was correct and nobody interfered. Parse out the Signal key material.
const byteArray = new Uint8Array(plaintext);
const registrationId = byteArray[0] | (byteArray[1] << 8);
let offset = 6;
this.peerIdentityKey = plaintext.slice(offset, offset + byteArray[2]);
offset += byteArray[2];
const preKey = plaintext.slice(offset, offset + byteArray[3]);
offset += byteArray[3];
const signedPreKey = plaintext.slice(offset, offset + byteArray[4]);
offset += byteArray[4];
const signature = plaintext.slice(offset, offset + byteArray[5]);
// Signal protocol requires that a session is set up by having one peer send
// an initial message to the other (not both sending messages to each other).
// That means we have to choose which of the two peers is going to send the
// message, since up to this point the protocol has been symmetric. We choose
// a peer based on lexicographic ordering of the SPAKE2 messages. Since the
// SPAKE2 shared secret includes a hash over the messages sent and received,
// we know that both peers agree on the content of the SPAKE2 messages.
for (let i = 0; ; i++) {
if (i === this.sentSpakeMsg.byteLength) throw new Error('SPAKE2 messages are identical');
if (this.sentSpakeMsg[i] < this.receivedSpakeMsg[i]) return;
if (this.sentSpakeMsg[i] > this.receivedSpakeMsg[i]) break;
}
// We get here if sentSpakeMsg is greater than receivedSpakeMsg. That means
// it's our job to initiate the Signal protocol setup.
const sessionBuilder = new libsignal.SessionBuilder(this.store, SIGNAL_ADDRESS);
await sessionBuilder.processPreKey({
registrationId,
identityKey: this.peerIdentityKey,
signedPreKey: {keyId: PRE_KEY_ID, publicKey: signedPreKey, signature},
preKey: {keyId: PRE_KEY_ID, publicKey: preKey}
});
const session = new libsignal.SessionCipher(this.store, SIGNAL_ADDRESS);
return await session.encrypt(INITIAL_MESSAGE);
}
async step4(message) {
// Only one of the two peers in step3 sent a message. If we didn't receive
// a message in that step, we don't need to do anything.
if (message === undefined) return;
// Decrypt the first Signal protocol message, which also sets up the
// session state.
const session = new libsignal.SessionCipher(this.store, SIGNAL_ADDRESS);
if (message.type !== 3) throw new Error(`Unexpected message type: ${message.type}`);
const decrypted = await session.decryptPreKeyWhisperMessage(message.body, 'binary');
if (!compareByteArrays(decrypted, INITIAL_MESSAGE)) throw new Error('initial message mismatch');
// Check that the identity key of the established Signal session matches
// the one we received in step3. This binds the Signal session to the
// successful SPAKE2 handshake.
const sessionIdentityKey = await this.store.loadIdentityKey(SIGNAL_ADDRESS.getName());
if (!compareByteArrays(sessionIdentityKey, this.peerIdentityKey)) {
throw new Error('Signal session identity key mismatch')
}
// If we got here without any exceptions, the Signal session is correctly set up.
}
// Encrypts a message to the peer using the Signal session. Returns the encrypted message.
async send(message) {
const session = new libsignal.SessionCipher(this.store, SIGNAL_ADDRESS);
return await session.encrypt(message);
}
// Decrypts a message that was encrypted by `send()`.
async receive(message) {
const session = new libsignal.SessionCipher(this.store, SIGNAL_ADDRESS);
let decrypted;
if (message.type === 1) { // textsecure.protobuf.IncomingPushMessageSignal.Type.CIPHERTEXT
decrypted = await session.decryptWhisperMessage(message.body, 'binary');
} else if (message.type === 3) { // textsecure.protobuf.IncomingPushMessageSignal.Type.PREKEY_BUNDLE
decrypted = await session.decryptPreKeyWhisperMessage(message.body, 'binary');
} else {
throw new Error(`Unknown message type: ${message.type}`)
}
// Convert ArrayBuffer to string
return new TextDecoder('utf-8').decode(decrypted);
}
}
// Based on https://github.com/signalapp/libsignal-protocol-javascript/blob/master/test/InMemorySignalProtocolStore.js
class SignalProtocolStore {
constructor() {
this.Direction = {SENDING: 1, RECEIVING: 2};
this.store = {};
}
put(key, value) {
if (key === undefined || value === undefined || key === null || value === null)
throw new Error("Tried to store undefined/null");
this.store[key] = value;
}
get(key, defaultValue) {
if (key === null || key === undefined)
throw new Error("Tried to get value for undefined/null key");
if (key in this.store) {
return this.store[key];
} else {
return defaultValue;
}
}
remove(key) {
if (key === null || key === undefined)
throw new Error("Tried to remove value for undefined/null key");
delete this.store[key];
}
// Get the local client's identity key pair.
getIdentityKeyPair() {
return Promise.resolve(this.get('identityKey'));
}
// Return the local client's registration ID.
// Clients should maintain a registration ID, a random number
// between 1 and 16380 that's generated once at install time.
getLocalRegistrationId() {
return Promise.resolve(this.get('registrationId'));
}
// Determine whether a remote client's identity is trusted. The Signal protocol
// uses 'trust on first use.' This means that an identity key is considered
// 'trusted' if there is no entry for the recipient in the local store, or if
// it matches the saved key for a recipient in the local store. Only if it
// mismatches an entry in the local store is it considered 'untrusted.'
isTrustedIdentity(identifier, identityKey, direction) {
return Promise.resolve(true);
}
loadIdentityKey(identifier) {
if (identifier === null || identifier === undefined)
throw new Error("Tried to get identity key for undefined/null key");
return Promise.resolve(this.get('identityKey' + identifier));
}
// Save a remote client's identity key, marking it as trusted.
saveIdentity(identifier, identityKey) {
if (identifier === null || identifier === undefined)
throw new Error("Tried to put identity key for undefined/null key");
const address = new libsignal.SignalProtocolAddress.fromString(identifier);
this.put('identityKey' + address.getName(), identityKey)
return Promise.resolve(false);
}
// Load a local serialized PreKey record.
loadPreKey(keyId) {
let res = this.get('25519KeypreKey' + keyId);
if (res !== undefined) {
res = { pubKey: res.pubKey, privKey: res.privKey };
}
return Promise.resolve(res);
}
// Store a local serialized PreKey record.
storePreKey(keyId, keyPair) {
return Promise.resolve(this.put('25519KeypreKey' + keyId, keyPair));
}
// Delete a PreKey record from local storage.
removePreKey(keyId) {
return Promise.resolve(this.remove('25519KeypreKey' + keyId));
}
// Load a local serialized signed PreKey record.
loadSignedPreKey(keyId) {
let res = this.get('25519KeysignedKey' + keyId);
if (res !== undefined) {
res = { pubKey: res.pubKey, privKey: res.privKey };
}
return Promise.resolve(res);
}
// Store a local serialized signed PreKey record.
storeSignedPreKey(keyId, keyPair) {
return Promise.resolve(this.put('25519KeysignedKey' + keyId, keyPair));
}
// Delete a SignedPreKeyRecord from local storage.
removeSignedPreKey(keyId) {
return Promise.resolve(this.remove('25519KeysignedKey' + keyId));
}
// Returns a copy of the serialized session record corresponding to the
// provided recipient ID + device ID tuple.
loadSession(identifier) {
return Promise.resolve(this.get('session' + identifier));
}
// Writes to storage the session record for a given recipient ID + device
// ID tuple.
storeSession(identifier, record) {
return Promise.resolve(this.put('session' + identifier, record));
}
// Remove a session record for a recipient ID + device ID tuple.
removeSession(identifier) {
return Promise.resolve(this.remove('session' + identifier));
}
// Remove the session records corresponding to all devices of a recipient ID.
removeAllSessions(identifier) {
for (let key of Object.keys(this.store)) {
if (key.startsWith('session' + identifier)) {
delete this.store[key];
}
}
return Promise.resolve();
}
}
async function run() {
await init();
const peer1 = new Peer(), peer2 = new Peer();
const msg1a = await peer1.step1(password), msg1b = await peer2.step1(password);
const msg2a = await peer1.step2(msg1b), msg2b = await peer2.step2(msg1a);
const msg3a = await peer1.step3(msg2b), msg3b = await peer2.step3(msg2a);
await peer1.step4(msg3b);
await peer2.step4(msg3a);
// Now the peers can send each other messages
console.log(await peer1.receive(await peer2.send('Hello world!')));
console.log(await peer1.receive(await peer2.send('How are you doing?')));
console.log(await peer2.receive(await peer1.send('Pretty good, thanks. And you?')));
}
run();
</script>
</body>
</html>