[PATCH v5 00/27] Integrate MbedTLS v3.6 LTS with U-Boot

Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.
Motivations: ------------
1. MbedTLS is well maintained with LTS versions. 2. LWIP is integrated with MbedTLS and easily to enable HTTPS. 3. MbedTLS recently switched license back to GPLv2.
Prerequisite: -------------
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via: $ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually: $ git add --renormalize . $ git commit
New Kconfig options: --------------------
`MBEDTLS_LIB` is for MbedTLS general switch. `MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto libs with MbedTLS. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. `LEGACY_CRYPTO` is introduced as a main switch for legacy crypto library. `LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and `LEGACY_CRYPTO_CERT` is for the certificate related functionalities. For each of the algorithm, a pair of `<alg>_LEGACY` and `<alg>_MBEDTLS` Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options are introduced.
In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and MBEDTLS_LIB_X509 are by default enabled in qemu_arm64_defconfig and sandbox_defconfig for testing purpose.
Patches for external MbedTLS project: -------------------------------------
Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs executables which is not supported by MbedTLS at the moment, addtional patches for MbedTLS are created to adapt with the EFI loader: 1. Decoding of Microsoft Authentication Code. 2. Decoding of PKCS#9 Authenticate Attributes. 3. Extending MbedTLS PKCS#7 lib to support multiple signer's certificates. 4. MbedTLS native test suites for PKCS#7 signer's info.
All above 4 patches (tagged with `mbedtls/external`) are submitted to MbedTLS project and being reviewed, eventually they should be part of MbedTLS LTS release. But before that, please merge them into U-Boot, otherwise the building will be broken when MBEDTLS_LIB_X509 is enabled.
See below PR link for the reference: https://github.com/Mbed-TLS/mbedtls/pull/9001
Miscellaneous: --------------
Optimized MbedTLS library size by tailoring the config file and disabling all unnecessary features for EFI loader.
From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1, sha256,
sha512) are completely replaced when MbedTLS is enabled.
From v3, the size-growth is slightly reduced by refactoring Hash functions.
Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66%
From v3: 4.55%
Please see the latest output from buildman for size-growth on QEMU arm64, Sandbox and Nanopi A64. [1]
Tests done: -----------
EFI Secure Boot test (EFI variables loading and verifying, EFI signed image verifying and booting) via U-Boot console. EFI Secure Boot and Capsule sandbox test passed.
Known issues: -------------
None.
[1]: buildman output for size comparison (qemu_arm64, sandbox and nanopi_a64) ``` aarch64: (for 2/2 boards) all +582.0 bss +40.0 data -64.0 rodata +206.0 text +400.0 qemu_arm64 : all +7040 bss +80 data -64 rodata +212 text +6812 u-boot: add: 28/-17, grow: 12/-16 bytes: 15492/-8304 (7188) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 mbedtls_internal_sha256_process - 2052 +2052 mbedtls_internal_sha512_process - 1056 +1056 K - 896 +896 mbedtls_sha512_finish - 556 +556 mbedtls_sha256_finish - 484 +484 mbedtls_sha1_finish - 420 +420 mbedtls_sha512_starts - 340 +340 mbedtls_md5_finish - 336 +336 mbedtls_sha512_update - 264 +264 mbedtls_sha256_update - 252 +252 mbedtls_sha1_update - 236 +236 mbedtls_md5_update - 236 +236 mbedtls_sha512 - 148 +148 mbedtls_sha256_starts - 124 +124 hash_init_sha512 52 128 +76 hash_init_sha256 52 128 +76 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 hash_init_sha1 52 112 +60 mbedtls_platform_zeroize - 56 +56 mbedtls_sha512_free - 16 +16 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +16 hash_finish_sha512 72 88 +16 hash_finish_sha256 72 88 +16 hash_finish_sha1 72 88 +16 sha512_csum_wd 68 80 +12 sha256_csum_wd 68 80 +12 sha1_csum_wd 68 80 +12 md5_wd 68 80 +12 mbedtls_sha512_init - 12 +12 mbedtls_sha256_init - 12 +12 mbedtls_sha1_init - 12 +12 mbedtls_md5_init - 12 +12 memset_func - 8 +8 sha512_update 4 8 +4 sha384_update 4 8 +4 sha256_update 12 8 -4 sha1_update 12 8 -4 sha256_process 16 - -16 sha1_process 16 - -16 hash_update_sha512 36 16 -20 hash_update_sha256 36 16 -20 hash_update_sha1 36 16 -20 MD5Init 56 36 -20 sha1_starts 60 36 -24 hash_update_sha384 36 - -36 hash_init_sha384 52 - -52 sha384_csum_wd 68 12 -56 sha256_starts 104 40 -64 sha256_padding 64 - -64 sha1_padding 64 - -64 hash_finish_sha384 72 - -72 sha512_finish 152 36 -116 sha512_starts 168 40 -128 sha384_starts 168 40 -128 sha384_finish 152 4 -148 MD5Final 196 44 -152 sha512_base_do_finalize 160 - -160 static.sha256_update 228 - -228 static.sha1_update 240 - -240 sha512_base_do_update 244 - -244 MD5Update 260 - -260 sha1_finish 300 36 -264 sha256_finish 404 36 -368 sha256_armv8_ce_process 428 - -428 sha1_armv8_ce_process 484 - -484 sha512_K 640 - -640 sha512_block_fn 1212 - -1212 MD5Transform 2552 - -2552 nanopi_a64 : all -5876 data -64 rodata +200 text -6012 u-boot: add: 21/-8, grow: 4/-8 bytes: 12312/-4364 (7948) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 mbedtls_internal_sha256_process - 2052 +2052 mbedtls_sha256_finish - 484 +484 mbedtls_sha1_finish - 420 +420 mbedtls_md5_finish - 336 +336 K - 256 +256 mbedtls_sha256_update - 252 +252 mbedtls_sha1_update - 236 +236 mbedtls_md5_update - 236 +236 mbedtls_sha256_starts - 124 +124 hash_init_sha256 52 128 +76 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 hash_init_sha1 52 112 +60 mbedtls_platform_zeroize - 56 +56 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +16 hash_finish_sha256 72 88 +16 hash_finish_sha1 72 88 +16 mbedtls_sha256_init - 12 +12 mbedtls_sha1_init - 12 +12 mbedtls_md5_init - 12 +12 memset_func - 8 +8 sha256_update 12 - -12 sha1_update 12 - -12 hash_update_sha256 36 16 -20 hash_update_sha1 36 16 -20 MD5Init 56 36 -20 sha1_starts 60 36 -24 sha256_starts 104 40 -64 sha256_padding 64 - -64 sha1_padding 64 - -64 MD5Final 196 44 -152 static.sha256_update 228 - -228 static.sha1_update 240 - -240 MD5Update 260 - -260 sha1_finish 300 36 -264 sha256_finish 404 36 -368 MD5Transform 2552 - -2552 sandbox: (for 1/1 boards) all +22416.0 data +1440.0 rodata -4160.0 text +25136.0 sandbox : all +22416 data +1440 rodata -4160 text +25136 u-boot: add: 253/-203, grow: 115/-61 bytes: 93168/-76647 (16521) function old new delta mbedtls_internal_sha1_process - 4982 +4982 static.mbedtls_x509_crt_parse_der_internal - 4184 +4184 static.pci_uclass_post_probe - 3570 +3570 pkcs7_parse_message 361 3638 +3277 mbedtls_internal_sha256_process - 2726 +2726 static.sandbox_tpm2_xfer - 2605 +2605 rsa_verify 541 2794 +2253 mbedtls_internal_md5_process - 2189 +2189 mbedtls_rsa_parse_pubkey - 2053 +2053 mbedtls_rsa_private - 1813 +1813 run_test 2220 3932 +1712 mbedtls_mpi_exp_mod - 1649 +1649 read_one_chunk - 1606 +1606 x509_populate_cert - 1462 +1462 mbedtls_mpi_div_mpi - 1459 +1459 static.simple_panel_get_edid_timing - 1385 +1385 mbedtls_internal_sha512_process - 1368 +1368 static.sqfs_search_dir - 1336 +1336 static.mbedtls_x509_dn_gets - 1305 +1305 mbedtls_mpi_inv_mod - 1214 +1214 mbedtls_rsa_rsaes_pkcs1_v15_decrypt - 1156 +1156 mbedtls_x509_get_subject_alt_name_ext - 1155 +1155 rsa_check_pair_wrap - 1018 +1018 static.K - 896 +896 oid_x520_attr_type - 840 +840 static.pci_uclass_pre_probe - 832 +832 read_persistent_digest - 825 +825 ta_rpc_test_invoke_func - 812 +812 ta_avb_invoke_func - 783 +783 static.dm_pciauto_setup_device - 747 +747 efi_load_image 4418 5157 +739 static.pkcs7_get_signer_info - 671 +671 mbedtls_sha512_finish - 658 +658 static.dfu_bind - 637 +637 efi_tcg2_hash_log_extend_event - 622 +622 static.sqfs_frag_lookup - 605 +605 mbedtls_mpi_core_montmul - 537 +537 mbedtls_mpi_core_mla - 520 +520 mbedtls_sha256_finish - 519 +519 static.sqfs_resolve_symlink - 509 +509 static.overlay_update_local_node_references - 483 +483 mbedtls_x509_get_time - 483 +483 mbedtls_mpi_mul_mpi - 479 +479 mbedtls_x509_get_name - 470 +470 mbedtls_pk_parse_subpubkey - 463 +463 efi_tcg2_get_capability - 462 +462 find_and_setup_root - 456 +456 static.new_string - 450 +450 static.set_string - 448 +448 mbedtls_sha1_finish - 445 +445 longest_match - 424 +424 rsa_rsassa_pkcs1_v15_encode - 414 +414 mbedtls_mpi_gcd - 413 +413 load_full_partition - 413 +413 static.get_languages - 402 +402 static.efi_uninstall_protocol - 400 +400 static.list_package_lists - 398 +398 static.update_package_list - 374 +374 static.efi_disconnect_all_drivers - 363 +363 efi_tcg2_get_eventlog - 361 +361 static.get_string - 360 +360 oid_x509_ext - 360 +360 static.new_package_list - 359 +359 static.efi_convert_device_path_to_text - 359 +359 static.get_keyboard_layout - 355 +355 rsa_sign_wrap - 355 +355 add_sub_mpi - 355 +355 efi_tcg2_submit_command - 351 +351 static.find_keyboard_layouts - 339 +339 rsa_verify_wrap - 324 +324 oid_sig_alg - 320 +320 efi_tcg2_notify_exit_boot_services - 316 +316 mbedtls_mpi_sub_abs - 315 +315 static.append_device_path_instance - 311 +311 static.get_secondary_languages - 301 +301 rsa_encrypt_wrap - 294 +294 static.hash_init_sha512 41 334 +293 static.efi_convert_device_node_to_text - 293 +293 static.get_next_device_path_instance - 290 +290 spi_set_speed_mode - 287 +287 static.buck_get_suspend_enable - 276 +276 mbedtls_mpi_core_get_mont_r2_unsafe - 276 +276 efi_tcg2_get_active_pcr_banks - 273 +273 public_key - 270 +270 static.buck_set_suspend_enable - 264 +264 static.rsa_check_context - 260 +260 public_key_verify_signature 419 678 +259 __udivti3 - 248 +248 mbedtls_rsa_public - 242 +242 static.oid_md_alg - 240 +240 mbedtls_asn1_get_alg - 238 +238 static.get_package_list_handle - 231 +231 static.dm_pciauto_exp_link_stable - 231 +231 static.overlay_get_target - 224 +224 mbedtls_mpi_shift_l - 224 +224 mbedtls_pkcs7_free - 223 +223 static.register_package_notify - 222 +222 static.create_device_node - 222 +222 mbedtls_mpi_fill_random - 221 +221 static.dfu_handle - 213 +213 static.usb_emul_find_devnum - 210 +210 mbedtls_sha512_update - 209 +209 static.remove_package_list - 208 +208 static.export_package_lists - 206 +206 static.sqfs_tokenize - 201 +201 static.is_device_path_multi_instance - 201 +201 mbedtls_mpi_copy - 200 +200 mbedtls_sha256_update - 197 +197 static.set_keyboard_layout - 196 +196 static.ldo_set_suspend_enable - 195 +195 static.asn1_get_tagged_int - 194 +194 static.get_device_path_size - 191 +191 static.efi_open_volume - 191 +191 static.append_device_path - 190 +190 static.append_device_node - 188 +188 static.ldo_get_suspend_enable - 182 +182 mbedtls_pk_parse_public_key - 182 +182 static.duplicate_device_path - 180 +180 mbedtls_x509_crt_free - 177 +177 static.mbedtls_sha1_update - 176 +176 mbedtls_mpi_shift_r - 174 +174 static.unregister_package_notify - 169 +169 rsa_free_wrap - 161 +161 mbedtls_mpi_cmp_mpi - 161 +161 static.pkcs7_get_one_cert - 160 +160 oid_pk_alg - 160 +160 mbedtls_mpi_read_binary - 159 +159 md5_wd 571 729 +158 mbedtls_mpi_core_write_be - 154 +154 static.switch_set_enable - 150 +150 mbedtls_mpi_mod_mpi - 146 +146 mbedtls_asn1_get_alg_null - 142 +142 __alloc_extent_buffer - 142 +142 static.pldo_set_enable - 141 +141 mbedtls_mpi_cmp_abs - 141 +141 mbedtls_mpi_mul_int - 138 +138 mbedtls_asn1_get_len - 133 +133 static.switch_get_enable - 130 +130 static.nldo_set_enable - 130 +130 static.overlay_adjust_node_phandles - 121 +121 static.hash_init_sha256 41 161 +120 mbedtls_mpi_grow - 120 +120 reg_set_enable - 118 +118 mbedtls_rsa_check_pubkey - 109 +109 static.pldo_get_enable - 108 +108 static.mbedtls_asn1_get_bitstring - 108 +108 x509_get_timestamp - 106 +106 static.buck_get_suspend_value - 101 +101 mbedtls_asn1_get_bool - 99 +99 static.asn1_get_sequence_of_cb - 98 +98 efi_reserve_memory - 97 +97 mbedtls_rsa_info - 96 +96 static.buck_set_suspend_value - 93 +93 ldo_get_enable - 92 +92 buck_get_enable - 92 +92 data_gz 21219 21309 +90 mbedtls_x509_get_serial - 88 +88 mbedtls_mpi_resize_clear - 87 +87 static.sqfs_read_entry - 86 +86 static.nldo_get_enable - 83 +83 mbedtls_mpi_bitlen - 82 +82 static.x509_get_uid - 81 +81 static.mbedtls_mpi_sub_int - 81 +81 static.pldo_set_suspend_enable - 78 +78 mbedtls_oid_get_md_alg - 78 +78 ldo_set_enable - 77 +77 buck_set_enable - 77 +77 static.sqfs_count_tokens - 76 +76 static.pldo_set_value - 75 +75 static.pldo_set_suspend_value - 75 +75 static.pldo_get_suspend_enable - 75 +75 static.nldo_set_value - 75 +75 static.nldo_set_suspend_value - 75 +75 mbedtls_mpi_cmp_int - 75 +75 find_device - 75 +75 rsa_decrypt_wrap - 73 +73 pta_scp03_invoke_func - 73 +73 mbedtls_mpi_lset - 73 +73 mbedtls_md_info_from_type - 72 +72 static.sqfs_disk_read - 69 +69 static.sqfs_calc_n_blks - 69 +69 static.simple_panel_set_backlight - 68 +68 ldo_get_value - 67 +67 buck_get_value - 67 +67 static.nldo_set_suspend_enable - 65 +65 free_extent_state_func - 65 +65 static.nldo_get_suspend_enable - 64 +64 sha1_starts - 64 +64 mbedtls_mpi_lsb - 64 +64 rsa_alloc_wrap - 62 +62 mbedtls_pk_setup - 62 +62 pkcs7_free_message 115 176 +61 static.unicode_test_u16_strcmp - 60 +60 rsa_debug - 60 +60 lib_test_strlcat 1195 1255 +60 public_key_signature_free - 58 +58 static.x509_free_mbedtls_ctx - 57 +57 static.nldo_get_value - 57 +57 static.nldo_get_suspend_value - 57 +57 x509_populate_dn_name_string - 56 +56 efi_tcg2_protocol - 56 +56 mbedtls_mpi_core_montmul_init - 55 +55 static.pldo_get_value - 54 +54 static.pldo_get_suspend_value - 54 +54 mbedtls_asn1_get_bitstring_null - 53 +53 efi_launch_capsules 3090 3142 +52 static.pkcs7_free_signer_info - 51 +51 static.ldo_set_suspend_value - 51 +51 mbedtls_mpi_free - 51 +51 static.mbedtls_mpi_core_bigendian_to_host - 50 +50 mbedtls_asn1_get_tag - 50 +50 event_log - 48 +48 mbedtls_pk_free - 45 +45 mbedtls_zeroize_and_free - 42 +42 static.ldo_get_suspend_value - 38 +38 static.sandbox_tpm2_get_desc - 35 +35 efi_capsule_update_firmware 1354 1389 +35 static.simple_panel_enable_backlight - 34 +34 static.efi_firmware_get_image_info 696 730 +34 x509_parse2_int - 33 +33 ldo_set_value - 32 +32 buck_set_value - 32 +32 static.hash_init_sha1 75 105 +30 mbedtls_asn1_sequence_free - 30 +30 mbedtls_asn1_free_named_data_list_shallow - 30 +30 efi_start_image 2492 2522 +30 static.hash_finish_sha512 40 66 +26 static.hash_finish_sha256 40 66 +26 static.hash_finish_sha1 40 66 +26 generic_phy_get_bulk 366 392 +26 reboot_mode_probe 139 164 +25 static.efi_open_protocol 495 519 +24 static.mbedtls_mpi_get_bit - 23 +23 sqfs_opendir 1655 1677 +22 rsa_can_do - 22 +22 efi_install_fdt 572 594 +22 sha512_starts 132 152 +20 mbedtls_sha512_free - 20 +20 mbedtls_sha256_free - 20 +20 mbedtls_sha1_free - 20 +20 efi_query_capsule_caps 210 229 +19 static.mbedtls_platform_zeroize - 18 +18 sha256_starts 68 86 +18 pta_scp03_open_session - 18 +18 mbedtls_mpi_size - 18 +18 c2 - 18 +18 static.efi_cout_set_cursor_position 257 274 +17 rsa_get_bitlen - 17 +17 static.efi_register_notify_events - 16 +16 static.efi_cout_query_mode 241 257 +16 static.dfu_runtime_descs - 16 +16 static.__reset_get_bulk 166 182 +16 mbedtls_sha512_init - 16 +16 efi_guid_tcg2_protocol - 16 +16 efi_guid_final_events - 16 +16 efi_file_info_guid - 16 +16 clk_get_bulk 157 173 +16 efi_tcg2_set_active_pcr_banks - 15 +15 efi_tcg2_get_result_of_set_active_pcr_banks - 15 +15 efi_pxe_base_code_arp - 15 +15 unicode_test_utf8_utf16_strcpy 946 960 +14 mbedtls_mpi_add_mpi - 14 +14 c4 - 14 +14 c1 - 14 +14 efi_locate_device_path 541 554 +13 efi_file_read_int 610 623 +13 d4 - 13 +13 rtc_days_in_month - 12 +12 mbedtls_mpi_sub_mpi - 12 +12 i2 - 12 +12 static.efi_cin_unregister_key_notify 257 268 +11 efi_auth_var_get_type 102 113 +11 i1 - 10 +10 fdt_overlay_apply 1887 1897 +10 x509_free_certificate 115 124 +9 static.efi_cout_output_string 534 543 +9 static.efi_cin_reset_ex 185 194 +9 static.efi_cin_reset 185 194 +9 static.dfu_intf_runtime - 9 +9 free_map_lookup - 9 +9 static.memset_func - 8 +8 static.efi_connect_controller 685 693 +8 mbedtls_sha512_info - 8 +8 mbedtls_sha384_info - 8 +8 mbedtls_sha256_info - 8 +8 mbedtls_sha1_info - 8 +8 mbedtls_md5_info - 8 +8 mbedtls_ct_zero - 8 +8 i3 - 8 +8 c3 - 8 +8 unicode_test_utf8_utf16_strlen 443 450 +7 unicode_test_utf16_utf8_strlen 443 450 +7 unicode_test_utf16_utf8_strcpy 1021 1028 +7 static.efi_firmware_raw_set_image 2312 2319 +7 static.efi_cin_register_key_notify 296 303 +7 static.efi_cin_read_key_stroke_ex 386 393 +7 static.efi_cin_read_key_stroke 247 254 +7 pci_bus_read_config 83 90 +7 mpi_bigendian_to_host - 7 +7 check_node_type 171 178 +7 ta_rpc_test_open_session - 6 +6 ta_avb_open_session - 6 +6 j3 - 6 +6 efi_signature_verify 1640 1646 +6 j1 - 5 +5 eficonfig_process_select_file 2179 2184 +5 efi_protocol_open 408 413 +5 efi_dp_from_file 274 279 +5 crypt_sha512crypt_rn_wrapped 2408 2413 +5 crypt_sha256crypt_rn_wrapped 1669 1674 +5 unicode_test_u16_strlen 269 273 +4 static.eficonfig_edit_boot_option 1567 1571 +4 static.efi_purge_handle 150 154 +4 sqfs_find_inode 347 351 +4 sqfs_dir_offset 101 105 +4 pci_conv_32_to_size 46 50 +4 pci_bus_find_devfn 121 125 +4 fdt_subnode_offset_namelen 240 244 +4 efi_unload_image 403 407 +4 efi_search_obj 43 47 +4 efi_delete_image 150 154 +4 efi_close_protocol 229 233 +4 efi_add_memory_map 34 38 +4 do_bootefi_exec 444 448 +4 dm_spi_release_bus 23 27 +4 dm_spi_claim_bus 153 157 +4 dm_pci_write_config8 10 14 +4 dm_pci_write_config16 13 17 +4 asymmetric_key_generate_id 109 113 +4 unicode_test_u16_strncmp 377 380 +3 unicode_test_u16_strlcat 840 843 +3 unflatten_device_tree 274 277 +3 str_upper 648 651 +3 static.efi_reinstall_protocol_interface 277 280 +3 static.efi_exit 668 671 +3 sandbox_hub_bind 20 23 +3 find_handle 314 317 +3 eficonfig_file_selected 484 487 +3 efi_firmware_get_lsv_from_dtb 369 372 +3 efi_create_indexed_name 174 177 +3 efi_auth_var_get_guid 85 88 +3 SHA256_Update_recycled 76 79 +3 unicode_test_utf8_utf16_strncpy 929 931 +2 unicode_test_utf16_utf8_strncpy 921 923 +2 static.tcg2_measure_variable 236 238 +2 static.efi_cout_set_mode 222 224 +2 static.do_env_print 1278 1280 +2 prepare_file_selection_entry 400 402 +2 eficonfig_boot_edit_save 96 98 +2 eficonfig_add_change_boot_order_entry 346 348 +2 eficonfig_add_boot_selection_entry 461 463 +2 efi_str_to_u16 103 105 +2 efi_serialize_load_option 260 262 +2 efi_get_variable_mem 492 494 +2 efi_file_setinfo 523 525 +2 efi_file_getinfo 783 785 +2 efi_convert_string 109 111 +2 efi_binary_run 790 792 +2 do_bootmenu 2154 2156 +2 create_boot_option_entry 206 208 +2 bootdev_hunt 366 368 +2 add_packages 890 892 +2 unicode_test_efi_create_indexed_name 481 482 +1 u16_strsize 20 21 +1 u16_strlcat 106 107 +1 file_open 738 739 +1 efi_var_mem_ins 257 258 +1 cros_ec_spi_command 420 421 +1 efi_update_capsule 427 426 -1 byteReverse 1 - -1 static.efi_cout_set_attribute 249 247 -2 sha256_csum_wd 155 153 -2 vidconsole_sync_copy 13 9 -4 vidconsole_memmove 51 47 -4 tcg2_uninit 212 208 -4 static.hash_update_sha1 29 25 -4 spi_find_chip_select 440 436 -4 sha512_csum_wd 169 165 -4 read_tree_block 1566 1562 -4 read_allocated_block 2304 2300 -4 put_ext4 383 379 -4 free_extent_buffer 321 317 -4 ext4fs_update_journal 893 889 -4 ext4fs_read_inode 392 388 -4 ext4fs_devread 34 30 -4 efi_init_early 1055 1051 -4 cros_ec_register 291 287 -4 cros_ec_calc_checksum 27 23 -4 cache_tree_free_extents 57 53 -4 btrfs_setup_root 101 97 -4 btrfs_scan_one_device 675 671 -4 btrfs_release_all_roots 62 58 -4 btrfs_read_dev_super 1228 1224 -4 btrfs_free_path 38 34 -4 btrfs_free_fs_info 53 49 -4 btrfs_close_devices 136 132 -4 avb_malloc 78 74 -4 static.hash_update_sha512 22 17 -5 static.hash_update_sha256 22 17 -5 lib_test_efi_dp_check_length 593 588 -5 efi_stri_coll 252 247 -5 cros_ec_i2c_command 409 404 -5 static.ta_rpc_test_open_session 6 - -6 static.ta_avb_open_session 6 - -6 static.load_and_verify_vbmeta 10699 10693 -6 efi_str_to_fat 369 362 -7 static.free_map_lookup 9 - -9 efi_init_obj_list 5665 5656 -9 dfu_intf_runtime 9 - -9 rsa_verify_key 383 372 -11 install_smbios_table 583 571 -12 d5 12 - -12 sha256_update 14 - -14 efi_runtime_relocate 240 226 -14 x509_akid_note_name 15 - -15 static.efi_tcg2_set_active_pcr_banks 15 - -15 static.efi_tcg2_get_result_of_set_active_pcr_banks 15 - -15 static.efi_pxe_base_code_arp 15 - -15 pkcs7_sig_note_skid 15 - -15 pkcs7_sig_note_serial 15 - -15 pkcs7_sig_note_issuer 15 - -15 static.rsapubkey_action_table 16 - -16 efi_register_notify_events 16 - -16 efi_guid_event_group_return_to_efibootmgr 16 - -16 efi_disk_probe 571 555 -16 dfu_runtime_descs 16 - -16 static.pta_scp03_open_session 18 - -18 sha384_csum_wd 296 276 -20 x509_note_serial 21 - -21 tcg2_create_digest 718 697 -21 static.hash_update_sha384 22 - -22 pkcs7_check_content_type 22 - -22 do_net_stats 371 349 -22 x509_decoder 24 - -24 x509_akid_decoder 24 - -24 rsapubkey_decoder 24 - -24 pkcs7_decoder 24 - -24 mscode_machine 24 - -24 mscode_decoder 24 - -24 mscode_action_table 24 - -24 efi_set_variable_int 2130 2105 -25 x509_note_tbs_certificate 26 - -26 x509_note_not_before 28 - -28 x509_note_not_after 28 - -28 pkcs7_note_data 28 - -28 x509_note_issuer 30 - -30 rsa_get_n 30 - -30 ZSTD_decompressDCtx 7789 7758 -31 static.ldo_set_value 113 81 -32 static.buck_set_value 203 171 -32 _u_boot_list_2_ut_lib_test_2_lib_asn1_x509 32 - -32 _u_boot_list_2_ut_lib_test_2_lib_asn1_pkey 32 - -32 _u_boot_list_2_ut_lib_test_2_lib_asn1_pkcs7 32 - -32 sandbox_tpm2_get_desc 35 - -35 x509_note_subject 36 - -36 pkcs7_note_content 36 - -36 simple_panel_enable_backlight 37 - -37 sha1_csum_wd 209 171 -38 ldo_get_suspend_value 38 - -38 x509_akid_action_table 40 - -40 static.hash_finish_sha384 40 - -40 x509_note_params 41 - -41 pkcs7_note_signeddata_version 41 - -41 asn1_op_lengths 41 - -41 efi_esrt_populate 1209 1165 -44 pkcs7_note_certificate_list 46 - -46 static.public_key_signature_free 48 - -48 static.event_log 48 - -48 mscode_note_digest 51 - -51 ldo_set_suspend_value 51 - -51 pldo_get_value 54 - -54 pldo_get_suspend_value 54 - -54 unicode_test_u16_strcmp 56 - -56 static.efi_tcg2_protocol 56 - -56 rsa_get_e 56 - -56 nldo_get_value 57 - -57 nldo_get_suspend_value 57 - -57 x509_extract_name_segment 62 - -62 sha256_padding 64 - -64 sha1_padding 64 - -64 nldo_get_suspend_enable 64 - -64 static.free_extent_state_func 65 - -65 sqfs_disk_read 65 - -65 sqfs_calc_n_blks 65 - -65 nldo_set_suspend_enable 65 - -65 static.ldo_get_value 133 66 -67 static.buck_get_value 196 129 -67 simple_panel_set_backlight 68 - -68 pkcs7_sig_note_signature 68 - -68 static.__func__ 32530 32459 -71 sqfs_count_tokens 72 - -72 pkcs7_sig_note_set_of_authattrs 72 - -72 static.pta_scp03_invoke_func 73 - -73 pldo_set_value 75 - -75 pldo_set_suspend_value 75 - -75 pldo_get_suspend_enable 75 - -75 pkcs7_sig_note_pkey_algo 75 - -75 nldo_set_value 75 - -75 nldo_set_suspend_value 75 - -75 static.ldo_set_enable 370 293 -77 static.buck_set_enable 482 405 -77 pldo_set_suspend_enable 78 - -78 static.find_device 79 - -79 pkcs7_note_signerinfo_version 79 - -79 x509_akid_note_kid 80 - -80 x509_akid_note_serial 81 - -81 pkcs7_extract_cert 81 - -81 sqfs_read_entry 82 - -82 nldo_get_enable 83 - -83 sha512_finish 123 32 -91 sha384_finish 123 32 -91 static.ldo_get_enable 386 294 -92 static.buck_get_enable 443 351 -92 x509_akid_machine 93 - -93 buck_set_suspend_value 93 - -93 x509_extract_key_data 98 - -98 static.efi_reserve_memory 101 - -101 buck_get_suspend_value 101 - -101 x509_action_table 104 - -104 x509_note_OID 105 - -105 pldo_get_enable 108 - -108 x509_machine 113 - -113 overlay_adjust_node_phandles 117 - -117 static.reg_set_enable 118 - -118 x509_process_extension 125 - -125 x509_note_signature 129 - -129 switch_get_enable 130 - -130 nldo_set_enable 130 - -130 pkcs7_note_OID 136 - -136 pkcs7_action_table 136 - -136 pldo_set_enable 141 - -141 static.__alloc_extent_buffer 146 - -146 switch_set_enable 150 - -150 oid_index 150 - -150 static.hash_init_sha384 152 - -152 sha512_base_do_finalize 154 - -154 unregister_package_notify 169 - -169 duplicate_device_path 180 - -180 ldo_get_suspend_enable 182 - -182 pkcs7_note_signed_info 187 - -187 append_device_node 188 - -188 mscode_note_content_type 189 - -189 pkcs7_sig_note_digest_algo 190 - -190 append_device_path 190 - -190 get_device_path_size 191 - -191 efi_open_volume 191 - -191 static.sha256_update 194 - -194 static.sha512_base_do_update 195 - -195 ldo_set_suspend_enable 195 - -195 set_keyboard_layout 196 - -196 sqfs_tokenize 197 - -197 is_device_path_multi_instance 201 - -201 usb_emul_find_devnum 206 - -206 export_package_lists 206 - -206 look_up_OID 207 - -207 remove_package_list 208 - -208 dfu_handle 213 - -213 static.sha1_update 216 - -216 overlay_get_target 220 - -220 register_package_notify 222 - -222 create_device_node 222 - -222 dm_pciauto_exp_link_stable 227 - -227 get_package_list_handle 231 - -231 pkcs7_machine 239 - -239 static.sprint_oid 241 - -241 lib_asn1_pkcs7 244 - -244 sha256_k 256 - -256 buck_set_suspend_enable 264 - -264 pkcs7_sig_note_authenticated_attr 268 - -268 static.efi_tcg2_get_active_pcr_banks 273 - -273 buck_get_suspend_enable 276 - -276 sha1_finish 288 - -288 lib_asn1_pkey 290 - -290 get_next_device_path_instance 290 - -290 x509_note_pkey_algo 291 - -291 static.spi_set_speed_mode 291 - -291 efi_convert_device_node_to_text 293 - -293 oid_search_table 296 - -296 get_secondary_languages 301 - -301 append_device_path_instance 311 - -311 static.efi_tcg2_notify_exit_boot_services 316 - -316 sha256_finish 357 32 -325 mscode_note_digest_algo 327 - -327 find_keyboard_layouts 339 - -339 static.efi_tcg2_submit_command 351 - -351 get_keyboard_layout 355 - -355 new_package_list 359 - -359 efi_disconnect_all_drivers 359 - -359 efi_convert_device_path_to_text 359 - -359 get_string 526 166 -360 static.efi_tcg2_get_eventlog 361 - -361 update_package_list 374 - -374 efi_uninstall_protocol 396 - -396 list_package_lists 398 - -398 get_languages 402 - -402 static.load_full_partition 417 - -417 lib_asn1_x509 423 - -423 static.x509_fabricate_name 428 - -428 static.longest_match 428 - -428 set_string 448 - -448 new_string 450 - -450 static.find_and_setup_root 460 - -460 static.efi_tcg2_get_capability 462 - -462 overlay_update_local_node_references 479 - -479 sqfs_resolve_symlink 505 - -505 oid_data 513 - -513 static.public_key 540 - -540 sqfs_frag_lookup 601 - -601 static.efi_tcg2_hash_log_extend_event 622 - -622 dfu_bind 637 - -637 sha512_k 640 - -640 dm_pciauto_setup_device 743 - -743 static.x509_decode_time 779 - -779 static.ta_avb_invoke_func 783 - -783 x509_cert_parse 973 179 -794 static.ta_rpc_test_invoke_func 812 - -812 static.read_persistent_digest 829 - -829 pci_uclass_pre_probe 832 - -832 cert_data 971 - -971 sqfs_search_dir 1332 - -1332 simple_panel_get_edid_timing 1381 - -1381 asn1_ber_decoder 1511 - -1511 static.read_one_chunk 1610 - -1610 rsa_verify_with_pkey 1680 - -1680 static.run_test 1710 - -1710 sha512_block_fn 1714 - -1714 image_pk7 1811 - -1811 MD5Transform 1812 - -1812 sandbox_tpm2_xfer 2605 - -2605 pci_uclass_post_probe 3570 - -3570 sha1_process_one 8090 - -8090 sha256_process_one 9972 - -9972 ```
Raymond Mao (27): CI: Exclude MbedTLS subtree for CONFIG checks mbedtls: add mbedtls into the build system lib: Adapt digest header files to MbedTLS md5: Remove md5 non-watchdog API sha1: Remove sha1 non-watchdog API mbedtls: add digest shim layer for MbedTLS hash: integrate hash on mbedtls mbedtls/external: support Microsoft Authentication Code mbedtls/external: support PKCS9 Authenticate Attributes mbedtls/external: support decoding multiple signer's cert mbedtls/external: update MbedTLS PKCS7 test suites public_key: move common functions to public key helper x509: move common functions to x509 helper pkcs7: move common functions to PKCS7 helper mbedtls: add public key porting layer lib/crypto: Adapt public_key header with MbedTLS mbedtls: add X509 cert parser porting layer lib/crypto: Adapt x509_cert_parser to MbedTLS mbedtls: add PKCS7 parser porting layer lib/crypto: Adapt PKCS7 parser to MbedTLS mbedtls: add MSCode parser porting layer lib/crypto: Adapt mscode_parser to MbedTLS mbedtls: add RSA helper layer on MbedTLS lib/rypto: Adapt rsa_helper to MbedTLS asn1_decoder: add build options for ASN1 decoder test: Remove ASN1 library test configs: enable MbedTLS as default setting
.azure-pipelines.yml | 3 +- .gitlab-ci.yml | 3 +- Makefile | 6 + board/friendlyarm/nanopi2/board.c | 3 +- board/gdsys/a38x/hre.c | 2 +- board/intel/edison/edison.c | 3 +- board/xilinx/zynq/bootimg.c | 2 +- common/hash.c | 146 +++++ configs/qemu_arm64_defconfig | 3 + configs/sandbox_defconfig | 3 + include/crypto/mscode.h | 4 + include/crypto/pkcs7_parser.h | 56 ++ include/crypto/public_key.h | 6 + include/crypto/x509_parser.h | 55 ++ include/limits.h | 29 + include/linux/kernel.h | 13 +- include/stdlib.h | 1 + include/u-boot/md5.h | 14 +- include/u-boot/sha1.h | 37 +- include/u-boot/sha256.h | 20 + include/u-boot/sha512.h | 22 +- lib/Kconfig | 4 + lib/Makefile | 14 +- lib/crypto/Kconfig | 2 +- lib/crypto/Makefile | 16 +- lib/crypto/asymmetric_type.c | 2 +- lib/crypto/pkcs7_helper.c | 37 ++ lib/crypto/pkcs7_parser.c | 28 - lib/crypto/public_key.c | 31 -- lib/crypto/public_key_helper.c | 39 ++ lib/crypto/x509_helper.c | 64 +++ lib/crypto/x509_public_key.c | 58 +- lib/mbedtls/Kconfig | 400 ++++++++++++++ lib/mbedtls/Makefile | 56 ++ .../external/mbedtls/include/mbedtls/oid.h | 35 ++ .../external/mbedtls/include/mbedtls/pkcs7.h | 21 + lib/mbedtls/external/mbedtls/library/pkcs7.c | 154 ++++-- .../tests/suites/test_suite_pkcs7.data | 4 +- lib/mbedtls/mbedtls_def_config.h | 69 +++ lib/mbedtls/md5.c | 57 ++ lib/mbedtls/mscode_parser.c | 123 +++++ lib/mbedtls/pkcs7_parser.c | 506 ++++++++++++++++++ lib/mbedtls/port/assert.h | 12 + lib/mbedtls/public_key.c | 82 +++ lib/mbedtls/rsa_helper.c | 95 ++++ lib/mbedtls/sha1.c | 99 ++++ lib/mbedtls/sha256.c | 62 +++ lib/mbedtls/sha512.c | 93 ++++ lib/mbedtls/x509_cert_parser.c | 447 ++++++++++++++++ lib/md5.c | 15 - lib/sha1.c | 13 - lib/tpm-v1.c | 2 +- test/Kconfig | 2 +- 53 files changed, 2837 insertions(+), 236 deletions(-) create mode 100644 include/limits.h create mode 100644 lib/crypto/pkcs7_helper.c create mode 100644 lib/crypto/public_key_helper.c create mode 100644 lib/crypto/x509_helper.c create mode 100644 lib/mbedtls/Kconfig create mode 100644 lib/mbedtls/Makefile create mode 100644 lib/mbedtls/mbedtls_def_config.h create mode 100644 lib/mbedtls/md5.c create mode 100644 lib/mbedtls/mscode_parser.c create mode 100644 lib/mbedtls/pkcs7_parser.c create mode 100644 lib/mbedtls/port/assert.h create mode 100644 lib/mbedtls/public_key.c create mode 100644 lib/mbedtls/rsa_helper.c create mode 100644 lib/mbedtls/sha1.c create mode 100644 lib/mbedtls/sha256.c create mode 100644 lib/mbedtls/sha512.c create mode 100644 lib/mbedtls/x509_cert_parser.c

