Debian Codegraph @

crypto/machine.go

raw
1 // Copyright (c) 2020 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package crypto
8
9 import (
10 "errors"
11 "fmt"
12 "sync"
13 "time"
14
15 "maunium.net/go/mautrix/appservice"
16 "maunium.net/go/mautrix/crypto/ssss"
17 "maunium.net/go/mautrix/id"
18
19 "maunium.net/go/mautrix"
20 "maunium.net/go/mautrix/event"
21 )
22
23 // Logger is a simple logging struct for OlmMachine.
24 // Implementations are recommended to use fmt.Sprintf and manually add a newline after the message.
25 type Logger interface {
26 Error(message string, args ...interface{})
27 Warn(message string, args ...interface{})
28 Debug(message string, args ...interface{})
29 Trace(message string, args ...interface{})
30 }
31
32 // OlmMachine is the main struct for handling Matrix end-to-end encryption.
33 type OlmMachine struct {
34 Client *mautrix.Client
35 SSSS *ssss.Machine
36 Log Logger
37
38 CryptoStore Store
39 StateStore StateStore
40
41 AllowUnverifiedDevices bool
42 ShareKeysToUnverifiedDevices bool
43
44 AllowKeyShare func(*DeviceIdentity, event.RequestedKeyInfo) *KeyShareRejection
45
46 DefaultSASTimeout time.Duration
47 // AcceptVerificationFrom determines whether the machine will accept verification requests from this device.
48 AcceptVerificationFrom func(string, *DeviceIdentity, id.RoomID) (VerificationRequestResponse, VerificationHooks)
49
50 account *OlmAccount
51
52 roomKeyRequestFilled *sync.Map
53 keyVerificationTransactionState *sync.Map
54
55 keyWaiters map[id.SessionID]chan struct{}
56 keyWaitersLock sync.Mutex
57
58 devicesToUnwedge map[id.IdentityKey]bool
59 devicesToUnwedgeLock sync.Mutex
60 recentlyUnwedged map[id.IdentityKey]time.Time
61 recentlyUnwedgedLock sync.Mutex
62
63 olmLock sync.Mutex
64
65 CrossSigningKeys *CrossSigningKeysCache
66 crossSigningPubkeys *CrossSigningPublicKeysCache
67 }
68
69 // StateStore is used by OlmMachine to get room state information that's needed for encryption.
70 type StateStore interface {
71 // IsEncrypted returns whether a room is encrypted.
72 IsEncrypted(id.RoomID) bool
73 // GetEncryptionEvent returns the encryption event's content for an encrypted room.
74 GetEncryptionEvent(id.RoomID) *event.EncryptionEventContent
75 // FindSharedRooms returns the encrypted rooms that another user is also in for a user ID.
76 FindSharedRooms(id.UserID) []id.RoomID
77 }
78
79 // NewOlmMachine creates an OlmMachine with the given client, logger and stores.
80 func NewOlmMachine(client *mautrix.Client, log Logger, cryptoStore Store, stateStore StateStore) *OlmMachine {
81 mach := &OlmMachine{
82 Client: client,
83 SSSS: ssss.NewSSSSMachine(client),
84 Log: log,
85 CryptoStore: cryptoStore,
86 StateStore: stateStore,
87
88 AllowUnverifiedDevices: true,
89 ShareKeysToUnverifiedDevices: false,
90
91 DefaultSASTimeout: 10 * time.Minute,
92 AcceptVerificationFrom: func(string, *DeviceIdentity, id.RoomID) (VerificationRequestResponse, VerificationHooks) {
93 // Reject requests by default. Users need to override this to return appropriate verification hooks.
94 return RejectRequest, nil
95 },
96
97 roomKeyRequestFilled: &sync.Map{},
98 keyVerificationTransactionState: &sync.Map{},
99
100 keyWaiters: make(map[id.SessionID]chan struct{}),
101
102 devicesToUnwedge: make(map[id.IdentityKey]bool),
103 recentlyUnwedged: make(map[id.IdentityKey]time.Time),
104 }
105 mach.AllowKeyShare = mach.defaultAllowKeyShare
106 return mach
107 }
108
109 // Load loads the Olm account information from the crypto store. If there's no olm account, a new one is created.
110 // This must be called before using the machine.
111 func (mach *OlmMachine) Load() (err error) {
112 mach.account, err = mach.CryptoStore.GetAccount()
113 if err != nil {
114 return
115 }
116 if mach.account == nil {
117 mach.account = NewOlmAccount()
118 }
119 return nil
120 }
121
122 func (mach *OlmMachine) saveAccount() {
123 err := mach.CryptoStore.PutAccount(mach.account)
124 if err != nil {
125 mach.Log.Error("Failed to save account: %v", err)
126 }
127 }
128
129 // FlushStore calls the Flush method of the CryptoStore.
130 func (mach *OlmMachine) FlushStore() error {
131 return mach.CryptoStore.Flush()
132 }
133
134 func (mach *OlmMachine) timeTrace(thing, trace string, expectedDuration time.Duration) func() {
135 start := time.Now()
136 return func() {
137 duration := time.Now().Sub(start)
138 if duration > expectedDuration {
139 mach.Log.Warn("%s took %s (trace: %s)", thing, duration, trace)
140 }
141 }
142 }
143
144 func Fingerprint(signingKey id.SigningKey) string {
145 spacedSigningKey := make([]byte, len(signingKey)+(len(signingKey)-1)/4)
146 var ptr = 0
147 for i, chr := range signingKey {
148 spacedSigningKey[ptr] = byte(chr)
149 ptr++
150 if i%4 == 3 {
151 spacedSigningKey[ptr] = ' '
152 ptr++
153 }
154 }
155 return string(spacedSigningKey)
156 }
157
158 // Fingerprint returns the fingerprint of the Olm account that can be used for non-interactive verification.
159 func (mach *OlmMachine) Fingerprint() string {
160 return Fingerprint(mach.account.SigningKey())
161 }
162
163 // OwnIdentity returns this device's DeviceIdentity struct
164 func (mach *OlmMachine) OwnIdentity() *DeviceIdentity {
165 return &DeviceIdentity{
166 UserID: mach.Client.UserID,
167 DeviceID: mach.Client.DeviceID,
168 IdentityKey: mach.account.IdentityKey(),
169 SigningKey: mach.account.SigningKey(),
170 Trust: TrustStateVerified,
171 Deleted: false,
172 }
173 }
174
175 func (mach *OlmMachine) AddAppserviceListener(ep *appservice.EventProcessor, az *appservice.AppService) {
176 // ToDeviceForwardedRoomKey and ToDeviceRoomKey should only be present inside encrypted to-device events
177 ep.On(event.ToDeviceEncrypted, mach.HandleToDeviceEvent)
178 ep.On(event.ToDeviceRoomKeyRequest, mach.HandleToDeviceEvent)
179 ep.On(event.ToDeviceRoomKeyWithheld, mach.HandleToDeviceEvent)
180 ep.On(event.ToDeviceOrgMatrixRoomKeyWithheld, mach.HandleToDeviceEvent)
181 ep.On(event.ToDeviceVerificationRequest, mach.HandleToDeviceEvent)
182 ep.On(event.ToDeviceVerificationStart, mach.HandleToDeviceEvent)
183 ep.On(event.ToDeviceVerificationAccept, mach.HandleToDeviceEvent)
184 ep.On(event.ToDeviceVerificationKey, mach.HandleToDeviceEvent)
185 ep.On(event.ToDeviceVerificationMAC, mach.HandleToDeviceEvent)
186 ep.On(event.ToDeviceVerificationCancel, mach.HandleToDeviceEvent)
187 ep.OnOTK(mach.HandleOTKCounts)
188 ep.OnDeviceList(mach.HandleDeviceLists)
189 mach.Log.Trace("Added listeners for encryption data coming from appservice transactions")
190 }
191
192 func (mach *OlmMachine) HandleDeviceLists(dl *mautrix.DeviceLists, since string) {
193 if len(dl.Changed) > 0 {
194 traceID := time.Now().Format("15:04:05.000000")
195 mach.Log.Trace("Device list changes in /sync: %v (trace: %s)", dl.Changed, traceID)
196 mach.fetchKeys(dl.Changed, since, false)
197 mach.Log.Trace("Finished handling device list changes (trace: %s)", traceID)
198 }
199 }
200
201 func (mach *OlmMachine) HandleOTKCounts(otkCount *mautrix.OTKCount) {
202 if (len(otkCount.UserID) > 0 && otkCount.UserID != mach.Client.UserID) || (len(otkCount.DeviceID) > 0 && otkCount.DeviceID != mach.Client.DeviceID) {
203 // TODO This log probably needs to be silence-able if someone wants to use encrypted appservices with multiple e2ee sessions
204 mach.Log.Debug("Dropping OTK counts targeted to %s/%s (not us)", otkCount.UserID, otkCount.DeviceID)
205 return
206 }
207
208 minCount := mach.account.Internal.MaxNumberOfOneTimeKeys() / 2
209 if otkCount.SignedCurve25519 < int(minCount) {
210 traceID := time.Now().Format("15:04:05.000000")
211 mach.Log.Debug("Sync response said we have %d signed curve25519 keys left, sharing new ones... (trace: %s)", otkCount.SignedCurve25519, traceID)
212 err := mach.ShareKeys(otkCount.SignedCurve25519)
213 if err != nil {
214 mach.Log.Error("Failed to share keys: %v (trace: %s)", err, traceID)
215 } else {
216 mach.Log.Debug("Successfully shared keys (trace: %s)", traceID)
217 }
218 }
219 }
220
221 // ProcessSyncResponse processes a single /sync response.
222 //
223 // This can be easily registered into a mautrix client using .OnSync():
224 //
225 // client.Syncer.(*mautrix.DefaultSyncer).OnSync(c.crypto.ProcessSyncResponse)
226 func (mach *OlmMachine) ProcessSyncResponse(resp *mautrix.RespSync, since string) bool {
227 mach.HandleDeviceLists(&resp.DeviceLists, since)
228
229 for _, evt := range resp.ToDevice.Events {
230 evt.Type.Class = event.ToDeviceEventType
231 err := evt.Content.ParseRaw(evt.Type)
232 if err != nil {
233 mach.Log.Warn("Failed to parse to-device event of type %s: %v", evt.Type.Type, err)
234 continue
235 }
236 mach.HandleToDeviceEvent(evt)
237 }
238
239 mach.HandleOTKCounts(&resp.DeviceOTKCount)
240 return true
241 }
242
243 // HandleMemberEvent handles a single membership event.
244 //
245 // Currently this is not automatically called, so you must add a listener yourself:
246 //
247 // client.Syncer.(*mautrix.DefaultSyncer).OnEventType(event.StateMember, c.crypto.HandleMemberEvent)
248 func (mach *OlmMachine) HandleMemberEvent(evt *event.Event) {
249 if !mach.StateStore.IsEncrypted(evt.RoomID) {
250 return
251 }
252 content := evt.Content.AsMember()
253 if content == nil {
254 return
255 }
256 var prevContent *event.MemberEventContent
257 if evt.Unsigned.PrevContent != nil {
258 _ = evt.Unsigned.PrevContent.ParseRaw(evt.Type)
259 prevContent = evt.Unsigned.PrevContent.AsMember()
260 }
261 if prevContent == nil {
262 prevContent = &event.MemberEventContent{Membership: "unknown"}
263 }
264 if prevContent.Membership == content.Membership ||
265 (prevContent.Membership == event.MembershipInvite && content.Membership == event.MembershipJoin) ||
266 (prevContent.Membership == event.MembershipBan && content.Membership == event.MembershipLeave) ||
267 (prevContent.Membership == event.MembershipLeave && content.Membership == event.MembershipBan) {
268 return
269 }
270 mach.Log.Trace("Got membership state event in %s changing %s from %s to %s, invalidating group session", evt.RoomID, evt.GetStateKey(), prevContent.Membership, content.Membership)
271 err := mach.CryptoStore.RemoveOutboundGroupSession(evt.RoomID)
272 if err != nil {
273 mach.Log.Warn("Failed to invalidate outbound group session of %s: %v", evt.RoomID, err)
274 }
275 }
276
277 // HandleToDeviceEvent handles a single to-device event. This is automatically called by ProcessSyncResponse, so you
278 // don't need to add any custom handlers if you use that method.
279 func (mach *OlmMachine) HandleToDeviceEvent(evt *event.Event) {
280 if len(evt.ToUserID) > 0 && (evt.ToUserID != mach.Client.UserID || evt.ToDeviceID != mach.Client.DeviceID) {
281 // TODO This log probably needs to be silence-able if someone wants to use encrypted appservices with multiple e2ee sessions
282 mach.Log.Debug("Dropping to-device event targeted to %s/%s (not us)", evt.ToUserID, evt.ToDeviceID)
283 return
284 }
285 traceID := time.Now().Format("15:04:05.000000")
286 if evt.Type != event.ToDeviceEncrypted {
287 mach.Log.Trace("Starting handling to-device event of type %s from %s (trace: %s)", evt.Type.Type, evt.Sender, traceID)
288 }
289 switch content := evt.Content.Parsed.(type) {
290 case *event.EncryptedEventContent:
291 mach.Log.Debug("Handling encrypted to-device event from %s/%s (trace: %s)", evt.Sender, content.SenderKey, traceID)
292 decryptedEvt, err := mach.decryptOlmEvent(evt, traceID)
293 if err != nil {
294 mach.Log.Error("Failed to decrypt to-device event: %v (trace: %s)", err, traceID)
295 return
296 }
297 mach.Log.Trace("Successfully decrypted to-device from %s/%s into type %s (sender key: %s, trace: %s)", decryptedEvt.Sender, decryptedEvt.SenderDevice, decryptedEvt.Type.String(), decryptedEvt.SenderKey, traceID)
298
299 switch decryptedContent := decryptedEvt.Content.Parsed.(type) {
300 case *event.RoomKeyEventContent:
301 mach.receiveRoomKey(decryptedEvt, decryptedContent, traceID)
302 mach.Log.Trace("Handled room key event from %s/%s (trace: %s)", decryptedEvt.Sender, decryptedEvt.SenderDevice, traceID)
303 case *event.ForwardedRoomKeyEventContent:
304 if mach.importForwardedRoomKey(decryptedEvt, decryptedContent) {
305 if ch, ok := mach.roomKeyRequestFilled.Load(decryptedContent.SessionID); ok {
306 // close channel to notify listener that the key was received
307 close(ch.(chan struct{}))
308 }
309 }
310 mach.Log.Trace("Handled forwarded room key event from %s/%s (trace: %s)", decryptedEvt.Sender, decryptedEvt.SenderDevice, traceID)
311 case *event.DummyEventContent:
312 mach.Log.Debug("Received encrypted dummy event from %s/%s (trace: %s)", decryptedEvt.Sender, decryptedEvt.SenderDevice, traceID)
313 default:
314 mach.Log.Debug("Unhandled encrypted to-device event of type %s from %s/%s (trace: %s)", decryptedEvt.Type.String(), decryptedEvt.Sender, decryptedEvt.SenderDevice, traceID)
315 }
316 return
317 case *event.RoomKeyRequestEventContent:
318 mach.handleRoomKeyRequest(evt.Sender, content)
319 // verification cases
320 case *event.VerificationStartEventContent:
321 mach.handleVerificationStart(evt.Sender, content, content.TransactionID, 10*time.Minute, "")
322 case *event.VerificationAcceptEventContent:
323 mach.handleVerificationAccept(evt.Sender, content, content.TransactionID)
324 case *event.VerificationKeyEventContent:
325 mach.handleVerificationKey(evt.Sender, content, content.TransactionID)
326 case *event.VerificationMacEventContent:
327 mach.handleVerificationMAC(evt.Sender, content, content.TransactionID)
328 case *event.VerificationCancelEventContent:
329 mach.handleVerificationCancel(evt.Sender, content, content.TransactionID)
330 case *event.VerificationRequestEventContent:
331 mach.handleVerificationRequest(evt.Sender, content, content.TransactionID, "")
332 case *event.RoomKeyWithheldEventContent:
333 mach.handleRoomKeyWithheld(content)
334 default:
335 deviceID, _ := evt.Content.Raw["device_id"].(string)
336 mach.Log.Trace("Unhandled to-device event of type %s from %s/%s (trace: %s)", evt.Type.Type, evt.Sender, deviceID, traceID)
337 return
338 }
339 mach.Log.Trace("Finished handling to-device event of type %s from %s (trace: %s)", evt.Type.Type, evt.Sender, traceID)
340 }
341
342 // GetOrFetchDevice attempts to retrieve the device identity for the given device from the store
343 // and if it's not found it asks the server for it.
344 func (mach *OlmMachine) GetOrFetchDevice(userID id.UserID, deviceID id.DeviceID) (*DeviceIdentity, error) {
345 // get device identity
346 device, err := mach.CryptoStore.GetDevice(userID, deviceID)
347 if err != nil {
348 return nil, fmt.Errorf("failed to get sender device from store: %w", err)
349 } else if device != nil {
350 return device, nil
351 }
352 // try to fetch if not found
353 usersToDevices := mach.fetchKeys([]id.UserID{userID}, "", true)
354 if devices, ok := usersToDevices[userID]; ok {
355 if device, ok = devices[deviceID]; ok {
356 return device, nil
357 }
358 return nil, fmt.Errorf("didn't get identity for device %s of %s", deviceID, userID)
359 }
360 return nil, fmt.Errorf("didn't get any devices for %s", userID)
361 }
362
363 // GetOrFetchDeviceByKey attempts to retrieve the device identity for the device with the given identity key from the
364 // store and if it's not found it asks the server for it. This returns nil if the server doesn't return a device with
365 // the given identity key.
366 func (mach *OlmMachine) GetOrFetchDeviceByKey(userID id.UserID, identityKey id.IdentityKey) (*DeviceIdentity, error) {
367 deviceIdentity, err := mach.CryptoStore.FindDeviceByKey(userID, identityKey)
368 if err != nil || deviceIdentity != nil {
369 return deviceIdentity, err
370 }
371 mach.Log.Debug("Didn't find identity of %s/%s in crypto store, fetching from server", userID, identityKey)
372 devices := mach.LoadDevices(userID)
373 for _, device := range devices {
374 if device.IdentityKey == identityKey {
375 return device, nil
376 }
377 }
378 return nil, nil
379 }
380
381 // SendEncryptedToDevice sends an Olm-encrypted event to the given user device.
382 func (mach *OlmMachine) SendEncryptedToDevice(device *DeviceIdentity, evtType event.Type, content event.Content) error {
383 if err := mach.createOutboundSessions(map[id.UserID]map[id.DeviceID]*DeviceIdentity{
384 device.UserID: {
385 device.DeviceID: device,
386 },
387 }); err != nil {
388 return err
389 }
390
391 mach.olmLock.Lock()
392 defer mach.olmLock.Unlock()
393
394 olmSess, err := mach.CryptoStore.GetLatestSession(device.IdentityKey)
395 if err != nil {
396 return err
397 }
398 if olmSess == nil {
399 return fmt.Errorf("didn't find created outbound session for device %s of %s", device.DeviceID, device.UserID)
400 }
401
402 encrypted := mach.encryptOlmEvent(olmSess, device, evtType, content)
403 encryptedContent := &event.Content{Parsed: &encrypted}
404
405 mach.Log.Debug("Sending encrypted to-device event of type %s to %s/%s (identity key: %s, olm session ID: %s)", evtType.Type, device.UserID, device.DeviceID, device.IdentityKey, olmSess.ID())
406 _, err = mach.Client.SendToDevice(event.ToDeviceEncrypted,
407 &mautrix.ReqSendToDevice{
408 Messages: map[id.UserID]map[id.DeviceID]*event.Content{
409 device.UserID: {
410 device.DeviceID: encryptedContent,
411 },
412 },
413 },
414 )
415
416 return err
417 }
418
419 func (mach *OlmMachine) createGroupSession(senderKey id.SenderKey, signingKey id.Ed25519, roomID id.RoomID, sessionID id.SessionID, sessionKey string, traceID string) {
420 igs, err := NewInboundGroupSession(senderKey, signingKey, roomID, sessionKey)
421 if err != nil {
422 mach.Log.Error("Failed to create inbound group session: %v", err)
423 return
424 } else if igs.ID() != sessionID {
425 mach.Log.Warn("Mismatched session ID while creating inbound group session")
426 return
427 }
428 err = mach.CryptoStore.PutGroupSession(roomID, senderKey, sessionID, igs)
429 if err != nil {
430 mach.Log.Error("Failed to store new inbound group session: %v", err)
431 return
432 }
433 mach.markSessionReceived(sessionID)
434 mach.Log.Debug("Received inbound group session %s / %s / %s", roomID, senderKey, sessionID)
435 }
436
437 func (mach *OlmMachine) markSessionReceived(id id.SessionID) {
438 mach.keyWaitersLock.Lock()
439 ch, ok := mach.keyWaiters[id]
440 if ok {
441 close(ch)
442 delete(mach.keyWaiters, id)
443 }
444 mach.keyWaitersLock.Unlock()
445 }
446
447 // WaitForSession waits for the given Megolm session to arrive.
448 func (mach *OlmMachine) WaitForSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, timeout time.Duration) bool {
449 mach.keyWaitersLock.Lock()
450 ch, ok := mach.keyWaiters[sessionID]
451 if !ok {
452 ch := make(chan struct{})
453 mach.keyWaiters[sessionID] = ch
454 }
455 mach.keyWaitersLock.Unlock()
456 select {
457 case <-ch:
458 return true
459 case <-time.After(timeout):
460 sess, err := mach.CryptoStore.GetGroupSession(roomID, senderKey, sessionID)
461 // Check if the session somehow appeared in the store without telling us
462 // We accept withheld sessions as received, as then the decryption attempt will show the error.
463 return sess != nil || errors.Is(err, ErrGroupSessionWithheld)
464 }
465 }
466
467 func (mach *OlmMachine) receiveRoomKey(evt *DecryptedOlmEvent, content *event.RoomKeyEventContent, traceID string) {
468 // TODO nio had a comment saying "handle this better" for the case where evt.Keys.Ed25519 is none?
469 if content.Algorithm != id.AlgorithmMegolmV1 || evt.Keys.Ed25519 == "" {
470 mach.Log.Debug("Ignoring weird room key from %s/%s: alg=%s, ed25519=%s, sessionid=%s, roomid=%s", evt.Sender, evt.SenderDevice, content.Algorithm, evt.Keys.Ed25519, content.SessionID, content.RoomID)
471 return
472 }
473
474 mach.createGroupSession(evt.SenderKey, evt.Keys.Ed25519, content.RoomID, content.SessionID, content.SessionKey, traceID)
475 }
476
477 func (mach *OlmMachine) handleRoomKeyWithheld(content *event.RoomKeyWithheldEventContent) {
478 if content.Algorithm != id.AlgorithmMegolmV1 {
479 mach.Log.Debug("Non-megolm room key withheld event: %+v", content)
480 return
481 }
482 err := mach.CryptoStore.PutWithheldGroupSession(*content)
483 if err != nil {
484 mach.Log.Error("Failed to save room key withheld event: %v", err)
485 }
486 }
487
488 // ShareKeys uploads necessary keys to the server.
489 //
490 // If the Olm account hasn't been shared, the account keys will be uploaded.
491 // If currentOTKCount is less than half of the limit (100 / 2 = 50), enough one-time keys will be uploaded so exactly
492 // half of the limit is filled.
493 func (mach *OlmMachine) ShareKeys(currentOTKCount int) error {
494 var deviceKeys *mautrix.DeviceKeys
495 if !mach.account.Shared {
496 deviceKeys = mach.account.getInitialKeys(mach.Client.UserID, mach.Client.DeviceID)
497 mach.Log.Trace("Going to upload initial account keys")
498 }
499 oneTimeKeys := mach.account.getOneTimeKeys(mach.Client.UserID, mach.Client.DeviceID, currentOTKCount)
500 if len(oneTimeKeys) == 0 && deviceKeys == nil {
501 mach.Log.Trace("No one-time keys nor device keys got when trying to share keys")
502 return nil
503 }
504 req := &mautrix.ReqUploadKeys{
505 DeviceKeys: deviceKeys,
506 OneTimeKeys: oneTimeKeys,
507 }
508 mach.Log.Trace("Uploading %d one-time keys", len(oneTimeKeys))
509 _, err := mach.Client.UploadKeys(req)
510 if err != nil {
511 return err
512 }
513 mach.account.Shared = true
514 mach.saveAccount()
515 return nil
516 }