Debian Codegraph @

crypto/encryptmegolm.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 "encoding/json"
11 "errors"
12 "fmt"
13
14 "maunium.net/go/mautrix"
15 "maunium.net/go/mautrix/event"
16 "maunium.net/go/mautrix/id"
17 )
18
19 var (
20 AlreadyShared = errors.New("group session already shared")
21 NoGroupSession = errors.New("no group session created")
22 )
23
24 func getRelatesTo(content interface{}) *event.RelatesTo {
25 contentStruct, ok := content.(*event.Content)
26 if ok {
27 content = contentStruct.Parsed
28 }
29 relatable, ok := content.(event.Relatable)
30 if ok {
31 return relatable.OptionalGetRelatesTo()
32 }
33 return nil
34 }
35
36 type rawMegolmEvent struct {
37 RoomID id.RoomID `json:"room_id"`
38 Type event.Type `json:"type"`
39 Content interface{} `json:"content"`
40 }
41
42 // IsShareError returns true if the error is caused by the lack of an outgoing megolm session and can be solved with OlmMachine.ShareGroupSession
43 func IsShareError(err error) bool {
44 return err == SessionExpired || err == SessionNotShared || err == NoGroupSession
45 }
46
47 // EncryptMegolmEvent encrypts data with the m.megolm.v1.aes-sha2 algorithm.
48 //
49 // If you use the event.Content struct, make sure you pass a pointer to the struct,
50 // as JSON serialization will not work correctly otherwise.
51 func (mach *OlmMachine) EncryptMegolmEvent(roomID id.RoomID, evtType event.Type, content interface{}) (*event.EncryptedEventContent, error) {
52 mach.Log.Trace("Encrypting event of type %s for %s", evtType.Type, roomID)
53 session, err := mach.CryptoStore.GetOutboundGroupSession(roomID)
54 if err != nil {
55 return nil, fmt.Errorf("failed to get outbound group session: %w", err)
56 } else if session == nil {
57 return nil, NoGroupSession
58 }
59 plaintext, err := json.Marshal(&rawMegolmEvent{
60 RoomID: roomID,
61 Type: evtType,
62 Content: content,
63 })
64 if err != nil {
65 return nil, err
66 }
67 ciphertext, err := session.Encrypt(plaintext)
68 if err != nil {
69 return nil, err
70 }
71 err = mach.CryptoStore.UpdateOutboundGroupSession(session)
72 if err != nil {
73 mach.Log.Warn("Failed to update megolm session in crypto store after encrypting: %v", err)
74 }
75 return &event.EncryptedEventContent{
76 Algorithm: id.AlgorithmMegolmV1,
77 SenderKey: mach.account.IdentityKey(),
78 DeviceID: mach.Client.DeviceID,
79 SessionID: session.ID(),
80 MegolmCiphertext: ciphertext,
81 RelatesTo: getRelatesTo(content),
82 }, nil
83 }
84
85 func (mach *OlmMachine) newOutboundGroupSession(roomID id.RoomID) *OutboundGroupSession {
86 session := NewOutboundGroupSession(roomID, mach.StateStore.GetEncryptionEvent(roomID))
87 signingKey, idKey := mach.account.Keys()
88 mach.createGroupSession(idKey, signingKey, roomID, session.ID(), session.Internal.Key(), "create")
89 return session
90 }
91
92 type deviceSessionWrapper struct {
93 session *OlmSession
94 identity *DeviceIdentity
95 }
96
97 // ShareGroupSession shares a group session for a specific room with all the devices of the given user list.
98 //
99 // For devices with TrustStateBlacklisted, a m.room_key.withheld event with code=m.blacklisted is sent.
100 // If AllowUnverifiedDevices is false, a similar event with code=m.unverified is sent to devices with TrustStateUnset
101 func (mach *OlmMachine) ShareGroupSession(roomID id.RoomID, users []id.UserID) error {
102 mach.Log.Debug("Sharing group session for room %s to %v", roomID, users)
103 session, err := mach.CryptoStore.GetOutboundGroupSession(roomID)
104 if err != nil {
105 return fmt.Errorf("failed to get previous outbound group session: %w", err)
106 } else if session != nil && session.Shared && !session.Expired() {
107 return AlreadyShared
108 }
109 if session == nil || session.Expired() {
110 session = mach.newOutboundGroupSession(roomID)
111 }
112
113 withheldCount := 0
114 toDeviceWithheld := &mautrix.ReqSendToDevice{Messages: make(map[id.UserID]map[id.DeviceID]*event.Content)}
115 olmSessions := make(map[id.UserID]map[id.DeviceID]deviceSessionWrapper)
116 missingSessions := make(map[id.UserID]map[id.DeviceID]*DeviceIdentity)
117 missingUserSessions := make(map[id.DeviceID]*DeviceIdentity)
118 var fetchKeys []id.UserID
119
120 for _, userID := range users {
121 devices, err := mach.CryptoStore.GetDevices(userID)
122 if err != nil {
123 mach.Log.Error("Failed to get devices of %s", userID)
124 } else if devices == nil {
125 mach.Log.Trace("GetDevices returned nil for %s, will fetch keys and retry", userID)
126 fetchKeys = append(fetchKeys, userID)
127 } else if len(devices) == 0 {
128 mach.Log.Trace("%s has no devices, skipping", userID)
129 } else {
130 mach.Log.Trace("Trying to find olm sessions to encrypt %s for %s", session.ID(), userID)
131 toDeviceWithheld.Messages[userID] = make(map[id.DeviceID]*event.Content)
132 olmSessions[userID] = make(map[id.DeviceID]deviceSessionWrapper)
133 mach.findOlmSessionsForUser(session, userID, devices, olmSessions[userID], toDeviceWithheld.Messages[userID], missingUserSessions)
134 mach.Log.Trace("Found %d sessions, withholding from %d sessions and missing %d sessions to encrypt %s for for %s", len(olmSessions[userID]), len(toDeviceWithheld.Messages[userID]), len(missingUserSessions), session.ID(), userID)
135 withheldCount += len(toDeviceWithheld.Messages[userID])
136 if len(missingUserSessions) > 0 {
137 missingSessions[userID] = missingUserSessions
138 missingUserSessions = make(map[id.DeviceID]*DeviceIdentity)
139 }
140 if len(toDeviceWithheld.Messages[userID]) == 0 {
141 delete(toDeviceWithheld.Messages, userID)
142 }
143 }
144 }
145
146 if len(fetchKeys) > 0 {
147 mach.Log.Trace("Fetching missing keys for %v", fetchKeys)
148 for userID, devices := range mach.fetchKeys(fetchKeys, "", true) {
149 mach.Log.Trace("Got %d device keys for %s", len(devices), userID)
150 missingSessions[userID] = devices
151 }
152 }
153
154 if len(missingSessions) > 0 {
155 mach.Log.Trace("Creating missing outbound sessions")
156 err = mach.createOutboundSessions(missingSessions)
157 if err != nil {
158 mach.Log.Error("Failed to create missing outbound sessions: %v", err)
159 }
160 }
161
162 for userID, devices := range missingSessions {
163 if len(devices) == 0 {
164 // No missing sessions
165 continue
166 }
167 output, ok := olmSessions[userID]
168 if !ok {
169 output = make(map[id.DeviceID]deviceSessionWrapper)
170 olmSessions[userID] = output
171 }
172 withheld, ok := toDeviceWithheld.Messages[userID]
173 if !ok {
174 withheld = make(map[id.DeviceID]*event.Content)
175 toDeviceWithheld.Messages[userID] = withheld
176 }
177 mach.Log.Trace("Trying to find olm sessions to encrypt %s for %s (post-fetch retry)", session.ID(), userID)
178 mach.findOlmSessionsForUser(session, userID, devices, output, withheld, nil)
179 mach.Log.Trace("Found %d sessions and withholding from %d sessions to encrypt %s for for %s (post-fetch retry)", len(output), len(withheld), session.ID(), userID)
180 withheldCount += len(toDeviceWithheld.Messages[userID])
181 if len(toDeviceWithheld.Messages[userID]) == 0 {
182 delete(toDeviceWithheld.Messages, userID)
183 }
184 }
185
186 err = mach.encryptAndSendGroupSession(session, olmSessions)
187 if err != nil {
188 return fmt.Errorf("failed to share group session: %w", err)
189 }
190
191 if len(toDeviceWithheld.Messages) > 0 {
192 mach.Log.Trace("Sending to-device messages to %d devices of %d users to report withheld keys in %s", withheldCount, len(toDeviceWithheld.Messages), roomID)
193 // TODO remove the next 4 lines once clients support m.room_key.withheld
194 _, err = mach.Client.SendToDevice(event.ToDeviceOrgMatrixRoomKeyWithheld, toDeviceWithheld)
195 if err != nil {
196 mach.Log.Warn("Failed to report withheld keys in %s (legacy event type): %v", roomID, err)
197 }
198 _, err = mach.Client.SendToDevice(event.ToDeviceRoomKeyWithheld, toDeviceWithheld)
199 if err != nil {
200 mach.Log.Warn("Failed to report withheld keys in %s: %v", roomID, err)
201 }
202 }
203
204 mach.Log.Debug("Group session %s for %s successfully shared", session.ID(), roomID)
205 session.Shared = true
206 return mach.CryptoStore.AddOutboundGroupSession(session)
207 }
208
209 func (mach *OlmMachine) encryptAndSendGroupSession(session *OutboundGroupSession, olmSessions map[id.UserID]map[id.DeviceID]deviceSessionWrapper) error {
210 mach.olmLock.Lock()
211 defer mach.olmLock.Unlock()
212 mach.Log.Trace("Encrypting group session %s for all found devices", session.ID())
213 deviceCount := 0
214 toDevice := &mautrix.ReqSendToDevice{Messages: make(map[id.UserID]map[id.DeviceID]*event.Content)}
215 for userID, sessions := range olmSessions {
216 if len(sessions) == 0 {
217 continue
218 }
219 output := make(map[id.DeviceID]*event.Content)
220 toDevice.Messages[userID] = output
221 for deviceID, device := range sessions {
222 mach.Log.Trace("Encrypting group session %s for %s of %s", session.ID(), deviceID, userID)
223 content := mach.encryptOlmEvent(device.session, device.identity, event.ToDeviceRoomKey, session.ShareContent())
224 output[deviceID] = &event.Content{Parsed: content}
225 deviceCount++
226 mach.Log.Trace("Encrypted group session %s for %s of %s", session.ID(), deviceID, userID)
227 }
228 }
229
230 mach.Log.Trace("Sending to-device to %d devices of %d users to share group session %s", deviceCount, len(toDevice.Messages), session.ID())
231 _, err := mach.Client.SendToDevice(event.ToDeviceEncrypted, toDevice)
232 return err
233 }
234
235 func (mach *OlmMachine) findOlmSessionsForUser(session *OutboundGroupSession, userID id.UserID, devices map[id.DeviceID]*DeviceIdentity, output map[id.DeviceID]deviceSessionWrapper, withheld map[id.DeviceID]*event.Content, missingOutput map[id.DeviceID]*DeviceIdentity) {
236 for deviceID, device := range devices {
237 userKey := UserDevice{UserID: userID, DeviceID: deviceID}
238 if state := session.Users[userKey]; state != OGSNotShared {
239 continue
240 } else if userID == mach.Client.UserID && deviceID == mach.Client.DeviceID {
241 session.Users[userKey] = OGSIgnored
242 } else if device.Trust == TrustStateBlacklisted {
243 mach.Log.Debug("Not encrypting group session %s for %s of %s: device is blacklisted", session.ID(), deviceID, userID)
244 withheld[deviceID] = &event.Content{Parsed: &event.RoomKeyWithheldEventContent{
245 RoomID: session.RoomID,
246 Algorithm: id.AlgorithmMegolmV1,
247 SessionID: session.ID(),
248 SenderKey: mach.account.IdentityKey(),
249 Code: event.RoomKeyWithheldBlacklisted,
250 Reason: "Device is blacklisted",
251 }}
252 session.Users[userKey] = OGSIgnored
253 } else if !mach.AllowUnverifiedDevices && !mach.IsDeviceTrusted(device) {
254 mach.Log.Debug("Not encrypting group session %s for %s of %s: device is not verified", session.ID(), deviceID, userID)
255 withheld[deviceID] = &event.Content{Parsed: &event.RoomKeyWithheldEventContent{
256 RoomID: session.RoomID,
257 Algorithm: id.AlgorithmMegolmV1,
258 SessionID: session.ID(),
259 SenderKey: mach.account.IdentityKey(),
260 Code: event.RoomKeyWithheldUnverified,
261 Reason: "This device does not encrypt messages for unverified devices",
262 }}
263 session.Users[userKey] = OGSIgnored
264 } else if deviceSession, err := mach.CryptoStore.GetLatestSession(device.IdentityKey); err != nil {
265 mach.Log.Error("Failed to get session for %s of %s: %v", deviceID, userID, err)
266 } else if deviceSession == nil {
267 mach.Log.Warn("Didn't find a session for %s of %s", deviceID, userID)
268 if missingOutput != nil {
269 missingOutput[deviceID] = device
270 }
271 } else {
272 output[deviceID] = deviceSessionWrapper{
273 session: deviceSession,
274 identity: device,
275 }
276 session.Users[userKey] = OGSAlreadyShared
277 }
278 }
279 }