Since MbedTLS is an external repo with its own coding style, exclude it from Azure and gitlab CI CONFIG checks.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Tom Rini trini@konsulko.com Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v2 - Initial patch. Changes in v3 - None. Changes in v4 - None. Changes in v5 - None.
.azure-pipelines.yml | 3 ++- .gitlab-ci.yml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml index c43bb51066a..339f9596b28 100644 --- a/.azure-pipelines.yml +++ b/.azure-pipelines.yml @@ -76,7 +76,8 @@ stages: # have no matches. - script: git grep -E '^#[[:blank:]]*(define|undef)[[:blank:]]*CONFIG_' :^doc/ :^arch/arm/dts/ :^scripts/kconfig/lkc.h - :^include/linux/kconfig.h :^tools/ :^dts/upstream/ && + :^include/linux/kconfig.h :^tools/ :^dts/upstream/ + :^lib/mbedtls/external :^lib/mbedtls/mbedtls_def_config.h && exit 1 || exit 0
- job: docs diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 165f765a833..a8f7f1940f3 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -156,7 +156,8 @@ check for new CONFIG symbols outside Kconfig: # have no matches. - git grep -E '^#[[:blank:]]*(define|undef)[[:blank:]]*CONFIG_' :^doc/ :^arch/arm/dts/ :^scripts/kconfig/lkc.h - :^include/linux/kconfig.h :^tools/ :^dts/upstream/ && + :^include/linux/kconfig.h :^tools/ :^dts/upstream/ + :^lib/mbedtls/external :^lib/mbedtls/mbedtls_def_config.h && exit 1 || exit 0
# build documentation

Port mbedtls with adapted libc header files. Add mbedtls default config header file. Optimize mbedtls default config by disabling unused features to reduce the target size. Add mbedtls kbuild makefile. Add Kconfig skeleton and config submenu entry for selecting crypto libraries between mbedtls and legacy ones. Add the mbedtls include directories into the build system.
Subsequent patches will separate those Kconfigs into pairs of _LEGACY and _MBEDTLS for controlling the implementations of legacy crypto libraries and MbedTLS ones respectively.
The motivation of moving and adapting *INT* macros from kernel.h to limits.h is to fullfill the MbedTLS building requirement. The conditional compilation statements in MbedTLS expects the *INT* macros as constant expressions, thus expressions like `((int)(~0U >> 1))` will not work.
Prerequisite ------------
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via:
$ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash
Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually:
$ git add --renormalize . $ git commit
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Disabled unused MbedTLS features to optimize the target size. Changes in v3 - Removed changes in stdio.h. Changes in v4 - Move limits.h as a common header file that is included by kernel.h. - Refactor the Kconfig to support legacy and MbedTLS options for each algorithm. - Refactor MbedTLS makefile and default config file to remove unused config options and objects. Changes in v5 - Merged patch #9 of v4 into this patch. - Removed unused config MBEDTLS_LIB_TLS. - Refactored MbedTLS Makefile and default config file.
Makefile | 6 +++ include/limits.h | 29 ++++++++++++++ include/linux/kernel.h | 13 +----- include/stdlib.h | 1 + lib/Kconfig | 4 ++ lib/Makefile | 2 + lib/mbedtls/Kconfig | 47 ++++++++++++++++++++++ lib/mbedtls/Makefile | 41 +++++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 69 ++++++++++++++++++++++++++++++++ lib/mbedtls/port/assert.h | 12 ++++++ 10 files changed, 212 insertions(+), 12 deletions(-) create mode 100644 include/limits.h create mode 100644 lib/mbedtls/Kconfig create mode 100644 lib/mbedtls/Makefile create mode 100644 lib/mbedtls/mbedtls_def_config.h create mode 100644 lib/mbedtls/port/assert.h
diff --git a/Makefile b/Makefile index 07d7947c8af..fd855dbd5c9 100644 --- a/Makefile +++ b/Makefile @@ -829,6 +829,12 @@ KBUILD_HOSTCFLAGS += $(if $(CONFIG_TOOLS_DEBUG),-g) UBOOTINCLUDE := \ -Iinclude \ $(if $(KBUILD_SRC), -I$(srctree)/include) \ + $(if $(CONFIG_MBEDTLS_LIB), \ + "-DMBEDTLS_CONFIG_FILE="mbedtls_def_config.h"" \ + -I$(srctree)/lib/mbedtls \ + -I$(srctree)/lib/mbedtls/port \ + -I$(srctree)/lib/mbedtls/external/mbedtls \ + -I$(srctree)/lib/mbedtls/external/mbedtls/include) \ $(if $(CONFIG_$(SPL_)SYS_THUMB_BUILD), \ $(if $(CONFIG_HAS_THUMB2), \ $(if $(CONFIG_CPU_V7M), \ diff --git a/include/limits.h b/include/limits.h new file mode 100644 index 00000000000..cc691d15650 --- /dev/null +++ b/include/limits.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Copyright (c) 2023 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#ifndef _LIMITS_H +#define _LIMITS_H + +#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffUL +#define CHAR_BIT 8 +#define UINT32_MAX 0xffffffffUL +#define UINT64_MAX 0xffffffffffffffffUL + +#ifdef CONFIG_64BIT + #define UINTPTR_MAX UINT64_MAX +#else + #define UINTPTR_MAX UINT32_MAX +#endif + +#ifndef SIZE_MAX +#define SIZE_MAX UINTPTR_MAX +#endif +#ifndef SSIZE_MAX +#define SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1)) +#endif + +#endif /* _LIMITS_H */ diff --git a/include/linux/kernel.h b/include/linux/kernel.h index 5cd6c9dc821..2cb2ceaf84b 100644 --- a/include/linux/kernel.h +++ b/include/linux/kernel.h @@ -3,25 +3,18 @@
#include <linux/types.h> #include <linux/printk.h> /* for printf/pr_* utilities */ +#include <limits.h>
#define USHRT_MAX ((u16)(~0U)) #define SHRT_MAX ((s16)(USHRT_MAX>>1)) #define SHRT_MIN ((s16)(-SHRT_MAX - 1)) -#define INT_MAX ((int)(~0U>>1)) #define INT_MIN (-INT_MAX - 1) -#define UINT_MAX (~0U) #define LONG_MAX ((long)(~0UL>>1)) #define LONG_MIN (-LONG_MAX - 1) #define ULONG_MAX (~0UL) #define LLONG_MAX ((long long)(~0ULL>>1)) #define LLONG_MIN (-LLONG_MAX - 1) #define ULLONG_MAX (~0ULL) -#ifndef SIZE_MAX -#define SIZE_MAX (~(size_t)0) -#endif -#ifndef SSIZE_MAX -#define SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1)) -#endif
#define U8_MAX ((u8)~0U) #define S8_MAX ((s8)(U8_MAX>>1)) @@ -36,10 +29,6 @@ #define S64_MAX ((s64)(U64_MAX>>1)) #define S64_MIN ((s64)(-S64_MAX - 1))
-/* Aliases defined by stdint.h */ -#define UINT32_MAX U32_MAX -#define UINT64_MAX U64_MAX - #define INT32_MAX S32_MAX
#define STACK_MAGIC 0xdeadbeef diff --git a/include/stdlib.h b/include/stdlib.h index 9c175d4d74c..dedfd52a144 100644 --- a/include/stdlib.h +++ b/include/stdlib.h @@ -7,5 +7,6 @@ #define __STDLIB_H_
#include <malloc.h> +#include <rand.h>
#endif /* __STDLIB_H_ */ diff --git a/lib/Kconfig b/lib/Kconfig index b3baa4b85b0..129063ca8a5 100644 --- a/lib/Kconfig +++ b/lib/Kconfig @@ -418,6 +418,10 @@ config CIRCBUF
source "lib/dhry/Kconfig"
+menu "Alternative crypto libraries" +source lib/mbedtls/Kconfig +endmenu + menu "Security support"
config AES diff --git a/lib/Makefile b/lib/Makefile index e389ad014f8..499d174199f 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -96,6 +96,8 @@ obj-$(CONFIG_LIBAVB) += libavb/ obj-$(CONFIG_$(SPL_TPL_)OF_LIBFDT) += libfdt/ obj-$(CONFIG_$(SPL_TPL_)OF_REAL) += fdtdec_common.o fdtdec.o
+obj-$(CONFIG_MBEDTLS_LIB) += mbedtls/ + ifdef CONFIG_SPL_BUILD obj-$(CONFIG_SPL_YMODEM_SUPPORT) += crc16-ccitt.o obj-$(CONFIG_$(SPL_TPL_)HASH) += crc16-ccitt.o diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig new file mode 100644 index 00000000000..3e9057f1acf --- /dev/null +++ b/lib/mbedtls/Kconfig @@ -0,0 +1,47 @@ +choice + prompt "Select crypto libraries" + default LEGACY_CRYPTO + help + Select crypto libraries. + LEGACY_CRYPTO for legacy crypto libraries, + MBEDTLS_LIB for MbedTLS libraries. + +config LEGACY_CRYPTO + bool "legacy crypto libraries" + select LEGACY_CRYPTO_BASIC + select LEGACY_CRYPTO_CERT + +config MBEDTLS_LIB + bool "MbedTLS libraries" + select MBEDTLS_LIB_CRYPTO + select MBEDTLS_LIB_X509 +endchoice + +if LEGACY_CRYPTO + +config LEGACY_CRYPTO_BASIC + bool "legacy basic crypto libraries" + help + Enable legacy basic crypto libraries. + +config LEGACY_CRYPTO_CERT + bool "legacy certificate libraries" + help + Enable legacy certificate libraries. + +endif # LEGACY_CRYPTO + +if MBEDTLS_LIB + +config MBEDTLS_LIB_CRYPTO + bool "MbedTLS crypto libraries" + help + Enable MbedTLS crypto libraries. + + +config MBEDTLS_LIB_X509 + bool "MbedTLS certificate libraries" + help + Enable MbedTLS certificate libraries. + +endif # MBEDTLS_LIB diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile new file mode 100644 index 00000000000..e98241b46ab --- /dev/null +++ b/lib/mbedtls/Makefile @@ -0,0 +1,41 @@ +# SPDX-License-Identifier: GPL-2.0+ +# +# Copyright (c) 2024 Linaro Limited +# Author: Raymond Mao raymond.mao@linaro.org + +MBEDTLS_LIB_DIR = external/mbedtls/library + +# MbedTLS crypto library +obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o +mbedtls_lib_crypto-y := \ + $(MBEDTLS_LIB_DIR)/platform_util.o \ + $(MBEDTLS_LIB_DIR)/constant_time.o \ + $(MBEDTLS_LIB_DIR)/md.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)MD5) += $(MBEDTLS_LIB_DIR)/md5.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA1) += $(MBEDTLS_LIB_DIR)/sha1.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA256) += \ + $(MBEDTLS_LIB_DIR)/sha256.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA512) += \ + $(MBEDTLS_LIB_DIR)/sha512.o + +# MbedTLS X509 library +obj-$(CONFIG_MBEDTLS_LIB_X509) += mbedtls_lib_x509.o +mbedtls_lib_x509-y := $(MBEDTLS_LIB_DIR)/x509.o +mbedtls_lib_x509-$(CONFIG_$(SPL_)ASN1_DECODER) += \ + $(MBEDTLS_LIB_DIR)/asn1parse.o \ + $(MBEDTLS_LIB_DIR)/asn1write.o \ + $(MBEDTLS_LIB_DIR)/oid.o +mbedtls_lib_x509-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER) += \ + $(MBEDTLS_LIB_DIR)/bignum.o \ + $(MBEDTLS_LIB_DIR)/bignum_core.o \ + $(MBEDTLS_LIB_DIR)/rsa.o \ + $(MBEDTLS_LIB_DIR)/rsa_alt_helpers.o +mbedtls_lib_x509-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += \ + $(MBEDTLS_LIB_DIR)/pk.o \ + $(MBEDTLS_LIB_DIR)/pk_wrap.o \ + $(MBEDTLS_LIB_DIR)/pkparse.o +mbedtls_lib_x509-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER) += \ + $(MBEDTLS_LIB_DIR)/x509_crl.o \ + $(MBEDTLS_LIB_DIR)/x509_crt.o +mbedtls_lib_x509-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER) += \ + $(MBEDTLS_LIB_DIR)/pkcs7.o diff --git a/lib/mbedtls/mbedtls_def_config.h b/lib/mbedtls/mbedtls_def_config.h new file mode 100644 index 00000000000..38de6b0b9af --- /dev/null +++ b/lib/mbedtls/mbedtls_def_config.h @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * MbedTLS config file + * + * Derived from the MbedTLS internal config file, + * for more information about each build option, + * please refer to: + * external/mbedtls/include/mbedtls/mbedtls_config.h + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO) + +#define MBEDTLS_MD_C + +#if CONFIG_IS_ENABLED(MD5) +#define MBEDTLS_MD5_C +#endif + +#if CONFIG_IS_ENABLED(SHA1) +#define MBEDTLS_SHA1_C +#endif + +#if CONFIG_IS_ENABLED(SHA256) +#define MBEDTLS_SHA256_C +#endif + +#if CONFIG_IS_ENABLED(SHA384) +#define MBEDTLS_SHA384_C +#endif + +#if CONFIG_IS_ENABLED(SHA512) +#define MBEDTLS_SHA512_C +#endif + +#endif /* CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO) */ + +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) + +#if CONFIG_IS_ENABLED(X509_CERTIFICATE_PARSER) +#define MBEDTLS_PKCS1_V15 +#define MBEDTLS_X509_USE_C +#define MBEDTLS_X509_CRT_PARSE_C +#define MBEDTLS_X509_CRL_PARSE_C +#endif + +#if CONFIG_IS_ENABLED(ASYMMETRIC_PUBLIC_KEY_SUBTYPE) +#define MBEDTLS_PK_C +#define MBEDTLS_PK_PARSE_C +#endif + +#if CONFIG_IS_ENABLED(RSA_PUBLIC_KEY_PARSER) +#define MBEDTLS_BIGNUM_C +#define MBEDTLS_RSA_C +#endif + +#if CONFIG_IS_ENABLED(PKCS7_MESSAGE_PARSER) +#define MBEDTLS_PKCS7_C +#endif + +#if CONFIG_IS_ENABLED(ASN1_DECODER) +#define MBEDTLS_OID_C +#define MBEDTLS_ASN1_PARSE_C +#define MBEDTLS_ASN1_WRITE_C +#endif + +#endif /* CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) */ diff --git a/lib/mbedtls/port/assert.h b/lib/mbedtls/port/assert.h new file mode 100644 index 00000000000..490701aa9d0 --- /dev/null +++ b/lib/mbedtls/port/assert.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Dummy file to allow mbedtls linked with U-Boot to include assert.h + * + * Copyright (c) 2023 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#ifndef _MBEDTLS_ASSERT_H +#define _MBEDTLS_ASSERT_H + +#endif /* _MBEDTLS_ASSERT_H */

Hi Raymond,
On Wed, 31 Jul 2024 at 20:27, Raymond Mao raymond.mao@linaro.org wrote:
Port mbedtls with adapted libc header files. Add mbedtls default config header file. Optimize mbedtls default config by disabling unused features to reduce the target size. Add mbedtls kbuild makefile. Add Kconfig skeleton and config submenu entry for selecting crypto libraries between mbedtls and legacy ones. Add the mbedtls include directories into the build system.
Subsequent patches will separate those Kconfigs into pairs of _LEGACY and _MBEDTLS for controlling the implementations of legacy crypto libraries and MbedTLS ones respectively.
The motivation of moving and adapting *INT* macros from kernel.h to limits.h is to fullfill the MbedTLS building requirement. The conditional compilation statements in MbedTLS expects the *INT* macros as constant expressions, thus expressions like `((int)(~0U >> 1))` will not work.
Prerequisite
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via:
$ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash
Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually:
$ git add --renormalize . $ git commit
Signed-off-by: Raymond Mao raymond.mao@linaro.org
Changes in v2
- Disabled unused MbedTLS features to optimize the target size.
Changes in v3
- Removed changes in stdio.h.
Changes in v4
- Move limits.h as a common header file that is included by kernel.h.
- Refactor the Kconfig to support legacy and MbedTLS options for each algorithm.
- Refactor MbedTLS makefile and default config file to remove unused config options and objects.
Changes in v5
- Merged patch #9 of v4 into this patch.
- Removed unused config MBEDTLS_LIB_TLS.
- Refactored MbedTLS Makefile and default config file.
Makefile | 6 +++ include/limits.h | 29 ++++++++++++++ include/linux/kernel.h | 13 +----- include/stdlib.h | 1 + lib/Kconfig | 4 ++ lib/Makefile | 2 + lib/mbedtls/Kconfig | 47 ++++++++++++++++++++++ lib/mbedtls/Makefile | 41 +++++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 69 ++++++++++++++++++++++++++++++++ lib/mbedtls/port/assert.h | 12 ++++++ 10 files changed, 212 insertions(+), 12 deletions(-) create mode 100644 include/limits.h create mode 100644 lib/mbedtls/Kconfig create mode 100644 lib/mbedtls/Makefile create mode 100644 lib/mbedtls/mbedtls_def_config.h create mode 100644 lib/mbedtls/port/assert.h
diff --git a/Makefile b/Makefile index 07d7947c8af..fd855dbd5c9 100644 --- a/Makefile +++ b/Makefile @@ -829,6 +829,12 @@ KBUILD_HOSTCFLAGS += $(if $(CONFIG_TOOLS_DEBUG),-g) UBOOTINCLUDE := \ -Iinclude \ $(if $(KBUILD_SRC), -I$(srctree)/include) \
$(if $(CONFIG_MBEDTLS_LIB), \
"-DMBEDTLS_CONFIG_FILE=\"mbedtls_def_config.h\"" \
-I$(srctree)/lib/mbedtls \
-I$(srctree)/lib/mbedtls/port \
-I$(srctree)/lib/mbedtls/external/mbedtls \
-I$(srctree)/lib/mbedtls/external/mbedtls/include) \ $(if $(CONFIG_$(SPL_)SYS_THUMB_BUILD), \ $(if $(CONFIG_HAS_THUMB2), \ $(if $(CONFIG_CPU_V7M), \
diff --git a/include/limits.h b/include/limits.h new file mode 100644 index 00000000000..cc691d15650 --- /dev/null +++ b/include/limits.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/*
- Copyright (c) 2023 Linaro Limited
- Author: Raymond Mao raymond.mao@linaro.org
- */
+#ifndef _LIMITS_H +#define _LIMITS_H
+#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffUL +#define CHAR_BIT 8 +#define UINT32_MAX 0xffffffffUL +#define UINT64_MAX 0xffffffffffffffffUL
Some of these seem wrong e.g UINT64_MAX should be ULL, etc Can you keep the original definitions?
Also, there's no copyright on this file, values where moved from one file to another, you should just preserve the original one.
Thanks /Ilias
+#ifdef CONFIG_64BIT
- #define UINTPTR_MAX UINT64_MAX
+#else
- #define UINTPTR_MAX UINT32_MAX
+#endif
+#ifndef SIZE_MAX +#define SIZE_MAX UINTPTR_MAX +#endif +#ifndef SSIZE_MAX +#define SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1)) +#endif
+#endif /* _LIMITS_H */ diff --git a/include/linux/kernel.h b/include/linux/kernel.h index 5cd6c9dc821..2cb2ceaf84b 100644 --- a/include/linux/kernel.h +++ b/include/linux/kernel.h @@ -3,25 +3,18 @@
#include <linux/types.h> #include <linux/printk.h> /* for printf/pr_* utilities */ +#include <limits.h>
#define USHRT_MAX ((u16)(~0U)) #define SHRT_MAX ((s16)(USHRT_MAX>>1)) #define SHRT_MIN ((s16)(-SHRT_MAX - 1)) -#define INT_MAX ((int)(~0U>>1)) #define INT_MIN (-INT_MAX - 1) -#define UINT_MAX (~0U) #define LONG_MAX ((long)(~0UL>>1)) #define LONG_MIN (-LONG_MAX - 1) #define ULONG_MAX (~0UL) #define LLONG_MAX ((long long)(~0ULL>>1)) #define LLONG_MIN (-LLONG_MAX - 1) #define ULLONG_MAX (~0ULL) -#ifndef SIZE_MAX -#define SIZE_MAX (~(size_t)0) -#endif -#ifndef SSIZE_MAX -#define SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1)) -#endif
#define U8_MAX ((u8)~0U) #define S8_MAX ((s8)(U8_MAX>>1)) @@ -36,10 +29,6 @@ #define S64_MAX ((s64)(U64_MAX>>1)) #define S64_MIN ((s64)(-S64_MAX - 1))
-/* Aliases defined by stdint.h */ -#define UINT32_MAX U32_MAX -#define UINT64_MAX U64_MAX
#define INT32_MAX S32_MAX
#define STACK_MAGIC 0xdeadbeef diff --git a/include/stdlib.h b/include/stdlib.h index 9c175d4d74c..dedfd52a144 100644 --- a/include/stdlib.h +++ b/include/stdlib.h @@ -7,5 +7,6 @@ #define __STDLIB_H_
#include <malloc.h> +#include <rand.h>
#endif /* __STDLIB_H_ */ diff --git a/lib/Kconfig b/lib/Kconfig index b3baa4b85b0..129063ca8a5 100644 --- a/lib/Kconfig +++ b/lib/Kconfig @@ -418,6 +418,10 @@ config CIRCBUF
source "lib/dhry/Kconfig"
+menu "Alternative crypto libraries" +source lib/mbedtls/Kconfig +endmenu
menu "Security support"
config AES diff --git a/lib/Makefile b/lib/Makefile index e389ad014f8..499d174199f 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -96,6 +96,8 @@ obj-$(CONFIG_LIBAVB) += libavb/ obj-$(CONFIG_$(SPL_TPL_)OF_LIBFDT) += libfdt/ obj-$(CONFIG_$(SPL_TPL_)OF_REAL) += fdtdec_common.o fdtdec.o
+obj-$(CONFIG_MBEDTLS_LIB) += mbedtls/
ifdef CONFIG_SPL_BUILD obj-$(CONFIG_SPL_YMODEM_SUPPORT) += crc16-ccitt.o obj-$(CONFIG_$(SPL_TPL_)HASH) += crc16-ccitt.o diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig new file mode 100644 index 00000000000..3e9057f1acf --- /dev/null +++ b/lib/mbedtls/Kconfig @@ -0,0 +1,47 @@ +choice
prompt "Select crypto libraries"
default LEGACY_CRYPTO
help
Select crypto libraries.
LEGACY_CRYPTO for legacy crypto libraries,
MBEDTLS_LIB for MbedTLS libraries.
+config LEGACY_CRYPTO
bool "legacy crypto libraries"
select LEGACY_CRYPTO_BASIC
select LEGACY_CRYPTO_CERT
+config MBEDTLS_LIB
bool "MbedTLS libraries"
select MBEDTLS_LIB_CRYPTO
select MBEDTLS_LIB_X509
+endchoice
+if LEGACY_CRYPTO
+config LEGACY_CRYPTO_BASIC
bool "legacy basic crypto libraries"
help
Enable legacy basic crypto libraries.
+config LEGACY_CRYPTO_CERT
bool "legacy certificate libraries"
help
Enable legacy certificate libraries.
+endif # LEGACY_CRYPTO
+if MBEDTLS_LIB
+config MBEDTLS_LIB_CRYPTO
bool "MbedTLS crypto libraries"
help
Enable MbedTLS crypto libraries.
+config MBEDTLS_LIB_X509
bool "MbedTLS certificate libraries"
help
Enable MbedTLS certificate libraries.
+endif # MBEDTLS_LIB diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile new file mode 100644 index 00000000000..e98241b46ab --- /dev/null +++ b/lib/mbedtls/Makefile @@ -0,0 +1,41 @@ +# SPDX-License-Identifier: GPL-2.0+ +# +# Copyright (c) 2024 Linaro Limited +# Author: Raymond Mao raymond.mao@linaro.org
+MBEDTLS_LIB_DIR = external/mbedtls/library
+# MbedTLS crypto library +obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o +mbedtls_lib_crypto-y := \
$(MBEDTLS_LIB_DIR)/platform_util.o \
$(MBEDTLS_LIB_DIR)/constant_time.o \
$(MBEDTLS_LIB_DIR)/md.o
+mbedtls_lib_crypto-$(CONFIG_$(SPL_)MD5) += $(MBEDTLS_LIB_DIR)/md5.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA1) += $(MBEDTLS_LIB_DIR)/sha1.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA256) += \
$(MBEDTLS_LIB_DIR)/sha256.o
+mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA512) += \
$(MBEDTLS_LIB_DIR)/sha512.o
+# MbedTLS X509 library +obj-$(CONFIG_MBEDTLS_LIB_X509) += mbedtls_lib_x509.o +mbedtls_lib_x509-y := $(MBEDTLS_LIB_DIR)/x509.o +mbedtls_lib_x509-$(CONFIG_$(SPL_)ASN1_DECODER) += \
$(MBEDTLS_LIB_DIR)/asn1parse.o \
$(MBEDTLS_LIB_DIR)/asn1write.o \
$(MBEDTLS_LIB_DIR)/oid.o
+mbedtls_lib_x509-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER) += \
$(MBEDTLS_LIB_DIR)/bignum.o \
$(MBEDTLS_LIB_DIR)/bignum_core.o \
$(MBEDTLS_LIB_DIR)/rsa.o \
$(MBEDTLS_LIB_DIR)/rsa_alt_helpers.o
+mbedtls_lib_x509-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += \
$(MBEDTLS_LIB_DIR)/pk.o \
$(MBEDTLS_LIB_DIR)/pk_wrap.o \
$(MBEDTLS_LIB_DIR)/pkparse.o
+mbedtls_lib_x509-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER) += \
$(MBEDTLS_LIB_DIR)/x509_crl.o \
$(MBEDTLS_LIB_DIR)/x509_crt.o
+mbedtls_lib_x509-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER) += \
$(MBEDTLS_LIB_DIR)/pkcs7.o
diff --git a/lib/mbedtls/mbedtls_def_config.h b/lib/mbedtls/mbedtls_def_config.h new file mode 100644 index 00000000000..38de6b0b9af --- /dev/null +++ b/lib/mbedtls/mbedtls_def_config.h @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/*
- MbedTLS config file
- Derived from the MbedTLS internal config file,
- for more information about each build option,
- please refer to:
- external/mbedtls/include/mbedtls/mbedtls_config.h
- Copyright (c) 2024 Linaro Limited
- Author: Raymond Mao raymond.mao@linaro.org
- */
+#if CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO)
+#define MBEDTLS_MD_C
+#if CONFIG_IS_ENABLED(MD5) +#define MBEDTLS_MD5_C +#endif
+#if CONFIG_IS_ENABLED(SHA1) +#define MBEDTLS_SHA1_C +#endif
+#if CONFIG_IS_ENABLED(SHA256) +#define MBEDTLS_SHA256_C +#endif
+#if CONFIG_IS_ENABLED(SHA384) +#define MBEDTLS_SHA384_C +#endif
+#if CONFIG_IS_ENABLED(SHA512) +#define MBEDTLS_SHA512_C +#endif
+#endif /* CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO) */
+#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
+#if CONFIG_IS_ENABLED(X509_CERTIFICATE_PARSER) +#define MBEDTLS_PKCS1_V15 +#define MBEDTLS_X509_USE_C +#define MBEDTLS_X509_CRT_PARSE_C +#define MBEDTLS_X509_CRL_PARSE_C +#endif
+#if CONFIG_IS_ENABLED(ASYMMETRIC_PUBLIC_KEY_SUBTYPE) +#define MBEDTLS_PK_C +#define MBEDTLS_PK_PARSE_C +#endif
+#if CONFIG_IS_ENABLED(RSA_PUBLIC_KEY_PARSER) +#define MBEDTLS_BIGNUM_C +#define MBEDTLS_RSA_C +#endif
+#if CONFIG_IS_ENABLED(PKCS7_MESSAGE_PARSER) +#define MBEDTLS_PKCS7_C +#endif
+#if CONFIG_IS_ENABLED(ASN1_DECODER) +#define MBEDTLS_OID_C +#define MBEDTLS_ASN1_PARSE_C +#define MBEDTLS_ASN1_WRITE_C +#endif
+#endif /* CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) */ diff --git a/lib/mbedtls/port/assert.h b/lib/mbedtls/port/assert.h new file mode 100644 index 00000000000..490701aa9d0 --- /dev/null +++ b/lib/mbedtls/port/assert.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/*
- Dummy file to allow mbedtls linked with U-Boot to include assert.h
- Copyright (c) 2023 Linaro Limited
- Author: Raymond Mao raymond.mao@linaro.org
- */
+#ifndef _MBEDTLS_ASSERT_H +#define _MBEDTLS_ASSERT_H
+#endif /* _MBEDTLS_ASSERT_H */
2.25.1

