[PATCH v8 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_CRYPTO_ALT` is for using original U-Boot crypto libs as MbedTLS crypto alternatives. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected when `MBEDTLS_LIB` is enabled. `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. From v6, smaller implementations for SHA256 and SHA512 are enabled and
target size reduce significantly. Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% v3 - v5: 4.55% v6: 2.90%
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 (With both `MBEDTLS_LIB` and `MBEDTLS_LIB_CRYPTO` selected) (qemu_arm64, sandbox and nanopi_a64) ``` aarch64: (for 2/2 boards) all -1568.0 bss -8.0 data -64.0 rodata +200.0 text -1696.0 qemu_arm64 : all +4472 bss -16 data -64 rodata +200 text +4352 u-boot: add: 29/-14, grow: 6/-13 bytes: 12812/-8084 (4728) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 K - 896 +896 mbedtls_sha256_finish - 484 +484 mbedtls_internal_sha256_process - 432 +432 mbedtls_sha1_finish - 420 +420 mbedtls_internal_sha512_process - 412 +412 mbedtls_sha512_finish - 360 +360 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 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 mbedtls_platform_zeroize - 56 +56 sha512_put_uint64_be - 40 +40 mbedtls_sha512_free - 16 +16 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +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 MD5Init 56 36 -20 sha1_starts 60 36 -24 sha384_csum_wd 68 12 -56 sha256_starts 104 40 -64 sha256_padding 64 - -64 sha1_padding 64 - -64 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 -7608 data -64 rodata +200 text -7744 u-boot: add: 21/-6, grow: 0/-8 bytes: 10524/-4308 (6216) function old new delta mbedtls_internal_sha1_process - 4540 +4540 mbedtls_internal_md5_process - 2928 +2928 mbedtls_sha256_finish - 484 +484 mbedtls_internal_sha256_process - 432 +432 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 mbedtls_sha1_starts - 72 +72 mbedtls_md5_starts - 60 +60 mbedtls_platform_zeroize - 56 +56 mbedtls_sha256_free - 16 +16 mbedtls_sha1_free - 16 +16 mbedtls_md5_free - 16 +16 mbedtls_sha256_init - 12 +12 mbedtls_sha1_init - 12 +12 mbedtls_md5_init - 12 +12 memset_func - 8 +8 sha256_update 12 8 -4 sha1_update 12 8 -4 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 +17776.0 bss +128.0 data +1376.0 rodata -4288.0 text +20560.0 sandbox : all +17776 bss +128 data +1376 rodata -4288 text +20560 u-boot: add: 246/-205, grow: 85/-47 bytes: 92037/-80203 (11834) function old new delta mbr_test_run - 6557 +6557 static.compress_using_gzip - 5344 +5344 mbedtls_internal_sha1_process - 4982 +4982 static.mbedtls_x509_crt_parse_der_internal - 4184 +4184 pkcs7_parse_message 361 3638 +3277 rsa_verify 541 2794 +2253 mbedtls_internal_md5_process - 2189 +2189 mbedtls_rsa_parse_pubkey - 2045 +2045 static.make_fuller_fdt - 1991 +1991 mbedtls_rsa_private - 1813 +1813 compress_frame_buffer - 1704 +1704 mbedtls_mpi_exp_mod - 1649 +1649 wget_handler - 1483 +1483 x509_populate_cert - 1462 +1462 mbedtls_mpi_div_mpi - 1455 +1455 static.mbedtls_x509_dn_gets - 1305 +1305 mbedtls_mpi_inv_mod - 1214 +1214 tftp_handler - 1199 +1199 mbedtls_rsa_rsaes_pkcs1_v15_decrypt - 1156 +1156 mbedtls_x509_get_subject_alt_name_ext - 1155 +1155 tcg2_log_parse - 1060 +1060 HUF_decompress4X1_usingDTable_internal_body - 1029 +1029 rsa_check_pair_wrap - 1018 +1018 static.K - 896 +896 oid_x520_attr_type - 840 +840 load_sandbox_scmi_test_devices - 776 +776 static.prep_mmc_bootdev - 773 +773 efi_load_image 4418 5157 +739 static.pkcs7_get_signer_info - 671 +671 mbedtls_mpi_core_montmul - 537 +537 mbedtls_internal_sha512_process - 536 +536 mbedtls_mpi_core_mla - 520 +520 static.compress_using_zstd - 498 +498 static.compress_using_lzo - 498 +498 static.compress_using_lzma - 498 +498 static.compress_using_lz4 - 498 +498 static.compress_using_bzip2 - 498 +498 mbedtls_internal_sha256_process - 487 +487 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 mbedtls_sha1_finish - 455 +455 new_string - 450 +450 set_string - 448 +448 wget_send_stored - 434 +434 rsa_rsassa_pkcs1_v15_encode - 414 +414 mbedtls_mpi_gcd - 409 +409 get_languages - 402 +402 list_package_lists - 398 +398 efi_cin_read_key_stroke_ex - 393 +393 update_package_list - 374 +374 static.dns_handler - 374 +374 fastboot_handler - 363 +363 static.efi_str_to_fat - 362 +362 oid_x509_ext - 360 +360 get_string 166 526 +360 new_package_list - 359 +359 efi_convert_device_path_to_text - 359 +359 mbedtls_sha512_finish - 358 +358 rsa_sign_wrap - 355 +355 get_keyboard_layout - 355 +355 add_sub_mpi - 355 +355 find_keyboard_layouts - 339 +339 static.scan_mmc_bootdev - 338 +338 rsa_verify_wrap - 324 +324 oid_sig_alg - 320 +320 mbedtls_mpi_sub_abs - 315 +315 static.sqfs_split_path - 313 +313 append_device_path_instance - 311 +311 efi_cin_register_key_notify - 303 +303 get_secondary_languages - 301 +301 rsa_encrypt_wrap - 294 +294 efi_convert_device_node_to_text - 293 +293 get_next_device_path_instance - 290 +290 mbedtls_mpi_core_get_mont_r2_unsafe - 276 +276 public_key - 270 +270 efi_cin_unregister_key_notify - 268 +268 static.rsa_check_context - 264 +264 public_key_verify_signature 419 678 +259 __udivti3 - 248 +248 static.efi_stri_coll - 247 +247 static.oid_md_alg - 240 +240 mbedtls_rsa_public - 239 +239 mbedtls_asn1_get_alg - 238 +238 get_package_list_handle - 231 +231 static.overlay_get_target - 224 +224 mbedtls_mpi_shift_l - 224 +224 static.efi_fat_to_str - 223 +223 mbedtls_pkcs7_free - 223 +223 register_package_notify - 222 +222 create_device_node - 222 +222 mbedtls_mpi_fill_random - 221 +221 mbedtls_sha512_update - 209 +209 remove_package_list - 208 +208 export_package_lists - 206 +206 is_device_path_multi_instance - 201 +201 mbedtls_mpi_copy - 200 +200 mbedtls_sha256_update - 197 +197 set_keyboard_layout - 196 +196 static.asn1_get_tagged_int - 194 +194 efi_cin_reset_ex - 194 +194 get_device_path_size - 191 +191 append_device_path - 190 +190 static.efi_metai_match - 188 +188 append_device_node - 188 +188 static.efi_str_upr - 187 +187 static.efi_str_lwr - 187 +187 mbedtls_pk_parse_public_key - 182 +182 duplicate_device_path - 180 +180 mbedtls_x509_crt_free - 177 +177 static.mbedtls_sha1_update - 176 +176 sha256_finish 357 533 +176 fastboot_timed_send_info - 174 +174 mbedtls_mpi_shift_r - 170 +170 unregister_package_notify - 169 +169 efi_cin_set_state - 169 +169 static.cdp_compute_csum - 168 +168 efi_key_notify - 164 +164 efi_console_timer_notify - 164 +164 static.cdp_send_trigger - 161 +161 rsa_free_wrap - 161 +161 mbedtls_mpi_cmp_mpi - 161 +161 static.pkcs7_get_one_cert - 160 +160 oid_pk_alg - 160 +160 sha384_starts - 159 +159 mbedtls_mpi_read_binary - 159 +159 md5_wd 571 729 +158 mbedtls_mpi_core_write_be - 154 +154 mbedtls_mpi_mod_mpi - 146 +146 mbedtls_asn1_get_alg_null - 142 +142 mbedtls_mpi_cmp_abs - 141 +141 mbedtls_mpi_mul_int - 138 +138 HUF_decompress1X1_usingDTable_internal_body - 138 +138 mbedtls_asn1_get_len - 133 +133 wget_timeout_handler - 131 +131 tftp_filename - 128 +128 static.setup_ctx_and_base_tables - 122 +122 static.overlay_adjust_node_phandles - 121 +121 mbedtls_mpi_grow - 120 +120 mbedtls_rsa_check_pubkey - 110 +110 static.mbedtls_asn1_get_bitstring - 108 +108 x509_get_timestamp - 106 +106 ZSTD_frameHeaderSize_internal - 103 +103 tftp_timeout_handler - 102 +102 data_gz 21367 21468 +101 static.uncompress_using_bzip2 - 100 +100 mbedtls_asn1_get_bool - 99 +99 static.uncompress_using_lzma - 98 +98 static.asn1_get_sequence_of_cb - 98 +98 mbedtls_rsa_info - 96 +96 static.uncompress_using_lzo - 95 +95 static.uncompress_using_lz4 - 95 +95 static.uncompress_using_gzip - 90 +90 release_sandbox_scmi_test_devices - 88 +88 mbedtls_x509_get_serial - 88 +88 inject_response - 88 +88 mbedtls_mpi_resize_clear - 87 +87 mbedtls_mpi_bitlen - 82 +82 static.x509_get_uid - 81 +81 static.mbedtls_mpi_sub_int - 81 +81 mbedtls_oid_get_md_alg - 78 +78 mbedtls_mpi_cmp_int - 75 +75 rsa_decrypt_wrap - 73 +73 static.cdp_timeout_handler - 72 +72 sha512_put_uint64_be - 72 +72 mbedtls_md_info_from_type - 72 +72 mbedtls_mpi_lset - 69 +69 sha1_starts - 64 +64 rsa_alloc_wrap - 62 +62 mbedtls_pk_setup - 62 +62 static.clear_bloblist - 61 +61 pkcs7_free_message 115 176 +61 rsa_debug - 60 +60 mbedtls_mpi_lsb - 60 +60 lib_test_strlcat 1195 1255 +60 public_key_signature_free - 58 +58 static.x509_free_mbedtls_ctx - 57 +57 x509_populate_dn_name_string - 56 +56 mbedtls_mpi_core_montmul_init - 55 +55 mbedtls_asn1_get_bitstring_null - 53 +53 static.pkcs7_free_signer_info - 51 +51 mbedtls_mpi_free - 51 +51 static.mbedtls_mpi_core_bigendian_to_host - 50 +50 mbedtls_asn1_get_tag - 50 +50 BIT_reloadDStreamFast - 50 +50 tftp_init_load_addr - 47 +47 mbedtls_pk_free - 45 +45 mbedtls_zeroize_and_free - 42 +42 x509_parse2_int - 33 +33 mbedtls_asn1_sequence_free - 30 +30 mbedtls_asn1_free_named_data_list_shallow - 30 +30 static.check_zero - 28 +28 static.himport_r 968 995 +27 static.hexport_r 653 680 +27 sha512_starts 132 159 +27 generic_phy_get_bulk 366 392 +26 reboot_mode_probe 139 164 +25 static.mbedtls_mpi_get_bit - 23 +23 static.sqfs_opendir_nest 1655 1677 +22 rsa_can_do - 22 +22 ping_timeout_handler - 22 +22 static.mbedtls_platform_zeroize - 18 +18 static.hash_finish_sha1 40 58 +18 sha256_starts 68 86 +18 mbedtls_mpi_size - 18 +18 c2 - 18 +18 rsa_get_bitlen - 17 +17 static.time_start - 16 +16 static.__reset_get_bulk 166 182 +16 clk_get_bulk 157 173 +16 unicode_test_utf8_utf16_strcpy 946 960 +14 mbedtls_mpi_add_mpi - 14 +14 c4 - 14 +14 c1 - 14 +14 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 efi_auth_var_get_type 102 113 +11 i1 - 10 +10 d3 - 10 +10 d2 - 10 +10 x509_free_certificate 115 124 +9 wget_load_size - 8 +8 tftp_load_addr - 8 +8 tftp_cur_block - 8 +8 static.memset_func - 8 +8 packet_icmp_handler - 8 +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 image_url - 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 mpi_bigendian_to_host - 7 +7 efi_auth_var_get_guid 81 88 +7 d1 - 7 +7 string_to_vlan 35 41 +6 ping6_timeout - 6 +6 j3 - 6 +6 j2 - 6 +6 efi_signature_verify 1640 1646 +6 static.test_data - 5 +5 on_vlan 28 33 +5 on_nvlan 28 33 +5 j1 - 5 +5 eficonfig_process_select_file 2179 2184 +5 crypt_sha512crypt_rn_wrapped 2408 2413 +5 crypt_sha256crypt_rn_wrapped 1669 1674 +5 wget_timeout_count - 4 +4 unicode_test_u16_strlen 269 273 +4 timeout_count_max - 4 +4 timeout_count - 4 +4 tftp_state - 4 +4 tftp_our_port - 4 +4 static.net_arp_wait_reply_ip - 4 +4 static.eth_errno - 4 +4 static.dns_our_port - 4 +4 static.cdp_seq - 4 +4 static.cdp_ok - 4 +4 static.bootdev_test_prio 928 932 +4 static.bootdev_test_order_default 562 566 +4 static.bootdev_test_order 2435 2439 +4 rmt_timestamp - 4 +4 retry_tcp_seq_num - 4 +4 retry_tcp_ack_num - 4 +4 retry_len - 4 +4 our_port - 4 +4 net_set_udp_header 103 107 +4 loc_timestamp - 4 +4 fastboot_our_port - 4 +4 eficonfig_edit_boot_option 1563 1567 +4 efi_launch_capsules 3138 3142 +4 efi_init_early 1051 1055 +4 current_wget_state - 4 +4 current_tcp_state - 4 +4 bootp_reset 48 52 +4 bootp_request 632 636 +4 asymmetric_key_generate_id 109 113 +4 arp_request 87 91 +4 arp_raw_request 223 227 +4 adler32 767 771 +4 unicode_test_u16_strncmp 377 380 +3 str_upper 648 651 +3 eficonfig_file_selected 484 487 +3 efi_init_obj_list 5873 5876 +3 efi_create_indexed_name 174 177 +3 bloblist_test_grow 719 722 +3 SHA256_Update_recycled 76 79 +3 unicode_test_utf8_utf16_strncpy 929 931 +2 unicode_test_utf16_utf8_strncpy 921 923 +2 tftp_windowsize - 2 +2 tftp_next_ack - 2 +2 tftp_block_size - 2 +2 static.tcg2_measure_variable 236 238 +2 static.efi_cout_output_string 541 543 +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 503 505 +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 static.hash_update_sha1 29 30 +1 static.efi_set_variable_runtime 553 554 +1 retry_action - 1 +1 file_open 738 739 +1 efi_var_mem_ins 287 288 +1 efi_set_variable_int 1929 1930 +1 efi_dp_from_file 278 279 +1 static.retry_action 1 - -1 fastboot_send 1815 1814 -1 byteReverse 1 - -1 static.tftp_windowsize 2 - -2 static.tftp_next_ack 2 - -2 static.tftp_block_size 2 - -2 sha256_csum_wd 155 153 -2 net_send_udp_packet6 415 413 -2 net_set_timeout_handler 26 23 -3 fdt_open_into 435 432 -3 fdt_delprop 121 118 -3 tftp_start 1367 1363 -4 static.wget_timeout_count 4 - -4 static.timeout_count_max 4 - -4 static.timeout_count 4 - -4 static.tftp_state 4 - -4 static.tftp_our_port 4 - -4 static.rmt_timestamp 4 - -4 static.retry_tcp_seq_num 4 - -4 static.retry_tcp_ack_num 4 - -4 static.retry_len 4 - -4 static.our_port 4 - -4 static.loc_timestamp 4 - -4 static.fastboot_our_port 4 - -4 static.current_wget_state 4 - -4 static.current_tcp_state 4 - -4 static.alist_expand_to 120 116 -4 static.ZSTD_freeDDict 89 85 -4 sha512_csum_wd 169 165 -4 rarp_request 202 198 -4 pcap_post 321 317 -4 net_send_tcp_packet 52 48 -4 net_arp_wait_reply_ip 4 - -4 ndisc_request 451 447 -4 ip6_add_hdr 77 73 -4 fdt_find_string_ 83 79 -4 fdt_check_node_offset_ 46 42 -4 eth_errno 4 - -4 efi_dp_from_uart 87 83 -4 dns_our_port 4 - -4 dm_check_devices 251 247 -4 dhcp6_start 236 232 -4 cdp_seq 4 - -4 cdp_ok 4 - -4 ZSTD_getFrameHeader_advanced 449 445 -4 test_data 5 - -5 lib_test_efi_dp_check_length 593 588 -5 static.ping6_timeout 6 - -6 net_cdp_ethaddr 6 - -6 fdt_pack 80 74 -6 fdt_create_empty_tree 102 96 -6 fdt_add_subnode 312 306 -6 ZSTD_initFseState 44 37 -7 static.wget_load_size 8 - -8 static.tftp_load_addr 8 - -8 static.tftp_cur_block 8 - -8 static.packet_icmp_handler 8 - -8 static.image_url 8 - -8 static.BIT_initDStream 518 510 -8 sha384_csum_wd 296 288 -8 cdp_snap_hdr 8 - -8 static.fdt_rw_probe_ 79 70 -9 ZSTD_decompressDCtx 7745 7736 -9 rsa_verify_key 383 372 -11 fdt_setprop 147 135 -12 sha256_update 14 - -14 x509_akid_note_name 15 - -15 pkcs7_sig_note_skid 15 - -15 pkcs7_sig_note_serial 15 - -15 pkcs7_sig_note_issuer 15 - -15 time_start 16 - -16 static.rsapubkey_action_table 16 - -16 fdt_add_mem_rsv 101 85 -16 fdt_del_mem_rsv 84 67 -17 x509_note_serial 21 - -21 static.ping_timeout_handler 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 check_zero 24 - -24 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 _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 sha1_csum_wd 209 176 -33 static.hash_init_sha1 75 41 -34 static.hash_finish_sha384 40 6 -34 x509_note_subject 36 - -36 pkcs7_note_content 36 - -36 HUF_decodeStreamX1 187 151 -36 static.ZSTD_decodeSequence 462 425 -37 x509_akid_action_table 40 - -40 x509_note_params 41 - -41 pkcs7_note_signeddata_version 41 - -41 asn1_op_lengths 41 - -41 pkcs7_note_certificate_list 46 - -46 static.public_key_signature_free 48 - -48 static.tftp_init_load_addr 51 - -51 mscode_note_digest 51 - -51 static.BIT_reloadDStreamFast 54 - -54 rsa_get_e 56 - -56 clear_bloblist 57 - -57 x509_extract_name_segment 62 - -62 sha256_padding 64 - -64 sha1_padding 64 - -64 pkcs7_sig_note_signature 68 - -68 pkcs7_sig_note_set_of_authattrs 72 - -72 cdp_timeout_handler 72 - -72 pkcs7_sig_note_pkey_algo 75 - -75 sha512_finish 123 47 -76 sha384_finish 123 47 -76 pkcs7_note_signerinfo_version 79 - -79 x509_akid_note_kid 80 - -80 x509_akid_note_serial 81 - -81 pkcs7_extract_cert 81 - -81 net_loop 3226 3145 -81 uncompress_using_gzip 90 - -90 static.release_sandbox_scmi_test_devices 92 - -92 static.inject_response 92 - -92 x509_akid_machine 93 - -93 uncompress_using_lzo 95 - -95 uncompress_using_lz4 95 - -95 x509_extract_key_data 98 - -98 uncompress_using_lzma 98 - -98 uncompress_using_bzip2 100 - -100 static.tftp_timeout_handler 102 - -102 x509_action_table 104 - -104 x509_note_OID 105 - -105 static.ZSTD_frameHeaderSize_internal 107 - -107 static.hash_init_sha384 152 41 -111 x509_machine 113 - -113 overlay_adjust_node_phandles 117 - -117 setup_ctx_and_base_tables 118 - -118 x509_process_extension 125 - -125 static.tftp_filename 128 - -128 x509_note_signature 129 - -129 static.wget_timeout_handler 131 - -131 static.__func__ 34215 34080 -135 pkcs7_note_OID 136 - -136 pkcs7_action_table 136 - -136 static.HUF_decompress1X1_usingDTable_internal_body 150 - -150 oid_index 150 - -150 sha512_base_do_finalize 154 - -154 cdp_send_trigger 157 - -157 static.efi_key_notify 164 - -164 static.efi_console_timer_notify 164 - -164 cdp_compute_csum 164 - -164 static.unregister_package_notify 169 - -169 static.efi_cin_set_state 169 - -169 static.fastboot_timed_send_info 174 - -174 static.duplicate_device_path 180 - -180 pkcs7_note_signed_info 187 - -187 efi_str_upr 187 - -187 efi_str_lwr 187 - -187 static.append_device_node 188 - -188 efi_metai_match 188 - -188 mscode_note_content_type 189 - -189 static.append_device_path 190 - -190 pkcs7_sig_note_digest_algo 190 - -190 static.get_device_path_size 191 - -191 static.sha256_update 194 - -194 static.efi_cin_reset_ex 194 - -194 static.sha512_base_do_update 195 - -195 static.set_keyboard_layout 196 - -196 static.is_device_path_multi_instance 201 - -201 static.export_package_lists 206 - -206 look_up_OID 207 - -207 static.remove_package_list 208 - -208 static.sha1_update 216 - -216 tcg2_create_digest 718 500 -218 overlay_get_target 220 - -220 static.register_package_notify 222 - -222 static.create_device_node 222 - -222 efi_fat_to_str 223 - -223 static.get_package_list_handle 231 - -231 pkcs7_machine 239 - -239 static.sprint_oid 241 - -241 lib_asn1_pkcs7 244 - -244 efi_stri_coll 247 - -247 sha256_k 256 - -256 static.efi_cin_unregister_key_notify 268 - -268 pkcs7_sig_note_authenticated_attr 268 - -268 sha1_finish 288 - -288 static.get_next_device_path_instance 290 - -290 lib_asn1_pkey 290 - -290 x509_note_pkey_algo 291 - -291 static.efi_convert_device_node_to_text 293 - -293 oid_search_table 296 - -296 static.get_secondary_languages 301 - -301 static.efi_cin_register_key_notify 303 - -303 sqfs_split_path 309 - -309 static.append_device_path_instance 311 - -311 mscode_note_digest_algo 327 - -327 scan_mmc_bootdev 334 - -334 static.find_keyboard_layouts 339 - -339 plain 351 - -351 static.get_keyboard_layout 355 - -355 static.new_package_list 359 - -359 static.efi_convert_device_path_to_text 359 - -359 static.get_string 360 - -360 efi_str_to_fat 362 - -362 static.fastboot_handler 363 - -363 static.update_package_list 374 - -374 dns_handler 374 - -374 static.efi_cin_read_key_stroke_ex 393 - -393 static.list_package_lists 398 - -398 static.get_languages 402 - -402 lib_asn1_x509 423 - -423 static.x509_fabricate_name 428 - -428 static.wget_send_stored 438 - -438 static.set_string 448 - -448 static.new_string 450 - -450 overlay_update_local_node_references 479 - -479 compress_using_zstd 498 - -498 compress_using_lzo 498 - -498 compress_using_lzma 498 - -498 compress_using_lz4 498 - -498 compress_using_bzip2 498 - -498 oid_data 513 - -513 static.public_key 540 - -540 sha512_k 640 - -640 prep_mmc_bootdev 769 - -769 static.x509_decode_time 779 - -779 static.load_sandbox_scmi_test_devices 780 - -780 x509_cert_parse 973 179 -794 cert_data 971 - -971 static.HUF_decompress4X1_usingDTable_internal_body 1056 - -1056 static.tcg2_log_parse 1064 - -1064 static.tftp_handler 1199 - -1199 static.wget_handler 1483 - -1483 asn1_ber_decoder 1511 - -1511 rsa_verify_with_pkey 1676 - -1676 static.compress_frame_buffer 1708 - -1708 sha512_block_fn 1714 - -1714 image_pk7 1811 - -1811 MD5Transform 1812 - -1812 make_fuller_fdt 1987 - -1987 compress_using_gzip 5344 - -5344 static.mbr_test_run 6557 - -6557 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 mbedtls: Enable smaller implementation for SHA256/512 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 +- configs/qemu_arm64_defconfig | 1 + configs/sandbox_defconfig | 1 + drivers/mmc/Kconfig | 1 + 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 | 25 + 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 | 9 + lib/Kconfig | 4 + lib/Makefile | 15 +- 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 | 433 +++++++++++++++ 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 | 90 ++++ 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/port/md5_alt.h | 57 ++ lib/mbedtls/port/sha1_alt.h | 57 ++ lib/mbedtls/port/sha256_alt.h | 64 +++ lib/mbedtls/port/sha512_alt.h | 78 +++ 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 | 14 - lib/sha1.c | 13 - lib/tpm-v1.c | 2 +- test/Kconfig | 2 +- 56 files changed, 2983 insertions(+), 232 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/port/md5_alt.h create mode 100644 lib/mbedtls/port/sha1_alt.h create mode 100644 lib/mbedtls/port/sha256_alt.h create mode 100644 lib/mbedtls/port/sha512_alt.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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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 93111eb6127..b66d49a62ba 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 7d621031b85..2a52e15d0fe 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -159,7 +159,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

On Thu, 3 Oct 2024 at 15:51, Raymond Mao raymond.mao@linaro.org wrote:
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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- 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 93111eb6127..b66d49a62ba 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 7d621031b85..2a52e15d0fe 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -159,7 +159,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
2.25.1
Reviewed-by: Simon Glass sjg@chromium.org
(since I queried this on an earlier revision)

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. Port u-boot hash functions as MbedTLS crypto alternatives and set it as default.
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. Changes in v6 - Fixed UINT64_MAX. - Removed copy right statement from limits.h Changes in v7 - Fixed CI world build failures due to config dependencies. - Fixed values of UINT_MAX and UINT32_MAX. Changes in v8 - Port u-boot hash functions as MbedTLS crypto alternatives and set it as default.
Makefile | 6 +++ include/limits.h | 25 ++++++++++ include/linux/kernel.h | 13 +---- include/stdlib.h | 1 + lib/Kconfig | 4 ++ lib/Makefile | 2 + lib/mbedtls/Kconfig | 56 +++++++++++++++++++++ lib/mbedtls/Makefile | 41 ++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 84 ++++++++++++++++++++++++++++++++ lib/mbedtls/port/assert.h | 12 +++++ lib/mbedtls/port/md5_alt.h | 57 ++++++++++++++++++++++ lib/mbedtls/port/sha1_alt.h | 57 ++++++++++++++++++++++ lib/mbedtls/port/sha256_alt.h | 64 ++++++++++++++++++++++++ lib/mbedtls/port/sha512_alt.h | 78 +++++++++++++++++++++++++++++ 14 files changed, 488 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 create mode 100644 lib/mbedtls/port/md5_alt.h create mode 100644 lib/mbedtls/port/sha1_alt.h create mode 100644 lib/mbedtls/port/sha256_alt.h create mode 100644 lib/mbedtls/port/sha512_alt.h
diff --git a/Makefile b/Makefile index 525576f987d..f4659f9493a 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..4700cc7a59f --- /dev/null +++ b/include/limits.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ + +#ifndef _LIMITS_H +#define _LIMITS_H + +#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffU +#define CHAR_BIT 8 +#define UINT32_MAX 0xffffffffU +#define UINT64_MAX 0xffffffffffffffffULL + +#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 939465f372b..9467edd65ab 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 1dd4f271595..67a60160dac 100644 --- a/lib/Kconfig +++ b/lib/Kconfig @@ -419,6 +419,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 d300249f57c..c4950b78a29 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..9d1a63c1ca6 --- /dev/null +++ b/lib/mbedtls/Kconfig @@ -0,0 +1,56 @@ +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_X509 +endchoice + +if LEGACY_CRYPTO || MBEDTLS_LIB_CRYPTO_ALT + +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_ALT + bool "MbedTLS crypto alternatives" + depends on MBEDTLS_LIB && !MBEDTLS_LIB_CRYPTO + select LEGACY_CRYPTO_BASIC + default y if MBEDTLS_LIB && !MBEDTLS_LIB_CRYPTO + help + Enable MbedTLS crypto alternatives. + Mutually incompatible with MBEDTLS_LIB_CRYPTO. + +config MBEDTLS_LIB_CRYPTO + bool "MbedTLS crypto libraries" + help + Enable MbedTLS crypto libraries. + Mutually incompatible with MBEDTLS_LIB_CRYPTO_ALT. + + +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..0b6d6ca808f --- /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) += 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..6fba053bd7c --- /dev/null +++ b/lib/mbedtls/mbedtls_def_config.h @@ -0,0 +1,84 @@ +/* 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 defined CONFIG_MBEDTLS_LIB + +#if CONFIG_IS_ENABLED(MD5) +#define MBEDTLS_MD_C +#define MBEDTLS_MD5_C +#if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT +#define MBEDTLS_MD5_ALT +#endif +#endif + +#if CONFIG_IS_ENABLED(SHA1) +#define MBEDTLS_MD_C +#define MBEDTLS_SHA1_C +#if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT +#define MBEDTLS_SHA1_ALT +#endif +#endif + +#if CONFIG_IS_ENABLED(SHA256) +#define MBEDTLS_MD_C +#define MBEDTLS_SHA256_C +#if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT +#define MBEDTLS_SHA256_ALT +#endif +#endif + +#if CONFIG_IS_ENABLED(SHA384) +#define MBEDTLS_MD_C +#define MBEDTLS_SHA384_C +#endif + +#if CONFIG_IS_ENABLED(SHA512) +#define MBEDTLS_MD_C +#define MBEDTLS_SHA512_C +#if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT +#define MBEDTLS_SHA512_ALT +#endif +#endif + +#if defined CONFIG_MBEDTLS_LIB_X509 + +#if CONFIG_IS_ENABLED(X509_CERTIFICATE_PARSER) +#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 +#define MBEDTLS_PKCS1_V15 +#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 /* #if defined CONFIG_MBEDTLS_LIB_X509 */ + +#endif /* #if defined CONFIG_MBEDTLS_LIB */ 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 */ diff --git a/lib/mbedtls/port/md5_alt.h b/lib/mbedtls/port/md5_alt.h new file mode 100644 index 00000000000..c6e8eabf68a --- /dev/null +++ b/lib/mbedtls/port/md5_alt.h @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#ifndef MD5_ALT_H +#define MD5_ALT_H + +#include <image.h> +#include <u-boot/md5.h> + +typedef MD5Context mbedtls_md5_context; + +static inline void mbedtls_md5_init(mbedtls_md5_context *ctx) +{ +} + +static inline void mbedtls_md5_free(mbedtls_md5_context *ctx) +{ +} + +static inline void +mbedtls_md5_clone(mbedtls_md5_context *dst, const mbedtls_md5_context *src) +{ + *dst = *src; +} + +static inline int mbedtls_md5_starts(mbedtls_md5_context *ctx) +{ + MD5Init(ctx); + return 0; +} + +static inline int mbedtls_md5_update(mbedtls_md5_context *ctx, + const unsigned char *input, + size_t ilen) +{ + MD5Update(ctx, input, ilen); + return 0; +} + +static inline int mbedtls_md5_finish(mbedtls_md5_context *ctx, + unsigned char output[16]) +{ + MD5Final(output, ctx); + return 0; +} + +static inline int mbedtls_md5(const unsigned char *input, + size_t ilen, + unsigned char output[16]) +{ + md5_wd(input, ilen, output, CHUNKSZ_MD5); + return 0; +} + +#endif /* md5_alt.h */ diff --git a/lib/mbedtls/port/sha1_alt.h b/lib/mbedtls/port/sha1_alt.h new file mode 100644 index 00000000000..cbfe0ddc478 --- /dev/null +++ b/lib/mbedtls/port/sha1_alt.h @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#ifndef SHA1_ALT_H +#define SHA1_ALT_H + +#include <image.h> +#include <u-boot/sha1.h> + +typedef sha1_context mbedtls_sha1_context; + +static inline void mbedtls_sha1_init(mbedtls_sha1_context *ctx) +{ +} + +static inline void mbedtls_sha1_free(mbedtls_sha1_context *ctx) +{ +} + +static inline void mbedtls_sha1_clone(mbedtls_sha1_context *dst, + const mbedtls_sha1_context *src) +{ + *dst = *src; +} + +static inline int mbedtls_sha1_starts(mbedtls_sha1_context *ctx) +{ + sha1_starts(ctx); + return 0; +} + +static inline int mbedtls_sha1_update(mbedtls_sha1_context *ctx, + const unsigned char *input, + size_t ilen) +{ + sha1_update(ctx, input, ilen); + return 0; +} + +static inline int mbedtls_sha1_finish(mbedtls_sha1_context *ctx, + unsigned char output[20]) +{ + sha1_finish(ctx, output); + return 0; +} + +static inline int mbedtls_sha1(const unsigned char *input, + size_t ilen, + unsigned char output[20]) +{ + sha1_csum_wd(input, ilen, output, CHUNKSZ_SHA1); + return 0; +} + +#endif /* sha1_alt.h */ diff --git a/lib/mbedtls/port/sha256_alt.h b/lib/mbedtls/port/sha256_alt.h new file mode 100644 index 00000000000..80be94b0a06 --- /dev/null +++ b/lib/mbedtls/port/sha256_alt.h @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#ifndef SHA256_ALT_H +#define SHA256_ALT_H + +#include <image.h> +#include <u-boot/sha256.h> + +typedef sha256_context mbedtls_sha256_context; + +static inline void mbedtls_sha256_init(mbedtls_sha256_context *ctx) +{ +} + +static inline void mbedtls_sha256_free(mbedtls_sha256_context *ctx) +{ +} + +static inline void mbedtls_sha256_clone(mbedtls_sha256_context *dst, + const mbedtls_sha256_context *src) +{ + *dst = *src; +} + +static inline int mbedtls_sha256_starts(mbedtls_sha256_context *ctx, int is224) +{ + if (is224) + return -EOPNOTSUPP; + + sha256_starts(ctx); + return 0; +} + +static inline int mbedtls_sha256_update(mbedtls_sha256_context *ctx, + const unsigned char *input, + size_t ilen) +{ + sha256_update(ctx, input, ilen); + return 0; +} + +static inline int mbedtls_sha256_finish(mbedtls_sha256_context *ctx, + unsigned char *output) +{ + sha256_finish(ctx, output); + return 0; +} + +static inline int mbedtls_sha256(const unsigned char *input, + size_t ilen, + unsigned char *output, + int is224) +{ + if (is224) + return -EOPNOTSUPP; + + sha256_csum_wd(input, ilen, output, CHUNKSZ_SHA256); + return 0; +} + +#endif /* sha256_alt.h */ diff --git a/lib/mbedtls/port/sha512_alt.h b/lib/mbedtls/port/sha512_alt.h new file mode 100644 index 00000000000..596f17ae4da --- /dev/null +++ b/lib/mbedtls/port/sha512_alt.h @@ -0,0 +1,78 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Copyright (c) 2024 Linaro Limited + * Author: Raymond Mao raymond.mao@linaro.org + */ +#ifndef SHA512_ALT_H +#define SHA512_ALT_H + +#include <image.h> +#include <u-boot/sha512.h> + +typedef struct mbedtls_sha512_context { + sha512_context *ubctx; + bool is384; +} mbedtls_sha512_context; + +static inline void mbedtls_sha512_init(mbedtls_sha512_context *ctx) +{ +} + +static inline void mbedtls_sha512_free(mbedtls_sha512_context *ctx) +{ +} + +static inline void mbedtls_sha512_clone(mbedtls_sha512_context *dst, + const mbedtls_sha512_context *src) +{ + *dst = *src; +} + +static inline int mbedtls_sha512_starts(mbedtls_sha512_context *ctx, int is384) +{ + if (is384) + sha384_starts(ctx->ubctx); + else + sha512_starts(ctx->ubctx); + + ctx->is384 = is384; + return 0; +} + +static inline int mbedtls_sha512_update(mbedtls_sha512_context *ctx, + const unsigned char *input, + size_t ilen) +{ + if (ctx->is384) + sha384_update(ctx->ubctx, input, ilen); + else + sha512_update(ctx->ubctx, input, ilen); + + return 0; +} + +static inline int mbedtls_sha512_finish(mbedtls_sha512_context *ctx, + unsigned char *output) +{ + if (ctx->is384) + sha384_finish(ctx->ubctx, output); + else + sha512_finish(ctx->ubctx, output); + + return 0; +} + +static inline int mbedtls_sha512(const unsigned char *input, + size_t ilen, + unsigned char *output, + int is384) +{ + if (is384) + sha384_csum_wd(input, ilen, output, CHUNKSZ_SHA512); + else + sha512_csum_wd(input, ilen, output, CHUNKSZ_SHA512); + + return 0; +} + +#endif /* sha512_alt.h */

Hi Raymond
On Fri, 4 Oct 2024 at 00:52, 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. Port u-boot hash functions as MbedTLS crypto alternatives and set it as default.
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.
Changes in v6
- Fixed UINT64_MAX.
- Removed copy right statement from limits.h
Changes in v7
- Fixed CI world build failures due to config dependencies.
- Fixed values of UINT_MAX and UINT32_MAX.
Changes in v8
- Port u-boot hash functions as MbedTLS crypto alternatives and set it as default.
Makefile | 6 +++ include/limits.h | 25 ++++++++++ include/linux/kernel.h | 13 +---- include/stdlib.h | 1 + lib/Kconfig | 4 ++ lib/Makefile | 2 + lib/mbedtls/Kconfig | 56 +++++++++++++++++++++ lib/mbedtls/Makefile | 41 ++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 84 ++++++++++++++++++++++++++++++++ lib/mbedtls/port/assert.h | 12 +++++ lib/mbedtls/port/md5_alt.h | 57 ++++++++++++++++++++++ lib/mbedtls/port/sha1_alt.h | 57 ++++++++++++++++++++++ lib/mbedtls/port/sha256_alt.h | 64 ++++++++++++++++++++++++ lib/mbedtls/port/sha512_alt.h | 78 +++++++++++++++++++++++++++++ 14 files changed, 488 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 create mode 100644 lib/mbedtls/port/md5_alt.h create mode 100644 lib/mbedtls/port/sha1_alt.h create mode 100644 lib/mbedtls/port/sha256_alt.h create mode 100644 lib/mbedtls/port/sha512_alt.h
diff --git a/Makefile b/Makefile index 525576f987d..f4659f9493a 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..4700cc7a59f --- /dev/null +++ b/include/limits.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0+ */
+#ifndef _LIMITS_H +#define _LIMITS_H
+#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffU +#define CHAR_BIT 8 +#define UINT32_MAX 0xffffffffU +#define UINT64_MAX 0xffffffffffffffffULL
+#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 939465f372b..9467edd65ab 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 1dd4f271595..67a60160dac 100644 --- a/lib/Kconfig +++ b/lib/Kconfig @@ -419,6 +419,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 d300249f57c..c4950b78a29 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..9d1a63c1ca6 --- /dev/null +++ b/lib/mbedtls/Kconfig @@ -0,0 +1,56 @@ +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
This overall llooks ok, but the native mbedTLS hashing should depend on !CONFIG_SHA_HW_ACCEL. If everyone thinks the series is good enough to merge, I don't mind this going on a followup commit
+config MBEDTLS_LIB
bool "MbedTLS libraries"
select MBEDTLS_LIB_X509
+endchoice
+if LEGACY_CRYPTO || MBEDTLS_LIB_CRYPTO_ALT
+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_ALT
bool "MbedTLS crypto alternatives"
depends on MBEDTLS_LIB && !MBEDTLS_LIB_CRYPTO
select LEGACY_CRYPTO_BASIC
default y if MBEDTLS_LIB && !MBEDTLS_LIB_CRYPTO
help
Enable MbedTLS crypto alternatives.
Mutually incompatible with MBEDTLS_LIB_CRYPTO.
+config MBEDTLS_LIB_CRYPTO
bool "MbedTLS crypto libraries"
help
Enable MbedTLS crypto libraries.
Mutually incompatible with MBEDTLS_LIB_CRYPTO_ALT.
+config MBEDTLS_LIB_X509
bool "MbedTLS certificate libraries"
- Author: Raymond Mao raymond.mao@linaro.org
- */
+#if defined CONFIG_MBEDTLS_LIB
+#if CONFIG_IS_ENABLED(MD5) +#define MBEDTLS_MD_C +#define MBEDTLS_MD5_C +#if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT +#define MBEDTLS_MD5_ALT +#endif +#endif
+#if CONFIG_IS_ENABLED(SHA1) +#define MBEDTLS_MD_C +#define MBEDTLS_SHA1_C +#if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT +#define MBEDTLS_SHA1_ALT +#endif +#endif
+#if CONFIG_IS_ENABLED(SHA256) +#define MBEDTLS_MD_C +#define MBEDTLS_SHA256_C +#if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT +#define MBEDTLS_SHA256_ALT +#endif +#endif
+#if CONFIG_IS_ENABLED(SHA384) +#define MBEDTLS_MD_C +#define MBEDTLS_SHA384_C +#endif
[...]
Thanks /Ilias

Hi Ilias,
On Wed, 9 Oct 2024 at 06:14, Ilias Apalodimas ilias.apalodimas@linaro.org wrote:
Hi Raymond
On Fri, 4 Oct 2024 at 00:52, 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. Port u-boot hash functions as MbedTLS crypto alternatives and set it as default.
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.
Changes in v6
- Fixed UINT64_MAX.
- Removed copy right statement from limits.h
Changes in v7
- Fixed CI world build failures due to config dependencies.
- Fixed values of UINT_MAX and UINT32_MAX.
Changes in v8
- Port u-boot hash functions as MbedTLS crypto alternatives and set it as default.
Makefile | 6 +++ include/limits.h | 25 ++++++++++ include/linux/kernel.h | 13 +---- include/stdlib.h | 1 + lib/Kconfig | 4 ++ lib/Makefile | 2 + lib/mbedtls/Kconfig | 56 +++++++++++++++++++++ lib/mbedtls/Makefile | 41 ++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 84 ++++++++++++++++++++++++++++++++ lib/mbedtls/port/assert.h | 12 +++++ lib/mbedtls/port/md5_alt.h | 57 ++++++++++++++++++++++ lib/mbedtls/port/sha1_alt.h | 57 ++++++++++++++++++++++ lib/mbedtls/port/sha256_alt.h | 64 ++++++++++++++++++++++++ lib/mbedtls/port/sha512_alt.h | 78 +++++++++++++++++++++++++++++ 14 files changed, 488 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 create mode 100644 lib/mbedtls/port/md5_alt.h create mode 100644 lib/mbedtls/port/sha1_alt.h create mode 100644 lib/mbedtls/port/sha256_alt.h create mode 100644 lib/mbedtls/port/sha512_alt.h
diff --git a/Makefile b/Makefile index 525576f987d..f4659f9493a 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..4700cc7a59f --- /dev/null +++ b/include/limits.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0+ */
+#ifndef _LIMITS_H +#define _LIMITS_H
+#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffU +#define CHAR_BIT 8 +#define UINT32_MAX 0xffffffffU +#define UINT64_MAX 0xffffffffffffffffULL
+#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 939465f372b..9467edd65ab 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 1dd4f271595..67a60160dac 100644 --- a/lib/Kconfig +++ b/lib/Kconfig @@ -419,6 +419,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 d300249f57c..c4950b78a29 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..9d1a63c1ca6 --- /dev/null +++ b/lib/mbedtls/Kconfig @@ -0,0 +1,56 @@ +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
This overall llooks ok, but the native mbedTLS hashing should depend on !CONFIG_SHA_HW_ACCEL. If everyone thinks the series is good enough to merge, I don't mind this going on a followup commit
I will add this into v9 with other changes.
[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. sha256.o should depend on SHA256 kconfig only but not SUPPORT_EMMC_RPMB, SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
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 - 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. Changes in v6 - Update commit message. - Rebased on next branch. Changes in v7 - Fixed the dependency between SUPPORT_EMMC_RPMB and SHA256. Changes in v8 - None
drivers/mmc/Kconfig | 1 + include/u-boot/md5.h | 7 ++++ include/u-boot/sha1.h | 21 +++++++++- include/u-boot/sha256.h | 20 +++++++++ include/u-boot/sha512.h | 9 ++++ lib/Makefile | 11 ++--- lib/mbedtls/Kconfig | 91 +++++++++++++++++++++++++++++++++++++++++ 7 files changed, 154 insertions(+), 6 deletions(-)
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB + select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in eMMC. 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 83c2119cd26..7e10f590a1d 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[];
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o @@ -71,14 +70,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 9d1a63c1ca6..8a7b3a30c04 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -20,9 +20,100 @@ if LEGACY_CRYPTO || MBEDTLS_LIB_CRYPTO_ALT
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 Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not SUPPORT_EMMC_RPMB, SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old new delta hash_command 108 296 +188 sha1_finish - 156 +156 static.sha1_update - 114 +114 hash_algo - 112 +112 sha1_padding - 64 +64 hash_lookup_algo - 60 +60 sha1_starts - 52 +52 crc16_ccitt_wd_buf - 36 +36 sha256_csum_wd - 34 +34 sha1_csum_wd - 34 +34 hash_finish_sha256 - 34 +34 hash_finish_sha1 - 34 +34 crc32_wd_buf - 34 +34 hash_finish_crc32 - 28 +28 hash_finish_crc16_ccitt - 28 +28 hash_init_sha256 - 22 +22 hash_init_sha1 - 22 +22 hash_update_crc32 - 20 +20 hash_update_crc16_ccitt - 20 +20 hash_init_crc32 - 20 +20 hash_init_crc16_ccitt - 20 +20 hash_update_sha256 - 16 +16 hash_update_sha1 - 16 +16 sha1_update - 8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
- select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And since two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!

Hi Tom,
On Wed, 9 Oct 2024 at 10:38, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not SUPPORT_EMMC_RPMB, SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old new delta hash_command 108 296 +188 sha1_finish - 156 +156 static.sha1_update - 114 +114 hash_algo - 112 +112 sha1_padding - 64 +64 hash_lookup_algo - 60 +60 sha1_starts - 52 +52 crc16_ccitt_wd_buf - 36 +36 sha256_csum_wd - 34 +34 sha1_csum_wd - 34 +34 hash_finish_sha256 - 34 +34 hash_finish_sha1 - 34 +34 crc32_wd_buf - 34 +34 hash_finish_crc32 - 28 +28 hash_finish_crc16_ccitt - 28 +28 hash_init_sha256 - 22 +22 hash_init_sha1 - 22 +22 hash_update_crc32 - 20 +20 hash_update_crc16_ccitt - 20 +20 hash_init_crc32 - 20 +20 hash_init_crc16_ccitt - 20 +20 hash_update_sha256 - 16 +16 hash_update_sha1 - 16 +16 sha1_update - 8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And since two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!
To address this, I think there are two options.
1. Introduce SUPPORT_EMMC_RPMB into the MbedTLS sub makefile. 2. Make MBEDTLS_LIB_CRYPTO depends on !SUPPORT_EMMC_RPMB. 1) looks to be ugly, I prefer 2) if you agree.
Regards, Raymond

On Wed, Oct 09, 2024 at 11:32:29AM -0400, Raymond Mao wrote:
Hi Tom,
On Wed, 9 Oct 2024 at 10:38, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not SUPPORT_EMMC_RPMB, SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old new delta hash_command 108 296 +188 sha1_finish - 156 +156 static.sha1_update - 114 +114 hash_algo - 112 +112 sha1_padding - 64 +64 hash_lookup_algo - 60 +60 sha1_starts - 52 +52 crc16_ccitt_wd_buf - 36 +36 sha256_csum_wd - 34 +34 sha1_csum_wd - 34 +34 hash_finish_sha256 - 34 +34 hash_finish_sha1 - 34 +34 crc32_wd_buf - 34 +34 hash_finish_crc32 - 28 +28 hash_finish_crc16_ccitt - 28 +28 hash_init_sha256 - 22 +22 hash_init_sha1 - 22 +22 hash_update_crc32 - 20 +20 hash_update_crc16_ccitt - 20 +20 hash_init_crc32 - 20 +20 hash_init_crc16_ccitt - 20 +20 hash_update_sha256 - 16 +16 hash_update_sha1 - 16 +16 sha1_update - 8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And since two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!
To address this, I think there are two options.
- Introduce SUPPORT_EMMC_RPMB into the MbedTLS sub makefile.
- Make MBEDTLS_LIB_CRYPTO depends on !SUPPORT_EMMC_RPMB.
- looks to be ugly, I prefer 2) if you agree.
Well, part of the size issue is that it looks like a number of other algorithms are now being enabled too?

On Wed, 9 Oct 2024 at 18:32, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Wed, 9 Oct 2024 at 10:38, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not SUPPORT_EMMC_RPMB, SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old new delta hash_command 108 296 +188 sha1_finish - 156 +156 static.sha1_update - 114 +114 hash_algo - 112 +112 sha1_padding - 64 +64 hash_lookup_algo - 60 +60 sha1_starts - 52 +52 crc16_ccitt_wd_buf - 36 +36 sha256_csum_wd - 34 +34 sha1_csum_wd - 34 +34 hash_finish_sha256 - 34 +34 hash_finish_sha1 - 34 +34 crc32_wd_buf - 34 +34 hash_finish_crc32 - 28 +28 hash_finish_crc16_ccitt - 28 +28 hash_init_sha256 - 22 +22 hash_init_sha1 - 22 +22 hash_update_crc32 - 20 +20 hash_update_crc16_ccitt - 20 +20 hash_init_crc32 - 20 +20 hash_init_crc16_ccitt - 20 +20 hash_update_sha256 - 16 +16 hash_update_sha1 - 16 +16 sha1_update - 8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And since two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!
To address this, I think there are two options.
- Introduce SUPPORT_EMMC_RPMB into the MbedTLS sub makefile.
- Make MBEDTLS_LIB_CRYPTO depends on !SUPPORT_EMMC_RPMB.
- looks to be ugly, I prefer 2) if you agree.
2 is not a good idea either. We can't just drop RPMB support when mbedTLS is enabled
Thanks /Ilias
Regards, Raymond

On Wed, Oct 09, 2024 at 08:32:29PM +0300, Ilias Apalodimas wrote:
On Wed, 9 Oct 2024 at 18:32, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Wed, 9 Oct 2024 at 10:38, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not SUPPORT_EMMC_RPMB, SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old new delta hash_command 108 296 +188 sha1_finish - 156 +156 static.sha1_update - 114 +114 hash_algo - 112 +112 sha1_padding - 64 +64 hash_lookup_algo - 60 +60 sha1_starts - 52 +52 crc16_ccitt_wd_buf - 36 +36 sha256_csum_wd - 34 +34 sha1_csum_wd - 34 +34 hash_finish_sha256 - 34 +34 hash_finish_sha1 - 34 +34 crc32_wd_buf - 34 +34 hash_finish_crc32 - 28 +28 hash_finish_crc16_ccitt - 28 +28 hash_init_sha256 - 22 +22 hash_init_sha1 - 22 +22 hash_update_crc32 - 20 +20 hash_update_crc16_ccitt - 20 +20 hash_init_crc32 - 20 +20 hash_init_crc16_ccitt - 20 +20 hash_update_sha256 - 16 +16 hash_update_sha1 - 16 +16 sha1_update - 8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And since two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!
To address this, I think there are two options.
- Introduce SUPPORT_EMMC_RPMB into the MbedTLS sub makefile.
- Make MBEDTLS_LIB_CRYPTO depends on !SUPPORT_EMMC_RPMB.
- looks to be ugly, I prefer 2) if you agree.
2 is not a good idea either. We can't just drop RPMB support when mbedTLS is enabled
To be clear, while I hope we can do something about this growth, I would rather live with it (as it's not an unreasonable amount) than do 2, and if 1 is too ugly, probably skip that as well. If it's not a matter of loosening some select statements, or maybe introducing a library type symbol we can see if anyone else more motivated has a better idea as it's literally 3 platforms (ev-imx280-nano-x-mb is the other nano, and then uniphier_v8 where it's arguably a missing feature anyhow) rather than a large number of them. And not even other "mini" or "nano" configs.

Hi Tom
On Wed, 9 Oct 2024 at 20:52, Tom Rini trini@konsulko.com wrote:
On Wed, Oct 09, 2024 at 08:32:29PM +0300, Ilias Apalodimas wrote:
On Wed, 9 Oct 2024 at 18:32, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Wed, 9 Oct 2024 at 10:38, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not SUPPORT_EMMC_RPMB, SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old new delta hash_command 108 296 +188 sha1_finish - 156 +156 static.sha1_update - 114 +114 hash_algo - 112 +112 sha1_padding - 64 +64 hash_lookup_algo - 60 +60 sha1_starts - 52 +52 crc16_ccitt_wd_buf - 36 +36 sha256_csum_wd - 34 +34 sha1_csum_wd - 34 +34 hash_finish_sha256 - 34 +34 hash_finish_sha1 - 34 +34 crc32_wd_buf - 34 +34 hash_finish_crc32 - 28 +28 hash_finish_crc16_ccitt - 28 +28 hash_init_sha256 - 22 +22 hash_init_sha1 - 22 +22 hash_update_crc32 - 20 +20 hash_update_crc16_ccitt - 20 +20 hash_init_crc32 - 20 +20 hash_init_crc16_ccitt - 20 +20 hash_update_sha256 - 16 +16 hash_update_sha1 - 16 +16 sha1_update - 8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And since two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!
To address this, I think there are two options.
- Introduce SUPPORT_EMMC_RPMB into the MbedTLS sub makefile.
- Make MBEDTLS_LIB_CRYPTO depends on !SUPPORT_EMMC_RPMB.
- looks to be ugly, I prefer 2) if you agree.
2 is not a good idea either. We can't just drop RPMB support when mbedTLS is enabled
To be clear, while I hope we can do something about this growth, I would rather live with it (as it's not an unreasonable amount) than do 2, and if 1 is too ugly, probably skip that as well.
Yep, I agree. That was pretty clear from your first email as well. I just pointed out that option 2 was just as bad
If it's not a matter of loosening some select statements, or maybe introducing a library type symbol we can see if anyone else more motivated has a better idea as it's literally 3 platforms (ev-imx280-nano-x-mb is the other nano, and then uniphier_v8 where it's arguably a missing feature anyhow) rather than a large number of them. And not even other "mini" or "nano" configs.
-- Tom
Cheers /Ilias

Hi Tom,
On Wed, 9 Oct 2024 at 13:52, Tom Rini trini@konsulko.com wrote:
On Wed, Oct 09, 2024 at 08:32:29PM +0300, Ilias Apalodimas wrote:
On Wed, 9 Oct 2024 at 18:32, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Wed, 9 Oct 2024 at 10:38, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not
SUPPORT_EMMC_RPMB,
SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0
text +5400.0
o4-imx6ull-nano: all +5651 data +112 rodata +139 text
+5400
u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old
new delta
hash_command 108
296 +188
sha1_finish -
156 +156
static.sha1_update -
114 +114
hash_algo -
112 +112
sha1_padding -
64 +64
hash_lookup_algo -
60 +60
sha1_starts -
52 +52
crc16_ccitt_wd_buf -
36 +36
sha256_csum_wd -
34 +34
sha1_csum_wd -
34 +34
hash_finish_sha256 -
34 +34
hash_finish_sha1 -
34 +34
crc32_wd_buf -
34 +34
hash_finish_crc32 -
28 +28
hash_finish_crc16_ccitt -
28 +28
hash_init_sha256 -
22 +22
hash_init_sha1 -
22 +22
hash_update_crc32 -
20 +20
hash_update_crc16_ccitt -
20 +20
hash_init_crc32 -
20 +20
hash_init_crc16_ccitt -
20 +20
hash_update_sha256 -
16 +16
hash_update_sha1 -
16 +16
sha1_update -
8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in
eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And
since
two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!
To address this, I think there are two options.
- Introduce SUPPORT_EMMC_RPMB into the MbedTLS sub makefile.
- Make MBEDTLS_LIB_CRYPTO depends on !SUPPORT_EMMC_RPMB.
- looks to be ugly, I prefer 2) if you agree.
2 is not a good idea either. We can't just drop RPMB support when mbedTLS is enabled
To be clear, while I hope we can do something about this growth, I would rather live with it (as it's not an unreasonable amount) than do 2, and if 1 is too ugly, probably skip that as well. If it's not a matter of loosening some select statements, or maybe introducing a library type symbol we can see if anyone else more motivated has a better idea as it's literally 3 platforms (ev-imx280-nano-x-mb is the other nano, and then uniphier_v8 where it's arguably a missing feature anyhow) rather than a large number of them. And not even other "mini" or "nano" configs.
Yes. I figured out what the problem is.
The "select SHA256" change doesn't matter, but size growth was introduced by the inline function in sha1_alt.h I added in patch #2 of v8. I already fixed this in my working branch:
aarch64: (for 1/1 boards) all +8502.0 data +224.0 rodata +218.0 text +8060.0 uniphier_v8 : all +8502 data +224 rodata +218 text +8060 arm: (for 2/2 boards) all +5649.0 data +112.0 rodata +137.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 ev-imx280-nano-x-mb: all +5647 data +112 rodata +135 text +5400
Now there is no "u-boot: add" any more on these three boards. I will update v9 with this fix, and we don't need either 1) or 2) options mentioned in my previous reply.
Regards, Raymond

On Fri, Oct 11, 2024 at 02:25:20PM -0400, Raymond Mao wrote:
Hi Tom,
On Wed, 9 Oct 2024 at 13:52, Tom Rini trini@konsulko.com wrote:
On Wed, Oct 09, 2024 at 08:32:29PM +0300, Ilias Apalodimas wrote:
On Wed, 9 Oct 2024 at 18:32, Raymond Mao raymond.mao@linaro.org wrote:
Hi Tom,
On Wed, 9 Oct 2024 at 10:38, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:16PM -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. sha256.o should depend on SHA256 kconfig only but not
SUPPORT_EMMC_RPMB,
SHA256 should be selected when SUPPORT_EMMC_RPMB is enabled instead.
`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, Thus we use `#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)` instead.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org
There's three platforms where we see something like: arm: (for 1/1 boards) all +5651.0 data +112.0 rodata +139.0
text +5400.0
o4-imx6ull-nano: all +5651 data +112 rodata +139 text
+5400
u-boot: add: 23/0, grow: 1/0 bytes: 1172/0 (1172) function old
new delta
hash_command 108
296 +188
sha1_finish -
156 +156
static.sha1_update -
114 +114
hash_algo -
112 +112
sha1_padding -
64 +64
hash_lookup_algo -
60 +60
sha1_starts -
52 +52
crc16_ccitt_wd_buf -
36 +36
sha256_csum_wd -
34 +34
sha1_csum_wd -
34 +34
hash_finish_sha256 -
34 +34
hash_finish_sha1 -
34 +34
crc32_wd_buf -
34 +34
hash_finish_crc32 -
28 +28
hash_finish_crc16_ccitt -
28 +28
hash_init_sha256 -
22 +22
hash_init_sha1 -
22 +22
hash_update_crc32 -
20 +20
hash_update_crc16_ccitt -
20 +20
hash_init_crc32 -
20 +20
hash_init_crc16_ccitt -
20 +20
hash_update_sha256 -
16 +16
hash_update_sha1 -
16 +16
sha1_update -
8 +8
This is because:
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig index 982e84dc3bc..5d7fd904950 100644 --- a/drivers/mmc/Kconfig +++ b/drivers/mmc/Kconfig @@ -119,6 +119,7 @@ config MMC_HW_PARTITIONING config SUPPORT_EMMC_RPMB bool "Support eMMC replay protected memory block (RPMB)" imply CMD_MMC_RPMB
select SHA256 help Enable support for reading, writing and programming the key for the Replay Protection Memory Block partition in
eMMC.
Wasn't true / required before now, no hashing algorithms were enabled. This was fine because: [snip]
diff --git a/lib/Makefile b/lib/Makefile index c4950b78a29..33755778283 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o obj-y += net_utils.o obj-$(CONFIG_PHYSMEM) += physmem.o obj-y += rc4.o -obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o obj-$(CONFIG_RBTREE) += rbtree.o obj-$(CONFIG_BITREVERSE) += bitrev.o obj-y += list_sort.o
Got us the library access without bringing in everything else. And
since
two of the platforms that are hitting this now are "nano" this is an important thing to figure out how to continue to support. If there's just no way around it, we can likely live with the size increase, but I'd like to see this looked in to specifically first, thanks!
To address this, I think there are two options.
- Introduce SUPPORT_EMMC_RPMB into the MbedTLS sub makefile.
- Make MBEDTLS_LIB_CRYPTO depends on !SUPPORT_EMMC_RPMB.
- looks to be ugly, I prefer 2) if you agree.
2 is not a good idea either. We can't just drop RPMB support when mbedTLS is enabled
To be clear, while I hope we can do something about this growth, I would rather live with it (as it's not an unreasonable amount) than do 2, and if 1 is too ugly, probably skip that as well. If it's not a matter of loosening some select statements, or maybe introducing a library type symbol we can see if anyone else more motivated has a better idea as it's literally 3 platforms (ev-imx280-nano-x-mb is the other nano, and then uniphier_v8 where it's arguably a missing feature anyhow) rather than a large number of them. And not even other "mini" or "nano" configs.
Yes. I figured out what the problem is.
The "select SHA256" change doesn't matter, but size growth was introduced by the inline function in sha1_alt.h I added in patch #2 of v8. I already fixed this in my working branch:
aarch64: (for 1/1 boards) all +8502.0 data +224.0 rodata +218.0 text +8060.0 uniphier_v8 : all +8502 data +224 rodata +218 text +8060 arm: (for 2/2 boards) all +5649.0 data +112.0 rodata +137.0 text +5400.0 o4-imx6ull-nano: all +5651 data +112 rodata +139 text +5400 ev-imx280-nano-x-mb: all +5647 data +112 rodata +135 text +5400
Now there is no "u-boot: add" any more on these three boards. I will update v9 with this fix, and we don't need either 1) or 2) options mentioned in my previous reply.
Erm, it looks like you just don't have the flag passed to show the functions that changed? That's pretty close to the text change I saw. For reference I do: -----8> #!/bin/bash
# Initial and constant buildman args ARGS="-devl -PEWM" ALL=0 KEEP=0
# Find our arguments while test $# -ne 0; do if [ "$1" == "--all" ]; then ALL=1 shift 1 elif [ "$1" == "--branch" ]; then BRANCH=$2 shift 2 elif [ "$1" == "--keep" ]; then KEEP=1 ARGS="$ARGS -k" shift 1 elif [ "$1" == "--board" ]; then MACHINE="--board $2" OUTDIR=/tmp/$2 shift 2 else MACHINE=$1 shift 1 fi done
OUTDIR=${OUTDIR:-/tmp/$MACHINE}
if [ -z "$MACHINE" ]; then echo Usage: $0 MACHINE [--all] [--keep] [--branch BRANCH] exit 1 fi
# If not all, then only first/last if [ $ALL -ne 1 ]; then ARGS="$ARGS --step 0" fi
if [ ! -z $BRANCH ]; then ARGS="$ARGS -b $BRANCH" else ARGS="$ARGS -b `git rev-parse --abbrev-ref HEAD`" fi
mkdir -p ${OUTDIR}
export SOURCE_DATE_EPOCH=`date +%s` ./tools/buildman/buildman -o ${OUTDIR} $ARGS -SBC $MACHINE ./tools/buildman/buildman -o ${OUTDIR} $ARGS -SsB $MACHINE
[ $KEEP -eq 0 ] && rm -rf ${OUTDIR} <----8

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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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 | 14 -------------- 5 files changed, 6 insertions(+), 23 deletions(-)
diff --git a/board/friendlyarm/nanopi2/board.c b/board/friendlyarm/nanopi2/board.c index b32dfc6b570..4dff32e10d6 100644 --- a/board/friendlyarm/nanopi2/board.c +++ b/board/friendlyarm/nanopi2/board.c @@ -264,7 +264,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 584463d55ca..2d8977b2e85 100644 --- a/lib/md5.c +++ b/lib/md5.c @@ -262,20 +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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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;

