forked from adiwajshing/libsignal-node
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathsession_builder.js
More file actions
173 lines (163 loc) · 7.21 KB
/
session_builder.js
File metadata and controls
173 lines (163 loc) · 7.21 KB
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
'use strict';
const BaseKeyType = require('./base_key_type');
const ChainType = require('./chain_type');
const SessionRecord = require('./session_record');
const crypto = require('./crypto');
const curve = require('./curve');
const errors = require('./errors');
const queueJob = require('./queue_job');
const Util = require('./util');
class SessionBuilder {
constructor(storage, protocolAddress) {
this.addr = protocolAddress;
this.storage = storage;
}
async initOutgoing(device) {
const fqAddr = this.addr.toString();
return await queueJob(fqAddr, async () => {
if (!await this.storage.isTrustedIdentity(this.addr.id, device.identityKey)) {
throw new errors.UntrustedIdentityKeyError(this.addr.id, device.identityKey);
}
curve.verifySignature(device.identityKey, device.signedPreKey.publicKey,
device.signedPreKey.signature);
const baseKey = curve.generateKeyPair();
const devicePreKey = device.preKey && device.preKey.publicKey;
const session = await this.initSession(true, baseKey, undefined, device.identityKey,
devicePreKey, device.signedPreKey.publicKey,
device.registrationId);
session.pendingPreKey = {
signedKeyId: device.signedPreKey.keyId,
baseKey: baseKey.pubKey
};
if (device.preKey) {
session.pendingPreKey.preKeyId = device.preKey.keyId;
}
let record = await this.storage.loadSession(fqAddr);
if (!record) {
record = new SessionRecord();
}
const openSession = record.getOpenSession();
record.archiveCurrentState();
if (openSession && session && !Util.isEqual(openSession.indexInfo.remoteIdentityKey, session.indexInfo.remoteIdentityKey)) {
console.warn("Deleting all sessions because identity has changed");
record.deleteAllSessions();
}
record.updateSessionState(session);
await this.storage.storeSession(fqAddr, record);
});
}
async initIncoming(record, message) {
const fqAddr = this.addr.toString();
if (!await this.storage.isTrustedIdentity(fqAddr, message.identityKey)) {
throw new errors.UntrustedIdentityKeyError(this.addr.id, message.identityKey);
}
if (record.getSession(message.baseKey)) {
// This just means we haven't replied.
return;
}
const [preKeyPair, signedPreKeyPair] = await Promise.all([
this.storage.loadPreKey(message.preKeyId),
this.storage.loadSignedPreKey(message.signedPreKeyId)
]);
const existingOpenSession = record.getOpenSession();
if (!signedPreKeyPair) {
if (existingOpenSession && existingOpenSession.currentRatchet) return;
throw new errors.PreKeyError("Missing Signed PreKey for PreKeyWhisperMessage");
}
if (existingOpenSession) {
record.archiveCurrentState();
}
if (message.preKeyId && !preKeyPair) {
throw new errors.PreKeyError("Invalid PreKey ID");
}
const session = await this.initSession(false, preKeyPair, signedPreKeyPair,
message.identityKey, message.baseKey,
undefined, message.registrationId);
if (existingOpenSession && session && !Util.isEqual(existingOpenSession.indexInfo.remoteIdentityKey, session.indexInfo.remoteIdentityKey)) {
console.warn("Deleting all sessions because identity has changed");
record.deleteAllSessions();
}
record.updateSessionState(session);
// this.storage.saveIdentity
return message.preKeyId;
}
async initSession(isInitiator, ourEphemeralKey, ourSignedKey, theirIdentityPubKey,
theirEphemeralPubKey, theirSignedPubKey, registrationId) {
if (isInitiator) {
if (ourSignedKey) {
throw new Error("Invalid call to initSession");
}
ourSignedKey = ourEphemeralKey;
} else {
if (theirSignedPubKey) {
throw new Error("Invalid call to initSession");
}
theirSignedPubKey = theirEphemeralPubKey;
}
let sharedSecret;
if (!ourEphemeralKey || !theirEphemeralPubKey) {
sharedSecret = new Uint8Array(32 * 4);
} else {
sharedSecret = new Uint8Array(32 * 5);
}
for (var i = 0; i < 32; i++) {
sharedSecret[i] = 0xff;
}
const ourIdentityKey = await this.storage.getOurIdentity();
const a1 = curve.calculateAgreement(theirSignedPubKey, ourIdentityKey.privKey);
const a2 = curve.calculateAgreement(theirIdentityPubKey, ourSignedKey.privKey);
const a3 = curve.calculateAgreement(theirSignedPubKey, ourSignedKey.privKey);
if (isInitiator) {
sharedSecret.set(new Uint8Array(a1), 32);
sharedSecret.set(new Uint8Array(a2), 32 * 2);
} else {
sharedSecret.set(new Uint8Array(a1), 32 * 2);
sharedSecret.set(new Uint8Array(a2), 32);
}
sharedSecret.set(new Uint8Array(a3), 32 * 3);
if (ourEphemeralKey && theirEphemeralPubKey) {
const a4 = curve.calculateAgreement(theirEphemeralPubKey, ourEphemeralKey.privKey);
sharedSecret.set(new Uint8Array(a4), 32 * 4);
}
const masterKey = crypto.deriveSecrets(Buffer.from(sharedSecret), Buffer.alloc(32),
Buffer.from("WhisperText"));
const session = SessionRecord.createEntry();
session.registrationId = registrationId;
session.currentRatchet = {
rootKey: masterKey[0],
ephemeralKeyPair: isInitiator ? curve.generateKeyPair() : ourSignedKey,
lastRemoteEphemeralKey: theirSignedPubKey,
previousCounter: 0
};
session.indexInfo = {
created: Date.now(),
used: Date.now(),
remoteIdentityKey: theirIdentityPubKey,
baseKey: isInitiator ? ourEphemeralKey.pubKey : theirEphemeralPubKey,
baseKeyType: isInitiator ? BaseKeyType.OURS : BaseKeyType.THEIRS,
closed: -1
};
if (isInitiator) {
// If we're initiating we go ahead and set our first sending ephemeral key now,
// otherwise we figure it out when we first maybeStepRatchet with the remote's
// ephemeral key
this.calculateSendingRatchet(session, theirSignedPubKey);
}
return session;
}
calculateSendingRatchet(session, remoteKey) {
const ratchet = session.currentRatchet;
const sharedSecret = curve.calculateAgreement(remoteKey, ratchet.ephemeralKeyPair.privKey);
const masterKey = crypto.deriveSecrets(sharedSecret, ratchet.rootKey, Buffer.from("WhisperRatchet"));
session.addChain(ratchet.ephemeralKeyPair.pubKey, {
messageKeys: {},
chainKey: {
counter: -1,
key: masterKey[1]
},
chainType: ChainType.SENDING
});
ratchet.rootKey = masterKey[0];
}
}
module.exports = SessionBuilder;