Hi Ilias,
On Wed, 14 Aug 2024 at 08:08, Ilias Apalodimas ilias.apalodimas@linaro.org wrote:
Hi Raymond,
On Wed, 31 Jul 2024 at 20:27, Raymond Mao raymond.mao@linaro.org wrote:
Port mbedtls with adapted libc header files. Add mbedtls default config header file. Optimize mbedtls default config by disabling unused features to reduce the target size. Add mbedtls kbuild makefile. Add Kconfig skeleton and config submenu entry for selecting crypto libraries between mbedtls and legacy ones. Add the mbedtls include directories into the build system.
Subsequent patches will separate those Kconfigs into pairs of _LEGACY and _MBEDTLS for controlling the implementations of legacy crypto libraries and MbedTLS ones respectively.
The motivation of moving and adapting *INT* macros from kernel.h to limits.h is to fullfill the MbedTLS building requirement. The conditional compilation statements in MbedTLS expects the *INT* macros as constant expressions, thus expressions like `((int)(~0U >> 1))` will not work.
Prerequisite
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via:
$ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash
Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually:
$ git add --renormalize . $ git commit
Signed-off-by: Raymond Mao raymond.mao@linaro.org
Changes in v2
- Disabled unused MbedTLS features to optimize the target size.
Changes in v3
- Removed changes in stdio.h.
Changes in v4
- Move limits.h as a common header file that is included by kernel.h.
- Refactor the Kconfig to support legacy and MbedTLS options for each algorithm.
- Refactor MbedTLS makefile and default config file to remove unused config options and objects.
Changes in v5
- Merged patch #9 of v4 into this patch.
- Removed unused config MBEDTLS_LIB_TLS.
- Refactored MbedTLS Makefile and default config file.
Makefile | 6 +++ include/limits.h | 29 ++++++++++++++ include/linux/kernel.h | 13 +----- include/stdlib.h | 1 + lib/Kconfig | 4 ++ lib/Makefile | 2 + lib/mbedtls/Kconfig | 47 ++++++++++++++++++++++ lib/mbedtls/Makefile | 41 +++++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 69 ++++++++++++++++++++++++++++++++ lib/mbedtls/port/assert.h | 12 ++++++ 10 files changed, 212 insertions(+), 12 deletions(-) create mode 100644 include/limits.h create mode 100644 lib/mbedtls/Kconfig create mode 100644 lib/mbedtls/Makefile create mode 100644 lib/mbedtls/mbedtls_def_config.h create mode 100644 lib/mbedtls/port/assert.h
diff --git a/Makefile b/Makefile index 07d7947c8af..fd855dbd5c9 100644 --- a/Makefile +++ b/Makefile @@ -829,6 +829,12 @@ KBUILD_HOSTCFLAGS += $(if $(CONFIG_TOOLS_DEBUG),-g) UBOOTINCLUDE := \ -Iinclude \ $(if $(KBUILD_SRC), -I$(srctree)/include) \
$(if $(CONFIG_MBEDTLS_LIB), \
"-DMBEDTLS_CONFIG_FILE=\"mbedtls_def_config.h\"" \
-I$(srctree)/lib/mbedtls \
-I$(srctree)/lib/mbedtls/port \
-I$(srctree)/lib/mbedtls/external/mbedtls \
-I$(srctree)/lib/mbedtls/external/mbedtls/include) \ $(if $(CONFIG_$(SPL_)SYS_THUMB_BUILD), \ $(if $(CONFIG_HAS_THUMB2), \ $(if $(CONFIG_CPU_V7M), \
diff --git a/include/limits.h b/include/limits.h new file mode 100644 index 00000000000..cc691d15650 --- /dev/null +++ b/include/limits.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/*
- Copyright (c) 2023 Linaro Limited
- Author: Raymond Mao raymond.mao@linaro.org
- */
+#ifndef _LIMITS_H +#define _LIMITS_H
+#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffUL +#define CHAR_BIT 8 +#define UINT32_MAX 0xffffffffUL +#define UINT64_MAX 0xffffffffffffffffUL
Some of these seem wrong e.g UINT64_MAX should be ULL, etc Can you keep the original definitions?
The original definitions cannot work with building MbedTLS.
As I stated in the commit message: ``` The conditional compilation statements in MbedTLS expects the *INT* macros as constant expressions, thus expressions like `((int)(~0U >> 1))` will not work. ``` [snip]
Raymond

On Wed, 14 Aug 2024 at 16:22, Raymond Mao raymond.mao@linaro.org wrote:
Hi Ilias,
On Wed, 14 Aug 2024 at 08:08, Ilias Apalodimas ilias.apalodimas@linaro.org wrote:
Hi Raymond,
On Wed, 31 Jul 2024 at 20:27, Raymond Mao raymond.mao@linaro.org wrote:
Port mbedtls with adapted libc header files. Add mbedtls default config header file. Optimize mbedtls default config by disabling unused features to reduce the target size. Add mbedtls kbuild makefile. Add Kconfig skeleton and config submenu entry for selecting crypto libraries between mbedtls and legacy ones. Add the mbedtls include directories into the build system.
Subsequent patches will separate those Kconfigs into pairs of _LEGACY and _MBEDTLS for controlling the implementations of legacy crypto libraries and MbedTLS ones respectively.
The motivation of moving and adapting *INT* macros from kernel.h to limits.h is to fullfill the MbedTLS building requirement. The conditional compilation statements in MbedTLS expects the *INT* macros as constant expressions, thus expressions like `((int)(~0U >> 1))` will not work.
Prerequisite
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via:
$ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash
Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually:
$ git add --renormalize . $ git commit
Signed-off-by: Raymond Mao raymond.mao@linaro.org
Changes in v2
- Disabled unused MbedTLS features to optimize the target size.
Changes in v3
- Removed changes in stdio.h.
Changes in v4
- Move limits.h as a common header file that is included by kernel.h.
- Refactor the Kconfig to support legacy and MbedTLS options for each algorithm.
- Refactor MbedTLS makefile and default config file to remove unused config options and objects.
Changes in v5
- Merged patch #9 of v4 into this patch.
- Removed unused config MBEDTLS_LIB_TLS.
- Refactored MbedTLS Makefile and default config file.
Makefile | 6 +++ include/limits.h | 29 ++++++++++++++ include/linux/kernel.h | 13 +----- include/stdlib.h | 1 + lib/Kconfig | 4 ++ lib/Makefile | 2 + lib/mbedtls/Kconfig | 47 ++++++++++++++++++++++ lib/mbedtls/Makefile | 41 +++++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 69 ++++++++++++++++++++++++++++++++ lib/mbedtls/port/assert.h | 12 ++++++ 10 files changed, 212 insertions(+), 12 deletions(-) create mode 100644 include/limits.h create mode 100644 lib/mbedtls/Kconfig create mode 100644 lib/mbedtls/Makefile create mode 100644 lib/mbedtls/mbedtls_def_config.h create mode 100644 lib/mbedtls/port/assert.h
diff --git a/Makefile b/Makefile index 07d7947c8af..fd855dbd5c9 100644 --- a/Makefile +++ b/Makefile @@ -829,6 +829,12 @@ KBUILD_HOSTCFLAGS += $(if $(CONFIG_TOOLS_DEBUG),-g) UBOOTINCLUDE := \ -Iinclude \ $(if $(KBUILD_SRC), -I$(srctree)/include) \
$(if $(CONFIG_MBEDTLS_LIB), \
"-DMBEDTLS_CONFIG_FILE=\"mbedtls_def_config.h\"" \
-I$(srctree)/lib/mbedtls \
-I$(srctree)/lib/mbedtls/port \
-I$(srctree)/lib/mbedtls/external/mbedtls \
-I$(srctree)/lib/mbedtls/external/mbedtls/include) \ $(if $(CONFIG_$(SPL_)SYS_THUMB_BUILD), \ $(if $(CONFIG_HAS_THUMB2), \ $(if $(CONFIG_CPU_V7M), \
diff --git a/include/limits.h b/include/limits.h new file mode 100644 index 00000000000..cc691d15650 --- /dev/null +++ b/include/limits.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/*
- Copyright (c) 2023 Linaro Limited
- Author: Raymond Mao raymond.mao@linaro.org
- */
+#ifndef _LIMITS_H +#define _LIMITS_H
+#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffUL +#define CHAR_BIT 8 +#define UINT32_MAX 0xffffffffUL +#define UINT64_MAX 0xffffffffffffffffUL
Some of these seem wrong e.g UINT64_MAX should be ULL, etc Can you keep the original definitions?
The original definitions cannot work with building MbedTLS. As I stated in the commit message:
The conditional compilation statements in MbedTLS expects the *INT* macros as constant expressions, thus expressions like `((int)(~0U >> 1))` will not work.
Ah that's ok, fix the UL etc and keep it as is
[snip] Raymond

Adapt digest header files to support both original libs and MbedTLS by switching on/off MBEDTLS_LIB_CRYPTO. Introduce <alg>_LEGACY kconfig for legacy hash implementations.
FIXME: `IS_ENABLED` or `CONFIG_IS_ENABLED` is not applicable here, since including <linux/kconfig.h> causes undefined reference on schedule() with sandbox build. As <linux/kconfig.h> includes <generated/autoconf.h> which enables `CONFIG_HW_WATCHDOG` and `CONFIG_WATCHDOG` but no schedule() are defined in sandbox build. `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` is a workaround.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Initial patch. Changes in v3 - Remove the changes that were done in previous clean-up patch set. Changes in v4 - Introduce <alg>_LEGACY kconfig for legacy hash implementations. Changes in v5 - Correct header file include directories. - Correct kconfig dependence.
include/u-boot/md5.h | 7 ++++ include/u-boot/sha1.h | 21 +++++++++- include/u-boot/sha256.h | 20 +++++++++ include/u-boot/sha512.h | 22 ++++++++-- lib/Makefile | 10 +++-- lib/mbedtls/Kconfig | 91 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+), 8 deletions(-)
diff --git a/include/u-boot/md5.h b/include/u-boot/md5.h index c465925ea8d..69898fcbe49 100644 --- a/include/u-boot/md5.h +++ b/include/u-boot/md5.h @@ -6,10 +6,16 @@ #ifndef _MD5_H #define _MD5_H
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +#include <mbedtls/md5.h> +#endif #include "compiler.h"
#define MD5_SUM_LEN 16
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +typedef mbedtls_md5_context MD5Context; +#else typedef struct MD5Context { __u32 buf[4]; __u32 bits[2]; @@ -18,6 +24,7 @@ typedef struct MD5Context { __u32 in32[16]; }; } MD5Context; +#endif
void MD5Init(MD5Context *ctx); void MD5Update(MD5Context *ctx, unsigned char const *buf, unsigned int len); diff --git a/include/u-boot/sha1.h b/include/u-boot/sha1.h index c1e9f67068d..ab88134fb98 100644 --- a/include/u-boot/sha1.h +++ b/include/u-boot/sha1.h @@ -16,6 +16,21 @@
#include <linux/types.h>
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +/* + * FIXME: + * MbedTLS define the members of "mbedtls_sha256_context" as private, + * but "state" needs to be access by arch/arm/cpu/armv8/sha1_ce_glue. + * MBEDTLS_ALLOW_PRIVATE_ACCESS needs to be enabled to allow the external + * access. + * Directly including <external/mbedtls/library/common.h> is not allowed, + * since this will include <malloc.h> and break the sandbox test. + */ +#define MBEDTLS_ALLOW_PRIVATE_ACCESS + +#include <mbedtls/sha1.h> +#endif + #ifdef __cplusplus extern "C" { #endif @@ -26,6 +41,9 @@ extern "C" {
extern const uint8_t sha1_der_prefix[];
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +typedef mbedtls_sha1_context sha1_context; +#else /** * \brief SHA-1 context structure */ @@ -36,13 +54,14 @@ typedef struct unsigned char buffer[64]; /*!< data block being processed */ } sha1_context; +#endif
/** * \brief SHA-1 context setup * * \param ctx SHA-1 context to be initialized */ -void sha1_starts( sha1_context *ctx ); +void sha1_starts(sha1_context *ctx);
/** * \brief SHA-1 process buffer diff --git a/include/u-boot/sha256.h b/include/u-boot/sha256.h index a4fe176c0b4..b58d5b58d39 100644 --- a/include/u-boot/sha256.h +++ b/include/u-boot/sha256.h @@ -3,6 +3,22 @@
#include <linux/types.h>
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +/* + * FIXME: + * MbedTLS define the members of "mbedtls_sha256_context" as private, + * but "state" needs to be access by arch/arm/cpu/armv8/sha256_ce_glue. + * MBEDTLS_ALLOW_PRIVATE_ACCESS needs to be enabled to allow the external + * access. + * Directly including <external/mbedtls/library/common.h> is not allowed, + * since this will include <malloc.h> and break the sandbox test. + */ +#define MBEDTLS_ALLOW_PRIVATE_ACCESS + +#include <mbedtls/sha256.h> +#endif + +#define SHA224_SUM_LEN 28 #define SHA256_SUM_LEN 32 #define SHA256_DER_LEN 19
@@ -11,11 +27,15 @@ extern const uint8_t sha256_der_prefix[]; /* Reset watchdog each time we process this many bytes */ #define CHUNKSZ_SHA256 (64 * 1024)
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +typedef mbedtls_sha256_context sha256_context; +#else typedef struct { uint32_t total[2]; uint32_t state[8]; uint8_t buffer[64]; } sha256_context; +#endif
void sha256_starts(sha256_context * ctx); void sha256_update(sha256_context *ctx, const uint8_t *input, uint32_t length); diff --git a/include/u-boot/sha512.h b/include/u-boot/sha512.h index 90bd96a3f8c..2b5a21a7c70 100644 --- a/include/u-boot/sha512.h +++ b/include/u-boot/sha512.h @@ -3,6 +3,10 @@
#include <linux/types.h>
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +#include <mbedtls/sha512.h> +#endif + #define SHA384_SUM_LEN 48 #define SHA384_DER_LEN 19 #define SHA512_SUM_LEN 64 @@ -12,11 +16,16 @@ #define CHUNKSZ_SHA384 (16 * 1024) #define CHUNKSZ_SHA512 (16 * 1024)
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +typedef mbedtls_sha512_context sha384_context; +typedef mbedtls_sha512_context sha512_context; +#else typedef struct { uint64_t state[SHA512_SUM_LEN / 8]; uint64_t count[2]; uint8_t buf[SHA512_BLOCK_SIZE]; } sha512_context; +#endif
extern const uint8_t sha512_der_prefix[];
@@ -29,12 +38,19 @@ void sha512_csum_wd(const unsigned char *input, unsigned int ilen,
extern const uint8_t sha384_der_prefix[];
+#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) +void sha384_starts(sha512_context *ctx); +void +sha384_update(sha512_context *ctx, const uint8_t *input, uint32_t length); +void sha384_finish(sha512_context *ctx, uint8_t digest[SHA384_SUM_LEN]); +void sha384_csum_wd(const unsigned char *input, unsigned int length, + unsigned char *output, unsigned int chunk_sz); +#else void sha384_starts(sha512_context * ctx); void sha384_update(sha512_context *ctx, const uint8_t *input, uint32_t length); void sha384_finish(sha512_context * ctx, uint8_t digest[SHA384_SUM_LEN]);
void sha384_csum_wd(const unsigned char *input, unsigned int ilen, - unsigned char *output, unsigned int chunk_sz); - - + unsigned char *output, unsigned int chunk_sz); +#endif #endif /* _SHA512_H */ diff --git a/lib/Makefile b/lib/Makefile index 499d174199f..35b73d8d00c 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -71,14 +71,16 @@ obj-$(CONFIG_$(SPL_TPL_)CRC16) += crc16.o obj-y += crypto/
obj-$(CONFIG_$(SPL_TPL_)ACPI) += acpi/ -obj-$(CONFIG_$(SPL_)MD5) += md5.o obj-$(CONFIG_ECDSA) += ecdsa/ obj-$(CONFIG_$(SPL_)RSA) += rsa/ obj-$(CONFIG_HASH) += hash-checksum.o obj-$(CONFIG_BLAKE2) += blake2/blake2b.o -obj-$(CONFIG_$(SPL_)SHA1) += sha1.o -obj-$(CONFIG_$(SPL_)SHA256) += sha256.o -obj-$(CONFIG_$(SPL_)SHA512) += sha512.o + +obj-$(CONFIG_$(SPL_)MD5_LEGACY) += md5.o +obj-$(CONFIG_$(SPL_)SHA1_LEGACY) += sha1.o +obj-$(CONFIG_$(SPL_)SHA256_LEGACY) += sha256.o +obj-$(CONFIG_$(SPL_)SHA512_LEGACY) += sha512.o + obj-$(CONFIG_CRYPT_PW) += crypt/ obj-$(CONFIG_$(SPL_)ASN1_DECODER) += asn1_decoder.o
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index 3e9057f1acf..efae2c4fd72 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -21,9 +21,100 @@ if LEGACY_CRYPTO
config LEGACY_CRYPTO_BASIC bool "legacy basic crypto libraries" + select MD5_LEGACY if MD5 + select SHA1_LEGACY if SHA1 + select SHA256_LEGACY if SHA256 + select SHA512_LEGACY if SHA512 + select SHA384_LEGACY if SHA384 + select SPL_MD5_LEGACY if SPL_MD5 + select SPL_SHA1_LEGACY if SPL_SHA1 + select SPL_SHA256_LEGACY if SPL_SHA256 + select SPL_SHA512_LEGACY if SPL_SHA512 + select SPL_SHA384_LEGACY if SPL_SHA384 help Enable legacy basic crypto libraries.
+if LEGACY_CRYPTO_BASIC + +config SHA1_LEGACY + bool "Enable SHA1 support with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SHA1 + help + This option enables support of hashing using SHA1 algorithm + with legacy crypto library. + +config SHA256_LEGACY + bool "Enable SHA256 support with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SHA256 + help + This option enables support of hashing using SHA256 algorithm + with legacy crypto library. + +config SHA512_LEGACY + bool "Enable SHA512 support with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SHA512 + default y if TI_SECURE_DEVICE && FIT_SIGNATURE + help + This option enables support of hashing using SHA512 algorithm + with legacy crypto library. + +config SHA384_LEGACY + bool "Enable SHA384 support with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SHA384 + select SHA512_LEGACY + help + This option enables support of hashing using SHA384 algorithm + with legacy crypto library. + +config MD5_LEGACY + bool "Enable MD5 support with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && MD5 + help + This option enables support of hashing using MD5 algorithm + with legacy crypto library. + +if SPL + +config SPL_SHA1_LEGACY + bool "Enable SHA1 support in SPL with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SPL_SHA1 + help + This option enables support of hashing using SHA1 algorithm + with legacy crypto library. + +config SPL_SHA256_LEGACY + bool "Enable SHA256 support in SPL with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SPL_SHA256 + help + This option enables support of hashing using SHA256 algorithm + with legacy crypto library. + +config SPL_SHA512_LEGACY + bool "Enable SHA512 support in SPL with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SPL_SHA512 + help + This option enables support of hashing using SHA512 algorithm + with legacy crypto library. + +config SPL_SHA384_LEGACY + bool "Enable SHA384 support in SPL with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SPL_SHA384 + select SPL_SHA512_LEGACY + help + This option enables support of hashing using SHA384 algorithm + with legacy crypto library. + +config SPL_MD5_LEGACY + bool "Enable MD5 support in SPL with legacy crypto library" + depends on LEGACY_CRYPTO_BASIC && SPL_MD5 + help + This option enables support of hashing using MD5 algorithm + with legacy crypto library. + +endif # SPL + +endif # LEGACY_CRYPTO_BASIC + config LEGACY_CRYPTO_CERT bool "legacy certificate libraries" help

On Wed, Jul 31, 2024 at 10:25:13AM -0700, Raymond Mao wrote:
Adapt digest header files to support both original libs and MbedTLS by switching on/off MBEDTLS_LIB_CRYPTO. Introduce <alg>_LEGACY kconfig for legacy hash implementations.
FIXME: `IS_ENABLED` or `CONFIG_IS_ENABLED` is not applicable here, since including <linux/kconfig.h> causes undefined reference on schedule() with sandbox build. As <linux/kconfig.h> includes <generated/autoconf.h> which enables `CONFIG_HW_WATCHDOG` and `CONFIG_WATCHDOG` but no schedule() are defined in sandbox build. `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` is a workaround.
Signed-off-by: Raymond Mao raymond.mao@linaro.org
Please either FIXME or reword this for the next iteration.

We don't need an API specially for non-watchdog since md5_wd supports it by disabling CONFIG_HW_WATCHDOG and CONFIG_WATCHDOG. Set 0x10000 as default chunk size for MD5.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org Reviewed-by: Michal Simek michal.simek@amd.com --- Changes in v3 - Initial patch. Changes in v4 - Update commit message. Changes in v5 - None.
board/friendlyarm/nanopi2/board.c | 3 ++- board/intel/edison/edison.c | 3 ++- board/xilinx/zynq/bootimg.c | 2 +- include/u-boot/md5.h | 7 +------ lib/md5.c | 15 --------------- 5 files changed, 6 insertions(+), 24 deletions(-)
diff --git a/board/friendlyarm/nanopi2/board.c b/board/friendlyarm/nanopi2/board.c index c8cbc5a15fa..2d764e8eef3 100644 --- a/board/friendlyarm/nanopi2/board.c +++ b/board/friendlyarm/nanopi2/board.c @@ -263,7 +263,8 @@ static void make_ether_addr(u8 *addr) hash[6] = readl(PHY_BASEADDR_ECID + 0x08); hash[7] = readl(PHY_BASEADDR_ECID + 0x0c);
- md5((unsigned char *)&hash[4], 64, (unsigned char *)hash); + md5_wd((unsigned char *)&hash[4], 64, (unsigned char *)hash, + MD5_DEF_CHUNK_SZ);
hash[0] ^= hash[2]; hash[1] ^= hash[3]; diff --git a/board/intel/edison/edison.c b/board/intel/edison/edison.c index 911ffda2fc7..27fda3fc1d2 100644 --- a/board/intel/edison/edison.c +++ b/board/intel/edison/edison.c @@ -32,7 +32,8 @@ static void assign_serial(void) if (!mmc) return;
- md5((unsigned char *)mmc->cid, sizeof(mmc->cid), ssn); + md5_wd((unsigned char *)mmc->cid, sizeof(mmc->cid), ssn, + MD5_DEF_CHUNK_SZ);
snprintf(usb0addr, sizeof(usb0addr), "02:00:86:%02x:%02x:%02x", ssn[13], ssn[14], ssn[15]); diff --git a/board/xilinx/zynq/bootimg.c b/board/xilinx/zynq/bootimg.c index 79bec3a4cfb..9eb0735f55d 100644 --- a/board/xilinx/zynq/bootimg.c +++ b/board/xilinx/zynq/bootimg.c @@ -135,7 +135,7 @@ int zynq_validate_partition(u32 start_addr, u32 len, u32 chksum_off)
memcpy(&checksum[0], (u32 *)chksum_off, MD5_CHECKSUM_SIZE);
- md5_wd((u8 *)start_addr, len, &calchecksum[0], 0x10000); + md5_wd((u8 *)start_addr, len, &calchecksum[0], MD5_DEF_CHUNK_SZ);
if (!memcmp(checksum, calchecksum, MD5_CHECKSUM_SIZE)) return 0; diff --git a/include/u-boot/md5.h b/include/u-boot/md5.h index 69898fcbe49..c98b1a58088 100644 --- a/include/u-boot/md5.h +++ b/include/u-boot/md5.h @@ -12,6 +12,7 @@ #include "compiler.h"
#define MD5_SUM_LEN 16 +#define MD5_DEF_CHUNK_SZ 0x10000
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) typedef mbedtls_md5_context MD5Context; @@ -30,12 +31,6 @@ void MD5Init(MD5Context *ctx); void MD5Update(MD5Context *ctx, unsigned char const *buf, unsigned int len); void MD5Final(unsigned char digest[16], MD5Context *ctx);
-/* - * Calculate and store in 'output' the MD5 digest of 'len' bytes at - * 'input'. 'output' must have enough space to hold 16 bytes. - */ -void md5 (unsigned char *input, int len, unsigned char output[16]); - /* * Calculate and store in 'output' the MD5 digest of 'len' bytes at 'input'. * 'output' must have enough space to hold 16 bytes. If 'chunk' Trigger the diff --git a/lib/md5.c b/lib/md5.c index 34343cf8e23..2d8977b2e85 100644 --- a/lib/md5.c +++ b/lib/md5.c @@ -262,21 +262,6 @@ MD5Transform(__u32 buf[4], __u32 const in[16]) buf[3] += d; }
-/* - * Calculate and store in 'output' the MD5 digest of 'len' bytes at - * 'input'. 'output' must have enough space to hold 16 bytes. - */ -void -md5 (unsigned char *input, int len, unsigned char output[16]) -{ - MD5Context context; - - MD5Init(&context); - MD5Update(&context, input, len); - MD5Final(output, &context); -} - - /* * Calculate and store in 'output' the MD5 digest of 'len' bytes at 'input'. * 'output' must have enough space to hold 16 bytes. If 'chunk' Trigger the

We don't need an API specially for non-watchdog since sha1_csum_wd supports it by disabling CONFIG_HW_WATCHDOG and CONFIG_WATCHDOG. Set 0x10000 as default chunk size for SHA1.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v4 - Initial patch. Changes in v5 - None.
board/gdsys/a38x/hre.c | 2 +- include/u-boot/sha1.h | 12 ++---------- lib/sha1.c | 13 ------------- lib/tpm-v1.c | 2 +- 4 files changed, 4 insertions(+), 25 deletions(-)
diff --git a/board/gdsys/a38x/hre.c b/board/gdsys/a38x/hre.c index f303793b63b..06856ea36d3 100644 --- a/board/gdsys/a38x/hre.c +++ b/board/gdsys/a38x/hre.c @@ -166,7 +166,7 @@ static int find_key(struct udevice *tpm, const uint8_t auth[20], return -1; if (err) continue; - sha1_csum(buf, buf_len, digest); + sha1_csum_wd(buf, buf_len, digest, SHA1_DEF_CHUNK_SZ); if (!memcmp(digest, pubkey_digest, 20)) { *handle = key_handles[i]; return 0; diff --git a/include/u-boot/sha1.h b/include/u-boot/sha1.h index ab88134fb98..36c3db15e22 100644 --- a/include/u-boot/sha1.h +++ b/include/u-boot/sha1.h @@ -39,6 +39,8 @@ extern "C" { #define SHA1_SUM_LEN 20 #define SHA1_DER_LEN 15
+#define SHA1_DEF_CHUNK_SZ 0x10000 + extern const uint8_t sha1_der_prefix[];
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) @@ -81,16 +83,6 @@ void sha1_update(sha1_context *ctx, const unsigned char *input, */ void sha1_finish( sha1_context *ctx, unsigned char output[20] );
-/** - * \brief Output = SHA-1( input buffer ) - * - * \param input buffer holding the data - * \param ilen length of the input data - * \param output SHA-1 checksum result - */ -void sha1_csum(const unsigned char *input, unsigned int ilen, - unsigned char *output); - /** * \brief Output = SHA-1( input buffer ), with watchdog triggering * diff --git a/lib/sha1.c b/lib/sha1.c index 7ef536f4b5d..81412283b49 100644 --- a/lib/sha1.c +++ b/lib/sha1.c @@ -304,19 +304,6 @@ void sha1_finish (sha1_context * ctx, unsigned char output[20]) PUT_UINT32_BE (ctx->state[4], output, 16); }
-/* - * Output = SHA-1( input buffer ) - */ -void sha1_csum(const unsigned char *input, unsigned int ilen, - unsigned char *output) -{ - sha1_context ctx; - - sha1_starts (&ctx); - sha1_update (&ctx, input, ilen); - sha1_finish (&ctx, output); -} - /* * Output = SHA-1( input buffer ). Trigger the watchdog every 'chunk_sz' * bytes of input processed. diff --git a/lib/tpm-v1.c b/lib/tpm-v1.c index e66023da5e6..a6727c575fd 100644 --- a/lib/tpm-v1.c +++ b/lib/tpm-v1.c @@ -871,7 +871,7 @@ u32 tpm1_find_key_sha1(struct udevice *dev, const u8 auth[20], return -1; if (err) continue; - sha1_csum(buf, buf_len, digest); + sha1_csum_wd(buf, buf_len, digest, SHA1_DEF_CHUNK_SZ); if (!memcmp(digest, pubkey_digest, 20)) { *handle = key_handles[i]; return 0;

Implement digest shim layer on top of MbedTLS crypto library. Introduce <alg>_MBEDTLS kconfig for MbedTLS crypto implementations.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Split the shim layer into separated files and use the original head files instead of creating new ones. Changes in v3 - Refactored sha1_hmac and removed non-watchdog md5 function. Changes in v4 - Refactored hash _wd functions. - Introduce <alg>_MBEDTLS kconfig for MbedTLS crypto implementations. Changes in v5 - Correct kconfig dependence. - Refactored MbedTLS makefile.
include/u-boot/sha1.h | 4 ++ lib/mbedtls/Kconfig | 90 +++++++++++++++++++++++++++++++++++++++ lib/mbedtls/Makefile | 14 ++++-- lib/mbedtls/md5.c | 57 +++++++++++++++++++++++++ lib/mbedtls/sha1.c | 99 +++++++++++++++++++++++++++++++++++++++++++ lib/mbedtls/sha256.c | 62 +++++++++++++++++++++++++++ lib/mbedtls/sha512.c | 93 ++++++++++++++++++++++++++++++++++++++++ 7 files changed, 415 insertions(+), 4 deletions(-) create mode 100644 lib/mbedtls/md5.c create mode 100644 lib/mbedtls/sha1.c create mode 100644 lib/mbedtls/sha256.c create mode 100644 lib/mbedtls/sha512.c
diff --git a/include/u-boot/sha1.h b/include/u-boot/sha1.h index 36c3db15e22..2fca7f1be16 100644 --- a/include/u-boot/sha1.h +++ b/include/u-boot/sha1.h @@ -41,6 +41,10 @@ extern "C" {
#define SHA1_DEF_CHUNK_SZ 0x10000
+#define K_IPAD_VAL 0x36 +#define K_OPAD_VAL 0x5C +#define K_PAD_LEN 64 + extern const uint8_t sha1_der_prefix[];
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO) diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index efae2c4fd72..12f8c965f5a 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -126,9 +126,99 @@ if MBEDTLS_LIB
config MBEDTLS_LIB_CRYPTO bool "MbedTLS crypto libraries" + select MD5_MBEDTLS if MD5 + select SHA1_MBEDTLS if SHA1 + select SHA256_MBEDTLS if SHA256 + select SHA512_MBEDTLS if SHA512 + select SHA384_MBEDTLS if SHA384 + select SPL_MD5_MBEDTLS if SPL_MD5 + select SPL_SHA1_MBEDTLS if SPL_SHA1 + select SPL_SHA256_MBEDTLS if SPL_SHA256 + select SPL_SHA512_MBEDTLS if SPL_SHA512 + select SPL_SHA384_MBEDTLS if SPL_SHA384 help Enable MbedTLS crypto libraries.
+if MBEDTLS_LIB_CRYPTO + +config SHA1_MBEDTLS + bool "Enable SHA1 support with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SHA1 + help + This option enables support of hashing using SHA1 algorithm + with MbedTLS crypto library. + +config SHA256_MBEDTLS + bool "Enable SHA256 support with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SHA256 + help + This option enables support of hashing using SHA256 algorithm + with MbedTLS crypto library. + +config SHA512_MBEDTLS + bool "Enable SHA512 support with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SHA512 + default y if TI_SECURE_DEVICE && FIT_SIGNATURE + help + This option enables support of hashing using SHA512 algorithm + with MbedTLS crypto library. + +config SHA384_MBEDTLS + bool "Enable SHA384 support with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SHA384 + select SHA512_MBEDTLS + help + This option enables support of hashing using SHA384 algorithm + with MbedTLS crypto library. + +config MD5_MBEDTLS + bool "Enable MD5 support with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && MD5 + help + This option enables support of hashing using MD5 algorithm + with MbedTLS crypto library. + +if SPL + +config SPL_SHA1_MBEDTLS + bool "Enable SHA1 support in SPL with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SPL_SHA1 + help + This option enables support of hashing using SHA1 algorithm + with MbedTLS crypto library. + +config SPL_SHA256_MBEDTLS + bool "Enable SHA256 support in SPL with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SPL_SHA256 + help + This option enables support of hashing using SHA256 algorithm + with MbedTLS crypto library. + +config SPL_SHA512_MBEDTLS + bool "Enable SHA512 support in SPL with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SPL_SHA512 + help + This option enables support of hashing using SHA512 algorithm + with MbedTLS crypto library. + +config SPL_SHA384_MBEDTLS + bool "Enable SHA384 support in SPL with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SPL_SHA384 + select SPL_SHA512 + help + This option enables support of hashing using SHA384 algorithm + with MbedTLS crypto library. + +config SPL_MD5_MBEDTLS + bool "Enable MD5 support in SPL with MbedTLS crypto library" + depends on MBEDTLS_LIB_CRYPTO && SPL_MD5 + help + This option enables support of hashing using MD5 algorithm + with MbedTLS crypto library. + +endif # SPL + +endif # MBEDTLS_LIB_CRYPTO
config MBEDTLS_LIB_X509 bool "MbedTLS certificate libraries" diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile index e98241b46ab..50c1ba5f88e 100644 --- a/lib/mbedtls/Makefile +++ b/lib/mbedtls/Makefile @@ -5,17 +5,23 @@
MBEDTLS_LIB_DIR = external/mbedtls/library
+# shim layer for hash +obj-$(CONFIG_$(SPL_)MD5_MBEDTLS) += md5.o +obj-$(CONFIG_$(SPL_)SHA1_MBEDTLS) += sha1.o +obj-$(CONFIG_$(SPL_)SHA256_MBEDTLS) += sha256.o +obj-$(CONFIG_$(SPL_)SHA512_MBEDTLS) += sha512.o + # MbedTLS crypto library obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o mbedtls_lib_crypto-y := \ $(MBEDTLS_LIB_DIR)/platform_util.o \ $(MBEDTLS_LIB_DIR)/constant_time.o \ $(MBEDTLS_LIB_DIR)/md.o -mbedtls_lib_crypto-$(CONFIG_$(SPL_)MD5) += $(MBEDTLS_LIB_DIR)/md5.o -mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA1) += $(MBEDTLS_LIB_DIR)/sha1.o -mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA256) += \ +mbedtls_lib_crypto-$(CONFIG_$(SPL_)MD5_MBEDTLS) += $(MBEDTLS_LIB_DIR)/md5.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA1_MBEDTLS) += $(MBEDTLS_LIB_DIR)/sha1.o +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA256_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/sha256.o -mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA512) += \ +mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA512_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/sha512.o
# MbedTLS X509 library diff --git a/lib/mbedtls/md5.c b/lib/mbedtls/md5.c new file mode 100644 index 00000000000..04388fce249 --- /dev/null +++ b/lib/mbedtls/md5.c @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Hash shim layer on MbedTLS Crypto library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#include "compiler.h" + +#ifndef USE_HOSTCC +#include <watchdog.h> +#endif /* USE_HOSTCC */ +#include <u-boot/md5.h> + +void MD5Init(MD5Context *ctx) +{ + mbedtls_md5_init(ctx); + mbedtls_md5_starts(ctx); +} + +void MD5Update(MD5Context *ctx, unsigned char const *buf, unsigned int len) +{ + mbedtls_md5_update(ctx, buf, len); +} + +void MD5Final(unsigned char digest[16], MD5Context *ctx) +{ + mbedtls_md5_finish(ctx, digest); + mbedtls_md5_free(ctx); +} + +void md5_wd(const unsigned char *input, unsigned int len, + unsigned char output[16], unsigned int chunk_sz) +{ + MD5Context context; + + MD5Init(&context); + + if (IS_ENABLED(CONFIG_HW_WATCHDOG) || IS_ENABLED(CONFIG_WATCHDOG)) { + const unsigned char *curr = input; + const unsigned char *end = input + len; + int chunk; + + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + MD5Update(&context, curr, chunk); + curr += chunk; + schedule(); + } + } else { + MD5Update(&context, input, len); + } + + MD5Final(output, &context); +} diff --git a/lib/mbedtls/sha1.c b/lib/mbedtls/sha1.c new file mode 100644 index 00000000000..2aee5037795 --- /dev/null +++ b/lib/mbedtls/sha1.c @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Hash shim layer on MbedTLS Crypto library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#ifndef USE_HOSTCC +#include <cyclic.h> +#endif /* USE_HOSTCC */ +#include <string.h> +#include <u-boot/sha1.h> + +const u8 sha1_der_prefix[SHA1_DER_LEN] = { + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, + 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 +}; + +void sha1_starts(sha1_context *ctx) +{ + mbedtls_sha1_init(ctx); + mbedtls_sha1_starts(ctx); +} + +void sha1_update(sha1_context *ctx, const unsigned char *input, + unsigned int length) +{ + mbedtls_sha1_update(ctx, input, length); +} + +void sha1_finish(sha1_context *ctx, unsigned char output[SHA1_SUM_LEN]) +{ + mbedtls_sha1_finish(ctx, output); + mbedtls_sha1_free(ctx); +} + +void sha1_csum_wd(const unsigned char *input, unsigned int ilen, + unsigned char *output, unsigned int chunk_sz) +{ + sha1_context ctx; + + sha1_starts(&ctx); + + if (IS_ENABLED(CONFIG_HW_WATCHDOG) || IS_ENABLED(CONFIG_WATCHDOG)) { + const unsigned char *curr = input; + const unsigned char *end = input + ilen; + int chunk; + + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + sha1_update(&ctx, curr, chunk); + curr += chunk; + schedule(); + } + } else { + sha1_update(&ctx, input, ilen); + } + + sha1_finish(&ctx, output); +} + +void sha1_hmac(const unsigned char *key, int keylen, + const unsigned char *input, unsigned int ilen, + unsigned char *output) +{ + int i; + sha1_context ctx; + unsigned char k_ipad[K_PAD_LEN]; + unsigned char k_opad[K_PAD_LEN]; + unsigned char tmpbuf[20]; + + if (keylen > K_PAD_LEN) + return; + + memset(k_ipad, K_IPAD_VAL, sizeof(k_ipad)); + memset(k_opad, K_OPAD_VAL, sizeof(k_opad)); + + for (i = 0; i < keylen; i++) { + k_ipad[i] ^= key[i]; + k_opad[i] ^= key[i]; + } + + sha1_starts(&ctx); + sha1_update(&ctx, k_ipad, sizeof(k_ipad)); + sha1_update(&ctx, input, ilen); + sha1_finish(&ctx, tmpbuf); + + sha1_starts(&ctx); + sha1_update(&ctx, k_opad, sizeof(k_opad)); + sha1_update(&ctx, tmpbuf, sizeof(tmpbuf)); + sha1_finish(&ctx, output); + + memset(k_ipad, 0, sizeof(k_ipad)); + memset(k_opad, 0, sizeof(k_opad)); + memset(tmpbuf, 0, sizeof(tmpbuf)); + memset(&ctx, 0, sizeof(sha1_context)); +} diff --git a/lib/mbedtls/sha256.c b/lib/mbedtls/sha256.c new file mode 100644 index 00000000000..24aa58fa674 --- /dev/null +++ b/lib/mbedtls/sha256.c @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Hash shim layer on MbedTLS Crypto library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#ifndef USE_HOSTCC +#include <cyclic.h> +#endif /* USE_HOSTCC */ +#include <u-boot/sha256.h> + +const u8 sha256_der_prefix[SHA256_DER_LEN] = { + 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, + 0x00, 0x04, 0x20 +}; + +void sha256_starts(sha256_context *ctx) +{ + mbedtls_sha256_init(ctx); + mbedtls_sha256_starts(ctx, 0); +} + +void +sha256_update(sha256_context *ctx, const uint8_t *input, uint32_t length) +{ + mbedtls_sha256_update(ctx, input, length); +} + +void sha256_finish(sha256_context *ctx, uint8_t digest[SHA256_SUM_LEN]) +{ + mbedtls_sha256_finish(ctx, digest); + mbedtls_sha256_free(ctx); +} + +void sha256_csum_wd(const unsigned char *input, unsigned int ilen, + unsigned char *output, unsigned int chunk_sz) +{ + sha256_context ctx; + + sha256_starts(&ctx); + + if (IS_ENABLED(CONFIG_HW_WATCHDOG) || IS_ENABLED(CONFIG_WATCHDOG)) { + const unsigned char *curr = input; + const unsigned char *end = input + ilen; + int chunk; + + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + sha256_update(&ctx, curr, chunk); + curr += chunk; + schedule(); + } + } else { + sha256_update(&ctx, input, ilen); + } + + sha256_finish(&ctx, output); +} diff --git a/lib/mbedtls/sha512.c b/lib/mbedtls/sha512.c new file mode 100644 index 00000000000..5615248cb91 --- /dev/null +++ b/lib/mbedtls/sha512.c @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Hash shim layer on MbedTLS Crypto library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#ifndef USE_HOSTCC +#include <cyclic.h> +#endif /* USE_HOSTCC */ +#include <compiler.h> +#include <u-boot/sha512.h> + +const u8 sha384_der_prefix[SHA384_DER_LEN] = { + 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, + 0x00, 0x04, 0x30 +}; + +const u8 sha512_der_prefix[SHA512_DER_LEN] = { + 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, + 0x00, 0x04, 0x40 +}; + +void sha384_starts(sha512_context *ctx) +{ + mbedtls_sha512_init(ctx); + mbedtls_sha512_starts(ctx, 1); +} + +void +sha384_update(sha512_context *ctx, const uint8_t *input, uint32_t length) +{ + mbedtls_sha512_update(ctx, input, length); +} + +void sha384_finish(sha512_context *ctx, uint8_t digest[SHA384_SUM_LEN]) +{ + mbedtls_sha512_finish(ctx, digest); + mbedtls_sha512_free(ctx); +} + +void sha384_csum_wd(const unsigned char *input, unsigned int length, + unsigned char *output, unsigned int chunk_sz) +{ + mbedtls_sha512(input, length, output, 1); +} + +void sha512_starts(sha512_context *ctx) +{ + mbedtls_sha512_init(ctx); + mbedtls_sha512_starts(ctx, 0); +} + +void +sha512_update(sha512_context *ctx, const uint8_t *input, uint32_t length) +{ + mbedtls_sha512_update(ctx, input, length); +} + +void sha512_finish(sha512_context *ctx, uint8_t digest[SHA512_SUM_LEN]) +{ + mbedtls_sha512_finish(ctx, digest); + mbedtls_sha512_free(ctx); +} + +void sha512_csum_wd(const unsigned char *input, unsigned int ilen, + unsigned char *output, unsigned int chunk_sz) +{ + sha512_context ctx; + + sha512_starts(&ctx); + + if (IS_ENABLED(CONFIG_HW_WATCHDOG) || IS_ENABLED(CONFIG_WATCHDOG)) { + const unsigned char *curr = input; + const unsigned char *end = input + ilen; + int chunk; + + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + sha512_update(&ctx, curr, chunk); + curr += chunk; + schedule(); + } + } else { + sha512_update(&ctx, input, ilen); + } + + sha512_finish(&ctx, output); +}

Integrate common/hash.c on the hash shim layer so that hash APIs from mbedtls can be leveraged by boot/image and efi_loader.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Use the original head files instead of creating new ones. Changes in v3 - Add handle checkers for malloc. Changes in v4 - None. Changes in v5 - Add __maybe_unused to solve linker errors in some platforms. - replace malloc with calloc.
common/hash.c | 146 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+)
diff --git a/common/hash.c b/common/hash.c index ac63803fed9..d25fc4854c7 100644 --- a/common/hash.c +++ b/common/hash.c @@ -35,6 +35,144 @@ #include <u-boot/sha512.h> #include <u-boot/md5.h>
+#if CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO) + +static int __maybe_unused hash_init_sha1(struct hash_algo *algo, void **ctxp) +{ + int ret; + mbedtls_sha1_context *ctx = calloc(1, sizeof(*ctx)); + + if (!ctx) + return -ENOMEM; + + mbedtls_sha1_init(ctx); + ret = mbedtls_sha1_starts(ctx); + if (!ret) { + *ctxp = ctx; + } else { + mbedtls_sha1_free(ctx); + free(ctx); + } + + return ret; +} + +static int __maybe_unused hash_update_sha1(struct hash_algo *algo, void *ctx, + const void *buf, unsigned int size, + int is_last) +{ + return mbedtls_sha1_update((mbedtls_sha1_context *)ctx, buf, size); +} + +static int __maybe_unused +hash_finish_sha1(struct hash_algo *algo, void *ctx, void *dest_buf, int size) +{ + int ret; + + if (size < algo->digest_size) + return -1; + + ret = mbedtls_sha1_finish((mbedtls_sha1_context *)ctx, dest_buf); + if (!ret) { + mbedtls_sha1_free((mbedtls_sha1_context *)ctx); + free(ctx); + } + + return ret; +} + +static int __maybe_unused hash_init_sha256(struct hash_algo *algo, void **ctxp) +{ + int ret; + int is224 = algo->digest_size == SHA224_SUM_LEN ? 1 : 0; + mbedtls_sha256_context *ctx = calloc(1, sizeof(*ctx)); + + if (!ctx) + return -ENOMEM; + + mbedtls_sha256_init(ctx); + ret = mbedtls_sha256_starts(ctx, is224); + if (!ret) { + *ctxp = ctx; + } else { + mbedtls_sha256_free(ctx); + free(ctx); + } + + return ret; +} + +static int __maybe_unused hash_update_sha256(struct hash_algo *algo, void *ctx, + const void *buf, uint size, + int is_last) +{ + return mbedtls_sha256_update((mbedtls_sha256_context *)ctx, buf, size); +} + +static int __maybe_unused +hash_finish_sha256(struct hash_algo *algo, void *ctx, void *dest_buf, int size) +{ + int ret; + + if (size < algo->digest_size) + return -1; + + ret = mbedtls_sha256_finish((mbedtls_sha256_context *)ctx, dest_buf); + if (!ret) { + mbedtls_sha256_free((mbedtls_sha256_context *)ctx); + free(ctx); + } + + return ret; +} + +static int __maybe_unused hash_init_sha512(struct hash_algo *algo, void **ctxp) +{ + int ret; + int is384 = algo->digest_size == SHA384_SUM_LEN ? 1 : 0; + mbedtls_sha512_context *ctx = calloc(1, sizeof(*ctx)); + + if (!ctx) + return -ENOMEM; + + mbedtls_sha512_init(ctx); + ret = mbedtls_sha512_starts(ctx, is384); + if (!ret) { + *ctxp = ctx; + } else { + mbedtls_sha512_free(ctx); + free(ctx); + } + + return ret; +} + +static int __maybe_unused hash_update_sha512(struct hash_algo *algo, void *ctx, + const void *buf, uint size, + int is_last) +{ + return mbedtls_sha512_update((mbedtls_sha512_context *)ctx, buf, size); +} + +static int __maybe_unused +hash_finish_sha512(struct hash_algo *algo, void *ctx, void *dest_buf, int size) +{ + int ret; + + if (size < algo->digest_size) + return -1; + + ret = mbedtls_sha512_finish((mbedtls_sha512_context *)ctx, dest_buf); + if (!ret) { + mbedtls_sha512_free((mbedtls_sha512_context *)ctx); + free(ctx); + } + + return ret; +} + +#else /* CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO) */ + static int __maybe_unused hash_init_sha1(struct hash_algo *algo, void **ctxp) { sha1_context *ctx = malloc(sizeof(sha1_context)); @@ -143,6 +281,8 @@ static int __maybe_unused hash_finish_sha512(struct hash_algo *algo, void *ctx, return 0; }
+#endif /* CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO) */ + static int hash_init_crc16_ccitt(struct hash_algo *algo, void **ctxp) { uint16_t *ctx = malloc(sizeof(uint16_t)); @@ -267,10 +407,16 @@ static struct hash_algo hash_algo[] = { .hash_init = hw_sha_init, .hash_update = hw_sha_update, .hash_finish = hw_sha_finish, +#else +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_CRYPTO) + .hash_init = hash_init_sha512, + .hash_update = hash_update_sha512, + .hash_finish = hash_finish_sha512, #else .hash_init = hash_init_sha384, .hash_update = hash_update_sha384, .hash_finish = hash_finish_sha384, +#endif #endif }, #endif

Populate Microsoft Authentication Code from the content data into PKCS7 decoding context if it exists in a PKCS7 message. Add OIDs for describing objects using for Microsoft Authentication Code.
The PR for this patch is at: https://github.com/Mbed-TLS/mbedtls/pull/9001
For enabling EFI loader PKCS7 features with MbedTLS build, we need this patch on top of MbedTLS v3.6.0 before it is merged into the next MbedTLS LTS release.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - None. Changes in v3 - Update commit message. Changes in v4 - None. Changes in v5 - None.
.../external/mbedtls/include/mbedtls/oid.h | 30 ++++++++++ .../external/mbedtls/include/mbedtls/pkcs7.h | 10 ++++ lib/mbedtls/external/mbedtls/library/pkcs7.c | 60 +++++++++++++++---- 3 files changed, 90 insertions(+), 10 deletions(-)
diff --git a/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h b/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h index fdc25ebf885..2ee982808fa 100644 --- a/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h +++ b/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h @@ -352,6 +352,36 @@ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE "\x05" /**< pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 5} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE "\x06" /**< pbeWithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 6} */
+/* + * MicroSoft Authenticate Code OIDs + */ +#define MBEDTLS_OID_PRIVATE_ENTERPRISE MBEDTLS_OID_INTERNET "\x04\x01" /* {iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) */ +#define MBEDTLS_OID_MICROSOFT "\x82\x37" /* {microsoft(311)} */ +/* + * OID_msIndirectData: (1.3.6.1.4.1.311.2.1.4) + * {iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) microsoft(311) 2(2) 1(1) 4(4)} + */ +#define MBEDTLS_OID_MICROSOFT_INDIRECTDATA MBEDTLS_OID_PRIVATE_ENTERPRISE MBEDTLS_OID_MICROSOFT \ + "\x02\x01\x04" +/* + * OID_msStatementType: (1.3.6.1.4.1.311.2.1.11) + * {iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) microsoft(311) 2(2) 1(1) 11(11)} + */ +#define MBEDTLS_OID_MICROSOFT_STATETYPE MBEDTLS_OID_PRIVATE_ENTERPRISE MBEDTLS_OID_MICROSOFT \ + "\x02\x01\x0b" +/* + * OID_msSpOpusInfo: (1.3.6.1.4.1.311.2.1.12) + * {iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) microsoft(311) 2(2) 1(1) 12(12)} + */ +#define MBEDTLS_OID_MICROSOFT_SPOPUSINFO MBEDTLS_OID_PRIVATE_ENTERPRISE MBEDTLS_OID_MICROSOFT \ + "\x02\x01\x0b" +/* + * OID_msPeImageDataObjId: (1.3.6.1.4.1.311.2.1.15) + * {iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) microsoft(311) 2(2) 1(1) 15(15)} + */ +#define MBEDTLS_OID_MICROSOFT_PEIMAGEDATA MBEDTLS_OID_PRIVATE_ENTERPRISE MBEDTLS_OID_MICROSOFT \ + "\x02\x01\x0f" + /* * EC key algorithms from RFC 5480 */ diff --git a/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h b/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h index e9b482208e6..9e29b74af70 100644 --- a/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h +++ b/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h @@ -132,12 +132,22 @@ typedef struct mbedtls_pkcs7_signed_data { } mbedtls_pkcs7_signed_data;
+/* Content Data for MicroSoft Authentication Code using in U-Boot Secure Boot */ +typedef struct mbedtls_pkcs7_conten_data { + int data_type; /* Type of Data */ + size_t data_len; /* Length of Data */ + size_t data_hdrlen; /* Length of Data ASN.1 header */ + void *data; /* Content Data */ +} +mbedtls_pkcs7_conten_data; + /** * Structure holding PKCS #7 structure, only signed data for now */ typedef struct mbedtls_pkcs7 { mbedtls_pkcs7_buf MBEDTLS_PRIVATE(raw); mbedtls_pkcs7_signed_data MBEDTLS_PRIVATE(signed_data); + mbedtls_pkcs7_conten_data content_data; } mbedtls_pkcs7;
diff --git a/lib/mbedtls/external/mbedtls/library/pkcs7.c b/lib/mbedtls/external/mbedtls/library/pkcs7.c index 3aac662ba69..0c2436b56b7 100644 --- a/lib/mbedtls/external/mbedtls/library/pkcs7.c +++ b/lib/mbedtls/external/mbedtls/library/pkcs7.c @@ -29,6 +29,13 @@ #include <time.h> #endif
+enum OID { + /* PKCS#7 {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-7(7)} */ + MBEDTLS_OID_DATA = 13, /* 1.2.840.113549.1.7.1 */ + /* Microsoft Authenticode & Software Publishing */ + MBEDTLS_OID_MS_INDIRECTDATA = 24, /* 1.3.6.1.4.1.311.2.1.4 */ +}; + /** * Initializes the mbedtls_pkcs7 structure. */ @@ -449,7 +456,7 @@ cleanup: * signerInfos SignerInfos } */ static int pkcs7_get_signed_data(unsigned char *buf, size_t buflen, - mbedtls_pkcs7_signed_data *signed_data) + mbedtls_pkcs7 *pkcs7) { unsigned char *p = buf; unsigned char *end = buf + buflen; @@ -457,6 +464,7 @@ static int pkcs7_get_signed_data(unsigned char *buf, size_t buflen, size_t len = 0; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_md_type_t md_alg; + mbedtls_pkcs7_signed_data *signed_data = &pkcs7->signed_data;
ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); @@ -493,25 +501,57 @@ static int pkcs7_get_signed_data(unsigned char *buf, size_t buflen, if (ret != 0) { return ret; } - if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_DATA, &content_type)) { + + /* + * We should only support 1.2.840.113549.1.7.1 (PKCS7 DATA) and + * 1.3.6.1.4.1.311.2.1.4 (MicroSoft Authentication Code) that is for + * U-Boot Secure Boot + */ + if (!MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_DATA, &content_type)) { + pkcs7->content_data.data_type = MBEDTLS_OID_DATA; + } else if (!MBEDTLS_OID_CMP(MBEDTLS_OID_MICROSOFT_INDIRECTDATA, + &content_type)) { + pkcs7->content_data.data_type = MBEDTLS_OID_MS_INDIRECTDATA; + } else { return MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO; }
if (p != end_content_info) { + unsigned char *tmp_p = p; + /* Determine if valid content is present */ ret = mbedtls_asn1_get_tag(&p, end_content_info, &len, - MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC); + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_CONTEXT_SPECIFIC); + if (ret != 0 || p + len != end_content_info) { + return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, + ret); + } + + /* + * U-Boot Secure Boot needs to calculate the digest of MicroSoft + * Authentication Code during verifying an EFI image. + * Thus we need to save the context of Content Data. + */ + pkcs7->content_data.data_hdrlen = p - tmp_p; + /* Parse the content data from a sequence */ + ret = mbedtls_asn1_get_tag(&p, end_content_info, &len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); if (ret != 0) { - return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, ret); + /* TODO: Other Content Data formats are not supported at the moment */ + return MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE; + } else if (p + len != end_content_info) { + return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, + ret); } + + pkcs7->content_data.data = p; + pkcs7->content_data.data_len = len; + p += len; - if (p != end_content_info) { - return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, ret); - } - /* Valid content is present - this is not supported */ - return MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE; }
/* Look for certificates, there may or may not be any */ @@ -624,7 +664,7 @@ int mbedtls_pkcs7_parse_der(mbedtls_pkcs7 *pkcs7, const unsigned char *buf, }
try_data: - ret = pkcs7_get_signed_data(p, len, &pkcs7->signed_data); + ret = pkcs7_get_signed_data(p, len, pkcs7); if (ret != 0) { goto out; }

