| 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 | package crypto |
| 8 | |
| 9 | import ( |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "time" |
| 13 | |
| 14 | "maunium.net/go/mautrix/crypto/canonicaljson" |
| 15 | "maunium.net/go/mautrix/crypto/olm" |
| 16 | "maunium.net/go/mautrix/event" |
| 17 | "maunium.net/go/mautrix/id" |
| 18 | ) |
| 19 | |
| 20 | var ( |
| 21 | ErrNoVerificationFromDevice = errors.New("from_device field is empty") |
| 22 | ErrNoVerificationMethods = errors.New("verification method list is empty") |
| 23 | ErrNoRelatesTo = errors.New("missing m.relates_to info") |
| 24 | ) |
| 25 | |
| 26 | // ProcessInRoomVerification is a callback that is to be called when a client receives a message |
| 27 | // related to in-room verification. |
| 28 | // |
| 29 | // Currently this is not automatically called, so you must add the listener yourself. |
| 30 | // Note that in-room verification events are wrapped in m.room.encrypted, but this expects the decrypted events. |
| 31 | func (mach *OlmMachine) ProcessInRoomVerification(evt *event.Event) error { |
| 32 | if evt.Sender == mach.Client.UserID { |
| 33 | // nothing to do if the message is our own |
| 34 | return nil |
| 35 | } |
| 36 | if relatable, ok := evt.Content.Parsed.(event.Relatable); !ok || relatable.OptionalGetRelatesTo() == nil { |
| 37 | return ErrNoRelatesTo |
| 38 | } |
| 39 | |
| 40 | switch content := evt.Content.Parsed.(type) { |
| 41 | case *event.MessageEventContent: |
| 42 | if content.MsgType == event.MsgVerificationRequest { |
| 43 | if content.FromDevice == "" { |
| 44 | return ErrNoVerificationFromDevice |
| 45 | } |
| 46 | if content.Methods == nil { |
| 47 | return ErrNoVerificationMethods |
| 48 | } |
| 49 | |
| 50 | newContent := &event.VerificationRequestEventContent{ |
| 51 | FromDevice: content.FromDevice, |
| 52 | Methods: content.Methods, |
| 53 | Timestamp: evt.Timestamp, |
| 54 | TransactionID: evt.ID.String(), |
| 55 | } |
| 56 | mach.handleVerificationRequest(evt.Sender, newContent, evt.ID.String(), evt.RoomID) |
| 57 | } |
| 58 | case *event.VerificationStartEventContent: |
| 59 | mach.handleVerificationStart(evt.Sender, content, content.RelatesTo.EventID.String(), 10*time.Minute, evt.RoomID) |
| 60 | case *event.VerificationReadyEventContent: |
| 61 | mach.handleInRoomVerificationReady(evt.Sender, evt.RoomID, content, content.RelatesTo.EventID.String()) |
| 62 | case *event.VerificationAcceptEventContent: |
| 63 | mach.handleVerificationAccept(evt.Sender, content, content.RelatesTo.EventID.String()) |
| 64 | case *event.VerificationKeyEventContent: |
| 65 | mach.handleVerificationKey(evt.Sender, content, content.RelatesTo.EventID.String()) |
| 66 | case *event.VerificationMacEventContent: |
| 67 | mach.handleVerificationMAC(evt.Sender, content, content.RelatesTo.EventID.String()) |
| 68 | case *event.VerificationCancelEventContent: |
| 69 | mach.handleVerificationCancel(evt.Sender, content, content.RelatesTo.EventID.String()) |
| 70 | } |
| 71 | return nil |
| 72 | } |
| 73 | |
| 74 | // SendInRoomSASVerificationCancel is used to manually send an in-room SAS cancel message process with the given reason and cancellation code. |
| 75 | func (mach *OlmMachine) SendInRoomSASVerificationCancel(roomID id.RoomID, userID id.UserID, transactionID string, reason string, code event.VerificationCancelCode) error { |
| 76 | content := &event.VerificationCancelEventContent{ |
| 77 | RelatesTo: &event.RelatesTo{Type: event.RelReference, EventID: id.EventID(transactionID)}, |
| 78 | Reason: reason, |
| 79 | Code: code, |
| 80 | To: userID, |
| 81 | } |
| 82 | |
| 83 | encrypted, err := mach.EncryptMegolmEvent(roomID, event.InRoomVerificationCancel, content) |
| 84 | if err != nil { |
| 85 | return err |
| 86 | } |
| 87 | _, err = mach.Client.SendMessageEvent(roomID, event.EventEncrypted, encrypted) |
| 88 | return err |
| 89 | } |
| 90 | |
| 91 | // SendInRoomSASVerificationRequest is used to manually send an in-room SAS verification request message to another user. |
| 92 | func (mach *OlmMachine) SendInRoomSASVerificationRequest(roomID id.RoomID, toUserID id.UserID, methods []VerificationMethod) (string, error) { |
| 93 | content := &event.MessageEventContent{ |
| 94 | MsgType: event.MsgVerificationRequest, |
| 95 | FromDevice: mach.Client.DeviceID, |
| 96 | Methods: []event.VerificationMethod{event.VerificationMethodSAS}, |
| 97 | To: toUserID, |
| 98 | } |
| 99 | |
| 100 | encrypted, err := mach.EncryptMegolmEvent(roomID, event.EventMessage, content) |
| 101 | if err != nil { |
| 102 | return "", err |
| 103 | } |
| 104 | resp, err := mach.Client.SendMessageEvent(roomID, event.EventEncrypted, encrypted) |
| 105 | if err != nil { |
| 106 | return "", err |
| 107 | } |
| 108 | return resp.EventID.String(), nil |
| 109 | } |
| 110 | |
| 111 | // SendInRoomSASVerificationReady is used to manually send an in-room SAS verification ready message to another user. |
| 112 | func (mach *OlmMachine) SendInRoomSASVerificationReady(roomID id.RoomID, transactionID string) error { |
| 113 | content := &event.VerificationReadyEventContent{ |
| 114 | FromDevice: mach.Client.DeviceID, |
| 115 | Methods: []event.VerificationMethod{event.VerificationMethodSAS}, |
| 116 | RelatesTo: &event.RelatesTo{Type: event.RelReference, EventID: id.EventID(transactionID)}, |
| 117 | } |
| 118 | |
| 119 | encrypted, err := mach.EncryptMegolmEvent(roomID, event.InRoomVerificationReady, content) |
| 120 | if err != nil { |
| 121 | return err |
| 122 | } |
| 123 | _, err = mach.Client.SendMessageEvent(roomID, event.EventEncrypted, encrypted) |
| 124 | return err |
| 125 | } |
| 126 | |
| 127 | // SendInRoomSASVerificationStart is used to manually send the in-room SAS verification start message to another user. |
| 128 | func (mach *OlmMachine) SendInRoomSASVerificationStart(roomID id.RoomID, toUserID id.UserID, transactionID string, methods []VerificationMethod) (*event.VerificationStartEventContent, error) { |
| 129 | sasMethods := make([]event.SASMethod, len(methods)) |
| 130 | for i, method := range methods { |
| 131 | sasMethods[i] = method.Type() |
| 132 | } |
| 133 | content := &event.VerificationStartEventContent{ |
| 134 | FromDevice: mach.Client.DeviceID, |
| 135 | RelatesTo: &event.RelatesTo{Type: event.RelReference, EventID: id.EventID(transactionID)}, |
| 136 | Method: event.VerificationMethodSAS, |
| 137 | KeyAgreementProtocols: []event.KeyAgreementProtocol{event.KeyAgreementCurve25519HKDFSHA256}, |
| 138 | Hashes: []event.VerificationHashMethod{event.VerificationHashSHA256}, |
| 139 | MessageAuthenticationCodes: []event.MACMethod{event.HKDFHMACSHA256}, |
| 140 | ShortAuthenticationString: sasMethods, |
| 141 | To: toUserID, |
| 142 | } |
| 143 | |
| 144 | encrypted, err := mach.EncryptMegolmEvent(roomID, event.InRoomVerificationStart, content) |
| 145 | if err != nil { |
| 146 | return nil, err |
| 147 | } |
| 148 | _, err = mach.Client.SendMessageEvent(roomID, event.EventEncrypted, encrypted) |
| 149 | return content, err |
| 150 | } |
| 151 | |
| 152 | // SendInRoomSASVerificationAccept is used to manually send an accept for an in-room SAS verification process from a received m.key.verification.start event. |
| 153 | func (mach *OlmMachine) SendInRoomSASVerificationAccept(roomID id.RoomID, fromUser id.UserID, startEvent *event.VerificationStartEventContent, transactionID string, publicKey []byte, methods []VerificationMethod) error { |
| 154 | if startEvent.Method != event.VerificationMethodSAS { |
| 155 | reason := "Unknown verification method: " + string(startEvent.Method) |
| 156 | if err := mach.SendInRoomSASVerificationCancel(roomID, fromUser, transactionID, reason, event.VerificationCancelUnknownMethod); err != nil { |
| 157 | return err |
| 158 | } |
| 159 | return ErrUnknownVerificationMethod |
| 160 | } |
| 161 | payload, err := json.Marshal(startEvent) |
| 162 | if err != nil { |
| 163 | return err |
| 164 | } |
| 165 | canonical, err := canonicaljson.CanonicalJSON(payload) |
| 166 | if err != nil { |
| 167 | return err |
| 168 | } |
| 169 | hash := olm.NewUtility().Sha256(string(publicKey) + string(canonical)) |
| 170 | sasMethods := make([]event.SASMethod, len(methods)) |
| 171 | for i, method := range methods { |
| 172 | sasMethods[i] = method.Type() |
| 173 | } |
| 174 | content := &event.VerificationAcceptEventContent{ |
| 175 | RelatesTo: &event.RelatesTo{Type: event.RelReference, EventID: id.EventID(transactionID)}, |
| 176 | Method: event.VerificationMethodSAS, |
| 177 | KeyAgreementProtocol: event.KeyAgreementCurve25519HKDFSHA256, |
| 178 | Hash: event.VerificationHashSHA256, |
| 179 | MessageAuthenticationCode: event.HKDFHMACSHA256, |
| 180 | ShortAuthenticationString: sasMethods, |
| 181 | Commitment: hash, |
| 182 | To: fromUser, |
| 183 | } |
| 184 | |
| 185 | encrypted, err := mach.EncryptMegolmEvent(roomID, event.InRoomVerificationAccept, content) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | _, err = mach.Client.SendMessageEvent(roomID, event.EventEncrypted, encrypted) |
| 190 | return err |
| 191 | } |
| 192 | |
| 193 | // SendInRoomSASVerificationKey sends the ephemeral public key for a device to the partner device for an in-room verification. |
| 194 | func (mach *OlmMachine) SendInRoomSASVerificationKey(roomID id.RoomID, userID id.UserID, transactionID string, key string) error { |
| 195 | content := &event.VerificationKeyEventContent{ |
| 196 | RelatesTo: &event.RelatesTo{Type: event.RelReference, EventID: id.EventID(transactionID)}, |
| 197 | Key: key, |
| 198 | To: userID, |
| 199 | } |
| 200 | |
| 201 | encrypted, err := mach.EncryptMegolmEvent(roomID, event.InRoomVerificationKey, content) |
| 202 | if err != nil { |
| 203 | return err |
| 204 | } |
| 205 | _, err = mach.Client.SendMessageEvent(roomID, event.EventEncrypted, encrypted) |
| 206 | return err |
| 207 | } |
| 208 | |
| 209 | // SendInRoomSASVerificationMAC sends the MAC of a device's key to the partner device for an in-room verification. |
| 210 | func (mach *OlmMachine) SendInRoomSASVerificationMAC(roomID id.RoomID, userID id.UserID, deviceID id.DeviceID, transactionID string, sas *olm.SAS) error { |
| 211 | keyID := id.NewKeyID(id.KeyAlgorithmEd25519, mach.Client.DeviceID.String()) |
| 212 | |
| 213 | signingKey := mach.account.SigningKey() |
| 214 | keyIDsMap := map[id.KeyID]string{keyID: ""} |
| 215 | macMap := make(map[id.KeyID]string) |
| 216 | |
| 217 | if mach.CrossSigningKeys != nil { |
| 218 | masterKey := mach.CrossSigningKeys.MasterKey.PublicKey |
| 219 | masterKeyID := id.NewKeyID(id.KeyAlgorithmEd25519, masterKey.String()) |
| 220 | // add master key ID to key map |
| 221 | keyIDsMap[masterKeyID] = "" |
| 222 | masterKeyMAC, _, err := mach.getPKAndKeysMAC(sas, mach.Client.UserID, mach.Client.DeviceID, |
| 223 | userID, deviceID, transactionID, masterKey, masterKeyID, keyIDsMap) |
| 224 | if err != nil { |
| 225 | mach.Log.Error("Error generating master key MAC: %v", err) |
| 226 | } else { |
| 227 | mach.Log.Debug("Generated master key `%v` MAC: %v", masterKey, masterKeyMAC) |
| 228 | macMap[masterKeyID] = masterKeyMAC |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | pubKeyMac, keysMac, err := mach.getPKAndKeysMAC(sas, mach.Client.UserID, mach.Client.DeviceID, userID, deviceID, transactionID, signingKey, keyID, keyIDsMap) |
| 233 | if err != nil { |
| 234 | return err |
| 235 | } |
| 236 | mach.Log.Debug("MAC of key %s is: %s", signingKey, pubKeyMac) |
| 237 | mach.Log.Debug("MAC of key ID(s) %s is: %s", keyID, keysMac) |
| 238 | macMap[keyID] = pubKeyMac |
| 239 | |
| 240 | content := &event.VerificationMacEventContent{ |
| 241 | RelatesTo: &event.RelatesTo{Type: event.RelReference, EventID: id.EventID(transactionID)}, |
| 242 | Keys: keysMac, |
| 243 | Mac: macMap, |
| 244 | To: userID, |
| 245 | } |
| 246 | |
| 247 | encrypted, err := mach.EncryptMegolmEvent(roomID, event.InRoomVerificationMAC, content) |
| 248 | if err != nil { |
| 249 | return err |
| 250 | } |
| 251 | _, err = mach.Client.SendMessageEvent(roomID, event.EventEncrypted, encrypted) |
| 252 | return err |
| 253 | } |
| 254 | |
| 255 | // NewInRoomSASVerificationWith starts the in-room SAS verification process with another user in the given room. |
| 256 | // It returns the generated transaction ID. |
| 257 | func (mach *OlmMachine) NewInRoomSASVerificationWith(inRoomID id.RoomID, userID id.UserID, hooks VerificationHooks, timeout time.Duration) (string, error) { |
| 258 | return mach.newInRoomSASVerificationWithInner(inRoomID, &DeviceIdentity{UserID: userID}, hooks, "", timeout) |
| 259 | } |
| 260 | |
| 261 | func (mach *OlmMachine) newInRoomSASVerificationWithInner(inRoomID id.RoomID, device *DeviceIdentity, hooks VerificationHooks, transactionID string, timeout time.Duration) (string, error) { |
| 262 | mach.Log.Debug("Starting new in-room verification transaction user %v", device.UserID) |
| 263 | |
| 264 | request := transactionID == "" |
| 265 | if request { |
| 266 | var err error |
| 267 | // get new transaction ID from the request message event ID |
| 268 | transactionID, err = mach.SendInRoomSASVerificationRequest(inRoomID, device.UserID, hooks.VerificationMethods()) |
| 269 | if err != nil { |
| 270 | return "", err |
| 271 | } |
| 272 | } |
| 273 | verState := &verificationState{ |
| 274 | sas: olm.NewSAS(), |
| 275 | otherDevice: device, |
| 276 | initiatedByUs: true, |
| 277 | verificationStarted: false, |
| 278 | keyReceived: false, |
| 279 | sasMatched: make(chan bool, 1), |
| 280 | hooks: hooks, |
| 281 | inRoomID: inRoomID, |
| 282 | } |
| 283 | verState.lock.Lock() |
| 284 | defer verState.lock.Unlock() |
| 285 | |
| 286 | if !request { |
| 287 | // start in-room verification |
| 288 | startEvent, err := mach.SendInRoomSASVerificationStart(inRoomID, device.UserID, transactionID, hooks.VerificationMethods()) |
| 289 | if err != nil { |
| 290 | return "", err |
| 291 | } |
| 292 | |
| 293 | payload, err := json.Marshal(startEvent) |
| 294 | if err != nil { |
| 295 | return "", err |
| 296 | } |
| 297 | canonical, err := canonicaljson.CanonicalJSON(payload) |
| 298 | if err != nil { |
| 299 | return "", err |
| 300 | } |
| 301 | |
| 302 | verState.startEventCanonical = string(canonical) |
| 303 | } |
| 304 | |
| 305 | mach.keyVerificationTransactionState.Store(device.UserID.String()+":"+transactionID, verState) |
| 306 | |
| 307 | mach.timeoutAfter(verState, transactionID, timeout) |
| 308 | |
| 309 | return transactionID, nil |
| 310 | } |
| 311 | |
| 312 | func (mach *OlmMachine) handleInRoomVerificationReady(userID id.UserID, roomID id.RoomID, content *event.VerificationReadyEventContent, transactionID string) { |
| 313 | device, err := mach.GetOrFetchDevice(userID, content.FromDevice) |
| 314 | if err != nil { |
| 315 | mach.Log.Error("Error fetching device %v of user %v: %v", content.FromDevice, userID, err) |
| 316 | return |
| 317 | } |
| 318 | |
| 319 | verState, err := mach.getTransactionState(transactionID, userID) |
| 320 | if err != nil { |
| 321 | mach.Log.Error("Error getting transaction state: %v", err) |
| 322 | return |
| 323 | } |
| 324 | //mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 325 | |
| 326 | if mach.Client.UserID < userID { |
| 327 | // up to us to send the start message |
| 328 | verState.lock.Lock() |
| 329 | mach.newInRoomSASVerificationWithInner(roomID, device, verState.hooks, transactionID, 10*time.Minute) |
| 330 | verState.lock.Unlock() |
| 331 | } |
| 332 | } |