| 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 |
"encoding/json" |
| 15 |
"errors" |
| 16 |
"fmt" |
| 17 |
"math/rand" |
| 18 |
"sort" |
| 19 |
"strconv" |
| 20 |
"strings" |
| 21 |
"sync" |
| 22 |
"time" |
| 23 |
|
| 24 |
"maunium.net/go/mautrix" |
| 25 |
"maunium.net/go/mautrix/crypto/canonicaljson" |
| 26 |
"maunium.net/go/mautrix/crypto/olm" |
| 27 |
"maunium.net/go/mautrix/event" |
| 28 |
"maunium.net/go/mautrix/id" |
| 29 |
) |
| 30 |
|
| 31 |
var ( |
| 32 |
ErrUnknownUserForTransaction = errors.New("unknown user for transaction") |
| 33 |
ErrTransactionAlreadyExists = errors.New("transaction already exists") |
| 34 |
// ErrUnknownTransaction is returned when a key verification message is received with an unknown transaction ID. |
| 35 |
ErrUnknownTransaction = errors.New("unknown transaction") |
| 36 |
// ErrUnknownVerificationMethod is returned when the verification method in a received m.key.verification.start is unknown. |
| 37 |
ErrUnknownVerificationMethod = errors.New("unknown verification method") |
| 38 |
) |
| 39 |
|
| 40 |
type VerificationHooks interface { |
| 41 |
// VerifySASMatch receives the generated SAS and its method, as well as the device that is being verified. |
| 42 |
// It returns whether the given SAS match with the SAS displayed on other device. |
| 43 |
VerifySASMatch(otherDevice *DeviceIdentity, sas SASData) bool |
| 44 |
// VerificationMethods returns the list of supported verification methods in order of preference. |
| 45 |
// It must contain at least the decimal method. |
| 46 |
VerificationMethods() []VerificationMethod |
| 47 |
OnCancel(cancelledByUs bool, reason string, reasonCode event.VerificationCancelCode) |
| 48 |
OnSuccess() |
| 49 |
} |
| 50 |
|
| 51 |
type VerificationRequestResponse int |
| 52 |
|
| 53 |
const ( |
| 54 |
AcceptRequest VerificationRequestResponse = iota |
| 55 |
RejectRequest |
| 56 |
IgnoreRequest |
| 57 |
) |
| 58 |
|
| 59 |
// sendToOneDevice sends a to-device event to a single device. |
| 60 |
func (mach *OlmMachine) sendToOneDevice(userID id.UserID, deviceID id.DeviceID, eventType event.Type, content interface{}) error { |
| 61 |
_, err := mach.Client.SendToDevice(eventType, &mautrix.ReqSendToDevice{ |
| 62 |
Messages: map[id.UserID]map[id.DeviceID]*event.Content{ |
| 63 |
userID: { |
| 64 |
deviceID: { |
| 65 |
Parsed: content, |
| 66 |
}, |
| 67 |
}, |
| 68 |
}, |
| 69 |
}) |
| 70 |
|
| 71 |
return err |
| 72 |
} |
| 73 |
|
| 74 |
func (mach *OlmMachine) getPKAndKeysMAC(sas *olm.SAS, sendingUser id.UserID, sendingDevice id.DeviceID, receivingUser id.UserID, receivingDevice id.DeviceID, |
| 75 |
transactionID string, signingKey id.SigningKey, mainKeyID id.KeyID, keys map[id.KeyID]string) (string, string, error) { |
| 76 |
sasInfo := "MATRIX_KEY_VERIFICATION_MAC" + |
| 77 |
sendingUser.String() + sendingDevice.String() + |
| 78 |
receivingUser.String() + receivingDevice.String() + |
| 79 |
transactionID |
| 80 |
|
| 81 |
// get key IDs from key map |
| 82 |
keyIDStrings := make([]string, len(keys)) |
| 83 |
i := 0 |
| 84 |
for keyID := range keys { |
| 85 |
keyIDStrings[i] = keyID.String() |
| 86 |
i++ |
| 87 |
} |
| 88 |
sort.Sort(sort.StringSlice(keyIDStrings)) |
| 89 |
keyIDString := strings.Join(keyIDStrings, ",") |
| 90 |
|
| 91 |
pubKeyMac, err := sas.CalculateMAC([]byte(signingKey), []byte(sasInfo+mainKeyID.String())) |
| 92 |
if err != nil { |
| 93 |
return "", "", err |
| 94 |
} |
| 95 |
mach.Log.Trace("sas.CalculateMAC(\"%s\", \"%s\") -> \"%s\"", signingKey, sasInfo+mainKeyID.String(), string(pubKeyMac)) |
| 96 |
|
| 97 |
keysMac, err := sas.CalculateMAC([]byte(keyIDString), []byte(sasInfo+"KEY_IDS")) |
| 98 |
if err != nil { |
| 99 |
return "", "", err |
| 100 |
} |
| 101 |
mach.Log.Trace("sas.CalculateMAC(\"%s\", \"%s\") -> \"%s\"", keyIDString, sasInfo+"KEY_IDS", string(keysMac)) |
| 102 |
|
| 103 |
return string(pubKeyMac), string(keysMac), nil |
| 104 |
} |
| 105 |
|
| 106 |
// verificationState holds all the information needed for the state of a SAS verification with another device. |
| 107 |
type verificationState struct { |
| 108 |
sas *olm.SAS |
| 109 |
otherDevice *DeviceIdentity |
| 110 |
initiatedByUs bool |
| 111 |
verificationStarted bool |
| 112 |
keyReceived bool |
| 113 |
sasMatched chan bool |
| 114 |
commitment string |
| 115 |
startEventCanonical string |
| 116 |
chosenSASMethod VerificationMethod |
| 117 |
hooks VerificationHooks |
| 118 |
extendTimeout context.CancelFunc |
| 119 |
inRoomID id.RoomID |
| 120 |
lock sync.Mutex |
| 121 |
} |
| 122 |
|
| 123 |
// getTransactionState retrieves the given transaction's state, or cancels the transaction if it cannot be found or there is a mismatch. |
| 124 |
func (mach *OlmMachine) getTransactionState(transactionID string, userID id.UserID) (*verificationState, error) { |
| 125 |
verStateInterface, ok := mach.keyVerificationTransactionState.Load(userID.String() + ":" + transactionID) |
| 126 |
if !ok { |
| 127 |
_ = mach.SendSASVerificationCancel(userID, id.DeviceID("*"), transactionID, "Unknown transaction: "+transactionID, event.VerificationCancelUnknownTransaction) |
| 128 |
return nil, ErrUnknownTransaction |
| 129 |
} |
| 130 |
verState := verStateInterface.(*verificationState) |
| 131 |
if verState.otherDevice.UserID != userID { |
| 132 |
reason := fmt.Sprintf("Unknown user for transaction %v: %v", transactionID, userID) |
| 133 |
if verState.inRoomID == "" { |
| 134 |
_ = mach.SendSASVerificationCancel(userID, id.DeviceID("*"), transactionID, reason, event.VerificationCancelUserMismatch) |
| 135 |
} else { |
| 136 |
_ = mach.SendInRoomSASVerificationCancel(verState.inRoomID, userID, transactionID, reason, event.VerificationCancelUserMismatch) |
| 137 |
} |
| 138 |
mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 139 |
return nil, fmt.Errorf("%w %s: %s", ErrUnknownUserForTransaction, transactionID, userID) |
| 140 |
} |
| 141 |
return verState, nil |
| 142 |
} |
| 143 |
|
| 144 |
// handleVerificationStart handles an incoming m.key.verification.start message. |
| 145 |
// It initializes the state for this SAS verification process and stores it. |
| 146 |
func (mach *OlmMachine) handleVerificationStart(userID id.UserID, content *event.VerificationStartEventContent, transactionID string, timeout time.Duration, inRoomID id.RoomID) { |
| 147 |
mach.Log.Debug("Received verification start from %v", content.FromDevice) |
| 148 |
otherDevice, err := mach.GetOrFetchDevice(userID, content.FromDevice) |
| 149 |
if err != nil { |
| 150 |
mach.Log.Error("Could not find device %v of user %v", content.FromDevice, userID) |
| 151 |
return |
| 152 |
} |
| 153 |
warnAndCancel := func(logReason, cancelReason string) { |
| 154 |
mach.Log.Warn("Canceling verification transaction %v as it %s", transactionID, logReason) |
| 155 |
if inRoomID == "" { |
| 156 |
_ = mach.SendSASVerificationCancel(otherDevice.UserID, otherDevice.DeviceID, transactionID, cancelReason, event.VerificationCancelUnknownMethod) |
| 157 |
} else { |
| 158 |
_ = mach.SendInRoomSASVerificationCancel(inRoomID, otherDevice.UserID, transactionID, cancelReason, event.VerificationCancelUnknownMethod) |
| 159 |
} |
| 160 |
} |
| 161 |
switch { |
| 162 |
case content.Method != event.VerificationMethodSAS: |
| 163 |
warnAndCancel("is not SAS", "Only SAS method is supported") |
| 164 |
case !content.SupportsKeyAgreementProtocol(event.KeyAgreementCurve25519HKDFSHA256): |
| 165 |
warnAndCancel("does not support key agreement protocol curve25519-hkdf-sha256", |
| 166 |
"Only curve25519-hkdf-sha256 key agreement protocol is supported") |
| 167 |
case !content.SupportsHashMethod(event.VerificationHashSHA256): |
| 168 |
warnAndCancel("does not support SHA256 hashing", "Only SHA256 hashing is supported") |
| 169 |
case !content.SupportsMACMethod(event.HKDFHMACSHA256): |
| 170 |
warnAndCancel("does not support MAC method hkdf-hmac-sha256", "Only hkdf-hmac-sha256 MAC method is supported") |
| 171 |
case !content.SupportsSASMethod(event.SASDecimal): |
| 172 |
warnAndCancel("does not support decimal SAS", "Decimal SAS method must be supported") |
| 173 |
default: |
| 174 |
mach.actuallyStartVerification(userID, content, otherDevice, transactionID, timeout, inRoomID) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
func (mach *OlmMachine) actuallyStartVerification(userID id.UserID, content *event.VerificationStartEventContent, otherDevice *DeviceIdentity, transactionID string, timeout time.Duration, inRoomID id.RoomID) { |
| 179 |
if inRoomID != "" && transactionID != "" { |
| 180 |
verState, err := mach.getTransactionState(transactionID, userID) |
| 181 |
if err != nil { |
| 182 |
mach.Log.Error("Failed to get transaction state for in-room verification %s start: %v", transactionID, err) |
| 183 |
_ = mach.SendInRoomSASVerificationCancel(inRoomID, otherDevice.UserID, transactionID, "Internal state error in gomuks :(", "net.maunium.internal_error") |
| 184 |
return |
| 185 |
} |
| 186 |
mach.timeoutAfter(verState, transactionID, timeout) |
| 187 |
sasMethods := commonSASMethods(verState.hooks, content.ShortAuthenticationString) |
| 188 |
err = mach.SendInRoomSASVerificationAccept(inRoomID, userID, content, transactionID, verState.sas.GetPubkey(), sasMethods) |
| 189 |
if err != nil { |
| 190 |
mach.Log.Error("Error accepting in-room SAS verification: %v", err) |
| 191 |
} |
| 192 |
verState.chosenSASMethod = sasMethods[0] |
| 193 |
verState.verificationStarted = true |
| 194 |
return |
| 195 |
} |
| 196 |
resp, hooks := mach.AcceptVerificationFrom(transactionID, otherDevice, inRoomID) |
| 197 |
if resp == AcceptRequest { |
| 198 |
sasMethods := commonSASMethods(hooks, content.ShortAuthenticationString) |
| 199 |
if len(sasMethods) == 0 { |
| 200 |
mach.Log.Error("No common SAS methods: %v", content.ShortAuthenticationString) |
| 201 |
if inRoomID == "" { |
| 202 |
_ = mach.SendSASVerificationCancel(otherDevice.UserID, otherDevice.DeviceID, transactionID, "No common SAS methods", event.VerificationCancelUnknownMethod) |
| 203 |
} else { |
| 204 |
_ = mach.SendInRoomSASVerificationCancel(inRoomID, otherDevice.UserID, transactionID, "No common SAS methods", event.VerificationCancelUnknownMethod) |
| 205 |
} |
| 206 |
return |
| 207 |
} |
| 208 |
verState := &verificationState{ |
| 209 |
sas: olm.NewSAS(), |
| 210 |
otherDevice: otherDevice, |
| 211 |
initiatedByUs: false, |
| 212 |
verificationStarted: true, |
| 213 |
keyReceived: false, |
| 214 |
sasMatched: make(chan bool, 1), |
| 215 |
hooks: hooks, |
| 216 |
chosenSASMethod: sasMethods[0], |
| 217 |
inRoomID: inRoomID, |
| 218 |
} |
| 219 |
verState.lock.Lock() |
| 220 |
defer verState.lock.Unlock() |
| 221 |
|
| 222 |
_, loaded := mach.keyVerificationTransactionState.LoadOrStore(userID.String()+":"+transactionID, verState) |
| 223 |
if loaded { |
| 224 |
// transaction already exists |
| 225 |
mach.Log.Error("Transaction %v already exists, canceling", transactionID) |
| 226 |
if inRoomID == "" { |
| 227 |
_ = mach.SendSASVerificationCancel(otherDevice.UserID, otherDevice.DeviceID, transactionID, "Transaction already exists", event.VerificationCancelUnexpectedMessage) |
| 228 |
} else { |
| 229 |
_ = mach.SendInRoomSASVerificationCancel(inRoomID, otherDevice.UserID, transactionID, "Transaction already exists", event.VerificationCancelUnexpectedMessage) |
| 230 |
} |
| 231 |
return |
| 232 |
} |
| 233 |
|
| 234 |
mach.timeoutAfter(verState, transactionID, timeout) |
| 235 |
|
| 236 |
var err error |
| 237 |
if inRoomID == "" { |
| 238 |
err = mach.SendSASVerificationAccept(userID, content, verState.sas.GetPubkey(), sasMethods) |
| 239 |
} else { |
| 240 |
err = mach.SendInRoomSASVerificationAccept(inRoomID, userID, content, transactionID, verState.sas.GetPubkey(), sasMethods) |
| 241 |
} |
| 242 |
if err != nil { |
| 243 |
mach.Log.Error("Error accepting SAS verification: %v", err) |
| 244 |
} |
| 245 |
} else if resp == RejectRequest { |
| 246 |
mach.Log.Debug("Not accepting SAS verification %v from %v of user %v", transactionID, otherDevice.DeviceID, otherDevice.UserID) |
| 247 |
var err error |
| 248 |
if inRoomID == "" { |
| 249 |
err = mach.SendSASVerificationCancel(otherDevice.UserID, otherDevice.DeviceID, transactionID, "Not accepted by user", event.VerificationCancelByUser) |
| 250 |
} else { |
| 251 |
err = mach.SendInRoomSASVerificationCancel(inRoomID, otherDevice.UserID, transactionID, "Not accepted by user", event.VerificationCancelByUser) |
| 252 |
} |
| 253 |
if err != nil { |
| 254 |
mach.Log.Error("Error canceling SAS verification: %v", err) |
| 255 |
} |
| 256 |
} else { |
| 257 |
mach.Log.Debug("Ignoring SAS verification %v from %v of user %v", transactionID, otherDevice.DeviceID, otherDevice.UserID) |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
func (mach *OlmMachine) timeoutAfter(verState *verificationState, transactionID string, timeout time.Duration) { |
| 262 |
timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), timeout) |
| 263 |
verState.extendTimeout = timeoutCancel |
| 264 |
go func() { |
| 265 |
mapKey := verState.otherDevice.UserID.String() + ":" + transactionID |
| 266 |
for { |
| 267 |
<-timeoutCtx.Done() |
| 268 |
// when timeout context is done |
| 269 |
verState.lock.Lock() |
| 270 |
// if transaction not active anymore, return |
| 271 |
if _, ok := mach.keyVerificationTransactionState.Load(mapKey); !ok { |
| 272 |
verState.lock.Unlock() |
| 273 |
return |
| 274 |
} |
| 275 |
if timeoutCtx.Err() == context.DeadlineExceeded { |
| 276 |
// if deadline exceeded cancel due to timeout |
| 277 |
mach.keyVerificationTransactionState.Delete(mapKey) |
| 278 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Timed out", event.VerificationCancelByTimeout) |
| 279 |
mach.Log.Warn("Verification transaction %v is canceled due to timing out", transactionID) |
| 280 |
verState.lock.Unlock() |
| 281 |
return |
| 282 |
} |
| 283 |
// otherwise the cancel func was called, so the timeout is reset |
| 284 |
mach.Log.Debug("Extending timeout for transaction %v", transactionID) |
| 285 |
timeoutCtx, timeoutCancel = context.WithTimeout(context.Background(), timeout) |
| 286 |
verState.extendTimeout = timeoutCancel |
| 287 |
verState.lock.Unlock() |
| 288 |
} |
| 289 |
}() |
| 290 |
} |
| 291 |
|
| 292 |
// handleVerificationAccept handles an incoming m.key.verification.accept message. |
| 293 |
// It continues the SAS verification process by sending the SAS key message to the other device. |
| 294 |
func (mach *OlmMachine) handleVerificationAccept(userID id.UserID, content *event.VerificationAcceptEventContent, transactionID string) { |
| 295 |
mach.Log.Debug("Received verification accept for transaction %v", transactionID) |
| 296 |
verState, err := mach.getTransactionState(transactionID, userID) |
| 297 |
if err != nil { |
| 298 |
mach.Log.Error("Error getting transaction state: %v", err) |
| 299 |
return |
| 300 |
} |
| 301 |
verState.lock.Lock() |
| 302 |
defer verState.lock.Unlock() |
| 303 |
verState.extendTimeout() |
| 304 |
|
| 305 |
if !verState.initiatedByUs || verState.verificationStarted { |
| 306 |
// unexpected accept at this point |
| 307 |
mach.Log.Warn("Unexpected verification accept message for transaction %v", transactionID) |
| 308 |
mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 309 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Unexpected accept message", event.VerificationCancelUnexpectedMessage) |
| 310 |
return |
| 311 |
} |
| 312 |
|
| 313 |
sasMethods := commonSASMethods(verState.hooks, content.ShortAuthenticationString) |
| 314 |
if content.KeyAgreementProtocol != event.KeyAgreementCurve25519HKDFSHA256 || |
| 315 |
content.Hash != event.VerificationHashSHA256 || |
| 316 |
content.MessageAuthenticationCode != event.HKDFHMACSHA256 || |
| 317 |
len(sasMethods) == 0 { |
| 318 |
|
| 319 |
mach.Log.Warn("Canceling verification transaction %v due to unknown parameter", transactionID) |
| 320 |
mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 321 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Verification uses unknown method", event.VerificationCancelUnknownMethod) |
| 322 |
return |
| 323 |
} |
| 324 |
|
| 325 |
key := verState.sas.GetPubkey() |
| 326 |
verState.commitment = content.Commitment |
| 327 |
verState.chosenSASMethod = sasMethods[0] |
| 328 |
verState.verificationStarted = true |
| 329 |
|
| 330 |
if verState.inRoomID == "" { |
| 331 |
err = mach.SendSASVerificationKey(userID, verState.otherDevice.DeviceID, transactionID, string(key)) |
| 332 |
} else { |
| 333 |
err = mach.SendInRoomSASVerificationKey(verState.inRoomID, userID, transactionID, string(key)) |
| 334 |
} |
| 335 |
if err != nil { |
| 336 |
mach.Log.Error("Error sending SAS key to other device: %v", err) |
| 337 |
return |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
// handleVerificationKey handles an incoming m.key.verification.key message. |
| 342 |
// It stores the other device's public key in order to acquire the SAS shared secret. |
| 343 |
func (mach *OlmMachine) handleVerificationKey(userID id.UserID, content *event.VerificationKeyEventContent, transactionID string) { |
| 344 |
mach.Log.Debug("Got verification key for transaction %v: %v", transactionID, content.Key) |
| 345 |
verState, err := mach.getTransactionState(transactionID, userID) |
| 346 |
if err != nil { |
| 347 |
mach.Log.Error("Error getting transaction state: %v", err) |
| 348 |
return |
| 349 |
} |
| 350 |
verState.lock.Lock() |
| 351 |
defer verState.lock.Unlock() |
| 352 |
verState.extendTimeout() |
| 353 |
|
| 354 |
device := verState.otherDevice |
| 355 |
|
| 356 |
if !verState.verificationStarted || verState.keyReceived { |
| 357 |
// unexpected key at this point |
| 358 |
mach.Log.Warn("Unexpected verification key message for transaction %v", transactionID) |
| 359 |
mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 360 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Unexpected key message", event.VerificationCancelUnexpectedMessage) |
| 361 |
return |
| 362 |
} |
| 363 |
|
| 364 |
if err := verState.sas.SetTheirKey([]byte(content.Key)); err != nil { |
| 365 |
mach.Log.Error("Error setting other device's key: %v", err) |
| 366 |
return |
| 367 |
} |
| 368 |
|
| 369 |
verState.keyReceived = true |
| 370 |
|
| 371 |
if verState.initiatedByUs { |
| 372 |
// verify commitment string from accept message now |
| 373 |
expectedCommitment := olm.NewUtility().Sha256(content.Key + verState.startEventCanonical) |
| 374 |
mach.Log.Debug("Received commitment: %v Expected: %v", verState.commitment, expectedCommitment) |
| 375 |
if expectedCommitment != verState.commitment { |
| 376 |
mach.Log.Warn("Canceling verification transaction %v due to commitment mismatch", transactionID) |
| 377 |
mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 378 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Commitment mismatch", event.VerificationCancelCommitmentMismatch) |
| 379 |
return |
| 380 |
} |
| 381 |
} else { |
| 382 |
// if verification was initiated by other device, send out our key now |
| 383 |
key := verState.sas.GetPubkey() |
| 384 |
|
| 385 |
if verState.inRoomID == "" { |
| 386 |
err = mach.SendSASVerificationKey(userID, device.DeviceID, transactionID, string(key)) |
| 387 |
} else { |
| 388 |
err = mach.SendInRoomSASVerificationKey(verState.inRoomID, userID, transactionID, string(key)) |
| 389 |
} |
| 390 |
if err != nil { |
| 391 |
mach.Log.Error("Error sending SAS key to other device: %v", err) |
| 392 |
return |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
// compare the SAS keys in a new goroutine and, when the verification is complete, send out the MAC |
| 397 |
var initUserID, acceptUserID id.UserID |
| 398 |
var initDeviceID, acceptDeviceID id.DeviceID |
| 399 |
var initKey, acceptKey string |
| 400 |
if verState.initiatedByUs { |
| 401 |
initUserID = mach.Client.UserID |
| 402 |
initDeviceID = mach.Client.DeviceID |
| 403 |
initKey = string(verState.sas.GetPubkey()) |
| 404 |
acceptUserID = device.UserID |
| 405 |
acceptDeviceID = device.DeviceID |
| 406 |
acceptKey = content.Key |
| 407 |
} else { |
| 408 |
initUserID = device.UserID |
| 409 |
initDeviceID = device.DeviceID |
| 410 |
initKey = content.Key |
| 411 |
acceptUserID = mach.Client.UserID |
| 412 |
acceptDeviceID = mach.Client.DeviceID |
| 413 |
acceptKey = string(verState.sas.GetPubkey()) |
| 414 |
} |
| 415 |
// use the prefered SAS method to generate a SAS |
| 416 |
sasMethod := verState.chosenSASMethod |
| 417 |
sas, err := sasMethod.GetVerificationSAS(initUserID, initDeviceID, initKey, acceptUserID, acceptDeviceID, acceptKey, transactionID, verState.sas) |
| 418 |
if err != nil { |
| 419 |
mach.Log.Error("Error generating SAS (method %v): %v", sasMethod.Type(), err) |
| 420 |
return |
| 421 |
} |
| 422 |
mach.Log.Debug("Generated SAS (%v): %v", sasMethod.Type(), sas) |
| 423 |
go func() { |
| 424 |
result := verState.hooks.VerifySASMatch(device, sas) |
| 425 |
mach.sasCompared(result, transactionID, verState) |
| 426 |
}() |
| 427 |
} |
| 428 |
|
| 429 |
// sasCompared is called asynchronously. It waits for the SAS to be compared for the verification to proceed. |
| 430 |
// If the SAS match, then our MAC is sent out. Otherwise the transaction is canceled. |
| 431 |
func (mach *OlmMachine) sasCompared(didMatch bool, transactionID string, verState *verificationState) { |
| 432 |
verState.lock.Lock() |
| 433 |
defer verState.lock.Unlock() |
| 434 |
verState.extendTimeout() |
| 435 |
if didMatch { |
| 436 |
verState.sasMatched <- true |
| 437 |
var err error |
| 438 |
if verState.inRoomID == "" { |
| 439 |
err = mach.SendSASVerificationMAC(verState.otherDevice.UserID, verState.otherDevice.DeviceID, transactionID, verState.sas) |
| 440 |
} else { |
| 441 |
err = mach.SendInRoomSASVerificationMAC(verState.inRoomID, verState.otherDevice.UserID, verState.otherDevice.DeviceID, transactionID, verState.sas) |
| 442 |
} |
| 443 |
if err != nil { |
| 444 |
mach.Log.Error("Error sending verification MAC to other device: %v", err) |
| 445 |
} |
| 446 |
} else { |
| 447 |
verState.sasMatched <- false |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
// handleVerificationMAC handles an incoming m.key.verification.mac message. |
| 452 |
// It verifies the other device's MAC and if the MAC is valid it marks the device as trusted. |
| 453 |
func (mach *OlmMachine) handleVerificationMAC(userID id.UserID, content *event.VerificationMacEventContent, transactionID string) { |
| 454 |
mach.Log.Debug("Got MAC for verification %v: %v, MAC for keys: %v", transactionID, content.Mac, content.Keys) |
| 455 |
verState, err := mach.getTransactionState(transactionID, userID) |
| 456 |
if err != nil { |
| 457 |
mach.Log.Error("Error getting transaction state: %v", err) |
| 458 |
return |
| 459 |
} |
| 460 |
verState.lock.Lock() |
| 461 |
defer verState.lock.Unlock() |
| 462 |
verState.extendTimeout() |
| 463 |
|
| 464 |
device := verState.otherDevice |
| 465 |
|
| 466 |
// we are done with this SAS verification in all cases so we forget about it |
| 467 |
mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 468 |
|
| 469 |
if !verState.verificationStarted || !verState.keyReceived { |
| 470 |
// unexpected MAC at this point |
| 471 |
mach.Log.Warn("Unexpected MAC message for transaction %v", transactionID) |
| 472 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Unexpected MAC message", event.VerificationCancelUnexpectedMessage) |
| 473 |
return |
| 474 |
} |
| 475 |
|
| 476 |
// do this in another goroutine as the match result might take a long time to arrive |
| 477 |
go func() { |
| 478 |
matched := <-verState.sasMatched |
| 479 |
verState.lock.Lock() |
| 480 |
defer verState.lock.Unlock() |
| 481 |
|
| 482 |
if !matched { |
| 483 |
mach.Log.Warn("SAS do not match! Canceling transaction %v", transactionID) |
| 484 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "SAS do not match", event.VerificationCancelSASMismatch) |
| 485 |
return |
| 486 |
} |
| 487 |
|
| 488 |
keyID := id.NewKeyID(id.KeyAlgorithmEd25519, device.DeviceID.String()) |
| 489 |
|
| 490 |
expectedPKMAC, expectedKeysMAC, err := mach.getPKAndKeysMAC(verState.sas, device.UserID, device.DeviceID, |
| 491 |
mach.Client.UserID, mach.Client.DeviceID, transactionID, device.SigningKey, keyID, content.Mac) |
| 492 |
if err != nil { |
| 493 |
mach.Log.Error("Error generating MAC to match with received MAC: %v", err) |
| 494 |
return |
| 495 |
} |
| 496 |
|
| 497 |
mach.Log.Debug("Expected %s keys MAC, got %s", expectedKeysMAC, content.Keys) |
| 498 |
if content.Keys != expectedKeysMAC { |
| 499 |
mach.Log.Warn("Canceling verification transaction %v due to mismatched keys MAC", transactionID) |
| 500 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Mismatched keys MACs", event.VerificationCancelKeyMismatch) |
| 501 |
return |
| 502 |
} |
| 503 |
|
| 504 |
mach.Log.Debug("Expected %s PK MAC, got %s", expectedPKMAC, content.Mac[keyID]) |
| 505 |
if content.Mac[keyID] != expectedPKMAC { |
| 506 |
mach.Log.Warn("Canceling verification transaction %v due to mismatched PK MAC", transactionID) |
| 507 |
_ = mach.callbackAndCancelSASVerification(verState, transactionID, "Mismatched PK MACs", event.VerificationCancelKeyMismatch) |
| 508 |
return |
| 509 |
} |
| 510 |
|
| 511 |
// we can finally trust this device |
| 512 |
device.Trust = TrustStateVerified |
| 513 |
err = mach.CryptoStore.PutDevice(device.UserID, device) |
| 514 |
if err != nil { |
| 515 |
mach.Log.Warn("Failed to put device after verifying: %v", err) |
| 516 |
} |
| 517 |
|
| 518 |
if mach.CrossSigningKeys != nil { |
| 519 |
if device.UserID == mach.Client.UserID { |
| 520 |
err := mach.SignOwnDevice(device) |
| 521 |
if err != nil { |
| 522 |
mach.Log.Error("Failed to cross-sign own device %s: %v", device.DeviceID, err) |
| 523 |
} else { |
| 524 |
mach.Log.Debug("Cross-signed own device %v after SAS verification", device.DeviceID) |
| 525 |
} |
| 526 |
} else { |
| 527 |
masterKey, err := mach.fetchMasterKey(device, content, verState, transactionID) |
| 528 |
if err != nil { |
| 529 |
mach.Log.Warn("Failed to fetch %s's master key: %v", device.UserID, err) |
| 530 |
} else { |
| 531 |
if err := mach.SignUser(device.UserID, masterKey); err != nil { |
| 532 |
mach.Log.Error("Failed to cross-sign master key of %s: %v", device.UserID, err) |
| 533 |
} else { |
| 534 |
mach.Log.Debug("Cross-signed master key of %v after SAS verification", device.UserID) |
| 535 |
} |
| 536 |
} |
| 537 |
} |
| 538 |
} else { |
| 539 |
// TODO ask user to unlock cross-signing keys? |
| 540 |
mach.Log.Debug("Cross-signing keys not cached, not signing %s/%s", device.UserID, device.DeviceID) |
| 541 |
} |
| 542 |
|
| 543 |
mach.Log.Debug("Device %v of user %v verified successfully!", device.DeviceID, device.UserID) |
| 544 |
|
| 545 |
verState.hooks.OnSuccess() |
| 546 |
}() |
| 547 |
} |
| 548 |
|
| 549 |
// handleVerificationCancel handles an incoming m.key.verification.cancel message. |
| 550 |
// It cancels the verification process for the given reason. |
| 551 |
func (mach *OlmMachine) handleVerificationCancel(userID id.UserID, content *event.VerificationCancelEventContent, transactionID string) { |
| 552 |
// make sure to not reply with a cancel to not cause a loop of cancel messages |
| 553 |
// this verification will get canceled even if the senders do not match |
| 554 |
verStateInterface, ok := mach.keyVerificationTransactionState.Load(userID.String() + ":" + transactionID) |
| 555 |
if ok { |
| 556 |
go verStateInterface.(*verificationState).hooks.OnCancel(false, content.Reason, content.Code) |
| 557 |
} |
| 558 |
|
| 559 |
mach.keyVerificationTransactionState.Delete(userID.String() + ":" + transactionID) |
| 560 |
mach.Log.Warn("SAS verification %v was canceled by %v with reason: %v (%v)", |
| 561 |
transactionID, userID, content.Reason, content.Code) |
| 562 |
} |
| 563 |
|
| 564 |
// handleVerificationRequest handles an incoming m.key.verification.request message. |
| 565 |
func (mach *OlmMachine) handleVerificationRequest(userID id.UserID, content *event.VerificationRequestEventContent, transactionID string, inRoomID id.RoomID) { |
| 566 |
mach.Log.Debug("Received verification request from %v", content.FromDevice) |
| 567 |
otherDevice, err := mach.GetOrFetchDevice(userID, content.FromDevice) |
| 568 |
if err != nil { |
| 569 |
mach.Log.Error("Could not find device %v of user %v", content.FromDevice, userID) |
| 570 |
return |
| 571 |
} |
| 572 |
if !content.SupportsVerificationMethod(event.VerificationMethodSAS) { |
| 573 |
mach.Log.Warn("Canceling verification transaction %v as SAS is not supported", transactionID) |
| 574 |
if inRoomID == "" { |
| 575 |
_ = mach.SendSASVerificationCancel(otherDevice.UserID, otherDevice.DeviceID, transactionID, "Only SAS method is supported", event.VerificationCancelUnknownMethod) |
| 576 |
} else { |
| 577 |
_ = mach.SendInRoomSASVerificationCancel(inRoomID, otherDevice.UserID, transactionID, "Only SAS method is supported", event.VerificationCancelUnknownMethod) |
| 578 |
} |
| 579 |
return |
| 580 |
} |
| 581 |
resp, hooks := mach.AcceptVerificationFrom(transactionID, otherDevice, inRoomID) |
| 582 |
if resp == AcceptRequest { |
| 583 |
mach.Log.Debug("Accepting SAS verification %v from %v of user %v", transactionID, otherDevice.DeviceID, otherDevice.UserID) |
| 584 |
if inRoomID == "" { |
| 585 |
_, err = mach.NewSASVerificationWith(otherDevice, hooks, transactionID, mach.DefaultSASTimeout) |
| 586 |
} else { |
| 587 |
if err := mach.SendInRoomSASVerificationReady(inRoomID, transactionID); err != nil { |
| 588 |
mach.Log.Error("Error sending in-room SAS verification ready: %v", err) |
| 589 |
} |
| 590 |
if mach.Client.UserID < otherDevice.UserID { |
| 591 |
// up to us to send the start message |
| 592 |
_, err = mach.newInRoomSASVerificationWithInner(inRoomID, otherDevice, hooks, transactionID, mach.DefaultSASTimeout) |
| 593 |
} |
| 594 |
} |
| 595 |
if err != nil { |
| 596 |
mach.Log.Error("Error accepting SAS verification request: %v", err) |
| 597 |
} |
| 598 |
} else if resp == RejectRequest { |
| 599 |
mach.Log.Debug("Rejecting SAS verification %v from %v of user %v", transactionID, otherDevice.DeviceID, otherDevice.UserID) |
| 600 |
if inRoomID == "" { |
| 601 |
_ = mach.SendSASVerificationCancel(otherDevice.UserID, otherDevice.DeviceID, transactionID, "Not accepted by user", event.VerificationCancelByUser) |
| 602 |
} else { |
| 603 |
_ = mach.SendInRoomSASVerificationCancel(inRoomID, otherDevice.UserID, transactionID, "Not accepted by user", event.VerificationCancelByUser) |
| 604 |
} |
| 605 |
} else { |
| 606 |
mach.Log.Debug("Ignoring SAS verification %v from %v of user %v", transactionID, otherDevice.DeviceID, otherDevice.UserID) |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
// NewSimpleSASVerificationWith starts the SAS verification process with another device with a default timeout, |
| 611 |
// a generated transaction ID and support for both emoji and decimal SAS methods. |
| 612 |
func (mach *OlmMachine) NewSimpleSASVerificationWith(device *DeviceIdentity, hooks VerificationHooks) (string, error) { |
| 613 |
return mach.NewSASVerificationWith(device, hooks, "", mach.DefaultSASTimeout) |
| 614 |
} |
| 615 |
|
| 616 |
// NewSASVerificationWith starts the SAS verification process with another device. |
| 617 |
// If the other device accepts the verification transaction, the methods in `hooks` will be used to verify the SAS match and to complete the transaction.. |
| 618 |
// If the transaction ID is empty, a new one is generated. |
| 619 |
func (mach *OlmMachine) NewSASVerificationWith(device *DeviceIdentity, hooks VerificationHooks, transactionID string, timeout time.Duration) (string, error) { |
| 620 |
if transactionID == "" { |
| 621 |
transactionID = strconv.Itoa(rand.Int()) |
| 622 |
} |
| 623 |
mach.Log.Debug("Starting new verification transaction %v with device %v of user %v", transactionID, device.DeviceID, device.UserID) |
| 624 |
|
| 625 |
verState := &verificationState{ |
| 626 |
sas: olm.NewSAS(), |
| 627 |
otherDevice: device, |
| 628 |
initiatedByUs: true, |
| 629 |
verificationStarted: false, |
| 630 |
keyReceived: false, |
| 631 |
sasMatched: make(chan bool, 1), |
| 632 |
hooks: hooks, |
| 633 |
} |
| 634 |
verState.lock.Lock() |
| 635 |
defer verState.lock.Unlock() |
| 636 |
|
| 637 |
startEvent, err := mach.SendSASVerificationStart(device.UserID, device.DeviceID, transactionID, hooks.VerificationMethods()) |
| 638 |
if err != nil { |
| 639 |
return "", err |
| 640 |
} |
| 641 |
|
| 642 |
payload, err := json.Marshal(startEvent) |
| 643 |
if err != nil { |
| 644 |
return "", err |
| 645 |
} |
| 646 |
canonical, err := canonicaljson.CanonicalJSON(payload) |
| 647 |
if err != nil { |
| 648 |
return "", err |
| 649 |
} |
| 650 |
|
| 651 |
verState.startEventCanonical = string(canonical) |
| 652 |
_, loaded := mach.keyVerificationTransactionState.LoadOrStore(device.UserID.String()+":"+transactionID, verState) |
| 653 |
if loaded { |
| 654 |
return "", ErrTransactionAlreadyExists |
| 655 |
} |
| 656 |
|
| 657 |
mach.timeoutAfter(verState, transactionID, timeout) |
| 658 |
|
| 659 |
return transactionID, nil |
| 660 |
} |
| 661 |
|
| 662 |
// CancelSASVerification is used by the user to cancel a SAS verification process with the given reason. |
| 663 |
func (mach *OlmMachine) CancelSASVerification(userID id.UserID, transactionID, reason string) error { |
| 664 |
mapKey := userID.String() + ":" + transactionID |
| 665 |
verStateInterface, ok := mach.keyVerificationTransactionState.Load(mapKey) |
| 666 |
if !ok { |
| 667 |
return ErrUnknownTransaction |
| 668 |
} |
| 669 |
verState := verStateInterface.(*verificationState) |
| 670 |
verState.lock.Lock() |
| 671 |
defer verState.lock.Unlock() |
| 672 |
mach.Log.Trace("User canceled verification transaction %v with reason: %v", transactionID, reason) |
| 673 |
mach.keyVerificationTransactionState.Delete(mapKey) |
| 674 |
return mach.callbackAndCancelSASVerification(verState, transactionID, reason, event.VerificationCancelByUser) |
| 675 |
} |
| 676 |
|
| 677 |
// SendSASVerificationCancel is used to manually send a SAS cancel message process with the given reason and cancellation code. |
| 678 |
func (mach *OlmMachine) SendSASVerificationCancel(userID id.UserID, deviceID id.DeviceID, transactionID string, reason string, code event.VerificationCancelCode) error { |
| 679 |
content := &event.VerificationCancelEventContent{ |
| 680 |
TransactionID: transactionID, |
| 681 |
Reason: reason, |
| 682 |
Code: code, |
| 683 |
} |
| 684 |
return mach.sendToOneDevice(userID, deviceID, event.ToDeviceVerificationCancel, content) |
| 685 |
} |
| 686 |
|
| 687 |
// SendSASVerificationStart is used to manually send the SAS verification start message to another device. |
| 688 |
func (mach *OlmMachine) SendSASVerificationStart(toUserID id.UserID, toDeviceID id.DeviceID, transactionID string, methods []VerificationMethod) (*event.VerificationStartEventContent, error) { |
| 689 |
sasMethods := make([]event.SASMethod, len(methods)) |
| 690 |
for i, method := range methods { |
| 691 |
sasMethods[i] = method.Type() |
| 692 |
} |
| 693 |
content := &event.VerificationStartEventContent{ |
| 694 |
FromDevice: mach.Client.DeviceID, |
| 695 |
TransactionID: transactionID, |
| 696 |
Method: event.VerificationMethodSAS, |
| 697 |
KeyAgreementProtocols: []event.KeyAgreementProtocol{event.KeyAgreementCurve25519HKDFSHA256}, |
| 698 |
Hashes: []event.VerificationHashMethod{event.VerificationHashSHA256}, |
| 699 |
MessageAuthenticationCodes: []event.MACMethod{event.HKDFHMACSHA256}, |
| 700 |
ShortAuthenticationString: sasMethods, |
| 701 |
} |
| 702 |
return content, mach.sendToOneDevice(toUserID, toDeviceID, event.ToDeviceVerificationStart, content) |
| 703 |
} |
| 704 |
|
| 705 |
// SendSASVerificationAccept is used to manually send an accept for a SAS verification process from a received m.key.verification.start event. |
| 706 |
func (mach *OlmMachine) SendSASVerificationAccept(fromUser id.UserID, startEvent *event.VerificationStartEventContent, publicKey []byte, methods []VerificationMethod) error { |
| 707 |
if startEvent.Method != event.VerificationMethodSAS { |
| 708 |
reason := "Unknown verification method: " + string(startEvent.Method) |
| 709 |
if err := mach.SendSASVerificationCancel(fromUser, startEvent.FromDevice, startEvent.TransactionID, reason, event.VerificationCancelUnknownMethod); err != nil { |
| 710 |
return err |
| 711 |
} |
| 712 |
return ErrUnknownVerificationMethod |
| 713 |
} |
| 714 |
payload, err := json.Marshal(startEvent) |
| 715 |
if err != nil { |
| 716 |
return err |
| 717 |
} |
| 718 |
canonical, err := canonicaljson.CanonicalJSON(payload) |
| 719 |
if err != nil { |
| 720 |
return err |
| 721 |
} |
| 722 |
hash := olm.NewUtility().Sha256(string(publicKey) + string(canonical)) |
| 723 |
sasMethods := make([]event.SASMethod, len(methods)) |
| 724 |
for i, method := range methods { |
| 725 |
sasMethods[i] = method.Type() |
| 726 |
} |
| 727 |
content := &event.VerificationAcceptEventContent{ |
| 728 |
TransactionID: startEvent.TransactionID, |
| 729 |
Method: event.VerificationMethodSAS, |
| 730 |
KeyAgreementProtocol: event.KeyAgreementCurve25519HKDFSHA256, |
| 731 |
Hash: event.VerificationHashSHA256, |
| 732 |
MessageAuthenticationCode: event.HKDFHMACSHA256, |
| 733 |
ShortAuthenticationString: sasMethods, |
| 734 |
Commitment: hash, |
| 735 |
} |
| 736 |
return mach.sendToOneDevice(fromUser, startEvent.FromDevice, event.ToDeviceVerificationAccept, content) |
| 737 |
} |
| 738 |
|
| 739 |
func (mach *OlmMachine) callbackAndCancelSASVerification(verState *verificationState, transactionID, reason string, code event.VerificationCancelCode) error { |
| 740 |
go verState.hooks.OnCancel(true, reason, code) |
| 741 |
return mach.SendSASVerificationCancel(verState.otherDevice.UserID, verState.otherDevice.DeviceID, transactionID, reason, code) |
| 742 |
} |
| 743 |
|
| 744 |
// SendSASVerificationKey sends the ephemeral public key for a device to the partner device. |
| 745 |
func (mach *OlmMachine) SendSASVerificationKey(userID id.UserID, deviceID id.DeviceID, transactionID string, key string) error { |
| 746 |
content := &event.VerificationKeyEventContent{ |
| 747 |
TransactionID: transactionID, |
| 748 |
Key: key, |
| 749 |
} |
| 750 |
return mach.sendToOneDevice(userID, deviceID, event.ToDeviceVerificationKey, content) |
| 751 |
} |
| 752 |
|
| 753 |
// SendSASVerificationMAC is use the MAC of a device's key to the partner device. |
| 754 |
func (mach *OlmMachine) SendSASVerificationMAC(userID id.UserID, deviceID id.DeviceID, transactionID string, sas *olm.SAS) error { |
| 755 |
keyID := id.NewKeyID(id.KeyAlgorithmEd25519, mach.Client.DeviceID.String()) |
| 756 |
|
| 757 |
signingKey := mach.account.SigningKey() |
| 758 |
keyIDsMap := map[id.KeyID]string{keyID: ""} |
| 759 |
macMap := make(map[id.KeyID]string) |
| 760 |
|
| 761 |
if mach.CrossSigningKeys != nil { |
| 762 |
masterKey := mach.CrossSigningKeys.MasterKey.PublicKey |
| 763 |
masterKeyID := id.NewKeyID(id.KeyAlgorithmEd25519, masterKey.String()) |
| 764 |
// add master key ID to key map |
| 765 |
keyIDsMap[masterKeyID] = "" |
| 766 |
masterKeyMAC, _, err := mach.getPKAndKeysMAC(sas, mach.Client.UserID, mach.Client.DeviceID, |
| 767 |
userID, deviceID, transactionID, masterKey, masterKeyID, keyIDsMap) |
| 768 |
if err != nil { |
| 769 |
mach.Log.Error("Error generating master key MAC: %v", err) |
| 770 |
} else { |
| 771 |
mach.Log.Debug("Generated master key `%v` MAC: %v", masterKey, masterKeyMAC) |
| 772 |
macMap[masterKeyID] = masterKeyMAC |
| 773 |
} |
| 774 |
} |
| 775 |
|
| 776 |
pubKeyMac, keysMac, err := mach.getPKAndKeysMAC(sas, mach.Client.UserID, mach.Client.DeviceID, userID, deviceID, transactionID, signingKey, keyID, keyIDsMap) |
| 777 |
if err != nil { |
| 778 |
return err |
| 779 |
} |
| 780 |
mach.Log.Debug("MAC of key %s is: %s", signingKey, pubKeyMac) |
| 781 |
mach.Log.Debug("MAC of key ID(s) %s is: %s", keyID, keysMac) |
| 782 |
macMap[keyID] = pubKeyMac |
| 783 |
|
| 784 |
content := &event.VerificationMacEventContent{ |
| 785 |
TransactionID: transactionID, |
| 786 |
Keys: keysMac, |
| 787 |
Mac: macMap, |
| 788 |
} |
| 789 |
|
| 790 |
return mach.sendToOneDevice(userID, deviceID, event.ToDeviceVerificationMAC, content) |
| 791 |
} |
| 792 |
|
| 793 |
func commonSASMethods(hooks VerificationHooks, otherDeviceMethods []event.SASMethod) []VerificationMethod { |
| 794 |
methods := make([]VerificationMethod, 0) |
| 795 |
for _, hookMethod := range hooks.VerificationMethods() { |
| 796 |
for _, otherMethod := range otherDeviceMethods { |
| 797 |
if hookMethod.Type() == otherMethod { |
| 798 |
methods = append(methods, hookMethod) |
| 799 |
break |
| 800 |
} |
| 801 |
} |
| 802 |
} |
| 803 |
return methods |
| 804 |
} |