Populate PKCS9 Authenticate Attributes from signer info if it exists in a PKCS7 message. Add OIDs for describing objects using for Authenticate Attributes.
The PR for this patch is at: https://github.com/Mbed-TLS/mbedtls/pull/9001
For enabling EFI loader PKCS7 features with MbedTLS build, we need this patch on top of MbedTLS v3.6.0 before it is merged into the next MbedTLS LTS release.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - None. Changes in v3 - Update commit message. Changes in v4 - None. Changes in v5 - None.
.../external/mbedtls/include/mbedtls/oid.h | 5 +++++ .../external/mbedtls/include/mbedtls/pkcs7.h | 11 +++++++++++ lib/mbedtls/external/mbedtls/library/pkcs7.c | 19 ++++++++++++++++++- 3 files changed, 34 insertions(+), 1 deletion(-)
diff --git a/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h b/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h index 2ee982808fa..43cef99f1e3 100644 --- a/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h +++ b/lib/mbedtls/external/mbedtls/include/mbedtls/oid.h @@ -238,6 +238,11 @@ #define MBEDTLS_OID_RSA_SHA_OBS "\x2B\x0E\x03\x02\x1D"
#define MBEDTLS_OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9 "\x01" /**< emailAddress AttributeType ::= { pkcs-9 1 } */ +#define MBEDTLS_OID_PKCS9_CONTENTTYPE MBEDTLS_OID_PKCS9 "\x03" /**< contentType AttributeType ::= { pkcs-9 3 } */ +#define MBEDTLS_OID_PKCS9_MESSAGEDIGEST MBEDTLS_OID_PKCS9 "\x04" /**< messageDigest AttributeType ::= { pkcs-9 4 } */ +#define MBEDTLS_OID_PKCS9_SIGNINGTIME MBEDTLS_OID_PKCS9 "\x05" /**< signingTime AttributeType ::= { pkcs-9 5 } */ +#define MBEDTLS_OID_PKCS9_SMIMECAP MBEDTLS_OID_PKCS9 "\x0f" /**< smimeCapabilites AttributeType ::= { pkcs-9 15 } */ +#define MBEDTLS_OID_PKCS9_SMIMEAA MBEDTLS_OID_PKCS9 "\x10\x02\x0b" /**< smimeCapabilites AttributeType ::= { pkcs-9 16 2 11} */
/* RFC 4055 */ #define MBEDTLS_OID_RSASSA_PSS MBEDTLS_OID_PKCS1 "\x0a" /**< id-RSASSA-PSS ::= { pkcs-1 10 } */ diff --git a/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h b/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h index 9e29b74af70..a88a5e858fc 100644 --- a/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h +++ b/lib/mbedtls/external/mbedtls/include/mbedtls/pkcs7.h @@ -102,6 +102,16 @@ typedef enum { } mbedtls_pkcs7_type;
+/* + * Authenticate Attributes for MicroSoft Authentication Code using in U-Boot + * Secure Boot + */ +typedef struct mbedtls_pkcs7_authattrs { + size_t data_len; + void *data; +} +mbedtls_pkcs7_authattrs; + /** * Structure holding PKCS #7 signer info */ @@ -113,6 +123,7 @@ typedef struct mbedtls_pkcs7_signer_info { mbedtls_x509_buf MBEDTLS_PRIVATE(alg_identifier); mbedtls_x509_buf MBEDTLS_PRIVATE(sig_alg_identifier); mbedtls_x509_buf MBEDTLS_PRIVATE(sig); + mbedtls_pkcs7_authattrs authattrs; struct mbedtls_pkcs7_signer_info *MBEDTLS_PRIVATE(next); } mbedtls_pkcs7_signer_info; diff --git a/lib/mbedtls/external/mbedtls/library/pkcs7.c b/lib/mbedtls/external/mbedtls/library/pkcs7.c index 0c2436b56b7..da73fb341d6 100644 --- a/lib/mbedtls/external/mbedtls/library/pkcs7.c +++ b/lib/mbedtls/external/mbedtls/library/pkcs7.c @@ -288,6 +288,7 @@ static int pkcs7_get_signer_info(unsigned char **p, unsigned char *end, unsigned char *end_signer, *end_issuer_and_sn; int asn1_ret = 0, ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; + unsigned char *tmp_p;
asn1_ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); @@ -349,7 +350,23 @@ static int pkcs7_get_signer_info(unsigned char **p, unsigned char *end, goto out; }
- /* Assume authenticatedAttributes is nonexistent */ + /* Save authenticatedAttributes if present */ + if (*p < end_signer && + **p == (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0)) { + tmp_p = *p; + + ret = mbedtls_asn1_get_tag(p, end_signer, &len, + MBEDTLS_ASN1_CONTEXT_SPECIFIC | + MBEDTLS_ASN1_CONSTRUCTED | 0); + if (ret != 0) { + goto out; + } + + signer->authattrs.data = tmp_p; + signer->authattrs.data_len = len + *p - tmp_p; + *p += len; + } + ret = pkcs7_get_digest_algorithm(p, end_signer, &signer->sig_alg_identifier); if (ret != 0) { goto out;

Support decoding multiple signer's cert in the signed data within a PKCS7 message.
The PR for this patch is at: https://github.com/Mbed-TLS/mbedtls/pull/9001
For enabling EFI loader PKCS7 features with MbedTLS build, we need this patch on top of MbedTLS v3.6.0 before it is merged into the next MbedTLS LTS release.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - None. Changes in v3 - Update commit message. Changes in v4 - None. Changes in v5 - None.
lib/mbedtls/external/mbedtls/library/pkcs7.c | 75 ++++++++++++-------- 1 file changed, 47 insertions(+), 28 deletions(-)
diff --git a/lib/mbedtls/external/mbedtls/library/pkcs7.c b/lib/mbedtls/external/mbedtls/library/pkcs7.c index da73fb341d6..01105227d7a 100644 --- a/lib/mbedtls/external/mbedtls/library/pkcs7.c +++ b/lib/mbedtls/external/mbedtls/library/pkcs7.c @@ -61,6 +61,36 @@ static int pkcs7_get_next_content_len(unsigned char **p, unsigned char *end, return ret; }
+/** + * Get and decode one cert from a sequence. + * Return 0 for success, + * Return negative error code for failure. + **/ +static int pkcs7_get_one_cert(unsigned char **p, unsigned char *end, + mbedtls_x509_crt *certs) +{ + int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + size_t len = 0; + unsigned char *start = *p; + unsigned char *end_cert; + + ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED + | MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CERT, ret); + } + + end_cert = *p + len; + + if ((ret = mbedtls_x509_crt_parse_der(certs, start, end_cert - start)) < 0) { + return MBEDTLS_ERR_PKCS7_INVALID_CERT; + } + + *p = end_cert; + + return 0; +} + /** * version Version * Version ::= INTEGER @@ -178,11 +208,12 @@ static int pkcs7_get_certificates(unsigned char **p, unsigned char *end, mbedtls_x509_crt *certs) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - size_t len1 = 0; - size_t len2 = 0; - unsigned char *end_set, *end_cert, *start; + size_t len = 0; + unsigned char *end_set; + int num_of_certs = 0;
- ret = mbedtls_asn1_get_tag(p, end, &len1, MBEDTLS_ASN1_CONSTRUCTED + /* Get the set of certs */ + ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC); if (ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) { return 0; @@ -190,38 +221,26 @@ static int pkcs7_get_certificates(unsigned char **p, unsigned char *end, if (ret != 0) { return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_FORMAT, ret); } - start = *p; - end_set = *p + len1; + end_set = *p + len;
- ret = mbedtls_asn1_get_tag(p, end_set, &len2, MBEDTLS_ASN1_CONSTRUCTED - | MBEDTLS_ASN1_SEQUENCE); + ret = pkcs7_get_one_cert(p, end_set, certs); if (ret != 0) { - return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CERT, ret); + return ret; }
- end_cert = *p + len2; + num_of_certs++;
- /* - * This is to verify that there is only one signer certificate. It seems it is - * not easy to differentiate between the chain vs different signer's certificate. - * So, we support only the root certificate and the single signer. - * The behaviour would be improved with addition of multiple signer support. - */ - if (end_cert != end_set) { - return MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE; - } - - if ((ret = mbedtls_x509_crt_parse_der(certs, start, len1)) < 0) { - return MBEDTLS_ERR_PKCS7_INVALID_CERT; + while (*p != end_set) { + ret = pkcs7_get_one_cert(p, end_set, certs); + if (ret != 0) { + return ret; + } + num_of_certs++; }
- *p = end_cert; + *p = end_set;
- /* - * Since in this version we strictly support single certificate, and reaching - * here implies we have parsed successfully, we return 1. - */ - return 1; + return num_of_certs; }
/**

Update the PKCS7 test suites for multiple certs.
The PR for this patch is at: https://github.com/Mbed-TLS/mbedtls/pull/9001
For enabling EFI loader PKCS7 features with MbedTLS build, we need this patch on top of MbedTLS v3.6.0 before it is merged into the next MbedTLS LTS release.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - None. Changes in v3 - Update commit message. Changes in v4 - None. Changes in v5 - None.
.../external/mbedtls/tests/suites/test_suite_pkcs7.data | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/lib/mbedtls/external/mbedtls/tests/suites/test_suite_pkcs7.data b/lib/mbedtls/external/mbedtls/tests/suites/test_suite_pkcs7.data index d3b83cdf0aa..2dd1c56109f 100644 --- a/lib/mbedtls/external/mbedtls/tests/suites/test_suite_pkcs7.data +++ b/lib/mbedtls/external/mbedtls/tests/suites/test_suite_pkcs7.data @@ -14,9 +14,9 @@ PKCS7 Signed Data Parse with zero signers depends_on:MBEDTLS_MD_CAN_SHA256 pkcs7_parse:"data_files/pkcs7_data_no_signers.der":MBEDTLS_PKCS7_SIGNED_DATA
-PKCS7 Signed Data Parse Fail with multiple certs #4 +PKCS7 Signed Data Parse Pass with multiple certs #4 depends_on:MBEDTLS_MD_CAN_SHA256:MBEDTLS_RSA_C -pkcs7_parse:"data_files/pkcs7_data_multiple_certs_signed.der":MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE +pkcs7_parse:"data_files/pkcs7_data_multiple_certs_signed.der":MBEDTLS_PKCS7_SIGNED_DATA
PKCS7 Signed Data Parse Fail with corrupted cert #5.0 depends_on:MBEDTLS_MD_CAN_SHA256:MBEDTLS_RSA_C

Move public_key_free and public_key_signature_free as helper functions that can be shared by legacy crypto lib and MbedTLS implementation.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v4 - Initial patch. Changes in v5 - Removed authorship.
lib/crypto/Makefile | 4 +++- lib/crypto/public_key.c | 31 --------------------------- lib/crypto/public_key_helper.c | 39 ++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 32 deletions(-) create mode 100644 lib/crypto/public_key_helper.c
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index bec1bc95a65..4ad1849040d 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -7,7 +7,9 @@ obj-$(CONFIG_$(SPL_)ASYMMETRIC_KEY_TYPE) += asymmetric_keys.o
asymmetric_keys-y := asymmetric_type.o
-obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key.o +obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += \ + public_key_helper.o \ + public_key.o
# # RSA public key parser diff --git a/lib/crypto/public_key.c b/lib/crypto/public_key.c index 6efe951c057..408742907f1 100644 --- a/lib/crypto/public_key.c +++ b/lib/crypto/public_key.c @@ -51,38 +51,7 @@ static void public_key_describe(const struct key *asymmetric_key, } #endif
-/* - * Destroy a public key algorithm key. - */ -void public_key_free(struct public_key *key) -{ - if (key) { - kfree(key->key); - kfree(key->params); - kfree(key); - } -} -EXPORT_SYMBOL_GPL(public_key_free); - #ifdef __UBOOT__ -/* - * from <linux>/crypto/asymmetric_keys/signature.c - * - * Destroy a public key signature. - */ -void public_key_signature_free(struct public_key_signature *sig) -{ - int i; - - if (sig) { - for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++) - free(sig->auth_ids[i]); - free(sig->s); - free(sig->digest); - free(sig); - } -} -EXPORT_SYMBOL_GPL(public_key_signature_free);
/** * public_key_verify_signature - Verify a signature using a public key. diff --git a/lib/crypto/public_key_helper.c b/lib/crypto/public_key_helper.c new file mode 100644 index 00000000000..2c55922bdcb --- /dev/null +++ b/lib/crypto/public_key_helper.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * X509 helper functions + * + * Copyright (c) 2012 Red Hat, Inc. All Rights Reserved. + * Written by David Howells (dhowells@redhat.com) + */ +#include <linux/compat.h> +#include <crypto/public_key.h> + +/* + * Destroy a public key algorithm key. + */ +void public_key_free(struct public_key *key) +{ + if (key) { + kfree(key->key); + kfree(key->params); + kfree(key); + } +} + +/* + * from <linux>/crypto/asymmetric_keys/signature.c + * + * Destroy a public key signature. + */ +void public_key_signature_free(struct public_key_signature *sig) +{ + int i; + + if (sig) { + for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++) + kfree(sig->auth_ids[i]); + kfree(sig->s); + kfree(sig->digest); + kfree(sig); + } +}