Raymond Mao raymond.mao@linaro.org writes:
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.
I have to say I believe this is a step in the wrong direction. Having everybody call a function with that _wd suffix is ugly, as is having them all pass some pre-defined constant. Moreover, nowadays what happens every chunksize bytes isn't restricted to watchdog handling.
So yes, we don't need an API specially for non-watchdog, but why not just make sha1_csum() be the interface to call, and let the "maybe we need to call schedule() once in a while" be an implementation detail of sha1_csum().
The same as with our zlib implementaion; we don't have a separate _wd set of routines, we've just hooked schedule() into the main loop of that inflate algorithm.
Also, I think the IS_ENABLED(CONFIG_HW_WATCHDOG) || IS_ENABLED(CONFIG_WATCHDOG) guards are wrong and shouldn't be copy-pasted to new code. Preferably, the code shouldn't even have any ifdefs, but just always be built as a loop with the (possibly no-op) schedule() every xxx bytes.
I just sent a series which is the beginning of cleaning up the CONFIG_HW_WATCHDOG/CONFIG_WATCHDOG/CONFIG_CYCLIC/when is schedule defined and when should it be called.
Rasmus

Hi Rasmus,
On Fri, 4 Oct 2024 at 03:50, Rasmus Villemoes rasmus.villemoes@prevas.dk wrote:
Raymond Mao raymond.mao@linaro.org writes:
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.
I have to say I believe this is a step in the wrong direction. Having everybody call a function with that _wd suffix is ugly, as is having them all pass some pre-defined constant. Moreover, nowadays what happens every chunksize bytes isn't restricted to watchdog handling.
So yes, we don't need an API specially for non-watchdog, but why not just make sha1_csum() be the interface to call, and let the "maybe we need to call schedule() once in a while" be an implementation detail of sha1_csum().
The same as with our zlib implementaion; we don't have a separate _wd set of routines, we've just hooked schedule() into the main loop of that inflate algorithm.
The reason I keep the ` _csum_wd()` one is to align to other hash APIs
currently we have. For MD5, SHA256, SHA512, we only have `_csum_wd()` but no `_csum()` - SHA1 is a special one due to the historical problem I guess. The minimum refactoring I did here is to unify the interface and make it adaptable to the MbedTLS library I introduced with this series. Yes, I agree some optimizations or refactoring are needed for the hash APIs, but I will prefer to do this in a new series other than increasing the scope of this patch set.
[snip]
Regards, Raymond

