forked from alijundi/Chat-API-NET
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSessionCipher.cs
454 lines (393 loc) · 16.4 KB
/
SessionCipher.cs
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* Copyright (C) 2015 smndtrl
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using libaxolotl.ecc;
using libaxolotl.protocol;
using libaxolotl.ratchet;
using libaxolotl.state;
using libaxolotl.util;
using Strilanc.Value;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace libaxolotl
{
/**
* The main entry point for Axolotl encrypt/decrypt operations.
*
* Once a session has been established with {@link SessionBuilder},
* this class can be used for all encrypt/decrypt operations within
* that session.
*
* @author Moxie Marlinspike
*/
public class SessionCipher
{
public static readonly Object SESSION_LOCK = new Object();
private readonly SessionStore sessionStore;
private readonly SessionBuilder sessionBuilder;
private readonly PreKeyStore preKeyStore;
private readonly AxolotlAddress remoteAddress;
/**
* Construct a SessionCipher for encrypt/decrypt operations on a session.
* In order to use SessionCipher, a session must have already been created
* and stored using {@link SessionBuilder}.
*
* @param sessionStore The {@link SessionStore} that contains a session for this recipient.
* @param remoteAddress The remote address that messages will be encrypted to or decrypted from.
*/
public SessionCipher(SessionStore sessionStore, PreKeyStore preKeyStore,
SignedPreKeyStore signedPreKeyStore, IdentityKeyStore identityKeyStore,
AxolotlAddress remoteAddress)
{
this.sessionStore = sessionStore;
this.preKeyStore = preKeyStore;
this.remoteAddress = remoteAddress;
this.sessionBuilder = new SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,
identityKeyStore, remoteAddress);
}
public SessionCipher(AxolotlStore store, AxolotlAddress remoteAddress)
: this(store, store, store, store, remoteAddress)
{
}
/**
* Encrypt a message.
*
* @param paddedMessage The plaintext message bytes, optionally padded to a constant multiple.
* @return A ciphertext message encrypted to the recipient+device tuple.
*/
public CiphertextMessage encrypt(byte[] paddedMessage)
{
lock (SESSION_LOCK)
{
SessionRecord sessionRecord = sessionStore.LoadSession(remoteAddress);
SessionState sessionState = sessionRecord.getSessionState();
ChainKey chainKey = sessionState.getSenderChainKey();
MessageKeys messageKeys = chainKey.getMessageKeys();
ECPublicKey senderEphemeral = sessionState.getSenderRatchetKey();
uint previousCounter = sessionState.getPreviousCounter();
uint sessionVersion = sessionState.getSessionVersion();
byte[] ciphertextBody = getCiphertext(sessionVersion, messageKeys, paddedMessage);
CiphertextMessage ciphertextMessage = new WhisperMessage(sessionVersion, messageKeys.getMacKey(),
senderEphemeral, chainKey.getIndex(),
previousCounter, ciphertextBody,
sessionState.getLocalIdentityKey(),
sessionState.getRemoteIdentityKey());
if (sessionState.hasUnacknowledgedPreKeyMessage())
{
SessionState.UnacknowledgedPreKeyMessageItems items = sessionState.getUnacknowledgedPreKeyMessageItems();
uint localRegistrationId = sessionState.GetLocalRegistrationId();
ciphertextMessage = new PreKeyWhisperMessage(sessionVersion, localRegistrationId, items.getPreKeyId(),
items.getSignedPreKeyId(), items.getBaseKey(),
sessionState.getLocalIdentityKey(),
(WhisperMessage)ciphertextMessage);
}
sessionState.setSenderChainKey(chainKey.getNextChainKey());
sessionStore.StoreSession(remoteAddress, sessionRecord);
return ciphertextMessage;
}
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link PreKeyWhisperMessage} to decrypt.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws InvalidKeyIdException when there is no local {@link org.whispersystems.libaxolotl.state.PreKeyRecord}
* that corresponds to the PreKey ID in the message.
* @throws InvalidKeyException when the message is formatted incorrectly.
* @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
*/
public byte[] decrypt(PreKeyWhisperMessage ciphertext)
{
return decrypt(ciphertext, new NullDecryptionCallback());
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link PreKeyWhisperMessage} to decrypt.
* @param callback A callback that is triggered after decryption is complete,
* but before the updated session state has been committed to the session
* DB. This allows some implementations to store the committed plaintext
* to a DB first, in case they are concerned with a crash happening between
* the time the session state is updated but before they're able to store
* the plaintext to disk.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws InvalidKeyIdException when there is no local {@link org.whispersystems.libaxolotl.state.PreKeyRecord}
* that corresponds to the PreKey ID in the message.
* @throws InvalidKeyException when the message is formatted incorrectly.
* @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
*/
public byte[] decrypt(PreKeyWhisperMessage ciphertext, DecryptionCallback callback)
{
lock (SESSION_LOCK)
{
SessionRecord sessionRecord = sessionStore.LoadSession(remoteAddress);
May<uint> unsignedPreKeyId = sessionBuilder.process(sessionRecord, ciphertext);
byte[] plaintext = decrypt(sessionRecord, ciphertext.getWhisperMessage());
callback.handlePlaintext(plaintext);
sessionStore.StoreSession(remoteAddress, sessionRecord);
if (unsignedPreKeyId.HasValue)
{
preKeyStore.RemovePreKey(unsignedPreKeyId.ForceGetValue());
}
return plaintext;
}
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link WhisperMessage} to decrypt.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws NoSessionException if there is no established session for this contact.
*/
public byte[] decrypt(WhisperMessage ciphertext)
{
return decrypt(ciphertext, new NullDecryptionCallback());
}
/**
* Decrypt a message.
*
* @param ciphertext The {@link WhisperMessage} to decrypt.
* @param callback A callback that is triggered after decryption is complete,
* but before the updated session state has been committed to the session
* DB. This allows some implementations to store the committed plaintext
* to a DB first, in case they are concerned with a crash happening between
* the time the session state is updated but before they're able to store
* the plaintext to disk.
*
* @return The plaintext.
* @throws InvalidMessageException if the input is not valid ciphertext.
* @throws DuplicateMessageException if the input is a message that has already been received.
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
* is no longer supported.
* @throws NoSessionException if there is no established session for this contact.
*/
public byte[] decrypt(WhisperMessage ciphertext, DecryptionCallback callback)
{
lock (SESSION_LOCK)
{
if (!sessionStore.ContainsSession(remoteAddress))
{
throw new NoSessionException($"No session for: {remoteAddress}");
}
SessionRecord sessionRecord = sessionStore.LoadSession(remoteAddress);
byte[] plaintext = decrypt(sessionRecord, ciphertext);
callback.handlePlaintext(plaintext);
sessionStore.StoreSession(remoteAddress, sessionRecord);
return plaintext;
}
}
private byte[] decrypt(SessionRecord sessionRecord, WhisperMessage ciphertext)
{
lock (SESSION_LOCK)
{
IEnumerator<SessionState> previousStates = sessionRecord.getPreviousSessionStates().GetEnumerator(); //iterator
LinkedList<Exception> exceptions = new LinkedList<Exception>();
try
{
SessionState sessionState = new SessionState(sessionRecord.getSessionState());
byte[] plaintext = decrypt(sessionState, ciphertext);
sessionRecord.setState(sessionState);
return plaintext;
}
catch (InvalidMessageException e)
{
exceptions.AddLast(e); // add (java default behavioir addlast)
}
while (previousStates.MoveNext()) //hasNext();
{
try
{
SessionState promotedState = new SessionState(previousStates.Current); //.next()
byte[] plaintext = decrypt(promotedState, ciphertext);
sessionRecord.getPreviousSessionStates().Remove(previousStates.Current); // previousStates.remove()
sessionRecord.promoteState(promotedState);
return plaintext;
}
catch (InvalidMessageException e)
{
exceptions.AddLast(e);
}
}
throw new InvalidMessageException("No valid sessions.", exceptions);
}
}
private byte[] decrypt(SessionState sessionState, WhisperMessage ciphertextMessage)
{
if (!sessionState.hasSenderChain())
{
throw new InvalidMessageException("Uninitialized session!");
}
if (ciphertextMessage.getMessageVersion() != sessionState.getSessionVersion())
{
throw new InvalidMessageException($"Message version {ciphertextMessage.getMessageVersion()}, but session version {sessionState.getSessionVersion()}");
}
uint messageVersion = ciphertextMessage.getMessageVersion();
ECPublicKey theirEphemeral = ciphertextMessage.getSenderRatchetKey();
uint counter = ciphertextMessage.getCounter();
ChainKey chainKey = getOrCreateChainKey(sessionState, theirEphemeral);
MessageKeys messageKeys = getOrCreateMessageKeys(sessionState, theirEphemeral,
chainKey, counter);
//Fixed BadMac
//ciphertextMessage.verifyMac(messageVersion,
// sessionState.getRemoteIdentityKey(),
// sessionState.getLocalIdentityKey(),
// messageKeys.getMacKey());
byte[] plaintext = getPlaintext(messageVersion, messageKeys, ciphertextMessage.getBody());
sessionState.clearUnacknowledgedPreKeyMessage();
return plaintext;
}
public uint getRemoteRegistrationId()
{
lock (SESSION_LOCK)
{
SessionRecord record = sessionStore.LoadSession(remoteAddress);
return record.getSessionState().getRemoteRegistrationId();
}
}
public uint getSessionVersion()
{
lock (SESSION_LOCK)
{
if (!sessionStore.ContainsSession(remoteAddress))
{
throw new Exception($"No session for {remoteAddress}!"); // IllegalState
}
SessionRecord record = sessionStore.LoadSession(remoteAddress);
return record.getSessionState().getSessionVersion();
}
}
private ChainKey getOrCreateChainKey(SessionState sessionState, ECPublicKey theirEphemeral)
{
try
{
if (sessionState.hasReceiverChain(theirEphemeral))
{
return sessionState.getReceiverChainKey(theirEphemeral);
}
else
{
RootKey rootKey = sessionState.getRootKey();
ECKeyPair ourEphemeral = sessionState.getSenderRatchetKeyPair();
Pair<RootKey, ChainKey> receiverChain = rootKey.createChain(theirEphemeral, ourEphemeral);
ECKeyPair ourNewEphemeral = Curve.generateKeyPair();
Pair<RootKey, ChainKey> senderChain = receiverChain.first().createChain(theirEphemeral, ourNewEphemeral);
sessionState.setRootKey(senderChain.first());
sessionState.addReceiverChain(theirEphemeral, receiverChain.second());
sessionState.setPreviousCounter(Math.Max(sessionState.getSenderChainKey().getIndex() - 1, 0));
sessionState.setSenderChain(ourNewEphemeral, senderChain.second());
return receiverChain.second();
}
}
catch (InvalidKeyException e)
{
throw new InvalidMessageException(e);
}
}
private MessageKeys getOrCreateMessageKeys(SessionState sessionState,
ECPublicKey theirEphemeral,
ChainKey chainKey, uint counter)
{
if (chainKey.getIndex() > counter)
{
if (sessionState.hasMessageKeys(theirEphemeral, counter))
{
return sessionState.removeMessageKeys(theirEphemeral, counter);
}
else
{
throw new DuplicateMessageException($"Received message with old counter: {chainKey.getIndex()} , {counter}");
}
}
//Avoiding a uint overflow
uint chainKeyIndex = chainKey.getIndex();
if ((counter > chainKeyIndex) && (counter - chainKeyIndex > 2000))
{
throw new InvalidMessageException("Over 2000 messages into the future!");
}
while (chainKey.getIndex() < counter)
{
MessageKeys messageKeys = chainKey.getMessageKeys();
sessionState.setMessageKeys(theirEphemeral, messageKeys);
chainKey = chainKey.getNextChainKey();
}
sessionState.setReceiverChainKey(theirEphemeral, chainKey.getNextChainKey());
return chainKey.getMessageKeys();
}
private byte[] getCiphertext(uint version, MessageKeys messageKeys, byte[] plaintext)
{
try
{
if (version >= 3)
{
//cipher = getCipher(Cipher.ENCRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getIv());
return Encrypt.aesCbcPkcs5(plaintext, messageKeys.getCipherKey(), messageKeys.getIv());
}
else
{
//cipher = getCipher(Cipher.ENCRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getCounter());
return Encrypt.aesCtr(plaintext, messageKeys.getCipherKey(), messageKeys.getCounter());
}
}
catch (/*IllegalBlockSizeException | BadPadding*/Exception e)
{
throw new Exception(e.Message);
}
}
private byte[] getPlaintext(uint version, MessageKeys messageKeys, byte[] cipherText)
{
try
{
//Cipher cipher;
if (version >= 3)
{
//cipher = getCipher(Cipher.DECRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getIv());
return Decrypt.aesCbcPkcs5(cipherText, messageKeys.getCipherKey(), messageKeys.getIv());
}
else
{
//cipher = getCipher(Cipher.DECRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getCounter())
return Decrypt.aesCtr(cipherText, messageKeys.getCipherKey(), messageKeys.getCounter());
}
}
catch (/*IllegalBlockSizeException | BadPadding*/Exception e)
{
throw new InvalidMessageException(e);
}
}
private class NullDecryptionCallback : DecryptionCallback
{
public void handlePlaintext(byte[] plaintext) { }
}
}
}