Move x509_check_for_self_signed as a common helper function that can be shared by legacy crypto lib and MbedTLS implementation.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v4 - Initial patch. Changes in v5 - Removed authorship.
lib/crypto/Makefile | 1 + lib/crypto/x509_helper.c | 64 ++++++++++++++++++++++++++++++++++++ lib/crypto/x509_public_key.c | 56 +------------------------------ 3 files changed, 66 insertions(+), 55 deletions(-) create mode 100644 lib/crypto/x509_helper.c
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index 4ad1849040d..946cc3a7b59 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -37,6 +37,7 @@ x509_key_parser-y := \ x509.asn1.o \ x509_akid.asn1.o \ x509_cert_parser.o \ + x509_helper.o \ x509_public_key.o
$(obj)/x509_cert_parser.o: \ diff --git a/lib/crypto/x509_helper.c b/lib/crypto/x509_helper.c new file mode 100644 index 00000000000..87e8ff67ae1 --- /dev/null +++ b/lib/crypto/x509_helper.c @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * X509 helper functions + * + * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved. + * Written by David Howells (dhowells@redhat.com) + */ +#include <linux/err.h> +#include <crypto/public_key.h> +#include <crypto/x509_parser.h> + +/* + * Check for self-signedness in an X.509 cert and if found, check the signature + * immediately if we can. + */ +int x509_check_for_self_signed(struct x509_certificate *cert) +{ + int ret = 0; + + if (cert->raw_subject_size != cert->raw_issuer_size || + memcmp(cert->raw_subject, cert->raw_issuer, + cert->raw_issuer_size)) + goto not_self_signed; + + if (cert->sig->auth_ids[0] || cert->sig->auth_ids[1]) { + /* + * If the AKID is present it may have one or two parts. If + * both are supplied, both must match. + */ + bool a = asymmetric_key_id_same(cert->skid, + cert->sig->auth_ids[1]); + bool b = asymmetric_key_id_same(cert->id, + cert->sig->auth_ids[0]); + + if (!a && !b) + goto not_self_signed; + + ret = -EKEYREJECTED; + if (((a && !b) || (b && !a)) && + cert->sig->auth_ids[0] && cert->sig->auth_ids[1]) + goto out; + } + + ret = -EKEYREJECTED; + if (strcmp(cert->pub->pkey_algo, cert->sig->pkey_algo)) + goto out; + + ret = public_key_verify_signature(cert->pub, cert->sig); + if (ret == -ENOPKG) { + cert->unsupported_sig = true; + goto not_self_signed; + } + if (ret < 0) + goto out; + + pr_devel("Cert Self-signature verified"); + cert->self_signed = true; + +out: + return ret; + +not_self_signed: + return 0; +} diff --git a/lib/crypto/x509_public_key.c b/lib/crypto/x509_public_key.c index a10145a7cdc..4ba13c1adc3 100644 --- a/lib/crypto/x509_public_key.c +++ b/lib/crypto/x509_public_key.c @@ -139,61 +139,7 @@ error: return ret; }
-/* - * Check for self-signedness in an X.509 cert and if found, check the signature - * immediately if we can. - */ -int x509_check_for_self_signed(struct x509_certificate *cert) -{ - int ret = 0; - - pr_devel("==>%s()\n", __func__); - - if (cert->raw_subject_size != cert->raw_issuer_size || - memcmp(cert->raw_subject, cert->raw_issuer, - cert->raw_issuer_size) != 0) - goto not_self_signed; - - if (cert->sig->auth_ids[0] || cert->sig->auth_ids[1]) { - /* If the AKID is present it may have one or two parts. If - * both are supplied, both must match. - */ - bool a = asymmetric_key_id_same(cert->skid, cert->sig->auth_ids[1]); - bool b = asymmetric_key_id_same(cert->id, cert->sig->auth_ids[0]); - - if (!a && !b) - goto not_self_signed; - - ret = -EKEYREJECTED; - if (((a && !b) || (b && !a)) && - cert->sig->auth_ids[0] && cert->sig->auth_ids[1]) - goto out; - } - - ret = -EKEYREJECTED; - if (strcmp(cert->pub->pkey_algo, cert->sig->pkey_algo) != 0) - goto out; - - ret = public_key_verify_signature(cert->pub, cert->sig); - if (ret < 0) { - if (ret == -ENOPKG) { - cert->unsupported_sig = true; - ret = 0; - } - goto out; - } - - pr_devel("Cert Self-signature verified"); - cert->self_signed = true; - -out: - pr_devel("<==%s() = %d\n", __func__, ret); - return ret; - -not_self_signed: - pr_devel("<==%s() = 0 [not]\n", __func__); - return 0; -} +#endif /* !CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) */
#ifndef __UBOOT__ /*

Move pkcs7_get_content_data as a helper function that can be shared by legacy crypto lib and MbedTLS implementation.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v4 - Initial patch. Changes in v5 - Remove authorship.
lib/crypto/Makefile | 1 + lib/crypto/pkcs7_helper.c | 37 +++++++++++++++++++++++++++++++++++++ lib/crypto/pkcs7_parser.c | 28 ---------------------------- 3 files changed, 38 insertions(+), 28 deletions(-) create mode 100644 lib/crypto/pkcs7_helper.c
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index 946cc3a7b59..16059088f26 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -53,6 +53,7 @@ $(obj)/x509_akid.asn1.o: $(obj)/x509_akid.asn1.c $(obj)/x509_akid.asn1.h obj-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER) += pkcs7_message.o pkcs7_message-y := \ pkcs7.asn1.o \ + pkcs7_helper.o \ pkcs7_parser.o obj-$(CONFIG_$(SPL_)PKCS7_VERIFY) += pkcs7_verify.o
diff --git a/lib/crypto/pkcs7_helper.c b/lib/crypto/pkcs7_helper.c new file mode 100644 index 00000000000..bb3b9d1354f --- /dev/null +++ b/lib/crypto/pkcs7_helper.c @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * PKCS7 helper functions + * + * Copyright (c) 2012 Red Hat, Inc. All Rights Reserved. + * Written by David Howells (dhowells@redhat.com) + */ +#include <linux/kernel.h> +#include <linux/err.h> +#include <crypto/pkcs7_parser.h> + +/** + * pkcs7_get_content_data - Get access to the PKCS#7 content + * @pkcs7: The preparsed PKCS#7 message to access + * @_data: Place to return a pointer to the data + * @_data_len: Place to return the data length + * @_headerlen: Size of ASN.1 header not included in _data + * + * Get access to the data content of the PKCS#7 message. The size of the + * header of the ASN.1 object that contains it is also provided and can be used + * to adjust *_data and *_data_len to get the entire object. + * + * Returns -ENODATA if the data object was missing from the message. + */ +int pkcs7_get_content_data(const struct pkcs7_message *pkcs7, + const void **_data, size_t *_data_len, + size_t *_headerlen) +{ + if (!pkcs7->data) + return -ENODATA; + + *_data = pkcs7->data; + *_data_len = pkcs7->data_len; + if (_headerlen) + *_headerlen = pkcs7->data_hdrlen; + return 0; +} diff --git a/lib/crypto/pkcs7_parser.c b/lib/crypto/pkcs7_parser.c index d5efa828d6a..c849dc0d92d 100644 --- a/lib/crypto/pkcs7_parser.c +++ b/lib/crypto/pkcs7_parser.c @@ -182,34 +182,6 @@ out_no_ctx: } EXPORT_SYMBOL_GPL(pkcs7_parse_message);
-/** - * pkcs7_get_content_data - Get access to the PKCS#7 content - * @pkcs7: The preparsed PKCS#7 message to access - * @_data: Place to return a pointer to the data - * @_data_len: Place to return the data length - * @_headerlen: Size of ASN.1 header not included in _data - * - * Get access to the data content of the PKCS#7 message. The size of the - * header of the ASN.1 object that contains it is also provided and can be used - * to adjust *_data and *_data_len to get the entire object. - * - * Returns -ENODATA if the data object was missing from the message. - */ -int pkcs7_get_content_data(const struct pkcs7_message *pkcs7, - const void **_data, size_t *_data_len, - size_t *_headerlen) -{ - if (!pkcs7->data) - return -ENODATA; - - *_data = pkcs7->data; - *_data_len = pkcs7->data_len; - if (_headerlen) - *_headerlen = pkcs7->data_hdrlen; - return 0; -} -EXPORT_SYMBOL_GPL(pkcs7_get_content_data); - /* * Note an OID when we find one for later processing when we know how * to interpret it.

Add porting layer for public key on top of MbedTLS X509 library. Introduce _LEGACY and _MBEDTLS kconfigs for public key legacy and MbedTLS implementations respectively.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. Changes in v3 - None. Changes in v4 - Introduce _LEGACY and _MBEDTLS kconfigs for public key legacy and MbedTLS implementations respectively. - Move common functions to helper. Changes in v5 - Correct kconfig dependence. - Kconfig rename. - Refactored MbedTLS makefile. - Adjust a few inline comments.
lib/mbedtls/Kconfig | 52 +++++++++++++++++++++++++ lib/mbedtls/Makefile | 6 ++- lib/mbedtls/public_key.c | 82 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 lib/mbedtls/public_key.c
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index 12f8c965f5a..e95b722c6e8 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -117,9 +117,35 @@ endif # LEGACY_CRYPTO_BASIC
config LEGACY_CRYPTO_CERT bool "legacy certificate libraries" + select ASYMMETRIC_PUBLIC_KEY_LEGACY if \ + ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY if \ + SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help Enable legacy certificate libraries.
+if LEGACY_CRYPTO_CERT + +config ASYMMETRIC_PUBLIC_KEY_LEGACY + bool "Asymmetric public key crypto with legacy certificate library" + depends on LEGACY_CRYPTO_CERT && ASYMMETRIC_PUBLIC_KEY_SUBTYPE + help + This option chooses legacy certificate library for asymmetric public + key crypto algorithm. + +if SPL + +config SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY + bool "Asymmetric public key crypto with legacy certificate library in SPL" + depends on LEGACY_CRYPTO_CERT && SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE + help + This option chooses legacy certificate library for asymmetric public + key crypto algorithm in SPL. + +endif # SPL + +endif # LEGACY_CRYPTO_CERT + endif # LEGACY_CRYPTO
if MBEDTLS_LIB @@ -222,7 +248,33 @@ endif # MBEDTLS_LIB_CRYPTO
config MBEDTLS_LIB_X509 bool "MbedTLS certificate libraries" + select ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ + ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ + SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help Enable MbedTLS certificate libraries.
+if MBEDTLS_LIB_X509 + +config ASYMMETRIC_PUBLIC_KEY_MBEDTLS + bool "Asymmetric public key crypto with MbedTLS certificate library" + depends on MBEDTLS_LIB_X509 && ASYMMETRIC_PUBLIC_KEY_SUBTYPE + help + This option chooses MbedTLS certificate library for asymmetric public + key crypto algorithm. + +if SPL + +config SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS + bool "Asymmetric public key crypto with MbedTLS certificate library in SPL" + depends on MBEDTLS_LIB_X509 && SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE + help + This option chooses MbedTLS certificate library for asymmetric public + key crypto algorithm in SPL. + +endif # SPL + +endif # MBEDTLS_LIB_X509 + endif # MBEDTLS_LIB diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile index 50c1ba5f88e..2d2220dd4fd 100644 --- a/lib/mbedtls/Makefile +++ b/lib/mbedtls/Makefile @@ -11,6 +11,10 @@ obj-$(CONFIG_$(SPL_)SHA1_MBEDTLS) += sha1.o obj-$(CONFIG_$(SPL_)SHA256_MBEDTLS) += sha256.o obj-$(CONFIG_$(SPL_)SHA512_MBEDTLS) += sha512.o
+# x509 libraries +obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \ + public_key.o + # MbedTLS crypto library obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o mbedtls_lib_crypto-y := \ @@ -36,7 +40,7 @@ mbedtls_lib_x509-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER) += \ $(MBEDTLS_LIB_DIR)/bignum_core.o \ $(MBEDTLS_LIB_DIR)/rsa.o \ $(MBEDTLS_LIB_DIR)/rsa_alt_helpers.o -mbedtls_lib_x509-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += \ +mbedtls_lib_x509-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/pk.o \ $(MBEDTLS_LIB_DIR)/pk_wrap.o \ $(MBEDTLS_LIB_DIR)/pkparse.o diff --git a/lib/mbedtls/public_key.c b/lib/mbedtls/public_key.c new file mode 100644 index 00000000000..5f73b99d4f2 --- /dev/null +++ b/lib/mbedtls/public_key.c @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Public key helper functions using MbedTLS X509 library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#include <linux/compat.h> +#include <crypto/public_key.h> + +int public_key_verify_signature(const struct public_key *pkey, + const struct public_key_signature *sig) +{ + mbedtls_md_type_t mb_hash_algo; + mbedtls_pk_context pk_ctx; + int ret; + + if (!pkey || !sig || pkey->key_is_private) + return -EINVAL; + + /* + * ECRDSA (Elliptic Curve Russian Digital Signature Algorithm) is not + * supported by MbedTLS. + */ + if (strcmp(pkey->pkey_algo, "rsa")) { + pr_err("Encryption is not RSA: %s\n", sig->pkey_algo); + return -EINVAL; + } + + /* + * Can be pkcs1 or raw, but pkcs1 is expected. + * This is just for argument checking, not necessarily passed to MbedTLS, + * For RSA signatures, MbedTLS typically supports the PKCS#1 v1.5 + * (aka. pkcs1) encoding by default. + * The library internally handles the details of decoding and verifying + * the signature according to the expected encoding for the specified algorithm. + */ + if (strcmp(sig->encoding, "pkcs1")) { + pr_err("Encoding %s is not supported, only supports pkcs1\n", + sig->encoding); + return -EINVAL; + } + + if (!strcmp(sig->hash_algo, "sha1")) + mb_hash_algo = MBEDTLS_MD_SHA1; + else if (!strcmp(sig->hash_algo, "sha224")) + mb_hash_algo = MBEDTLS_MD_SHA224; + else if (!strcmp(sig->hash_algo, "sha256")) + mb_hash_algo = MBEDTLS_MD_SHA256; + else if (!strcmp(sig->hash_algo, "sha384")) + mb_hash_algo = MBEDTLS_MD_SHA384; + else if (!strcmp(sig->hash_algo, "sha512")) + mb_hash_algo = MBEDTLS_MD_SHA512; + else /* Unknown or unsupported hash algorithm */ + return -EINVAL; + /* Initialize the mbedtls_pk_context with RSA key type */ + mbedtls_pk_init(&pk_ctx); + + /* Parse the DER-encoded public key */ + ret = mbedtls_pk_parse_public_key(&pk_ctx, pkey->key, pkey->keylen); + if (ret) { + pr_err("Failed to parse public key, ret:-0x%04x\n", -ret); + ret = -EINVAL; + goto err_key; + } + + /* Ensure that it is a RSA key */ + if (mbedtls_pk_get_type(&pk_ctx) != MBEDTLS_PK_RSA) { + pr_err("Only RSA keys are supported\n"); + ret = -EKEYREJECTED; + goto err_key; + } + + /* Verify the hash */ + ret = mbedtls_pk_verify(&pk_ctx, mb_hash_algo, sig->digest, + sig->digest_size, sig->s, sig->s_size); + +err_key: + mbedtls_pk_free(&pk_ctx); + return ret; +}

Previous patch has introduced MbedTLS porting layer for public key, here to adjust the header and makefiles accordingly.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. Changes in v3 - Update commit message. Changes in v4 - Control building legacy library via '_LEGACY' Kconfig. Changes in v5 - Correct header file include directories. - Kconfig rename.
include/crypto/public_key.h | 6 ++++++ lib/crypto/Makefile | 5 ++--- lib/crypto/asymmetric_type.c | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-)
diff --git a/include/crypto/public_key.h b/include/crypto/public_key.h index 3ba90fcc348..25cfb68adce 100644 --- a/include/crypto/public_key.h +++ b/include/crypto/public_key.h @@ -12,6 +12,12 @@
#ifdef __UBOOT__ #include <linux/types.h> +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) +#include <library/common.h> +#include <mbedtls/pk.h> +#include <mbedtls/x509_crt.h> +#include <mbedtls/md.h> +#endif #else #include <linux/keyctl.h> #endif diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index 16059088f26..7e877214aa8 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -7,9 +7,8 @@ obj-$(CONFIG_$(SPL_)ASYMMETRIC_KEY_TYPE) += asymmetric_keys.o
asymmetric_keys-y := asymmetric_type.o
-obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += \ - public_key_helper.o \ - public_key.o +obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key_helper.o +obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_LEGACY) += public_key.o
# # RSA public key parser diff --git a/lib/crypto/asymmetric_type.c b/lib/crypto/asymmetric_type.c index 24c2d15ef97..95b82cd8e84 100644 --- a/lib/crypto/asymmetric_type.c +++ b/lib/crypto/asymmetric_type.c @@ -12,7 +12,6 @@ #include <keys/asymmetric-subtype.h> #include <keys/asymmetric-parser.h> #endif -#include <crypto/public_key.h> #ifdef __UBOOT__ #include <linux/bug.h> #include <linux/compat.h> @@ -26,6 +25,7 @@ #include <linux/slab.h> #include <linux/ctype.h> #endif +#include <crypto/public_key.h> #ifdef __UBOOT__ #include <keys/asymmetric-type.h> #else

Add porting layer for X509 cert parser on top of MbedTLS X509 library. Introduce _LEGACY and _MBEDTLS kconfigs for X509 cert parser legacy and MbedTLS implementations respectively.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. Changes in v3 - None. Changes in v4 - Introduce _LEGACY and _MBEDTLS kconfigs for X509 cert parser legacy and MbedTLS implementations respectively. - Move common functions to helper. Changes in v5 - Kconfig rename. - Adjust a few inline comments.
lib/mbedtls/Kconfig | 18 ++ lib/mbedtls/Makefile | 4 +- lib/mbedtls/x509_cert_parser.c | 447 +++++++++++++++++++++++++++++++++ 3 files changed, 468 insertions(+), 1 deletion(-) create mode 100644 lib/mbedtls/x509_cert_parser.c
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index e95b722c6e8..66de9d1c15f 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -119,6 +119,7 @@ config LEGACY_CRYPTO_CERT bool "legacy certificate libraries" select ASYMMETRIC_PUBLIC_KEY_LEGACY if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select X509_CERTIFICATE_PARSER_LEGACY if X509_CERTIFICATE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help @@ -133,6 +134,14 @@ config ASYMMETRIC_PUBLIC_KEY_LEGACY This option chooses legacy certificate library for asymmetric public key crypto algorithm.
+config X509_CERTIFICATE_PARSER_LEGACY + bool "X.509 certificate parser with legacy certificate library" + depends on ASYMMETRIC_PUBLIC_KEY_LEGACY + select ASN1_DECODER_LEGACY + help + This option chooses legacy certificate library for X509 certificate + parser. + if SPL
config SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY @@ -250,6 +259,7 @@ config MBEDTLS_LIB_X509 bool "MbedTLS certificate libraries" select ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select X509_CERTIFICATE_PARSER_MBEDTLS if X509_CERTIFICATE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help @@ -264,6 +274,14 @@ config ASYMMETRIC_PUBLIC_KEY_MBEDTLS This option chooses MbedTLS certificate library for asymmetric public key crypto algorithm.
+config X509_CERTIFICATE_PARSER_MBEDTLS + bool "X.509 certificate parser with MbedTLS certificate library" + depends on ASYMMETRIC_PUBLIC_KEY_MBEDTLS + select ASN1_DECODER_MBEDTLS + help + This option chooses MbedTLS certificate library for X509 certificate + parser. + if SPL
config SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile index 2d2220dd4fd..ab64365a99a 100644 --- a/lib/mbedtls/Makefile +++ b/lib/mbedtls/Makefile @@ -14,6 +14,8 @@ obj-$(CONFIG_$(SPL_)SHA512_MBEDTLS) += sha512.o # x509 libraries obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \ public_key.o +obj-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \ + x509_cert_parser.o
# MbedTLS crypto library obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o @@ -44,7 +46,7 @@ mbedtls_lib_x509-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/pk.o \ $(MBEDTLS_LIB_DIR)/pk_wrap.o \ $(MBEDTLS_LIB_DIR)/pkparse.o -mbedtls_lib_x509-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER) += \ +mbedtls_lib_x509-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/x509_crl.o \ $(MBEDTLS_LIB_DIR)/x509_crt.o mbedtls_lib_x509-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER) += \ diff --git a/lib/mbedtls/x509_cert_parser.c b/lib/mbedtls/x509_cert_parser.c new file mode 100644 index 00000000000..cb42018695c --- /dev/null +++ b/lib/mbedtls/x509_cert_parser.c @@ -0,0 +1,447 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * X509 cert parser using MbedTLS X509 library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#include <linux/err.h> +#include <crypto/public_key.h> +#include <crypto/x509_parser.h> + +static void x509_free_mbedtls_ctx(struct x509_cert_mbedtls_ctx *ctx) +{ + if (!ctx) + return; + + kfree(ctx->tbs); + kfree(ctx->raw_serial); + kfree(ctx->raw_issuer); + kfree(ctx->raw_subject); + kfree(ctx->raw_skid); + kfree(ctx); +} + +static int x509_set_cert_flags(struct x509_certificate *cert) +{ + struct public_key_signature *sig = cert->sig; + + if (!sig || !cert->pub) { + pr_err("Signature or public key is not initialized\n"); + return -ENOPKG; + } + + if (!cert->pub->pkey_algo) + cert->unsupported_key = true; + + if (!sig->pkey_algo) + cert->unsupported_sig = true; + + if (!sig->hash_algo) + cert->unsupported_sig = true; + + /* TODO: is_hash_blacklisted()? */ + + /* Detect self-signed certificates and set self_signed flag */ + return x509_check_for_self_signed(cert); +} + +time64_t x509_get_timestamp(const mbedtls_x509_time *x509_time) +{ + unsigned int year, mon, day, hour, min, sec; + + /* Adjust for year since 1900 */ + year = x509_time->year - 1900; + /* Adjust for 0-based month */ + mon = x509_time->mon - 1; + day = x509_time->day; + hour = x509_time->hour; + min = x509_time->min; + sec = x509_time->sec; + + return (time64_t)mktime64(year, mon, day, hour, min, sec); +} + +static char *x509_populate_dn_name_string(const mbedtls_x509_name *name) +{ + size_t len = 256; + size_t wb; + char *name_str; + + do { + name_str = kzalloc(len, GFP_KERNEL); + if (!name_str) + return NULL; + + wb = mbedtls_x509_dn_gets(name_str, len, name); + if (wb < 0) { + pr_err("Get DN string failed, ret:-0x%04x\n", + (unsigned int)-wb); + kfree(name_str); + len = len * 2; /* Try with a bigger buffer */ + } + } while (wb < 0); + + name_str[wb] = '\0'; /* add the terminator */ + + return name_str; +} + +static int x509_populate_signature_params(const mbedtls_x509_crt *cert, + struct public_key_signature **sig) +{ + struct public_key_signature *s; + struct image_region region; + size_t akid_len; + unsigned char *akid_data; + int ret; + + /* Check if signed data exist */ + if (!cert->tbs.p || !cert->tbs.len) + return -EINVAL; + + region.data = cert->tbs.p; + region.size = cert->tbs.len; + + s = kzalloc(sizeof(*s), GFP_KERNEL); + if (!s) + return -ENOMEM; + + /* + * Get the public key algorithm. + * Note: + * ECRDSA (Elliptic Curve Russian Digital Signature Algorithm) is not + * supported by MbedTLS. + */ + switch (cert->sig_pk) { + case MBEDTLS_PK_RSA: + s->pkey_algo = "rsa"; + break; + default: + ret = -EINVAL; + goto error_sig; + } + + /* Get the hash algorithm */ + switch (cert->sig_md) { + case MBEDTLS_MD_SHA1: + s->hash_algo = "sha1"; + s->digest_size = SHA1_SUM_LEN; + break; + case MBEDTLS_MD_SHA256: + s->hash_algo = "sha256"; + s->digest_size = SHA256_SUM_LEN; + break; + case MBEDTLS_MD_SHA384: + s->hash_algo = "sha384"; + s->digest_size = SHA384_SUM_LEN; + break; + case MBEDTLS_MD_SHA512: + s->hash_algo = "sha512"; + s->digest_size = SHA512_SUM_LEN; + break; + /* Unsupported algo */ + case MBEDTLS_MD_MD5: + case MBEDTLS_MD_SHA224: + default: + ret = -EINVAL; + goto error_sig; + } + + /* + * Optional attributes: + * auth_ids holds AuthorityKeyIdentifier (information of issuer), + * aka akid, which is used to match with a cert's id or skid to + * indicate that is the issuer when we lookup a cert chain. + * + * auth_ids[0]: + * [PKCS#7 or CMS ver 1] - generated from "Issuer + Serial number" + * [CMS ver 3] - generated from skid (subjectKeyId) + * auth_ids[1]: generated from skid (subjectKeyId) + * + * Assume that we are using PKCS#7 (msg->version=1), + * not CMS ver 3 (msg->version=3). + */ + akid_len = cert->authority_key_id.authorityCertSerialNumber.len; + akid_data = cert->authority_key_id.authorityCertSerialNumber.p; + + /* Check if serial number exists */ + if (akid_len && akid_data) { + s->auth_ids[0] = asymmetric_key_generate_id(akid_data, + akid_len, + cert->issuer_raw.p, + cert->issuer_raw.len); + if (!s->auth_ids[0]) { + ret = -ENOMEM; + goto error_sig; + } + } + + akid_len = cert->authority_key_id.keyIdentifier.len; + akid_data = cert->authority_key_id.keyIdentifier.p; + + /* Check if subjectKeyId exists */ + if (akid_len && akid_data) { + s->auth_ids[1] = asymmetric_key_generate_id(akid_data, + akid_len, + "", 0); + if (!s->auth_ids[1]) { + ret = -ENOMEM; + goto error_sig; + } + } + + /* + * Encoding can be pkcs1 or raw, but only pkcs1 is supported. + * Set the encoding explicitly to pkcs1. + */ + s->encoding = "pkcs1"; + + /* Copy the signature data */ + s->s = kmemdup(cert->sig.p, cert->sig.len, GFP_KERNEL); + if (!s->s) { + ret = -ENOMEM; + goto error_sig; + } + s->s_size = cert->sig.len; + + /* Calculate the digest of signed data (tbs) */ + s->digest = kzalloc(s->digest_size, GFP_KERNEL); + if (!s->digest) { + ret = -ENOMEM; + goto error_sig; + } + + ret = hash_calculate(s->hash_algo, ®ion, 1, s->digest); + if (!ret) + *sig = s; + + return ret; + +error_sig: + public_key_signature_free(s); + return ret; +} + +static int x509_save_mbedtls_ctx(const mbedtls_x509_crt *cert, + struct x509_cert_mbedtls_ctx **pctx) +{ + struct x509_cert_mbedtls_ctx *ctx; + + ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); + if (!ctx) + return -ENOMEM; + + /* Signed data (tbs - The part that is To Be Signed)*/ + ctx->tbs = kmemdup(cert->tbs.p, cert->tbs.len, + GFP_KERNEL); + if (!ctx->tbs) + goto error_ctx; + + /* Raw serial number */ + ctx->raw_serial = kmemdup(cert->serial.p, + cert->serial.len, GFP_KERNEL); + if (!ctx->raw_serial) + goto error_ctx; + + /* Raw issuer */ + ctx->raw_issuer = kmemdup(cert->issuer_raw.p, + cert->issuer_raw.len, GFP_KERNEL); + if (!ctx->raw_issuer) + goto error_ctx; + + /* Raw subject */ + ctx->raw_subject = kmemdup(cert->subject_raw.p, + cert->subject_raw.len, GFP_KERNEL); + if (!ctx->raw_subject) + goto error_ctx; + + /* Raw subjectKeyId */ + ctx->raw_skid = kmemdup(cert->subject_key_id.p, + cert->subject_key_id.len, GFP_KERNEL); + if (!ctx->raw_skid) + goto error_ctx; + + *pctx = ctx; + + return 0; + +error_ctx: + x509_free_mbedtls_ctx(ctx); + return -ENOMEM; +} + +/* + * Free an X.509 certificate + */ +void x509_free_certificate(struct x509_certificate *cert) +{ + if (cert) { + public_key_free(cert->pub); + public_key_signature_free(cert->sig); + kfree(cert->issuer); + kfree(cert->subject); + kfree(cert->id); + kfree(cert->skid); + x509_free_mbedtls_ctx(cert->mbedtls_ctx); + kfree(cert); + } +} + +int x509_populate_pubkey(mbedtls_x509_crt *cert, struct public_key **pub_key) +{ + struct public_key *pk; + + pk = kzalloc(sizeof(*pk), GFP_KERNEL); + if (!pk) + return -ENOMEM; + + pk->key = kzalloc(cert->pk_raw.len, GFP_KERNEL); + if (!pk->key) { + kfree(pk); + return -ENOMEM; + } + memcpy(pk->key, cert->pk_raw.p, cert->pk_raw.len); + pk->keylen = cert->pk_raw.len; + + /* + * For ECC keys, params field might include information about the curve used, + * the generator point, or other algorithm-specific parameters. + * For RSA keys, it's common for the params field to be NULL. + * FIXME: Assume that we just support RSA keys with id_type X509. + */ + pk->params = NULL; + pk->paramlen = 0; + + pk->key_is_private = false; + pk->id_type = "X509"; + pk->pkey_algo = "rsa"; + pk->algo = OID_rsaEncryption; + + *pub_key = pk; + + return 0; +} + +int x509_populate_cert(mbedtls_x509_crt *mbedtls_cert, + struct x509_certificate **pcert) +{ + struct x509_certificate *cert; + struct asymmetric_key_id *kid; + struct asymmetric_key_id *skid; + int ret; + + cert = kzalloc(sizeof(*cert), GFP_KERNEL); + if (!cert) + return -ENOMEM; + + /* Public key details */ + ret = x509_populate_pubkey(mbedtls_cert, &cert->pub); + if (ret) + goto error_cert_pop; + + /* Signature parameters */ + ret = x509_populate_signature_params(mbedtls_cert, &cert->sig); + if (ret) + goto error_cert_pop; + + ret = -ENOMEM; + + /* Name of certificate issuer */ + cert->issuer = x509_populate_dn_name_string(&mbedtls_cert->issuer); + if (!cert->issuer) + goto error_cert_pop; + + /* Name of certificate subject */ + cert->subject = x509_populate_dn_name_string(&mbedtls_cert->subject); + if (!cert->subject) + goto error_cert_pop; + + /* Certificate validity */ + cert->valid_from = x509_get_timestamp(&mbedtls_cert->valid_from); + cert->valid_to = x509_get_timestamp(&mbedtls_cert->valid_to); + + /* Save mbedtls context we need */ + ret = x509_save_mbedtls_ctx(mbedtls_cert, &cert->mbedtls_ctx); + if (ret) + goto error_cert_pop; + + /* Signed data (tbs - The part that is To Be Signed)*/ + cert->tbs = cert->mbedtls_ctx->tbs; + cert->tbs_size = mbedtls_cert->tbs.len; + + /* Raw serial number */ + cert->raw_serial = cert->mbedtls_ctx->raw_serial; + cert->raw_serial_size = mbedtls_cert->serial.len; + + /* Raw issuer */ + cert->raw_issuer = cert->mbedtls_ctx->raw_issuer; + cert->raw_issuer_size = mbedtls_cert->issuer_raw.len; + + /* Raw subject */ + cert->raw_subject = cert->mbedtls_ctx->raw_subject; + cert->raw_subject_size = mbedtls_cert->subject_raw.len; + + /* Raw subjectKeyId */ + cert->raw_skid = cert->mbedtls_ctx->raw_skid; + cert->raw_skid_size = mbedtls_cert->subject_key_id.len; + + /* Generate cert issuer + serial number key ID */ + kid = asymmetric_key_generate_id(cert->raw_serial, + cert->raw_serial_size, + cert->raw_issuer, + cert->raw_issuer_size); + if (IS_ERR(kid)) { + ret = PTR_ERR(kid); + goto error_cert_pop; + } + cert->id = kid; + + /* Generate subject + subjectKeyId */ + skid = asymmetric_key_generate_id(cert->raw_skid, cert->raw_skid_size, "", 0); + if (IS_ERR(skid)) { + ret = PTR_ERR(skid); + goto error_cert_pop; + } + cert->skid = skid; + + /* + * Set the certificate flags: + * self_signed, unsupported_key, unsupported_sig, blacklisted + */ + ret = x509_set_cert_flags(cert); + if (!ret) { + *pcert = cert; + return 0; + } + +error_cert_pop: + x509_free_certificate(cert); + return ret; +} + +struct x509_certificate *x509_cert_parse(const void *data, size_t datalen) +{ + mbedtls_x509_crt mbedtls_cert; + struct x509_certificate *cert = NULL; + long ret; + + /* Parse DER encoded certificate */ + mbedtls_x509_crt_init(&mbedtls_cert); + ret = mbedtls_x509_crt_parse_der(&mbedtls_cert, data, datalen); + if (ret) + goto clean_up_ctx; + + /* Populate x509_certificate from mbedtls_x509_crt */ + ret = x509_populate_cert(&mbedtls_cert, &cert); + if (ret) + goto clean_up_ctx; + +clean_up_ctx: + mbedtls_x509_crt_free(&mbedtls_cert); + if (!ret) + return cert; + + return ERR_PTR(ret); +}