On Fri, Oct 04, 2024 at 11:24:28AM -0400, Raymond Mao wrote:
Hi Rasmus,
On Fri, 4 Oct 2024 at 03:50, Rasmus Villemoes rasmus.villemoes@prevas.dk wrote:
Raymond Mao raymond.mao@linaro.org writes:
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.
I have to say I believe this is a step in the wrong direction. Having everybody call a function with that _wd suffix is ugly, as is having them all pass some pre-defined constant. Moreover, nowadays what happens every chunksize bytes isn't restricted to watchdog handling.
So yes, we don't need an API specially for non-watchdog, but why not just make sha1_csum() be the interface to call, and let the "maybe we need to call schedule() once in a while" be an implementation detail of sha1_csum().
The same as with our zlib implementaion; we don't have a separate _wd set of routines, we've just hooked schedule() into the main loop of that inflate algorithm.
The reason I keep the ` _csum_wd()` one is to align to other hash APIs currently we have. For MD5, SHA256, SHA512, we only have `_csum_wd()` but no `_csum()` - SHA1 is a special one due to the historical problem I guess. The minimum refactoring I did here is to unify the interface and make it adaptable to the MbedTLS library I introduced with this series. Yes, I agree some optimizations or refactoring are needed for the hash APIs, but I will prefer to do this in a new series other than increasing the scope of this patch set.
I agree this should be the target of near-future follow-up work rather than gating for the series.

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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 8a7b3a30c04..262abb2cec7 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -134,10 +134,100 @@ config MBEDTLS_LIB_CRYPTO_ALT
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. Mutually incompatible with MBEDTLS_LIB_CRYPTO_ALT.
+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 0b6d6ca808f..eeb28ec1557 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) += 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); +}

