Debian Codegraph @

storage/innobase/os/os0enc.cc

raw
1 /***********************************************************************
2
3 Copyright (c) 2019, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License, version 2.0,
7 as published by the Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License, version 2.0, for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 ***********************************************************************/
27
28 /** @file os/os0enc.cc
29 Encryption code. */
30
31 #include "os0enc.h"
32 #include "fil0fil.h"
33 #ifdef UNIV_HOTBACKUP
34 #include "fsp0file.h"
35 #endif /* UNIV_HOTBACKUP */
36 #include "log0files_io.h"
37 #include "mach0data.h"
38 #include "os0file.h"
39 #include "page0page.h"
40 #include "ut0crc32.h"
41 #include "ut0mem.h"
42
43 #include <errno.h>
44 #include <mysql/components/services/keyring_generator.h>
45 #include <mysql/components/services/keyring_reader_with_status.h>
46 #include <mysql/components/services/keyring_writer.h>
47 #include <scope_guard.h>
48 #include "keyring_operations_helper.h"
49 #include "my_aes.h"
50 #include "my_rnd.h"
51 #include "mysql/service_mysql_keyring.h"
52 #include "mysqld.h"
53
54 namespace innobase {
55 namespace encryption {
56 #ifndef UNIV_HOTBACKUP
57 SERVICE_TYPE(keyring_reader_with_status) *keyring_reader_service = nullptr;
58 SERVICE_TYPE(keyring_writer) *keyring_writer_service = nullptr;
59 SERVICE_TYPE(keyring_generator) *keyring_generator_service = nullptr;
60
61 /**
62 Initialize keyring component service handles
63
64 @param [in] reg_srv Handle to registry service
65
66 @returns status of keyring service initialization
67 @retval true Success
68 @retval false Error
69 */
70 bool init_keyring_services(SERVICE_TYPE(registry) * reg_srv) {
71 DBUG_TRACE;
72
73 if (reg_srv == nullptr) {
74 return false;
75 }
76
77 my_h_service h_keyring_reader_service = nullptr;
78 my_h_service h_keyring_writer_service = nullptr;
79 my_h_service h_keyring_generator_service = nullptr;
80
81 auto cleanup = [&]() {
82 if (h_keyring_reader_service) {
83 reg_srv->release(h_keyring_reader_service);
84 }
85 if (h_keyring_writer_service) {
86 reg_srv->release(h_keyring_writer_service);
87 }
88 if (h_keyring_generator_service) {
89 reg_srv->release(h_keyring_generator_service);
90 }
91
92 keyring_reader_service = nullptr;
93 keyring_writer_service = nullptr;
94 keyring_generator_service = nullptr;
95 };
96
97 if (reg_srv->acquire("keyring_reader_with_status",
98 &h_keyring_reader_service) ||
99 reg_srv->acquire_related("keyring_writer", h_keyring_reader_service,
100 &h_keyring_writer_service) ||
101 reg_srv->acquire_related("keyring_generator", h_keyring_reader_service,
102 &h_keyring_generator_service)) {
103 cleanup();
104 return false;
105 }
106
107 keyring_reader_service =
108 reinterpret_cast<SERVICE_TYPE(keyring_reader_with_status) *>(
109 h_keyring_reader_service);
110 keyring_writer_service = reinterpret_cast<SERVICE_TYPE(keyring_writer) *>(
111 h_keyring_writer_service);
112 keyring_generator_service =
113 reinterpret_cast<SERVICE_TYPE(keyring_generator) *>(
114 h_keyring_generator_service);
115
116 return true;
117 }
118
119 /**
120 Deinitialize keyring component service handles
121
122 @param [in] reg_srv Handle to registry service
123 */
124 void deinit_keyring_services(SERVICE_TYPE(registry) * reg_srv) {
125 DBUG_TRACE;
126
127 if (reg_srv == nullptr) {
128 return;
129 }
130
131 using keyring_reader_t = SERVICE_TYPE_NO_CONST(keyring_reader_with_status);
132 using keyring_writer_t = SERVICE_TYPE_NO_CONST(keyring_writer);
133 using keyring_generator_t = SERVICE_TYPE_NO_CONST(keyring_generator);
134
135 if (keyring_reader_service) {
136 reg_srv->release(reinterpret_cast<my_h_service>(
137 const_cast<keyring_reader_t *>(keyring_reader_service)));
138 }
139 if (keyring_writer_service) {
140 reg_srv->release(reinterpret_cast<my_h_service>(
141 const_cast<keyring_writer_t *>(keyring_writer_service)));
142 }
143 if (keyring_generator_service) {
144 reg_srv->release(reinterpret_cast<my_h_service>(
145 const_cast<keyring_generator_t *>(keyring_generator_service)));
146 }
147
148 keyring_reader_service = nullptr;
149 keyring_writer_service = nullptr;
150 keyring_generator_service = nullptr;
151 }
152
153 /**
154 Generate a new key
155
156 @param [in] key_id Key identifier
157 @param [in] key_type Type of the key
158 @param [in] key_length Length of the key
159
160 @returns status of key generation
161 @retval true Success
162 @retval false Error. No error is raised.
163 */
164 bool generate_key(const char *key_id, const char *key_type, size_t key_length) {
165 if (key_id == nullptr || key_type == nullptr || key_length == 0) {
166 return false;
167 }
168
169 return keyring_generator_service->generate(key_id, nullptr, key_type,
170 key_length) == 0;
171 }
172
173 /**
174 Remove a key from keyring
175
176 @param [in] key_id Key to be removed
177 */
178 void remove_key(const char *key_id) {
179 if (key_id == nullptr) {
180 return;
181 }
182
183 /* We don't care about the removal status */
184 (void)keyring_writer_service->remove(key_id, nullptr);
185 }
186
187 #else
188
189 bool init_keyring_services(SERVICE_TYPE(registry) *) { return false; }
190
191 void deinit_keyring_services(SERVICE_TYPE(registry) *) { return; }
192
193 #endif // !UNIV_HOTBACKUP
194 } // namespace encryption
195 } // namespace innobase
196
197 /** Minimum length needed for encryption */
198 constexpr size_t MIN_ENCRYPTION_LEN = 2 * MY_AES_BLOCK_SIZE + FIL_PAGE_DATA;
199 /** Key type */
200 constexpr char innodb_key_type[] = "AES";
201
202 /** Current master key id */
203 uint32_t Encryption::s_master_key_id = Encryption::DEFAULT_MASTER_KEY_ID;
204
205 /** Current uuid of server instance */
206 char Encryption::s_uuid[Encryption::SERVER_UUID_LEN + 1] = {0};
207
208 /** Tablespaces whose key needs to be reencrypted */
209 std::vector<space_id_t> Encryption::s_tablespaces_to_reencrypt;
210
211 void Encryption::set(const Encryption_metadata &metadata) noexcept {
212 set_type(metadata.m_type);
213 set_key(metadata.m_key);
214 set_key_length(metadata.m_key_len);
215 set_initial_vector(metadata.m_iv);
216 }
217
218 const char *Encryption::to_string(Type type) noexcept {
219 switch (type) {
220 case NONE:
221 return ("N");
222 case AES:
223 return ("Y");
224 }
225
226 ut_d(ut_error);
227
228 ut_o(return ("<UNKNOWN>"));
229 }
230
231 void Encryption::random_value(byte *value) noexcept {
232 ut_ad(value != nullptr);
233
234 my_rand_buffer(value, KEY_LEN);
235 }
236
237 void Encryption::create_master_key(byte **master_key) noexcept {
238 #ifndef UNIV_HOTBACKUP
239 size_t key_len;
240 char *key_type = nullptr;
241 char key_name[MASTER_KEY_NAME_MAX_LEN];
242
243 /* If uuid does not match with current server uuid,
244 set uuid as current server uuid. */
245 if (strcmp(s_uuid, server_uuid) != 0) {
246 memcpy(s_uuid, server_uuid, sizeof(s_uuid) - 1);
247 }
248
249 /* Generate new master key */
250 snprintf(key_name, MASTER_KEY_NAME_MAX_LEN, "%s-%s-" UINT32PF,
251 MASTER_KEY_PREFIX, s_uuid, s_master_key_id + 1);
252
253 /* We call keyring API to generate master key here. */
254 bool ret =
255 innobase::encryption::generate_key(key_name, innodb_key_type, KEY_LEN);
256
257 /* We call keyring API to get master key here. */
258 int retval = keyring_operations_helper::read_secret(
259 innobase::encryption::keyring_reader_service, key_name, nullptr,
260 master_key, &key_len, &key_type, PSI_INSTRUMENT_ME);
261
262 if (retval == -1 || *master_key == nullptr) {
263 ib::error(ER_IB_MSG_831) << "Encryption can't find master key,"
264 << " please check the keyring is loaded."
265 << " ret=" << ret;
266
267 *master_key = nullptr;
268 } else {
269 ++s_master_key_id;
270 }
271
272 if (key_type != nullptr) {
273 my_free(key_type);
274 }
275 #endif /* !UNIV_HOTBACKUP */
276 }
277
278 void Encryption::get_master_key(uint32_t master_key_id, char *srv_uuid,
279 byte **master_key) noexcept {
280 size_t key_len = 0;
281 char *key_type = nullptr;
282 char key_name[MASTER_KEY_NAME_MAX_LEN];
283
284 memset(key_name, 0x0, sizeof(key_name));
285
286 if (srv_uuid != nullptr) {
287 ut_ad(strlen(srv_uuid) > 0);
288
289 snprintf(key_name, MASTER_KEY_NAME_MAX_LEN, "%s-%s-" UINT32PF,
290 MASTER_KEY_PREFIX, srv_uuid, master_key_id);
291 } else {
292 /* For compatibility with 5.7.11, we need to get master key with
293 server id. */
294
295 snprintf(key_name, MASTER_KEY_NAME_MAX_LEN, "%s-%lu-" UINT32PF,
296 MASTER_KEY_PREFIX, server_id, master_key_id);
297 }
298
299 #ifndef UNIV_HOTBACKUP
300 /* We call keyring API to get master key here. */
301 int ret =
302 (keyring_operations_helper::read_secret(
303 innobase::encryption::keyring_reader_service, key_name, nullptr,
304 master_key, &key_len, &key_type, PSI_INSTRUMENT_ME) > -1)
305 ? 0
306 : 1;
307 #else /* !UNIV_HOTBACKUP */
308 /* We call MEB to get master key here. */
309 int ret = meb_key_fetch(key_name, &key_type, nullptr,
310 reinterpret_cast<void **>(master_key), &key_len);
311 #endif /* !UNIV_HOTBACKUP */
312
313 if (key_type != nullptr) {
314 my_free(key_type);
315 }
316
317 if (ret != 0) {
318 *master_key = nullptr;
319
320 ib::error(ER_IB_MSG_832) << "Encryption can't find master key,"
321 << " please check the keyring is loaded.";
322 }
323
324 #ifdef UNIV_ENCRYPT_DEBUG
325 if (ret == 0 && *master_key != nullptr) {
326 std::ostringstream msg;
327
328 ut_print_buf(msg, *master_key, key_len);
329
330 ib::info(ER_IB_MSG_833)
331 << "Fetched master key: " << master_key_id << "{" << msg.str() << "}";
332 }
333 #endif /* UNIV_ENCRYPT_DEBUG */
334 }
335
336 void Encryption::get_master_key(uint32_t *master_key_id,
337 byte **master_key) noexcept {
338 #ifndef UNIV_HOTBACKUP
339 size_t key_len;
340 char *key_type = nullptr;
341 char key_name[MASTER_KEY_NAME_MAX_LEN];
342 extern ib_mutex_t master_key_id_mutex;
343 int retval;
344 bool key_id_locked = false;
345
346 if (s_master_key_id == DEFAULT_MASTER_KEY_ID) {
347 /* Take mutex as master_key_id is going to change. */
348 mutex_enter(&master_key_id_mutex);
349 key_id_locked = true;
350 }
351
352 memset(key_name, 0x0, sizeof(key_name));
353
354 /* Check for s_master_key_id again, as a parallel rotation might have caused
355 it to change. */
356 if (s_master_key_id == DEFAULT_MASTER_KEY_ID) {
357 ut_ad(strlen(server_uuid) > 0);
358 memset(s_uuid, 0x0, sizeof(s_uuid));
359
360 /* If m_master_key is DEFAULT_MASTER_KEY_ID, it means there's
361 no encrypted tablespace yet. Generate the first master key now and store
362 it to keyring. */
363 memcpy(s_uuid, server_uuid, sizeof(s_uuid) - 1);
364
365 /* Prepare the server s_uuid. */
366 snprintf(key_name, MASTER_KEY_NAME_MAX_LEN, "%s-%s-1", MASTER_KEY_PREFIX,
367 s_uuid);
368
369 /* We call keyring API to generate master key here. */
370 (void)innobase::encryption::generate_key(key_name, innodb_key_type,
371 KEY_LEN);
372
373 /* We call keyring API to get master key here. */
374 retval = keyring_operations_helper::read_secret(
375 innobase::encryption::keyring_reader_service, key_name, nullptr,
376 master_key, &key_len, &key_type, PSI_INSTRUMENT_ME);
377
378 if (retval > -1 && *master_key != nullptr) {
379 ++s_master_key_id;
380 *master_key_id = s_master_key_id;
381 }
382 #ifdef UNIV_ENCRYPT_DEBUG
383 if (retval > -1 && *master_key != nullptr) {
384 std::ostringstream msg;
385
386 ut_print_buf(msg, *master_key, key_len);
387
388 ib::info(ER_IB_MSG_834)
389 << "Generated new master key: {" << msg.str() << "}";
390 }
391 #endif /* UNIV_ENCRYPT_DEBUG */
392 } else {
393 *master_key_id = s_master_key_id;
394
395 snprintf(key_name, MASTER_KEY_NAME_MAX_LEN, "%s-%s-" UINT32PF,
396 MASTER_KEY_PREFIX, s_uuid, *master_key_id);
397
398 /* We call keyring API to get master key here. */
399 retval = keyring_operations_helper::read_secret(
400 innobase::encryption::keyring_reader_service, key_name, nullptr,
401 master_key, &key_len, &key_type, PSI_INSTRUMENT_ME);
402
403 /* For compitability with 5.7.11, we need to try to get master
404 key with server id when get master key with server uuid
405 failure. */
406 if (retval != 1) {
407 ut_ad(key_type == nullptr);
408 if (key_type != nullptr) {
409 my_free(key_type);
410 key_type = nullptr;
411 }
412
413 snprintf(key_name, MASTER_KEY_NAME_MAX_LEN, "%s-%lu-" UINT32PF,
414 MASTER_KEY_PREFIX, server_id, *master_key_id);
415
416 retval = keyring_operations_helper::read_secret(
417 innobase::encryption::keyring_reader_service, key_name, nullptr,
418 master_key, &key_len, &key_type, PSI_INSTRUMENT_ME);
419 }
420
421 #ifdef UNIV_ENCRYPT_DEBUG
422 if (retval == 1) {
423 std::ostringstream msg;
424
425 ut_print_buf(msg, *master_key, key_len);
426
427 ib::info(ER_IB_MSG_835) << "Fetched master key: " << *master_key_id
428 << ": {" << msg.str() << "}";
429 }
430 #endif /* UNIV_ENCRYPT_DEBUG */
431 }
432
433 if (retval == -1) {
434 *master_key = nullptr;
435 ib::error(ER_IB_MSG_836) << "Encryption can't find master key, please check"
436 << " the keyring is loaded.";
437 }
438
439 if (key_type != nullptr) {
440 my_free(key_type);
441 key_type = nullptr;
442 }
443
444 if (key_id_locked) {
445 mutex_exit(&master_key_id_mutex);
446 }
447
448 #endif /* !UNIV_HOTBACKUP */
449 }
450
451 bool Encryption::fill_encryption_info(
452 const Encryption_metadata &encryption_metadata, bool encrypt_key,
453 byte *encrypt_info) noexcept {
454 byte *master_key = nullptr;
455 uint32_t master_key_id = DEFAULT_MASTER_KEY_ID;
456
457 #ifndef UNIV_HOTBACKUP
458 /* Server uuid must have already been generated */
459 ut_ad(strlen(server_uuid) > 0);
460 #endif
461
462 /* Get master key from keyring. */
463 if (encrypt_key) {
464 get_master_key(&master_key_id, &master_key);
465
466 if (master_key == nullptr) {
467 return (false);
468 }
469
470 ut_ad(master_key_id != DEFAULT_MASTER_KEY_ID);
471 ut_ad(memcmp(master_key, DEFAULT_MASTER_KEY, sizeof(DEFAULT_MASTER_KEY)) !=
472 0);
473 }
474
475 /* Encryption info to be filled in following format
476 --------------------------------------------------------------------------
477 | Magic bytes | master key id | server uuid | tablespace key|iv | checksum |
478 --------------------------------------------------------------------------
479 */
480 ut_ad(encrypt_info != nullptr);
481 memset(encrypt_info, 0, INFO_SIZE);
482
483 auto ptr = encrypt_info;
484
485 /* Write Magic bytes */
486 memcpy(ptr, KEY_MAGIC_V3, MAGIC_SIZE);
487 ptr += MAGIC_SIZE;
488
489 /* Write master key id. */
490 mach_write_to_4(ptr, master_key_id);
491 ptr += sizeof(uint32_t);
492
493 /* Write server uuid. */
494 memcpy(reinterpret_cast<char *>(ptr), s_uuid, sizeof(s_uuid));
495 ptr += sizeof(s_uuid) - 1;
496
497 /* Write (and encrypt if needed) key and iv */
498 byte key_info[KEY_LEN * 2];
499 memset(key_info, 0x0, sizeof(key_info));
500
501 memcpy(key_info, encryption_metadata.m_key, KEY_LEN);
502
503 memcpy(key_info + KEY_LEN, encryption_metadata.m_iv, KEY_LEN);
504
505 if (encrypt_key) {
506 /* Encrypt key and iv. */
507 auto elen = my_aes_encrypt(key_info, sizeof(key_info), ptr, master_key,
508 KEY_LEN, my_aes_256_ecb, nullptr, false);
509
510 if (elen == MY_AES_BAD_DATA) {
511 my_free(master_key);
512 return (false);
513 }
514 } else {
515 /* Keep tablespace key unencrypted. Used by clone. */
516 memcpy(ptr, key_info, sizeof(key_info));
517 }
518 ptr += sizeof(key_info);
519
520 /* Write checksum bytes. */
521 auto crc = ut_crc32(key_info, sizeof(key_info));
522 mach_write_to_4(ptr, crc);
523
524 if (encrypt_key) {
525 ut_ad(master_key != nullptr);
526 my_free(master_key);
527 }
528
529 return (true);
530 }
531
532 const byte *Encryption::get_master_key_from_info(const byte *encrypt_info,
533 Version version,
534 uint32_t *m_key_id,
535 char *srv_uuid,
536 byte **master_key) noexcept {
537 const byte *ptr = encrypt_info;
538 *m_key_id = 0;
539
540 /* Get master key id. */
541 uint32_t key_id = mach_read_from_4(ptr);
542 ptr += sizeof(uint32_t);
543
544 /* Handle different version encryption information. */
545 switch (version) {
546 case VERSION_1:
547 /* For version 1, it's possible master key id occupied 8 bytes. */
548 if (mach_read_from_4(ptr) == 0) {
549 ptr += sizeof(uint32);
550 }
551
552 /* Get master key. */
553 get_master_key(key_id, nullptr, master_key);
554 if (*master_key == nullptr) {
555 return (encrypt_info);
556 }
557
558 *m_key_id = key_id;
559 return (ptr);
560
561 case VERSION_2:
562 /* For version 2, it's also possible master key id occupied 8 bytes. */
563 if (mach_read_from_4(ptr) == 0) {
564 ptr += sizeof(uint32);
565 }
566
567 /* Read server uuid. */
568 memset(srv_uuid, 0, SERVER_UUID_LEN + 1);
569 memcpy(srv_uuid, ptr, SERVER_UUID_LEN);
570
571 ut_ad(strlen(srv_uuid) != 0);
572 ptr += SERVER_UUID_LEN;
573
574 /* Get master key. */
575 get_master_key(key_id, srv_uuid, master_key);
576 if (*master_key == nullptr) {
577 return (encrypt_info);
578 }
579
580 *m_key_id = key_id;
581 break;
582
583 case VERSION_3:
584 /* Read server uuid. */
585 memset(srv_uuid, 0, SERVER_UUID_LEN + 1);
586 memcpy(srv_uuid, ptr, SERVER_UUID_LEN);
587
588 ptr += SERVER_UUID_LEN;
589
590 if (key_id == DEFAULT_MASTER_KEY_ID) {
591 *master_key = static_cast<byte *>(
592 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, KEY_LEN));
593 memcpy(*master_key, DEFAULT_MASTER_KEY, strlen(DEFAULT_MASTER_KEY));
594 } else {
595 ut_ad(strlen(srv_uuid) != 0);
596
597 /* Get master key. */
598 get_master_key(key_id, srv_uuid, master_key);
599 if (*master_key == nullptr) {
600 return (encrypt_info);
601 }
602 }
603
604 *m_key_id = key_id;
605 break;
606 }
607
608 ut_ad(*master_key != nullptr);
609
610 return (ptr);
611 }
612
613 bool Encryption::is_encrypted_with_version(
614 const byte *encryption_info, const char *version_magic_bytes) noexcept {
615 return std::memcmp(encryption_info, version_magic_bytes,
616 Encryption::MAGIC_SIZE) == 0;
617 }
618
619 bool Encryption::is_encrypted_with_v3(const byte *encryption_info) noexcept {
620 return is_encrypted_with_version(encryption_info, Encryption::KEY_MAGIC_V3);
621 }
622
623 bool Encryption::is_encrypted(const byte *encryption_info) noexcept {
624 return is_encrypted_with_v3(encryption_info) ||
625 is_encrypted_with_version(encryption_info, Encryption::KEY_MAGIC_V2) ||
626 is_encrypted_with_version(encryption_info, Encryption::KEY_MAGIC_V1);
627 }
628
629 bool Encryption::decode_encryption_info(Encryption_metadata &e_metadata,
630 const byte *encryption_info,
631 bool decrypt_key) noexcept {
632 Encryption_key e_key{e_metadata.m_key, e_metadata.m_iv};
633 if (decode_encryption_info(dict_sys_t::s_invalid_space_id, e_key,
634 encryption_info, decrypt_key)) {
635 e_metadata.m_key_len = Encryption::KEY_LEN;
636 e_metadata.m_type = Encryption::AES;
637 return true;
638 }
639 return false;
640 }
641
642 bool Encryption::decode_encryption_info(space_id_t space_id,
643 Encryption_key &e_key,
644 const byte *encryption_info,
645 bool decrypt_key) noexcept {
646 const byte *ptr = encryption_info;
647 byte *key = e_key.m_key;
648 byte *iv = e_key.m_iv;
649 uint32_t &master_key_id = e_key.m_master_key_id;
650
651 /* For compatibility with 5.7.11, we need to handle the
652 encryption information which created in this old version. */
653 Version version;
654 if (memcmp(ptr, KEY_MAGIC_V1, MAGIC_SIZE) == 0) {
655 version = VERSION_1;
656 } else if (memcmp(ptr, KEY_MAGIC_V2, MAGIC_SIZE) == 0) {
657 version = VERSION_2;
658 } else if (memcmp(ptr, KEY_MAGIC_V3, MAGIC_SIZE) == 0) {
659 version = VERSION_3;
660 } else {
661 /* We don't report an error during recovery, since the
662 encryption info maybe hasn't written into datafile when
663 the table is newly created. For clone encryption information
664 should have been already correct. */
665 if (recv_recovery_is_on() && !recv_sys->is_cloned_db) {
666 return (true);
667 }
668
669 ib::error(ER_IB_MSG_837) << "Failed to decrypt encryption information,"
670 << " found unexpected version of it!";
671 return (false);
672 }
673 ptr += MAGIC_SIZE;
674
675 /* Read master key id and read (decrypt if needed) tablespace key and iv. */
676 byte *master_key = nullptr;
677 char srv_uuid[SERVER_UUID_LEN + 1];
678 byte key_info[KEY_LEN * 2];
679 if (decrypt_key) {
680 /* Get master key by key id. */
681 ptr = get_master_key_from_info(ptr, version, &master_key_id, srv_uuid,
682 &master_key);
683
684 /* If can't find the master key, return failure. */
685 if (master_key == nullptr) {
686 return (false);
687 }
688
689 /* Decrypt tablespace key and iv. */
690 auto len = my_aes_decrypt(ptr, sizeof(key_info), key_info, master_key,
691 KEY_LEN, my_aes_256_ecb, nullptr, false);
692
693 if (master_key_id == DEFAULT_MASTER_KEY_ID) {
694 ut::free(master_key);
695 /* Re-encrypt tablespace key with current master key */
696 } else {
697 my_free(master_key);
698 }
699
700 /* If decryption failed, return error. */
701 if (len == MY_AES_BAD_DATA) {
702 return (false);
703 }
704 } else {
705 ut_ad(version == VERSION_3);
706 /* Skip master Key and server UUID*/
707 ptr += sizeof(uint32_t);
708 ptr += SERVER_UUID_LEN;
709
710 /* Get tablespace key information. */
711 memcpy(key_info, ptr, sizeof(key_info));
712 }
713 ptr += sizeof(key_info);
714
715 /* Check checksum bytes. */
716 uint32_t crc1 = mach_read_from_4(ptr);
717 uint32_t crc2 = ut_crc32(key_info, sizeof(key_info));
718 if (crc1 != crc2) {
719 /* This check could fail only while decrypting key. */
720 ut_ad(decrypt_key);
721
722 ib::error(ER_IB_MSG_839)
723 << "Failed to decrypt encryption information,"
724 << " please check whether key file has been changed!";
725
726 return (false);
727 }
728
729 /* Get tablespace key */
730 memcpy(key, key_info, KEY_LEN);
731
732 /* Get tablespace iv */
733 memcpy(iv, key_info + KEY_LEN, KEY_LEN);
734
735 if (decrypt_key) {
736 /* Update server uuid and master key id in encryption metadata */
737 if (master_key_id > s_master_key_id) {
738 s_master_key_id = master_key_id;
739 memcpy(s_uuid, srv_uuid, sizeof(s_uuid) - 1);
740 }
741
742 #ifndef UNIV_HOTBACKUP
743 if (master_key_id == DEFAULT_MASTER_KEY_ID &&
744 space_id != dict_sys_t::s_invalid_space_id) {
745 /* Tablespace key needs to be reencrypted with master key */
746
747 if (!srv_master_thread_is_active()) {
748 /* Note down this space and rotate key at the end of recovery */
749 s_tablespaces_to_reencrypt.push_back(space_id);
750 } else {
751 /* This tablespace might not be loaded yet. It's tablepace key will be
752 reencrypted with new master key once it is loaded in fil_ibd_open() */
753 }
754 }
755 #endif
756 }
757
758 return (true);
759 }
760
761 bool Encryption::is_encrypted_page(const byte *page) noexcept {
762 ulint page_type = mach_read_from_2(page + FIL_PAGE_TYPE);
763
764 return (page_type == FIL_PAGE_ENCRYPTED ||
765 page_type == FIL_PAGE_COMPRESSED_AND_ENCRYPTED ||
766 page_type == FIL_PAGE_ENCRYPTED_RTREE);
767 }
768
769 bool Encryption::is_encrypted_log(const byte *block) noexcept {
770 return (log_block_get_encrypt_bit(block));
771 }
772
773 bool Encryption::encrypt_log_block(byte *src_ptr,
774 byte *dst_ptr) const noexcept {
775 ulint len = 0;
776 ulint data_len;
777 ulint main_len;
778 ulint remain_len;
779 byte remain_buf[MY_AES_BLOCK_SIZE * 2];
780 /* in-place encryption is not supported */
781 ut_a(src_ptr != dst_ptr);
782 /* the buffers can't even overlap */
783 ut_ad(src_ptr + OS_FILE_LOG_BLOCK_SIZE <= dst_ptr ||
784 dst_ptr + OS_FILE_LOG_BLOCK_SIZE <= src_ptr);
785 #ifdef UNIV_ENCRYPT_DEBUG
786 {
787 std::ostringstream msg;
788
789 msg << "Encrypting block: " << log_block_get_hdr_no(src_ptr);
790 msg << "{";
791 ut_print_buf_hex(msg, src_ptr, OS_FILE_LOG_BLOCK_SIZE);
792 msg << "}";
793
794 ib::info(ER_IB_MSG_842) << msg.str();
795 }
796 #endif /* UNIV_ENCRYPT_DEBUG */
797
798 /* This is data size to encrypt. */
799 data_len = OS_FILE_LOG_BLOCK_SIZE - LOG_BLOCK_HDR_SIZE;
800 main_len = (data_len / MY_AES_BLOCK_SIZE) * MY_AES_BLOCK_SIZE;
801 remain_len = data_len - main_len;
802
803 /* Encrypt the block. */
804 /* Copy the header as is. */
805
806 /* Skip encryption if header is empty */
807 if (ut::is_zeros(src_ptr, LOG_BLOCK_HDR_SIZE)) {
808 /* Block is logically empty - this happens in write-ahead.
809 Don't waste time on encrypting it. Also, because write-ahead
810 blocks are "in future", and we might disable encryption at
811 any moment, we should avoid encrypting this block, so that
812 one can read it during recovery even when encryption is
813 disabled, soon after this call, before block gets filled
814 with data. */
815 std::memset(dst_ptr, 0x00, OS_FILE_LOG_BLOCK_SIZE);
816 return true;
817 }
818
819 std::memcpy(dst_ptr, src_ptr, LOG_BLOCK_HDR_SIZE);
820
821 switch (m_type) {
822 case NONE:
823 ut_error;
824
825 case AES: {
826 ut_ad(m_klen == KEY_LEN);
827
828 auto elen = my_aes_encrypt(
829 src_ptr + LOG_BLOCK_HDR_SIZE, static_cast<uint32>(main_len),
830 dst_ptr + LOG_BLOCK_HDR_SIZE, m_key, static_cast<uint32>(m_klen),
831 my_aes_256_cbc, m_iv, false);
832
833 if (elen == MY_AES_BAD_DATA) {
834 return (false);
835 }
836
837 len = static_cast<ulint>(elen);
838 ut_ad(len == main_len);
839
840 /* Copy remain bytes. */
841 memcpy(dst_ptr + LOG_BLOCK_HDR_SIZE + len,
842 src_ptr + LOG_BLOCK_HDR_SIZE + len,
843 OS_FILE_LOG_BLOCK_SIZE - LOG_BLOCK_HDR_SIZE - len);
844
845 /* Encrypt the remain bytes. Since my_aes_encrypt
846 request the content to encrypt is
847 multiple of MY_AES_BLOCK_SIZE, but the block
848 content is possibly not, so, we need to handle
849 the tail bytes first. */
850 if (remain_len != 0) {
851 remain_len = MY_AES_BLOCK_SIZE * 2;
852
853 elen = my_aes_encrypt(
854 dst_ptr + LOG_BLOCK_HDR_SIZE + data_len - remain_len,
855 static_cast<uint32>(remain_len), remain_buf, m_key,
856 static_cast<uint32>(m_klen), my_aes_256_cbc, m_iv, false);
857
858 if (elen == MY_AES_BAD_DATA) {
859 return (false);
860 }
861
862 memcpy(dst_ptr + LOG_BLOCK_HDR_SIZE + data_len - remain_len, remain_buf,
863 remain_len);
864 }
865
866 break;
867 }
868
869 default:
870 ut_error;
871 }
872
873 #ifdef UNIV_ENCRYPT_DEBUG
874 {
875 std::ostringstream os{};
876 os << "Encrypted block " << log_block_get_hdr_no(dst_ptr) << "."
877 << std::endl;
878 ut_print_buf_hex(os, dst_ptr, OS_FILE_LOG_BLOCK_SIZE);
879 os << std::endl;
880 ib::info() << os.str();
881
882 byte check_buf[OS_FILE_LOG_BLOCK_SIZE];
883
884 memcpy(check_buf, dst_ptr, OS_FILE_LOG_BLOCK_SIZE);
885 log_block_set_encrypt_bit(check_buf, true);
886 dberr_t err = decrypt_log(check_buf, OS_FILE_LOG_BLOCK_SIZE);
887 if (err != DB_SUCCESS ||
888 memcmp(src_ptr, check_buf, OS_FILE_LOG_BLOCK_SIZE) != 0) {
889 std::ostringstream msg{};
890 ut_print_buf_hex(msg, src_ptr, OS_FILE_LOG_BLOCK_SIZE);
891 ib::error() << msg.str();
892
893 msg.seekp(0);
894 ut_print_buf_hex(msg, check_buf, OS_FILE_LOG_BLOCK_SIZE);
895 ib::fatal(UT_LOCATION_HERE) << msg.str();
896 }
897 }
898 #endif /* UNIV_ENCRYPT_DEBUG */
899
900 /* Set the encrypted flag. */
901 log_block_set_encrypt_bit(dst_ptr, true);
902
903 return (true);
904 }
905
906 bool Encryption::encrypt_log(byte *src, size_t src_len,
907 byte *dst) const noexcept {
908 /* in-place encryption is not supported */
909 ut_a(src != dst);
910 /* the buffers can't even overlap */
911 ut_ad(src + src_len <= dst || dst + src_len <= src);
912 byte *src_ptr = src;
913 byte *dst_ptr = dst;
914 ut_ad(src_len % OS_FILE_LOG_BLOCK_SIZE == 0);
915 ut_ad(m_type != NONE);
916
917 /* Encrypt the log blocks one by one. */
918 while (src_ptr != src + src_len) {
919 if (!encrypt_log_block(src_ptr, dst_ptr)) {
920 ib::error{ER_IB_MSG_CANT_ENCRYPT_REDO_LOG_DATA};
921 return false;
922 }
923
924 src_ptr += OS_FILE_LOG_BLOCK_SIZE;
925 dst_ptr += OS_FILE_LOG_BLOCK_SIZE;
926 }
927
928 #ifdef UNIV_ENCRYPT_DEBUG
929 {
930 byte *check_buf = static_cast<byte *>(
931 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, src_len));
932 memcpy(check_buf, dst, src_len);
933
934 dberr_t err = decrypt_log(check_buf, src_len);
935 if (err != DB_SUCCESS || memcmp(src, check_buf, src_len) != 0) {
936 std::ostringstream msg{};
937 ut_print_buf_hex(msg, src, src_len);
938 ib::error() << msg.str();
939
940 msg.seekp(0);
941 ut_print_buf_hex(msg, check_buf, src_len);
942 ib::fatal(UT_LOCATION_HERE) << msg.str();
943 }
944 ut::free(check_buf);
945 }
946 #endif /* UNIV_ENCRYPT_DEBUG */
947
948 return true;
949 }
950
951 bool Encryption::encrypt_low(byte *src, ulint src_len, byte *dst,
952 ulint *dst_len) const noexcept {
953 const uint16_t page_type = mach_read_from_2(src + FIL_PAGE_TYPE);
954
955 /* Shouldn't encrypt an already encrypted page. */
956 ut_ad(!is_encrypted_page(src));
957
958 /* This is data size to encrypt. */
959 auto src_enc_len = src_len;
960
961 /* In FIL_PAGE_VERSION_2, we encrypt the actual compressed data length. */
962 if (page_type == FIL_PAGE_COMPRESSED) {
963 src_enc_len =
964 mach_read_from_2(src + FIL_PAGE_COMPRESS_SIZE_V1) + FIL_PAGE_DATA;
965 /* Extend src_enc_len if needed */
966 if (src_enc_len < MIN_ENCRYPTION_LEN) {
967 src_enc_len = MIN_ENCRYPTION_LEN;
968 }
969 ut_a(src_enc_len <= src_len);
970 }
971
972 /* Only encrypt the data + trailer, leave the header alone */
973
974 switch (m_type) {
975 case NONE:
976 ut_error;
977
978 case AES: {
979 ut_ad(m_klen == KEY_LEN);
980
981 /* Total length of the data to encrypt. */
982 const auto data_len = src_enc_len - FIL_PAGE_DATA;
983
984 /* Server encryption functions expect input data to be in multiples
985 of MY_AES_BLOCK SIZE. Therefore we encrypt the overlapping data of
986 the chunk_len and trailer_len twice. First we encrypt the bigger
987 chunk of data then we do the trailer. The trailer encryption block
988 starts at 2 * MY_AES_BLOCK_SIZE bytes offset from the end of the
989 enc_len. During decryption we do the reverse of the above process. */
990 ut_ad(data_len >= 2 * MY_AES_BLOCK_SIZE);
991
992 const auto chunk_len = (data_len / MY_AES_BLOCK_SIZE) * MY_AES_BLOCK_SIZE;
993 const auto remain_len = data_len - chunk_len;
994
995 auto elen = my_aes_encrypt(
996 src + FIL_PAGE_DATA, static_cast<uint32>(chunk_len),
997 dst + FIL_PAGE_DATA, m_key, static_cast<uint32>(m_klen),
998 my_aes_256_cbc, m_iv, false);
999
1000 if (elen == MY_AES_BAD_DATA) {
1001 const auto page_id = page_get_page_id(src);
1002
1003 ib::error(ER_IB_MSG_844) << " Can't encrypt data of page " << page_id;
1004 *dst_len = src_len;
1005 return false;
1006 }
1007
1008 const auto len = static_cast<size_t>(elen);
1009 ut_a(len == chunk_len);
1010
1011 /* Encrypt the trailing bytes. */
1012 if (remain_len != 0) {
1013 /* Copy remaining bytes and page tailer. */
1014 memcpy(dst + FIL_PAGE_DATA + len, src + FIL_PAGE_DATA + len,
1015 remain_len);
1016
1017 constexpr size_t trailer_len = MY_AES_BLOCK_SIZE * 2;
1018 byte buf[trailer_len];
1019
1020 elen = my_aes_encrypt(dst + FIL_PAGE_DATA + data_len - trailer_len,
1021 static_cast<uint32>(trailer_len), buf, m_key,
1022 static_cast<uint32>(m_klen), my_aes_256_cbc, m_iv,
1023 false);
1024
1025 if (elen == MY_AES_BAD_DATA) {
1026 const auto page_id = page_get_page_id(src);
1027
1028 ib::error(ER_IB_MSG_845) << " Can't encrypt data of page," << page_id;
1029 *dst_len = src_len;
1030 return false;
1031 }
1032
1033 ut_a(static_cast<size_t>(elen) == trailer_len);
1034
1035 memcpy(dst + FIL_PAGE_DATA + data_len - trailer_len, buf, trailer_len);
1036 }
1037
1038 break;
1039 }
1040
1041 default:
1042 ut_error;
1043 }
1044
1045 /* Copy the header as is. */
1046 memmove(dst, src, FIL_PAGE_DATA);
1047 ut_ad(memcmp(src, dst, FIL_PAGE_DATA) == 0);
1048
1049 /* Add encryption control information. Required for decrypting. */
1050 if (page_type == FIL_PAGE_COMPRESSED) {
1051 /* If the page is compressed, we don't need to save the
1052 original type, since it is done in compression already. */
1053 mach_write_to_2(dst + FIL_PAGE_TYPE, FIL_PAGE_COMPRESSED_AND_ENCRYPTED);
1054 ut_ad(memcmp(src + FIL_PAGE_TYPE + 2, dst + FIL_PAGE_TYPE + 2,
1055 FIL_PAGE_DATA - FIL_PAGE_TYPE - 2) == 0);
1056 } else if (page_type == FIL_PAGE_RTREE) {
1057 /* If the page is R-tree page, we need to save original type. */
1058 mach_write_to_2(dst + FIL_PAGE_TYPE, FIL_PAGE_ENCRYPTED_RTREE);
1059 } else {
1060 mach_write_to_2(dst + FIL_PAGE_TYPE, FIL_PAGE_ENCRYPTED);
1061 mach_write_to_2(dst + FIL_PAGE_ORIGINAL_TYPE_V1, page_type);
1062 }
1063
1064 /* Add padding 0 for unused portion */
1065 if (src_len > src_enc_len) {
1066 memset(dst + src_enc_len, 0, src_len - src_enc_len);
1067 }
1068
1069 *dst_len = src_len;
1070
1071 return (true);
1072 }
1073
1074 byte *Encryption::encrypt(const IORequest &type, byte *src, ulint src_len,
1075 byte *dst, ulint *dst_len) const noexcept {
1076 /* For encrypting redo log, take another way. */
1077 ut_ad(!type.is_log());
1078
1079 #ifdef UNIV_ENCRYPT_DEBUG
1080
1081 const auto space_id =
1082 mach_read_from_4(src + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
1083 const auto page_no = mach_read_from_4(src + FIL_PAGE_OFFSET);
1084
1085 fprintf(stderr, "Encrypting page:%" PRIu32 ".%" PRIu32 " len: " ULINTPF "\n ",
1086 space_id, page_no, src_len);
1087 ut_print_buf(stderr, m_key, 32);
1088 ut_print_buf(stderr, m_iv, 32);
1089
1090 #endif /* UNIV_ENCRYPT_DEBUG */
1091
1092 ut_ad(m_type != NONE);
1093
1094 if (!encrypt_low(src, src_len, dst, dst_len)) {
1095 return (src);
1096 }
1097
1098 #ifdef UNIV_ENCRYPT_DEBUG
1099 {
1100 byte *check_buf = static_cast<byte *>(
1101 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, src_len));
1102 byte *buf2 = static_cast<byte *>(
1103 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, src_len));
1104
1105 memcpy(check_buf, dst, src_len);
1106
1107 dberr_t err = decrypt(type, check_buf, src_len, buf2, src_len);
1108 if (err != DB_SUCCESS ||
1109 memcmp(src + FIL_PAGE_DATA, check_buf + FIL_PAGE_DATA,
1110 src_len - FIL_PAGE_DATA) != 0) {
1111 ut_print_buf(stderr, src, src_len);
1112 ut_print_buf(stderr, check_buf, src_len);
1113 ut_d(ut_error);
1114 }
1115 ut::free(buf2);
1116 ut::free(check_buf);
1117
1118 fprintf(stderr, "Encrypted page:%" PRIu32 ".%" PRIu32 "\n", space_id,
1119 page_no);
1120 }
1121 #endif /* UNIV_ENCRYPT_DEBUG */
1122 return dst;
1123 }
1124
1125 dberr_t Encryption::decrypt_log_block(byte *const buf) const noexcept {
1126 /* This is the data we have to decrypt */
1127 byte *const data = buf + LOG_BLOCK_HDR_SIZE;
1128 /* This is data size to decrypt. */
1129 constexpr size_t data_len = OS_FILE_LOG_BLOCK_SIZE - LOG_BLOCK_HDR_SIZE;
1130 /* Temporary storage for the data part of the block, into which we put the
1131 originally encrypted data (after decrypting the "remainder" if necessary). */
1132 byte tmp[data_len];
1133 /* This is the number of full blocks encrypted with AES in the tmp. */
1134 constexpr size_t main_len =
1135 (data_len / MY_AES_BLOCK_SIZE) * MY_AES_BLOCK_SIZE;
1136 /* This is the number of unencrypted bytes at the end of the tmp. */
1137 constexpr size_t remain_len = data_len - main_len;
1138
1139 switch (m_type) {
1140 case AES: {
1141 int elen;
1142
1143 /* First decrypt the last 2 blocks data of data, since
1144 data is not block aligned. */
1145 if constexpr (remain_len != 0) {
1146 ut_ad(m_klen == KEY_LEN);
1147
1148 byte two_blocks[MY_AES_BLOCK_SIZE * 2];
1149
1150 static_assert(remain_len <= sizeof(two_blocks));
1151 static_assert(sizeof(two_blocks) <= data_len);
1152
1153 /* Copy the last 2 blocks. */
1154 memcpy(two_blocks, data + data_len - sizeof(two_blocks),
1155 sizeof(two_blocks));
1156
1157 elen = my_aes_decrypt(
1158 two_blocks, static_cast<uint32>(sizeof(two_blocks)),
1159 tmp + data_len - sizeof(two_blocks), m_key,
1160 static_cast<uint32>(m_klen), my_aes_256_cbc, m_iv, false);
1161 if (elen == MY_AES_BAD_DATA) {
1162 return (DB_IO_DECRYPT_FAIL);
1163 }
1164
1165 /* Copy the other data bytes to temp area. */
1166 memcpy(tmp, data, data_len - sizeof(two_blocks));
1167 } else {
1168 ut_ad(data_len == main_len);
1169
1170 /* Copy the data bytes to temp area. */
1171 memcpy(tmp, data, data_len);
1172 }
1173
1174 /* Then decrypt the main data */
1175 elen = my_aes_decrypt(tmp, static_cast<uint32>(main_len), data, m_key,
1176 static_cast<uint32>(m_klen), my_aes_256_cbc, m_iv,
1177 false);
1178 if (elen == MY_AES_BAD_DATA) {
1179 return (DB_IO_DECRYPT_FAIL);
1180 }
1181
1182 ut_ad(elen == static_cast<int>(main_len));
1183
1184 /* Copy the remaining bytes. */
1185 memcpy(data + main_len, tmp + main_len, remain_len);
1186
1187 break;
1188 }
1189
1190 default:
1191 return (DB_UNSUPPORTED);
1192 }
1193
1194 #ifdef UNIV_ENCRYPT_DEBUG
1195 {
1196 std::ostringstream msg{};
1197 msg << "Decrypted block " << log_block_get_hdr_no(buf) << "." << std::endl;
1198 ut_print_buf_hex(msg, buf, OS_FILE_LOG_BLOCK_SIZE);
1199 msg << std::endl;
1200 ib::info() << msg.str();
1201 }
1202 #endif
1203
1204 /* Reset the encrypted flag. */
1205 log_block_set_encrypt_bit(buf, false);
1206
1207 return (DB_SUCCESS);
1208 }
1209
1210 dberr_t Encryption::decrypt_log(byte *buf, size_t buf_len) const noexcept {
1211 dberr_t ret;
1212
1213 /* Encrypt the log blocks one by one. */
1214 for (byte *ptr = buf; ptr != buf + buf_len; ptr += OS_FILE_LOG_BLOCK_SIZE) {
1215 #ifdef UNIV_ENCRYPT_DEBUG
1216 {
1217 std::ostringstream msg;
1218
1219 msg << "Decrypting block: " << log_block_get_hdr_no(ptr) << std::endl;
1220 msg << "data={" << std::endl;
1221 ut_print_buf_hex(msg, ptr, OS_FILE_LOG_BLOCK_SIZE);
1222 msg << std::endl << "}";
1223
1224 ib::info(ER_IB_MSG_847) << msg.str();
1225 }
1226 #endif /* UNIV_ENCRYPT_DEBUG */
1227
1228 /* If it's not an encrypted block, skip it. */
1229 if (!is_encrypted_log(ptr)) {
1230 continue;
1231 }
1232
1233 /* Decrypt block */
1234 ret = decrypt_log_block(ptr);
1235 if (ret != DB_SUCCESS) {
1236 return (ret);
1237 }
1238 }
1239
1240 return (DB_SUCCESS);
1241 }
1242
1243 dberr_t Encryption::decrypt(const IORequest &type, byte *src, ulint src_len,
1244 byte *tmp, ulint tmp_len) const noexcept {
1245 ulint data_len;
1246 ulint main_len;
1247 ulint remain_len;
1248 ulint original_type;
1249 byte remain_buf[MY_AES_BLOCK_SIZE * 2];
1250 file::Block *block;
1251
1252 /* If the page is encrypted, then we need key to decrypt it. */
1253 if (is_encrypted_page(src) && m_type == NONE) {
1254 return DB_IO_DECRYPT_FAIL;
1255 }
1256
1257 if (!is_encrypted_page(src) || m_type == NONE) {
1258 /* There is nothing we can do. */
1259 return DB_SUCCESS;
1260 }
1261
1262 /* For compressed page, we need to get the compressed size
1263 for decryption */
1264 const ulint page_type = mach_read_from_2(src + FIL_PAGE_TYPE);
1265
1266 /* Actual length of the compressed data */
1267 uint16_t z_len = 0;
1268
1269 if (page_type == FIL_PAGE_COMPRESSED_AND_ENCRYPTED) {
1270 z_len = mach_read_from_2(src + FIL_PAGE_COMPRESS_SIZE_V1);
1271 src_len = z_len + FIL_PAGE_DATA;
1272
1273 Compression::meta_t header;
1274 Compression::deserialize_header(src, &header);
1275 if (header.m_version == Compression::FIL_PAGE_VERSION_1) {
1276 src_len = ut_calc_align(src_len, type.block_size());
1277 } else {
1278 /* Extend src_len if needed */
1279 if (src_len < MIN_ENCRYPTION_LEN) {
1280 src_len = MIN_ENCRYPTION_LEN;
1281 }
1282 }
1283 }
1284
1285 #ifdef UNIV_ENCRYPT_DEBUG
1286 const page_id_t page_id(
1287 mach_read_from_4(src + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID),
1288 mach_read_from_4(src + FIL_PAGE_OFFSET));
1289
1290 {
1291 std::ostringstream msg;
1292
1293 msg << "Decrypting page: " << page_id << " len: " << src_len << std::endl;
1294 msg << "key={";
1295 ut_print_buf(msg, m_key, 32);
1296 msg << "}" << std::endl << "iv= {";
1297 ut_print_buf(msg, m_iv, 32);
1298 msg << "}";
1299
1300 ib::info(ER_IB_MSG_848) << msg.str();
1301 }
1302 #endif /* UNIV_ENCRYPT_DEBUG */
1303
1304 original_type =
1305 static_cast<uint16_t>(mach_read_from_2(src + FIL_PAGE_ORIGINAL_TYPE_V1));
1306
1307 byte *ptr = src + FIL_PAGE_DATA;
1308
1309 /* The caller doesn't know what to expect */
1310 if (tmp == nullptr) {
1311 block = os_alloc_block();
1312 tmp = block->m_ptr;
1313 } else {
1314 ut_a(src_len <= tmp_len);
1315 block = nullptr;
1316 }
1317
1318 data_len = src_len - FIL_PAGE_DATA;
1319 main_len = (data_len / MY_AES_BLOCK_SIZE) * MY_AES_BLOCK_SIZE;
1320 remain_len = data_len - main_len;
1321
1322 switch (m_type) {
1323 case AES: {
1324 lint elen;
1325
1326 /* First decrypt the last 2 blocks data of data, since
1327 data is no block aligned. */
1328 if (remain_len != 0) {
1329 ut_ad(m_klen == KEY_LEN);
1330
1331 remain_len = MY_AES_BLOCK_SIZE * 2;
1332
1333 /* Copy the last 2 blocks. */
1334 memcpy(remain_buf, ptr + data_len - remain_len, remain_len);
1335
1336 elen = my_aes_decrypt(remain_buf, static_cast<uint32>(remain_len),
1337 tmp + data_len - remain_len, m_key,
1338 static_cast<uint32>(m_klen), my_aes_256_cbc, m_iv,
1339 false);
1340
1341 if (elen == MY_AES_BAD_DATA) {
1342 if (block != nullptr) {
1343 os_free_block(block);
1344 }
1345
1346 return (DB_IO_DECRYPT_FAIL);
1347 }
1348
1349 ut_ad(static_cast<ulint>(elen) == remain_len);
1350
1351 /* Copy the other data bytes to temp area. */
1352 memcpy(tmp, ptr, data_len - remain_len);
1353 } else {
1354 ut_ad(data_len == main_len);
1355
1356 /* Copy the data bytes to temp area. */
1357 memcpy(tmp, ptr, data_len);
1358 }
1359
1360 /* Then decrypt the main data */
1361 elen = my_aes_decrypt(tmp, static_cast<uint32>(main_len), ptr, m_key,
1362 static_cast<uint32>(m_klen), my_aes_256_cbc, m_iv,
1363 false);
1364 if (elen == MY_AES_BAD_DATA) {
1365 if (block != nullptr) {
1366 os_free_block(block);
1367 }
1368
1369 return (DB_IO_DECRYPT_FAIL);
1370 }
1371
1372 ut_ad(static_cast<ulint>(elen) == main_len);
1373
1374 /* Copy the remain bytes. */
1375 memcpy(ptr + main_len, tmp + main_len, data_len - main_len);
1376
1377 break;
1378 }
1379
1380 default:
1381 if (!type.is_dblwr()) {
1382 ib::error(ER_IB_MSG_849)
1383 << "Encryption algorithm support missing: " << to_string(m_type);
1384 }
1385
1386 if (block != nullptr) {
1387 os_free_block(block);
1388 }
1389
1390 return (DB_UNSUPPORTED);
1391 }
1392
1393 /* Restore the original page type. If it's a compressed and
1394 encrypted page, just reset it as compressed page type, since
1395 we will do uncompress later. */
1396
1397 if (page_type == FIL_PAGE_ENCRYPTED) {
1398 mach_write_to_2(src + FIL_PAGE_TYPE, original_type);
1399 mach_write_to_2(src + FIL_PAGE_ORIGINAL_TYPE_V1, 0);
1400 } else if (page_type == FIL_PAGE_ENCRYPTED_RTREE) {
1401 mach_write_to_2(src + FIL_PAGE_TYPE, FIL_PAGE_RTREE);
1402 } else {
1403 ut_ad(page_type == FIL_PAGE_COMPRESSED_AND_ENCRYPTED);
1404 mach_write_to_2(src + FIL_PAGE_TYPE, FIL_PAGE_COMPRESSED);
1405 }
1406
1407 if (block != nullptr) {
1408 os_free_block(block);
1409 }
1410
1411 #ifdef UNIV_DEBUG
1412 {
1413 /* Check if all the padding bytes are zeroes. */
1414 if (page_type == FIL_PAGE_COMPRESSED_AND_ENCRYPTED) {
1415 uint32_t padding = src_len - FIL_PAGE_DATA - z_len;
1416 for (uint32_t i = 0; i < padding; ++i) {
1417 byte *pad = src + z_len + FIL_PAGE_DATA + i;
1418 ut_ad(*pad == 0x0);
1419 }
1420 }
1421 }
1422 #endif /* UNIV_DEBUG */
1423
1424 #ifdef UNIV_ENCRYPT_DEBUG
1425 ib::info(ER_IB_MSG_850) << "Decrypted page: " << page_id;
1426 #endif /* UNIV_ENCRYPT_DEBUG */
1427
1428 DBUG_EXECUTE_IF("ib_crash_during_decrypt_page", DBUG_SUICIDE(););
1429
1430 return (DB_SUCCESS);
1431 }
1432
1433 #ifndef UNIV_HOTBACKUP
1434 bool Encryption::check_keyring() noexcept {
1435 bool ret = false;
1436 byte *master_key = nullptr;
1437
1438 if (s_master_key_id == DEFAULT_MASTER_KEY_ID) {
1439 /* This is the first time encryption is being used or till now no encrypted
1440 tablespace is loaded. */
1441 static bool checked = false;
1442 if (checked) {
1443 return true;
1444 }
1445
1446 /* Generate/Fetch/Delete a dummy master key to confirm keyring is up and
1447 running. */
1448 size_t key_len;
1449 char *key_type = nullptr;
1450 char key_name[MASTER_KEY_NAME_MAX_LEN];
1451
1452 key_name[sizeof(DEFAULT_MASTER_KEY)] = 0;
1453
1454 strncpy(key_name, DEFAULT_MASTER_KEY, sizeof(key_name));
1455
1456 /*
1457 We call keyring API to generate master key here.
1458 We don't care about failure at this point because
1459 master key may very well be present in keyring.
1460 All we are trying to check is keyring is functional.
1461 */
1462 (void)innobase::encryption::generate_key(key_name, innodb_key_type,
1463 KEY_LEN);
1464
1465 /* We call keyring API to get master key here. */
1466 int retval = keyring_operations_helper::read_secret(
1467 innobase::encryption::keyring_reader_service, key_name, nullptr,
1468 &master_key, &key_len, &key_type, PSI_INSTRUMENT_ME);
1469
1470 if (retval == -1) {
1471 ib::error(ER_IB_MSG_851) << "Check keyring fail, please check the"
1472 << " keyring is loaded.";
1473 } else {
1474 innobase::encryption::remove_key(key_name);
1475 ret = true;
1476 checked = true;
1477 }
1478
1479 if (key_type != nullptr) {
1480 my_free(key_type);
1481 }
1482
1483 if (master_key != nullptr) {
1484 my_free(master_key);
1485 }
1486 } else {
1487 uint32_t master_key_id;
1488
1489 Encryption::get_master_key(&master_key_id, &master_key);
1490 if (master_key != nullptr) {
1491 my_free(master_key);
1492 ret = true;
1493 }
1494 }
1495
1496 return (ret);
1497 }
1498 #endif /* !UNIV_HOTBACKUP */
1499
1500 Encryption::Type Encryption::get_type() const { return m_type; }
1501
1502 void Encryption::set_type(Encryption::Type type) { m_type = type; }
1503
1504 void Encryption::set_key(const byte *key) { m_key = key; }
1505
1506 ulint Encryption::get_key_length() const { return m_klen; }
1507
1508 void Encryption::set_key_length(ulint klen) { m_klen = klen; }
1509
1510 void Encryption::set_initial_vector(const byte *iv) { m_iv = iv; }
1511
1512 uint32_t Encryption::get_master_key_id() { return s_master_key_id; }
1513
1514 void Encryption::set_or_generate(Type type, byte *key, byte *iv,
1515 Encryption_metadata &metadata) {
1516 ut_ad(type != Encryption::NONE);
1517 metadata.m_type = type;
1518 metadata.m_key_len = Encryption::KEY_LEN;
1519 if (key == nullptr && iv == nullptr) {
1520 Encryption::random_value(metadata.m_key);
1521 Encryption::random_value(metadata.m_iv);
1522 } else if (key != nullptr && iv != nullptr) {
1523 memcpy(metadata.m_key, key, Encryption::KEY_LEN);
1524 memcpy(metadata.m_iv, iv, Encryption::KEY_LEN);
1525 } else {
1526 ut_error;
1527 }
1528 }