Previous patch has introduced MbedTLS porting layer for x509 cert parser, here to adjust the header and makefiles accordingly.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. Changes in v3 - Update commit message. Changes in v4 - Control building legacy library via '_LEGACY' Kconfig. - Add function comments for the new APIs. Changes in v5 - Correct kconfig dependence. - Correct header file include directories. - Adjust a few inline comments.
include/crypto/x509_parser.h | 55 ++++++++++++++++++++++++++++++++++++ lib/crypto/Kconfig | 2 +- lib/crypto/Makefile | 4 +-- lib/crypto/x509_public_key.c | 2 ++ 4 files changed, 60 insertions(+), 3 deletions(-)
diff --git a/include/crypto/x509_parser.h b/include/crypto/x509_parser.h index 4cbdc1d6612..0e22e33f66b 100644 --- a/include/crypto/x509_parser.h +++ b/include/crypto/x509_parser.h @@ -11,8 +11,35 @@ #include <linux/time.h> #include <crypto/public_key.h> #include <keys/asymmetric-type.h> +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) +#include <image.h> +#include <mbedtls/error.h> +#include <mbedtls/asn1.h> +#endif
+#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) +struct x509_cert_mbedtls_ctx { + void *tbs; /* Signed data */ + void *raw_serial; /* Raw serial number in ASN.1 */ + void *raw_issuer; /* Raw issuer name in ASN.1 */ + void *raw_subject; /* Raw subject name in ASN.1 */ + void *raw_skid; /* Raw subjectKeyId in ASN.1 */ +}; +#endif + +/* + * MbedTLS integration Notes: + * + * Fields we don't need to populate from MbedTLS context: + * 'raw_sig' and 'raw_sig_size' are buffer for x509_parse_context, + * not needed for MbedTLS. + * 'signer' and 'seen' are used internally by pkcs7_verify. + * 'verified' is not in use. + */ struct x509_certificate { +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) + struct x509_cert_mbedtls_ctx *mbedtls_ctx; +#endif struct x509_certificate *next; struct x509_certificate *signer; /* Certificate that signed this one */ struct public_key *pub; /* Public key details */ @@ -48,6 +75,32 @@ struct x509_certificate { * x509_cert_parser.c */ extern void x509_free_certificate(struct x509_certificate *cert); +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) +/** + * x509_populate_pubkey() - Populate public key from MbedTLS context + * + * @cert: Pointer to MbedTLS X509 cert + * @pub_key: Pointer to the populated public key handle + * Return: 0 on succcess, error code on failure + */ +int x509_populate_pubkey(mbedtls_x509_crt *cert, struct public_key **pub_key); +/** + * x509_populate_cert() - Populate X509 cert from MbedTLS context + * + * @mbedtls_cert: Pointer to MbedTLS X509 cert + * @pcert: Pointer to the populated X509 cert handle + * Return: 0 on succcess, error code on failure + */ +int x509_populate_cert(mbedtls_x509_crt *mbedtls_cert, + struct x509_certificate **pcert); +/** + * x509_get_timestamp() - Translate timestamp from MbedTLS context + * + * @x509_time: Pointer to MbedTLS time + * Return: Time in time64_t format + */ +time64_t x509_get_timestamp(const mbedtls_x509_time *x509_time); +#endif extern struct x509_certificate *x509_cert_parse(const void *data, size_t datalen); extern int x509_decode_time(time64_t *_t, size_t hdrlen, unsigned char tag, @@ -56,6 +109,8 @@ extern int x509_decode_time(time64_t *_t, size_t hdrlen, /* * x509_public_key.c */ +#if !CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) extern int x509_get_sig_params(struct x509_certificate *cert); +#endif extern int x509_check_for_self_signed(struct x509_certificate *cert); #endif /* _X509_PARSER_H */ diff --git a/lib/crypto/Kconfig b/lib/crypto/Kconfig index 6e0656ad1c5..6106190677e 100644 --- a/lib/crypto/Kconfig +++ b/lib/crypto/Kconfig @@ -1,6 +1,6 @@ menuconfig ASYMMETRIC_KEY_TYPE bool "Asymmetric (public-key cryptographic) key Support" - depends on FIT_SIGNATURE + depends on LEGACY_CRYPTO_CERT || MBEDTLS_LIB_X509 help This option provides support for a key type that holds the data for the asymmetric keys used for public key cryptographic operations such diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index 7e877214aa8..4302f197297 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -32,11 +32,11 @@ endif # X.509 Certificate handling # obj-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER) += x509_key_parser.o -x509_key_parser-y := \ +x509_key_parser-y := x509_helper.o +x509_key_parser-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_LEGACY) += \ x509.asn1.o \ x509_akid.asn1.o \ x509_cert_parser.o \ - x509_helper.o \ x509_public_key.o
$(obj)/x509_cert_parser.o: \ diff --git a/lib/crypto/x509_public_key.c b/lib/crypto/x509_public_key.c index 4ba13c1adc3..310edbd21be 100644 --- a/lib/crypto/x509_public_key.c +++ b/lib/crypto/x509_public_key.c @@ -30,6 +30,8 @@ #include "x509_parser.h" #endif
+#if !CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) + /* * Set up the signature parameters in an X.509 certificate. This involves * digesting the signed data and extracting the signature.

Add porting layer for PKCS7 parser on top of MbedTLS PKCS7 library. Introduce _LEGACY and _MBEDTLS kconfigs for PKCS7 parser legacy and MbedTLS implementations respectively.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. - Fix EFI Capsule CI test failures. Changes in v3 - None. Changes in v4 - Introduce _LEGACY and _MBEDTLS kconfigs for PKCS7 parser legacy and MbedTLS implementations respectively. - Move common functions to helper. - Fix an unnecessary pointer casting. Changes in v5 - Refactored MbedTLS makefile.
lib/mbedtls/Kconfig | 18 ++ lib/mbedtls/Makefile | 3 +- lib/mbedtls/pkcs7_parser.c | 506 +++++++++++++++++++++++++++++++++++++ 3 files changed, 526 insertions(+), 1 deletion(-) create mode 100644 lib/mbedtls/pkcs7_parser.c
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index 66de9d1c15f..4a65f6ab488 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -120,6 +120,7 @@ config LEGACY_CRYPTO_CERT select ASYMMETRIC_PUBLIC_KEY_LEGACY if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE select X509_CERTIFICATE_PARSER_LEGACY if X509_CERTIFICATE_PARSER + select PKCS7_MESSAGE_PARSER_LEGACY if PKCS7_MESSAGE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help @@ -142,6 +143,14 @@ config X509_CERTIFICATE_PARSER_LEGACY This option chooses legacy certificate library for X509 certificate parser.
+config PKCS7_MESSAGE_PARSER_LEGACY + bool "PKCS#7 message parser with legacy certificate library" + depends on X509_CERTIFICATE_PARSER_LEGACY + select ASN1_DECODER_LEGACY + help + This option chooses legacy certificate library for PKCS7 message + parser. + if SPL
config SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY @@ -260,6 +269,7 @@ config MBEDTLS_LIB_X509 select ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE select X509_CERTIFICATE_PARSER_MBEDTLS if X509_CERTIFICATE_PARSER + select PKCS7_MESSAGE_PARSER_MBEDTLS if PKCS7_MESSAGE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help @@ -282,6 +292,14 @@ config X509_CERTIFICATE_PARSER_MBEDTLS This option chooses MbedTLS certificate library for X509 certificate parser.
+config PKCS7_MESSAGE_PARSER_MBEDTLS + bool "PKCS#7 message parser with MbedTLS certificate library" + depends on X509_CERTIFICATE_PARSER_MBEDTLS + select ASN1_DECODER_MBEDTLS + help + This option chooses MbedTLS certificate library for PKCS7 message + parser. + if SPL
config SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile index ab64365a99a..36eba07bf43 100644 --- a/lib/mbedtls/Makefile +++ b/lib/mbedtls/Makefile @@ -16,6 +16,7 @@ obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \ public_key.o obj-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \ x509_cert_parser.o +obj-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_MBEDTLS) += pkcs7_parser.o
# MbedTLS crypto library obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o @@ -49,5 +50,5 @@ mbedtls_lib_x509-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \ mbedtls_lib_x509-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/x509_crl.o \ $(MBEDTLS_LIB_DIR)/x509_crt.o -mbedtls_lib_x509-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER) += \ +mbedtls_lib_x509-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/pkcs7.o diff --git a/lib/mbedtls/pkcs7_parser.c b/lib/mbedtls/pkcs7_parser.c new file mode 100644 index 00000000000..69ca784858e --- /dev/null +++ b/lib/mbedtls/pkcs7_parser.c @@ -0,0 +1,506 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * PKCS#7 parser using MbedTLS PKCS#7 library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#include <log.h> +#include <linux/kernel.h> +#include <linux/err.h> +#include <crypto/public_key.h> +#include <crypto/pkcs7_parser.h> + +static void pkcs7_free_mbedtls_ctx(struct pkcs7_mbedtls_ctx *ctx) +{ + if (ctx) { + kfree(ctx->content_data); + kfree(ctx); + } +} + +static void pkcs7_free_sinfo_mbedtls_ctx(struct pkcs7_sinfo_mbedtls_ctx *ctx) +{ + if (ctx) { + kfree(ctx->authattrs_data); + kfree(ctx->content_data_digest); + kfree(ctx); + } +} + +/* + * Parse Authenticate Attributes + * TODO: Shall we consider to integrate decoding of authenticate attribute into + * MbedTLS library? + * + * There are two kinds of structure for the Authenticate Attributes being used + * in U-Boot. + * + * Type 1 - contains in a PE/COFF EFI image: + * + * [C.P.0] { + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.9.3 (OID_contentType) + * U.P.SET { + * U.P.OBJECTIDENTIFIER 1.3.6.1.4.1.311.2.1.4 (OID_msIndirectData) + * } + * } + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.9.5 (OID_signingTime) + * U.P.SET { + * U.P.UTCTime '<siging_time>' + * } + * } + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.9.4 (OID_messageDigest) + * U.P.SET { + * U.P.OCTETSTRING <digest> + * } + * } + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.9.15 (OID_smimeCapabilites) + * U.P.SET { + * U.P.SEQUENCE { + * <...> + * } + * } + * } + * } + * + * Type 2 - contains in an EFI Capsule: + * + * [C.P.0] { + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.9.3 (OID_contentType) + * U.P.SET { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.7.1 (OID_data) + * } + * } + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.9.5 (OID_signingTime) + * U.P.SET { + * U.P.UTCTime '<siging_time>' + * } + * } + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.2.840.113549.1.9.4 (OID_messageDigest) + * U.P.SET { + * U.P.OCTETSTRING <digest> + * } + * } + *} + * + * Note: + * They have different Content Type (OID_msIndirectData or OID_data). + * OID_smimeCapabilites only exists in a PE/COFF EFI image. + */ +static int authattrs_parse(struct pkcs7_message *msg, void *aa, size_t aa_len, + struct pkcs7_signed_info *sinfo) +{ + unsigned char *p = aa; + unsigned char *end = (unsigned char *)aa + aa_len; + size_t len = 0; + int ret; + unsigned char *inner_p; + size_t seq_len = 0; + + ret = mbedtls_asn1_get_tag(&p, end, &seq_len, + MBEDTLS_ASN1_CONTEXT_SPECIFIC | + MBEDTLS_ASN1_CONSTRUCTED); + if (ret) + return ret; + + while (!mbedtls_asn1_get_tag(&p, end, &seq_len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE)) { + inner_p = p; + ret = mbedtls_asn1_get_tag(&inner_p, p + seq_len, &len, + MBEDTLS_ASN1_OID); + if (ret) + return ret; + + if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_PKCS9_CONTENTTYPE, inner_p, len)) { + inner_p += len; + ret = mbedtls_asn1_get_tag(&inner_p, p + seq_len, &len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SET); + if (ret) + return ret; + + ret = mbedtls_asn1_get_tag(&inner_p, p + seq_len, &len, + MBEDTLS_ASN1_OID); + if (ret) + return ret; + + /* + * We should only support 1.2.840.113549.1.7.1 (OID_data) + * for PKCS7 DATA that is used in EFI Capsule and + * 1.3.6.1.4.1.311.2.1.4 (OID_msIndirectData) for + * MicroSoft Authentication Code that is used in EFI + * Secure Boot. + */ + if (MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_MICROSOFT_INDIRECTDATA, + inner_p, len) && + MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_PKCS7_DATA, + inner_p, len)) + return -EINVAL; + + if (__test_and_set_bit(sinfo_has_content_type, &sinfo->aa_set)) + return -EINVAL; + } else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_PKCS9_MESSAGEDIGEST, inner_p, + len)) { + inner_p += len; + ret = mbedtls_asn1_get_tag(&inner_p, p + seq_len, &len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SET); + if (ret) + return ret; + + ret = mbedtls_asn1_get_tag(&inner_p, p + seq_len, &len, + MBEDTLS_ASN1_OCTET_STRING); + if (ret) + return ret; + + sinfo->msgdigest = inner_p; + sinfo->msgdigest_len = len; + + if (__test_and_set_bit(sinfo_has_message_digest, &sinfo->aa_set)) + return -EINVAL; + } else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_PKCS9_SIGNINGTIME, inner_p, + len)) { + mbedtls_x509_time st; + + inner_p += len; + ret = mbedtls_asn1_get_tag(&inner_p, p + seq_len, &len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SET); + if (ret) + return ret; + + ret = mbedtls_x509_get_time(&inner_p, p + seq_len, &st); + if (ret) + return ret; + sinfo->signing_time = x509_get_timestamp(&st); + + if (__test_and_set_bit(sinfo_has_signing_time, &sinfo->aa_set)) + return -EINVAL; + } else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_PKCS9_SMIMECAP, inner_p, + len)) { + if (__test_and_set_bit(sinfo_has_smime_caps, &sinfo->aa_set)) + return -EINVAL; + + if (msg->data_type != OID_msIndirectData && + msg->data_type != OID_data) + return -EINVAL; + } else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_MICROSOFT_SPOPUSINFO, inner_p, + len)) { + if (__test_and_set_bit(sinfo_has_ms_opus_info, &sinfo->aa_set)) + return -EINVAL; + } else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_MICROSOFT_STATETYPE, inner_p, + len)) { + if (__test_and_set_bit(sinfo_has_ms_statement_type, &sinfo->aa_set)) + return -EINVAL; + } + + p += seq_len; + } + + if (ret && ret != MBEDTLS_ERR_ASN1_OUT_OF_DATA) + return ret; + + msg->have_authattrs = true; + + /* + * Skip the leading tag byte (MBEDTLS_ASN1_CONTEXT_SPECIFIC | + * MBEDTLS_ASN1_CONSTRUCTED) to satisfy pkcs7_digest() when calculating + * the digest of authattrs. + */ + sinfo->authattrs = aa + 1; + sinfo->authattrs_len = aa_len - 1; + + return 0; +} + +static int x509_populate_content_data(struct pkcs7_message *msg, + mbedtls_pkcs7 *pkcs7_ctx) +{ + struct pkcs7_mbedtls_ctx *mctx; + + if (!pkcs7_ctx->content_data.data || + !pkcs7_ctx->content_data.data_len) + return 0; + + mctx = kzalloc(sizeof(*mctx), GFP_KERNEL); + if (!mctx) + return -ENOMEM; + + mctx->content_data = kmemdup(pkcs7_ctx->content_data.data, + pkcs7_ctx->content_data.data_len, + GFP_KERNEL); + if (!mctx->content_data) { + pkcs7_free_mbedtls_ctx(mctx); + return -ENOMEM; + } + + msg->data = mctx->content_data; + msg->data_len = pkcs7_ctx->content_data.data_len; + msg->data_hdrlen = pkcs7_ctx->content_data.data_hdrlen; + msg->data_type = pkcs7_ctx->content_data.data_type; + + msg->mbedtls_ctx = mctx; + return 0; +} + +static int x509_populate_sinfo(struct pkcs7_message *msg, + mbedtls_pkcs7_signer_info *mb_sinfo, + struct pkcs7_signed_info **sinfo) +{ + struct pkcs7_signed_info *signed_info; + struct public_key_signature *s; + mbedtls_md_type_t md_alg; + struct pkcs7_sinfo_mbedtls_ctx *mctx; + int ret; + + signed_info = kzalloc(sizeof(*signed_info), GFP_KERNEL); + if (!signed_info) + return -ENOMEM; + + s = kzalloc(sizeof(*s), GFP_KERNEL); + if (!s) { + ret = -ENOMEM; + goto out_no_sig; + } + + mctx = kzalloc(sizeof(*mctx), GFP_KERNEL); + if (!mctx) { + ret = -ENOMEM; + goto out_no_mctx; + } + + /* + * Hash algorithm: + * + * alg_identifier = digestAlgorithm (DigestAlgorithmIdentifier) + * MbedTLS internally checks this field to ensure + * it is the same as digest_alg_identifiers. + * sig_alg_identifier = digestEncryptionAlgorithm + * (DigestEncryptionAlgorithmIdentifier) + * MbedTLS just saves this field without any actions. + * See function pkcs7_get_signer_info() for reference. + * + * Public key algorithm: + * No information related to public key algorithm under MbedTLS signer + * info. Assume that we are using RSA. + */ + ret = mbedtls_oid_get_md_alg(&mb_sinfo->alg_identifier, &md_alg); + if (ret) + goto out_err_sinfo; + s->pkey_algo = "rsa"; + + /* Translate the hash algorithm */ + switch (md_alg) { + case MBEDTLS_MD_SHA1: + s->hash_algo = "sha1"; + s->digest_size = SHA1_SUM_LEN; + break; + case MBEDTLS_MD_SHA256: + s->hash_algo = "sha256"; + s->digest_size = SHA256_SUM_LEN; + break; + case MBEDTLS_MD_SHA384: + s->hash_algo = "sha384"; + s->digest_size = SHA384_SUM_LEN; + break; + case MBEDTLS_MD_SHA512: + s->hash_algo = "sha512"; + s->digest_size = SHA512_SUM_LEN; + break; + /* Unsupported algo */ + case MBEDTLS_MD_MD5: + case MBEDTLS_MD_SHA224: + default: + ret = -EINVAL; + goto out_err_sinfo; + } + + /* + * auth_ids holds AuthorityKeyIdentifier, aka akid + * auth_ids[0]: + * [PKCS#7 or CMS ver 1] - generated from "Issuer + Serial number" + * [CMS ver 3] - generated from skid (subjectKeyId) + * auth_ids[1]: generated from skid (subjectKeyId) + * + * Assume that we are using PKCS#7 (msg->version=1), + * not CMS ver 3 (msg->version=3). + */ + s->auth_ids[0] = asymmetric_key_generate_id(mb_sinfo->serial.p, + mb_sinfo->serial.len, + mb_sinfo->issuer_raw.p, + mb_sinfo->issuer_raw.len); + if (!s->auth_ids[0]) { + ret = -ENOMEM; + goto out_err_sinfo; + } + + /* skip s->auth_ids[1], no subjectKeyId in MbedTLS signer info ctx */ + + /* + * Encoding can be pkcs1 or raw, but only pkcs1 is supported. + * Set the encoding explicitly to pkcs1. + */ + s->encoding = "pkcs1"; + + /* Copy the signature data */ + s->s = kmemdup(mb_sinfo->sig.p, mb_sinfo->sig.len, GFP_KERNEL); + if (!s->s) { + ret = -ENOMEM; + goto out_err_sinfo; + } + s->s_size = mb_sinfo->sig.len; + signed_info->sig = s; + + /* Save the Authenticate Attributes data if exists */ + if (!mb_sinfo->authattrs.data || !mb_sinfo->authattrs.data_len) + goto no_authattrs; + + mctx->authattrs_data = kmemdup(mb_sinfo->authattrs.data, + mb_sinfo->authattrs.data_len, + GFP_KERNEL); + if (!mctx->authattrs_data) { + ret = -ENOMEM; + goto out_err_sinfo; + } + signed_info->mbedtls_ctx = mctx; + + /* If authattrs exists, decode it and parse msgdigest from it */ + ret = authattrs_parse(msg, mctx->authattrs_data, + mb_sinfo->authattrs.data_len, + signed_info); + if (ret) + goto out_err_sinfo; + +no_authattrs: + *sinfo = signed_info; + return 0; + +out_err_sinfo: + pkcs7_free_sinfo_mbedtls_ctx(mctx); +out_no_mctx: + public_key_signature_free(s); +out_no_sig: + kfree(signed_info); + return ret; +} + +/* + * Free a signed information block. + */ +static void pkcs7_free_signed_info(struct pkcs7_signed_info *sinfo) +{ + if (sinfo) { + public_key_signature_free(sinfo->sig); + pkcs7_free_sinfo_mbedtls_ctx(sinfo->mbedtls_ctx); + kfree(sinfo); + } +} + +/** + * pkcs7_free_message - Free a PKCS#7 message + * @pkcs7: The PKCS#7 message to free + */ +void pkcs7_free_message(struct pkcs7_message *pkcs7) +{ + struct x509_certificate *cert; + struct pkcs7_signed_info *sinfo; + + if (pkcs7) { + while (pkcs7->certs) { + cert = pkcs7->certs; + pkcs7->certs = cert->next; + x509_free_certificate(cert); + } + while (pkcs7->crl) { + cert = pkcs7->crl; + pkcs7->crl = cert->next; + x509_free_certificate(cert); + } + while (pkcs7->signed_infos) { + sinfo = pkcs7->signed_infos; + pkcs7->signed_infos = sinfo->next; + pkcs7_free_signed_info(sinfo); + } + pkcs7_free_mbedtls_ctx(pkcs7->mbedtls_ctx); + kfree(pkcs7); + } +} + +struct pkcs7_message *pkcs7_parse_message(const void *data, size_t datalen) +{ + int i; + int ret; + mbedtls_pkcs7 pkcs7_ctx; + mbedtls_pkcs7_signer_info *mb_sinfos; + mbedtls_x509_crt *mb_certs; + struct pkcs7_message *msg; + struct x509_certificate **cert; + struct pkcs7_signed_info **sinfos; + + msg = kzalloc(sizeof(*msg), GFP_KERNEL); + if (!msg) { + ret = -ENOMEM; + goto out_no_msg; + } + + /* Parse the DER encoded PKCS#7 message using MbedTLS */ + mbedtls_pkcs7_init(&pkcs7_ctx); + ret = mbedtls_pkcs7_parse_der(&pkcs7_ctx, data, datalen); + /* Check if it is a PKCS#7 message with signed data */ + if (ret != MBEDTLS_PKCS7_SIGNED_DATA) + goto parse_fail; + + /* Assume that we are using PKCS#7, not CMS ver 3 */ + msg->version = 1; /* 1 for [PKCS#7 or CMS ver 1] */ + + /* Populate the certs to msg->certs */ + for (i = 0, cert = &msg->certs, mb_certs = &pkcs7_ctx.signed_data.certs; + i < pkcs7_ctx.signed_data.no_of_certs && mb_certs; + i++, cert = &(*cert)->next, mb_certs = mb_certs->next) { + ret = x509_populate_cert(mb_certs, cert); + if (ret) + goto parse_fail; + + (*cert)->index = i + 1; + } + + /* + * Skip populating crl, that is not currently in-use. + */ + + /* Populate content data */ + ret = x509_populate_content_data(msg, &pkcs7_ctx); + if (ret) + goto parse_fail; + + /* Populate signed info to msg->signed_infos */ + for (i = 0, sinfos = &msg->signed_infos, + mb_sinfos = &pkcs7_ctx.signed_data.signers; + i < pkcs7_ctx.signed_data.no_of_signers && mb_sinfos; + i++, sinfos = &(*sinfos)->next, mb_sinfos = mb_sinfos->next) { + ret = x509_populate_sinfo(msg, mb_sinfos, sinfos); + if (ret) + goto parse_fail; + + (*sinfos)->index = i + 1; + } + + mbedtls_pkcs7_free(&pkcs7_ctx); + return msg; + +parse_fail: + mbedtls_pkcs7_free(&pkcs7_ctx); + pkcs7_free_message(msg); +out_no_msg: + msg = ERR_PTR(ret); + return msg; +}

Previous patch has introduced MbedTLS porting layer for PKCS7 parser, here to adjust the header and makefiles accordingly.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. Changes in v3 - Update commit message. Changes in v4 - Control building legacy library via '_LEGACY' Kconfig. Changes in v5 - Correct header file include directories.
include/crypto/pkcs7_parser.h | 56 +++++++++++++++++++++++++++++++++++ lib/crypto/Makefile | 7 +++-- 2 files changed, 60 insertions(+), 3 deletions(-)
diff --git a/include/crypto/pkcs7_parser.h b/include/crypto/pkcs7_parser.h index 2c45cce5234..469c2711fa6 100644 --- a/include/crypto/pkcs7_parser.h +++ b/include/crypto/pkcs7_parser.h @@ -11,6 +11,12 @@ #include <linux/oid_registry.h> #include <crypto/pkcs7.h> #include <crypto/x509_parser.h> +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) +#include <mbedtls/pkcs7.h> +#include <library/x509_internal.h> +#include <mbedtls/asn1.h> +#include <mbedtls/oid.h> +#endif #include <linux/printk.h>
#define kenter(FMT, ...) \ @@ -18,7 +24,54 @@ #define kleave(FMT, ...) \ pr_devel("<== %s()"FMT"\n", __func__, ##__VA_ARGS__)
+/* Backup the parsed MedTLS context that we need */ +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) +struct pkcs7_mbedtls_ctx { + void *content_data; +}; + +struct pkcs7_sinfo_mbedtls_ctx { + void *authattrs_data; + void *content_data_digest; +}; +#endif + +/* + * MbedTLS integration Notes: + * + * MbedTLS PKCS#7 library does not originally support parsing MicroSoft + * Authentication Code which is used for verifying the PE image digest. + * + * 1. Authenticated Attributes (authenticatedAttributes) + * MbedTLS assumes unauthenticatedAttributes and authenticatedAttributes + * fields not exist. + * See MbedTLS function 'pkcs7_get_signer_info' for details. + * + * 2. MicroSoft Authentication Code (mscode) + * MbedTLS only supports Content Data type defined as 1.2.840.113549.1.7.1 + * (MBEDTLS_OID_PKCS7_DATA, aka OID_data). + * 1.3.6.1.4.1.311.2.1.4 (MicroSoft Authentication Code, aka + * OID_msIndirectData) is not supported. + * See MbedTLS function 'pkcs7_get_content_info_type' for details. + * + * But the EFI loader assumes that a PKCS#7 message with an EFI image always + * contains MicroSoft Authentication Code as Content Data (msg->data is NOT + * NULL), see function 'efi_signature_verify'. + * + * MbedTLS patch "0002-support-MicroSoft-authentication-code-in-PKCS7-lib.patch" + * is to support both above features by parsing the Content Data and + * Authenticate Attributes from a given PKCS#7 message. + * + * Other fields we don't need to populate from MbedTLS, which are used + * internally by pkcs7_verify: + * 'signer', 'unsupported_crypto', 'blacklisted' + * 'sig->digest' is used internally by pkcs7_digest to calculate the hash of + * Content Data or Authenticate Attributes. + */ struct pkcs7_signed_info { +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) + struct pkcs7_sinfo_mbedtls_ctx *mbedtls_ctx; +#endif struct pkcs7_signed_info *next; struct x509_certificate *signer; /* Signing certificate (in msg->certs) */ unsigned index; @@ -55,6 +108,9 @@ struct pkcs7_signed_info { };
struct pkcs7_message { +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) + struct pkcs7_mbedtls_ctx *mbedtls_ctx; +#endif struct x509_certificate *certs; /* Certificate list */ struct x509_certificate *crl; /* Revocation list */ struct pkcs7_signed_info *signed_infos; diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index 4302f197297..7129315393f 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -50,15 +50,16 @@ $(obj)/x509_akid.asn1.o: $(obj)/x509_akid.asn1.c $(obj)/x509_akid.asn1.h # PKCS#7 message handling # obj-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER) += pkcs7_message.o -pkcs7_message-y := \ +pkcs7_message-y := pkcs7_helper.o +pkcs7_message-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_LEGACY) += \ pkcs7.asn1.o \ - pkcs7_helper.o \ pkcs7_parser.o -obj-$(CONFIG_$(SPL_)PKCS7_VERIFY) += pkcs7_verify.o
$(obj)/pkcs7_parser.o: $(obj)/pkcs7.asn1.h $(obj)/pkcs7.asn1.o: $(obj)/pkcs7.asn1.c $(obj)/pkcs7.asn1.h
+obj-$(CONFIG_$(SPL_)PKCS7_VERIFY) += pkcs7_verify.o + # # Signed PE binary-wrapped key handling #

Add porting layer for MSCode on top of MbedTLS ASN1 library. Introduce _MBEDTLS kconfigs for MSCode MbedTLS implementation.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. Changes in v3 - None. Changes in v4 - Introduce _LEGACY and _MBEDTLS kconfigs for MSCode legacy and MbedTLS implementations respectively. - Fix a few code style. Changes in v5 - Correct kconfig dependence. - Refactored MbedTLS makefile. - Move mscode legacy kconfig to the next patch.
lib/mbedtls/Kconfig | 9 +++ lib/mbedtls/Makefile | 1 + lib/mbedtls/mscode_parser.c | 123 ++++++++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 lib/mbedtls/mscode_parser.c
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index 4a65f6ab488..a80e996fe90 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -270,6 +270,7 @@ config MBEDTLS_LIB_X509 ASYMMETRIC_PUBLIC_KEY_SUBTYPE select X509_CERTIFICATE_PARSER_MBEDTLS if X509_CERTIFICATE_PARSER select PKCS7_MESSAGE_PARSER_MBEDTLS if PKCS7_MESSAGE_PARSER + select MSCODE_PARSER_MBEDTLS if MSCODE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help @@ -300,6 +301,14 @@ config PKCS7_MESSAGE_PARSER_MBEDTLS This option chooses MbedTLS certificate library for PKCS7 message parser.
+config MSCODE_PARSER_MBEDTLS + bool "MS authenticode parser with MbedTLS certificate library" + depends on MBEDTLS_LIB_X509 && MSCODE_PARSER + select ASN1_DECODER_MBEDTLS + help + This option chooses MbedTLS certificate library for MS authenticode + parser. + if SPL
config SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile index 36eba07bf43..83333b1b6a5 100644 --- a/lib/mbedtls/Makefile +++ b/lib/mbedtls/Makefile @@ -17,6 +17,7 @@ obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \ obj-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \ x509_cert_parser.o obj-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_MBEDTLS) += pkcs7_parser.o +obj-$(CONFIG_$(SPL_)MSCODE_PARSER_MBEDTLS) += mscode_parser.o
# MbedTLS crypto library obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o diff --git a/lib/mbedtls/mscode_parser.c b/lib/mbedtls/mscode_parser.c new file mode 100644 index 00000000000..c3805c6503c --- /dev/null +++ b/lib/mbedtls/mscode_parser.c @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * MSCode parser using MbedTLS ASN1 library + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#include <linux/kernel.h> +#include <linux/err.h> +#include <crypto/pkcs7.h> +#include <crypto/mscode.h> + +/* + * Parse a Microsoft Individual Code Signing blob + * + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER 1.3.6.1.4.1.311.2.1.15 (SPC_PE_IMAGE_DATA_OBJID) + * U.P.SEQUENCE { + * U.P.BITSTRING NaN : 0 unused bit(s); + * [C.P.0] { + * [C.P.2] { + * [C.P.0] <arbitrary string> + * } + * } + * } + * } + * U.P.SEQUENCE { + * U.P.SEQUENCE { + * U.P.OBJECTIDENTIFIER <digest algorithm OID> + * U.P.NULL + * } + * U.P.OCTETSTRING <PE image digest> + * } + * + * @ctx: PE file context. + * @content_data: content data pointer. + * @data_len: content data length. + * @asn1hdrlen: ASN1 header length. + */ +int mscode_parse(void *ctx, const void *content_data, size_t data_len, + size_t asn1hdrlen) +{ + struct pefile_context *_ctx = ctx; + unsigned char *p = (unsigned char *)content_data; + unsigned char *end = (unsigned char *)content_data + data_len; + size_t len = 0; + int ret; + unsigned char *inner_p; + size_t seq_len = 0; + + ret = mbedtls_asn1_get_tag(&p, end, &seq_len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret) + return ret; + + inner_p = p; + ret = mbedtls_asn1_get_tag(&inner_p, inner_p + seq_len, &len, + MBEDTLS_ASN1_OID); + if (ret) + return ret; + + /* Sanity check on the PE Image Data OID (1.3.6.1.4.1.311.2.1.15) */ + if (MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_MICROSOFT_PEIMAGEDATA, inner_p, + len)) + return -EINVAL; + + p += seq_len; + ret = mbedtls_asn1_get_tag(&p, end, &seq_len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret) + return ret; + + ret = mbedtls_asn1_get_tag(&p, p + seq_len, &seq_len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret) + return ret; + + inner_p = p; + + /* + * Check if the inner sequence contains a supported hash + * algorithm OID + */ + ret = mbedtls_asn1_get_tag(&inner_p, inner_p + seq_len, &len, + MBEDTLS_ASN1_OID); + if (ret) + return ret; + + if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_DIGEST_ALG_MD5, inner_p, len)) + _ctx->digest_algo = "md5"; + else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_DIGEST_ALG_SHA1, inner_p, + len)) + _ctx->digest_algo = "sha1"; + else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_DIGEST_ALG_SHA224, inner_p, + len)) + _ctx->digest_algo = "sha224"; + else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_DIGEST_ALG_SHA256, inner_p, + len)) + _ctx->digest_algo = "sha256"; + else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_DIGEST_ALG_SHA384, inner_p, + len)) + _ctx->digest_algo = "sha384"; + else if (!MBEDTLS_OID_CMP_RAW(MBEDTLS_OID_DIGEST_ALG_SHA512, inner_p, + len)) + _ctx->digest_algo = "sha512"; + + if (!_ctx->digest_algo) + return -EINVAL; + + p += seq_len; + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); + if (ret) + return ret; + + _ctx->digest = p; + _ctx->digest_len = len; + + return 0; +}

