/
olm_session.go
476 lines (438 loc) · 15.1 KB
/
olm_session.go
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package session
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"maunium.net/go/mautrix/crypto/goolm"
"maunium.net/go/mautrix/crypto/goolm/cipher"
"maunium.net/go/mautrix/crypto/goolm/crypto"
"maunium.net/go/mautrix/crypto/goolm/libolmpickle"
"maunium.net/go/mautrix/crypto/goolm/message"
"maunium.net/go/mautrix/crypto/goolm/olm"
"maunium.net/go/mautrix/crypto/goolm/utilities"
"maunium.net/go/mautrix/id"
)
const (
olmSessionPickleVersionJSON uint8 = 1
olmSessionPickleVersionLibOlm uint32 = 1
)
const (
protocolVersion = 0x3
)
// OlmSession stores all information for an olm session
type OlmSession struct {
ReceivedMessage bool `json:"received_message"`
AliceIdentityKey crypto.Curve25519PublicKey `json:"alice_id_key"`
AliceBaseKey crypto.Curve25519PublicKey `json:"alice_base_key"`
BobOneTimeKey crypto.Curve25519PublicKey `json:"bob_one_time_key"`
Ratchet olm.Ratchet `json:"ratchet"`
}
// SearchOTKFunc is used to retrieve a crypto.OneTimeKey from a public key.
type SearchOTKFunc = func(crypto.Curve25519PublicKey) *crypto.OneTimeKey
// OlmSessionFromJSONPickled loads an OlmSession from a pickled base64 string. Decrypts
// the Session using the supplied key.
func OlmSessionFromJSONPickled(pickled, key []byte) (*OlmSession, error) {
if len(pickled) == 0 {
return nil, fmt.Errorf("sessionFromPickled: %w", goolm.ErrEmptyInput)
}
a := &OlmSession{}
err := a.UnpickleAsJSON(pickled, key)
if err != nil {
return nil, err
}
return a, nil
}
// OlmSessionFromPickled loads the OlmSession details from a pickled base64 string. The input is decrypted with the supplied key.
func OlmSessionFromPickled(pickled, key []byte) (*OlmSession, error) {
if len(pickled) == 0 {
return nil, fmt.Errorf("sessionFromPickled: %w", goolm.ErrEmptyInput)
}
a := &OlmSession{}
err := a.Unpickle(pickled, key)
if err != nil {
return nil, err
}
return a, nil
}
// NewOlmSession creates a new Session.
func NewOlmSession() *OlmSession {
s := &OlmSession{}
s.Ratchet = *olm.New()
return s
}
// NewOutboundOlmSession creates a new outbound session for sending the first message to a
// given curve25519 identityKey and oneTimeKey.
func NewOutboundOlmSession(identityKeyAlice crypto.Curve25519KeyPair, identityKeyBob crypto.Curve25519PublicKey, oneTimeKeyBob crypto.Curve25519PublicKey) (*OlmSession, error) {
s := NewOlmSession()
//generate E_A
baseKey, err := crypto.Curve25519GenerateKey(nil)
if err != nil {
return nil, err
}
//generate T_0
ratchetKey, err := crypto.Curve25519GenerateKey(nil)
if err != nil {
return nil, err
}
//Calculate shared secret via Triple Diffie-Hellman
var secret []byte
//ECDH(I_A,E_B)
idSecret, err := identityKeyAlice.SharedSecret(oneTimeKeyBob)
if err != nil {
return nil, err
}
//ECDH(E_A,I_B)
baseIdSecret, err := baseKey.SharedSecret(identityKeyBob)
if err != nil {
return nil, err
}
//ECDH(E_A,E_B)
baseOneTimeSecret, err := baseKey.SharedSecret(oneTimeKeyBob)
if err != nil {
return nil, err
}
secret = append(secret, idSecret...)
secret = append(secret, baseIdSecret...)
secret = append(secret, baseOneTimeSecret...)
//Init Ratchet
s.Ratchet.InitializeAsAlice(secret, ratchetKey)
s.AliceIdentityKey = identityKeyAlice.PublicKey
s.AliceBaseKey = baseKey.PublicKey
s.BobOneTimeKey = oneTimeKeyBob
return s, nil
}
// NewInboundOlmSession creates a new inbound session from receiving the first message.
func NewInboundOlmSession(identityKeyAlice *crypto.Curve25519PublicKey, receivedOTKMsg []byte, searchBobOTK SearchOTKFunc, identityKeyBob crypto.Curve25519KeyPair) (*OlmSession, error) {
decodedOTKMsg, err := goolm.Base64Decode(receivedOTKMsg)
if err != nil {
return nil, err
}
s := NewOlmSession()
//decode OneTimeKeyMessage
oneTimeMsg := message.PreKeyMessage{}
err = oneTimeMsg.Decode(decodedOTKMsg)
if err != nil {
return nil, fmt.Errorf("OneTimeKeyMessage decode: %w", err)
}
if !oneTimeMsg.CheckFields(identityKeyAlice) {
return nil, fmt.Errorf("OneTimeKeyMessage check fields: %w", goolm.ErrBadMessageFormat)
}
//Either the identityKeyAlice is set and/or the oneTimeMsg.IdentityKey is set, which is checked
// by oneTimeMsg.CheckFields
if identityKeyAlice != nil && len(oneTimeMsg.IdentityKey) != 0 {
//if both are set, compare them
if !identityKeyAlice.Equal(oneTimeMsg.IdentityKey) {
return nil, fmt.Errorf("OneTimeKeyMessage identity keys: %w", goolm.ErrBadMessageKeyID)
}
}
if identityKeyAlice == nil {
//for downstream use set
identityKeyAlice = &oneTimeMsg.IdentityKey
}
oneTimeKeyBob := searchBobOTK(oneTimeMsg.OneTimeKey)
if oneTimeKeyBob == nil {
return nil, fmt.Errorf("ourOneTimeKey: %w", goolm.ErrBadMessageKeyID)
}
//Calculate shared secret via Triple Diffie-Hellman
var secret []byte
//ECDH(E_B,I_A)
idSecret, err := oneTimeKeyBob.Key.SharedSecret(*identityKeyAlice)
if err != nil {
return nil, err
}
//ECDH(I_B,E_A)
baseIdSecret, err := identityKeyBob.SharedSecret(oneTimeMsg.BaseKey)
if err != nil {
return nil, err
}
//ECDH(E_B,E_A)
baseOneTimeSecret, err := oneTimeKeyBob.Key.SharedSecret(oneTimeMsg.BaseKey)
if err != nil {
return nil, err
}
secret = append(secret, idSecret...)
secret = append(secret, baseIdSecret...)
secret = append(secret, baseOneTimeSecret...)
//decode message
msg := message.Message{}
err = msg.Decode(oneTimeMsg.Message)
if err != nil {
return nil, fmt.Errorf("Message decode: %w", err)
}
if len(msg.RatchetKey) == 0 {
return nil, fmt.Errorf("Message missing ratchet key: %w", goolm.ErrBadMessageFormat)
}
//Init Ratchet
s.Ratchet.InitializeAsBob(secret, msg.RatchetKey)
s.AliceBaseKey = oneTimeMsg.BaseKey
s.AliceIdentityKey = oneTimeMsg.IdentityKey
s.BobOneTimeKey = oneTimeKeyBob.Key.PublicKey
//https://gitlab.matrix.org/matrix-org/olm/blob/master/docs/olm.md states to remove the oneTimeKey
//this is done via the account itself
return s, nil
}
// PickleAsJSON returns an Session as a base64 string encrypted using the supplied key. The unencrypted representation of the Account is in JSON format.
func (a OlmSession) PickleAsJSON(key []byte) ([]byte, error) {
return utilities.PickleAsJSON(a, olmSessionPickleVersionJSON, key)
}
// UnpickleAsJSON updates an Session by a base64 encrypted string with the key. The unencrypted representation has to be in JSON format.
func (a *OlmSession) UnpickleAsJSON(pickled, key []byte) error {
return utilities.UnpickleAsJSON(a, pickled, key, olmSessionPickleVersionJSON)
}
// ID returns an identifier for this Session. Will be the same for both ends of the conversation.
// Generated by hashing the public keys used to create the session.
func (s OlmSession) ID() id.SessionID {
message := make([]byte, 3*crypto.Curve25519KeyLength)
copy(message, s.AliceIdentityKey)
copy(message[crypto.Curve25519KeyLength:], s.AliceBaseKey)
copy(message[2*crypto.Curve25519KeyLength:], s.BobOneTimeKey)
hash := crypto.SHA256(message)
res := id.SessionID(goolm.Base64Encode(hash))
return res
}
// HasReceivedMessage returns true if this session has received any message.
func (s OlmSession) HasReceivedMessage() bool {
return s.ReceivedMessage
}
// MatchesInboundSessionFrom checks if the oneTimeKeyMsg message is set for this inbound
// Session. This can happen if multiple messages are sent to this Account
// before this Account sends a message in reply. Returns true if the session
// matches. Returns false if the session does not match.
func (s OlmSession) MatchesInboundSessionFrom(theirIdentityKeyEncoded *id.Curve25519, receivedOTKMsg []byte) (bool, error) {
if len(receivedOTKMsg) == 0 {
return false, fmt.Errorf("inbound match: %w", goolm.ErrEmptyInput)
}
decodedOTKMsg, err := goolm.Base64Decode(receivedOTKMsg)
if err != nil {
return false, err
}
var theirIdentityKey *crypto.Curve25519PublicKey
if theirIdentityKeyEncoded != nil {
decodedKey, err := base64.RawStdEncoding.DecodeString(string(*theirIdentityKeyEncoded))
if err != nil {
return false, err
}
theirIdentityKeyByte := crypto.Curve25519PublicKey(decodedKey)
theirIdentityKey = &theirIdentityKeyByte
}
msg := message.PreKeyMessage{}
err = msg.Decode(decodedOTKMsg)
if err != nil {
return false, err
}
if !msg.CheckFields(theirIdentityKey) {
return false, nil
}
same := true
if msg.IdentityKey != nil {
same = same && msg.IdentityKey.Equal(s.AliceIdentityKey)
}
if theirIdentityKey != nil {
same = same && theirIdentityKey.Equal(s.AliceIdentityKey)
}
same = same && bytes.Equal(msg.BaseKey, s.AliceBaseKey)
same = same && bytes.Equal(msg.OneTimeKey, s.BobOneTimeKey)
return same, nil
}
// EncryptMsgType returns the type of the next message that Encrypt will
// return. Returns MsgTypePreKey if the message will be a oneTimeKeyMsg.
// Returns MsgTypeMsg if the message will be a normal message.
func (s OlmSession) EncryptMsgType() id.OlmMsgType {
if s.ReceivedMessage {
return id.OlmMsgTypeMsg
}
return id.OlmMsgTypePreKey
}
// Encrypt encrypts a message using the Session. Returns the encrypted message base64 encoded. If reader is nil, crypto/rand is used for key generations.
func (s *OlmSession) Encrypt(plaintext []byte, reader io.Reader) (id.OlmMsgType, []byte, error) {
if len(plaintext) == 0 {
return 0, nil, fmt.Errorf("encrypt: %w", goolm.ErrEmptyInput)
}
messageType := s.EncryptMsgType()
encrypted, err := s.Ratchet.Encrypt(plaintext, reader)
if err != nil {
return 0, nil, err
}
result := encrypted
if !s.ReceivedMessage {
msg := message.PreKeyMessage{}
msg.Version = protocolVersion
msg.OneTimeKey = s.BobOneTimeKey
msg.IdentityKey = s.AliceIdentityKey
msg.BaseKey = s.AliceBaseKey
msg.Message = encrypted
var err error
messageBody, err := msg.Encode()
if err != nil {
return 0, nil, err
}
result = messageBody
}
return messageType, goolm.Base64Encode(result), nil
}
// Decrypt decrypts a base64 encoded message using the Session.
func (s *OlmSession) Decrypt(crypttext []byte, msgType id.OlmMsgType) ([]byte, error) {
if len(crypttext) == 0 {
return nil, fmt.Errorf("decrypt: %w", goolm.ErrEmptyInput)
}
decodedCrypttext, err := goolm.Base64Decode(crypttext)
if err != nil {
return nil, err
}
msgBody := decodedCrypttext
if msgType != id.OlmMsgTypeMsg {
//Pre-Key Message
msg := message.PreKeyMessage{}
err := msg.Decode(decodedCrypttext)
if err != nil {
return nil, err
}
msgBody = msg.Message
}
plaintext, err := s.Ratchet.Decrypt(msgBody)
if err != nil {
return nil, err
}
s.ReceivedMessage = true
return plaintext, nil
}
// Unpickle decodes the base64 encoded string and decrypts the result with the key.
// The decrypted value is then passed to UnpickleLibOlm.
func (o *OlmSession) Unpickle(pickled, key []byte) error {
decrypted, err := cipher.Unpickle(key, pickled)
if err != nil {
return err
}
_, err = o.UnpickleLibOlm(decrypted)
return err
}
// UnpickleLibOlm decodes the unencryted value and populates the Session accordingly. It returns the number of bytes read.
func (o *OlmSession) UnpickleLibOlm(value []byte) (int, error) {
//First 4 bytes are the accountPickleVersion
pickledVersion, curPos, err := libolmpickle.UnpickleUInt32(value)
if err != nil {
return 0, err
}
includesChainIndex := true
switch pickledVersion {
case olmSessionPickleVersionLibOlm:
includesChainIndex = false
case uint32(0x80000001):
includesChainIndex = true
default:
return 0, fmt.Errorf("unpickle olmSession: %w", goolm.ErrBadVersion)
}
var readBytes int
o.ReceivedMessage, readBytes, err = libolmpickle.UnpickleBool(value[curPos:])
if err != nil {
return 0, err
}
curPos += readBytes
readBytes, err = o.AliceIdentityKey.UnpickleLibOlm(value[curPos:])
if err != nil {
return 0, err
}
curPos += readBytes
readBytes, err = o.AliceBaseKey.UnpickleLibOlm(value[curPos:])
if err != nil {
return 0, err
}
curPos += readBytes
readBytes, err = o.BobOneTimeKey.UnpickleLibOlm(value[curPos:])
if err != nil {
return 0, err
}
curPos += readBytes
readBytes, err = o.Ratchet.UnpickleLibOlm(value[curPos:], includesChainIndex)
if err != nil {
return 0, err
}
curPos += readBytes
return curPos, nil
}
// Pickle returns a base64 encoded and with key encrypted pickled olmSession using PickleLibOlm().
func (o OlmSession) Pickle(key []byte) ([]byte, error) {
pickeledBytes := make([]byte, o.PickleLen())
written, err := o.PickleLibOlm(pickeledBytes)
if err != nil {
return nil, err
}
if written != len(pickeledBytes) {
return nil, errors.New("number of written bytes not correct")
}
encrypted, err := cipher.Pickle(key, pickeledBytes)
if err != nil {
return nil, err
}
return encrypted, nil
}
// PickleLibOlm encodes the session into target. target has to have a size of at least PickleLen() and is written to from index 0.
// It returns the number of bytes written.
func (o OlmSession) PickleLibOlm(target []byte) (int, error) {
if len(target) < o.PickleLen() {
return 0, fmt.Errorf("pickle MegolmOutboundSession: %w", goolm.ErrValueTooShort)
}
written := libolmpickle.PickleUInt32(olmSessionPickleVersionLibOlm, target)
written += libolmpickle.PickleBool(o.ReceivedMessage, target[written:])
writtenRatchet, err := o.AliceIdentityKey.PickleLibOlm(target[written:])
if err != nil {
return 0, fmt.Errorf("pickle MegolmOutboundSession: %w", err)
}
written += writtenRatchet
writtenRatchet, err = o.AliceBaseKey.PickleLibOlm(target[written:])
if err != nil {
return 0, fmt.Errorf("pickle MegolmOutboundSession: %w", err)
}
written += writtenRatchet
writtenRatchet, err = o.BobOneTimeKey.PickleLibOlm(target[written:])
if err != nil {
return 0, fmt.Errorf("pickle MegolmOutboundSession: %w", err)
}
written += writtenRatchet
writtenRatchet, err = o.Ratchet.PickleLibOlm(target[written:])
if err != nil {
return 0, fmt.Errorf("pickle MegolmOutboundSession: %w", err)
}
written += writtenRatchet
return written, nil
}
// PickleLen returns the actual number of bytes the pickled session will have.
func (o OlmSession) PickleLen() int {
length := libolmpickle.PickleUInt32Len(olmSessionPickleVersionLibOlm)
length += libolmpickle.PickleBoolLen(o.ReceivedMessage)
length += o.AliceIdentityKey.PickleLen()
length += o.AliceBaseKey.PickleLen()
length += o.BobOneTimeKey.PickleLen()
length += o.Ratchet.PickleLen()
return length
}
// PickleLenMin returns the minimum number of bytes the pickled session must have.
func (o OlmSession) PickleLenMin() int {
length := libolmpickle.PickleUInt32Len(olmSessionPickleVersionLibOlm)
length += libolmpickle.PickleBoolLen(o.ReceivedMessage)
length += o.AliceIdentityKey.PickleLen()
length += o.AliceBaseKey.PickleLen()
length += o.BobOneTimeKey.PickleLen()
length += o.Ratchet.PickleLenMin()
return length
}
// Describe returns a string describing the current state of the session for debugging.
func (o OlmSession) Describe() string {
var res string
if o.Ratchet.SenderChains.IsSet {
res += fmt.Sprintf("sender chain index: %d ", o.Ratchet.SenderChains.CKey.Index)
} else {
res += "sender chain index: "
}
res += "receiver chain indicies:"
for _, curChain := range o.Ratchet.ReceiverChains {
res += fmt.Sprintf(" %d", curChain.CKey.Index)
}
res += " skipped message keys:"
for _, curSkip := range o.Ratchet.SkippedMessageKeys {
res += fmt.Sprintf(" %d", curSkip.MKey.Index)
}
return res
}