On Fri, 4 Oct 2024 at 00:54, Raymond Mao raymond.mao@linaro.org wrote:
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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- None
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 8a7b3a30c04..262abb2cec7 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -134,10 +134,100 @@ config MBEDTLS_LIB_CRYPTO_ALT
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. Mutually incompatible with MBEDTLS_LIB_CRYPTO_ALT.
+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 0b6d6ca808f..eeb28ec1557 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) += 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);
+}
2.25.1
Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org

Smaller implementation for SHA256 and SHA512 helps to reduce the ROM footprint though it has a certain impact on performance. As a trade-off, enable it as a default config when MbedTLS is enabled can reduce the target size significantly with acceptable performace loss.
Signed-off-by: Raymond Mao raymond.mao@linaro.org --- Changes in v6 - Initial patch Changes in v7 - Fixed the config dependencies. Changes in v8 - None
lib/mbedtls/Kconfig | 24 ++++++++++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 6 ++++++ 2 files changed, 30 insertions(+)
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index 262abb2cec7..8e3a94c6f2b 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -164,6 +164,18 @@ config SHA256_MBEDTLS This option enables support of hashing using SHA256 algorithm with MbedTLS crypto library.
+if SHA256_MBEDTLS + +config SHA256_SMALLER + bool "Enable SHA256 smaller implementation with MbedTLS crypto library" + depends on SHA256_MBEDTLS + default y if SHA256_MBEDTLS + help + This option enables support of hashing using SHA256 algorithm + smaller implementation with MbedTLS crypto library. + +endif + config SHA512_MBEDTLS bool "Enable SHA512 support with MbedTLS crypto library" depends on MBEDTLS_LIB_CRYPTO && SHA512 @@ -172,6 +184,18 @@ config SHA512_MBEDTLS This option enables support of hashing using SHA512 algorithm with MbedTLS crypto library.
+if SHA512_MBEDTLS + +config SHA512_SMALLER + bool "Enable SHA512 smaller implementation with MbedTLS crypto library" + depends on SHA512_MBEDTLS + default y if SHA512_MBEDTLS + help + This option enables support of hashing using SHA512 algorithm + smaller implementation with MbedTLS crypto library. + +endif + config SHA384_MBEDTLS bool "Enable SHA384 support with MbedTLS crypto library" depends on MBEDTLS_LIB_CRYPTO && SHA384 diff --git a/lib/mbedtls/mbedtls_def_config.h b/lib/mbedtls/mbedtls_def_config.h index 6fba053bd7c..1af911c2003 100644 --- a/lib/mbedtls/mbedtls_def_config.h +++ b/lib/mbedtls/mbedtls_def_config.h @@ -35,6 +35,9 @@ #if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT #define MBEDTLS_SHA256_ALT #endif +#if CONFIG_IS_ENABLED(SHA256_SMALLER) +#define MBEDTLS_SHA256_SMALLER +#endif #endif
#if CONFIG_IS_ENABLED(SHA384) @@ -48,6 +51,9 @@ #if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT #define MBEDTLS_SHA512_ALT #endif +#if CONFIG_IS_ENABLED(SHA512_SMALLER) +#define MBEDTLS_SHA512_SMALLER +#endif #endif
#if defined CONFIG_MBEDTLS_LIB_X509