Previous patch has introduced MbedTLS porting layer for mscode parser, here to adjust the header and makefiles accordingly. Adding _LEGACY Kconfig for legacy mscode implementation.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Move the porting layer to MbedTLS dir. Changes in v3 - Update commit message. Changes in v4 - Control building legacy library via '_LEGACY' Kconfig. Changes in v5 - Add kconfig for legacy mscode parser. - Correct header file include directories.
include/crypto/mscode.h | 4 ++++ lib/crypto/Makefile | 2 +- lib/mbedtls/Kconfig | 9 +++++++++ 3 files changed, 14 insertions(+), 1 deletion(-)
diff --git a/include/crypto/mscode.h b/include/crypto/mscode.h index 551058b96e6..678e69001b9 100644 --- a/include/crypto/mscode.h +++ b/include/crypto/mscode.h @@ -9,6 +9,10 @@ #ifndef __UBOOT__ #include <crypto/hash_info.h> #endif +#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) +#include <mbedtls/asn1.h> +#include <mbedtls/oid.h> +#endif
struct pefile_context { #ifndef __UBOOT__ diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index 7129315393f..3caa45dc2a8 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -63,7 +63,7 @@ obj-$(CONFIG_$(SPL_)PKCS7_VERIFY) += pkcs7_verify.o # # Signed PE binary-wrapped key handling # -obj-$(CONFIG_$(SPL_)MSCODE_PARSER) += mscode.o +obj-$(CONFIG_$(SPL_)MSCODE_PARSER_LEGACY) += mscode.o
mscode-y := \ mscode_parser.o \ diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index a80e996fe90..436fd7d1f94 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -121,6 +121,7 @@ config LEGACY_CRYPTO_CERT ASYMMETRIC_PUBLIC_KEY_SUBTYPE select X509_CERTIFICATE_PARSER_LEGACY if X509_CERTIFICATE_PARSER select PKCS7_MESSAGE_PARSER_LEGACY if PKCS7_MESSAGE_PARSER + select MSCODE_PARSER_LEGACY if MSCODE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE help @@ -151,6 +152,14 @@ config PKCS7_MESSAGE_PARSER_LEGACY This option chooses legacy certificate library for PKCS7 message parser.
+config MSCODE_PARSER_LEGACY + bool "MS authenticode parser with legacy certificate library" + depends on LEGACY_CRYPTO_CERT && MSCODE_PARSER + select ASN1_DECODER_LEGACY + help + This option chooses legacy certificate library for MS authenticode + parser. + if SPL
config SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY

Add RSA helper layer on top on MbedTLS PK and RSA library. Introduce _LEGACY and _MBEDTLS kconfigs for RSA helper legacy and MbedTLS implementations respectively.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Initial patch. Changes in v3 - None. Changes in v4 - Introduce _LEGACY and _MBEDTLS kconfigs for RSA helper legacy and MbedTLS implementations respectively. - Remove unnecessary type casting. Changes in v5 - Correct header file include directories. - Correct kconfig dependence. - Kconfig rename. - Refactored MbedTLS makefile.
lib/mbedtls/Kconfig | 36 +++++++++++++++ lib/mbedtls/Makefile | 3 +- lib/mbedtls/rsa_helper.c | 95 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 lib/mbedtls/rsa_helper.c
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index 436fd7d1f94..ea306e07ee4 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -119,11 +119,13 @@ config LEGACY_CRYPTO_CERT bool "legacy certificate libraries" select ASYMMETRIC_PUBLIC_KEY_LEGACY if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select RSA_PUBLIC_KEY_PARSER_LEGACY if RSA_PUBLIC_KEY_PARSER select X509_CERTIFICATE_PARSER_LEGACY if X509_CERTIFICATE_PARSER select PKCS7_MESSAGE_PARSER_LEGACY if PKCS7_MESSAGE_PARSER select MSCODE_PARSER_LEGACY if MSCODE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select SPL_RSA_PUBLIC_KEY_PARSER_LEGACY if SPL_RSA_PUBLIC_KEY_PARSER help Enable legacy certificate libraries.
@@ -136,6 +138,14 @@ config ASYMMETRIC_PUBLIC_KEY_LEGACY This option chooses legacy certificate library for asymmetric public key crypto algorithm.
+config RSA_PUBLIC_KEY_PARSER_LEGACY + bool "RSA public key parser with legacy certificate library" + depends on ASYMMETRIC_PUBLIC_KEY_LEGACY + select ASN1_DECODER_LEGACY + help + This option chooses legacy certificate library for RSA public key + parser. + config X509_CERTIFICATE_PARSER_LEGACY bool "X.509 certificate parser with legacy certificate library" depends on ASYMMETRIC_PUBLIC_KEY_LEGACY @@ -169,6 +179,14 @@ config SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY This option chooses legacy certificate library for asymmetric public key crypto algorithm in SPL.
+config SPL_RSA_PUBLIC_KEY_PARSER_LEGACY + bool "RSA public key parser with legacy certificate library in SPL" + depends on SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY + select SPL_ASN1_DECODER_LEGACY + help + This option chooses legacy certificate library for RSA public key + parser in SPL. + endif # SPL
endif # LEGACY_CRYPTO_CERT @@ -277,11 +295,13 @@ config MBEDTLS_LIB_X509 bool "MbedTLS certificate libraries" select ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select RSA_PUBLIC_KEY_PARSER_MBEDTLS if RSA_PUBLIC_KEY_PARSER select X509_CERTIFICATE_PARSER_MBEDTLS if X509_CERTIFICATE_PARSER select PKCS7_MESSAGE_PARSER_MBEDTLS if PKCS7_MESSAGE_PARSER select MSCODE_PARSER_MBEDTLS if MSCODE_PARSER select SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select SPL_RSA_PUBLIC_KEY_PARSER_MBEDTLS if SPL_RSA_PUBLIC_KEY_PARSER help Enable MbedTLS certificate libraries.
@@ -294,6 +314,14 @@ config ASYMMETRIC_PUBLIC_KEY_MBEDTLS This option chooses MbedTLS certificate library for asymmetric public key crypto algorithm.
+config RSA_PUBLIC_KEY_PARSER_MBEDTLS + bool "RSA public key parser with MbedTLS certificate library" + depends on ASYMMETRIC_PUBLIC_KEY_MBEDTLS + select ASN1_DECODER_MBEDTLS + help + This option chooses MbedTLS certificate library for RSA public key + parser. + config X509_CERTIFICATE_PARSER_MBEDTLS bool "X.509 certificate parser with MbedTLS certificate library" depends on ASYMMETRIC_PUBLIC_KEY_MBEDTLS @@ -327,6 +355,14 @@ config SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS This option chooses MbedTLS certificate library for asymmetric public key crypto algorithm in SPL.
+config SPL_RSA_PUBLIC_KEY_PARSER_MBEDTLS + bool "RSA public key parser with MbedTLS certificate library in SPL" + depends on SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS + select SPL_ASN1_DECODER_MBEDTLS + help + This option chooses MbedTLS certificate library for RSA public key + parser in SPL. + endif # SPL
endif # MBEDTLS_LIB_X509 diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile index 83333b1b6a5..40031994708 100644 --- a/lib/mbedtls/Makefile +++ b/lib/mbedtls/Makefile @@ -18,6 +18,7 @@ obj-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \ x509_cert_parser.o obj-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_MBEDTLS) += pkcs7_parser.o obj-$(CONFIG_$(SPL_)MSCODE_PARSER_MBEDTLS) += mscode_parser.o +obj-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER_MBEDTLS) += rsa_helper.o
# MbedTLS crypto library obj-$(CONFIG_MBEDTLS_LIB_CRYPTO) += mbedtls_lib_crypto.o @@ -39,7 +40,7 @@ mbedtls_lib_x509-$(CONFIG_$(SPL_)ASN1_DECODER) += \ $(MBEDTLS_LIB_DIR)/asn1parse.o \ $(MBEDTLS_LIB_DIR)/asn1write.o \ $(MBEDTLS_LIB_DIR)/oid.o -mbedtls_lib_x509-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER) += \ +mbedtls_lib_x509-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/bignum.o \ $(MBEDTLS_LIB_DIR)/bignum_core.o \ $(MBEDTLS_LIB_DIR)/rsa.o \ diff --git a/lib/mbedtls/rsa_helper.c b/lib/mbedtls/rsa_helper.c new file mode 100644 index 00000000000..3d94eee9954 --- /dev/null +++ b/lib/mbedtls/rsa_helper.c @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * RSA helper functions using MbedTLS + * + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ + +#include <linux/err.h> +#include <crypto/internal/rsa.h> +#include <library/common.h> +#include <mbedtls/pk.h> +#include <mbedtls/rsa.h> +#include <mbedtls/asn1.h> + +/** + * rsa_parse_pub_key() - decodes the BER encoded buffer and stores in the + * provided struct rsa_key, pointers to the raw key as is, + * so that the caller can copy it or MPI parse it, etc. + * + * @rsa_key: struct rsa_key key representation + * @key: key in BER format + * @key_len: length of key + * + * Return: 0 on success or error code in case of error + */ +int rsa_parse_pub_key(struct rsa_key *rsa_key, const void *key, + unsigned int key_len) +{ + int ret = 0; + mbedtls_pk_context pk; + mbedtls_rsa_context *rsa; + + mbedtls_pk_init(&pk); + + ret = mbedtls_pk_parse_public_key(&pk, (const unsigned char *)key, + key_len); + if (ret) { + pr_err("Failed to parse public key, ret:-0x%04x\n", -ret); + ret = -EINVAL; + goto clean_pubkey; + } + + /* Ensure that it is a RSA key */ + if (mbedtls_pk_get_type(&pk) != MBEDTLS_PK_RSA) { + pr_err("Non-RSA keys are not supported\n"); + ret = -EKEYREJECTED; + goto clean_pubkey; + } + + /* Get RSA key context */ + rsa = mbedtls_pk_rsa(pk); + if (!rsa) { + pr_err("Failed to get RSA key context, ret:-0x%04x\n", -ret); + ret = -EINVAL; + goto clean_pubkey; + } + + /* Parse modulus (n) */ + rsa_key->n_sz = mbedtls_mpi_size(&rsa->N); + rsa_key->n = kzalloc(rsa_key->n_sz, GFP_KERNEL); + if (!rsa_key->n) { + ret = -ENOMEM; + goto clean_pubkey; + } + ret = mbedtls_mpi_write_binary(&rsa->N, (unsigned char *)rsa_key->n, + rsa_key->n_sz); + if (ret) { + pr_err("Failed to parse modulus (n), ret:-0x%04x\n", -ret); + ret = -EINVAL; + goto clean_modulus; + } + + /* Parse public exponent (e) */ + rsa_key->e_sz = mbedtls_mpi_size(&rsa->E); + rsa_key->e = kzalloc(rsa_key->e_sz, GFP_KERNEL); + if (!rsa_key->e) { + ret = -ENOMEM; + goto clean_modulus; + } + ret = mbedtls_mpi_write_binary(&rsa->E, (unsigned char *)rsa_key->e, + rsa_key->e_sz); + if (!ret) + return 0; + + pr_err("Failed to parse public exponent (e), ret:-0x%04x\n", -ret); + ret = -EINVAL; + + kfree(rsa_key->e); +clean_modulus: + kfree(rsa_key->n); +clean_pubkey: + mbedtls_pk_free(&pk); + return ret; +}

Previous patch has introduced MbedTLS porting layer for RSA helper, here to adjust the makefile accordingly.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v2 - Initial patch. Changes in v3 - Update commit message. Changes in v4 - Control building legacy library via '_LEGACY' Kconfig. Changes in v5 - None.
lib/crypto/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index 3caa45dc2a8..72b413d85a9 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -13,7 +13,7 @@ obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_LEGACY) += public_key.o # # RSA public key parser # -obj-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER) += rsa_public_key.o +obj-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER_LEGACY) += rsa_public_key.o rsa_public_key-y := \ rsapubkey.asn1.o \ rsa_helper.o

When building with MbedTLS, we are using MbedTLS to decode ASN1 data for x509, pkcs7 and mscode. Introduce _LEGACY and _MBEDTLS kconfigs for ASN1 decoder legacy and MbedTLS implementations respectively.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - Initial patch. Changes in v3 - None. Changes in v4 - Introduce _LEGACY and _MBEDTLS kconfigs for ASN1 decoder legacy and MbedTLS implementations respectively. - Update the commit subject. Changes in v5 - Correct kconfig dependence. - Refactored MbedTLS makefile.
lib/Makefile | 2 +- lib/mbedtls/Kconfig | 30 ++++++++++++++++++++++++++++++ lib/mbedtls/Makefile | 2 +- 3 files changed, 32 insertions(+), 2 deletions(-)
diff --git a/lib/Makefile b/lib/Makefile index 35b73d8d00c..f0c5b9a9bb4 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -82,7 +82,7 @@ obj-$(CONFIG_$(SPL_)SHA256_LEGACY) += sha256.o obj-$(CONFIG_$(SPL_)SHA512_LEGACY) += sha512.o
obj-$(CONFIG_CRYPT_PW) += crypt/ -obj-$(CONFIG_$(SPL_)ASN1_DECODER) += asn1_decoder.o +obj-$(CONFIG_$(SPL_)ASN1_DECODER_LEGACY) += asn1_decoder.o
obj-$(CONFIG_$(SPL_)ZLIB) += zlib/ obj-$(CONFIG_$(SPL_)ZSTD) += zstd/ diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index ea306e07ee4..336c5220805 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -117,12 +117,14 @@ endif # LEGACY_CRYPTO_BASIC
config LEGACY_CRYPTO_CERT bool "legacy certificate libraries" + select ASN1_DECODER_LEGACY if ASN1_DECODER select ASYMMETRIC_PUBLIC_KEY_LEGACY if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE select RSA_PUBLIC_KEY_PARSER_LEGACY if RSA_PUBLIC_KEY_PARSER select X509_CERTIFICATE_PARSER_LEGACY if X509_CERTIFICATE_PARSER select PKCS7_MESSAGE_PARSER_LEGACY if PKCS7_MESSAGE_PARSER select MSCODE_PARSER_LEGACY if MSCODE_PARSER + select SPL_ASN1_DECODER_LEGACY if SPL_ASN1_DECODER select SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE select SPL_RSA_PUBLIC_KEY_PARSER_LEGACY if SPL_RSA_PUBLIC_KEY_PARSER @@ -131,6 +133,12 @@ config LEGACY_CRYPTO_CERT
if LEGACY_CRYPTO_CERT
+config ASN1_DECODER_LEGACY + bool "ASN1 decoder with legacy certificate library" + depends on LEGACY_CRYPTO_CERT && ASN1_DECODER + help + This option chooses legacy certificate library for ASN1 decoder. + config ASYMMETRIC_PUBLIC_KEY_LEGACY bool "Asymmetric public key crypto with legacy certificate library" depends on LEGACY_CRYPTO_CERT && ASYMMETRIC_PUBLIC_KEY_SUBTYPE @@ -172,6 +180,13 @@ config MSCODE_PARSER_LEGACY
if SPL
+config SPL_ASN1_DECODER_LEGACY + bool "ASN1 decoder with legacy certificate library in SPL" + depends on LEGACY_CRYPTO_CERT && SPL_ASN1_DECODER + help + This option chooses legacy certificate library for ASN1 decoder in + SPL. + config SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY bool "Asymmetric public key crypto with legacy certificate library in SPL" depends on LEGACY_CRYPTO_CERT && SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE @@ -293,12 +308,14 @@ endif # MBEDTLS_LIB_CRYPTO
config MBEDTLS_LIB_X509 bool "MbedTLS certificate libraries" + select ASN1_DECODER_MBEDTLS if ASN1_DECODER select ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ ASYMMETRIC_PUBLIC_KEY_SUBTYPE select RSA_PUBLIC_KEY_PARSER_MBEDTLS if RSA_PUBLIC_KEY_PARSER select X509_CERTIFICATE_PARSER_MBEDTLS if X509_CERTIFICATE_PARSER select PKCS7_MESSAGE_PARSER_MBEDTLS if PKCS7_MESSAGE_PARSER select MSCODE_PARSER_MBEDTLS if MSCODE_PARSER + select SPL_ASN1_DECODER_MBEDTLS if SPL_ASN1_DECODER select SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \ SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE select SPL_RSA_PUBLIC_KEY_PARSER_MBEDTLS if SPL_RSA_PUBLIC_KEY_PARSER @@ -307,6 +324,12 @@ config MBEDTLS_LIB_X509
if MBEDTLS_LIB_X509
+config ASN1_DECODER_MBEDTLS + bool "ASN1 decoder with MbedTLS certificate library" + depends on MBEDTLS_LIB_X509 && ASN1_DECODER + help + This option chooses MbedTLS certificate library for ASN1 decoder. + config ASYMMETRIC_PUBLIC_KEY_MBEDTLS bool "Asymmetric public key crypto with MbedTLS certificate library" depends on MBEDTLS_LIB_X509 && ASYMMETRIC_PUBLIC_KEY_SUBTYPE @@ -348,6 +371,13 @@ config MSCODE_PARSER_MBEDTLS
if SPL
+config SPL_ASN1_DECODER_MBEDTLS + bool "ASN1 decoder with MbedTLS certificate library in SPL" + depends on MBEDTLS_LIB_X509 && SPL_ASN1_DECODER + help + This option chooses MbedTLS certificate library for ASN1 decoder in + SPL. + config SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS bool "Asymmetric public key crypto with MbedTLS certificate library in SPL" depends on MBEDTLS_LIB_X509 && SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE diff --git a/lib/mbedtls/Makefile b/lib/mbedtls/Makefile index 40031994708..14bc59f6cf3 100644 --- a/lib/mbedtls/Makefile +++ b/lib/mbedtls/Makefile @@ -36,7 +36,7 @@ mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA512_MBEDTLS) += \ # MbedTLS X509 library obj-$(CONFIG_MBEDTLS_LIB_X509) += mbedtls_lib_x509.o mbedtls_lib_x509-y := $(MBEDTLS_LIB_DIR)/x509.o -mbedtls_lib_x509-$(CONFIG_$(SPL_)ASN1_DECODER) += \ +mbedtls_lib_x509-$(CONFIG_$(SPL_)ASN1_DECODER_MBEDTLS) += \ $(MBEDTLS_LIB_DIR)/asn1parse.o \ $(MBEDTLS_LIB_DIR)/asn1write.o \ $(MBEDTLS_LIB_DIR)/oid.o

With MBEDTLS_LIB_X509 enabled, we don't build the original ASN1 lib, So remove it from test.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v2 - Initial patch. Changes in v3 - None. Changes in v4 - None. Changes in v5 - None.
test/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/test/Kconfig b/test/Kconfig index e2ec0994a2e..558a9cd49b4 100644 --- a/test/Kconfig +++ b/test/Kconfig @@ -32,7 +32,7 @@ if UT_LIB
config UT_LIB_ASN1 bool "Unit test for asn1 compiler and decoder function" - depends on SANDBOX + depends on SANDBOX && !MBEDTLS_LIB_X509 default y imply ASYMMETRIC_KEY_TYPE imply ASYMMETRIC_PUBLIC_KEY_SUBTYPE

Enable MbedTLS as default setting for qemu arm64
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v2 - None. Changes in v3 - None. Changes in v4 - None. Changes in v5 - Remove unused config MBEDTLS_LIB_TLS. - Remove EFI_SECURE_BOOT from the default config.
configs/qemu_arm64_defconfig | 3 +++ configs/sandbox_defconfig | 3 +++ 2 files changed, 6 insertions(+)
diff --git a/configs/qemu_arm64_defconfig b/configs/qemu_arm64_defconfig index 7e166f43908..22d38608842 100644 --- a/configs/qemu_arm64_defconfig +++ b/configs/qemu_arm64_defconfig @@ -67,4 +67,7 @@ CONFIG_TPM2_MMIO=y CONFIG_USB_EHCI_HCD=y CONFIG_USB_EHCI_PCI=y CONFIG_SEMIHOSTING=y +CONFIG_MBEDTLS_LIB=y +CONFIG_MBEDTLS_LIB_CRYPTO=y +CONFIG_MBEDTLS_LIB_X509=y CONFIG_TPM=y diff --git a/configs/sandbox_defconfig b/configs/sandbox_defconfig index 93b52f2de5c..679bbf69936 100644 --- a/configs/sandbox_defconfig +++ b/configs/sandbox_defconfig @@ -343,6 +343,9 @@ CONFIG_FS_CBFS=y CONFIG_FS_CRAMFS=y CONFIG_ADDR_MAP=y CONFIG_CMD_DHRYSTONE=y +CONFIG_MBEDTLS_LIB=y +CONFIG_MBEDTLS_LIB_CRYPTO=y +CONFIG_MBEDTLS_LIB_X509=y CONFIG_ECDSA=y CONFIG_ECDSA_VERIFY=y CONFIG_TPM=y

On Wed, Jul 31, 2024 at 10:25:37AM -0700, Raymond Mao wrote:
Enable MbedTLS as default setting for qemu arm64
Signed-off-by: Raymond Mao raymond.mao@linaro.org
Changes in v2
- None.
Changes in v3
- None.
Changes in v4
- None.
Changes in v5
- Remove unused config MBEDTLS_LIB_TLS.
- Remove EFI_SECURE_BOOT from the default config.
configs/qemu_arm64_defconfig | 3 +++ configs/sandbox_defconfig | 3 +++ 2 files changed, 6 insertions(+)
diff --git a/configs/qemu_arm64_defconfig b/configs/qemu_arm64_defconfig index 7e166f43908..22d38608842 100644 --- a/configs/qemu_arm64_defconfig +++ b/configs/qemu_arm64_defconfig @@ -67,4 +67,7 @@ CONFIG_TPM2_MMIO=y CONFIG_USB_EHCI_HCD=y CONFIG_USB_EHCI_PCI=y CONFIG_SEMIHOSTING=y +CONFIG_MBEDTLS_LIB=y +CONFIG_MBEDTLS_LIB_CRYPTO=y +CONFIG_MBEDTLS_LIB_X509=y CONFIG_TPM=y diff --git a/configs/sandbox_defconfig b/configs/sandbox_defconfig index 93b52f2de5c..679bbf69936 100644 --- a/configs/sandbox_defconfig +++ b/configs/sandbox_defconfig @@ -343,6 +343,9 @@ CONFIG_FS_CBFS=y CONFIG_FS_CRAMFS=y CONFIG_ADDR_MAP=y CONFIG_CMD_DHRYSTONE=y +CONFIG_MBEDTLS_LIB=y +CONFIG_MBEDTLS_LIB_CRYPTO=y +CONFIG_MBEDTLS_LIB_X509=y CONFIG_ECDSA=y CONFIG_ECDSA_VERIFY=y CONFIG_TPM=y
Please run this through savedefconfig as I believe it's just one line, not 3, in the end.

On Wed, Jul 31, 2024 at 10:25:10AM -0700, Raymond Mao wrote:
Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.
Motivations:
- MbedTLS is well maintained with LTS versions.
- LWIP is integrated with MbedTLS and easily to enable HTTPS.
- MbedTLS recently switched license back to GPLv2.
Prerequisite:
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via: $ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually: $ git add --renormalize . $ git commit
New Kconfig options:
`MBEDTLS_LIB` is for MbedTLS general switch. `MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto libs with MbedTLS. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. `LEGACY_CRYPTO` is introduced as a main switch for legacy crypto library. `LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and `LEGACY_CRYPTO_CERT` is for the certificate related functionalities. For each of the algorithm, a pair of `<alg>_LEGACY` and `<alg>_MBEDTLS` Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options are introduced.
In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and MBEDTLS_LIB_X509 are by default enabled in qemu_arm64_defconfig and sandbox_defconfig for testing purpose.
Patches for external MbedTLS project:
Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs executables which is not supported by MbedTLS at the moment, addtional patches for MbedTLS are created to adapt with the EFI loader:
- Decoding of Microsoft Authentication Code.
- Decoding of PKCS#9 Authenticate Attributes.
- Extending MbedTLS PKCS#7 lib to support multiple signer's certificates.
- MbedTLS native test suites for PKCS#7 signer's info.
All above 4 patches (tagged with `mbedtls/external`) are submitted to MbedTLS project and being reviewed, eventually they should be part of MbedTLS LTS release. But before that, please merge them into U-Boot, otherwise the building will be broken when MBEDTLS_LIB_X509 is enabled.
See below PR link for the reference: https://github.com/Mbed-TLS/mbedtls/pull/9001
Miscellaneous:
Optimized MbedTLS library size by tailoring the config file and disabling all unnecessary features for EFI loader. From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1, sha256, sha512) are completely replaced when MbedTLS is enabled. From v3, the size-growth is slightly reduced by refactoring Hash functions.
Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% From v3: 4.55%
Please see the latest output from buildman for size-growth on QEMU arm64, Sandbox and Nanopi A64. [1]
Let us inline the growth on qemu_arm64 for a moment: aarch64: (for 1/1 boards) all +6916.0 bss -32.0 data -64.0 rodata +200.0 text +6812.0 qemu_arm64 : all +6916 bss -32 data -64 rodata +200 text +6812 u-boot: add: 28/-17, grow: 12/-16 bytes: 15492/-8304 (7188) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 mbedtls_internal_sha256_process - 2052 +2052 mbedtls_internal_sha512_process - 1056 +1056 K - 896 +896 mbedtls_sha512_finish - 556 +556 mbedtls_sha256_finish - 484 +484 mbedtls_sha1_finish - 420 +420 mbedtls_sha512_starts - 340 +340 mbedtls_md5_finish - 336 +336 mbedtls_sha512_update - 264 +264 mbedtls_sha256_update - 252 +252 mbedtls_sha1_update - 236 +236 mbedtls_md5_update - 236 +236 mbedtls_sha512 - 148 +148 mbedtls_sha256_starts - 124 +124 hash_init_sha512 52 128 +76 hash_init_sha256 52 128 +76 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 hash_init_sha1 52 112 +60 mbedtls_platform_zeroize - 56 +56 mbedtls_sha512_free - 16 +16 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +16 hash_finish_sha512 72 88 +16 hash_finish_sha256 72 88 +16 hash_finish_sha1 72 88 +16 sha512_csum_wd 68 80 +12 sha256_csum_wd 68 80 +12 sha1_csum_wd 68 80 +12 md5_wd 68 80 +12 mbedtls_sha512_init - 12 +12 mbedtls_sha256_init - 12 +12 mbedtls_sha1_init - 12 +12 mbedtls_md5_init - 12 +12 memset_func - 8 +8 sha512_update 4 8 +4 sha384_update 4 8 +4 sha256_update 12 8 -4 sha1_update 12 8 -4 sha256_process 16 - -16 sha1_process 16 - -16 hash_update_sha512 36 16 -20 hash_update_sha256 36 16 -20 hash_update_sha1 36 16 -20 MD5Init 56 36 -20 sha1_starts 60 36 -24 hash_update_sha384 36 - -36 hash_init_sha384 52 - -52 sha384_csum_wd 68 12 -56 sha256_starts 104 40 -64 sha256_padding 64 - -64 sha1_padding 64 - -64 hash_finish_sha384 72 - -72 sha512_finish 152 36 -116 sha512_starts 168 40 -128 sha384_starts 168 40 -128 sha384_finish 152 4 -148 MD5Final 196 44 -152 sha512_base_do_finalize 160 - -160 static.sha256_update 228 - -228 static.sha1_update 240 - -240 sha512_base_do_update 244 - -244 MD5Update 260 - -260 sha1_finish 300 36 -264 sha256_finish 404 36 -368 sha256_armv8_ce_process 428 - -428 sha1_armv8_ce_process 484 - -484 sha512_K 640 - -640 sha512_block_fn 1212 - -1212 MD5Transform 2552 - -2552
And to start with, that's not bad. In fact, tossing LTO in before mbedTLS only changes the top-line a little: aarch64: (for 1/1 boards) all +5120.0 bss -16.0 data -64.0 rodata +200.0 text +5000.0 qemu_arm64 : all +5120 bss -16 data -64 rodata +200 text +5000 u-boot: add: 19/-18, grow: 11/-7 bytes: 14696/-7884 (6812)
But, is there something we can do still? mbedTLS is a more robust solution and I'm accepting there will be growth. But still the process/start/finish is much larger. Is there something configurable there?

Hi Tom,
On Thu, 1 Aug 2024 at 16:46, Tom Rini trini@konsulko.com wrote:
On Wed, Jul 31, 2024 at 10:25:10AM -0700, Raymond Mao wrote:
Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.
Motivations:
- MbedTLS is well maintained with LTS versions.
- LWIP is integrated with MbedTLS and easily to enable HTTPS.
- MbedTLS recently switched license back to GPLv2.
Prerequisite:
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via: $ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually: $ git add --renormalize . $ git commit
New Kconfig options:
`MBEDTLS_LIB` is for MbedTLS general switch. `MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto libs
with
MbedTLS. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. `LEGACY_CRYPTO` is introduced as a main switch for legacy crypto library. `LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and `LEGACY_CRYPTO_CERT` is for the certificate related functionalities. For each of the algorithm, a pair of `<alg>_LEGACY` and `<alg>_MBEDTLS` Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options are introduced.
In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and MBEDTLS_LIB_X509 are by default enabled in qemu_arm64_defconfig and sandbox_defconfig for testing purpose.
Patches for external MbedTLS project:
Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs executables which is not supported by MbedTLS at the moment, addtional patches for MbedTLS are created to adapt with the EFI loader:
- Decoding of Microsoft Authentication Code.
- Decoding of PKCS#9 Authenticate Attributes.
- Extending MbedTLS PKCS#7 lib to support multiple signer's
certificates.
- MbedTLS native test suites for PKCS#7 signer's info.
All above 4 patches (tagged with `mbedtls/external`) are submitted to MbedTLS project and being reviewed, eventually they should be part of MbedTLS LTS release. But before that, please merge them into U-Boot, otherwise the building will be broken when MBEDTLS_LIB_X509 is enabled.
See below PR link for the reference: https://github.com/Mbed-TLS/mbedtls/pull/9001
Miscellaneous:
Optimized MbedTLS library size by tailoring the config file and disabling all unnecessary features for EFI loader. From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1, sha256, sha512) are completely replaced when MbedTLS is enabled. From v3, the size-growth is slightly reduced by refactoring Hash
functions.
Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% From v3: 4.55%
Please see the latest output from buildman for size-growth on QEMU arm64, Sandbox and Nanopi A64. [1]
Let us inline the growth on qemu_arm64 for a moment: aarch64: (for 1/1 boards) all +6916.0 bss -32.0 data -64.0 rodata +200.0 text +6812.0 qemu_arm64 : all +6916 bss -32 data -64 rodata +200 text +6812 u-boot: add: 28/-17, grow: 12/-16 bytes: 15492/-8304 (7188) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 mbedtls_internal_sha256_process - 2052 +2052 mbedtls_internal_sha512_process - 1056 +1056 K - 896 +896 mbedtls_sha512_finish - 556 +556 mbedtls_sha256_finish - 484 +484 mbedtls_sha1_finish - 420 +420 mbedtls_sha512_starts - 340 +340 mbedtls_md5_finish - 336 +336 mbedtls_sha512_update - 264 +264 mbedtls_sha256_update - 252 +252 mbedtls_sha1_update - 236 +236 mbedtls_md5_update - 236 +236 mbedtls_sha512 - 148 +148 mbedtls_sha256_starts - 124 +124 hash_init_sha512 52 128 +76 hash_init_sha256 52 128 +76 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 hash_init_sha1 52 112 +60 mbedtls_platform_zeroize - 56 +56 mbedtls_sha512_free - 16 +16 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +16 hash_finish_sha512 72 88 +16 hash_finish_sha256 72 88 +16 hash_finish_sha1 72 88 +16 sha512_csum_wd 68 80 +12 sha256_csum_wd 68 80 +12 sha1_csum_wd 68 80 +12 md5_wd 68 80 +12 mbedtls_sha512_init - 12 +12 mbedtls_sha256_init - 12 +12 mbedtls_sha1_init - 12 +12 mbedtls_md5_init - 12 +12 memset_func - 8 +8 sha512_update 4 8 +4 sha384_update 4 8 +4 sha256_update 12 8 -4 sha1_update 12 8 -4 sha256_process 16 - -16 sha1_process 16 - -16 hash_update_sha512 36 16 -20 hash_update_sha256 36 16 -20 hash_update_sha1 36 16 -20 MD5Init 56 36 -20 sha1_starts 60 36 -24 hash_update_sha384 36 - -36 hash_init_sha384 52 - -52 sha384_csum_wd 68 12 -56 sha256_starts 104 40 -64 sha256_padding 64 - -64 sha1_padding 64 - -64 hash_finish_sha384 72 - -72 sha512_finish 152 36 -116 sha512_starts 168 40 -128 sha384_starts 168 40 -128 sha384_finish 152 4 -148 MD5Final 196 44 -152 sha512_base_do_finalize 160 - -160 static.sha256_update 228 - -228 static.sha1_update 240 - -240 sha512_base_do_update 244 - -244 MD5Update 260 - -260 sha1_finish 300 36 -264 sha256_finish 404 36 -368 sha256_armv8_ce_process 428 - -428 sha1_armv8_ce_process 484 - -484 sha512_K 640 - -640 sha512_block_fn 1212 - -1212 MD5Transform 2552 - -2552
And to start with, that's not bad. In fact, tossing LTO in before mbedTLS only changes the top-line a little: aarch64: (for 1/1 boards) all +5120.0 bss -16.0 data -64.0 rodata +200.0 text +5000.0 qemu_arm64 : all +5120 bss -16 data -64 rodata +200 text +5000 u-boot: add: 19/-18, grow: 11/-7 bytes: 14696/-7884 (6812)
But, is there something we can do still? mbedTLS is a more robust solution and I'm accepting there will be growth. But still the process/start/finish is much larger. Is there something configurable there?
I have investigated all those MbedTLS native functions with big-size
(_process/_update/_finish). For MD5 and SHA1, we don't have turnable configs. For SHA256 and SHA512, there are a few configs: 1. Performance configs only for Armv8/a64. I didn't turn that on, which might affect the target size as well. 2. Smaller implementation with lower size (only for non-Armv8/a64) at the expense of losing performance. I didn't enable both, as #1 is more for performance and might potentially increase target size; #2 compromises the performance and only for non-Armv8/a64. Looks like that both don't help in reducing the size of qemu_arm64. But I will try #1 on qemu_arm64 and #2 on sandbox and let you know the size impact soon.
Thanks. Regards, Raymond

