| 1 | // SPDX-FileCopyrightText: Nheko Contributors |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include "DeviceVerificationFlow.h" |
| 6 | |
| 7 | #include <tuple> |
| 8 | |
| 9 | #include <QDateTime> |
| 10 | #include <QTimer> |
| 11 | |
| 12 | #include <fmt/ranges.h> |
| 13 | #include <nlohmann/json.hpp> |
| 14 | |
| 15 | #include "Cache.h" |
| 16 | #include "Cache_p.h" |
| 17 | #include "ChatPage.h" |
| 18 | #include "Logging.h" |
| 19 | #include "MatrixClient.h" |
| 20 | #include "Utils.h" |
| 21 | #include "timeline/TimelineModel.h" |
| 22 | |
| 23 | static constexpr int TIMEOUT = 2 * 60 * 1000; // 2 minutes |
| 24 | |
| 25 | static constexpr std::string_view mac_method_alg_v1 = "hkdf-hmac-sha256"; |
| 26 | static constexpr std::string_view mac_method_alg_v2 = "hkdf-hmac-sha256.v2"; |
| 27 | |
| 28 | DeviceVerificationFlow::DeviceVerificationFlow(QObject *, |
| 29 | DeviceVerificationFlow::Type flow_type, |
| 30 | TimelineModel *model, |
| 31 | const QString &userID, |
| 32 | const std::vector<QString> &deviceIds_) |
| 33 | : sender(false) |
| 34 | , type(flow_type) |
| 35 | , deviceIds(std::move(deviceIds_)) |
| 36 | , model_(model) |
| 37 | { |
| 38 | nhlog::crypto()->debug("CREATING NEW FLOW, {}, {}", static_cast<int>(flow_type), (void *)this); |
| 39 | if (deviceIds.size() == 1) |
| 40 | deviceId = deviceIds.front(); |
| 41 | |
| 42 | timeout = new QTimer(this); |
| 43 | timeout->setSingleShot(true); |
| 44 | this->sas = olm::client()->sas_init(); |
| 45 | this->isMacVerified = false; |
| 46 | |
| 47 | auto user_id_ = userID.toStdString(); |
| 48 | this->toClient = mtx::identifiers::parse<mtx::identifiers::User>(user_id_); |
| 49 | cache::client()->query_keys( |
| 50 | user_id_, [user_id_, this](const UserKeyCache &res, mtx::http::RequestErr err) { |
| 51 | if (err) { |
| 52 | nhlog::net()->warn("failed to query device keys: {},{}", |
| 53 | mtx::errors::to_string(err->matrix_error.errcode), |
| 54 | static_cast<int>(err->status_code)); |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | if (!this->deviceId.isEmpty() && |
| 59 | (res.device_keys.find(deviceId.toStdString()) == res.device_keys.end())) { |
| 60 | nhlog::net()->warn("no devices retrieved {}", user_id_); |
| 61 | return; |
| 62 | } |
| 63 | |
| 64 | this->their_keys = res; |
| 65 | }); |
| 66 | |
| 67 | cache::client()->query_keys( |
| 68 | http::client()->user_id().to_string(), |
| 69 | [this](const UserKeyCache &res, mtx::http::RequestErr err) { |
| 70 | if (err) { |
| 71 | nhlog::net()->warn("failed to query device keys: {},{}", |
| 72 | mtx::errors::to_string(err->matrix_error.errcode), |
| 73 | static_cast<int>(err->status_code)); |
| 74 | return; |
| 75 | } |
| 76 | |
| 77 | if (res.master_keys.keys.empty()) |
| 78 | return; |
| 79 | |
| 80 | if (auto status = cache::verificationStatus(http::client()->user_id().to_string()); |
| 81 | status && status->user_verified == crypto::Trust::Verified) |
| 82 | this->our_trusted_master_key = res.master_keys.keys.begin()->second; |
| 83 | }); |
| 84 | |
| 85 | if (model) { |
| 86 | connect(this->model_, |
| 87 | &TimelineModel::updateFlowEventId, |
| 88 | this, |
| 89 | [this](const std::string &event_id_) { |
| 90 | this->relation.rel_type = mtx::common::RelationType::Reference; |
| 91 | this->relation.event_id = event_id_; |
| 92 | this->transaction_id = event_id_; |
| 93 | }); |
| 94 | } |
| 95 | |
| 96 | connect(timeout, &QTimer::timeout, this, [this]() { |
| 97 | nhlog::crypto()->info("verification: timeout"); |
| 98 | if (state_ != Success && state_ != Failed) |
| 99 | this->cancelVerification(DeviceVerificationFlow::Error::Timeout); |
| 100 | }); |
| 101 | |
| 102 | connect(ChatPage::instance(), |
| 103 | &ChatPage::receivedDeviceVerificationStart, |
| 104 | this, |
| 105 | &DeviceVerificationFlow::handleStartMessage); |
| 106 | connect(ChatPage::instance(), |
| 107 | &ChatPage::receivedDeviceVerificationAccept, |
| 108 | this, |
| 109 | [this](const mtx::events::msg::KeyVerificationAccept &msg) { |
| 110 | if (state_ == Failed || state_ == Success) |
| 111 | return; |
| 112 | |
| 113 | nhlog::crypto()->info("verification: received accept with mac methods {}", |
| 114 | fmt::join(msg.message_authentication_code, ", ")); |
| 115 | if (msg.transaction_id.has_value()) { |
| 116 | if (msg.transaction_id.value() != this->transaction_id) |
| 117 | return; |
| 118 | } else if (msg.relations.references()) { |
| 119 | if (msg.relations.references() != this->relation.event_id) |
| 120 | return; |
| 121 | } |
| 122 | |
| 123 | if (msg.key_agreement_protocol == "curve25519-hkdf-sha256" && |
| 124 | msg.hash == "sha256" && |
| 125 | (msg.message_authentication_code == mac_method_alg_v1 || |
| 126 | msg.message_authentication_code == mac_method_alg_v2)) { |
| 127 | this->commitment = msg.commitment; |
| 128 | if (std::find(msg.short_authentication_string.begin(), |
| 129 | msg.short_authentication_string.end(), |
| 130 | mtx::events::msg::SASMethods::Emoji) != |
| 131 | msg.short_authentication_string.end()) { |
| 132 | this->method = mtx::events::msg::SASMethods::Emoji; |
| 133 | } else { |
| 134 | this->method = mtx::events::msg::SASMethods::Decimal; |
| 135 | } |
| 136 | this->mac_method = msg.message_authentication_code; |
| 137 | this->sendVerificationKey(); |
| 138 | } else { |
| 139 | this->cancelVerification(DeviceVerificationFlow::Error::UnknownMethod); |
| 140 | } |
| 141 | }); |
| 142 | |
| 143 | connect(ChatPage::instance(), |
| 144 | &ChatPage::receivedDeviceVerificationCancel, |
| 145 | this, |
| 146 | [this](const mtx::events::msg::KeyVerificationCancel &msg) { |
| 147 | nhlog::crypto()->info( |
| 148 | "verification: received cancel, {} : {}", msg.code, msg.reason); |
| 149 | if (msg.transaction_id.has_value()) { |
| 150 | if (msg.transaction_id.value() != this->transaction_id) |
| 151 | return; |
| 152 | } else if (msg.relations.references()) { |
| 153 | if (msg.relations.references() != this->relation.event_id) |
| 154 | return; |
| 155 | } |
| 156 | error_ = User; |
| 157 | emit errorChanged(); |
| 158 | setState(Failed); |
| 159 | }); |
| 160 | |
| 161 | connect( |
| 162 | ChatPage::instance(), |
| 163 | &ChatPage::receivedDeviceVerificationKey, |
| 164 | this, |
| 165 | [this](const mtx::events::msg::KeyVerificationKey &msg) { |
| 166 | if (state_ == Failed || state_ == Success) |
| 167 | return; |
| 168 | |
| 169 | nhlog::crypto()->info( |
| 170 | "verification: received key, sender {}, state {}", sender, state().toStdString()); |
| 171 | if (msg.transaction_id.has_value()) { |
| 172 | if (msg.transaction_id.value() != this->transaction_id) |
| 173 | return; |
| 174 | } else if (msg.relations.references()) { |
| 175 | if (msg.relations.references() != this->relation.event_id) |
| 176 | return; |
| 177 | } |
| 178 | |
| 179 | if (sender) { |
| 180 | if (state_ != WaitingForOtherToAccept && state_ != WaitingForKeys) { |
| 181 | this->cancelVerification(OutOfOrder); |
| 182 | return; |
| 183 | } |
| 184 | } else { |
| 185 | if (state_ != WaitingForKeys) { |
| 186 | this->cancelVerification(OutOfOrder); |
| 187 | return; |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | this->sas->set_their_key(msg.key); |
| 192 | std::string info; |
| 193 | if (this->sender == true) { |
| 194 | info = "MATRIX_KEY_VERIFICATION_SAS|" + http::client()->user_id().to_string() + "|" + |
| 195 | http::client()->device_id() + "|" + this->sas->public_key() + "|" + |
| 196 | this->toClient.to_string() + "|" + this->deviceId.toStdString() + "|" + |
| 197 | msg.key + "|" + this->transaction_id; |
| 198 | } else { |
| 199 | info = "MATRIX_KEY_VERIFICATION_SAS|" + this->toClient.to_string() + "|" + |
| 200 | this->deviceId.toStdString() + "|" + msg.key + "|" + |
| 201 | http::client()->user_id().to_string() + "|" + http::client()->device_id() + |
| 202 | "|" + this->sas->public_key() + "|" + this->transaction_id; |
| 203 | } |
| 204 | |
| 205 | nhlog::ui()->info("Info is: '{}'", info); |
| 206 | |
| 207 | if (this->sender == false) { |
| 208 | this->sendVerificationKey(); |
| 209 | } else { |
| 210 | if (this->commitment != mtx::crypto::bin2base64_unpadded( |
| 211 | mtx::crypto::sha256(msg.key + this->canonical_json))) { |
| 212 | this->cancelVerification(DeviceVerificationFlow::Error::MismatchedCommitment); |
| 213 | return; |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | if (this->method == mtx::events::msg::SASMethods::Emoji) { |
| 218 | this->sasList = this->sas->generate_bytes_emoji(info); |
| 219 | setState(CompareEmoji); |
| 220 | } else if (this->method == mtx::events::msg::SASMethods::Decimal) { |
| 221 | this->sasList = this->sas->generate_bytes_decimal(info); |
| 222 | setState(CompareNumber); |
| 223 | } |
| 224 | }); |
| 225 | |
| 226 | connect( |
| 227 | ChatPage::instance(), |
| 228 | &ChatPage::receivedDeviceVerificationMac, |
| 229 | this, |
| 230 | [this](const mtx::events::msg::KeyVerificationMac &msg) { |
| 231 | if (state_ == Failed || state_ == Success) |
| 232 | return; |
| 233 | |
| 234 | nhlog::crypto()->info("verification: received mac"); |
| 235 | if (msg.transaction_id.has_value()) { |
| 236 | if (msg.transaction_id.value() != this->transaction_id) |
| 237 | return; |
| 238 | } else if (msg.relations.references()) { |
| 239 | if (msg.relations.references() != this->relation.event_id) |
| 240 | return; |
| 241 | } |
| 242 | |
| 243 | std::map<std::string, std::string> key_list; |
| 244 | std::string key_string; |
| 245 | for (const auto &mac : msg.mac) { |
| 246 | for (const auto &[deviceid, key] : their_keys.device_keys) { |
| 247 | (void)deviceid; |
| 248 | if (key.keys.count(mac.first)) |
| 249 | key_list[mac.first] = key.keys.at(mac.first); |
| 250 | } |
| 251 | |
| 252 | if (their_keys.master_keys.keys.count(mac.first)) |
| 253 | key_list[mac.first] = their_keys.master_keys.keys[mac.first]; |
| 254 | if (their_keys.user_signing_keys.keys.count(mac.first)) |
| 255 | key_list[mac.first] = their_keys.user_signing_keys.keys[mac.first]; |
| 256 | if (their_keys.self_signing_keys.keys.count(mac.first)) |
| 257 | key_list[mac.first] = their_keys.self_signing_keys.keys[mac.first]; |
| 258 | } |
| 259 | auto macs = sas->calculate_mac(mac_method, |
| 260 | toClient, |
| 261 | this->deviceId.toStdString(), |
| 262 | http::client()->user_id(), |
| 263 | http::client()->device_id(), |
| 264 | this->transaction_id, |
| 265 | key_list); |
| 266 | |
| 267 | for (const auto &[key, mac] : macs.mac) { |
| 268 | if (mac != msg.mac.at(key)) { |
| 269 | this->cancelVerification(DeviceVerificationFlow::Error::KeyMismatch); |
| 270 | return; |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | if (msg.keys == macs.keys) { |
| 275 | mtx::requests::KeySignaturesUpload req; |
| 276 | if (utils::localUser().toStdString() == this->toClient.to_string()) { |
| 277 | // self verification, sign master key with device key, if we |
| 278 | // verified it |
| 279 | for (const auto &mac : msg.mac) { |
| 280 | if (their_keys.master_keys.keys.count(mac.first)) { |
| 281 | nlohmann::json j = their_keys.master_keys; |
| 282 | j.erase("signatures"); |
| 283 | j.erase("unsigned"); |
| 284 | mtx::crypto::CrossSigningKeys master_key = |
| 285 | j.get<mtx::crypto::CrossSigningKeys>(); |
| 286 | master_key.signatures[utils::localUser().toStdString()] |
| 287 | ["ed25519:" + http::client()->device_id()] = |
| 288 | olm::client()->sign_message(j.dump()); |
| 289 | req.signatures[utils::localUser().toStdString()] |
| 290 | [master_key.keys.at(mac.first)] = master_key; |
| 291 | } else if (mac.first == "ed25519:" + this->deviceId.toStdString()) { |
| 292 | // Sign their device key with self signing key |
| 293 | |
| 294 | auto device_id = this->deviceId.toStdString(); |
| 295 | |
| 296 | if (their_keys.device_keys.count(device_id)) { |
| 297 | nlohmann::json j = their_keys.device_keys.at(device_id); |
| 298 | j.erase("signatures"); |
| 299 | j.erase("unsigned"); |
| 300 | |
| 301 | auto secret = cache::secret( |
| 302 | mtx::secret_storage::secrets::cross_signing_self_signing); |
| 303 | if (!secret) |
| 304 | continue; |
| 305 | auto ssk = mtx::crypto::PkSigning::from_seed(*secret); |
| 306 | |
| 307 | mtx::crypto::DeviceKeys dev = j.get<mtx::crypto::DeviceKeys>(); |
| 308 | dev.signatures[utils::localUser().toStdString()] |
| 309 | ["ed25519:" + ssk.public_key()] = ssk.sign(j.dump()); |
| 310 | |
| 311 | req.signatures[utils::localUser().toStdString()][device_id] = dev; |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | } else { |
| 316 | // Sign their master key with user signing key |
| 317 | for (const auto &mac : msg.mac) { |
| 318 | if (their_keys.master_keys.keys.count(mac.first)) { |
| 319 | nlohmann::json j = their_keys.master_keys; |
| 320 | j.erase("signatures"); |
| 321 | j.erase("unsigned"); |
| 322 | |
| 323 | auto secret = |
| 324 | cache::secret(mtx::secret_storage::secrets::cross_signing_user_signing); |
| 325 | if (!secret) |
| 326 | continue; |
| 327 | auto usk = mtx::crypto::PkSigning::from_seed(*secret); |
| 328 | |
| 329 | mtx::crypto::CrossSigningKeys master_key = |
| 330 | j.get<mtx::crypto::CrossSigningKeys>(); |
| 331 | master_key.signatures[utils::localUser().toStdString()] |
| 332 | ["ed25519:" + usk.public_key()] = usk.sign(j.dump()); |
| 333 | |
| 334 | req.signatures[toClient.to_string()][master_key.keys.at(mac.first)] = |
| 335 | master_key; |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | if (!req.signatures.empty()) { |
| 341 | nhlog::crypto()->debug("Signatures to send: {}", nlohmann::json(req).dump(2)); |
| 342 | http::client()->keys_signatures_upload( |
| 343 | req, |
| 344 | [](const mtx::responses::KeySignaturesUpload &res, mtx::http::RequestErr err) { |
| 345 | if (err) { |
| 346 | nhlog::net()->error("failed to upload signatures: {},{}", |
| 347 | mtx::errors::to_string(err->matrix_error.errcode), |
| 348 | static_cast<int>(err->status_code)); |
| 349 | } |
| 350 | |
| 351 | // MSVC bug, error C3493: 'key_id' cannot be implicitly captured because no |
| 352 | // default capture mode has been specified |
| 353 | // for (const auto &[user_id, tmp] : res.errors) |
| 354 | // for (const auto &[key_id, e] : tmp) |
| 355 | // nhlog::net()->error("signature error for user {} and key " |
| 356 | // "id {}: {}, {}", |
| 357 | // user_id, |
| 358 | // key_id, |
| 359 | // mtx::errors::to_string(e.errcode), |
| 360 | // e.error); |
| 361 | for (const auto &error : res.errors) { |
| 362 | const auto &user_id = error.first; |
| 363 | for (const auto &key_error : error.second) { |
| 364 | const auto &key_id = key_error.first; |
| 365 | const auto &e = key_error.second; |
| 366 | |
| 367 | nhlog::net()->error("signature error for user {} and key " |
| 368 | "id {}: {}, {}", |
| 369 | user_id, |
| 370 | key_id, |
| 371 | mtx::errors::to_string(e.errcode), |
| 372 | e.error); |
| 373 | } |
| 374 | } |
| 375 | }); |
| 376 | } |
| 377 | |
| 378 | this->isMacVerified = true; |
| 379 | this->acceptDevice(); |
| 380 | } else { |
| 381 | this->cancelVerification(DeviceVerificationFlow::Error::KeyMismatch); |
| 382 | } |
| 383 | }); |
| 384 | |
| 385 | connect( |
| 386 | ChatPage::instance(), |
| 387 | &ChatPage::receivedDeviceVerificationReady, |
| 388 | this, |
| 389 | [this](const mtx::events::msg::KeyVerificationReady &msg) { |
| 390 | if (state_ == Failed || state_ == Success) |
| 391 | return; |
| 392 | |
| 393 | nhlog::crypto()->info("verification: received ready {}", (void *)this); |
| 394 | if (!sender) { |
| 395 | if (msg.from_device != this->deviceId.toStdString()) { |
| 396 | nhlog::crypto()->debug("Accepted by {}, we are communicating with {}", |
| 397 | msg.from_device, |
| 398 | this->deviceId.toStdString()); |
| 399 | cancelVerification(AcceptedOnOtherDevice); |
| 400 | } |
| 401 | |
| 402 | return; |
| 403 | } |
| 404 | |
| 405 | if (msg.transaction_id.has_value()) { |
| 406 | if (msg.transaction_id.value() != this->transaction_id) |
| 407 | return; |
| 408 | |
| 409 | if (this->deviceId.isEmpty() && this->deviceIds.size() > 1) { |
| 410 | auto from = QString::fromStdString(msg.from_device); |
| 411 | if (std::find(deviceIds.begin(), deviceIds.end(), from) != deviceIds.end()) { |
| 412 | mtx::events::msg::KeyVerificationCancel req{}; |
| 413 | req.code = "m.user"; |
| 414 | req.reason = "accepted by other device"; |
| 415 | req.transaction_id = this->transaction_id; |
| 416 | mtx::requests::ToDeviceMessages<mtx::events::msg::KeyVerificationCancel> body; |
| 417 | |
| 418 | for (const auto &d : this->deviceIds) { |
| 419 | if (d != from) |
| 420 | body[this->toClient][d.toStdString()] = req; |
| 421 | } |
| 422 | |
| 423 | http::client()->send_to_device( |
| 424 | http::client()->generate_txn_id(), body, [](mtx::http::RequestErr err) { |
| 425 | if (err) |
| 426 | nhlog::net()->warn( |
| 427 | "failed to send verification to_device message: {} {}", |
| 428 | err->matrix_error.error, |
| 429 | static_cast<int>(err->status_code)); |
| 430 | }); |
| 431 | |
| 432 | this->deviceId = from; |
| 433 | this->deviceIds = {from}; |
| 434 | } |
| 435 | } |
| 436 | } else if (msg.relations.references()) { |
| 437 | if (msg.relations.references() != this->relation.event_id) |
| 438 | return; |
| 439 | else { |
| 440 | this->deviceId = QString::fromStdString(msg.from_device); |
| 441 | } |
| 442 | } else { |
| 443 | return; |
| 444 | } |
| 445 | nhlog::crypto()->info("verification: received ready sending start {}", (void *)this); |
| 446 | this->startVerificationRequest(); |
| 447 | }); |
| 448 | |
| 449 | connect(ChatPage::instance(), |
| 450 | &ChatPage::receivedDeviceVerificationDone, |
| 451 | this, |
| 452 | [this](const mtx::events::msg::KeyVerificationDone &msg) { |
| 453 | nhlog::crypto()->info("verification: received done"); |
| 454 | if (msg.transaction_id.has_value()) { |
| 455 | if (msg.transaction_id.value() != this->transaction_id) |
| 456 | return; |
| 457 | } else if (msg.relations.references()) { |
| 458 | if (msg.relations.references() != this->relation.event_id) |
| 459 | return; |
| 460 | } |
| 461 | nhlog::ui()->info("Flow done on other side"); |
| 462 | }); |
| 463 | |
| 464 | timeout->start(TIMEOUT); |
| 465 | } |
| 466 | |
| 467 | QString |
| 468 | DeviceVerificationFlow::state() |
| 469 | { |
| 470 | switch (state_) { |
| 471 | case PromptStartVerification: |
| 472 | return QStringLiteral("PromptStartVerification"); |
| 473 | case CompareEmoji: |
| 474 | return QStringLiteral("CompareEmoji"); |
| 475 | case CompareNumber: |
| 476 | return QStringLiteral("CompareNumber"); |
| 477 | case WaitingForKeys: |
| 478 | return QStringLiteral("WaitingForKeys"); |
| 479 | case WaitingForOtherToAccept: |
| 480 | return QStringLiteral("WaitingForOtherToAccept"); |
| 481 | case WaitingForMac: |
| 482 | return QStringLiteral("WaitingForMac"); |
| 483 | case Success: |
| 484 | return QStringLiteral("Success"); |
| 485 | case Failed: |
| 486 | return QStringLiteral("Failed"); |
| 487 | default: |
| 488 | return QString(); |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | void |
| 493 | DeviceVerificationFlow::next() |
| 494 | { |
| 495 | if (sender) { |
| 496 | switch (state_) { |
| 497 | case PromptStartVerification: |
| 498 | sendVerificationRequest(); |
| 499 | break; |
| 500 | case CompareEmoji: |
| 501 | case CompareNumber: |
| 502 | sendVerificationMac(); |
| 503 | break; |
| 504 | case WaitingForKeys: |
| 505 | case WaitingForOtherToAccept: |
| 506 | case WaitingForMac: |
| 507 | case Success: |
| 508 | case Failed: |
| 509 | nhlog::db()->error("verification: Invalid state transition!"); |
| 510 | break; |
| 511 | } |
| 512 | } else { |
| 513 | switch (state_) { |
| 514 | case PromptStartVerification: |
| 515 | if (canonical_json.empty()) |
| 516 | sendVerificationReady(); |
| 517 | else // legacy path without request and ready |
| 518 | acceptVerificationRequest(); |
| 519 | break; |
| 520 | case CompareEmoji: |
| 521 | [[fallthrough]]; |
| 522 | case CompareNumber: |
| 523 | sendVerificationMac(); |
| 524 | break; |
| 525 | case WaitingForKeys: |
| 526 | case WaitingForOtherToAccept: |
| 527 | case WaitingForMac: |
| 528 | case Success: |
| 529 | case Failed: |
| 530 | nhlog::db()->error("verification: Invalid state transition!"); |
| 531 | break; |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | QString |
| 537 | DeviceVerificationFlow::getUserId() |
| 538 | { |
| 539 | return QString::fromStdString(this->toClient.to_string()); |
| 540 | } |
| 541 | |
| 542 | QString |
| 543 | DeviceVerificationFlow::getDeviceId() |
| 544 | { |
| 545 | return this->deviceId; |
| 546 | } |
| 547 | |
| 548 | bool |
| 549 | DeviceVerificationFlow::getSender() |
| 550 | { |
| 551 | return this->sender; |
| 552 | } |
| 553 | |
| 554 | std::vector<int> |
| 555 | DeviceVerificationFlow::getSasList() |
| 556 | { |
| 557 | return this->sasList; |
| 558 | } |
| 559 | |
| 560 | bool |
| 561 | DeviceVerificationFlow::isSelfVerification() const |
| 562 | { |
| 563 | return this->toClient.to_string() == http::client()->user_id().to_string(); |
| 564 | } |
| 565 | |
| 566 | void |
| 567 | DeviceVerificationFlow::setEventId(const std::string &event_id_) |
| 568 | { |
| 569 | this->relation.rel_type = mtx::common::RelationType::Reference; |
| 570 | this->relation.event_id = event_id_; |
| 571 | this->transaction_id = event_id_; |
| 572 | } |
| 573 | |
| 574 | void |
| 575 | DeviceVerificationFlow::handleStartMessage(const mtx::events::msg::KeyVerificationStart &msg, |
| 576 | std::string) |
| 577 | { |
| 578 | if (state_ == Failed || state_ == Success) |
| 579 | return; |
| 580 | |
| 581 | if (msg.transaction_id.has_value()) { |
| 582 | if (msg.transaction_id.value() != this->transaction_id) |
| 583 | return; |
| 584 | } else if (msg.relations.references()) { |
| 585 | if (msg.relations.references() != this->relation.event_id) |
| 586 | return; |
| 587 | } else { |
| 588 | return; |
| 589 | } |
| 590 | |
| 591 | if (state_ == Failed) |
| 592 | return; |
| 593 | |
| 594 | if (msg.from_device != this->deviceId.toStdString()) { |
| 595 | cancelVerification(AcceptedOnOtherDevice); |
| 596 | return; |
| 597 | } |
| 598 | |
| 599 | nhlog::crypto()->info("verification: received start with mac methods {}", |
| 600 | fmt::join(msg.message_authentication_codes, ", ")); |
| 601 | |
| 602 | // TODO(Nico): Replace with contains once we use C++23 |
| 603 | if (std::ranges::count(msg.key_agreement_protocols, "curve25519-hkdf-sha256") && |
| 604 | std::ranges::count(msg.hashes, "sha256")) { |
| 605 | if (std::ranges::count(msg.message_authentication_codes, mac_method_alg_v2)) { |
| 606 | this->mac_method = mac_method_alg_v2; |
| 607 | } else if (std::ranges::count(msg.message_authentication_codes, mac_method_alg_v1)) { |
| 608 | this->mac_method = mac_method_alg_v1; |
| 609 | } else { |
| 610 | this->cancelVerification(DeviceVerificationFlow::Error::UnknownMethod); |
| 611 | return; |
| 612 | } |
| 613 | |
| 614 | if (std::ranges::count(msg.short_authentication_string, |
| 615 | mtx::events::msg::SASMethods::Emoji)) { |
| 616 | this->method = mtx::events::msg::SASMethods::Emoji; |
| 617 | } else if (std::ranges::count(msg.short_authentication_string, |
| 618 | mtx::events::msg::SASMethods::Decimal)) { |
| 619 | this->method = mtx::events::msg::SASMethods::Decimal; |
| 620 | } else { |
| 621 | this->cancelVerification(DeviceVerificationFlow::Error::UnknownMethod); |
| 622 | return; |
| 623 | } |
| 624 | |
| 625 | if (!sender) |
| 626 | this->canonical_json = nlohmann::json(msg).dump(); |
| 627 | else { |
| 628 | // resolve glare |
| 629 | if (std::tuple(this->toClient.to_string(), this->deviceId.toStdString()) < |
| 630 | std::tuple(utils::localUser().toStdString(), http::client()->device_id())) { |
| 631 | // treat this as if the user with the smaller mxid or smaller deviceid (if the mxid |
| 632 | // was the same) was the sender of "start" |
| 633 | this->canonical_json = nlohmann::json(msg).dump(); |
| 634 | this->sender = false; |
| 635 | } |
| 636 | |
| 637 | if (msg.method != mtx::events::msg::VerificationMethods::SASv1) { |
| 638 | cancelVerification(DeviceVerificationFlow::Error::UnknownMethod); |
| 639 | return; |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | // If we didn't send "start", accept the verification (otherwise wait for the other side to |
| 644 | // accept |
| 645 | if (state_ != PromptStartVerification && !sender) |
| 646 | this->acceptVerificationRequest(); |
| 647 | } else { |
| 648 | this->cancelVerification(DeviceVerificationFlow::Error::UnknownMethod); |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | //! accepts a verification |
| 653 | void |
| 654 | DeviceVerificationFlow::acceptVerificationRequest() |
| 655 | { |
| 656 | if (state_ == Failed || state_ == Success) |
| 657 | return; |
| 658 | |
| 659 | if (acceptSent) |
| 660 | return; |
| 661 | |
| 662 | if (mac_method.empty()) { |
| 663 | nhlog::crypto()->critical("Ignoring start without mac method set!"); |
| 664 | return; |
| 665 | } else { |
| 666 | nhlog::crypto()->debug("Accepted verification using mac_method {}", mac_method); |
| 667 | } |
| 668 | |
| 669 | acceptSent = true; |
| 670 | |
| 671 | mtx::events::msg::KeyVerificationAccept req; |
| 672 | |
| 673 | req.method = mtx::events::msg::VerificationMethods::SASv1; |
| 674 | req.key_agreement_protocol = "curve25519-hkdf-sha256"; |
| 675 | req.hash = "sha256"; |
| 676 | req.message_authentication_code = this->mac_method; |
| 677 | if (this->method == mtx::events::msg::SASMethods::Emoji) |
| 678 | req.short_authentication_string = {mtx::events::msg::SASMethods::Emoji}; |
| 679 | else if (this->method == mtx::events::msg::SASMethods::Decimal) |
| 680 | req.short_authentication_string = {mtx::events::msg::SASMethods::Decimal}; |
| 681 | req.commitment = mtx::crypto::bin2base64_unpadded( |
| 682 | mtx::crypto::sha256(this->sas->public_key() + this->canonical_json)); |
| 683 | |
| 684 | send(req); |
| 685 | setState(WaitingForKeys); |
| 686 | } |
| 687 | //! responds verification request |
| 688 | void |
| 689 | DeviceVerificationFlow::sendVerificationReady() |
| 690 | { |
| 691 | mtx::events::msg::KeyVerificationReady req; |
| 692 | |
| 693 | req.from_device = http::client()->device_id(); |
| 694 | req.methods = {mtx::events::msg::VerificationMethods::SASv1}; |
| 695 | |
| 696 | send(req); |
| 697 | setState(WaitingForKeys); |
| 698 | } |
| 699 | //! accepts a verification |
| 700 | void |
| 701 | DeviceVerificationFlow::sendVerificationDone() |
| 702 | { |
| 703 | mtx::events::msg::KeyVerificationDone req; |
| 704 | |
| 705 | send(req); |
| 706 | } |
| 707 | //! starts the verification flow |
| 708 | void |
| 709 | DeviceVerificationFlow::startVerificationRequest() |
| 710 | { |
| 711 | if (startSent) |
| 712 | return; |
| 713 | startSent = true; |
| 714 | |
| 715 | mtx::events::msg::KeyVerificationStart req; |
| 716 | |
| 717 | req.from_device = http::client()->device_id(); |
| 718 | req.method = mtx::events::msg::VerificationMethods::SASv1; |
| 719 | req.key_agreement_protocols = {"curve25519-hkdf-sha256"}; |
| 720 | req.hashes = {"sha256"}; |
| 721 | req.message_authentication_codes = {std::string(mac_method_alg_v1), |
| 722 | std::string(mac_method_alg_v2)}; |
| 723 | req.short_authentication_string = {mtx::events::msg::SASMethods::Decimal, |
| 724 | mtx::events::msg::SASMethods::Emoji}; |
| 725 | |
| 726 | if (this->type == DeviceVerificationFlow::Type::ToDevice) { |
| 727 | mtx::requests::ToDeviceMessages<mtx::events::msg::KeyVerificationStart> body; |
| 728 | req.transaction_id = this->transaction_id; |
| 729 | this->canonical_json = nlohmann::json(req).dump(); |
| 730 | } else if (this->type == DeviceVerificationFlow::Type::RoomMsg && model_) { |
| 731 | req.relations.relations.push_back(this->relation); |
| 732 | // Set synthesized to surpress the nheko relation extensions |
| 733 | req.relations.synthesized = true; |
| 734 | this->canonical_json = nlohmann::json(req).dump(); |
| 735 | } |
| 736 | send(req); |
| 737 | setState(WaitingForOtherToAccept); |
| 738 | } |
| 739 | //! sends a verification request |
| 740 | void |
| 741 | DeviceVerificationFlow::sendVerificationRequest() |
| 742 | { |
| 743 | mtx::events::msg::KeyVerificationRequest req; |
| 744 | |
| 745 | req.from_device = http::client()->device_id(); |
| 746 | req.methods = {mtx::events::msg::VerificationMethods::SASv1}; |
| 747 | |
| 748 | if (this->type == DeviceVerificationFlow::Type::ToDevice) { |
| 749 | QDateTime currentTime = QDateTime::currentDateTimeUtc(); |
| 750 | |
| 751 | req.timestamp = (uint64_t)currentTime.toMSecsSinceEpoch(); |
| 752 | |
| 753 | } else if (this->type == DeviceVerificationFlow::Type::RoomMsg && model_) { |
| 754 | req.to = this->toClient.to_string(); |
| 755 | req.msgtype = "m.key.verification.request"; |
| 756 | // clang-format off |
| 757 | // clang-format < 12 is buggy on this |
| 758 | req.body = "User is requesting to verify keys with you. However, your client does " |
| 759 | "not support this method, so you will need to use the legacy method of " |
| 760 | "key verification."; |
| 761 | // clang-format on |
| 762 | } |
| 763 | |
| 764 | send(req); |
| 765 | setState(WaitingForOtherToAccept); |
| 766 | } |
| 767 | //! cancels a verification flow |
| 768 | void |
| 769 | DeviceVerificationFlow::cancelVerification(DeviceVerificationFlow::Error error_code) |
| 770 | { |
| 771 | if (state_ == State::Success || state_ == State::Failed) |
| 772 | return; |
| 773 | |
| 774 | mtx::events::msg::KeyVerificationCancel req; |
| 775 | |
| 776 | if (error_code == DeviceVerificationFlow::Error::UnknownMethod) { |
| 777 | req.code = "m.unknown_method"; |
| 778 | req.reason = "unknown method received"; |
| 779 | } else if (error_code == DeviceVerificationFlow::Error::MismatchedCommitment) { |
| 780 | req.code = "m.mismatched_commitment"; |
| 781 | req.reason = "commitment didn't match"; |
| 782 | } else if (error_code == DeviceVerificationFlow::Error::MismatchedSAS) { |
| 783 | req.code = "m.mismatched_sas"; |
| 784 | req.reason = "sas didn't match"; |
| 785 | } else if (error_code == DeviceVerificationFlow::Error::KeyMismatch) { |
| 786 | req.code = "m.key_match"; |
| 787 | req.reason = "keys did not match"; |
| 788 | } else if (error_code == DeviceVerificationFlow::Error::Timeout) { |
| 789 | req.code = "m.timeout"; |
| 790 | req.reason = "timed out"; |
| 791 | } else if (error_code == DeviceVerificationFlow::Error::User) { |
| 792 | req.code = "m.user"; |
| 793 | req.reason = "user cancelled the verification"; |
| 794 | } else if (error_code == DeviceVerificationFlow::Error::OutOfOrder) { |
| 795 | req.code = "m.unexpected_message"; |
| 796 | req.reason = "received messages out of order"; |
| 797 | } |
| 798 | |
| 799 | this->error_ = error_code; |
| 800 | this->setState(Failed); |
| 801 | emit errorChanged(); |
| 802 | |
| 803 | // Don't cancel if the user accepted the request elsewhere, instead just silently stop |
| 804 | if (error_code != AcceptedOnOtherDevice) |
| 805 | send(req); |
| 806 | } |
| 807 | //! sends the verification key |
| 808 | void |
| 809 | DeviceVerificationFlow::sendVerificationKey() |
| 810 | { |
| 811 | if (keySent) |
| 812 | return; |
| 813 | keySent = true; |
| 814 | |
| 815 | mtx::events::msg::KeyVerificationKey req; |
| 816 | |
| 817 | req.key = this->sas->public_key(); |
| 818 | |
| 819 | send(req); |
| 820 | } |
| 821 | |
| 822 | //! sends the mac of the keys |
| 823 | void |
| 824 | DeviceVerificationFlow::sendVerificationMac() |
| 825 | { |
| 826 | if (macSent) |
| 827 | return; |
| 828 | macSent = true; |
| 829 | |
| 830 | nhlog::crypto()->debug("Sending mac using mac_method {}", mac_method); |
| 831 | |
| 832 | std::map<std::string, std::string> key_list; |
| 833 | key_list["ed25519:" + http::client()->device_id()] = olm::client()->identity_keys().ed25519; |
| 834 | |
| 835 | // send our master key, if we trust it |
| 836 | if (!this->our_trusted_master_key.empty()) |
| 837 | key_list["ed25519:" + our_trusted_master_key] = our_trusted_master_key; |
| 838 | |
| 839 | mtx::events::msg::KeyVerificationMac req = sas->calculate_mac(mac_method, |
| 840 | http::client()->user_id(), |
| 841 | http::client()->device_id(), |
| 842 | this->toClient, |
| 843 | this->deviceId.toStdString(), |
| 844 | this->transaction_id, |
| 845 | key_list); |
| 846 | |
| 847 | send(req); |
| 848 | |
| 849 | setState(WaitingForMac); |
| 850 | acceptDevice(); |
| 851 | } |
| 852 | //! Completes the verification flow |
| 853 | void |
| 854 | DeviceVerificationFlow::acceptDevice() |
| 855 | { |
| 856 | if (!isMacVerified) { |
| 857 | setState(WaitingForMac); |
| 858 | } else if (state_ == WaitingForMac) { |
| 859 | cache::markDeviceVerified(this->toClient.to_string(), this->deviceId.toStdString()); |
| 860 | this->sendVerificationDone(); |
| 861 | setState(Success); |
| 862 | |
| 863 | // Request secrets. We should probably check somehow, if a device knowns about the |
| 864 | // secrets. |
| 865 | if (utils::localUser().toStdString() == this->toClient.to_string() && |
| 866 | (!cache::secret(mtx::secret_storage::secrets::cross_signing_self_signing) || |
| 867 | !cache::secret(mtx::secret_storage::secrets::cross_signing_user_signing))) { |
| 868 | olm::request_cross_signing_keys(); |
| 869 | } |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | void |
| 874 | DeviceVerificationFlow::unverify() |
| 875 | { |
| 876 | cache::markDeviceUnverified(this->toClient.to_string(), this->deviceId.toStdString()); |
| 877 | |
| 878 | emit refreshProfile(); |
| 879 | } |
| 880 | |
| 881 | QSharedPointer<DeviceVerificationFlow> |
| 882 | DeviceVerificationFlow::NewInRoomVerification(QObject *parent_, |
| 883 | TimelineModel *timelineModel_, |
| 884 | const mtx::events::msg::KeyVerificationRequest &msg, |
| 885 | const QString &other_user_, |
| 886 | const QString &event_id_) |
| 887 | { |
| 888 | QSharedPointer<DeviceVerificationFlow> flow( |
| 889 | new DeviceVerificationFlow(parent_, |
| 890 | Type::RoomMsg, |
| 891 | timelineModel_, |
| 892 | other_user_, |
| 893 | {QString::fromStdString(msg.from_device)})); |
| 894 | |
| 895 | flow->setEventId(event_id_.toStdString()); |
| 896 | |
| 897 | if (std::find(msg.methods.begin(), |
| 898 | msg.methods.end(), |
| 899 | mtx::events::msg::VerificationMethods::SASv1) == msg.methods.end()) { |
| 900 | flow->cancelVerification(UnknownMethod); |
| 901 | } |
| 902 | |
| 903 | return flow; |
| 904 | } |
| 905 | QSharedPointer<DeviceVerificationFlow> |
| 906 | DeviceVerificationFlow::NewToDeviceVerification(QObject *parent_, |
| 907 | const mtx::events::msg::KeyVerificationRequest &msg, |
| 908 | const QString &other_user_, |
| 909 | const QString &txn_id_) |
| 910 | { |
| 911 | QSharedPointer<DeviceVerificationFlow> flow(new DeviceVerificationFlow( |
| 912 | parent_, Type::ToDevice, nullptr, other_user_, {QString::fromStdString(msg.from_device)})); |
| 913 | flow->transaction_id = txn_id_.toStdString(); |
| 914 | |
| 915 | if (std::find(msg.methods.begin(), |
| 916 | msg.methods.end(), |
| 917 | mtx::events::msg::VerificationMethods::SASv1) == msg.methods.end()) { |
| 918 | flow->cancelVerification(UnknownMethod); |
| 919 | } |
| 920 | |
| 921 | return flow; |
| 922 | } |
| 923 | QSharedPointer<DeviceVerificationFlow> |
| 924 | DeviceVerificationFlow::NewToDeviceVerification(QObject *parent_, |
| 925 | const mtx::events::msg::KeyVerificationStart &msg, |
| 926 | const QString &other_user_, |
| 927 | const QString &txn_id_) |
| 928 | { |
| 929 | QSharedPointer<DeviceVerificationFlow> flow(new DeviceVerificationFlow( |
| 930 | parent_, Type::ToDevice, nullptr, other_user_, {QString::fromStdString(msg.from_device)})); |
| 931 | flow->transaction_id = txn_id_.toStdString(); |
| 932 | |
| 933 | flow->handleStartMessage(msg, ""); |
| 934 | |
| 935 | return flow; |
| 936 | } |
| 937 | QSharedPointer<DeviceVerificationFlow> |
| 938 | DeviceVerificationFlow::InitiateUserVerification(QObject *parent_, |
| 939 | TimelineModel *timelineModel_, |
| 940 | const QString &userid) |
| 941 | { |
| 942 | QSharedPointer<DeviceVerificationFlow> flow( |
| 943 | new DeviceVerificationFlow(parent_, Type::RoomMsg, timelineModel_, userid, {})); |
| 944 | flow->sender = true; |
| 945 | return flow; |
| 946 | } |
| 947 | QSharedPointer<DeviceVerificationFlow> |
| 948 | DeviceVerificationFlow::InitiateDeviceVerification(QObject *parent_, |
| 949 | const QString &userid, |
| 950 | const std::vector<QString> &devices) |
| 951 | { |
| 952 | assert(!devices.empty()); |
| 953 | |
| 954 | QSharedPointer<DeviceVerificationFlow> flow( |
| 955 | new DeviceVerificationFlow(parent_, Type::ToDevice, nullptr, userid, devices)); |
| 956 | |
| 957 | flow->sender = true; |
| 958 | flow->transaction_id = http::client()->generate_txn_id(); |
| 959 | |
| 960 | return flow; |
| 961 | } |
| 962 | template<typename T> |
| 963 | void |
| 964 | DeviceVerificationFlow::send(T msg) |
| 965 | { |
| 966 | if (this->type == DeviceVerificationFlow::Type::ToDevice) { |
| 967 | mtx::requests::ToDeviceMessages<T> body; |
| 968 | msg.transaction_id = this->transaction_id; |
| 969 | for (const auto &d : deviceIds) |
| 970 | body[this->toClient][d.toStdString()] = msg; |
| 971 | |
| 972 | http::client()->send_to_device<T>( |
| 973 | http::client()->generate_txn_id(), body, [](mtx::http::RequestErr err) { |
| 974 | if (err) |
| 975 | nhlog::net()->warn("failed to send verification to_device message: {} {}", |
| 976 | err->matrix_error.error, |
| 977 | static_cast<int>(err->status_code)); |
| 978 | }); |
| 979 | } else if (this->type == DeviceVerificationFlow::Type::RoomMsg && model_) { |
| 980 | if constexpr (!std::is_same_v<T, mtx::events::msg::KeyVerificationRequest>) { |
| 981 | msg.relations.relations.push_back(this->relation); |
| 982 | // Set synthesized to surpress the nheko relation extensions |
| 983 | msg.relations.synthesized = true; |
| 984 | } |
| 985 | (model_)->sendMessageEvent(msg, mtx::events::to_device_content_to_type<T>); |
| 986 | } |
| 987 | |
| 988 | nhlog::net()->debug("Sent verification step: {} in state: {}", |
| 989 | mtx::events::to_string(mtx::events::to_device_content_to_type<T>), |
| 990 | state().toStdString()); |
| 991 | } |
| 992 | |
| 993 | #include "moc_DeviceVerificationFlow.cpp" |