On Fri, 4 Oct 2024 at 00:55, Raymond Mao raymond.mao@linaro.org wrote:
Smaller implementation for SHA256 and SHA512 helps to reduce the ROM footprint though it has a certain impact on performance. As a trade-off, enable it as a default config when MbedTLS is enabled can reduce the target size significantly with acceptable performace loss.
Signed-off-by: Raymond Mao raymond.mao@linaro.org
Changes in v6
- Initial patch
Changes in v7
- Fixed the config dependencies.
Changes in v8
- None
lib/mbedtls/Kconfig | 24 ++++++++++++++++++++++++ lib/mbedtls/mbedtls_def_config.h | 6 ++++++ 2 files changed, 30 insertions(+)
diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig index 262abb2cec7..8e3a94c6f2b 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -164,6 +164,18 @@ config SHA256_MBEDTLS This option enables support of hashing using SHA256 algorithm with MbedTLS crypto library.
+if SHA256_MBEDTLS
+config SHA256_SMALLER
bool "Enable SHA256 smaller implementation with MbedTLS crypto library"
depends on SHA256_MBEDTLS
default y if SHA256_MBEDTLS
help
This option enables support of hashing using SHA256 algorithm
smaller implementation with MbedTLS crypto library.
+endif
config SHA512_MBEDTLS bool "Enable SHA512 support with MbedTLS crypto library" depends on MBEDTLS_LIB_CRYPTO && SHA512 @@ -172,6 +184,18 @@ config SHA512_MBEDTLS This option enables support of hashing using SHA512 algorithm with MbedTLS crypto library.
+if SHA512_MBEDTLS
+config SHA512_SMALLER
bool "Enable SHA512 smaller implementation with MbedTLS crypto library"
depends on SHA512_MBEDTLS
default y if SHA512_MBEDTLS
help
This option enables support of hashing using SHA512 algorithm
smaller implementation with MbedTLS crypto library.
+endif
config SHA384_MBEDTLS bool "Enable SHA384 support with MbedTLS crypto library" depends on MBEDTLS_LIB_CRYPTO && SHA384 diff --git a/lib/mbedtls/mbedtls_def_config.h b/lib/mbedtls/mbedtls_def_config.h index 6fba053bd7c..1af911c2003 100644 --- a/lib/mbedtls/mbedtls_def_config.h +++ b/lib/mbedtls/mbedtls_def_config.h @@ -35,6 +35,9 @@ #if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT #define MBEDTLS_SHA256_ALT #endif +#if CONFIG_IS_ENABLED(SHA256_SMALLER) +#define MBEDTLS_SHA256_SMALLER +#endif #endif
#if CONFIG_IS_ENABLED(SHA384) @@ -48,6 +51,9 @@ #if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT #define MBEDTLS_SHA512_ALT #endif +#if CONFIG_IS_ENABLED(SHA512_SMALLER) +#define MBEDTLS_SHA512_SMALLER +#endif #endif
#if defined CONFIG_MBEDTLS_LIB_X509
2.25.1
Reviewed-by: Ilias Apalodimas ilias.apalodimas@linaro.org

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 Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v2 - None. Changes in v3 - Update commit message. Changes in v4 - None. Changes in v5 - None. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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 Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v2 - None. Changes in v3 - Update commit message. Changes in v4 - None. Changes in v5 - None. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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; }
/**

On Fri, 4 Oct 2024 at 00:56, Raymond Mao raymond.mao@linaro.org wrote:
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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- 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;
}
/**
2.25.1
Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org

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 Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org --- Changes in v2 - None. Changes in v3 - Update commit message. Changes in v4 - None. Changes in v5 - None. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 Reviewed-by: Ilias Apalodimas ilias.apalodimas@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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 8e3a94c6f2b..e81d14505ff 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -116,9 +116,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 @@ -255,7 +281,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 eeb28ec1557..d3f566d0c91 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) += 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 Reviewed-by: Ilias Apalodimas ilias.apalodimas@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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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

On Fri, 4 Oct 2024 at 00:59, Raymond Mao raymond.mao@linaro.org wrote:
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 Reviewed-by: Ilias Apalodimas ilias.apalodimas@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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- None
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
2.25.1
Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org

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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 e81d14505ff..abdafd04e89 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -118,6 +118,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 @@ -132,6 +133,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 @@ -283,6 +292,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 @@ -297,6 +307,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 d3f566d0c91..29653323279 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) += 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); +}

On Fri, 4 Oct 2024 at 01:00, Raymond Mao raymond.mao@linaro.org wrote:
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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- None
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 e81d14505ff..abdafd04e89 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -118,6 +118,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
@@ -132,6 +133,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 @@ -283,6 +292,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
@@ -297,6 +307,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 d3f566d0c91..29653323279 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) += 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);
+}
2.25.1
Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org

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. Changes in v6 - None. Changes in v7 - Drop the changes in kconfig. Changes in v8 - None
include/crypto/x509_parser.h | 55 ++++++++++++++++++++++++++++++++++++ lib/crypto/Makefile | 4 +-- lib/crypto/x509_public_key.c | 2 ++ 3 files changed, 59 insertions(+), 2 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/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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 abdafd04e89..189bb3186b6 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -119,6 +119,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 @@ -141,6 +142,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 @@ -293,6 +302,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 @@ -315,6 +325,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 29653323279..128a29c512f 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) += 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; +}

On Fri, 4 Oct 2024 at 01:01, Raymond Mao raymond.mao@linaro.org wrote:
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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- None
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 abdafd04e89..189bb3186b6 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -119,6 +119,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
@@ -141,6 +142,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 @@ -293,6 +302,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
@@ -315,6 +325,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 29653323279..128a29c512f 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) += 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;
+}
2.25.1
I don't know if it would be easier to try and merge this with the existing pkcs7 parser. It's unlikely since it has too much mbedTLS specific structs, but we might look into it in the future. In any case these are mutually exclusive so FWIW
Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org

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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 #

On Fri, 4 Oct 2024 at 01:02, Raymond Mao raymond.mao@linaro.org wrote:
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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- None
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.
- Authenticated Attributes (authenticatedAttributes)
MbedTLS assumes unauthenticatedAttributes and authenticatedAttributes
fields not exist.
See MbedTLS function 'pkcs7_get_signer_info' for details.
- 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
#
2.25.1
Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org

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 Acked-by: Ilias Apalodimas ilias.apalodimas@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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 189bb3186b6..fd7263f9616 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -303,6 +303,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 @@ -333,6 +334,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 128a29c512f..488b66402b3 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) += 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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 fd7263f9616..efeaed50385 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -120,6 +120,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 @@ -150,6 +151,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

On Fri, 4 Oct 2024 at 01:03, Raymond Mao raymond.mao@linaro.org wrote:
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.
Changes in v6
- None.
Changes in v7
- None.
Changes in v8
- None
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 fd7263f9616..efeaed50385 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -120,6 +120,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
@@ -150,6 +151,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
2.25.1
Acked-by: Ilias Apalodimas ilias.apalodimas@linaro.org

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 Acked-by: Ilias Apalodimas ilias.apalodimas@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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 efeaed50385..ab50ad4ebe9 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -118,11 +118,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.
@@ -135,6 +137,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 @@ -168,6 +178,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 @@ -310,11 +328,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.
@@ -327,6 +347,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 @@ -360,6 +388,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 488b66402b3..04d450afd82 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) += 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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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 Reviewed-by: Ilias Apalodimas ilias.apalodimas@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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - None
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 33755778283..561e0d44a16 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -81,7 +81,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 ab50ad4ebe9..d71adc3648a 100644 --- a/lib/mbedtls/Kconfig +++ b/lib/mbedtls/Kconfig @@ -116,12 +116,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 @@ -130,6 +132,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 @@ -171,6 +179,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 @@ -326,12 +341,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 @@ -340,6 +357,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 @@ -381,6 +404,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 04d450afd82..83cb3c2fa70 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. Changes in v6 - None. Changes in v7 - None. Changes in v8 - 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 and sandbox.
Signed-off-by: Raymond Mao raymond.mao@linaro.org Reviewed-by: Ilias Apalodimas ilias.apalodimas@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. Changes in v6 - Remove MBEDTLS_LIB_CRYPTO and MBEDTLS_LIB_X509. Changes in v7 - None. Changes in v8 - None
configs/qemu_arm64_defconfig | 1 + configs/sandbox_defconfig | 1 + 2 files changed, 2 insertions(+)
diff --git a/configs/qemu_arm64_defconfig b/configs/qemu_arm64_defconfig index 088ba39f18e..6d18a8571ca 100644 --- a/configs/qemu_arm64_defconfig +++ b/configs/qemu_arm64_defconfig @@ -68,5 +68,6 @@ CONFIG_TPM2_MMIO=y CONFIG_USB_EHCI_HCD=y CONFIG_USB_EHCI_PCI=y CONFIG_SEMIHOSTING=y +CONFIG_MBEDTLS_LIB=y CONFIG_TPM=y CONFIG_EFI_HTTP_BOOT=y diff --git a/configs/sandbox_defconfig b/configs/sandbox_defconfig index a50fbce8d06..0ecdeebb45f 100644 --- a/configs/sandbox_defconfig +++ b/configs/sandbox_defconfig @@ -345,6 +345,7 @@ CONFIG_FS_CBFS=y CONFIG_FS_CRAMFS=y CONFIG_ADDR_MAP=y CONFIG_CMD_DHRYSTONE=y +CONFIG_MBEDTLS_LIB=y CONFIG_ECDSA=y CONFIG_ECDSA_VERIFY=y CONFIG_TPM=y

On Thu, 3 Oct 2024 at 15:51, Raymond Mao raymond.mao@linaro.org 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_CRYPTO_ALT` is for using original U-Boot crypto libs as MbedTLS crypto alternatives. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected when `MBEDTLS_LIB` is enabled. `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. From v6, smaller implementations for SHA256 and SHA512 are enabled and target size reduce significantly. Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% v3 - v5: 4.55% v6: 2.90%
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 (With both `MBEDTLS_LIB` and `MBEDTLS_LIB_CRYPTO` selected) (qemu_arm64, sandbox and nanopi_a64)
aarch64: (for 2/2 boards) all -1568.0 bss -8.0 data -64.0 rodata +200.0 text -1696.0 qemu_arm64 : all +4472 bss -16 data -64 rodata +200 text +4352 u-boot: add: 29/-14, grow: 6/-13 bytes: 12812/-8084 (4728) function old new delta mbedtls_internal_sha1_process - 4540 +4540
I am not going to review this version as others are on top of this. It looks reasonable to me. We do need to tidy up the hashing in common/hash.c at some point but this series doesn't add to the pain there.
I do worry about the size growth, though. Do we want/need the mbed algorithms? Why are they so large?
Regards, Simon

Hi Simon,
On Wed, 9 Oct 2024 at 04:52, Simon Glass sjg@chromium.org wrote:
On Thu, 3 Oct 2024 at 15:51, Raymond Mao raymond.mao@linaro.org 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_CRYPTO_ALT` is for using original U-Boot crypto libs as MbedTLS crypto alternatives. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected when `MBEDTLS_LIB` is enabled. `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. From v6, smaller implementations for SHA256 and SHA512 are enabled and target size reduce significantly. Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% v3 - v5: 4.55% v6: 2.90%
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 (With both `MBEDTLS_LIB` and `MBEDTLS_LIB_CRYPTO` selected) (qemu_arm64, sandbox and nanopi_a64)
aarch64: (for 2/2 boards) all -1568.0 bss -8.0 data -64.0 rodata +200.0 text -1696.0 qemu_arm64 : all +4472 bss -16 data -64 rodata +200 text +4352 u-boot: add: 29/-14, grow: 6/-13 bytes: 12812/-8084 (4728) function old new delta mbedtls_internal_sha1_process - 4540 +4540
I am not going to review this version as others are on top of this. It looks reasonable to me. We do need to tidy up the hashing in common/hash.c at some point but this series doesn't add to the pain there.
I don't have time to review those things in depth. OTOH we have enough testing on the CI to make sure cryptography is working and I do like the state of the patches as well.
The current code leave mbedTLS hashing algorithms as a choice, but set the existing hashing algos as the default, since they are smaller and work with offloading. Since using new algorithms from mbedTLS might have valid use cases, I suggest we pull this and clean up the hash subsystem, to include all 4 options - mbedTLS in sw - U-Boot hashes in sw - Mix of mbedTLS & hardware offloading - Mix of U-Boot hashing & hardware offloading (already works)
Thanks /Ilias
I do worry about the size growth, though. Do we want/need the mbed algorithms? Why are they so large?
Regards, Simon

Hi Ilias,
On Wed, 9 Oct 2024 at 05:50, Ilias Apalodimas ilias.apalodimas@linaro.org wrote:
Hi Simon,
On Wed, 9 Oct 2024 at 04:52, Simon Glass sjg@chromium.org wrote:
On Thu, 3 Oct 2024 at 15:51, Raymond Mao raymond.mao@linaro.org 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_CRYPTO_ALT` is for using original U-Boot crypto libs as MbedTLS crypto alternatives. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected when `MBEDTLS_LIB` is enabled. `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.
From v6, smaller implementations for SHA256 and SHA512 are enabled and target size reduce significantly. Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% v3 - v5: 4.55% v6: 2.90%
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 (With both `MBEDTLS_LIB` and `MBEDTLS_LIB_CRYPTO` selected) (qemu_arm64, sandbox and nanopi_a64)
aarch64: (for 2/2 boards) all -1568.0 bss -8.0 data -64.0 rodata
+200.0 text -1696.0
qemu_arm64 : all +4472 bss -16 data -64 rodata +200
text +4352
u-boot: add: 29/-14, grow: 6/-13 bytes: 12812/-8084
(4728)
function old
new delta
mbedtls_internal_sha1_process -
4540 +4540
I am not going to review this version as others are on top of this. It looks reasonable to me. We do need to tidy up the hashing in common/hash.c at some point but this series doesn't add to the pain there.
I don't have time to review those things in depth. OTOH we have enough testing on the CI to make sure cryptography is working and I do like the state of the patches as well.
The current code leave mbedTLS hashing algorithms as a choice, but set the existing hashing algos as the default, since they are smaller and work with offloading. Since using new algorithms from mbedTLS might have valid use cases, I suggest we pull this and clean up the hash subsystem, to include all 4 options
- mbedTLS in sw
- U-Boot hashes in sw
- Mix of mbedTLS & hardware offloading
- Mix of U-Boot hashing & hardware offloading (already works)
The patch set has these already with combinations of kconfigs: - mbedTLS in sw (set CONFIG_MBEDTLS_LIB=y && MBEDTLS_LIB_CRYPTO=y, tested via github CI) - U-Boot hashes in sw (default when setting CONFIG_MBEDTLS_LIB=y only, tested via github CI) - Mix of mbedTLS & hardware offloading (I didn't test this but it should work as it was when SHA_HW_ACCEL=y)
Regards, Raymond

On Thu, Oct 03, 2024 at 02:50:13PM -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_CRYPTO_ALT` is for using original U-Boot crypto libs as MbedTLS crypto alternatives. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected when `MBEDTLS_LIB` is enabled. `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. From v6, smaller implementations for SHA256 and SHA512 are enabled and target size reduce significantly. Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% v3 - v5: 4.55% v6: 2.90%
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.
For the whole series, applied to u-boot/master. Thanks again for all the hard work here.

Hi Tom,
On Tue, 15 Oct 2024 at 07:30, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:13PM -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_CRYPTO_ALT` is for using original U-Boot crypto libs as MbedTLS crypto alternatives. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected when `MBEDTLS_LIB` is enabled. `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. From v6, smaller implementations for SHA256 and SHA512 are enabled and target size reduce significantly. Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% v3 - v5: 4.55% v6: 2.90%
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.
For the whole series, applied to u-boot/master. Thanks again for all the hard work here.
Likewise, thanks for the patience and testing! Regards /Ilias
-- Tom

Hi Tom,
On Tue, 15 Oct 2024 at 00:30, Tom Rini trini@konsulko.com wrote:
On Thu, Oct 03, 2024 at 02:50:13PM -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_CRYPTO_ALT` is for using original U-Boot crypto libs as MbedTLS crypto alternatives. `MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1, and Pubkey parser with MbedTLS. By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected when `MBEDTLS_LIB` is enabled. `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.
From v6, smaller implementations for SHA256 and SHA512 are enabled and target size reduce significantly. Target(QEMU arm64) size-growth when enabling MbedTLS: v1: 6.03% v2: 4.66% v3 - v5: 4.55% v6: 2.90%
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.
For the whole series, applied to u-boot/master. Thanks again for all the hard work here.
Thanks a lot for the time spent on reviewing, testing and all the
suggestions.
Raymond
participants (5)
-
Ilias Apalodimas
-
Rasmus Villemoes
-
Raymond Mao
-
Simon Glass
-
Tom Rini