Hi Tom,
On Fri, 2 Aug 2024 at 11:34, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Thu, 1 Aug 2024 at 16:46, Tom Rini trini@konsulko.com wrote:
On Wed, Jul 31, 2024 at 10:25:10AM -0700, Raymond Mao wrote:
Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.
Motivations:
- MbedTLS is well maintained with LTS versions.
- LWIP is integrated with MbedTLS and easily to enable HTTPS.
- MbedTLS recently switched license back to GPLv2.
Prerequisite:
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via: $ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually: $ git add --renormalize . $ git commit
New Kconfig options:
`MBEDTLS_LIB` is for MbedTLS general switch. `MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto libs
with
MbedTLS. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. `LEGACY_CRYPTO` is introduced as a main switch for legacy crypto
library.
`LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and `LEGACY_CRYPTO_CERT` is for the certificate related functionalities. For each of the algorithm, a pair of `<alg>_LEGACY` and `<alg>_MBEDTLS` Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options are introduced.
In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and MBEDTLS_LIB_X509 are by default enabled in qemu_arm64_defconfig and sandbox_defconfig for testing purpose.
Patches for external MbedTLS project:
Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs executables which is not supported by MbedTLS at the moment, addtional patches for MbedTLS are created to adapt with the EFI loader:
- Decoding of Microsoft Authentication Code.
- Decoding of PKCS#9 Authenticate Attributes.
- Extending MbedTLS PKCS#7 lib to support multiple signer's
certificates.
- MbedTLS native test suites for PKCS#7 signer's info.
All above 4 patches (tagged with `mbedtls/external`) are submitted to MbedTLS project and being reviewed, eventually they should be part of MbedTLS LTS release. But before that, please merge them into U-Boot, otherwise the building will be broken when MBEDTLS_LIB_X509 is enabled.
See below PR link for the reference: https://github.com/Mbed-TLS/mbedtls/pull/9001
Miscellaneous:
Optimized MbedTLS library size by tailoring the config file and disabling all unnecessary features for EFI loader. From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1,
sha256,
sha512) are completely replaced when MbedTLS is enabled. From v3, the size-growth is slightly reduced by refactoring Hash
functions.
Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% From v3: 4.55%
Please see the latest output from buildman for size-growth on QEMU
arm64,
Sandbox and Nanopi A64. [1]
Let us inline the growth on qemu_arm64 for a moment: aarch64: (for 1/1 boards) all +6916.0 bss -32.0 data -64.0 rodata +200.0 text +6812.0 qemu_arm64 : all +6916 bss -32 data -64 rodata +200 text +6812 u-boot: add: 28/-17, grow: 12/-16 bytes: 15492/-8304 (7188) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 mbedtls_internal_sha256_process - 2052 +2052 mbedtls_internal_sha512_process - 1056 +1056 K - 896 +896 mbedtls_sha512_finish - 556 +556 mbedtls_sha256_finish - 484 +484 mbedtls_sha1_finish - 420 +420 mbedtls_sha512_starts - 340 +340 mbedtls_md5_finish - 336 +336 mbedtls_sha512_update - 264 +264 mbedtls_sha256_update - 252 +252 mbedtls_sha1_update - 236 +236 mbedtls_md5_update - 236 +236 mbedtls_sha512 - 148 +148 mbedtls_sha256_starts - 124 +124 hash_init_sha512 52 128 +76 hash_init_sha256 52 128 +76 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 hash_init_sha1 52 112 +60 mbedtls_platform_zeroize - 56 +56 mbedtls_sha512_free - 16 +16 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +16 hash_finish_sha512 72 88 +16 hash_finish_sha256 72 88 +16 hash_finish_sha1 72 88 +16 sha512_csum_wd 68 80 +12 sha256_csum_wd 68 80 +12 sha1_csum_wd 68 80 +12 md5_wd 68 80 +12 mbedtls_sha512_init - 12 +12 mbedtls_sha256_init - 12 +12 mbedtls_sha1_init - 12 +12 mbedtls_md5_init - 12 +12 memset_func - 8 +8 sha512_update 4 8 +4 sha384_update 4 8 +4 sha256_update 12 8 -4 sha1_update 12 8 -4 sha256_process 16 - -16 sha1_process 16 - -16 hash_update_sha512 36 16 -20 hash_update_sha256 36 16 -20 hash_update_sha1 36 16 -20 MD5Init 56 36 -20 sha1_starts 60 36 -24 hash_update_sha384 36 - -36 hash_init_sha384 52 - -52 sha384_csum_wd 68 12 -56 sha256_starts 104 40 -64 sha256_padding 64 - -64 sha1_padding 64 - -64 hash_finish_sha384 72 - -72 sha512_finish 152 36 -116 sha512_starts 168 40 -128 sha384_starts 168 40 -128 sha384_finish 152 4 -148 MD5Final 196 44 -152 sha512_base_do_finalize 160 - -160 static.sha256_update 228 - -228 static.sha1_update 240 - -240 sha512_base_do_update 244 - -244 MD5Update 260 - -260 sha1_finish 300 36 -264 sha256_finish 404 36 -368 sha256_armv8_ce_process 428 - -428 sha1_armv8_ce_process 484 - -484 sha512_K 640 - -640 sha512_block_fn 1212 - -1212 MD5Transform 2552 - -2552
And to start with, that's not bad. In fact, tossing LTO in before mbedTLS only changes the top-line a little: aarch64: (for 1/1 boards) all +5120.0 bss -16.0 data -64.0 rodata +200.0 text +5000.0 qemu_arm64 : all +5120 bss -16 data -64 rodata +200 text +5000 u-boot: add: 19/-18, grow: 11/-7 bytes: 14696/-7884 (6812)
But, is there something we can do still? mbedTLS is a more robust solution and I'm accepting there will be growth. But still the process/start/finish is much larger. Is there something configurable there?
I have investigated all those MbedTLS native functions with big-size
(_process/_update/_finish). For MD5 and SHA1, we don't have turnable configs. For SHA256 and SHA512, there are a few configs:
- Performance configs only for Armv8/a64. I didn't turn that on, which might affect the target size as well.
- Smaller implementation with lower size (only for non-Armv8/a64) at the
expense of losing performance. I didn't enable both, as #1 is more for performance and might potentially increase target size; #2 compromises the performance and only for non-Armv8/a64. Looks like that both don't help in reducing the size of qemu_arm64. But I will try #1 on qemu_arm64 and #2 on sandbox and let you know the size impact soon.
The smaller footprint implementation for SHA256/512 can reduce the target
size significantly on those "<hash>_process()" functions. Please see below output from buildman: ``` aarch64: (for 2/2 boards) all -1468.0 bss +16.0 data -64.0 rodata +200.0 text -1620.0 qemu_arm64 : all +4608 bss +80 data -64 rodata +200 text +4392 u-boot: add: 29/-17, grow: 12/-16 bytes: 13072/-8304 (4768) nanopi_a64 : all -7544 bss -48 data -64 rodata +200 text -7632 u-boot: add: 21/-8, grow: 4/-8 bytes: 10692/-4364 (6328) sandbox: (for 1/1 boards) all +19312.0 data +1440.0 rodata -4128.0 text +22000.0 sandbox : all +19312 data +1440 rodata -4128 text +22000 u-boot: add: 258/-206, grow: 122/-59 bytes: 90286/-76286 (14000) ``` Since this is a trade-off between size and performance, I will add one more kconfig to allow the user to turn it on/off. What are your thoughts?
On the other hand, the "Armv8/a64 only" options depend on NEON instructions, so I will keep them off.
Regards, Raymond

On Wed, Aug 14, 2024 at 09:42:08AM -0400, Raymond Mao wrote:
Hi Tom,
On Fri, 2 Aug 2024 at 11:34, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Thu, 1 Aug 2024 at 16:46, Tom Rini trini@konsulko.com wrote:
On Wed, Jul 31, 2024 at 10:25:10AM -0700, Raymond Mao wrote:
Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.
Motivations:
- MbedTLS is well maintained with LTS versions.
- LWIP is integrated with MbedTLS and easily to enable HTTPS.
- MbedTLS recently switched license back to GPLv2.
Prerequisite:
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via: $ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually: $ git add --renormalize . $ git commit
New Kconfig options:
`MBEDTLS_LIB` is for MbedTLS general switch. `MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto libs
with
MbedTLS. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. `LEGACY_CRYPTO` is introduced as a main switch for legacy crypto
library.
`LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and `LEGACY_CRYPTO_CERT` is for the certificate related functionalities. For each of the algorithm, a pair of `<alg>_LEGACY` and `<alg>_MBEDTLS` Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options are introduced.
In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and MBEDTLS_LIB_X509 are by default enabled in qemu_arm64_defconfig and sandbox_defconfig for testing purpose.
Patches for external MbedTLS project:
Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs executables which is not supported by MbedTLS at the moment, addtional patches for MbedTLS are created to adapt with the EFI loader:
- Decoding of Microsoft Authentication Code.
- Decoding of PKCS#9 Authenticate Attributes.
- Extending MbedTLS PKCS#7 lib to support multiple signer's
certificates.
- MbedTLS native test suites for PKCS#7 signer's info.
All above 4 patches (tagged with `mbedtls/external`) are submitted to MbedTLS project and being reviewed, eventually they should be part of MbedTLS LTS release. But before that, please merge them into U-Boot, otherwise the building will be broken when MBEDTLS_LIB_X509 is enabled.
See below PR link for the reference: https://github.com/Mbed-TLS/mbedtls/pull/9001
Miscellaneous:
Optimized MbedTLS library size by tailoring the config file and disabling all unnecessary features for EFI loader. From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1,
sha256,
sha512) are completely replaced when MbedTLS is enabled. From v3, the size-growth is slightly reduced by refactoring Hash
functions.
Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% From v3: 4.55%
Please see the latest output from buildman for size-growth on QEMU
arm64,
Sandbox and Nanopi A64. [1]
Let us inline the growth on qemu_arm64 for a moment: aarch64: (for 1/1 boards) all +6916.0 bss -32.0 data -64.0 rodata +200.0 text +6812.0 qemu_arm64 : all +6916 bss -32 data -64 rodata +200 text +6812 u-boot: add: 28/-17, grow: 12/-16 bytes: 15492/-8304 (7188) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 mbedtls_internal_sha256_process - 2052 +2052 mbedtls_internal_sha512_process - 1056 +1056 K - 896 +896 mbedtls_sha512_finish - 556 +556 mbedtls_sha256_finish - 484 +484 mbedtls_sha1_finish - 420 +420 mbedtls_sha512_starts - 340 +340 mbedtls_md5_finish - 336 +336 mbedtls_sha512_update - 264 +264 mbedtls_sha256_update - 252 +252 mbedtls_sha1_update - 236 +236 mbedtls_md5_update - 236 +236 mbedtls_sha512 - 148 +148 mbedtls_sha256_starts - 124 +124 hash_init_sha512 52 128 +76 hash_init_sha256 52 128 +76 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 hash_init_sha1 52 112 +60 mbedtls_platform_zeroize - 56 +56 mbedtls_sha512_free - 16 +16 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +16 hash_finish_sha512 72 88 +16 hash_finish_sha256 72 88 +16 hash_finish_sha1 72 88 +16 sha512_csum_wd 68 80 +12 sha256_csum_wd 68 80 +12 sha1_csum_wd 68 80 +12 md5_wd 68 80 +12 mbedtls_sha512_init - 12 +12 mbedtls_sha256_init - 12 +12 mbedtls_sha1_init - 12 +12 mbedtls_md5_init - 12 +12 memset_func - 8 +8 sha512_update 4 8 +4 sha384_update 4 8 +4 sha256_update 12 8 -4 sha1_update 12 8 -4 sha256_process 16 - -16 sha1_process 16 - -16 hash_update_sha512 36 16 -20 hash_update_sha256 36 16 -20 hash_update_sha1 36 16 -20 MD5Init 56 36 -20 sha1_starts 60 36 -24 hash_update_sha384 36 - -36 hash_init_sha384 52 - -52 sha384_csum_wd 68 12 -56 sha256_starts 104 40 -64 sha256_padding 64 - -64 sha1_padding 64 - -64 hash_finish_sha384 72 - -72 sha512_finish 152 36 -116 sha512_starts 168 40 -128 sha384_starts 168 40 -128 sha384_finish 152 4 -148 MD5Final 196 44 -152 sha512_base_do_finalize 160 - -160 static.sha256_update 228 - -228 static.sha1_update 240 - -240 sha512_base_do_update 244 - -244 MD5Update 260 - -260 sha1_finish 300 36 -264 sha256_finish 404 36 -368 sha256_armv8_ce_process 428 - -428 sha1_armv8_ce_process 484 - -484 sha512_K 640 - -640 sha512_block_fn 1212 - -1212 MD5Transform 2552 - -2552
And to start with, that's not bad. In fact, tossing LTO in before mbedTLS only changes the top-line a little: aarch64: (for 1/1 boards) all +5120.0 bss -16.0 data -64.0 rodata +200.0 text +5000.0 qemu_arm64 : all +5120 bss -16 data -64 rodata +200 text +5000 u-boot: add: 19/-18, grow: 11/-7 bytes: 14696/-7884 (6812)
But, is there something we can do still? mbedTLS is a more robust solution and I'm accepting there will be growth. But still the process/start/finish is much larger. Is there something configurable there?
I have investigated all those MbedTLS native functions with big-size
(_process/_update/_finish). For MD5 and SHA1, we don't have turnable configs. For SHA256 and SHA512, there are a few configs:
- Performance configs only for Armv8/a64. I didn't turn that on, which might affect the target size as well.
- Smaller implementation with lower size (only for non-Armv8/a64) at the
expense of losing performance. I didn't enable both, as #1 is more for performance and might potentially increase target size; #2 compromises the performance and only for non-Armv8/a64. Looks like that both don't help in reducing the size of qemu_arm64. But I will try #1 on qemu_arm64 and #2 on sandbox and let you know the size impact soon.
The smaller footprint implementation for SHA256/512 can reduce the target
size significantly on those "<hash>_process()" functions. Please see below output from buildman:
aarch64: (for 2/2 boards) all -1468.0 bss +16.0 data -64.0 rodata +200.0 text -1620.0 qemu_arm64 : all +4608 bss +80 data -64 rodata +200 text +4392 u-boot: add: 29/-17, grow: 12/-16 bytes: 13072/-8304 (4768) nanopi_a64 : all -7544 bss -48 data -64 rodata +200 text -7632 u-boot: add: 21/-8, grow: 4/-8 bytes: 10692/-4364 (6328) sandbox: (for 1/1 boards) all +19312.0 data +1440.0 rodata -4128.0 text +22000.0 sandbox : all +19312 data +1440 rodata -4128 text +22000 u-boot: add: 258/-206, grow: 122/-59 bytes: 90286/-76286 (14000)
Since this is a trade-off between size and performance, I will add one more kconfig to allow the user to turn it on/off. What are your thoughts?
On the other hand, the "Armv8/a64 only" options depend on NEON instructions, so I will keep them off.
Yes, we should have it as a Kconfig option. Can you perhaps do a real-world performance test (so some not-qemu platform) where you sha256 a big hunk of memory? That might help inform the defaults. Also, sorry, I don't understand your comment about NEON instructions. Is it the kind of thing where there's too much core variability in terms of who has what? If so, it too should be an option, but not enabled by default.

Hi Tom,
On Wed, 14 Aug 2024 at 11:07, Tom Rini trini@konsulko.com wrote:
On Wed, Aug 14, 2024 at 09:42:08AM -0400, Raymond Mao wrote:
Hi Tom,
On Fri, 2 Aug 2024 at 11:34, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Thu, 1 Aug 2024 at 16:46, Tom Rini trini@konsulko.com wrote:
On Wed, Jul 31, 2024 at 10:25:10AM -0700, Raymond Mao wrote:
Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.
Motivations:
- MbedTLS is well maintained with LTS versions.
- LWIP is integrated with MbedTLS and easily to enable HTTPS.
- MbedTLS recently switched license back to GPLv2.
Prerequisite:
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via: $ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually: $ git add --renormalize . $ git commit
New Kconfig options:
`MBEDTLS_LIB` is for MbedTLS general switch. `MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto
libs
with
MbedTLS. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode,
ASN1,
and Pubkey parser with MbedTLS. `LEGACY_CRYPTO` is introduced as a main switch for legacy crypto
library.
`LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and `LEGACY_CRYPTO_CERT` is for the certificate related functionalities. For each of the algorithm, a pair of `<alg>_LEGACY` and
`<alg>_MBEDTLS`
Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options
are
introduced.
In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and
MBEDTLS_LIB_X509
are by default enabled in qemu_arm64_defconfig and sandbox_defconfig for testing purpose.
Patches for external MbedTLS project:
Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs executables which is not supported by MbedTLS at the moment, addtional patches for MbedTLS are created to adapt with the EFI
loader:
- Decoding of Microsoft Authentication Code.
- Decoding of PKCS#9 Authenticate Attributes.
- Extending MbedTLS PKCS#7 lib to support multiple signer's
certificates.
- MbedTLS native test suites for PKCS#7 signer's info.
All above 4 patches (tagged with `mbedtls/external`) are submitted
to
MbedTLS project and being reviewed, eventually they should be part
of
MbedTLS LTS release. But before that, please merge them into U-Boot, otherwise the
building
will be broken when MBEDTLS_LIB_X509 is enabled.
See below PR link for the reference: https://github.com/Mbed-TLS/mbedtls/pull/9001
Miscellaneous:
Optimized MbedTLS library size by tailoring the config file and disabling all unnecessary features for EFI loader. From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1,
sha256,
sha512) are completely replaced when MbedTLS is enabled. From v3, the size-growth is slightly reduced by refactoring Hash
functions.
Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% From v3: 4.55%
Please see the latest output from buildman for size-growth on QEMU
arm64,
Sandbox and Nanopi A64. [1]
Let us inline the growth on qemu_arm64 for a moment: aarch64: (for 1/1 boards) all +6916.0 bss -32.0 data -64.0 rodata +200.0 text +6812.0 qemu_arm64 : all +6916 bss -32 data -64 rodata +200
text
+6812 u-boot: add: 28/-17, grow: 12/-16 bytes: 15492/-8304
(7188)
function old
new
delta mbedtls_internal_sha1_process -
4540
+4540 mbedtls_internal_md5_process -
2928
+2928 mbedtls_internal_sha256_process -
2052
+2052 mbedtls_internal_sha512_process -
1056
+1056 K -
896
+896 mbedtls_sha512_finish -
556
+556 mbedtls_sha256_finish -
484
+484 mbedtls_sha1_finish -
420
+420 mbedtls_sha512_starts -
340
+340 mbedtls_md5_finish -
336
+336 mbedtls_sha512_update -
264
+264 mbedtls_sha256_update -
252
+252 mbedtls_sha1_update -
236
+236 mbedtls_md5_update -
236
+236 mbedtls_sha512 -
148
+148 mbedtls_sha256_starts -
124
+124 hash_init_sha512 52
128
+76 hash_init_sha256 52
128
+76 mbedtls_sha1_starts -
72
+72 mbedtls_md5_starts -
60
+60 hash_init_sha1 52
112
+60 mbedtls_platform_zeroize -
56
+56 mbedtls_sha512_free -
16
+16 mbedtls_sha256_free -
16
+16 mbedtls_sha1_free -
16
+16 mbedtls_md5_free -
16
+16 hash_finish_sha512 72
88
+16 hash_finish_sha256 72
88
+16 hash_finish_sha1 72
88
+16 sha512_csum_wd 68
80
+12 sha256_csum_wd 68
80
+12 sha1_csum_wd 68
80
+12 md5_wd 68
80
+12 mbedtls_sha512_init -
12
+12 mbedtls_sha256_init -
12
+12 mbedtls_sha1_init -
12
+12 mbedtls_md5_init -
12
+12 memset_func -
8
+8 sha512_update 4
8
+4 sha384_update 4
8
+4 sha256_update 12
8
-4 sha1_update 12
8
-4 sha256_process 16
-16 sha1_process 16
-16 hash_update_sha512 36
16
-20 hash_update_sha256 36
16
-20 hash_update_sha1 36
16
-20 MD5Init 56
36
-20 sha1_starts 60
36
-24 hash_update_sha384 36
-36 hash_init_sha384 52
-52 sha384_csum_wd 68
12
-56 sha256_starts 104
40
-64 sha256_padding 64
-64 sha1_padding 64
-64 hash_finish_sha384 72
-72 sha512_finish 152
36
-116 sha512_starts 168
40
-128 sha384_starts 168
40
-128 sha384_finish 152
4
-148 MD5Final 196
44
-152 sha512_base_do_finalize 160
-160 static.sha256_update 228
-228 static.sha1_update 240
-240 sha512_base_do_update 244
-244 MD5Update 260
-260 sha1_finish 300
36
-264 sha256_finish 404
36
-368 sha256_armv8_ce_process 428
-428 sha1_armv8_ce_process 484
-484 sha512_K 640
-640 sha512_block_fn 1212
-1212 MD5Transform 2552
-2552
And to start with, that's not bad. In fact, tossing LTO in before
mbedTLS
only changes the top-line a little: aarch64: (for 1/1 boards) all +5120.0 bss -16.0 data -64.0 rodata +200.0 text +5000.0 qemu_arm64 : all +5120 bss -16 data -64 rodata +200
text
+5000 u-boot: add: 19/-18, grow: 11/-7 bytes: 14696/-7884
(6812)
But, is there something we can do still? mbedTLS is a more robust solution and I'm accepting there will be growth. But still the process/start/finish is much larger. Is there something configurable there?
I have investigated all those MbedTLS native functions with big-size
(_process/_update/_finish). For MD5 and SHA1, we don't have turnable configs. For SHA256 and SHA512, there are a few configs:
- Performance configs only for Armv8/a64. I didn't turn that on, which might affect the target size as well.
- Smaller implementation with lower size (only for non-Armv8/a64) at
the
expense of losing performance. I didn't enable both, as #1 is more for performance and might
potentially
increase target size; #2 compromises the performance and only for non-Armv8/a64. Looks like that both don't help in reducing the size of qemu_arm64. But I will try #1 on qemu_arm64 and #2 on sandbox and let you know the size impact soon.
The smaller footprint implementation for SHA256/512 can reduce the
target
size significantly on those "<hash>_process()" functions. Please see below output from
buildman:
aarch64: (for 2/2 boards) all -1468.0 bss +16.0 data -64.0 rodata
+200.0
text -1620.0 qemu_arm64 : all +4608 bss +80 data -64 rodata +200 text +4392 u-boot: add: 29/-17, grow: 12/-16 bytes: 13072/-8304
(4768)
nanopi_a64 : all -7544 bss -48 data -64 rodata +200 text
-7632 u-boot: add: 21/-8, grow: 4/-8 bytes: 10692/-4364 (6328) sandbox: (for 1/1 boards) all +19312.0 data +1440.0 rodata -4128.0
text
+22000.0 sandbox : all +19312 data +1440 rodata -4128 text
+22000
u-boot: add: 258/-206, grow: 122/-59 bytes: 90286/-76286
(14000)
Since this is a trade-off between size and performance, I will add one
more
kconfig to allow the user to turn it on/off. What are your thoughts?
On the other hand, the "Armv8/a64 only" options depend on NEON instructions, so I will keep them off.
Yes, we should have it as a Kconfig option. Can you perhaps do a real-world performance test (so some not-qemu platform) where you sha256 a big hunk of memory? That might help inform the defaults.
Below are a few tests I did on my Ubuntu PC, leveraging the benchmark tool. I measured two key factors, throughput and the number of CPU cycles per byte. Each process was done with a 1KB data block. The throughput was measured in an average data process (KiB/s) in 10 seconds. The number of CPU cycles per byte is an average number of processing 4096 times with the same data block size.
See below result:
Original: SHA-256 : 87972 KiB/s, 23 cycles/byte SHA-512 : 107328 KiB/s, 20 cycles/byte
Smaller implementations: SHA-256 : 65872 KiB/s, 36 cycles/byte SHA-512 : 94059 KiB/s, 23 cycles/byte
Please note that this is not very precise as it depends on many other factors, but we still can take this as a reference. As we can see here, the "smaller" one is not too bad. I would put the kconfig for the "smaller" one as a default config when MbedTLS is selected for qemu64 and sandbox. Other platforms can decide what they want depends on the real performance on each platform. Is this fine for you? Please feel free to advise.
Also, sorry, I don't understand your comment about NEON instructions. Is it the kind of thing where there's too much core variability in terms of who has what? If so, it too should be an option, but not enabled by default.
The Armv8/A64 accelerating config depends on some of the NEON instructions
for example, vaddq_u32() and vaddq_u64(). Please see this link for the reference: https://developer.arm.com/documentation/dht0002/a/Introducing-NEON/Developin... I think we are missing this in U-Boot. I would suggest ignoring it at the moment (keep them all off).
Regards, Raymond

On Wed, Aug 14, 2024 at 01:49:43PM -0400, Raymond Mao wrote:
Hi Tom,
On Wed, 14 Aug 2024 at 11:07, Tom Rini trini@konsulko.com wrote:
On Wed, Aug 14, 2024 at 09:42:08AM -0400, Raymond Mao wrote:
Hi Tom,
On Fri, 2 Aug 2024 at 11:34, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Thu, 1 Aug 2024 at 16:46, Tom Rini trini@konsulko.com wrote:
On Wed, Jul 31, 2024 at 10:25:10AM -0700, Raymond Mao wrote:
Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.
Motivations:
- MbedTLS is well maintained with LTS versions.
- LWIP is integrated with MbedTLS and easily to enable HTTPS.
- MbedTLS recently switched license back to GPLv2.
Prerequisite:
This patch series requires mbedtls git repo to be added as a subtree to the main U-Boot repo via: $ git subtree add --prefix lib/mbedtls/external/mbedtls \ https://github.com/Mbed-TLS/mbedtls.git \ v3.6.0 --squash Moreover, due to the Windows-style files from mbedtls git repo, we need to convert the CRLF endings to LF and do a commit manually: $ git add --renormalize . $ git commit
New Kconfig options:
`MBEDTLS_LIB` is for MbedTLS general switch. `MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto
libs
with
MbedTLS. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode,
ASN1,
and Pubkey parser with MbedTLS. `LEGACY_CRYPTO` is introduced as a main switch for legacy crypto
library.
`LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and `LEGACY_CRYPTO_CERT` is for the certificate related functionalities. For each of the algorithm, a pair of `<alg>_LEGACY` and
`<alg>_MBEDTLS`
Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options
are
introduced.
In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and
MBEDTLS_LIB_X509
are by default enabled in qemu_arm64_defconfig and sandbox_defconfig for testing purpose.
Patches for external MbedTLS project:
Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs executables which is not supported by MbedTLS at the moment, addtional patches for MbedTLS are created to adapt with the EFI
loader:
- Decoding of Microsoft Authentication Code.
- Decoding of PKCS#9 Authenticate Attributes.
- Extending MbedTLS PKCS#7 lib to support multiple signer's
certificates.
- MbedTLS native test suites for PKCS#7 signer's info.
All above 4 patches (tagged with `mbedtls/external`) are submitted
to
MbedTLS project and being reviewed, eventually they should be part
of
MbedTLS LTS release. But before that, please merge them into U-Boot, otherwise the
building
will be broken when MBEDTLS_LIB_X509 is enabled.
See below PR link for the reference: https://github.com/Mbed-TLS/mbedtls/pull/9001
Miscellaneous:
Optimized MbedTLS library size by tailoring the config file and disabling all unnecessary features for EFI loader. From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1,
sha256,
sha512) are completely replaced when MbedTLS is enabled. From v3, the size-growth is slightly reduced by refactoring Hash
functions.
Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% From v3: 4.55%
Please see the latest output from buildman for size-growth on QEMU
arm64,
Sandbox and Nanopi A64. [1]
Let us inline the growth on qemu_arm64 for a moment: aarch64: (for 1/1 boards) all +6916.0 bss -32.0 data -64.0 rodata +200.0 text +6812.0 qemu_arm64 : all +6916 bss -32 data -64 rodata +200
text
+6812 u-boot: add: 28/-17, grow: 12/-16 bytes: 15492/-8304
(7188)
function old
new
delta mbedtls_internal_sha1_process -
4540
+4540 mbedtls_internal_md5_process -
2928
+2928 mbedtls_internal_sha256_process -
2052
+2052 mbedtls_internal_sha512_process -
1056
+1056 K -
896
+896 mbedtls_sha512_finish -
556
+556 mbedtls_sha256_finish -
484
+484 mbedtls_sha1_finish -
420
+420 mbedtls_sha512_starts -
340
+340 mbedtls_md5_finish -
336
+336 mbedtls_sha512_update -
264
+264 mbedtls_sha256_update -
252
+252 mbedtls_sha1_update -
236
+236 mbedtls_md5_update -
236
+236 mbedtls_sha512 -
148
+148 mbedtls_sha256_starts -
124
+124 hash_init_sha512 52
128
+76 hash_init_sha256 52
128
+76 mbedtls_sha1_starts -
72
+72 mbedtls_md5_starts -
60
+60 hash_init_sha1 52
112
+60 mbedtls_platform_zeroize -
56
+56 mbedtls_sha512_free -
16
+16 mbedtls_sha256_free -
16
+16 mbedtls_sha1_free -
16
+16 mbedtls_md5_free -
16
+16 hash_finish_sha512 72
88
+16 hash_finish_sha256 72
88
+16 hash_finish_sha1 72
88
+16 sha512_csum_wd 68
80
+12 sha256_csum_wd 68
80
+12 sha1_csum_wd 68
80
+12 md5_wd 68
80
+12 mbedtls_sha512_init -
12
+12 mbedtls_sha256_init -
12
+12 mbedtls_sha1_init -
12
+12 mbedtls_md5_init -
12
+12 memset_func -
8
+8 sha512_update 4
8
+4 sha384_update 4
8
+4 sha256_update 12
8
-4 sha1_update 12
8
-4 sha256_process 16
-16 sha1_process 16
-16 hash_update_sha512 36
16
-20 hash_update_sha256 36
16
-20 hash_update_sha1 36
16
-20 MD5Init 56
36
-20 sha1_starts 60
36
-24 hash_update_sha384 36
-36 hash_init_sha384 52
-52 sha384_csum_wd 68
12
-56 sha256_starts 104
40
-64 sha256_padding 64
-64 sha1_padding 64
-64 hash_finish_sha384 72
-72 sha512_finish 152
36
-116 sha512_starts 168
40
-128 sha384_starts 168
40
-128 sha384_finish 152
4
-148 MD5Final 196
44
-152 sha512_base_do_finalize 160
-160 static.sha256_update 228
-228 static.sha1_update 240
-240 sha512_base_do_update 244
-244 MD5Update 260
-260 sha1_finish 300
36
-264 sha256_finish 404
36
-368 sha256_armv8_ce_process 428
-428 sha1_armv8_ce_process 484
-484 sha512_K 640
-640 sha512_block_fn 1212
-1212 MD5Transform 2552
-2552
And to start with, that's not bad. In fact, tossing LTO in before
mbedTLS
only changes the top-line a little: aarch64: (for 1/1 boards) all +5120.0 bss -16.0 data -64.0 rodata +200.0 text +5000.0 qemu_arm64 : all +5120 bss -16 data -64 rodata +200
text
+5000 u-boot: add: 19/-18, grow: 11/-7 bytes: 14696/-7884
(6812)
But, is there something we can do still? mbedTLS is a more robust solution and I'm accepting there will be growth. But still the process/start/finish is much larger. Is there something configurable there?
I have investigated all those MbedTLS native functions with big-size
(_process/_update/_finish). For MD5 and SHA1, we don't have turnable configs. For SHA256 and SHA512, there are a few configs:
- Performance configs only for Armv8/a64. I didn't turn that on, which might affect the target size as well.
- Smaller implementation with lower size (only for non-Armv8/a64) at
the
expense of losing performance. I didn't enable both, as #1 is more for performance and might
potentially
increase target size; #2 compromises the performance and only for non-Armv8/a64. Looks like that both don't help in reducing the size of qemu_arm64. But I will try #1 on qemu_arm64 and #2 on sandbox and let you know the size impact soon.
The smaller footprint implementation for SHA256/512 can reduce the
target
size significantly on those "<hash>_process()" functions. Please see below output from
buildman:
aarch64: (for 2/2 boards) all -1468.0 bss +16.0 data -64.0 rodata
+200.0
text -1620.0 qemu_arm64 : all +4608 bss +80 data -64 rodata +200 text +4392 u-boot: add: 29/-17, grow: 12/-16 bytes: 13072/-8304
(4768)
nanopi_a64 : all -7544 bss -48 data -64 rodata +200 text
-7632 u-boot: add: 21/-8, grow: 4/-8 bytes: 10692/-4364 (6328) sandbox: (for 1/1 boards) all +19312.0 data +1440.0 rodata -4128.0
text
+22000.0 sandbox : all +19312 data +1440 rodata -4128 text
+22000
u-boot: add: 258/-206, grow: 122/-59 bytes: 90286/-76286
(14000)
Since this is a trade-off between size and performance, I will add one
more
kconfig to allow the user to turn it on/off. What are your thoughts?
On the other hand, the "Armv8/a64 only" options depend on NEON instructions, so I will keep them off.
Yes, we should have it as a Kconfig option. Can you perhaps do a real-world performance test (so some not-qemu platform) where you sha256 a big hunk of memory? That might help inform the defaults.
Below are a few tests I did on my Ubuntu PC, leveraging the benchmark tool. I measured two key factors, throughput and the number of CPU cycles per byte. Each process was done with a 1KB data block. The throughput was measured in an average data process (KiB/s) in 10 seconds. The number of CPU cycles per byte is an average number of processing 4096 times with the same data block size.
See below result:
Original: SHA-256 : 87972 KiB/s, 23 cycles/byte SHA-512 : 107328 KiB/s, 20 cycles/byte
Smaller implementations: SHA-256 : 65872 KiB/s, 36 cycles/byte SHA-512 : 94059 KiB/s, 23 cycles/byte
Please note that this is not very precise as it depends on many other factors, but we still can take this as a reference. As we can see here, the "smaller" one is not too bad. I would put the kconfig for the "smaller" one as a default config when MbedTLS is selected for qemu64 and sandbox. Other platforms can decide what they want depends on the real performance on each platform. Is this fine for you? Please feel free to advise.
Thanks. Yes, we should just default to "smaller" for everyone.
Also, sorry, I don't understand your comment about NEON instructions. Is it the kind of thing where there's too much core variability in terms of who has what? If so, it too should be an option, but not enabled by default.
The Armv8/A64 accelerating config depends on some of the NEON instructions
for example, vaddq_u32() and vaddq_u64(). Please see this link for the reference: https://developer.arm.com/documentation/dht0002/a/Introducing-NEON/Developin... I think we are missing this in U-Boot. I would suggest ignoring it at the moment (keep them all off).
Ah OK, follow-up work then.
participants (3)
-
Ilias Apalodimas
-
Raymond Mao
-
Tom Rini