Debian Codegraph @

src/encryption/SelfVerificationStatus.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "SelfVerificationStatus.h"
6
7 #include <QApplication>
8
9 #include <nlohmann/json.hpp>
10
11 #include <mtx/responses/common.hpp>
12
13 #include "Cache.h"
14 #include "Cache_p.h"
15 #include "ChatPage.h"
16 #include "Logging.h"
17 #include "MatrixClient.h"
18 #include "Olm.h"
19 #include "encryption/VerificationManager.h"
20 #include "timeline/TimelineViewManager.h"
21 #include "ui/UIA.h"
22
23 SelfVerificationStatus::SelfVerificationStatus(QObject *o)
24 : QObject(o)
25 {
26 connect(ChatPage::instance(), &ChatPage::contentLoaded, this, [this] {
27 // We connect INSIDE a lambda, not A lambda...
28 connect(cache::client(),
29 &Cache::selfVerificationStatusChanged,
30 this,
31 &SelfVerificationStatus::invalidate,
32 Qt::UniqueConnection); // clazy:exclude=lambda-unique-connection
33 cache::client()->markUserKeysOutOfDate({http::client()->user_id().to_string()});
34 });
35
36 connect(ChatPage::instance(),
37 &ChatPage::initializeEmptyViews,
38 this,
39 &SelfVerificationStatus::invalidate);
40 }
41
42 void
43 SelfVerificationStatus::setupCrosssigning(bool useSSSS,
44 const QString &password,
45 bool useOnlineKeyBackup)
46 {
47 nhlog::db()->info("Clicked setup crossigning");
48
49 auto xsign_keys = olm::client()->create_crosssigning_keys();
50
51 if (!xsign_keys) {
52 nhlog::crypto()->critical("Failed to setup cross-signing keys!");
53 emit setupFailed(tr("Failed to create keys for cross-signing!"));
54 return;
55 }
56
57 cache::client()->storeSecret(mtx::secret_storage::secrets::cross_signing_master,
58 xsign_keys->private_master_key);
59 cache::client()->storeSecret(mtx::secret_storage::secrets::cross_signing_self_signing,
60 xsign_keys->private_self_signing_key);
61 cache::client()->storeSecret(mtx::secret_storage::secrets::cross_signing_user_signing,
62 xsign_keys->private_user_signing_key);
63
64 std::optional<mtx::crypto::OlmClient::OnlineKeyBackupSetup> okb;
65 if (useOnlineKeyBackup) {
66 okb = olm::client()->create_online_key_backup(xsign_keys->private_master_key);
67 if (!okb) {
68 nhlog::crypto()->critical("Failed to setup online key backup!");
69 emit setupFailed(tr("Failed to create keys for online key backup!"));
70 return;
71 }
72
73 cache::client()->storeSecret(
74 mtx::secret_storage::secrets::megolm_backup_v1,
75 mtx::crypto::bin2base64(mtx::crypto::to_string(okb->privateKey)));
76
77 http::client()->post_backup_version(
78 okb->backupVersion.algorithm,
79 okb->backupVersion.auth_data,
80 [](const mtx::responses::Version &v, mtx::http::RequestErr e) {
81 if (e) {
82 nhlog::net()->error("error setting up online key backup: {} {} {} {}",
83 e->parse_error,
84 e->status_code,
85 e->error_code,
86 e->matrix_error.error);
87 } else {
88 nhlog::crypto()->info("Set up online key backup: '{}'", v.version);
89 }
90 });
91 }
92
93 std::optional<mtx::crypto::OlmClient::SSSSSetup> ssss;
94 if (useSSSS) {
95 ssss = olm::client()->create_ssss_key(password.toStdString());
96 if (!ssss) {
97 nhlog::crypto()->critical("Failed to setup secure server side secret storage!");
98 emit setupFailed(tr("Failed to create keys for secure server side secret storage!"));
99 return;
100 }
101
102 auto master = mtx::crypto::PkSigning::from_seed(xsign_keys->private_master_key);
103 nlohmann::json j = ssss->keyDescription;
104 j.erase("signatures");
105 ssss->keyDescription
106 .signatures[http::client()->user_id().to_string()]["ed25519:" + master.public_key()] =
107 master.sign(j.dump());
108
109 http::client()->upload_secret_storage_key(
110 ssss->keyDescription.name, ssss->keyDescription, [](mtx::http::RequestErr) {});
111 http::client()->set_secret_storage_default_key(ssss->keyDescription.name,
112 [](mtx::http::RequestErr) {});
113
114 auto uploadSecret = [ssss](std::string_view key_name, const std::string &secret) {
115 mtx::secret_storage::Secret s;
116 s.encrypted[ssss->keyDescription.name] =
117 mtx::crypto::encrypt(secret, ssss->privateKey, key_name);
118 http::client()->upload_secret_storage_secret(
119 key_name, s, [key_name](mtx::http::RequestErr) {
120 nhlog::crypto()->info("Uploaded secret: {}", key_name);
121 });
122 };
123
124 uploadSecret(mtx::secret_storage::secrets::cross_signing_master,
125 xsign_keys->private_master_key);
126 uploadSecret(mtx::secret_storage::secrets::cross_signing_self_signing,
127 xsign_keys->private_self_signing_key);
128 uploadSecret(mtx::secret_storage::secrets::cross_signing_user_signing,
129 xsign_keys->private_user_signing_key);
130
131 if (okb)
132 uploadSecret(mtx::secret_storage::secrets::megolm_backup_v1,
133 mtx::crypto::bin2base64(mtx::crypto::to_string(okb->privateKey)));
134 }
135
136 mtx::requests::DeviceSigningUpload device_sign{};
137 device_sign.master_key = xsign_keys->master_key;
138 device_sign.self_signing_key = xsign_keys->self_signing_key;
139 device_sign.user_signing_key = xsign_keys->user_signing_key;
140 http::client()->device_signing_upload(
141 device_sign,
142 UIA::instance()->genericHandler(tr("Encryption Setup")),
143 [this, ssss, xsign_keys](mtx::http::RequestErr e) {
144 if (e) {
145 nhlog::crypto()->critical("Failed to upload cross signing keys: {}",
146 e->matrix_error.error);
147
148 emit setupFailed(tr("Encryption setup failed: %1")
149 .arg(QString::fromStdString(e->matrix_error.error)));
150 return;
151 }
152 nhlog::crypto()->info("Crosssigning keys uploaded!");
153
154 auto deviceKeys = cache::client()->userKeys(http::client()->user_id().to_string());
155 if (deviceKeys) {
156 auto myKey = deviceKeys->device_keys.at(http::client()->device_id());
157 if (myKey.user_id == http::client()->user_id().to_string() &&
158 myKey.device_id == http::client()->device_id() &&
159 myKey.keys["ed25519:" + http::client()->device_id()] ==
160 olm::client()->identity_keys().ed25519 &&
161 myKey.keys["curve25519:" + http::client()->device_id()] ==
162 olm::client()->identity_keys().curve25519) {
163 nlohmann::json j = myKey;
164 j.erase("signatures");
165 j.erase("unsigned");
166
167 auto ssk =
168 mtx::crypto::PkSigning::from_seed(xsign_keys->private_self_signing_key);
169 myKey.signatures[http::client()->user_id().to_string()]
170 ["ed25519:" + ssk.public_key()] = ssk.sign(j.dump());
171 mtx::requests::KeySignaturesUpload req;
172 req.signatures[http::client()->user_id().to_string()]
173 [http::client()->device_id()] = myKey;
174
175 http::client()->keys_signatures_upload(
176 req,
177 [](const mtx::responses::KeySignaturesUpload &res, mtx::http::RequestErr err) {
178 if (err) {
179 nhlog::net()->error("failed to upload signatures: {},{}",
180 mtx::errors::to_string(err->matrix_error.errcode),
181 static_cast<int>(err->status_code));
182 }
183
184 // MSVC bug, error C3493: 'key_id' cannot be implicitly captured because no
185 // default capture mode has been specified
186 // for (const auto &[user_id, tmp] : res.errors)
187 // for (const auto &[key_id, e_] : tmp)
188 // nhlog::net()->error("signature error for user {} and key "
189 // "id {}: {}, {}",
190 // user_id,
191 // key_id,
192 // mtx::errors::to_string(e_.errcode),
193 // e_.error);
194 for (const auto &error : res.errors) {
195 const auto &user_id = error.first;
196 for (const auto &key_error : error.second) {
197 const auto &key_id = key_error.first;
198 const auto &e_ = key_error.second;
199
200 nhlog::net()->error("signature error for user {} and key "
201 "id {}: {}, {}",
202 user_id,
203 key_id,
204 mtx::errors::to_string(e_.errcode),
205 e_.error);
206 }
207 }
208 });
209 }
210 }
211
212 if (ssss) {
213 auto k = QString::fromStdString(mtx::crypto::key_to_recoverykey(ssss->privateKey));
214
215 QString r;
216 for (int i = 0; i < k.size(); i += 4)
217 r += k.mid(i, 4) + " ";
218
219 emit showRecoveryKey(r.trimmed());
220 } else {
221 emit setupCompleted();
222 }
223 });
224 }
225
226 void
227 SelfVerificationStatus::verifyMasterKey()
228 {
229 nhlog::db()->info("Clicked verify master key");
230
231 const auto this_user = http::client()->user_id().to_string();
232
233 auto keys = cache::client()->userKeys(this_user);
234 const auto &sigs = keys->master_keys.signatures[this_user];
235
236 std::vector<QString> devices;
237 for (const auto &[dev, sig] : sigs) {
238 (void)sig;
239
240 auto d = QString::fromStdString(dev);
241 if (d.startsWith(QLatin1String("ed25519:"))) {
242 d.remove(QStringLiteral("ed25519:"));
243
244 if (keys->device_keys.count(d.toStdString()))
245 devices.push_back(std::move(d));
246 }
247 }
248
249 if (!devices.empty())
250 ChatPage::instance()->timelineManager()->verificationManager()->verifyOneOfDevices(
251 QString::fromStdString(this_user), std::move(devices));
252 else
253 nhlog::db()->info("No devices to verify");
254 }
255
256 void
257 SelfVerificationStatus::verifyMasterKeyWithPassphrase()
258 {
259 nhlog::db()->info("Clicked verify master key with passphrase");
260 olm::download_cross_signing_keys();
261 }
262
263 void
264 SelfVerificationStatus::verifyUnverifiedDevices()
265 {
266 nhlog::db()->info("Clicked verify unverified devices");
267 const auto this_user = http::client()->user_id().to_string();
268
269 auto keys = cache::client()->userKeys(this_user);
270 auto verif = cache::client()->verificationStatus(this_user);
271
272 if (!keys)
273 return;
274
275 std::vector<QString> devices;
276 for (const auto &[device, keys_] : keys->device_keys) {
277 (void)keys_;
278 if (!verif.verified_devices.count(device))
279 devices.push_back(QString::fromStdString(device));
280 }
281
282 if (!devices.empty())
283 ChatPage::instance()->timelineManager()->verificationManager()->verifyOneOfDevices(
284 QString::fromStdString(this_user), std::move(devices));
285 }
286
287 void
288 SelfVerificationStatus::invalidate()
289 {
290 using namespace mtx::secret_storage;
291
292 nhlog::db()->debug("Invalidating self verification status");
293 if (!cache::isInitialized()) {
294 nhlog::db()->warn("SelfVerificationStatus: cache not initialized");
295 return;
296 }
297
298 this->hasSSSS_ = false;
299 emit hasSSSSChanged();
300
301 auto keys = cache::client()->userKeys(http::client()->user_id().to_string());
302 if (!keys || keys->device_keys.find(http::client()->device_id()) == keys->device_keys.end()) {
303 if (keys && (keys->seen_device_ids.count(http::client()->device_id()) ||
304 keys->seen_device_keys.count(olm::client()->identity_keys().curve25519))) {
305 emit ChatPage::instance()->dropToLoginPageCb(
306 tr("Identity key changed. This breaks E2EE, so logging out."));
307 return;
308 }
309
310 cache::client()->markUserKeysOutOfDate({http::client()->user_id().to_string()});
311
312 QTimer::singleShot(1'000, this, [] {
313 cache::client()->query_keys(http::client()->user_id().to_string(),
314 [](const UserKeyCache &, mtx::http::RequestErr) {});
315 });
316 }
317
318 if (keys->master_keys.keys.empty()) {
319 if (status_ != SelfVerificationStatus::NoMasterKey) {
320 this->status_ = SelfVerificationStatus::NoMasterKey;
321 emit statusChanged();
322 }
323 return;
324 }
325
326 http::client()->secret_storage_secret(secrets::cross_signing_self_signing,
327 [this](Secret secret, mtx::http::RequestErr err) {
328 if (!err && !secret.encrypted.empty()) {
329 this->hasSSSS_ = true;
330 emit hasSSSSChanged();
331 }
332 });
333
334 auto verifStatus = cache::client()->verificationStatus(http::client()->user_id().to_string());
335
336 if (!verifStatus.user_verified) {
337 if (status_ != SelfVerificationStatus::UnverifiedMasterKey) {
338 this->status_ = SelfVerificationStatus::UnverifiedMasterKey;
339 emit statusChanged();
340 }
341 return;
342 }
343
344 if (verifStatus.unverified_device_count > 0) {
345 if (status_ != SelfVerificationStatus::UnverifiedDevices) {
346 this->status_ = SelfVerificationStatus::UnverifiedDevices;
347 emit statusChanged();
348 }
349 return;
350 }
351
352 if (status_ != SelfVerificationStatus::AllVerified) {
353 this->status_ = SelfVerificationStatus::AllVerified;
354 emit statusChanged();
355 return;
356 }
357 }
358
359 #include "moc_SelfVerificationStatus.cpp"