Debian Codegraph @

crypto/keysharing.go

raw
1 // Copyright (c) 2020 Nikos Filippakis
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 //go:build !nosas
8 // +build !nosas
9
10 package crypto
11
12 import (
13 "context"
14
15 "maunium.net/go/mautrix/crypto/olm"
16 "maunium.net/go/mautrix/id"
17
18 "maunium.net/go/mautrix"
19 "maunium.net/go/mautrix/event"
20 )
21
22 type KeyShareRejection struct {
23 Code event.RoomKeyWithheldCode
24 Reason string
25 }
26
27 var (
28 // Reject a key request without responding
29 KeyShareRejectNoResponse = KeyShareRejection{}
30
31 KeyShareRejectBlacklisted = KeyShareRejection{event.RoomKeyWithheldBlacklisted, "You have been blacklisted by this device"}
32 KeyShareRejectUnverified = KeyShareRejection{event.RoomKeyWithheldUnverified, "You have not been verified by this device"}
33 KeyShareRejectOtherUser = KeyShareRejection{event.RoomKeyWithheldUnauthorized, "This device does not share keys to other users"}
34 KeyShareRejectUnavailable = KeyShareRejection{event.RoomKeyWithheldUnavailable, "Requested session ID not found on this device"}
35 KeyShareRejectInternalError = KeyShareRejection{event.RoomKeyWithheldUnavailable, "An internal error occurred while trying to share the requested session"}
36 )
37
38 // RequestRoomKey sends a key request for a room to the current user's devices. If the context is cancelled, then so is the key request.
39 // Returns a bool channel that will get notified either when the key is received or the request is cancelled.
40 //
41 // Deprecated: this only supports a single key request target, so the whole automatic cancelling feature isn't very useful.
42 func (mach *OlmMachine) RequestRoomKey(ctx context.Context, toUser id.UserID, toDevice id.DeviceID,
43 roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (chan bool, error) {
44
45 requestID := mach.Client.TxnID()
46 keyResponseReceived := make(chan struct{})
47 mach.roomKeyRequestFilled.Store(sessionID, keyResponseReceived)
48
49 err := mach.SendRoomKeyRequest(roomID, senderKey, sessionID, requestID, map[id.UserID][]id.DeviceID{toUser: {toDevice}})
50 if err != nil {
51 return nil, err
52 }
53
54 resChan := make(chan bool, 1)
55 go func() {
56 select {
57 case <-keyResponseReceived:
58 // key request successful
59 mach.Log.Debug("Key for session %v was received, cancelling other key requests", sessionID)
60 resChan <- true
61 case <-ctx.Done():
62 // if the context is done, key request was unsuccessful
63 mach.Log.Debug("Context closed (%v) before forwared key for session %v received, sending key request cancellation", ctx.Err(), sessionID)
64 resChan <- false
65 }
66
67 // send a message to all devices cancelling this key request
68 mach.roomKeyRequestFilled.Delete(sessionID)
69
70 cancelEvtContent := &event.Content{
71 Parsed: event.RoomKeyRequestEventContent{
72 Action: event.KeyRequestActionCancel,
73 RequestID: requestID,
74 RequestingDeviceID: mach.Client.DeviceID,
75 },
76 }
77
78 toDeviceCancel := &mautrix.ReqSendToDevice{
79 Messages: map[id.UserID]map[id.DeviceID]*event.Content{
80 toUser: {
81 toDevice: cancelEvtContent,
82 },
83 },
84 }
85
86 mach.Client.SendToDevice(event.ToDeviceRoomKeyRequest, toDeviceCancel)
87 }()
88 return resChan, nil
89 }
90
91 // SendRoomKeyRequest sends a key request for the given key (identified by the room ID, sender key and session ID) to the given users.
92 //
93 // The request ID parameter is optional. If it's empty, a random ID will be generated.
94 //
95 // This function does not wait for the keys to arrive. You can use WaitForSession to wait for the session to
96 // arrive (in any way, not just as a reply to this request). There's also RequestRoomKey which waits for a response
97 // to the specific key request, but currently it only supports a single target device and is therefore deprecated.
98 // A future function may properly support multiple targets and automatically canceling the other requests when receiving
99 // the first response.
100 func (mach *OlmMachine) SendRoomKeyRequest(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, requestID string, users map[id.UserID][]id.DeviceID) error {
101 if len(requestID) == 0 {
102 requestID = mach.Client.TxnID()
103 }
104 requestEvent := &event.Content{
105 Parsed: &event.RoomKeyRequestEventContent{
106 Action: event.KeyRequestActionRequest,
107 Body: event.RequestedKeyInfo{
108 Algorithm: id.AlgorithmMegolmV1,
109 RoomID: roomID,
110 SenderKey: senderKey,
111 SessionID: sessionID,
112 },
113 RequestID: requestID,
114 RequestingDeviceID: mach.Client.DeviceID,
115 },
116 }
117
118 toDeviceReq := &mautrix.ReqSendToDevice{
119 Messages: make(map[id.UserID]map[id.DeviceID]*event.Content, len(users)),
120 }
121 for user, devices := range users {
122 toDeviceReq.Messages[user] = make(map[id.DeviceID]*event.Content, len(devices))
123 for _, device := range devices {
124 toDeviceReq.Messages[user][device] = requestEvent
125 }
126 }
127 _, err := mach.Client.SendToDevice(event.ToDeviceRoomKeyRequest, toDeviceReq)
128 return err
129 }
130
131 func (mach *OlmMachine) importForwardedRoomKey(evt *DecryptedOlmEvent, content *event.ForwardedRoomKeyEventContent) bool {
132 if content.Algorithm != id.AlgorithmMegolmV1 || evt.Keys.Ed25519 == "" {
133 mach.Log.Debug("Ignoring weird forwarded 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)
134 return false
135 }
136
137 igsInternal, err := olm.InboundGroupSessionImport([]byte(content.SessionKey))
138 if err != nil {
139 mach.Log.Error("Failed to import inbound group session: %v", err)
140 return false
141 } else if igsInternal.ID() != content.SessionID {
142 mach.Log.Warn("Mismatched session ID while creating inbound group session")
143 return false
144 }
145 igs := &InboundGroupSession{
146 Internal: *igsInternal,
147 SigningKey: evt.Keys.Ed25519,
148 SenderKey: content.SenderKey,
149 RoomID: content.RoomID,
150 ForwardingChains: append(content.ForwardingKeyChain, evt.SenderKey.String()),
151 id: content.SessionID,
152 }
153 err = mach.CryptoStore.PutGroupSession(content.RoomID, content.SenderKey, content.SessionID, igs)
154 if err != nil {
155 mach.Log.Error("Failed to store new inbound group session: %v", err)
156 return false
157 }
158 mach.markSessionReceived(content.SessionID)
159 mach.Log.Trace("Received forwarded inbound group session %s/%s/%s", content.RoomID, content.SenderKey, content.SessionID)
160 return true
161 }
162
163 func (mach *OlmMachine) rejectKeyRequest(rejection KeyShareRejection, device *DeviceIdentity, request event.RequestedKeyInfo) {
164 if rejection.Code == "" {
165 // If the rejection code is empty, it means don't share keys, but also don't tell the requester.
166 return
167 }
168 content := event.RoomKeyWithheldEventContent{
169 RoomID: request.RoomID,
170 Algorithm: request.Algorithm,
171 SessionID: request.SessionID,
172 SenderKey: request.SenderKey,
173 Code: rejection.Code,
174 Reason: rejection.Reason,
175 }
176 err := mach.sendToOneDevice(device.UserID, device.DeviceID, event.ToDeviceRoomKeyWithheld, &content)
177 if err != nil {
178 mach.Log.Warn("Failed to send key share rejection %s to %s/%s: %v", rejection.Code, device.UserID, device.DeviceID, err)
179 }
180 err = mach.sendToOneDevice(device.UserID, device.DeviceID, event.ToDeviceOrgMatrixRoomKeyWithheld, &content)
181 if err != nil {
182 mach.Log.Warn("Failed to send key share rejection %s (org.matrix.) to %s/%s: %v", rejection.Code, device.UserID, device.DeviceID, err)
183 }
184 }
185
186 func (mach *OlmMachine) defaultAllowKeyShare(device *DeviceIdentity, _ event.RequestedKeyInfo) *KeyShareRejection {
187 if mach.Client.UserID != device.UserID {
188 mach.Log.Debug("Ignoring key request from a different user (%s)", device.UserID)
189 return &KeyShareRejectOtherUser
190 } else if mach.Client.DeviceID == device.DeviceID {
191 mach.Log.Debug("Ignoring key request from ourselves")
192 return &KeyShareRejectNoResponse
193 } else if device.Trust == TrustStateBlacklisted {
194 mach.Log.Debug("Ignoring key request from blacklisted device %s", device.DeviceID)
195 return &KeyShareRejectBlacklisted
196 } else if mach.IsDeviceTrusted(device) {
197 mach.Log.Debug("Accepting key request from verified device %s", device.DeviceID)
198 return nil
199 } else if mach.ShareKeysToUnverifiedDevices {
200 mach.Log.Debug("Accepting key request from unverified device %s (ShareKeysToUnverifiedDevices is true)", device.DeviceID)
201 return nil
202 } else {
203 mach.Log.Debug("Ignoring key request from unverified device %s", device.DeviceID)
204 return &KeyShareRejectUnverified
205 }
206 }
207
208 func (mach *OlmMachine) handleRoomKeyRequest(sender id.UserID, content *event.RoomKeyRequestEventContent) {
209 if content.Action != event.KeyRequestActionRequest {
210 return
211 } else if content.RequestingDeviceID == mach.Client.DeviceID && sender == mach.Client.UserID {
212 mach.Log.Debug("Ignoring key request %s from ourselves", content.RequestID)
213 return
214 }
215
216 mach.Log.Debug("Received key request %s for %s from %s/%s", content.RequestID, content.Body.SessionID, sender, content.RequestingDeviceID)
217
218 device, err := mach.GetOrFetchDevice(sender, content.RequestingDeviceID)
219 if err != nil {
220 mach.Log.Error("Failed to fetch device %s/%s that requested keys: %v", sender, content.RequestingDeviceID, err)
221 return
222 }
223
224 rejection := mach.AllowKeyShare(device, content.Body)
225 if rejection != nil {
226 mach.rejectKeyRequest(*rejection, device, content.Body)
227 return
228 }
229
230 igs, err := mach.CryptoStore.GetGroupSession(content.Body.RoomID, content.Body.SenderKey, content.Body.SessionID)
231 if err != nil {
232 mach.Log.Error("Failed to fetch group session to forward to %s/%s: %v", device.UserID, device.DeviceID, err)
233 mach.rejectKeyRequest(KeyShareRejectInternalError, device, content.Body)
234 return
235 } else if igs == nil {
236 mach.Log.Warn("Didn't find group session %s to forward to %s/%s", content.Body.SessionID, device.UserID, device.DeviceID)
237 mach.rejectKeyRequest(KeyShareRejectUnavailable, device, content.Body)
238 return
239 }
240
241 exportedKey, err := igs.Internal.Export(igs.Internal.FirstKnownIndex())
242 if err != nil {
243 mach.Log.Error("Failed to export session %s to forward to %s/%s: %v", igs.ID(), device.UserID, device.DeviceID, err)
244 mach.rejectKeyRequest(KeyShareRejectInternalError, device, content.Body)
245 return
246 }
247
248 forwardedRoomKey := event.Content{
249 Parsed: &event.ForwardedRoomKeyEventContent{
250 RoomKeyEventContent: event.RoomKeyEventContent{
251 Algorithm: id.AlgorithmMegolmV1,
252 RoomID: igs.RoomID,
253 SessionID: igs.ID(),
254 SessionKey: exportedKey,
255 },
256 SenderKey: content.Body.SenderKey,
257 ForwardingKeyChain: igs.ForwardingChains,
258 SenderClaimedKey: igs.SigningKey,
259 },
260 }
261
262 if err := mach.SendEncryptedToDevice(device, event.ToDeviceForwardedRoomKey, forwardedRoomKey); err != nil {
263 mach.Log.Error("Failed to send encrypted forwarded key %s to %s/%s: %v", igs.ID(), device.UserID, device.DeviceID, err)
264 }
265
266 mach.Log.Debug("Sent encrypted forwarded key to device %s/%s for session %s", device.UserID, device.DeviceID, igs.ID())
267 }