Debian Codegraph @

mtxclient/lib/crypto/client.cpp

raw symbols SCIP
1 #include <cstdint>
2 #include <nlohmann/json.hpp>
3 #include <utility>
4
5 #include <openssl/aes.h>
6 #include <openssl/sha.h>
7
8 #include "mtxclient/crypto/client.hpp"
9 #include "mtxclient/crypto/types.hpp"
10 #include "mtxclient/crypto/utils.hpp"
11
12 #include "mtx/log.hpp"
13
14 using json = nlohmann::json;
15 using namespace mtx::crypto;
16
17 static constexpr auto pwhash_SALTBYTES = 16u;
18
19 void
20 OlmClient::create_new_account()
21 {
22 account_ = create_olm_object<AccountObject>();
23
24 auto tmp_buf = create_buffer(olm_create_account_random_length(account_.get()));
25 auto ret = olm_create_account(account_.get(), tmp_buf.data(), tmp_buf.size());
26
27 if (ret == olm_error())
28 throw olm_exception("create_new_account", account_.get());
29 }
30
31 void
32 OlmClient::restore_account(const std::string &saved_data, const std::string &key)
33 {
34 account_ = unpickle<AccountObject>(saved_data, key);
35 }
36
37 mtx::crypto::IdentityKeys
38 OlmClient::identity_keys() const
39 {
40 if (!account_)
41 throw olm_exception("identity_keys", account_.get());
42
43 auto tmp_buf = create_buffer(olm_account_identity_keys_length(account_.get()));
44 auto ret = olm_account_identity_keys(account_.get(), (void *)tmp_buf.data(), tmp_buf.size());
45
46 if (ret == olm_error())
47 throw olm_exception("identity_keys", account_.get());
48
49 return json::parse(std::string(tmp_buf.begin(), tmp_buf.end()))
50 .get<mtx::crypto::IdentityKeys>();
51 }
52
53 std::string
54 OlmClient::sign_message(const std::string &msg) const
55 {
56 auto signature_buf = create_buffer(olm_account_signature_length(account_.get()));
57 olm_account_sign(
58 account_.get(), msg.data(), msg.size(), signature_buf.data(), signature_buf.size());
59
60 return {signature_buf.begin(), signature_buf.end()};
61 }
62
63 std::string
64 OlmClient::sign_identity_keys()
65 {
66 auto keys = identity_keys();
67
68 json body{{"algorithms", {"m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"}},
69 {"user_id", user_id_},
70 {"device_id", device_id_},
71 {"keys",
72 {
73 {"curve25519:" + device_id_, keys.curve25519},
74 {"ed25519:" + device_id_, keys.ed25519},
75 }}};
76
77 return sign_message(body.dump());
78 }
79
80 std::size_t
81 OlmClient::generate_one_time_keys(std::size_t number_of_keys, bool generate_fallback)
82 {
83 const std::size_t nbytes =
84 olm_account_generate_one_time_keys_random_length(account_.get(), number_of_keys);
85
86 auto buf = create_buffer(nbytes);
87
88 auto ret =
89 olm_account_generate_one_time_keys(account_.get(), number_of_keys, buf.data(), buf.size());
90
91 if (ret == olm_error())
92 throw olm_exception("generate_one_time_keys", account_.get());
93
94 if (generate_fallback) {
95 const std::size_t fnbytes = olm_account_generate_fallback_key_random_length(account_.get());
96 buf = create_buffer(fnbytes);
97 auto temp = olm_account_generate_fallback_key(account_.get(), buf.data(), buf.size());
98 if (temp == olm_error())
99 throw olm_exception("generate_fallback_keys", account_.get());
100 }
101
102 return ret;
103 }
104
105 mtx::crypto::OneTimeKeys
106 OlmClient::one_time_keys()
107 {
108 auto buf = create_buffer(olm_account_one_time_keys_length(account_.get()));
109
110 const auto ret = olm_account_one_time_keys(account_.get(), buf.data(), buf.size());
111
112 if (ret == olm_error())
113 throw olm_exception("one_time_keys", account_.get());
114
115 return json::parse(std::string(buf.begin(), buf.end())).get<mtx::crypto::OneTimeKeys>();
116 }
117
118 mtx::crypto::OneTimeKeys
119 OlmClient::unpublished_fallback_keys()
120 {
121 auto fbuf = create_buffer(olm_account_unpublished_fallback_key_length(account_.get()));
122
123 const auto fret =
124 olm_account_unpublished_fallback_key(account_.get(), fbuf.data(), fbuf.size());
125 if (fret == olm_error())
126 throw olm_exception("unpublished_fallback_keys", account_.get());
127
128 return json::parse(std::string(fbuf.begin(), fbuf.end())).get<mtx::crypto::OneTimeKeys>();
129 }
130
131 std::string
132 OlmClient::sign_one_time_key(const std::string &key, bool fallback)
133 {
134 json j{{"key", key}};
135 if (fallback)
136 j["fallback"] = true;
137 return sign_message(j.dump());
138 }
139
140 std::map<std::string, mtx::requests::SignedOneTimeKey>
141 OlmClient::sign_one_time_keys(const OneTimeKeys &keys, bool fallback)
142 {
143 // Sign & append the one time keys.
144 std::map<std::string, mtx::requests::SignedOneTimeKey> signed_one_time_keys;
145 for (const auto &elem : keys.curve25519) {
146 const auto key_id = elem.first;
147 const auto one_time_key = elem.second;
148
149 auto sig = sign_one_time_key(one_time_key, fallback);
150
151 signed_one_time_keys["signed_curve25519:" + key_id] =
152 signed_one_time_key(one_time_key, sig, fallback);
153 }
154
155 return signed_one_time_keys;
156 }
157
158 mtx::requests::SignedOneTimeKey
159 OlmClient::signed_one_time_key(const std::string &key, const std::string &signature, bool fallback)
160 {
161 mtx::requests::SignedOneTimeKey sign{};
162 sign.key = key;
163 sign.fallback = fallback;
164 sign.signatures = {{user_id_, {{"ed25519:" + device_id_, signature}}}};
165 return sign;
166 }
167
168 mtx::requests::UploadKeys
169 OlmClient::create_upload_keys_request()
170 {
171 return create_upload_keys_request(one_time_keys(), unpublished_fallback_keys());
172 }
173
174 mtx::requests::UploadKeys
175 OlmClient::create_upload_keys_request(const mtx::crypto::OneTimeKeys &one_time_keys,
176 const mtx::crypto::OneTimeKeys &fallback_keys)
177 {
178 mtx::requests::UploadKeys req;
179 req.device_keys.user_id = user_id_;
180 req.device_keys.device_id = device_id_;
181
182 auto id_keys = identity_keys();
183
184 req.device_keys.keys["curve25519:" + device_id_] = id_keys.curve25519;
185 req.device_keys.keys["ed25519:" + device_id_] = id_keys.ed25519;
186
187 // Generate and add the signature to the request.
188 auto sig = sign_identity_keys();
189
190 req.device_keys.signatures[user_id_]["ed25519:" + device_id_] = sig;
191
192 // Sign & append the one time keys.
193 auto temp = sign_one_time_keys(one_time_keys);
194 for (const auto &[key_id, key] : temp)
195 req.one_time_keys[key_id] = key;
196
197 temp = sign_one_time_keys(fallback_keys, true);
198 for (const auto &[key_id, key] : temp) {
199 req.fallback_keys[key_id] = key;
200 }
201
202 return req;
203 }
204
205 std::optional<OlmClient::CrossSigningSetup>
206 OlmClient::create_crosssigning_keys()
207 {
208 auto master = PkSigning::new_key();
209 auto user_signing = PkSigning::new_key();
210 auto self_signing = PkSigning::new_key();
211
212 CrossSigningSetup setup{};
213 setup.private_master_key = master.seed();
214 setup.private_user_signing_key = user_signing.seed();
215 setup.private_self_signing_key = self_signing.seed();
216
217 // master key
218 setup.master_key.usage = {"master"};
219 setup.master_key.user_id = user_id_;
220 setup.master_key.keys["ed25519:" + master.public_key()] = master.public_key();
221
222 nlohmann::json master_j = setup.master_key;
223 master_j.erase("unsigned");
224 master_j.erase("signatures");
225 setup.master_key.signatures[user_id_]["ed25519:" + master.public_key()] =
226 master.sign(master_j.dump());
227 setup.master_key.signatures[user_id_]["ed25519:" + device_id_] = sign_message(master_j.dump());
228
229 // user_signing_key
230 setup.user_signing_key.usage = {"user_signing"};
231 setup.user_signing_key.user_id = user_id_;
232 setup.user_signing_key.keys["ed25519:" + user_signing.public_key()] = user_signing.public_key();
233
234 nlohmann::json user_signing_j = setup.user_signing_key;
235 user_signing_j.erase("unsigned");
236 user_signing_j.erase("signatures");
237 setup.user_signing_key.signatures[user_id_]["ed25519:" + user_signing.public_key()] =
238 user_signing.sign(user_signing_j.dump());
239 setup.user_signing_key.signatures[user_id_]["ed25519:" + master.public_key()] =
240 master.sign(user_signing_j.dump());
241
242 // self_signing_key
243 setup.self_signing_key.usage = {"self_signing"};
244 setup.self_signing_key.user_id = user_id_;
245 setup.self_signing_key.keys["ed25519:" + self_signing.public_key()] = self_signing.public_key();
246
247 nlohmann::json self_signing_j = setup.self_signing_key;
248 self_signing_j.erase("unsigned");
249 self_signing_j.erase("signatures");
250 setup.self_signing_key.signatures[user_id_]["ed25519:" + self_signing.public_key()] =
251 self_signing.sign(self_signing_j.dump());
252 setup.self_signing_key.signatures[user_id_]["ed25519:" + master.public_key()] =
253 master.sign(self_signing_j.dump());
254
255 return setup;
256 }
257
258 std::optional<OlmClient::OnlineKeyBackupSetup>
259 OlmClient::create_online_key_backup(const std::string &masterKey)
260 {
261 OnlineKeyBackupSetup setup{};
262
263 auto key = create_buffer(olm_pk_private_key_length());
264 setup.privateKey = key;
265
266 json auth_data;
267 auth_data["public_key"] = bin2base64_unpadded(CURVE25519_public_key_from_private(key));
268 auto master = PkSigning::from_seed(masterKey);
269
270 auto sig = master.sign(auth_data.dump());
271 auth_data["signatures"][user_id_]["ed25519:" + master.public_key()] = sig;
272
273 setup.backupVersion.auth_data = auth_data.dump();
274 setup.backupVersion.algorithm = "m.megolm_backup.v1.curve25519-aes-sha2";
275
276 return setup;
277 }
278
279 std::optional<OlmClient::SSSSSetup>
280 OlmClient::create_ssss_key(const std::string &password)
281 {
282 OlmClient::SSSSSetup setup{};
283
284 if (password.empty()) {
285 setup.privateKey = create_buffer(32);
286 } else {
287 mtx::secret_storage::PBKDF2 pbkdf2{};
288 pbkdf2.algorithm = "m.pbkdf2";
289 // OWASP recommends 210'000 in 2023
290 // https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2
291 // We started out with 500'000 iterations, so we should still have a long time until we need
292 // to prompt users to upgrade and then we might want to go argon2 directly.
293 pbkdf2.iterations = 630'000;
294 pbkdf2.bits = 256; // 32 * 8
295 pbkdf2.salt = bin2base64(to_string(create_buffer(32)));
296
297 setup.privateKey = mtx::crypto::PBKDF2_HMAC_SHA_512(
298 password, to_binary_buf(pbkdf2.salt), pbkdf2.iterations, pbkdf2.bits / 8);
299 setup.keyDescription.passphrase = pbkdf2;
300 }
301
302 setup.keyDescription.algorithm = "m.secret_storage.v1.aes-hmac-sha2";
303 setup.keyDescription.name = bin2base58(to_string(create_buffer(16))); // create a random name
304 setup.keyDescription.iv = bin2base64(to_string(compatible_iv(create_buffer(32))));
305
306 auto testKeys = HKDF_SHA256(setup.privateKey, BinaryBuf(32, 0), BinaryBuf{});
307
308 auto encrypted = AES_CTR_256_Encrypt(
309 std::string(32, '\0'), testKeys.aes, to_binary_buf(base642bin(setup.keyDescription.iv)));
310
311 setup.keyDescription.mac = bin2base64(to_string(HMAC_SHA256(testKeys.mac, encrypted)));
312
313 return setup;
314 }
315
316 OutboundGroupSessionPtr
317 OlmClient::init_outbound_group_session()
318 {
319 auto session = create_olm_object<OutboundSessionObject>();
320 auto tmp_buf = create_buffer(olm_init_outbound_group_session_random_length(session.get()));
321
322 const auto ret = olm_init_outbound_group_session(session.get(), tmp_buf.data(), tmp_buf.size());
323
324 if (ret == olm_error())
325 throw olm_exception("init_outbound_group_session", session.get());
326
327 return session;
328 }
329
330 InboundGroupSessionPtr
331 OlmClient::init_inbound_group_session(const std::string &session_key)
332 {
333 auto session = create_olm_object<InboundSessionObject>();
334
335 auto temp = session_key;
336 const auto ret = olm_init_inbound_group_session(
337 session.get(), reinterpret_cast<const uint8_t *>(temp.data()), temp.size());
338
339 if (ret == olm_error())
340 throw olm_exception("init_inbound_group_session", session.get());
341
342 return session;
343 }
344
345 InboundGroupSessionPtr
346 OlmClient::import_inbound_group_session(const std::string &session_key)
347 {
348 auto session = create_olm_object<InboundSessionObject>();
349
350 auto temp = session_key;
351 const auto ret = olm_import_inbound_group_session(
352 session.get(), reinterpret_cast<const uint8_t *>(temp.data()), temp.size());
353
354 if (ret == olm_error())
355 throw olm_exception("init_inbound_group_session", session.get());
356
357 return session;
358 }
359
360 GroupPlaintext
361 OlmClient::decrypt_group_message(OlmInboundGroupSession *session,
362 const std::string &message,
363 uint32_t message_index)
364 {
365 if (!session)
366 throw olm_exception("decrypt_group_message", session);
367
368 auto tmp_msg = create_buffer(message.size());
369 std::copy(message.begin(), message.end(), tmp_msg.begin());
370
371 auto plaintext_len =
372 olm_group_decrypt_max_plaintext_length(session, tmp_msg.data(), tmp_msg.size());
373 if (plaintext_len == olm_error())
374 throw olm_exception("olm_group_decrypt_max_plaintext_length: invalid ciphertext", session);
375 auto plaintext = create_buffer(plaintext_len);
376
377 tmp_msg = create_buffer(message.size());
378 std::copy(message.begin(), message.end(), tmp_msg.begin());
379
380 const std::size_t nbytes = olm_group_decrypt(
381 session, tmp_msg.data(), tmp_msg.size(), plaintext.data(), plaintext.size(), &message_index);
382
383 if (nbytes == olm_error())
384 throw olm_exception("olm_group_decrypt", session);
385
386 auto output = create_buffer(nbytes);
387 std::memcpy(output.data(), plaintext.data(), nbytes);
388
389 return GroupPlaintext{std::move(output), message_index};
390 }
391
392 BinaryBuf
393 OlmClient::encrypt_group_message(OlmOutboundGroupSession *session, const std::string &plaintext)
394 {
395 auto encrypted_len = olm_group_encrypt_message_length(session, plaintext.size());
396 auto encrypted_message = create_buffer(encrypted_len);
397
398 const std::size_t nbytes =
399 olm_group_encrypt(session,
400 reinterpret_cast<const uint8_t *>(plaintext.data()),
401 plaintext.size(),
402 encrypted_message.data(),
403 encrypted_message.size());
404
405 if (nbytes == olm_error())
406 throw olm_exception("olm_group_encrypt", session);
407
408 return encrypted_message;
409 }
410
411 BinaryBuf
412 OlmClient::decrypt_message(OlmSession *session,
413 size_t msgtype,
414 const std::string &one_time_key_message)
415 {
416 auto tmp = create_buffer(one_time_key_message.size());
417 std::copy(one_time_key_message.begin(), one_time_key_message.end(), tmp.begin());
418
419 auto declen =
420 olm_decrypt_max_plaintext_length(session, msgtype, (void *)tmp.data(), tmp.size());
421
422 auto decrypted = create_buffer(declen);
423 std::copy(one_time_key_message.begin(), one_time_key_message.end(), tmp.begin());
424
425 const std::size_t nbytes = olm_decrypt(
426 session, msgtype, (void *)tmp.data(), tmp.size(), decrypted.data(), decrypted.size());
427
428 if (nbytes == olm_error())
429 throw olm_exception("olm_decrypt", session);
430
431 // Removing the extra padding from the origial buffer.
432 auto output = create_buffer(nbytes);
433 std::memcpy(output.data(), decrypted.data(), nbytes);
434
435 return output;
436 }
437
438 BinaryBuf
439 OlmClient::encrypt_message(OlmSession *session, const std::string &msg)
440 {
441 auto ciphertext = create_buffer(olm_encrypt_message_length(session, msg.size()));
442 auto random_buf = create_buffer(olm_encrypt_random_length(session));
443
444 const auto ret = olm_encrypt(session,
445 msg.data(),
446 msg.size(),
447 random_buf.data(),
448 random_buf.size(),
449 ciphertext.data(),
450 ciphertext.size());
451 if (ret == olm_error())
452 throw olm_exception("olm_encrypt", session);
453
454 return ciphertext;
455 }
456
457 OlmSessionPtr
458 OlmClient::create_inbound_session_from(const std::string &their_curve25519,
459 const std::string &one_time_key_message)
460 {
461 BinaryBuf tmp(one_time_key_message.size());
462 memcpy(tmp.data(), one_time_key_message.data(), one_time_key_message.size());
463
464 return create_inbound_session_from(their_curve25519, tmp);
465 }
466
467 OlmSessionPtr
468 OlmClient::create_inbound_session_from(const std::string &their_curve25519,
469 const BinaryBuf &one_time_key_message)
470 {
471 auto session = create_olm_object<SessionObject>();
472
473 auto tmp = create_buffer(one_time_key_message.size());
474 std::copy(one_time_key_message.begin(), one_time_key_message.end(), tmp.begin());
475
476 std::size_t ret = olm_create_inbound_session_from(session.get(),
477 account(),
478 their_curve25519.data(),
479 their_curve25519.size(),
480 (void *)tmp.data(),
481 tmp.size());
482
483 if (ret == olm_error())
484 throw olm_exception("create_inbound_session_from", session.get());
485
486 ret = olm_remove_one_time_keys(account_.get(), session.get());
487
488 if (ret == olm_error())
489 throw olm_exception("inbound_session_from_remove_one_time_keys", account_.get());
490
491 return session;
492 }
493
494 OlmSessionPtr
495 OlmClient::create_inbound_session(const std::string &one_time_key_message)
496 {
497 BinaryBuf tmp(one_time_key_message.size());
498 memcpy(tmp.data(), one_time_key_message.data(), one_time_key_message.size());
499
500 return create_inbound_session(tmp);
501 }
502
503 OlmSessionPtr
504 OlmClient::create_inbound_session(const BinaryBuf &one_time_key_message)
505 {
506 auto session = create_olm_object<SessionObject>();
507
508 auto tmp = create_buffer(one_time_key_message.size());
509 std::copy(one_time_key_message.begin(), one_time_key_message.end(), tmp.begin());
510
511 std::size_t ret =
512 olm_create_inbound_session(session.get(), account(), (void *)tmp.data(), tmp.size());
513
514 if (ret == olm_error())
515 throw olm_exception("create_inbound_session", session.get());
516
517 ret = olm_remove_one_time_keys(account_.get(), session.get());
518
519 if (ret == olm_error())
520 throw olm_exception("inbound_session_remove_one_time_keys", account_.get());
521
522 return session;
523 }
524
525 OlmSessionPtr
526 OlmClient::create_outbound_session(const std::string &identity_key, const std::string &one_time_key)
527 {
528 auto session = create_olm_object<SessionObject>();
529 auto random_buf = create_buffer(olm_create_outbound_session_random_length(session.get()));
530
531 const auto ret = olm_create_outbound_session(session.get(),
532 account(),
533 identity_key.data(),
534 identity_key.size(),
535 one_time_key.data(),
536 one_time_key.size(),
537 random_buf.data(),
538 random_buf.size());
539
540 if (ret == olm_error())
541 throw olm_exception("create_outbound_session", session.get());
542
543 return session;
544 }
545
546 std::unique_ptr<SAS>
547 OlmClient::sas_init()
548 {
549 return std::make_unique<SAS>();
550 }
551
552 //! constructor which create a new Curve25519 key pair which is stored in SASObject
553 SAS::SAS()
554 {
555 this->sas = create_olm_object<SASObject>();
556 auto random_buf = BinaryBuf(olm_create_sas_random_length(sas.get()));
557
558 const auto ret = olm_create_sas(this->sas.get(), random_buf.data(), random_buf.size());
559
560 if (ret == olm_error())
561 throw olm_exception("create_sas_instance", this->sas.get());
562 }
563
564 std::string
565 SAS::public_key()
566 {
567 auto pub_key_buffer = create_buffer(olm_sas_pubkey_length(this->sas.get()));
568
569 const auto ret =
570 olm_sas_get_pubkey(this->sas.get(), pub_key_buffer.data(), pub_key_buffer.size());
571
572 if (ret == olm_error())
573 throw olm_exception("get_public_key", this->sas.get());
574
575 return to_string(pub_key_buffer);
576 }
577
578 void
579 SAS::set_their_key(const std::string &their_public_key)
580 {
581 auto pub_key_buffer = to_binary_buf(their_public_key);
582
583 const auto ret =
584 olm_sas_set_their_key(this->sas.get(), pub_key_buffer.data(), pub_key_buffer.size());
585
586 if (ret == olm_error())
587 throw olm_exception("get_public_key", this->sas.get());
588 }
589
590 std::vector<int>
591 SAS::generate_bytes_decimal(const std::string &info)
592 {
593 auto input_info_buffer = to_binary_buf(info);
594 auto output_buffer = BinaryBuf(5);
595
596 std::vector<int> output_list;
597 output_list.resize(3);
598
599 const auto ret = olm_sas_generate_bytes(this->sas.get(),
600 input_info_buffer.data(),
601 input_info_buffer.size(),
602 output_buffer.data(),
603 output_buffer.size());
604
605 if (ret == olm_error())
606 throw olm_exception("get_bytes_decimal", this->sas.get());
607
608 output_list[0] = (((output_buffer[0] << 5) | (output_buffer[1] >> 3)) + 1000);
609 output_list[1] =
610 ((((output_buffer[1] & 0x07) << 10) | (output_buffer[2] << 2) | (output_buffer[3] >> 6)) +
611 1000);
612 output_list[2] = (((((output_buffer[3] & 0x3F) << 7)) | ((output_buffer[4] >> 1))) + 1000);
613
614 return output_list;
615 }
616
617 //! generates and returns a vector of number(int) ranging from 0 to 63, to be used only after using
618 //! `set_their_key`
619 std::vector<int>
620 SAS::generate_bytes_emoji(const std::string &info)
621 {
622 auto input_info_buffer = to_binary_buf(info);
623 auto output_buffer = BinaryBuf(6);
624
625 std::vector<int> output_list;
626 output_list.resize(7);
627
628 const auto ret = olm_sas_generate_bytes(this->sas.get(),
629 input_info_buffer.data(),
630 input_info_buffer.size(),
631 output_buffer.data(),
632 output_buffer.size());
633
634 if (ret == olm_error())
635 throw olm_exception("get_bytes_emoji", this->sas.get());
636
637 output_list[0] = (output_buffer[0] >> 2);
638 output_list[1] = (((output_buffer[0] << 4) & 0x3f) | (output_buffer[1] >> 4));
639 output_list[2] = (((output_buffer[1] << 2) & 0x3f) | (output_buffer[2] >> 6));
640 output_list[3] = (output_buffer[2] & 0x3f);
641 output_list[4] = (output_buffer[3] >> 2);
642 output_list[5] = (((output_buffer[3] << 4) & 0x3f) | (output_buffer[4] >> 4));
643 output_list[6] = (((output_buffer[4] << 2) & 0x3f) | (output_buffer[5] >> 6));
644
645 return output_list;
646 }
647
648 //! calculates the mac based on the given input and info using the shared secret produced after
649 //! `set_their_key`
650 static constexpr std::string_view mac_method_alg_v1 = "hkdf-hmac-sha256";
651 static constexpr std::string_view mac_method_alg_v2 = "hkdf-hmac-sha256.v2";
652
653 std::string
654 SAS::calculate_mac_v(const std::string &input_data,
655 const std::string &info,
656 std::string_view mac_version)
657 {
658 auto input_data_buffer = to_binary_buf(input_data);
659 auto info_buffer = to_binary_buf(info);
660 auto output_buffer = BinaryBuf(olm_sas_mac_length(this->sas.get()));
661
662 std::size_t ret = 0;
663 if (mac_version == mac_method_alg_v1) {
664 ret = olm_sas_calculate_mac(this->sas.get(),
665 input_data_buffer.data(),
666 input_data_buffer.size(),
667 info_buffer.data(),
668 info_buffer.size(),
669 output_buffer.data(),
670 output_buffer.size());
671 } else if (mac_version == mac_method_alg_v2) {
672 ret = olm_sas_calculate_mac_fixed_base64(this->sas.get(),
673 input_data_buffer.data(),
674 input_data_buffer.size(),
675 info_buffer.data(),
676 info_buffer.size(),
677 output_buffer.data(),
678 output_buffer.size());
679 } else {
680 throw olm_exception("calculate_mac unsupported mac version", this->sas.get());
681 }
682
683 if (ret == olm_error())
684 throw olm_exception("calculate_mac", this->sas.get());
685
686 return to_string(output_buffer);
687 }
688
689 mtx::events::msg::KeyVerificationMac
690 SAS::calculate_mac(std::string_view mac_version,
691 const mtx::identifiers::User &sender,
692 const std::string &senderDevice,
693 const mtx::identifiers::User &receiver,
694 const std::string &receiverDevice,
695 const std::string &transactionId,
696 const std::map<std::string, std::string> &keys)
697 {
698 mtx::events::msg::KeyVerificationMac req{};
699
700 std::string info = "MATRIX_KEY_VERIFICATION_MAC" + sender.to_string() + senderDevice +
701 receiver.to_string() + receiverDevice + transactionId;
702
703 std::string key_list;
704 bool first = true;
705 for (const auto &[key_id, key] : keys) {
706 req.mac[key_id] = this->calculate_mac_v(key, info + key_id, mac_version);
707
708 if (!first)
709 key_list += ",";
710 key_list += key_id;
711 first = false;
712 }
713
714 req.keys = this->calculate_mac_v(key_list, info + "KEY_IDS", mac_version);
715
716 return req;
717 }
718
719 PkSigning
720 PkSigning::new_key()
721 {
722 auto priv_seed = bin2base64(to_string(create_buffer(olm_pk_signing_seed_length())));
723 return from_seed(priv_seed);
724 }
725
726 PkSigning
727 PkSigning::from_seed(const std::string &seed)
728 {
729 PkSigning s{};
730 s.seed_ = seed;
731 s.signing = create_olm_object<PkSigningObject>();
732
733 auto seed_ = base642bin(seed);
734
735 auto pub_key_buffer = BinaryBuf(olm_pk_signing_public_key_length());
736 auto ret = olm_pk_signing_key_from_seed(
737 s.signing.get(), pub_key_buffer.data(), pub_key_buffer.size(), seed_.data(), seed_.size());
738
739 if (ret == olm_error())
740 throw olm_exception("signing_from_seed", s.signing.get());
741
742 s.public_key_ = to_string(pub_key_buffer);
743
744 return s;
745 }
746
747 std::string
748 PkSigning::sign(const std::string &message)
749 {
750 auto signature = BinaryBuf(olm_pk_signature_length());
751 auto message_ = to_binary_buf(message);
752
753 auto ret = olm_pk_sign(
754 signing.get(), message_.data(), message_.size(), signature.data(), signature.size());
755
756 if (ret == olm_error())
757 throw olm_exception("olm_pk_sign", signing.get());
758
759 return to_string(signature);
760 }
761
762 nlohmann::json
763 OlmClient::create_olm_encrypted_content(OlmSession *session,
764 nlohmann::json event,
765 const UserId &recipient,
766 const std::string &recipient_ed25519_key,
767 const std::string &recipient_curve25519_key)
768 {
769 event["keys"]["ed25519"] = identity_keys().ed25519;
770 event["sender"] = user_id_;
771 event["sender_device"] = device_id_;
772
773 event["recipient"] = recipient.get();
774 event["recipient_keys"]["ed25519"] = recipient_ed25519_key;
775
776 size_t msg_type = olm_encrypt_message_type(session);
777 auto encrypted = encrypt_message(session, json(event).dump());
778 auto encrypted_str = std::string((char *)encrypted.data(), encrypted.size());
779
780 return json{
781 {"algorithm", "m.olm.v1.curve25519-aes-sha2"},
782 {"sender_key", identity_keys().curve25519},
783 {"ciphertext", {{recipient_curve25519_key, {{"body", encrypted_str}, {"type", msg_type}}}}}};
784 }
785
786 std::string
787 OlmClient::save(const std::string &key)
788 {
789 if (!account_)
790 return std::string();
791
792 return pickle<AccountObject>(account(), key);
793 }
794
795 std::string
796 mtx::crypto::session_id(OlmSession *s)
797 {
798 auto tmp = create_buffer(olm_session_id_length(s));
799 olm_session_id(s, tmp.data(), tmp.size());
800
801 return std::string(tmp.begin(), tmp.end());
802 }
803
804 std::string
805 mtx::crypto::session_id(OlmOutboundGroupSession *s)
806 {
807 auto tmp = create_buffer(olm_outbound_group_session_id_length(s));
808 olm_outbound_group_session_id(s, tmp.data(), tmp.size());
809
810 return std::string(tmp.begin(), tmp.end());
811 }
812
813 std::string
814 mtx::crypto::session_key(OlmOutboundGroupSession *s)
815 {
816 auto tmp = create_buffer(olm_outbound_group_session_key_length(s));
817 olm_outbound_group_session_key(s, tmp.data(), tmp.size());
818
819 return std::string(tmp.begin(), tmp.end());
820 }
821
822 std::string
823 mtx::crypto::export_session(OlmInboundGroupSession *s, uint32_t at_index)
824 {
825 const size_t len = olm_export_inbound_group_session_length(s);
826 const uint32_t index =
827 at_index == uint32_t(-1) ? olm_inbound_group_session_first_known_index(s) : at_index;
828
829 auto session_key = create_buffer(len);
830 const std::size_t ret =
831 olm_export_inbound_group_session(s, session_key.data(), session_key.size(), index);
832
833 if (ret == olm_error())
834 throw olm_exception("session_key", s);
835
836 return std::string(session_key.begin(), session_key.end());
837 }
838
839 InboundGroupSessionPtr
840 mtx::crypto::import_session(const std::string &session_key)
841 {
842 auto session = create_olm_object<InboundSessionObject>();
843
844 const std::size_t ret = olm_import_inbound_group_session(
845 session.get(), reinterpret_cast<const uint8_t *>(session_key.data()), session_key.size());
846
847 if (ret == olm_error())
848 throw olm_exception("import_session", session.get());
849
850 return session;
851 }
852
853 bool
854 mtx::crypto::matches_inbound_session(OlmSession *session, const std::string &one_time_key_message)
855 {
856 auto tmp = create_buffer(one_time_key_message.size());
857 std::copy(one_time_key_message.begin(), one_time_key_message.end(), tmp.begin());
858
859 return olm_matches_inbound_session(session, (void *)tmp.data(), tmp.size());
860 }
861
862 bool
863 mtx::crypto::matches_inbound_session_from(OlmSession *session,
864 const std::string &id_key,
865 const std::string &one_time_key_message)
866 {
867 auto tmp = create_buffer(one_time_key_message.size());
868 std::copy(one_time_key_message.begin(), one_time_key_message.end(), tmp.begin());
869
870 return olm_matches_inbound_session_from(
871 session, id_key.data(), id_key.size(), (void *)tmp.data(), tmp.size());
872 }
873
874 bool
875 mtx::crypto::verify_identity_signature(const DeviceKeys &device_keys,
876 const DeviceId &device_id,
877 const UserId &user_id)
878 {
879 try {
880 const auto sign_key_id = "ed25519:" + device_id.get();
881 const auto signing_key = device_keys.keys.at(sign_key_id);
882 const auto signature = device_keys.signatures.at(user_id.get()).at(sign_key_id);
883
884 if (signature.empty())
885 return false;
886
887 return ed25519_verify_signature(signing_key, nlohmann::json(device_keys), signature);
888
889 } catch (const nlohmann::json::exception &e) {
890 mtx::utils::log::log()->error("verify_identity_signature: {}", e.what());
891 }
892
893 return false;
894 }
895
896 //! checks if the signature is signed by the signing_key
897 bool
898 mtx::crypto::ed25519_verify_signature(std::string signing_key,
899 nlohmann::json obj,
900 std::string signature)
901 {
902 try {
903 if (signature.empty())
904 return false;
905
906 obj.erase("unsigned");
907 obj.erase("signatures");
908
909 std::string canonical_json = obj.dump();
910
911 auto utility = create_olm_object<UtilityObject>();
912 auto ret = olm_ed25519_verify(utility.get(),
913 signing_key.data(),
914 signing_key.size(),
915 canonical_json.data(),
916 canonical_json.size(),
917 (void *)signature.data(),
918 signature.size());
919
920 // the signature is wrong
921 if (ret != 0)
922 return false;
923
924 return true;
925 } catch (const nlohmann::json::exception &e) {
926 mtx::utils::log::log()->error("verify_signature: {}", e.what());
927 }
928
929 return false;
930 }
931
932 std::string
933 mtx::crypto::encrypt_exported_sessions(const mtx::crypto::ExportedSessionKeys &keys,
934 const std::string &pass)
935 {
936 const auto plaintext = json(keys).dump();
937
938 auto nonce = create_buffer(AES_BLOCK_SIZE);
939 constexpr std::uint8_t mask = static_cast<std::uint8_t>(~(1U << (63 / 8)));
940 nonce[15 - 63 % 8] &= mask;
941
942 auto salt = create_buffer(pwhash_SALTBYTES);
943
944 auto buf = create_buffer(64U);
945
946 uint32_t iterations = 100000;
947 buf = mtx::crypto::PBKDF2_HMAC_SHA_512(pass, salt, iterations);
948
949 BinaryBuf aes256 = BinaryBuf(buf.begin(), buf.begin() + 32);
950
951 BinaryBuf hmac256 = BinaryBuf(buf.begin() + 32, buf.begin() + (2UL * 32));
952
953 auto ciphertext = mtx::crypto::AES_CTR_256_Encrypt(plaintext, aes256, nonce);
954
955 uint8_t iterationsArr[4];
956 mtx::crypto::uint32_to_uint8(iterationsArr, iterations);
957
958 // Format of the output buffer: (0x01 + salt + IV + number of rounds + ciphertext +
959 // hmac-sha-256)
960 BinaryBuf output{
961 0x01,
962 };
963 output.reserve(1 + salt.size() + nonce.size() + 4 + ciphertext.size());
964 output.insert(output.end(), salt.begin(), salt.end());
965 output.insert(output.end(), nonce.begin(), nonce.end());
966 output.insert(output.end(), &iterationsArr[0], &iterationsArr[4]);
967 output.insert(output.end(), ciphertext.begin(), ciphertext.end());
968
969 // Need to hmac-sha256 our string so far, and then use that to finish making the output.
970 auto hmacSha256 = mtx::crypto::HMAC_SHA256(hmac256, output);
971
972 output.insert(output.end(), hmacSha256.begin(), hmacSha256.end());
973 auto encrypted = std::string(output.begin(), output.end());
974
975 return encrypted;
976 }
977
978 mtx::crypto::ExportedSessionKeys
979 mtx::crypto::decrypt_exported_sessions(const std::string &data, const std::string &pass)
980 {
981 // Parse the data into a base64 string without the header and footer
982 std::string unpacked = mtx::crypto::unpack_key_file(data);
983
984 std::string binary_str = base642bin(unpacked);
985
986 if (binary_str.size() <
987 1 + pwhash_SALTBYTES + AES_BLOCK_SIZE + sizeof(uint32_t) + SHA256_DIGEST_LENGTH + 2)
988 throw crypto_exception("decrypt_exported_sessions", "Invalid session file: too short");
989
990 const auto binary_start = binary_str.begin();
991 const auto binary_end = binary_str.end();
992
993 // Format version 0x01, 1 byte
994 const auto format_end = binary_start + 1;
995 auto format = BinaryBuf(binary_start, format_end);
996 if (format[0] != 0x01)
997 throw crypto_exception("decrypt_exported_sessions", "Unsupported backup file format.");
998
999 // Salt, 16 bytes
1000 const auto salt_end = format_end + pwhash_SALTBYTES;
1001 auto salt = BinaryBuf(format_end, salt_end);
1002
1003 // IV, 16 bytes
1004 const auto iv_end = salt_end + AES_BLOCK_SIZE;
1005 auto iv = BinaryBuf(salt_end, iv_end);
1006
1007 // Number of rounds, 4 bytes
1008 const auto rounds_end = iv_end + sizeof(uint32_t);
1009 auto rounds_buff = BinaryBuf(iv_end, rounds_end);
1010 uint8_t rounds_arr[4];
1011 std::copy(rounds_buff.begin(), rounds_buff.end(), rounds_arr);
1012 uint32_t rounds;
1013 mtx::crypto::uint8_to_uint32(rounds_arr, rounds);
1014
1015 // Variable-length JSON object...
1016 const auto json_end = binary_end - SHA256_DIGEST_LENGTH;
1017 auto json = BinaryBuf(rounds_end, json_end);
1018
1019 // HMAC of the above, 32 bytes
1020 auto hmac = BinaryBuf(json_end, binary_end);
1021
1022 // derive the keys
1023 auto buf = mtx::crypto::PBKDF2_HMAC_SHA_512(pass, salt, rounds);
1024
1025 BinaryBuf aes256 = BinaryBuf(buf.begin(), buf.begin() + 32);
1026
1027 BinaryBuf hmac256 = BinaryBuf(buf.begin() + 32, buf.begin() + (2 * 32));
1028
1029 // get hmac and verify they match
1030 auto hmacSha256 = mtx::crypto::HMAC_SHA256(hmac256, BinaryBuf(binary_start, json_end));
1031
1032 if (hmacSha256 != hmac) {
1033 throw crypto_exception{"decrypt_exported_sessions", "HMAC doesn't match"};
1034 }
1035
1036 const std::string ciphertext(json.begin(), json.end());
1037 auto decrypted = mtx::crypto::AES_CTR_256_Decrypt(ciphertext, aes256, iv);
1038
1039 std::string plaintext(decrypted.begin(), decrypted.end());
1040 return json::parse(plaintext).get<mtx::crypto::ExportedSessionKeys>();
1041 }