diff --git a/.github/Dockerfile b/.github/Dockerfile new file mode 100644 index 00000000..73d903e3 --- /dev/null +++ b/.github/Dockerfile @@ -0,0 +1,71 @@ +FROM ubuntu:22.04 + +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get update -y && apt-get upgrade -y && apt-get install -y \ + git \ + build-essential \ + cmake \ + libxml2-dev \ + uuid-dev \ + libcurl4-openssl-dev \ + openssl \ + libssl-dev \ + wget \ + bsdmainutils \ + unzip \ + libglib2.0-dev \ + xxd \ + nghttp2 \ + libnghttp2-dev \ + ruby + +RUN mkdir build_dir + +# Build & Install Curl version 8.1.2 +WORKDIR /build_dir/ +RUN wget https://curl.se/download/curl-8.1.2.tar.gz -O - | tar -xz && cd curl-8.1.2 && \ +./configure --with-openssl --enable-versioned-symbols --with-nghttp2 && make && make install + +# Setup safestring +WORKDIR /build_dir +RUN git clone -b v1.2.0 --progress --verbose https://github.com/intel/safestringlib.git safestring +ENV SAFESTRING_ROOT /build_dir/safestring +WORKDIR ${SAFESTRING_ROOT} +RUN mkdir obj && make + +# Setup tinycbor +WORKDIR /build_dir +RUN git clone -b v0.6.0 --progress --verbose https://github.com/intel/tinycbor.git tinycbor +ENV TINYCBOR_ROOT /build_dir/tinycbor +WORKDIR ${TINYCBOR_ROOT} +RUN make + +# Setup metee +WORKDIR /build_dir +RUN git clone --progress --verbose https://github.com/intel/metee.git metee +ENV METEE_ROOT /build_dir/metee +WORKDIR ${METEE_ROOT} +RUN cmake . && make && make install + +ENV OPENSSL3_ROOT /usr +ENV CURL_ROOT /usr + +# Setup client-sdk-fidoiot. +# clone client-sdk-fidoiot to the current Dockerfile directory +WORKDIR /build_dir/ +RUN mkdir /cse-fdoout +WORKDIR /build_dir/cse-fdoout/ +RUN mkdir /client-sdk +WORKDIR /build_dir/fdoout/client-sdk/ +COPY . . + +# Install tpm libraries +RUN grep -rl '/opt/openssl' ./ | xargs sed -i 's/\/opt\/openssl/\/usr/g' +RUN grep -rl '/opt/curl' ./ | xargs sed -i 's/\/opt\/curl/\/usr/g' +RUN sed -i 's/lib64/lib\/x86_64-linux-gnu/' utils/install_tpm_libs.sh +RUN sed -i 's/==/-eq/' utils/tpm_make_ready_ecdsa.sh +RUN sh utils/install_tpm_libs.sh -i + + +CMD ["bash", "build.sh"] \ No newline at end of file diff --git a/.github/workflows/ai-review-cache.yaml b/.github/workflows/ai-review-cache.yaml new file mode 100644 index 00000000..bc9aaa4b --- /dev/null +++ b/.github/workflows/ai-review-cache.yaml @@ -0,0 +1,89 @@ +name: "AI Reviewer Cache" + +on: + workflow_dispatch: + push: + branches: + # TODO: Update with the repos trunk branch. + - "client-sdk-fidoiot-ai-code-review" + +jobs: + generate-cache: + name: Generate AI Cache + container: amr-registry.caas.intel.com/devops-ai-platform/gasp-oidc:0.0.4 + # TODO: Update'runs-on' to specify the type of runner your repo uses. + # If using GASP, do not add additional labels. Use ONLY "gasp". + runs-on: gasp + permissions: + contents: read + issues: write + pull-requests: write + id-token: write + + steps: + # Login using OIDC Auth + - name: Authenticate + uses: azure/login@v1 + with: + client-id: ${{ secrets.AZURE_CLIENT_ID }} + tenant-id: ${{ secrets.AZURE_TENANT_ID }} + subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} + + # Get a temporary access token. Expires in 5-60 minutes. + - name: Retrieve Access Token + id: auth + run: | + export output=$(az account get-access-token --resource https://cognitiveservices.azure.com --query \"accessToken\" -o tsv); + echo "result=$output" >> $GITHUB_OUTPUT; + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Cache embeddings + id: cache-embeddings + uses: actions/cache@v4 + env: + cache-name: cache-embeddings + with: + path: ./cache + key: ${{ env.cache-name }}-${{ github.run_id }} + restore-keys: ${{ env.cache-name }} + + - name: Create Document Embeddings + uses: intel-innersource/frameworks.devops.ai-devops-platform.embedding-action@v3 + env: + no_proxy: "*.azure.com" + with: + name: documentation_lookup + description: Used to answer questions about documentation. + service_model: embedding + service_token: bearer ${{ steps.auth.outputs.result }} + # TODO: Update 'file_types' with the code file extensions to parse. *Note it is a newline delimited list. + file_types: | + .md + # TODO: Update 'languages' to include the languages in the repository. *Note it is a newline delimited list. + # Supports the following values: 'cpp', 'go', 'java', 'js', 'php', 'proto', 'python', 'rst', 'ruby', 'rust', 'scala', 'swift', 'markdown', 'latex', 'html' + languages: | + markdown + # TODO: Update 'path' to represent the top level path where code files are found. + path: ./src + cache_path: ./cache + + - name: Create Code Embeddings + uses: intel-innersource/frameworks.devops.ai-devops-platform.embedding-action@v3 + env: + no_proxy: "*.azure.com" + with: + name: code_lookup + description: Used to get additional context for code. + service_model: embedding + service_token: bearer ${{ steps.auth.outputs.result }} + # TODO: Update 'file_types' with the code file extensions to parse. *Note it is a newline delimited list. + file_types: | + .ts + # TODO: Update 'languages' to include the languages in the repository. *Note it is a newline delimited list. + # Supports the following values: 'cpp', 'go', 'java', 'js', 'php', 'proto', 'python', 'rst', 'ruby', 'rust', 'scala', 'swift', 'markdown', 'latex', 'html' + languages: | + js + # TODO: Update 'path' to represent the top level path where code files are found. + path: ./src + cache_path: ./cache diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml new file mode 100644 index 00000000..a8ba8bfd --- /dev/null +++ b/.github/workflows/main.yaml @@ -0,0 +1,78 @@ +name: client-sdk-fidoiot-build +on: + workflow_dispatch: + push: + branches: [master, '*rel'] + pull_request: + branches: [master, '*rel'] +permissions: + contents: read +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: scm checkout + uses: actions/checkout@v3 + - name: Build docker image + run: docker build -t client-sdk -f '.github/Dockerfile' . + - name: run Docker container + run: docker run -v $PWD:/build_dir/fdoout/client-sdk/ client-sdk:latest + - name: tar client-sdk binaries + run: | + mkdir client-sdk-binaries && cd client-sdk-binaries + cp -r ../x86_ecdsa* ../tpm_ecdsa* ../cse_ecdsa* . + mkdir utils + cp ../utils/tpm_make_ready_ecdsa.sh ../utils/install_tpm_libs*.sh ../utils/keys_gen.sh utils/ + cd .. && tar -cvzf client-sdk-binaries.tar.gz client-sdk-binaries + - name: checkout test-fidoiot + uses: actions/checkout@v3 + with: + repository: fido-device-onboard/test-fidoiot + ref: master + path: test-fidoiot + - name: Download pri-fidoiot artifact + id: download-artifact + uses: dawidd6/action-download-artifact@v2 + with: + name: demo.tar.gz + repo: fido-device-onboard/pri-fidoiot + workflow: main.yaml + path: test-fidoiot/binaries/pri-fidoiot/ + search_artifacts: true + - name: Add host to /etc/hosts + run: | + sudo echo "127.0.0.1 host.docker.internal" | sudo tee -a /etc/hosts + - name: Smoke Test + run : | + mkdir -p test-fidoiot/binaries/client-sdk-fidoiot + tar -xvzf test-fidoiot/binaries/pri-fidoiot/demo.tar.gz + cp -r demo/* test-fidoiot/binaries/pri-fidoiot/ + cp x86_ecdsa256_gcm_bin/linux-client test-fidoiot/binaries/client-sdk-fidoiot/ + cp -r x86_ecdsa256_gcm_bin/data test-fidoiot/ + bash utils/install_openssl_curl.sh -i -v 3.0.8 + bash utils/keys_gen.sh test-fidoiot + cd test-fidoiot/binaries/pri-fidoiot/scripts + bash demo_ca.sh + bash web_csr_req.sh + bash user_csr_req.sh + bash keys_gen.sh + chmod -R 777 secrets/ + cp -r service.env secrets/ ../aio/ + cp -r secrets/ ../db/ + sed -i '//,/<.security-constraint>/d' ../aio/WEB-INF/web.xml + sed -i '/^innodb/d' ../db/custom/config-file.cnf + cd ${{ github.workspace }}/test-fidoiot/data + sed -i 's/8039/8080/g' manufacturer_addr.bin + cd ${{ github.workspace }}/test-fidoiot + export TEST_DIR=`pwd` + mvn clean test -Dgroups=fdo_clientsdk_smoketest + - name: archive artifacts + uses: actions/upload-artifact@v3 + with: + name: client-sdk-binaries.tar.gz + path: client-sdk-binaries.tar.gz + retention-days: 5 + if: github.event_name != 'pull_request' + + + diff --git a/.gitignore b/.gitignore index e421fc56..7d7a6df6 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,12 @@ *.so *.so.* *.a +*.blob +*.bin +*.pem +*.dat +*.ctx +*.key # Packages # ############ @@ -51,6 +57,7 @@ Thumbs.db ############### CMakeCache.txt CMakeFiles +Makefile CMakeScripts cmake_install.cmake install_manifest.txt @@ -92,6 +99,7 @@ buildNumber.properties .metadata *.iml *.ipr +.vscode # Visual Studio files # ####################### diff --git a/CMakeLists.txt b/CMakeLists.txt index 5efa0262..ba92a188 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,6 +16,13 @@ include(cmake/cli_input.cmake) include(cmake/extension.cmake) include(cmake/blob_path.cmake) +if (NOT(DEFINED ENV{OPENSSL3_ROOT})) + message(FATAL_ERROR "OPENSSL3_ROOT not set") +endif() + +if (NOT(DEFINED ENV{CURL_ROOT})) + message(FATAL_ERROR "CURL_ROOT not set") +endif() if (NOT(DEFINED ENV{SAFESTRING_ROOT})) message(FATAL_ERROR "SAFESTRING_ROOT not set") @@ -43,7 +50,6 @@ client_sdk_compile_options( -Wswitch-default -Wunused-parameter -Wsign-compare - -Wno-deprecated-declarations -Wpedantic -Werror -Wimplicit-function-declaration @@ -71,6 +77,8 @@ client_sdk_compile_options( if(${TARGET_OS} MATCHES linux) # Safestring lib client_sdk_include_directories( + $ENV{OPENSSL3_ROOT}/include + $ENV{CURL_ROOT}/include $ENV{SAFESTRING_ROOT}/include $ENV{TINYCBOR_ROOT}/src include @@ -121,11 +129,14 @@ if(${TARGET_OS} MATCHES linux) -L$ENV{TINYCBOR_ROOT}/lib/ -l:libtinycbor.a -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now + -L$ENV{CURL_ROOT}/lib -lcurl ) if (${TLS} STREQUAL openssl) client_sdk_ld_options( + -L$ENV{OPENSSL3_ROOT}/lib64 + -L$ENV{OPENSSL3_ROOT}/lib -Wl,--no-whole-archive -lssl -lcrypto -ldl ) elseif(${TLS} MATCHES mbedtls) diff --git a/Jenkinsfile.yml b/Jenkinsfile.yml index 57567518..7e5294ca 100644 --- a/Jenkinsfile.yml +++ b/Jenkinsfile.yml @@ -3,9 +3,7 @@ node('ccode'){ 'REPO_Safestring=https://github.com/intel/safestringlib.git', 'REPO_TinyCBOR=https://github.com/intel/tinycbor.git', 'REPO_METEE=https://github.com/intel/metee.git', - "TEST_DIR=${WORKSPACE}/test-fidoiot", - "MANUFACTURER_DB_CONNECT_STRING=jdbc:mariadb://127.0.0.1:3306/sdo", - "RESELLER_DB_CONNECT_STRING=jdbc:mariadb://127.0.0.1:4306/sdo" + "TEST_DIR=${WORKSPACE}/test-fidoiot" ]) { stage('Clone Client-SDK'){ @@ -13,7 +11,7 @@ node('ccode'){ dir('client-sdk'){ checkout scm } - sh 'git clone "${REPO_Safestring}"' + sh 'git clone -b v1.2.0 "${REPO_Safestring}"' sh 'git clone "${REPO_TinyCBOR}"' sh 'git clone "${REPO_METEE}"' } @@ -22,6 +20,7 @@ node('ccode'){ sh ''' cd $WORKSPACE/safestringlib echo 'Building safestring' + git checkout v1.2.0 mkdir obj make ''' @@ -31,7 +30,7 @@ node('ccode'){ sh ''' cd $WORKSPACE/tinycbor echo 'Building TinyCBOR' - git checkout v0.5.3 + git checkout v0.6.0 make ''' } @@ -40,6 +39,7 @@ node('ccode'){ sh ''' cd $WORKSPACE/metee echo 'Building METEE' + git checkout 3.2.3 cmake . make -j$(nproc) sudo make install @@ -54,8 +54,12 @@ node('ccode'){ echo $TINYCBOR_ROOT export METEE_ROOT=$WORKSPACE/metee echo $METEE_ROOT + export OPENSSL3_ROOT=/opt/openssl + echo $OPENSSL3_ROOT + export CURL_ROOT=/opt/curl + echo $CURL_ROOT cd $WORKSPACE/client-sdk - $WORKSPACE/client-sdk/build.sh -s + $WORKSPACE/client-sdk/build.sh mkdir client-sdk-binaries cd client-sdk-binaries cp -r ../x86_ecdsa256_gcm_bin . @@ -64,6 +68,8 @@ node('ccode'){ cp -r ../x86_ecdsa384_ccm_bin . cp -r ../tpm_ecdsa256_gcm_bin . cp -r ../tpm_ecdsa256_ccm_bin . + cp -r ../tpm_ecdsa384_gcm_bin . + cp -r ../tpm_ecdsa384_ccm_bin . cp -r ../cse_ecdsa384_gcm_bin . cp -r ../cse_ecdsa384_ccm_bin . mkdir utils @@ -150,4 +156,4 @@ node('ccode'){ cleanWs cleanWhenFailure: false, cleanWhenNotBuilt: false, notFailBuild: true } -} \ No newline at end of file +} diff --git a/NOTICE b/NOTICE index 4ee89afd..1958ce4a 100644 --- a/NOTICE +++ b/NOTICE @@ -325,6 +325,7 @@ The following components are used under The BSD 2-Clause License: tom2-software tpm2-tss tpm2-software tpm2-abrmd +tpm2-tools Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -349,7 +350,9 @@ OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The following components are used under The BSD 3-Clause License: -tpm2-software tpm2-tss-engine +tpm2-software +tpm2-openssl + Redistribution and use in source and binary forms, with or without diff --git a/NOTICES/tpm2-tools b/NOTICES/tpm2-tools new file mode 100644 index 00000000..723db9ee --- /dev/null +++ b/NOTICES/tpm2-tools @@ -0,0 +1,37 @@ +Copyright 2017 Alibaba Group +Copyright 2015-2017 Atom Software Studios, s.r.o. +Copyright 2017 Emmanuel Deloget +Copyright 2018-2019 Fraunhofer SIT +Copyright 2019 Fraunhofer SIT sponsored by Infineon Technologies AG +Copyright 2019 GlovePuppet +Copyright 2015-2019 Intel Corporation +Copyright 2019 Massachusetts Institute of Technology +Copyright 2017-2018 National Instruments +Copyright 2017 Red Hat, Inc. +Copyright 2019 Sebastien LE STUM +Copyright 2017 SUSE GmbH + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md index c6523173..ae184af3 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ ## Supported Versions -Information about different FDO release versions can be found on the [FDO Release page](https://secure-device-onboard.github.io/docs/latest/releases/). +Information about different FDO release versions can be found on the [FDO Release page](https://fido-device-onboard.github.io/docs/latest/releases/). ## Reporting a Vulnerability diff --git a/app/blob.c b/app/blob.c index d8af035b..269c680d 100644 --- a/app/blob.c +++ b/app/blob.c @@ -24,7 +24,7 @@ #include #include #include "safe_lib.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #if defined(USE_OPENSSL) #include #include @@ -35,7 +35,8 @@ #include "blob.h" #if defined(DEVICE_TPM20_ENABLED) #include "tpm20_Utils.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" +#include "tpm2_nv_storage.h" #endif #if !defined(DEVICE_TPM20_ENABLED) @@ -58,7 +59,6 @@ static int32_t gen_rdm_bytestream(uint8_t *random_buffer, size_t num_bytes) } return 0; } -#endif int32_t configure_normal_blob(void) { @@ -71,19 +71,6 @@ int32_t configure_normal_blob(void) uint8_t *signed_normal_blob = NULL; size_t signed_normal_blob_size = 0; int32_t ret = -1; - -#if defined(DEVICE_TPM20_ENABLED) - if (0 == is_valid_tpm_data_protection_key_present()) { - if (0 != fdo_generate_storage_hmac_key()) { - LOG(LOG_ERROR, "Failed to generate TPM data protection" - " key.\n"); - goto err; - } - - LOG(LOG_DEBUG, - "TPM data protection key generated successfully.\n"); - } -#else uint8_t hmac_key[PLATFORM_HMAC_KEY_DEFAULT_LEN] = {0}; size_t key_size_stored = @@ -114,7 +101,6 @@ int32_t configure_normal_blob(void) LOG(LOG_ERROR, "Failed to read plain Normal blob!\n"); goto err; } -#endif raw_normal_blob_size = fdo_blob_size((char *)FDO_CRED_NORMAL, FDO_SDK_RAW_DATA); @@ -158,13 +144,6 @@ int32_t configure_normal_blob(void) "Malloc Failed for sealed Normal Blob buffer!\n"); goto err; } -#if defined(DEVICE_TPM20_ENABLED) - if (0 != fdo_compute_storage_hmac(raw_normal_blob, raw_normal_blob_size, - signed_normal_blob, - PLATFORM_HMAC_SIZE)) { - goto err; - } -#else #if defined(USE_MBEDTLS) if (0 != mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), (const uint8_t *)hmac_key, @@ -178,7 +157,6 @@ int32_t configure_normal_blob(void) signed_normal_blob, NULL)) { goto err; } -#endif #endif // copy plain-text size signed_normal_blob[PLATFORM_HMAC_SIZE + 3] = raw_normal_blob_size >> 0; @@ -214,3 +192,4 @@ int32_t configure_normal_blob(void) } return ret; } +#endif \ No newline at end of file diff --git a/app/main.c b/app/main.c index 664cd97d..c1825e92 100644 --- a/app/main.c +++ b/app/main.c @@ -28,6 +28,10 @@ #include "cse_utils.h" #include "cse_tools.h" #endif +#if defined(DEVICE_TPM20_ENABLED) +#include "tpm20_Utils.h" +#include "fdo_crypto.h" +#endif #define STORAGE_NAMESPACE "storage" #define OWNERSHIP_TRANSFER_FILE "data/owner_transfer" @@ -111,7 +115,8 @@ static fdo_sdk_service_info_module *fdo_sv_info_modules_init(void) { fdo_sdk_service_info_module *module_info = NULL; - module_info = fdo_alloc(FDO_MAX_MODULES * (sizeof(fdo_sdk_service_info_module))); + module_info = + fdo_alloc(FDO_MAX_MODULES * (sizeof(fdo_sdk_service_info_module))); if (!module_info) { LOG(LOG_ERROR, "Malloc failed!\n"); @@ -127,6 +132,24 @@ static fdo_sdk_service_info_module *fdo_sv_info_modules_init(void) } module_info[0].service_info_callback = fdo_sys; + /* module#2: fdo.download */ + if (strncpy_s(module_info[1].module_name, FDO_MODULE_NAME_LEN, + "fdo.download", FDO_MODULE_NAME_LEN) != 0) { + LOG(LOG_ERROR, "Strcpy failed"); + fdo_free(module_info); + return NULL; + } + module_info[1].service_info_callback = fdo_sim_download; + + /* module#3: fdo.command */ + if (strncpy_s(module_info[2].module_name, FDO_MODULE_NAME_LEN, + "fdo.command", FDO_MODULE_NAME_LEN) != 0) { + LOG(LOG_ERROR, "Strcpy failed"); + fdo_free(module_info); + return NULL; + } + module_info[2].service_info_callback = fdo_sim_command; + return module_info; } @@ -199,19 +222,19 @@ static void print_device_status(void) status = fdo_sdk_get_status(); if (status == FDO_STATE_PRE_DI) { - LOG(LOG_DEBUG, "Device is ready for DI\n"); + LOG(LOG_INFO, "Device is ready for DI\n"); } if (status == FDO_STATE_PRE_TO1) { - LOG(LOG_DEBUG, "Device is ready for Ownership transfer\n"); + LOG(LOG_INFO, "Device is ready for Ownership transfer\n"); } if (status == FDO_STATE_IDLE) { - LOG(LOG_DEBUG, "Device Ownership transfer Done\n"); + LOG(LOG_INFO, "Device Ownership transfer Done\n"); } if (status == FDO_STATE_RESALE) { - LOG(LOG_DEBUG, "Device is ready for Ownership transfer\n"); + LOG(LOG_INFO, "Device is ready for Ownership transfer\n"); } if (status == FDO_STATE_ERROR) { - LOG(LOG_DEBUG, "Error in getting device status\n"); + LOG(LOG_ERROR, "Error in getting device status\n"); } } @@ -228,10 +251,44 @@ int app_main(bool is_resale) { fdo_sdk_service_info_module *module_info = NULL; int ret = -1; - + bool resale = false; bool do_resale = false; + int strcmp_res = 0; + LOG(LOG_DEBUG, "Starting FIDO Device Onboard\n"); + for (int index = 1; index < argc; index++) { + if (index + 1 < argc && + (!strcmp_s((char *)argv[index], DATA_CONTENT_SIZE, "-ip", + &strcmp_res) && + !strcmp_res)) { + index++; + mfg_addr = argv[index]; + use_mfg_addr_bin = false; + } else if (!strcmp_s((char *)argv[index], DATA_CONTENT_SIZE, + "-ss", &strcmp_res) && + !strcmp_res) { +#if defined SELF_SIGNED_CERTS_SUPPORTED + useSelfSignedCerts = true; + LOG(LOG_INFO, "Set connection for self signed " + "certificate usage.\n"); +#endif + } else if (!strcmp_s((char *)argv[index], DATA_CONTENT_SIZE, + "-r", &strcmp_res) && + !strcmp_res) { + resale = true; + } else { + printf("Usage: linux-client -ip ://:\n" + "\tif -ip not specified, manufacturer_addr.bin " + "will be used\n" + "\t-ss: specify if backend servers are using " + "self-signed certificates\n" + "\t-r: enable resale\n"); + exit(1); + } + } + #ifdef SECURE_ELEMENT if (-1 == se_provisioning()) { LOG(LOG_ERROR, "Provisioning Secure element failed!\n"); @@ -239,8 +296,9 @@ int app_main(bool is_resale) } #endif /* SECURE_ELEMENT */ -#if !defined(DEVICE_CSE_ENABLED) - LOG(LOG_DEBUG, "CSE not enabaled, Normal Blob Modules loaded!\n"); +#if !defined(DEVICE_CSE_ENABLED) && !defined(DEVICE_TPM20_ENABLED) + LOG(LOG_DEBUG, + "CSE and TPM not enabled, Normal Blob Modules loaded!\n"); if (-1 == configure_normal_blob()) { LOG(LOG_ERROR, "Provisioning Normal blob for the 1st time failed!\n"); @@ -256,7 +314,7 @@ int app_main(bool is_resale) LOG(LOG_DEBUG, "Sv_info Modules not loaded!\n"); } - /* Init fdo sdk */ + /* Init FDO sdk */ if (FDO_SUCCESS != fdo_sdk_init(error_cb, FDO_MAX_MODULES, module_info)) { LOG(LOG_ERROR, "fdo_sdk_init failed!!\n"); @@ -277,25 +335,15 @@ int app_main(bool is_resale) #endif #if defined TARGET_OS_LINUX - if (argc > 1 && *argv[1] == '1') { + if (resale == true) { do_resale = true; } #else - if (is_resale == true) { + if (is_resale == true) { do_resale = true; } #endif -#if defined SELF_SIGNED_CERTS_SUPPORTED - int strcmp_ss = 1; - int res = -1; - - res = (int)strcmp_s((char *)argv[1], DATA_CONTENT_SIZE, "-ss", - &strcmp_ss); - if (argc > 1 && (!res && !strcmp_ss)) { - useSelfSignedCerts = true; - } -#endif if (is_ownership_transfer(do_resale)) { ret = 0; goto end; diff --git a/app/se_provisioning.c b/app/se_provisioning.c index 8440771a..14ff3d12 100644 --- a/app/se_provisioning.c +++ b/app/se_provisioning.c @@ -52,7 +52,7 @@ uint8_t slot_config[] = { 0x0F, 0x0F, /* Slot 12 */ 0x0F, 0x0F, /* Slot 13 */ 0x0F, 0x0F, /* Slot 14 */ - 0x0F, 0x0F /* Slot 15 */ + 0x0F, 0x0F /* Slot 15 */ }; uint8_t key_config[] = { @@ -71,7 +71,7 @@ uint8_t key_config[] = { 0x3C, 0x00, /* Slot 12 */ 0x3C, 0x00, /* Slot 13 */ 0x32, 0x00, /* Slot 14 */ - 0x30, 0x00 /* Slot 15 */ + 0x30, 0x00 /* Slot 15 */ }; static void print_arr(uint8_t *arr, uint32_t len) diff --git a/build.sh b/build.sh index a1ac2586..bf0ed173 100755 --- a/build.sh +++ b/build.sh @@ -89,6 +89,8 @@ build_bin x86_ecdsa384_gcm_bin -DAES_MODE=gcm -DDA=ecdsa384 build_bin x86_ecdsa384_ccm_bin -DAES_MODE=ccm -DDA=ecdsa384 build_bin tpm_ecdsa256_gcm_bin -DAES_MODE=gcm -DDA=tpm20_ecdsa256 build_bin tpm_ecdsa256_ccm_bin -DAES_MODE=ccm -DDA=tpm20_ecdsa256 +build_bin tpm_ecdsa384_gcm_bin -DAES_MODE=gcm -DDA=tpm20_ecdsa384 +build_bin tpm_ecdsa384_ccm_bin -DAES_MODE=ccm -DDA=tpm20_ecdsa384 build_bin cse_ecdsa384_gcm_bin -DAES_MODE=gcm -DDA=cse_ecdsa384 -DCSE_CLEAR=true build_bin cse_ecdsa384_ccm_bin -DAES_MODE=ccm -DDA=cse_ecdsa384 -DCSE_CLEAR=true @@ -124,4 +126,4 @@ run_unit_test -DDA=ecdsa256 -DAES_MODE=gcm -DDA_FILE=pem fail_count=$(awk '/Tests Failed :/ {split($0,a,": "); count+=a[2]} END{print count}' $TEST_OUTPUT) echo "Found $fail_count unit-test failure(s)." -exit $fail_count \ No newline at end of file +exit $fail_count diff --git a/cmake/blob_path.cmake b/cmake/blob_path.cmake index 5359ca7d..9bae11e9 100644 --- a/cmake/blob_path.cmake +++ b/cmake/blob_path.cmake @@ -25,20 +25,22 @@ if(TARGET_OS MATCHES linux) ) endif() + if (${MTLS} MATCHES true) + client_sdk_compile_definitions( + -DSSL_CERT=\"${BLOB_PATH}/data/apiUser.pem\" + -DSSL_KEY=\"${BLOB_PATH}/data/clientKey.pem\" + ) + endif() + + if (${BUILD_MFG_TOOLKIT} MATCHES true) + client_sdk_compile_definitions( + -DMAC_ADDRESSES=\"${BLOB_PATH}/data/mac_addresses.bin\" + ) + endif() + if (${DA} MATCHES tpm) client_sdk_compile_definitions( -DDEVICE_TPM20_ENABLED - -DTPM_DEVICE_CSR=\"${BLOB_PATH}/data/tpm_device_csr\" - -DTPM_ECDSA_DEVICE_KEY=\"${BLOB_PATH}/data/tpm_ecdsa_priv_pub_blob.key\" - -DTPM_INPUT_DATA_TEMP_FILE=\"${BLOB_PATH}/data/tpm_input_data_temp_file\" - -DTPM_OUTPUT_DATA_TEMP_FILE=\"${BLOB_PATH}/data/tpm_output_data_temp_file\" - -DTPM_HMAC_PUB_KEY=\"${BLOB_PATH}/data/tpm_hmac_pub.key\" - -DTPM_HMAC_PRIV_KEY=\"${BLOB_PATH}/data/tpm_hmac_priv.key\" - -DTPM_HMAC_REPLACEMENT_PUB_KEY=\"${BLOB_PATH}/data/tpm_hmac_replacement_pub.key\" - -DTPM_HMAC_REPLACEMENT_PRIV_KEY=\"${BLOB_PATH}/data/tpm_hmac_replacement_priv.key\" - -DTPM_HMAC_DATA_PUB_KEY=\"${BLOB_PATH}/data/tpm_hmac_data_pub.key\" - -DTPM_HMAC_DATA_PRIV_KEY=\"${BLOB_PATH}/data/tpm_hmac_data_priv.key\" - -DTPM2_TSS_ENGINE_SO_PATH=\"/usr/local/lib/engines-1.1/libtpm2tss.so\" ) endif() @@ -170,9 +172,11 @@ if(TARGET_OS MATCHES linux) # Configure if needed at a later point # configure_file(${BLOB_PATH}/data/Normal.blob NEWLINE_STYLE DOS) -file(WRITE ${BLOB_PATH}/data/platform_iv.bin "") -file(WRITE ${BLOB_PATH}/data/platform_hmac_key.bin "") -file(WRITE ${BLOB_PATH}/data/platform_aes_key.bin "") -file(WRITE ${BLOB_PATH}/data/Normal.blob "") -file(WRITE ${BLOB_PATH}/data/Secure.blob "") -file(WRITE ${BLOB_PATH}/data/raw.blob "") +if (NOT ${DA} MATCHES tpm) + file(WRITE ${BLOB_PATH}/data/platform_iv.bin "") + file(WRITE ${BLOB_PATH}/data/platform_hmac_key.bin "") + file(WRITE ${BLOB_PATH}/data/platform_aes_key.bin "") + file(WRITE ${BLOB_PATH}/data/Normal.blob "") + file(WRITE ${BLOB_PATH}/data/Secure.blob "") + file(WRITE ${BLOB_PATH}/data/raw.blob "") +endif() diff --git a/cmake/cli_input.cmake b/cmake/cli_input.cmake index ccb1c42a..8a021025 100644 --- a/cmake/cli_input.cmake +++ b/cmake/cli_input.cmake @@ -16,6 +16,7 @@ set (TARGET_OS linux) set (HTTPPROXY true) set (PROXY_DISCOVERY false) set (SELF_SIGNED_CERTS true) +set (SNI true) set (OPTIMIZE 1) set (DA_FILE der) set (CRYPTO_HW false) @@ -28,6 +29,12 @@ set (BLOB_PATH .) set (TPM2_TCTI_TYPE tabrmd) set (RESALE true) set (REUSE true) +set (MTLS false) +set (GET_DEV_SERIAL false) +set (LOCK_TPM true) + +#Mfg toolkit specific +set (BUILD_MFG_TOOLKIT false) #for CSE set (CSE_SHUTDOWN true) @@ -244,6 +251,34 @@ endif() set(CACHED_SELF_SIGNED_CERTS ${SELF_SIGNED_CERTS} CACHE STRING "Selected SELF_SIGNED_CERTS") message("Selected SELF_SIGNED_CERTS ${SELF_SIGNED_CERTS}") +########################################### +# FOR SNI +get_property(cached_server_name_indication_value CACHE SNI PROPERTY VALUE) + +set(server_name_indication_cli_arg ${cached_server_name_indication_value}) +if(server_name_indication_cli_arg STREQUAL CACHED_SNI) + unset(server_name_indication_cli_arg) +endif() + +set(server_name_indication_app_cmake_lists ${SNI}) +if(cached_server_name_indication_value STREQUAL SNI) + unset(server_name_indication_app_cmake_lists) +endif() + +if(DEFINED CACHED_SNI) + if ((DEFINED server_name_indication_cli_arg) AND (NOT(CACHED_SNI STREQUAL server_name_indication_cli_arg))) + message(WARNING "Need to do make pristine before cmake args can change.") + endif() + set(SNI ${CACHED_SNI}) +elseif(DEFINED server_name_indication_cli_arg) + set(SNI ${server_name_indication_cli_arg}) +elseif(DEFINED server_name_indication_app_cmake_lists) + set(SNI ${server_name_indication_app_cmake_lists}) +endif() + +set(CACHED_SNI ${SNI} CACHE STRING "Selected SNI") +message("Selected SNI ${SNI}") + ########################################### # FOR DA_FILE get_property(cached_da_file_value CACHE DA_FILE PROPERTY VALUE) @@ -798,3 +833,111 @@ if (${DA} MATCHES cse) message("Selected CSE_CLEAR ${CSE_CLEAR}") endif() ########################################### +# FOR MTLS +get_property(cached_mtls_value CACHE MTLS PROPERTY VALUE) + +set(mtls_cli_arg ${cached_mtls_value}) +if(mtls_cli_arg STREQUAL CACHED_MTLS) + unset(mtls_cli_arg) +endif() + +set(mtls_app_cmake_lists ${MTLS}) +if(cached_mtls_value STREQUAL MTLS) + unset(mtls_app_cmake_lists) +endif() + +if(DEFINED CACHED_MTLS) + if ((DEFINED mtls_cli_arg) AND (NOT(CACHED_MTLS STREQUAL mtls_cli_arg))) + message(WARNING "Need to do make pristine before cmake args can change.") + endif() + set(MTLS ${CACHED_MTLS}) +elseif(DEFINED mtls_cli_arg) + set(MTLS ${mtls_cli_arg}) +elseif(DEFINED mtls_app_cmake_lists) + set(MTLS ${mtls_app_cmake_lists}) +endif() + +set(CACHED_MTLS ${MTLS} CACHE STRING "Selected MTLS") +message("Selected MTLS ${MTLS}") +########################################### +# FOR GET_DEV_SERIAL +get_property(cached_get_dev_serial_value CACHE GET_DEV_SERIAL PROPERTY VALUE) + +set(get_dev_serial_cli_arg ${cached_get_dev_serial_value}) +if(get_dev_serial_cli_arg STREQUAL CACHED_GET_DEV_SERIAL) + unset(get_dev_serial_cli_arg) +endif() + +set(get_dev_serial_app_cmake_lists ${GET_DEV_SERIAL}) +if(cached_get_dev_serial_value STREQUAL GET_DEV_SERIAL) + unset(get_dev_serial_app_cmake_lists) +endif() + +if(DEFINED CACHED_GET_DEV_SERIAL) + if ((DEFINED get_dev_serial_cli_arg) AND (NOT(CACHED_GET_DEV_SERIAL STREQUAL get_dev_serial_cli_arg))) + message(WARNING "Need to do make pristine before cmake args can change.") + endif() + set(GET_DEV_SERIAL ${CACHED_GET_DEV_SERIAL}) +elseif(DEFINED get_dev_serial_cli_arg) + set(GET_DEV_SERIAL ${get_dev_serial_cli_arg}) +elseif(DEFINED get_dev_serial_app_cmake_lists) + set(GET_DEV_SERIAL ${get_dev_serial_app_cmake_lists}) +endif() + +set(CACHED_GET_DEV_SERIAL ${GET_DEV_SERIAL} CACHE STRING "Selected GET_DEV_SERIAL") +message("Selected GET_DEV_SERIAL ${GET_DEV_SERIAL}") +########################################### +# FOR LOCK TPM +if (${DA} MATCHES tpm) + get_property(cached_lock_tpm_value CACHE LOCK_TPM PROPERTY VALUE) + + set(lock_tpm_cli_arg ${cached_lock_tpm_value}) + if(lock_tpm_cli_arg STREQUAL CACHED_LOCK_TPM) + unset(lock_tpm_cli_arg) + endif() + + set(lock_tpm_app_cmake_lists ${LOCK_TPM}) + if(cached_lock_tpm_value STREQUAL LOCK_TPM) + unset(lock_tpm_app_cmake_lists) + endif() + + if(DEFINED CACHED_LOCK_TPM) + if ((DEFINED lock_tpm_cli_arg) AND (NOT(CACHED_LOCK_TPM STREQUAL lock_tpm_cli_arg))) + message(WARNING "Need to do make pristine before cmake args can change.") + endif() + set(LOCK_TPM ${CACHED_LOCK_TPM}) + elseif(DEFINED lock_tpm_cli_arg) + set(LOCK_TPM ${lock_tpm_cli_arg}) + elseif(DEFINED lock_tpm_app_cmake_lists) + set(LOCK_TPM ${lock_tpm_app_cmake_lists}) + endif() + + set(CACHED_LOCK_TPM ${LOCK_TPM} CACHE STRING "Selected LOCK_TPM") + message("Selected LOCK_TPM ${LOCK_TPM}") +endif() +########################################### +# FOR BUILD MFG TOOLKIT +get_property(cached_build_mfg_toolkit_value CACHE BUILD_MFG_TOOLKIT PROPERTY VALUE) +set(build_mfg_toolkit_cli_arg ${cached_build_mfg_toolkit_value}) +if(build_mfg_toolkit_cli_arg STREQUAL CACHED_BUILD_MFG_TOOLKIT) + unset(build_mfg_toolkit_cli_arg) +endif() + +set(build_mfg_toolkit_app_cmake_lists ${BUILD_MFG_TOOLKIT}) +if(cached_build_mfg_toolkit_value STREQUAL BUILD_MFG_TOOLKIT) + unset(build_mfg_toolkit_app_cmake_lists) +endif() + +if(DEFINED CACHED_BUILD_MFG_TOOLKIT) + if ((DEFINED build_mfg_toolkit_cli_arg) AND (NOT(CACHED_BUILD_MFG_TOOLKIT STREQUAL build_mfg_toolkit_cli_arg))) + message(WARNING "Need to do make pristine before cmake args can change.") + endif() + set(BUILD_MFG_TOOLKIT ${CACHED_BUILD_MFG_TOOLKIT}) +elseif(DEFINED build_mfg_toolkit_cli_arg) + set(BUILD_MFG_TOOLKIT ${build_mfg_toolkit_cli_arg}) +elseif(DEFINED build_mfg_toolkit_app_cmake_lists) + set(BUILD_MFG_TOOLKIT ${build_mfg_toolkit_app_cmake_lists}) +endif() + +set(CACHED_BUILD_MFG_TOOLKIT ${BUILD_MFG_TOOLKIT} CACHE STRING "Selected BUILD_MFG_TOOLKIT") +message("Selected BUILD_MFG_TOOLKIT ${BUILD_MFG_TOOLKIT}") diff --git a/cmake/extension.cmake b/cmake/extension.cmake index dd695e98..42e6cf62 100644 --- a/cmake/extension.cmake +++ b/cmake/extension.cmake @@ -160,8 +160,20 @@ elseif(DA STREQUAL tpm20_ecdsa256) set (TPM2_TCTI_TYPE tabrmd) client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"tabrmd\") endif() +elseif(DA STREQUAL tpm20_ecdsa384) + client_sdk_compile_definitions(-DECDSA384_DA) + if(${TPM2_TCTI_TYPE} MATCHES tpmrm0) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"device:/dev/tpmrm0\") + elseif(${TPM2_TCTI_TYPE} MATCHES tabrmd) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"tabrmd\") + else() + message(WARNING "Incorrect TPM2_TCTI_TYPE selected. Supported values are 'tabrmd' and 'tpmrm0'. \ + Defaulting to 'tabrmd'") + set (TPM2_TCTI_TYPE tabrmd) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"tabrmd\") + endif() else() - message(WARNING "Incorrect DA selected. Supported values are 'ecdsa256', 'ecdsa384', 'cse_ecdsa384' and 'tpm20_ecdsa256'. \ + message(WARNING "Incorrect DA selected. Supported values are 'ecdsa256', 'ecdsa384', 'cse_ecdsa384', 'tpm20_ecdsa256' and 'tpm20_ecdsa384'. \ Defaulting to 'ecdsa384'") set (DA ecdsa384) client_sdk_compile_definitions(-DECDSA384_DA) @@ -240,6 +252,10 @@ if(${SELF_SIGNED_CERTS} STREQUAL true) client_sdk_compile_definitions(-DSELF_SIGNED_CERTS_SUPPORTED) endif() +if(${SNI} STREQUAL true) + client_sdk_compile_definitions(-DSNI_SUPPORTED) +endif() + if(${RESALE} STREQUAL true) client_sdk_compile_definitions(-DRESALE_SUPPORTED) endif() @@ -255,4 +271,20 @@ endif() if(${CSE_CLEAR} STREQUAL true) client_sdk_compile_definitions(-DCSE_CLEAR) endif() + +if(${MTLS} STREQUAL true) + client_sdk_compile_definitions(-DMTLS) +endif() + +if(${GET_DEV_SERIAL} STREQUAL true) + client_sdk_compile_definitions(-DGET_DEV_SERIAL) +endif() + +if(${LOCK_TPM} STREQUAL true) + client_sdk_compile_definitions(-DLOCK_TPM) +endif() + +if(${BUILD_MFG_TOOLKIT} STREQUAL true) + client_sdk_compile_definitions(-DBUILD_MFG_TOOLKIT) +endif() ############################################################ diff --git a/crypto/CMakeLists.txt b/crypto/CMakeLists.txt index 71c32b1c..f47024be 100644 --- a/crypto/CMakeLists.txt +++ b/crypto/CMakeLists.txt @@ -17,13 +17,13 @@ add_library(crypto "") client_sdk_sources_with_lib( crypto - common/fdoOvVerify.c - common/fdoKeyExchange.c - common/fdoAes.c - common/fdoHmac.c - common/fdoDevSign.c - common/fdoCryptoCommon.c - common/fdoDevAttest.c + common/fdo_ov_verify.c + common/fdo_key_exchange.c + common/fdo_aes.c + common/fdo_hmac.c + common/fdo_dev_sign.c + common/fdo_crypto_common.c + common/fdo_dev_attest.c ) @@ -31,27 +31,27 @@ client_sdk_sources_with_lib( #openssl build if (${TLS} STREQUAL openssl) client_sdk_sources_with_lib( crypto - openssl/openssl_AESRoutines.c - openssl/openssl_cryptoSupport.c - openssl/openssl_SSLRoutines.c + openssl/openssl_AES_routines.c + openssl/openssl_crypto_support.c + openssl/openssl_SSL_routines.c openssl/BN_support.c openssl/openssl_key_exchange_ecdh.c) ### Signature verifications types if (${CRYPTO_HW} STREQUAL false) - client_sdk_sources_with_lib( crypto openssl/openssl_ECDSAVerifyRoutines.c) + client_sdk_sources_with_lib( crypto openssl/openssl_ECDSA_verify_routines.c) endif() if (${DA} STREQUAL cse_ecdsa384) client_sdk_sources_with_lib ( crypto - openssl/cse_cryptoSupport.c + openssl/cse_crypto_support.c ) endif() if (${DA} MATCHES tpm) client_sdk_sources_with_lib ( crypto - openssl/tpm20_ECDSASignRoutines.c + openssl/tpm20_ECDSA_sign_routines.c openssl/tpm20_Utils.c openssl/openssl_csr.c openssl/ec_key.c @@ -60,7 +60,7 @@ if (${TLS} STREQUAL openssl) elseif (${DA} MATCHES ecdsa) if (${CRYPTO_HW} MATCHES false) client_sdk_sources_with_lib ( crypto - openssl/openssl_ECDSASignRoutines.c + openssl/openssl_ECDSA_sign_routines.c openssl/openssl_csr.c openssl/ec_key.c ecdsa/ecdsa_privkey.c) @@ -68,7 +68,7 @@ if (${TLS} STREQUAL openssl) endif() if (${CRYPTO_HW} MATCHES true) - client_sdk_sources_with_lib( crypto openssl/openssl_DERRoutines.c) + client_sdk_sources_with_lib( crypto openssl/openssl_DER_routines.c) endif() endif() @@ -115,13 +115,13 @@ endif() if (${CRYPTO_HW} MATCHES true) client_sdk_sources_with_lib( crypto - se/se_AESGCMRoutines.c - se/se_cryptoSupport.c + se/se_AES_GCM_routines.c + se/se_crypto_support.c se/se_csr.c - se/se_ECDSAVerifyRoutines.c) + se/se_ECDSA_verify_routines.c) if (${DA} STREQUAL ecdsa256 ) - client_sdk_sources_with_lib( crypto se/se_ECDSASignRoutines.c) + client_sdk_sources_with_lib( crypto se/se_ECDSA_sign_routines.c) endif() endif() diff --git a/crypto/common/fdoAes.c b/crypto/common/fdo_aes.c similarity index 91% rename from crypto/common/fdoAes.c rename to crypto/common/fdo_aes.c index 36e8c663..c5b4698a 100644 --- a/crypto/common/fdoAes.c +++ b/crypto/common/fdo_aes.c @@ -3,11 +3,11 @@ * SPDX-License-Identifier: Apache 2.0 */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "safe_lib.h" -#include "fdoCryptoCtx.h" -#include "fdoCrypto.h" +#include "fdo_crypto_ctx.h" +#include "fdo_crypto.h" #include "network_al.h" /** @@ -26,7 +26,8 @@ int32_t fdo_msg_encrypt_get_cipher_len(uint32_t clear_length, return -1; } - // for both AES GCM/CCM modes, same cipher data length is the same as plain data length + // for both AES GCM/CCM modes, same cipher data length is the same as + // plain data length *cipher_length = clear_length; return 0; } @@ -35,7 +36,7 @@ static int32_t getIV(uint8_t *iv, uint32_t clear_text_length) { // unused (void)clear_text_length; - //Generate IV for encryption + // Generate IV for encryption return fdo_crypto_random_bytes(iv, AES_IV_LEN); } @@ -65,15 +66,15 @@ static int32_t getIV(uint8_t *iv, uint32_t clear_text_length) * allocated before calling this API * @param tag_length In/Out In: Size of the tag * Out: Size of the authentication tag stored in tag - * @param aad In Pointer to the buffer containing the Additonal Authenticated Data (AAD) - * used during encryption + * @param aad In Pointer to the buffer containing the Additonal Authenticated + * Data (AAD) used during encryption * @param aad_length In Size of the aad * @return 0 on success and -1 on failures. */ int32_t fdo_msg_encrypt(const uint8_t *clear_text, uint32_t clear_text_length, uint8_t *cipher, uint32_t *cipher_length, uint8_t *iv, - uint8_t *tag, size_t tag_length, - const uint8_t *aad, size_t aad_length) + uint8_t *tag, size_t tag_length, const uint8_t *aad, + size_t aad_length) { fdo_aes_keyset_t *keyset = get_keyset(); uint8_t *sek; @@ -97,7 +98,8 @@ int32_t fdo_msg_encrypt(const uint8_t *clear_text, uint32_t clear_text_length, if (0 != crypto_hal_aes_encrypt(clear_text, clear_text_length, cipher, cipher_length, FDO_AES_BLOCK_SIZE, iv, - sek, sek_len, tag, tag_length, aad, aad_length)) { + sek, sek_len, tag, tag_length, aad, + aad_length)) { goto error; } return 0; @@ -148,14 +150,14 @@ int32_t fdo_msg_decrypt_get_pt_len(uint32_t cipher_length, * used for decryption. * @param tag_length In/Out In: Size of the tag * Out: Size of the authentication tag stored in tag - * @param aad In Pointer to the buffer containing the Additonal Authenticated Data (AAD) - * used during encryption + * @param aad In Pointer to the buffer containing the Additonal Authenticated + * Data (AAD) used during encryption * @param aad_length In Size of the aad * @return 0 on success and -1 on failures. */ int32_t fdo_msg_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, - const uint8_t *cipher, uint32_t cipher_length, uint8_t *iv, - uint8_t *tag, size_t tag_length, + const uint8_t *cipher, uint32_t cipher_length, + uint8_t *iv, uint8_t *tag, size_t tag_length, const uint8_t *aad, size_t aad_length) { fdo_aes_keyset_t *keyset = get_keyset(); @@ -174,7 +176,8 @@ int32_t fdo_msg_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, if (0 != crypto_hal_aes_decrypt(clear_text, clear_text_length, cipher, cipher_length, FDO_AES_BLOCK_SIZE, iv, - sek, sek_len, tag, tag_length, aad, aad_length)) { + sek, sek_len, tag, tag_length, aad, + aad_length)) { LOG(LOG_ERROR, "decrypt failed\n"); goto error; } diff --git a/crypto/common/fdoCryptoCommon.c b/crypto/common/fdo_crypto_common.c similarity index 82% rename from crypto/common/fdoCryptoCommon.c rename to crypto/common/fdo_crypto_common.c index 18075da3..9f357db8 100644 --- a/crypto/common/fdoCryptoCommon.c +++ b/crypto/common/fdo_crypto_common.c @@ -3,13 +3,13 @@ * SPDX-License-Identifier: Apache 2.0 */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "safe_lib.h" #include "snprintf_s.h" #include "stdlib.h" -#include "fdoCryptoCtx.h" -#include "fdoCrypto.h" +#include "fdo_crypto_ctx.h" +#include "fdo_crypto.h" #if defined(DEVICE_TPM20_ENABLED) #include "tpm20_Utils.h" #endif @@ -49,25 +49,25 @@ fdo_aes_keyset_t *get_keyset(void) * This function returns the address of Ownership voucher hmac key. * @return Byte array which holds the OV hmac key */ -fdo_byte_array_t **getOVKey(void) +fdo_byte_array_t **get_OV_key(void) { - return &crypto_ctx.OVKey; + return &crypto_ctx.OV_key; } /** * This function returns the address of Ownership voucher replacement hmac key. * @return Byte array which holds the OV replacement hmac key */ -fdo_byte_array_t **getreplacementOVKey(void) +fdo_byte_array_t **get_replacement_OV_key(void) { - return &crypto_ctx.replacement_OVKey; + return &crypto_ctx.replacement_OV_key; } /** * This function returns the address of the dev key struct inside crypto * context. */ -fdo_dev_key_ctx_t *getfdo_dev_key_ctx(void) +fdo_dev_key_ctx_t *get_fdo_dev_key_ctx(void) { return &crypto_ctx.dev_key; } @@ -76,7 +76,7 @@ fdo_dev_key_ctx_t *getfdo_dev_key_ctx(void) * This function returns the address of the kex struct inside crypto * context. */ -fdo_kex_ctx_t *getfdo_key_ctx(void) +fdo_kex_ctx_t *get_fdo_key_ctx(void) { return &crypto_ctx.kex; } @@ -114,10 +114,6 @@ int32_t fdo_crypto_close(void) ret = crypto_close(); /* CLeanup of context structs */ cleanup_ctx(); -#if defined(DEVICE_TPM20_ENABLED) - /* clear the replacement hmac key objects */ - fdo_tpm_clear_replacement_hmac_key(); -#endif return ret; } @@ -131,11 +127,11 @@ static void cleanup_ctx(void) } /* cleanup ovkey */ - fdo_byte_array_free(crypto_ctx.OVKey); - crypto_ctx.OVKey = NULL; - if (crypto_ctx.replacement_OVKey) { - fdo_byte_array_free(crypto_ctx.replacement_OVKey); - crypto_ctx.replacement_OVKey = NULL; + fdo_byte_array_free(crypto_ctx.OV_key); + crypto_ctx.OV_key = NULL; + if (crypto_ctx.replacement_OV_key) { + fdo_byte_array_free(crypto_ctx.replacement_OV_key); + crypto_ctx.replacement_OV_key = NULL; } } diff --git a/crypto/common/fdoDevAttest.c b/crypto/common/fdo_dev_attest.c similarity index 88% rename from crypto/common/fdoDevAttest.c rename to crypto/common/fdo_dev_attest.c index 45490b0d..df1c35f9 100644 --- a/crypto/common/fdoDevAttest.c +++ b/crypto/common/fdo_dev_attest.c @@ -11,8 +11,8 @@ #include #include "util.h" #include "safe_lib.h" -#include "fdoCryptoHal.h" -#include "fdoCrypto.h" +#include "fdo_crypto_hal.h" +#include "fdo_crypto.h" /* Do nothing for ECDSA based attestation */ int32_t dev_attestation_init(void) diff --git a/crypto/common/fdoDevSign.c b/crypto/common/fdo_dev_sign.c similarity index 83% rename from crypto/common/fdoDevSign.c rename to crypto/common/fdo_dev_sign.c index ebc1f9b5..519c53c6 100644 --- a/crypto/common/fdoDevSign.c +++ b/crypto/common/fdo_dev_sign.c @@ -3,19 +3,17 @@ * SPDX-License-Identifier: Apache 2.0 */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "safe_lib.h" #include "snprintf_s.h" #include "stdlib.h" -#include "fdoCryptoCtx.h" -#include "fdoCrypto.h" +#include "fdo_crypto_ctx.h" +#include "fdo_crypto.h" #if defined(DEVICE_CSE_ENABLED) #include "cse_utils.h" #endif -#define ECDSA_SIGNATURE_MAX_LEN BUFF_SIZE_256_BYTES - /* This function signs a message passed in message of size message_length. * The generated signature will be available in signature of size * signature_length. This API shall use the default device private key @@ -37,7 +35,8 @@ */ int32_t fdo_device_sign(const uint8_t *message, size_t message_length, - fdo_byte_array_t **signature, fdo_byte_array_t **eat_maroe) + fdo_byte_array_t **signature, + fdo_byte_array_t **eat_maroe) { int ret = -1; @@ -57,8 +56,10 @@ int32_t fdo_device_sign(const uint8_t *message, size_t message_length, goto end; } - if (0 != crypto_hal_ecdsa_sign_cse(message, message_length, (*signature)->bytes, - (*signature)->byte_sz, (*eat_maroe)->bytes, &(*eat_maroe)->byte_sz)) { + if (0 != crypto_hal_ecdsa_sign_cse( + message, message_length, (*signature)->bytes, + (*signature)->byte_sz, (*eat_maroe)->bytes, + &(*eat_maroe)->byte_sz)) { LOG(LOG_ERROR, "ECDSA signing failed!\n"); fdo_byte_array_free(*signature); fdo_byte_array_free(*eat_maroe); @@ -76,8 +77,9 @@ int32_t fdo_device_sign(const uint8_t *message, size_t message_length, goto end; } - if (0 != crypto_hal_ecdsa_sign(message, message_length, (*signature)->bytes, - &(*signature)->byte_sz)) { + if (0 != crypto_hal_ecdsa_sign(message, message_length, + (*signature)->bytes, + &(*signature)->byte_sz)) { LOG(LOG_ERROR, "ECDSA signing failed!\n"); fdo_byte_array_free(*signature); *signature = NULL; diff --git a/crypto/common/fdoHmac.c b/crypto/common/fdo_hmac.c similarity index 84% rename from crypto/common/fdoHmac.c rename to crypto/common/fdo_hmac.c index d9f59104..db82fa1c 100644 --- a/crypto/common/fdoHmac.c +++ b/crypto/common/fdo_hmac.c @@ -3,17 +3,18 @@ * SPDX-License-Identifier: Apache 2.0 */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "safe_lib.h" -#include "fdoCryptoCtx.h" -#include "fdoCrypto.h" +#include "fdo_crypto_ctx.h" +#include "fdo_crypto.h" #include "fdoprot.h" #include "storage_al.h" #include "platform_utils.h" #if defined(DEVICE_TPM20_ENABLED) #include "tpm20_Utils.h" +#include "tpm2_nv_storage.h" #endif #if defined(DEVICE_CSE_ENABLED) @@ -30,7 +31,7 @@ int32_t set_ov_key(fdo_byte_array_t *OVkey, size_t OVKey_len) { int ret = -1; - fdo_byte_array_t **ovkeyctx = getOVKey(); + fdo_byte_array_t **ovkeyctx = get_OV_key(); if ((NULL == OVkey) || !(OVkey->bytes) || !((BUFF_SIZE_32_BYTES == OVKey_len) || @@ -65,8 +66,8 @@ int32_t set_ov_key(fdo_byte_array_t *OVkey, size_t OVKey_len) } /** - * This function sets the Ownership Voucher replacement hmac key in the structure. - * Which will later be used to generate the replacement hmac. + * This function sets the Ownership Voucher replacement hmac key in the + * structure. Which will later be used to generate the replacement hmac. * @param OVkey In Pointer to the Ownership Voucher replacement hmac key. * @param OVKey_len In Size of the Ownership Voucher replacement hmac key * @return 0 on success and -1 on failure. @@ -74,7 +75,7 @@ int32_t set_ov_key(fdo_byte_array_t *OVkey, size_t OVKey_len) int32_t set_ov_replacement_key(fdo_byte_array_t *OVkey, size_t OVKey_len) { int ret = -1; - fdo_byte_array_t **ovkeyctx = getreplacementOVKey(); + fdo_byte_array_t **ovkeyctx = get_replacement_OV_key(); if ((NULL == OVkey) || !(OVkey->bytes) || !((BUFF_SIZE_32_BYTES == OVKey_len) || @@ -150,17 +151,17 @@ int32_t fdo_device_ov_hmac(uint8_t *OVHdr, size_t OVHdr_len, uint8_t *hmac, fdo_byte_array_t **keyset = NULL; if (is_replacement_hmac) { #if defined(DEVICE_TPM20_ENABLED) - return fdo_tpm_get_hmac(OVHdr, OVHdr_len, hmac, hmac_len, - TPM_HMAC_REPLACEMENT_PUB_KEY, TPM_HMAC_REPLACEMENT_PRIV_KEY); + return fdo_tpm_get_hmac(OVHdr, OVHdr_len, hmac, hmac_len, + TPM_HMAC_KEY_PERSISTANT_HANDLE); #else - keyset = getreplacementOVKey(); + keyset = get_replacement_OV_key(); #endif } else { #if defined(DEVICE_TPM20_ENABLED) - return fdo_tpm_get_hmac(OVHdr, OVHdr_len, hmac, hmac_len, - TPM_HMAC_PUB_KEY, TPM_HMAC_PRIV_KEY); + return fdo_tpm_get_hmac(OVHdr, OVHdr_len, hmac, hmac_len, + TPM_HMAC_KEY_PERSISTANT_HANDLE); #else - keyset = getOVKey(); + keyset = get_OV_key(); #endif } if (!keyset || !*keyset) { @@ -205,7 +206,7 @@ int32_t fdo_crypto_hash(const uint8_t *message, size_t message_length, } if (0 != crypto_hal_hash(FDO_CRYPTO_HASH_TYPE_USED, message, - message_length, hash, hash_length)) { + message_length, hash, hash_length)) { return -1; } @@ -224,8 +225,7 @@ int32_t fdo_generate_ov_hmac_key(void) int32_t ret = -1; #if defined(DEVICE_TPM20_ENABLED) - if (0 != - fdo_tpm_generate_hmac_key(TPM_HMAC_PUB_KEY, TPM_HMAC_PRIV_KEY)) { + if (0 != fdo_tpm_generate_hmac_key(TPM_HMAC_KEY_PERSISTANT_HANDLE)) { LOG(LOG_ERROR, "Failed to generate device HMAC key" " from TPM.\n"); return ret; @@ -258,7 +258,8 @@ int32_t fdo_generate_ov_hmac_key(void) } /** - * fdo_generate_ov_replacement_hmac_key function generates the new/replacement OV HMAC key + * fdo_generate_ov_replacement_hmac_key function generates the new/replacement + * OV HMAC key * * @return * return 0 on success, -1 on failure. @@ -268,9 +269,7 @@ int32_t fdo_generate_ov_replacement_hmac_key(void) int32_t ret = -1; #if defined(DEVICE_TPM20_ENABLED) - if (0 != - fdo_tpm_generate_hmac_key(TPM_HMAC_REPLACEMENT_PUB_KEY, - TPM_HMAC_REPLACEMENT_PRIV_KEY)) { + if (0 != fdo_tpm_generate_hmac_key(TPM_HMAC_KEY_PERSISTANT_HANDLE)) { LOG(LOG_ERROR, "Failed to generate device replacement HMAC key" " from TPM.\n"); return ret; @@ -288,7 +287,8 @@ int32_t fdo_generate_ov_replacement_hmac_key(void) goto err; } - /* Generate replacement HMAC key for calcuating it over Ownership header */ + /* Generate replacement HMAC key for calcuating it over Ownership header + */ fdo_crypto_random_bytes(secret->bytes, FDO_HMAC_KEY_LENGTH); if (0 != set_ov_replacement_key(secret, FDO_HMAC_KEY_LENGTH)) { goto err; @@ -303,8 +303,8 @@ int32_t fdo_generate_ov_replacement_hmac_key(void) /** * Commit the OV replacment key by replacing the original HMAC key - * with the replacement HMAC key. This operation is final and the original HMAC key - * is lost completely. + * with the replacement HMAC key. This operation is final and the original HMAC + * key is lost completely. * * @return * return 0 on success, -1 on failure. @@ -314,15 +314,9 @@ int32_t fdo_commit_ov_replacement_hmac_key(void) int32_t ret = -1; #if defined(DEVICE_TPM20_ENABLED) - if (0 != fdo_tpm_commit_replacement_hmac_key()) { - LOG(LOG_ERROR, "Failed to commit device replacement HMAC key" - " for TPM.\n"); - return ret; - } - ret = 0; #else - fdo_byte_array_t **secret = getreplacementOVKey(); + fdo_byte_array_t **secret = get_replacement_OV_key(); if (!secret || !(*secret) || !(*secret)->bytes) { LOG(LOG_ERROR, "Failed to read OV replacement HMAC key\n"); @@ -363,17 +357,6 @@ int32_t fdo_compute_storage_hmac(const uint8_t *data, uint32_t data_length, goto error; } -#if defined(DEVICE_TPM20_ENABLED) - if (0 != fdo_tpm_get_hmac(data, data_length, computed_hmac, - computed_hmac_size, TPM_HMAC_DATA_PUB_KEY, - TPM_HMAC_DATA_PRIV_KEY)) { - LOG(LOG_ERROR, "TPM HMAC Computation failed!\n"); - goto error; - } - - LOG(LOG_DEBUG, "TPM HMAC computed successfully!\n"); - -#else uint8_t hmac_key[PLATFORM_HMAC_KEY_DEFAULT_LEN] = {0}; if (!get_platform_hmac_key(hmac_key, PLATFORM_HMAC_KEY_DEFAULT_LEN)) { @@ -401,7 +384,6 @@ int32_t fdo_compute_storage_hmac(const uint8_t *data, uint32_t data_length, #endif return ret; } -#endif /** * fdo_generate_storage_hmac_key function generates Storage HMAC key @@ -416,18 +398,6 @@ int32_t fdo_generate_storage_hmac_key(void) #if defined(TARGET_OS_OPTEE) return 0; - -#elif defined(DEVICE_TPM20_ENABLED) - if (0 != fdo_tpm_generate_hmac_key(TPM_HMAC_DATA_PUB_KEY, - TPM_HMAC_DATA_PRIV_KEY)) { - LOG(LOG_ERROR, "Failed to generate TPM data protection " - "key.\n"); - return ret; - } - - ret = 0; - LOG(LOG_DEBUG, "TPM data protection key generated successfully.\n"); - #else uint8_t hmac_key[PLATFORM_HMAC_KEY_DEFAULT_LEN] = {0}; diff --git a/crypto/common/fdoKeyExchange.c b/crypto/common/fdo_key_exchange.c similarity index 82% rename from crypto/common/fdoKeyExchange.c rename to crypto/common/fdo_key_exchange.c index d0b989fc..07dd1755 100644 --- a/crypto/common/fdoKeyExchange.c +++ b/crypto/common/fdo_key_exchange.c @@ -5,13 +5,13 @@ #include #include "fdokeyexchange.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "safe_lib.h" #include "snprintf_s.h" #include "stdlib.h" -#include "fdoCryptoCtx.h" -#include "fdoCrypto.h" +#include "fdo_crypto_ctx.h" +#include "fdo_crypto.h" /* Static functions */ static int32_t remove_java_compatible_byte_array(fdo_byte_array_t *BArray); @@ -27,7 +27,7 @@ static int32_t remove_java_compatible_byte_array(fdo_byte_array_t *BArray); int32_t fdo_kex_init(void) { int32_t ret = -1; - fdo_kex_ctx_t *kex_ctx = getfdo_key_ctx(); + fdo_kex_ctx_t *kex_ctx = get_fdo_key_ctx(); fdo_to2Sym_enc_ctx_t *to2sym_ctx = get_fdo_to2_ctx(); size_t cs = COSE_ENC_TYPE; @@ -83,7 +83,7 @@ int32_t fdo_kex_init(void) */ int32_t fdo_kex_close(void) { - struct fdo_kex_ctx *kex_ctx = getfdo_key_ctx(); + struct fdo_kex_ctx *kex_ctx = get_fdo_key_ctx(); fdo_to2Sym_enc_ctx_t *to2sym_ctx = get_fdo_to2_ctx(); /* Free "KEX" string (Key Exchange) */ if (kex_ctx->kx) { @@ -133,7 +133,7 @@ int32_t fdo_kex_close(void) static int32_t set_encrypt_key(fdo_public_key_t *encrypt_key) { #ifdef KEX_ASYM_ENABLED - struct fdo_kex_ctx *kex_ctx = getfdo_key_ctx(); + struct fdo_kex_ctx *kex_ctx = get_fdo_key_ctx(); return set_encrypt_key_asym(kex_ctx->context, encrypt_key); #endif @@ -152,7 +152,7 @@ static int32_t set_encrypt_key(fdo_public_key_t *encrypt_key) int32_t fdo_get_kex_paramB(fdo_byte_array_t **xB) { int32_t ret = -1; - fdo_kex_ctx_t *kex_ctx = getfdo_key_ctx(); + fdo_kex_ctx_t *kex_ctx = get_fdo_key_ctx(); uint32_t bufsize = 0; fdo_byte_array_t *tmp_xB = NULL; @@ -198,7 +198,8 @@ static int32_t remove_java_compatible_byte_array(fdo_byte_array_t *BArray) if (BArray && BArray->bytes) { if (BArray->bytes[0] == 0x00) { if (!memmove_s(BArray->bytes, BArray->byte_sz - 1, - &BArray->bytes[1], BArray->byte_sz - 1)) { + &BArray->bytes[1], + BArray->byte_sz - 1)) { BArray->byte_sz--; } else { return -1; @@ -211,21 +212,22 @@ static int32_t remove_java_compatible_byte_array(fdo_byte_array_t *BArray) } /** - * Write the input to the KDF i.e KDFInput, of size kdf_input_len into kdf_input buffer. - * Refer to Section 3.6.4 in FIDO Device Onboard (FDO) specification. + * Write the input to the KDF i.e KDFInput, of size kdf_input_len into kdf_input + * buffer. Refer to Section 3.6.4 in FIDO Device Onboard (FDO) specification. * * KDFInput = (byte)i||"FIDO-KDF"||(byte)0||Context||Lstr, * where Context = "AutomaticOnboardTunnel"||ContextRand, and, * ContextRand = null for ECDH Key Exchange (Section 3.6.3) * * index is the counter (i), and cannot be more than 2. - * keymat_bit_length is the total number of key-bits to generate, and is used to calculate Lstr. + * keymat_bit_length is the total number of key-bits to generate, and is used to + * calculate Lstr. */ -static int32_t prep_kdf_input(uint8_t *kdf_input, size_t kdf_input_len, const int index, - const int keymat_bit_length) +static int32_t prep_kdf_input(uint8_t *kdf_input, size_t kdf_input_len, + const int index, const int keymat_bit_length) { int ret = -1; - struct fdo_kex_ctx *kex_ctx = getfdo_key_ctx(); + struct fdo_kex_ctx *kex_ctx = get_fdo_key_ctx(); size_t ofs = 0; uint8_t idx0_val; size_t kdf_label_len = 0; @@ -242,8 +244,7 @@ static int32_t prep_kdf_input(uint8_t *kdf_input, size_t kdf_input_len, const in goto err; } - context_label_len = strnlen_s(kex_ctx->context_label, - FDO_MAX_STR_SIZE); + context_label_len = strnlen_s(kex_ctx->context_label, FDO_MAX_STR_SIZE); if (!context_label_len || context_label_len == FDO_MAX_STR_SIZE) { LOG(LOG_ERROR, "Context Label is not NULL terminated.\n"); goto err; @@ -262,7 +263,7 @@ static int32_t prep_kdf_input(uint8_t *kdf_input, size_t kdf_input_len, const in kdf_input[ofs++] = idx0_val; // Fill in the kdflabel if (strncpy_s((char *)&kdf_input[ofs], kdf_input_len - ofs, - kex_ctx->kdf_label, kdf_label_len)) { + kex_ctx->kdf_label, kdf_label_len)) { LOG(LOG_ERROR, "Failed to fill kdf label in key Material\n"); goto err; } @@ -271,7 +272,7 @@ static int32_t prep_kdf_input(uint8_t *kdf_input, size_t kdf_input_len, const in kdf_input[ofs++] = 0x00; // Fill in the context if (strncpy_s((char *)&kdf_input[ofs], kdf_input_len - ofs, - kex_ctx->context_label, context_label_len)) { + kex_ctx->context_label, context_label_len)) { LOG(LOG_ERROR, "Failed to fill svk label\n"); goto err; } @@ -291,8 +292,8 @@ static fdo_byte_array_t *get_secret(void) fdo_byte_array_t *b = NULL; uint8_t *shared_secret_buffer = NULL; uint32_t secret_size = 0; - struct fdo_kex_ctx *kex_ctx = getfdo_key_ctx(); - fdo_kex_ctx_t *key_ex_data = (fdo_kex_ctx_t *)(getfdo_key_ctx()); + struct fdo_kex_ctx *kex_ctx = get_fdo_key_ctx(); + fdo_kex_ctx_t *key_ex_data = (fdo_kex_ctx_t *)(get_fdo_key_ctx()); if (crypto_hal_get_secret(key_ex_data->context, NULL, &secret_size) != 0) { @@ -350,7 +351,7 @@ static fdo_byte_array_t *get_secret(void) static int32_t kex_kdf(void) { int ret = -1; - struct fdo_kex_ctx *kex_ctx = getfdo_key_ctx(); + struct fdo_kex_ctx *kex_ctx = get_fdo_key_ctx(); fdo_byte_array_t *shse = get_secret(); fdo_aes_keyset_t *keyset = get_keyset(); // input data to the KDF @@ -358,7 +359,8 @@ static int32_t kex_kdf(void) size_t kdf_input_len = 0; // length of 1 byte in bits int byte_size = 8; - // Length of Output Keying Material, in bytes = SEK size for AES-GCM and AES-CCM modes + // Length of Output Keying Material, in bytes = SEK size for AES-GCM and + // AES-CCM modes size_t keymat_bytes_sz = SEK_KEY_SIZE; // Output Keying Material uint8_t keymat[keymat_bytes_sz]; @@ -384,8 +386,7 @@ static int32_t kex_kdf(void) goto err; } - context_label_len = strnlen_s(kex_ctx->context_label, - FDO_MAX_STR_SIZE); + context_label_len = strnlen_s(kex_ctx->context_label, FDO_MAX_STR_SIZE); if (!context_label_len || context_label_len == FDO_MAX_STR_SIZE) { LOG(LOG_ERROR, "Context Label is not NULL terminated.\n"); goto err; @@ -396,17 +397,19 @@ static int32_t kex_kdf(void) goto err; } - // total number of rounds (n) to iterate for generating the total number of key bits - // n = ceil (L/h), where, - // L = Keying Material length in bits, and - // h = PRF output length in bits - n = ceil((double)(keymat_bytes_sz * byte_size) / (hmac_sha256_sz * byte_size)); + // total number of rounds (n) to iterate for generating the total number + // of key bits n = ceil (L/h), where, L = Keying Material length in + // bits, and h = PRF output length in bits + n = ceil((double)(keymat_bytes_sz * byte_size) / + (hmac_sha256_sz * byte_size)); - // Input to the KDF, KDFInput = (byte)i||"FIDO-KDF"||(byte)0||Context||Lstr, where - // Context = "AutomaticOnboardTunnel"||ContextRand, ContextRand is NULL for ECDH key-exchange, - // Lstr = (byte)L1||(byte)L2, i.e, 16-bit number, depending on L=key-bits to generate - // Therefore, KDFInput size = 1 for byte (i) + length of Label + 1 for byte (0) + - // length of Context + 2 bytes for Lstr + // Input to the KDF, KDFInput = + // (byte)i||"FIDO-KDF"||(byte)0||Context||Lstr, where Context = + // "AutomaticOnboardTunnel"||ContextRand, ContextRand is NULL for ECDH + // key-exchange, Lstr = (byte)L1||(byte)L2, i.e, 16-bit number, + // depending on L=key-bits to generate Therefore, KDFInput size = 1 for + // byte (i) + length of Label + 1 for byte (0) + length of Context + 2 + // bytes for Lstr kdf_input_len = 1 + kdf_label_len + 1 + context_label_len + 2; // Allocate memory for KDFInput kdf_input = fdo_alloc(kdf_input_len); @@ -422,8 +425,8 @@ static int32_t kex_kdf(void) goto err; } - // iterate for the calculated number of iterations (n) to generate key bits - // once the iterations are done, keymat contains the generated key + // iterate for the calculated number of iterations (n) to generate key + // bits once the iterations are done, keymat contains the generated key for (i = 1; i <= n; i++) { // clear for new round usage @@ -431,8 +434,10 @@ static int32_t kex_kdf(void) LOG(LOG_ERROR, "Failed to clear kdf_input\n"); goto err; } - // prepare KDFInput by passing the number of rounds (i) and length of key bits (L) - ret = prep_kdf_input(kdf_input, kdf_input_len, i, keymat_bytes_sz * byte_size); + // prepare KDFInput by passing the number of rounds (i) and + // length of key bits (L) + ret = prep_kdf_input(kdf_input, kdf_input_len, i, + keymat_bytes_sz * byte_size); if (ret) { LOG(LOG_ERROR, "Failed to prepare kdf_input\n"); goto err; @@ -444,23 +449,24 @@ static int32_t kex_kdf(void) goto err; } // generate hmac that gives us the key (or a part of it) - if (crypto_hal_hmac(FDO_CRYPTO_HMAC_TYPE_SHA_256, kdf_input, kdf_input_len, - hmac, hmac_sha256_sz, shse->bytes, - shse->byte_sz)) { + if (crypto_hal_hmac(FDO_CRYPTO_HMAC_TYPE_SHA_256, kdf_input, + kdf_input_len, hmac, hmac_sha256_sz, + shse->bytes, shse->byte_sz)) { LOG(LOG_ERROR, "Failed to derive key via HMAC\n"); goto err; } if (keymat_bytes_index + hmac_sha256_sz <= keymat_bytes_sz) { keymat_bytes_to_copy = hmac_sha256_sz; - } - else { - keymat_bytes_to_copy = keymat_bytes_sz - keymat_bytes_index; + } else { + keymat_bytes_to_copy = + keymat_bytes_sz - keymat_bytes_index; } - // copy the generated hmac (key/a part of the key) into generated key buffer + // copy the generated hmac (key/a part of the key) into + // generated key buffer if (memcpy_s(&keymat[keymat_bytes_index], keymat_bytes_sz, hmac, - keymat_bytes_to_copy)) { + keymat_bytes_to_copy)) { LOG(LOG_ERROR, "Failed to copy generated key bytes\n"); goto err; } @@ -474,7 +480,7 @@ static int32_t kex_kdf(void) // Get the sevk if (memcpy_s(keyset->sek->bytes, keyset->sek->byte_sz, &keymat[0], - keyset->sek->byte_sz)) { + keyset->sek->byte_sz)) { LOG(LOG_ERROR, "Failed to copy sek key\n"); goto err; } @@ -505,7 +511,7 @@ int32_t fdo_set_kex_paramA(fdo_byte_array_t *xA, fdo_public_key_t *encrypt_key) { int32_t ret = true; - fdo_kex_ctx_t *key_ex_data = (fdo_kex_ctx_t *)(getfdo_key_ctx()); + fdo_kex_ctx_t *key_ex_data = (fdo_kex_ctx_t *)(get_fdo_key_ctx()); if (!xA) { return -1; diff --git a/crypto/common/fdoOvVerify.c b/crypto/common/fdo_ov_verify.c similarity index 96% rename from crypto/common/fdoOvVerify.c rename to crypto/common/fdo_ov_verify.c index bdbdd52d..efc3b504 100644 --- a/crypto/common/fdoOvVerify.c +++ b/crypto/common/fdo_ov_verify.c @@ -9,8 +9,8 @@ */ #include "fdotypes.h" -#include "fdoCryptoHal.h" -#include "fdoCrypto.h" +#include "fdo_crypto_hal.h" +#include "fdo_crypto.h" /** * This function verifies if the signature message_signature of length diff --git a/crypto/include/ec_key.h b/crypto/include/ec_key.h index a53352e5..3fc8ca83 100644 --- a/crypto/include/ec_key.h +++ b/crypto/include/ec_key.h @@ -7,5 +7,5 @@ #include -EC_KEY *get_ec_key(void); +EVP_PKEY *get_evp_key(void); #endif diff --git a/crypto/include/fdoCrypto.h b/crypto/include/fdo_crypto.h similarity index 83% rename from crypto/include/fdoCrypto.h rename to crypto/include/fdo_crypto.h index 6ddb050c..39dde2d6 100644 --- a/crypto/include/fdoCrypto.h +++ b/crypto/include/fdo_crypto.h @@ -11,8 +11,8 @@ #include #include "safe_lib.h" #include "snprintf_s.h" -#include "fdoCryptoCtx.h" -#include "fdoCryptoCommons.h" +#include "fdo_crypto_ctx.h" +#include "fdo_crypto_commons.h" /* Function declarations */ int32_t fdo_crypto_init(void); @@ -25,8 +25,8 @@ int32_t fdo_kex_close(void); fdo_string_t *fdo_get_device_kex_method(void); size_t fdo_get_device_crypto_suite(void); -fdo_byte_array_t **getOVKey(void); -fdo_byte_array_t **getreplacementOVKey(void); +fdo_byte_array_t **get_OV_key(void); +fdo_byte_array_t **get_replacement_OV_key(void); int32_t set_ov_key(fdo_byte_array_t *OVkey, size_t OVKey_len); int32_t set_ov_replacement_key(fdo_byte_array_t *OVkey, size_t OVKey_len); int32_t fdo_commit_ov_replacement_hmac_key(void); @@ -38,13 +38,13 @@ int32_t fdo_msg_encrypt_get_cipher_len(uint32_t clear_length, uint32_t *cipher_length); int32_t fdo_msg_encrypt(const uint8_t *clear_text, uint32_t clear_text_length, uint8_t *cipher, uint32_t *cipher_length, uint8_t *iv, - uint8_t *tag, size_t tag_length, - const uint8_t *aad, size_t aad_length); + uint8_t *tag, size_t tag_length, const uint8_t *aad, + size_t aad_length); int32_t fdo_msg_decrypt_get_pt_len(uint32_t cipher_length, uint32_t *clear_text_length); int32_t fdo_msg_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, - const uint8_t *cipher, uint32_t cipher_length, uint8_t *iv, - uint8_t *tag, size_t tag_length, + const uint8_t *cipher, uint32_t cipher_length, + uint8_t *iv, uint8_t *tag, size_t tag_length, const uint8_t *aad, size_t aad_length); int32_t fdo_device_ov_hmac(uint8_t *OVHdr, size_t OVHdr_len, uint8_t *hmac, size_t hmac_len, bool is_replacement_hmac); @@ -56,10 +56,11 @@ int32_t fdo_to2_chained_hmac(uint8_t *to2Msg, size_t to2Msg_len, uint8_t *hmac, int set_currentIV(uint8_t *iv); int32_t fdo_device_sign(const uint8_t *message, size_t message_length, - fdo_byte_array_t **signature, fdo_byte_array_t **eat_maroe); + fdo_byte_array_t **signature, + fdo_byte_array_t **eat_maroe); -fdo_dev_key_ctx_t *getfdo_dev_key_ctx(void); -fdo_kex_ctx_t *getfdo_key_ctx(void); +fdo_dev_key_ctx_t *get_fdo_dev_key_ctx(void); +fdo_kex_ctx_t *get_fdo_key_ctx(void); fdo_to2Sym_enc_ctx_t *get_fdo_to2_ctx(void); int32_t dev_attestation_init(void); void dev_attestation_close(void); diff --git a/crypto/include/fdoCryptoCommons.h b/crypto/include/fdo_crypto_commons.h similarity index 98% rename from crypto/include/fdoCryptoCommons.h rename to crypto/include/fdo_crypto_commons.h index b147b8df..2aa92152 100644 --- a/crypto/include/fdoCryptoCommons.h +++ b/crypto/include/fdo_crypto_commons.h @@ -13,7 +13,8 @@ // default Owner attestation #define FDO_OWNER_ATTEST_PK_ENC FDO_CRYPTO_PUB_KEY_ENCODING_X509 -// Device Attestation (DA) is used to decide the size of the key used for the following: +// Device Attestation (DA) is used to decide the size of the key used for the +// following: // 1. Key-Exchange // 2. Encryption/Decryption // 3. Hash/HMAC diff --git a/crypto/include/fdoCryptoCtx.h b/crypto/include/fdo_crypto_ctx.h similarity index 93% rename from crypto/include/fdoCryptoCtx.h rename to crypto/include/fdo_crypto_ctx.h index 0aa9c91f..44ec07e6 100644 --- a/crypto/include/fdoCryptoCtx.h +++ b/crypto/include/fdo_crypto_ctx.h @@ -36,8 +36,8 @@ typedef struct { fdo_dev_key_ctx_t dev_key; fdo_to2Sym_enc_ctx_t to2Sym_enc; fdo_kex_ctx_t kex; - fdo_byte_array_t *OVKey; - fdo_byte_array_t *replacement_OVKey; + fdo_byte_array_t *OV_key; + fdo_byte_array_t *replacement_OV_key; } fdo_crypto_context_t; fdo_aes_keyset_t *get_keyset(void); diff --git a/crypto/include/fdoCryptoHal.h b/crypto/include/fdo_crypto_hal.h similarity index 86% rename from crypto/include/fdoCryptoHal.h rename to crypto/include/fdo_crypto_hal.h index 7f8bc9b2..bc2a1503 100644 --- a/crypto/include/fdoCryptoHal.h +++ b/crypto/include/fdo_crypto_hal.h @@ -11,8 +11,8 @@ extern "C" { #include "fdokeyexchange.h" #include "util.h" -#include "fdoCryptoCommons.h" -#include "fdoCryptoCtx.h" +#include "fdo_crypto_commons.h" +#include "fdo_crypto_ctx.h" #ifdef USE_MBEDTLS #if !defined(TARGET_OS_LINUX) #include "mbedtls/net.h" @@ -36,6 +36,7 @@ extern "C" { #define SHA384_DIGEST_SIZE BUFF_SIZE_48_BYTES #define SHA512_DIGEST_SIZE BUFF_SIZE_64_BYTES #define HMACSHA256_KEY_SIZE BUFF_SIZE_32_BYTES +#define ECDSA_SIGNATURE_MAX_LEN BUFF_SIZE_256_BYTES /* Initialize randomization library. */ int random_init(void); @@ -54,9 +55,9 @@ int32_t crypto_close(void); /* Calculate hash of "buffer" and place the result in "output". "output" must * be allocated already. */ -int32_t crypto_hal_hash(uint8_t hash_type, const uint8_t *buffer, - size_t buffer_length, uint8_t *output, - size_t output_length); +int32_t crypto_hal_hash(int hash_type, const uint8_t *buffer, + size_t buffer_length, uint8_t *output, + size_t output_length); /* Calculate hmac of "buffer" using "key", and place the result in "output". * "output" must be allocated already. @@ -69,9 +70,8 @@ int32_t crypto_hal_hmac(uint8_t hmac_type, const uint8_t *buffer, /* Calculate hmac of "buffer", and place the result in "output". * "output" must be allocated already. */ -int32_t crypto_hal_hmac_cse(uint8_t *buffer,size_t buffer_length, - uint8_t *output, size_t output_length); - +int32_t crypto_hal_hmac_cse(uint8_t *buffer, size_t buffer_length, + uint8_t *output, size_t output_length); /* crypto_hal_sig_verify * Verify an RSA PKCS v1.5 Signature using provided public key @@ -105,12 +105,14 @@ int32_t crypto_hal_sig_verify(uint8_t key_encoding, int key_algorithm, /* Sign and generate ECDSA signature for a given message */ int32_t crypto_hal_ecdsa_sign(const uint8_t *message, size_t message_len, - unsigned char *signature, size_t *signature_len); + unsigned char *signature, size_t *signature_len); -/* Sign and generate ECDSA signature for a given message using CSE internal API*/ +/* Sign and generate ECDSA signature for a given message using CSE internal + * API*/ int32_t crypto_hal_ecdsa_sign_cse(const uint8_t *data, size_t data_len, - uint8_t *message_signature, size_t message_sig_len, uint8_t *eat_maroe, - size_t *maroe_length); + uint8_t *message_signature, + size_t message_sig_len, uint8_t *eat_maroe, + size_t *maroe_length); /* Encrypt "clear_text" using "key" and put the result in "cypher_text". * "cipher_txt" must point to a buffer large enough to store the @@ -121,9 +123,9 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, uint32_t clear_text_length, uint8_t *cypher_text, uint32_t *cypher_length, size_t block_size, const uint8_t *iv, const uint8_t *key, - uint32_t key_length, - uint8_t *tag, size_t tag_length, - const uint8_t *aad, size_t aad_length); + uint32_t key_length, uint8_t *tag, + size_t tag_length, const uint8_t *aad, + size_t aad_length); /* Decrypt "cypher_text" using "key" and put the result in "clear_text". * and "clear_text" must point to a buffer large enough to store the @@ -134,9 +136,9 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, const uint8_t *cypher_text, uint32_t cypher_length, size_t block_size, const uint8_t *iv, const uint8_t *key, - uint32_t key_length, - uint8_t *tag, size_t tag_length, - const uint8_t *aad, size_t aad_length); + uint32_t key_length, uint8_t *tag, + size_t tag_length, const uint8_t *aad, + size_t aad_length); /* * Helper API designed to convert the raw signature into DER format required by @@ -147,7 +149,8 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, * format. */ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, - uint8_t *message_signature, size_t *signature_length); + uint8_t *message_signature, + size_t *signature_length); /* * This internal API is used to convert public key and signature which is in @@ -162,9 +165,10 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, * raw_key_length: input, the buffer size of the raw_key */ int32_t crypto_hal_der_decode(uint8_t *raw_key, uint8_t *raw_sig, - const unsigned char *pub_key, size_t key_length, - const uint8_t *message_signature, size_t signature_length, - size_t raw_key_length, size_t raw_sig_length); + const unsigned char *pub_key, size_t key_length, + const uint8_t *message_signature, + size_t signature_length, size_t raw_key_length, + size_t raw_sig_length); int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr); diff --git a/crypto/include/tpm20_Utils.h b/crypto/include/tpm20_Utils.h index 6b62cffc..32e5f125 100644 --- a/crypto/include/tpm20_Utils.h +++ b/crypto/include/tpm20_Utils.h @@ -10,10 +10,20 @@ #include #define TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_128 128 -#define TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_160 160 -#define TPM_HMAC_PUB_KEY_CONTEXT_SIZE 48 +#if defined(ECDSA256_DA) #define FDO_TPM2_CURVE_ID TPM2_ECC_NIST_P256 +#define TPM_AES_BITS 128 +#define FDO_TPM2_ALG_SHA TPM2_ALG_SHA256 +#define TPM_HMAC_PRIV_KEY_CONTEXT_SIZE 160 +#define TPM_HMAC_PUB_KEY_CONTEXT_SIZE 48 +#else +#define FDO_TPM2_CURVE_ID TPM2_ECC_NIST_P384 +#define TPM_AES_BITS 256 +#define FDO_TPM2_ALG_SHA TPM2_ALG_SHA384 +#define TPM_HMAC_PRIV_KEY_CONTEXT_SIZE 224 +#define TPM_HMAC_PUB_KEY_CONTEXT_SIZE 64 +#endif #define TPM2_ZEROISE_FREE(ref) \ { \ @@ -26,78 +36,87 @@ static const TPM2B_PUBLIC in_public_primary_key_template = { .size = 0, - .publicArea = - { - .type = TPM2_ALG_ECC, - .nameAlg = TPM2_ALG_SHA256, - .objectAttributes = - (TPMA_OBJECT_USERWITHAUTH | TPMA_OBJECT_RESTRICTED | - TPMA_OBJECT_DECRYPT | TPMA_OBJECT_FIXEDTPM | - TPMA_OBJECT_FIXEDPARENT | TPMA_OBJECT_SENSITIVEDATAORIGIN), - .authPolicy = - { - .size = 0, - }, + .publicArea = { + .type = TPM2_ALG_ECC, + .nameAlg = FDO_TPM2_ALG_SHA, + .objectAttributes = + (TPMA_OBJECT_USERWITHAUTH | TPMA_OBJECT_RESTRICTED | + TPMA_OBJECT_DECRYPT | TPMA_OBJECT_FIXEDTPM | + TPMA_OBJECT_FIXEDPARENT | TPMA_OBJECT_SENSITIVEDATAORIGIN), + .authPolicy = + { + .size = 0, + }, + .parameters + .eccDetail = {.symmetric = {.algorithm = TPM2_ALG_AES, + .keyBits.aes = TPM_AES_BITS, + .mode.aes = TPM2_ALG_CFB}, + .scheme = {.scheme = TPM2_ALG_NULL, .details = {{0}}}, + .curveID = FDO_TPM2_CURVE_ID, + .kdf = {.scheme = TPM2_ALG_NULL, .details = {{0}}}}, + .unique.ecc = {.x = {.size = 0, .buffer = {0}}, + .y = {.size = 0, .buffer = {0}}}}}; - .parameters.eccDetail = {.symmetric = - { - .algorithm = TPM2_ALG_AES, - .keyBits.aes = 128, - .mode.aes = TPM2_ALG_CFB, - }, - .scheme = - { - .scheme = TPM2_ALG_NULL, - .details = {{0}}, - }, - .curveID = FDO_TPM2_CURVE_ID, - .kdf = {.scheme = TPM2_ALG_NULL, - .details = {{0}}}}, - .unique.ecc = - { - .x = {.size = 0, .buffer = {0}}, - .y = {.size = 0, .buffer = {0}}, - }, - }, -}; +static const TPM2B_PUBLIC in_publicECKey_template = { + .size = 0, + .publicArea = { + .type = TPM2_ALG_ECC, + .nameAlg = FDO_TPM2_ALG_SHA, + .objectAttributes = + (TPMA_OBJECT_USERWITHAUTH | TPMA_OBJECT_SIGN_ENCRYPT | + TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT | + TPMA_OBJECT_SENSITIVEDATAORIGIN), + .authPolicy = + { + .size = 0, + }, + .parameters.eccDetail = + {.symmetric = {.algorithm = TPM2_ALG_NULL, + .keyBits.aes = 0, + .mode.aes = 0}, + .scheme = {.scheme = TPM2_ALG_ECDSA, + .details = {.ecdsa = {.hashAlg = FDO_TPM2_ALG_SHA}}}, + .curveID = FDO_TPM2_CURVE_ID, + .kdf = {.scheme = TPM2_ALG_NULL, .details = {{0}}}}, + .unique.ecc = {.x = {.size = 0, .buffer = {0}}, + .y = {.size = 0, .buffer = {0}}}}}; static const TPM2B_PUBLIC in_publicHMACKey_template = { .size = 0, - .publicArea = - { - .type = TPM2_ALG_KEYEDHASH, - .nameAlg = TPM2_ALG_SHA256, - .objectAttributes = - (TPMA_OBJECT_USERWITHAUTH | TPMA_OBJECT_DECRYPT | - TPMA_OBJECT_SIGN_ENCRYPT | TPMA_OBJECT_FIXEDTPM | - TPMA_OBJECT_FIXEDPARENT | TPMA_OBJECT_SENSITIVEDATAORIGIN), - .authPolicy = - { - .size = 0, - }, - - .parameters.keyedHashDetail = - { - .scheme = - { - .scheme = TPM2_ALG_NULL, - .details = {{0}}, - }, - }, - .unique.keyedHash = - { - .size = 0, - .buffer = {0}, - }, - }, -}; + .publicArea = { + .type = TPM2_ALG_KEYEDHASH, + .nameAlg = FDO_TPM2_ALG_SHA, + .objectAttributes = + (TPMA_OBJECT_USERWITHAUTH | TPMA_OBJECT_SIGN_ENCRYPT | + TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT | + TPMA_OBJECT_SENSITIVEDATAORIGIN), + .authPolicy = + { + .size = 0, + }, + .parameters.keyedHashDetail = + {.scheme = {.scheme = TPM2_ALG_HMAC, + .details = {.hmac = {.hashAlg = FDO_TPM2_ALG_SHA}}}}, + .unique.keyedHash = + { + .size = 0, + .buffer = {0}, + }, + }}; int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, - size_t hmac_length, char *tpmHMACPub_key, - char *tpmHMACPriv_key); -int32_t fdo_tpm_generate_hmac_key(char *tpmHMACPub_key, char *tpmHMACPriv_key); -int32_t fdo_tpm_commit_replacement_hmac_key(void); -void fdo_tpm_clear_replacement_hmac_key(void); -int32_t is_valid_tpm_data_protection_key_present(void); + size_t hmac_length, + TPMI_DH_PERSISTENT persistent_handle); +int32_t fdo_tpm_generate_hmac_key(TPMI_DH_PERSISTENT persistent_handle); + +int32_t fdoTPMEsys_context_init(ESYS_CONTEXT **esys_context); +int32_t fdoTPMEsys_auth_session_init(ESYS_CONTEXT *esys_context, + ESYS_TR *session_handle); +int32_t fdoTPMTSSContext_clean_up(ESYS_CONTEXT **esys_context, + ESYS_TR *auth_session_handle, + ESYS_TR *primary_handle); +int32_t fdoTPMGenerate_primary_key_context(ESYS_CONTEXT **esys_context, + ESYS_TR *primary_handle, + ESYS_TR *auth_session_handle); #endif /* #ifndef __TPM20_UTILS_H__ */ diff --git a/crypto/mbedtls/mbedtls_AESGCMRoutines.c b/crypto/mbedtls/mbedtls_AESGCMRoutines.c index 8972932c..baf57050 100644 --- a/crypto/mbedtls/mbedtls_AESGCMRoutines.c +++ b/crypto/mbedtls/mbedtls_AESGCMRoutines.c @@ -9,7 +9,7 @@ * mbedtls library. */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "platform_utils.h" #include "crypto_utils.h" @@ -41,13 +41,10 @@ * @return ret * return cipher_length in bytes during success and -1 during any error. */ -int32_t fdo_crypto_aes_gcm_encrypt(const uint8_t *plain_text, - uint32_t plain_text_length, - uint8_t *cipher_text, - uint32_t cipher_text_length, - const uint8_t *iv, uint32_t iv_length, - const uint8_t *key, uint32_t key_length, - uint8_t *tag, uint32_t tag_length) +int32_t fdo_crypto_aes_gcm_encrypt( + const uint8_t *plain_text, uint32_t plain_text_length, uint8_t *cipher_text, + uint32_t cipher_text_length, const uint8_t *iv, uint32_t iv_length, + const uint8_t *key, uint32_t key_length, uint8_t *tag, uint32_t tag_length) { int32_t retval = -1; static mbedtls_gcm_context ctx; @@ -124,13 +121,10 @@ int32_t fdo_crypto_aes_gcm_encrypt(const uint8_t *plain_text, * return clear_text_length in bytes during success and -1 during any * error. */ -int32_t fdo_crypto_aes_gcm_decrypt(uint8_t *clear_text, - uint32_t clear_text_length, - const uint8_t *cipher_text, - uint32_t cipher_text_length, - const uint8_t *iv, uint32_t iv_length, - const uint8_t *key, uint32_t key_length, - uint8_t *tag, uint32_t tag_length) +int32_t fdo_crypto_aes_gcm_decrypt( + uint8_t *clear_text, uint32_t clear_text_length, const uint8_t *cipher_text, + uint32_t cipher_text_length, const uint8_t *iv, uint32_t iv_length, + const uint8_t *key, uint32_t key_length, uint8_t *tag, uint32_t tag_length) { int32_t retval = -1; static mbedtls_gcm_context ctx; diff --git a/crypto/mbedtls/mbedtls_AESRoutines.c b/crypto/mbedtls/mbedtls_AESRoutines.c index 08a292b5..4ae8c38b 100644 --- a/crypto/mbedtls/mbedtls_AESRoutines.c +++ b/crypto/mbedtls/mbedtls_AESRoutines.c @@ -15,7 +15,7 @@ #include "mbedtls/cipher_internal.h" #include "util.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "BN_support.h" #include "safe_lib.h" @@ -26,8 +26,8 @@ #define CIPHER_TYPE MBEDTLS_CIPHER_AES_256_CTR #else #define CIPHER_TYPE MBEDTLS_CIPHER_AES_256_CBC -#endif /* AES_MODE_CTR_ENABLED */ -#define KEY_LENGTH_LOCAL 32 //256 bit +#endif /* AES_MODE_CTR_ENABLED */ +#define KEY_LENGTH_LOCAL 32 // 256 bit #else @@ -35,8 +35,8 @@ #define CIPHER_TYPE MBEDTLS_CIPHER_AES_128_CTR #else #define CIPHER_TYPE MBEDTLS_CIPHER_AES_128_CBC -#endif /* AES_MODE_CTR_ENABLED */ -#define KEY_LENGTH_LOCAL 16 //128 bit +#endif /* AES_MODE_CTR_ENABLED */ +#define KEY_LENGTH_LOCAL 16 // 128 bit #endif /* AES_256_BIT */ @@ -125,7 +125,7 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, } ret = mbedtls_cipher_setkey(&cipher_ctx, key, 8 * key_length, - MBEDTLS_ENCRYPT); + MBEDTLS_ENCRYPT); if (ret != 0) { LOG(LOG_ERROR, "failed to set the key\n"); goto end; @@ -144,16 +144,14 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, } /* encrypt */ - ret = mbedtls_cipher_update(&cipher_ctx, clear_text, - clear_text_length, cipher_text, - &olen); + ret = mbedtls_cipher_update(&cipher_ctx, clear_text, clear_text_length, + cipher_text, &olen); if (ret != 0) { LOG(LOG_ERROR, "cipher_update failed\n"); goto end; } - ret = mbedtls_cipher_finish(&cipher_ctx, cipher_text + olen, - &olen); + ret = mbedtls_cipher_finish(&cipher_ctx, cipher_text + olen, &olen); if (ret != 0) { LOG(LOG_ERROR, "cipher failed\n"); goto end; diff --git a/crypto/mbedtls/mbedtls_DERRoutines.c b/crypto/mbedtls/mbedtls_DERRoutines.c index dd547061..030d10b7 100644 --- a/crypto/mbedtls/mbedtls_DERRoutines.c +++ b/crypto/mbedtls/mbedtls_DERRoutines.c @@ -8,7 +8,7 @@ * \ brief Abstraction layer for ECDSA signing routine using SE */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "storage_al.h" #include "safe_lib.h" @@ -25,7 +25,8 @@ * format. */ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, - uint8_t *message_signature, size_t *signature_length) + uint8_t *message_signature, + size_t *signature_length) { int ret; mbedtls_mpi r, s; @@ -80,9 +81,8 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, } len += ret; - ret = mbedtls_asn1_write_tag(&p, buf, - MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SEQUENCE); + ret = mbedtls_asn1_write_tag( + &p, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); if (0 > ret) { LOG(LOG_ERROR, "Unable to convert the raw signature into DER format"); @@ -118,9 +118,10 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, * raw_key_length: input, the buffer size of the raw_key */ int32_t crypto_hal_der_decode(uint8_t *raw_key, uint8_t *raw_sig, - const unsigned char *pub_key, size_t key_length, - const uint8_t *message_signature, size_t signature_length, - size_t raw_key_length, size_t raw_sig_length) + const unsigned char *pub_key, size_t key_length, + const uint8_t *message_signature, + size_t signature_length, size_t raw_key_length, + size_t raw_sig_length) { int ret; mbedtls_pk_context pk_ctx = {0}; @@ -141,8 +142,7 @@ int32_t crypto_hal_der_decode(uint8_t *raw_key, uint8_t *raw_sig, mbedtls_pk_init(&pk_ctx); - ret = mbedtls_pk_parse_public_key(&pk_ctx, pub_key, - (size_t)key_length); + ret = mbedtls_pk_parse_public_key(&pk_ctx, pub_key, (size_t)key_length); if (ret != 0) { LOG(LOG_ERROR, "Parsing EC public-key failed!\n"); diff --git a/crypto/mbedtls/mbedtls_ECDSASignRoutines.c b/crypto/mbedtls/mbedtls_ECDSASignRoutines.c index 84e7e14c..83c18a06 100644 --- a/crypto/mbedtls/mbedtls_ECDSASignRoutines.c +++ b/crypto/mbedtls/mbedtls_ECDSASignRoutines.c @@ -15,7 +15,7 @@ #include "mbedtls/ecdsa.h" #include "safe_lib.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "stdlib.h" #include "storage_al.h" @@ -32,8 +32,8 @@ * @return 0 if true, else -1. */ int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, - unsigned char *message_signature, - size_t *signature_length) + unsigned char *message_signature, + size_t *signature_length) { int ret = -1; int retval = -1; @@ -115,19 +115,17 @@ int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, /* From the EC keypair, get the private key */ ecp = mbedtls_pk_ec(pk_ctx); - retval = mbedtls_mpi_copy(&(ctx_sign.d), - (const mbedtls_mpi *)&(ecp->d)); + retval = + mbedtls_mpi_copy(&(ctx_sign.d), (const mbedtls_mpi *)&(ecp->d)); if (ecp == NULL || retval != 0) { goto end; } #endif // Generate Signature - retval = mbedtls_ecdsa_write_signature(&ctx_sign, hash_type, hash, - hash_length, message_signature, - (size_t *)signature_length, - mbedtls_ctr_drbg_random, - drbg_ctx); + retval = mbedtls_ecdsa_write_signature( + &ctx_sign, hash_type, hash, hash_length, message_signature, + (size_t *)signature_length, mbedtls_ctr_drbg_random, drbg_ctx); if (retval != 0) { LOG(LOG_ERROR, "signature creation failed ret:%d\n", retval); goto end; diff --git a/crypto/mbedtls/mbedtls_ECDSAVerifyRoutines.c b/crypto/mbedtls/mbedtls_ECDSAVerifyRoutines.c index a767693d..965029ef 100644 --- a/crypto/mbedtls/mbedtls_ECDSAVerifyRoutines.c +++ b/crypto/mbedtls/mbedtls_ECDSAVerifyRoutines.c @@ -16,7 +16,7 @@ #include #include "safe_lib.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "stdlib.h" #include "storage_al.h" diff --git a/crypto/mbedtls/mbedtls_SSLRoutines.c b/crypto/mbedtls/mbedtls_SSLRoutines.c index 416066c2..421476eb 100644 --- a/crypto/mbedtls/mbedtls_SSLRoutines.c +++ b/crypto/mbedtls/mbedtls_SSLRoutines.c @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache 2.0 */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "crypto_utils.h" #include "mbedtls/net_sockets.h" @@ -19,23 +19,23 @@ /* The list of recommended cipher suites to be used in TLS setup with server */ static const int ciphersuites[] = { - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, - MBEDTLS_TLS_RSA_WITH_AES_128_CCM, - MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_RSA_WITH_AES_256_CCM, - MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, - MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM, - MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM, - MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, + MBEDTLS_TLS_RSA_WITH_AES_128_CCM, + MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_RSA_WITH_AES_256_CCM, + MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, + MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM, + MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM, + MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, }; #if !defined(TARGET_OS_MBEDOS) // non mbedos platform @@ -124,21 +124,19 @@ void *fdo_ssl_setup_connect(char *SERVER_NAME, char *SERVER_PORT) mbedtls_ctr_drbg_init(&(p_ssl_info->ctr_drbg)); mbedtls_ssl_init(&(p_ssl_info->ssl)); mbedtls_ssl_config_init(&(p_ssl_info->conf)); - ret = mbedtls_ctr_drbg_seed(&(p_ssl_info->ctr_drbg), - mbedtls_entropy_func, - &(p_ssl_info->entropy), - (unsigned char *)DRBG_PERSONALIZED_STR, - strlen((char *)DRBG_PERSONALIZED_STR) + 1); + ret = mbedtls_ctr_drbg_seed( + &(p_ssl_info->ctr_drbg), mbedtls_entropy_func, + &(p_ssl_info->entropy), (unsigned char *)DRBG_PERSONALIZED_STR, + strlen((char *)DRBG_PERSONALIZED_STR) + 1); if (ret != 0) { LOG(LOG_ERROR, "mbedtls_ctr_drbg_seed returned %d", ret); goto exit; } #if !defined(TARGET_OS_MBEDOS) - ret = mbedtls_net_connect(&(p_ssl_info->server_fd), - (const char *)SERVER_NAME, - (const char *)SERVER_PORT, - MBEDTLS_NET_PROTO_TCP); + ret = mbedtls_net_connect( + &(p_ssl_info->server_fd), (const char *)SERVER_NAME, + (const char *)SERVER_PORT, MBEDTLS_NET_PROTO_TCP); if (ret != 0) { LOG(LOG_ERROR, "failed\n ! mbedtls_net_connect returned %d\n\n", ret); @@ -153,10 +151,9 @@ void *fdo_ssl_setup_connect(char *SERVER_NAME, char *SERVER_PORT) } ssl_info_var.socket = socket; #endif - ret = mbedtls_ssl_config_defaults(&(p_ssl_info->conf), - MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT); + ret = mbedtls_ssl_config_defaults( + &(p_ssl_info->conf), MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) { LOG(LOG_ERROR, "failed\n ! mbedtls_ssl_config_defaults returned %d\n\n", @@ -186,8 +183,7 @@ void *fdo_ssl_setup_connect(char *SERVER_NAME, char *SERVER_PORT) mbedtls_esp_enable_debug_log(&(p_ssl_info->conf), 4); #endif - ret = mbedtls_ssl_setup(&(p_ssl_info->ssl), - &(p_ssl_info->conf)); + ret = mbedtls_ssl_setup(&(p_ssl_info->ssl), &(p_ssl_info->conf)); if (ret != 0) { LOG(LOG_ERROR, "failed\n ! mbedtls_ssl_setup returned %d\n\n", ret); diff --git a/crypto/mbedtls/mbedtls_cryptoSupport.c b/crypto/mbedtls/mbedtls_cryptoSupport.c index 29ec88e5..b91f16e3 100644 --- a/crypto/mbedtls/mbedtls_cryptoSupport.c +++ b/crypto/mbedtls/mbedtls_cryptoSupport.c @@ -15,12 +15,11 @@ #include "mbedtls/pk.h" #include "mbedtls/sha256.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "safe_lib.h" #include "mbedtls_random.h" - int32_t inc_rollover_ctr(uint8_t *first_iv, uint8_t *new_iv, uint8_t iv_len, size_t aesblocks) { @@ -190,8 +189,8 @@ int32_t crypto_close(void) * return 0 on success. -ve value on failure. */ int32_t crypto_hal_hash(uint8_t _hash_type, const uint8_t *buffer, - size_t buffer_length, uint8_t *output, - size_t output_length) + size_t buffer_length, uint8_t *output, + size_t output_length) { mbedtls_md_type_t mbedhash_type = MBEDTLS_MD_NONE; uint8_t hash_type = FDO_CRYPTO_HASH_TYPE_USED; diff --git a/crypto/mbedtls/mbedtls_ec_csr.c b/crypto/mbedtls/mbedtls_ec_csr.c index db63a2f9..d3476b75 100644 --- a/crypto/mbedtls/mbedtls_ec_csr.c +++ b/crypto/mbedtls/mbedtls_ec_csr.c @@ -14,7 +14,7 @@ #include "util.h" #include "fdotypes.h" #include "mbedtls_random.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "safe_lib.h" #include "ecdsa_privkey.h" #include "fdocred.h" diff --git a/crypto/mbedtls/mbedtls_key_exchange_ecdh.c b/crypto/mbedtls/mbedtls_key_exchange_ecdh.c index 2f40cb3e..a70d0a83 100644 --- a/crypto/mbedtls/mbedtls_key_exchange_ecdh.c +++ b/crypto/mbedtls/mbedtls_key_exchange_ecdh.c @@ -5,7 +5,7 @@ #include #include "util.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "crypto_utils.h" #include "BN_support.h" #include "safe_lib.h" @@ -72,7 +72,7 @@ int32_t crypto_hal_kex_init(void **context) } if (crypto_hal_random_bytes(key_ex_data->_Device_random, - key_ex_data->_Dev_rand_size) != 0) { + key_ex_data->_Dev_rand_size) != 0) { LOG(LOG_ERROR, "Failed to generate device random\n"); goto error; } diff --git a/crypto/mbedtls/mbedtls_random.c b/crypto/mbedtls/mbedtls_random.c index e2132bf1..7c910ddc 100644 --- a/crypto/mbedtls/mbedtls_random.c +++ b/crypto/mbedtls/mbedtls_random.c @@ -7,8 +7,8 @@ #include #include -#include "fdoCrypto.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto.h" +#include "fdo_crypto_hal.h" #include "safe_lib.h" #include "util.h" #include "mbedtls_random.h" diff --git a/crypto/openssl/BN_support.c b/crypto/openssl/BN_support.c index 8730868a..cf7c6b18 100644 --- a/crypto/openssl/BN_support.c +++ b/crypto/openssl/BN_support.c @@ -9,7 +9,7 @@ */ #include "BN_support.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include #include "safe_lib.h" #include "util.h" diff --git a/crypto/openssl/cse_cryptoSupport.c b/crypto/openssl/cse_crypto_support.c similarity index 68% rename from crypto/openssl/cse_cryptoSupport.c rename to crypto/openssl/cse_crypto_support.c index 91648ebe..3b0d4405 100644 --- a/crypto/openssl/cse_cryptoSupport.c +++ b/crypto/openssl/cse_crypto_support.c @@ -9,7 +9,7 @@ * library. */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "cse_utils.h" /** @@ -25,9 +25,10 @@ int32_t crypto_hal_random_bytes(uint8_t *random_buffer, size_t num_bytes) if (NULL == random_buffer) { return -1; - } else if (TEE_SUCCESS != fdo_heci_generate_random(&fdo_cse_handle, - random_buffer, (uint32_t)num_bytes, &fdo_status) || - FDO_STATUS_SUCCESS != fdo_status) { + } else if (TEE_SUCCESS != fdo_heci_generate_random( + &fdo_cse_handle, random_buffer, + (uint32_t)num_bytes, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO CSE generate ranom bytes failed!!\n"); return -1; } @@ -44,8 +45,8 @@ int32_t crypto_hal_random_bytes(uint8_t *random_buffer, size_t num_bytes) * @param output_length - output data buffer size * @return return 0 on success. -ve value on failure. */ -int32_t crypto_hal_hmac_cse(uint8_t *buffer, - size_t buffer_length, uint8_t *output, size_t output_length) +int32_t crypto_hal_hmac_cse(uint8_t *buffer, size_t buffer_length, + uint8_t *output, size_t output_length) { if (NULL == output || 0 == output_length || NULL == buffer || 0 == buffer_length) { @@ -54,15 +55,17 @@ int32_t crypto_hal_hmac_cse(uint8_t *buffer, FDO_STATUS fdo_status; - if (TEE_SUCCESS != fdo_heci_load_file(&fdo_cse_handle, OVH_FILE_ID, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + if (TEE_SUCCESS != + fdo_heci_load_file(&fdo_cse_handle, OVH_FILE_ID, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI LOAD failed!! %u\n", fdo_status); return -1; } if (TEE_SUCCESS != fdo_heci_update_file(&fdo_cse_handle, OVH_FILE_ID, - buffer, buffer_length, output, output_length, &fdo_status) || - FDO_STATUS_SUCCESS != fdo_status) { + buffer, buffer_length, output, + output_length, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI UPDATE failed!! %u\n", fdo_status); return -1; } @@ -84,11 +87,12 @@ int32_t crypto_hal_hmac_cse(uint8_t *buffer, * @return 0 if true, else -1. */ int32_t crypto_hal_ecdsa_sign_cse(const uint8_t *data, size_t data_len, - uint8_t *message_signature, size_t message_sig_len, - uint8_t *eat_maroe, size_t *maroe_length) + uint8_t *message_signature, + size_t message_sig_len, uint8_t *eat_maroe, + size_t *maroe_length) { if (!data || !data_len || !message_signature || !message_sig_len || - !eat_maroe || !maroe_length) { + !eat_maroe || !maroe_length) { LOG(LOG_ERROR, "fdo_cryptoECDSASign params not valid\n"); return -1; } @@ -96,15 +100,18 @@ int32_t crypto_hal_ecdsa_sign_cse(const uint8_t *data, size_t data_len, FDO_STATUS fdo_status; uint32_t mp_len = 0; - if (TEE_SUCCESS != fdo_heci_ecdsa_device_sign_challenge(&fdo_cse_handle, - (uint8_t *)data, (uint32_t)data_len, message_signature, - message_sig_len, eat_maroe, &mp_len, &fdo_status) || - FDO_STATUS_SUCCESS != fdo_status) { + if (TEE_SUCCESS != fdo_heci_ecdsa_device_sign_challenge( + &fdo_cse_handle, (uint8_t *)data, + (uint32_t)data_len, message_signature, + message_sig_len, eat_maroe, &mp_len, + &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI ECDSA DEVICE SIGN failed!! %u\n", - fdo_status); - return -1; + fdo_status); + return -1; } - LOG(LOG_DEBUG, "FDO HECI ECDSA DEVICE SIGN compelete!! %u\n", fdo_status); + LOG(LOG_DEBUG, "FDO HECI ECDSA DEVICE SIGN compelete!! %u\n", + fdo_status); *maroe_length = mp_len; diff --git a/crypto/openssl/ec_key.c b/crypto/openssl/ec_key.c index d49e6892..86e38498 100644 --- a/crypto/openssl/ec_key.c +++ b/crypto/openssl/ec_key.c @@ -12,6 +12,7 @@ #include #include #include +#include #include "fdotypes.h" #include "storage_al.h" #include "util.h" @@ -20,12 +21,11 @@ #include "safe_lib.h" #ifdef ECDSA_PEM -EC_KEY *get_ec_key(void) +EVP_PKEY *get_evp_key(void) { int ret = -1; uint8_t *privkey = NULL; size_t privkey_size = 0; - EC_KEY *ec_key = NULL; BIO *ecprivkey_bio = NULL; EVP_PKEY *ecprivkey_evp = NULL; @@ -58,12 +58,6 @@ EC_KEY *get_ec_key(void) goto err; } - ec_key = EVP_PKEY_get1_EC_KEY(ecprivkey_evp); - if (!ec_key) { - LOG(LOG_ERROR, "Invalid EC key format\n"); - goto err; - } - err: /* At this point ret is already 0 */ if (privkey) { @@ -73,27 +67,24 @@ EC_KEY *get_ec_key(void) } fdo_free(privkey); } - if (ecprivkey_evp) { + if (ecprivkey_evp && ret) { EVP_PKEY_free(ecprivkey_evp); + ecprivkey_evp = NULL; } if (ecprivkey_bio) { BIO_free(ecprivkey_bio); } - if (ec_key && ret) { - EC_KEY_free(ec_key); - ec_key = NULL; - } - return ec_key; + return ecprivkey_evp; } #else -EC_KEY *get_ec_key(void) +EVP_PKEY *get_evp_key(void) { int ret = 0; uint8_t *privkey = NULL; size_t privkey_size = 0; - EC_KEY *ec_key = NULL; - BIGNUM *ec_key_bn = NULL; int32_t curve = NID_X9_62_prime256v1; + EVP_PKEY *evp_key_ec = NULL; + EVP_PKEY_CTX *evp_ctx = NULL; #ifdef ECDSA384_DA curve = NID_secp384r1; @@ -106,27 +97,37 @@ EC_KEY *get_ec_key(void) goto err; } - /* Load the key from memory into ec_key */ - ec_key_bn = BN_bin2bn(privkey, privkey_size, NULL); - if (!ec_key_bn) { - LOG(LOG_ERROR, "Failed to create eckey BN\n"); + evp_ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); + if (!evp_ctx) { + LOG(LOG_ERROR, "Failed to create evp ctx context \n"); goto err; } - /* Create and initialize openssl EC private key */ - ec_key = EC_KEY_new_by_curve_name(curve); - if (!ec_key) { - LOG(LOG_ERROR, "Failed to allocate ec key\n"); + const char *group_name = OBJ_nid2sn(curve); + OSSL_PARAM params[] = { + OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, privkey, privkey_size), + OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, + (char *)group_name, strlen(group_name)), + OSSL_PARAM_END}; + if (EVP_PKEY_fromdata_init(evp_ctx) <= 0) { + LOG(LOG_ERROR, "Failed to init the ec key from data object\n"); goto err; } - ret = EC_KEY_set_private_key(ec_key, ec_key_bn); - if (!ret) { - LOG(LOG_ERROR, "Failed to set ec private key\n"); + if (EVP_PKEY_fromdata(evp_ctx, &evp_key_ec, EVP_PKEY_KEYPAIR, params) <= + 0) { + LOG(LOG_ERROR, + "Failed to create the ec key from data\n"); // %s", (char + // *)params2); goto err; } + ret = 1; // success err: + if (evp_ctx) { + EVP_PKEY_CTX_free(evp_ctx); + evp_ctx = NULL; + } if (privkey) { if (memset_s(privkey, privkey_size, 0) != 0) { LOG(LOG_ERROR, "Memset Failed\n"); @@ -134,14 +135,10 @@ EC_KEY *get_ec_key(void) } fdo_free(privkey); } - if (ec_key && !ret) { - EC_KEY_free(ec_key); - ec_key = NULL; - } - if (ec_key_bn) { - BN_free(ec_key_bn); + if (evp_key_ec && !ret) { + EVP_PKEY_free(evp_key_ec); + evp_key_ec = NULL; } - - return ec_key; + return evp_key_ec; } #endif diff --git a/crypto/openssl/openssl_AESRoutines.c b/crypto/openssl/openssl_AES_routines.c similarity index 82% rename from crypto/openssl/openssl_AESRoutines.c rename to crypto/openssl/openssl_AES_routines.c index 47021de7..93359348 100644 --- a/crypto/openssl/openssl_AESRoutines.c +++ b/crypto/openssl/openssl_AES_routines.c @@ -9,19 +9,21 @@ * Supported modes are: * - AES-GCM-128 (Key = 128 bits) * - AES-GCM-256 (Key = 256 bits) - * - AES-CCM-64-128-128 (L=64 (8 octets,2^64 bytes message length), Tag = 128 bits, Key = 128 bits) - * - AES-CCM-64-128-256 (L=64 (8 octets,2^64 bytes message length), Tag = 128 bits, Key = 256 bits) + * - AES-CCM-64-128-128 (L=64 (8 octets,2^64 bytes message length), Tag = 128 + * bits, Key = 128 bits) + * - AES-CCM-64-128-256 (L=64 (8 octets,2^64 bytes message length), Tag = 128 + * bits, Key = 256 bits) * - * \NOTE: The IV/Nonce length 'N' for CCM mode is dependent on the maximum message length 'L' value - * and should be equal to 15-L (in octets). - * Refer to [RFC3610](https://datatracker.ietf.org/doc/html/rfc3610) for more information on - * trade-offs between 'L' and 'N' value. - * The current implementation uses L=8, and hence the IV/Nonce length N = 15-8 = 7 octets - * As per FDO and COSE [RFC8152](https://datatracker.ietf.org/doc/html/rfc8152) specifications, - * L=2 could also be used. N=13 MUST be used in this case. + * \NOTE: The IV/Nonce length 'N' for CCM mode is dependent on the maximum + * message length 'L' value and should be equal to 15-L (in octets). Refer to + * [RFC3610](https://datatracker.ietf.org/doc/html/rfc3610) for more information + * on trade-offs between 'L' and 'N' value. The current implementation uses L=8, + * and hence the IV/Nonce length N = 15-8 = 7 octets As per FDO and COSE + * [RFC8152](https://datatracker.ietf.org/doc/html/rfc8152) specifications, L=2 + * could also be used. N=13 MUST be used in this case. */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "crypto_utils.h" #include @@ -29,7 +31,7 @@ #include #include "safe_lib.h" -// Specify Openssl constants depending on the AES MODES (GCM/CCM) +// Specify Openssl constants depending on the AES MODES (GCM/CCM) #ifdef AES_MODE_GCM_ENABLED // GCM mode enabled @@ -38,7 +40,7 @@ #define CIPHER_TYPE EVP_aes_256_gcm() #define KEY_LENGTH_LOCAL 32 #else - //128 bit keys +// 128 bit keys #define CIPHER_TYPE EVP_aes_128_gcm() #define KEY_LENGTH_LOCAL 16 #endif @@ -55,16 +57,17 @@ #ifdef AES_256_BIT #define CIPHER_TYPE EVP_aes_256_ccm() -#define KEY_LENGTH_LOCAL 32 //256 bits +#define KEY_LENGTH_LOCAL 32 // 256 bits #else #define CIPHER_TYPE EVP_aes_128_ccm() -#define KEY_LENGTH_LOCAL 16 //128 bit +#define KEY_LENGTH_LOCAL 16 // 128 bit #endif #define TAG_LENGTH AES_CCM_TAG_LEN #define IV_LENGTH AES_CCM_IV_LEN -// 'L' value of 8 octets. A change to this value MUST be matched with a corresponding change -// of IV_LENGTH, 'N' to '15-L'. For example, for L_VALUE_BYTES(L)=2, IV_LENGTH(N)=13 +// 'L' value of 8 octets. A change to this value MUST be matched with a +// corresponding change of IV_LENGTH, 'N' to '15-L'. For example, for +// L_VALUE_BYTES(L)=2, IV_LENGTH(N)=13 #define L_VALUE_BYTES 8 #define SET_IV EVP_CTRL_CCM_SET_IVLEN @@ -97,7 +100,8 @@ * @param tag_length * Fixed tag length in BYTES (output). * @param aad - * Additional Authenticated Data(AAD) in Byte_array format used in encryption. + * Additional Authenticated Data(AAD) in Byte_array format used in + * encryption. * @param aad_length * Additional Authenticated Data(AAD) size in BYTES. * @return ret @@ -109,9 +113,9 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, uint32_t clear_text_length, uint8_t *cipher_text, uint32_t *cipher_length, size_t block_size, const uint8_t *iv, const uint8_t *key, - uint32_t key_length, - uint8_t *tag, size_t tag_length, - const uint8_t *aad, size_t aad_length) + uint32_t key_length, uint8_t *tag, + size_t tag_length, const uint8_t *aad, + size_t aad_length) { int ret = -1; EVP_CIPHER_CTX *ctx = NULL; @@ -123,8 +127,8 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, */ if (!clear_text || !clear_text_length || !cipher_length || FDO_AES_BLOCK_SIZE != block_size || !iv || !key || - KEY_LENGTH_LOCAL != key_length || - !tag || tag_length != TAG_LENGTH) { + KEY_LENGTH_LOCAL != key_length || !tag || + tag_length != TAG_LENGTH) { LOG(LOG_ERROR, "Invalid parameters received\n"); goto end; } @@ -143,7 +147,8 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, // Initialise the AES GCM encryption operation if (!EVP_EncryptInit_ex(ctx, CIPHER_TYPE, NULL, NULL, NULL)) { - LOG(LOG_ERROR, "Error during Initializing AES encrypt operation!\n"); + LOG(LOG_ERROR, + "Error during Initializing AES encrypt operation!\n"); goto end; } @@ -160,7 +165,8 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, goto end; } - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, L_VALUE_BYTES, NULL)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, L_VALUE_BYTES, + NULL)) { LOG(LOG_ERROR, "Error during setting AES tag length!\n"); goto end; } @@ -176,8 +182,10 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, if (aad && aad_length > 0) { #ifdef AES_MODE_CCM_ENABLED // Specify Plain data length (only required in case of CCM) - if (!EVP_EncryptUpdate(ctx, NULL, &len, NULL, clear_text_length)){ - LOG(LOG_ERROR, "Plain data length initialization failed!\n"); + if (!EVP_EncryptUpdate(ctx, NULL, &len, NULL, + clear_text_length)) { + LOG(LOG_ERROR, + "Plain data length initialization failed!\n"); goto end; } #endif @@ -190,7 +198,7 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, // Provide the message to be encrypted, and obtain the encrypted output. // EVP_EncryptUpdate can be called multiple times if necessary if (!EVP_EncryptUpdate(ctx, cipher_text, &len, clear_text, - clear_text_length)) { + clear_text_length)) { LOG(LOG_ERROR, "EVP_EncryptUpdate() failed!\n"); goto end; } @@ -242,7 +250,8 @@ int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, * @param tag_length * Fixed tag length in BYTES. * @param aad - * Additional Authenticated Data(AAD) in Byte_array format used in decryption. + * Additional Authenticated Data(AAD) in Byte_array format used in + * decryption. * @param aad_length * Additional Authenticated Data(AAD) size in BYTES. * @return ret @@ -254,9 +263,9 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, const uint8_t *cipher_text, uint32_t cipher_length, size_t block_size, const uint8_t *iv, const uint8_t *key, - uint32_t key_length, - uint8_t *tag, size_t tag_length, - const uint8_t *aad, size_t aad_length) + uint32_t key_length, uint8_t *tag, + size_t tag_length, const uint8_t *aad, + size_t aad_length) { int ret = -1; EVP_CIPHER_CTX *ctx = NULL; @@ -265,8 +274,8 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, // Check all the incoming parameters if (!clear_text_length || !cipher_text || cipher_length <= 0 || FDO_AES_BLOCK_SIZE != block_size || !iv || !key || - KEY_LENGTH_LOCAL != key_length || - !tag || tag_length != AES_TAG_LEN) { + KEY_LENGTH_LOCAL != key_length || !tag || + tag_length != AES_TAG_LEN) { LOG(LOG_ERROR, "Invalid paramters received\n"); goto end; } @@ -285,7 +294,8 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, // Initialise the AES decryption operation if (!EVP_DecryptInit_ex(ctx, CIPHER_TYPE, NULL, NULL, NULL)) { - LOG(LOG_ERROR, "Error during Initializing EVP AES decrypt operation!\n"); + LOG(LOG_ERROR, + "Error during Initializing EVP AES decrypt operation!\n"); goto end; } @@ -295,23 +305,23 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, goto end; } - // NOTE: As per Openssl's documentation, Tag is specified for CCM before EVP_DecryptUpdate, - // while the same is specified for GCM after EVP_DecryptUpdate. - // As a result, the tag for GCM is specified later. + // NOTE: As per Openssl's documentation, Tag is specified for CCM before + // EVP_DecryptUpdate, while the same is specified for GCM after + // EVP_DecryptUpdate. As a result, the tag for GCM is specified later. // L value is set for CCM separately here. #ifdef AES_MODE_CCM_ENABLED // Set tag - if (!EVP_CIPHER_CTX_ctrl(ctx, SET_TAG, tag_length, - tag)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, SET_TAG, tag_length, tag)) { LOG(LOG_ERROR, "Error during setting AES IV length!\n"); goto end; } - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, L_VALUE_BYTES, NULL)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, L_VALUE_BYTES, + NULL)) { LOG(LOG_ERROR, "Error during setting AES tag length!\n"); goto end; } - #endif +#endif // Initialise key and IV if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) { @@ -324,7 +334,7 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, #ifdef AES_MODE_CCM_ENABLED // Set ciphertext length (only required for CCM) - if (!EVP_DecryptUpdate(ctx, NULL, &len, NULL, cipher_length)) { + if (!EVP_DecryptUpdate(ctx, NULL, &len, NULL, cipher_length)) { LOG(LOG_ERROR, "Cipher length set failed!\n"); goto end; } @@ -338,7 +348,7 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, #ifdef AES_MODE_CCM_ENABLED // Decrypt the message. Can only be called once. ret = EVP_DecryptUpdate(ctx, clear_text, &len, cipher_text, - cipher_length); + cipher_length); if (ret > 0) { // Success: decrypted and authentication passed *clear_text_length = len; @@ -359,8 +369,7 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, *clear_text_length = len; // Set tag - if (!EVP_CIPHER_CTX_ctrl(ctx, SET_TAG, tag_length, - tag)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, SET_TAG, tag_length, tag)) { LOG(LOG_ERROR, "Error during setting AES tag length!\n"); goto end; } diff --git a/crypto/openssl/openssl_DERRoutines.c b/crypto/openssl/openssl_DER_routines.c similarity index 94% rename from crypto/openssl/openssl_DERRoutines.c rename to crypto/openssl/openssl_DER_routines.c index f092679e..3e8d8363 100644 --- a/crypto/openssl/openssl_DERRoutines.c +++ b/crypto/openssl/openssl_DER_routines.c @@ -8,7 +8,7 @@ * \ brief Abstraction layer for ECDSA signing routine using SE */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "storage_al.h" #include "safe_lib.h" @@ -22,7 +22,8 @@ * format. */ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, - uint8_t *message_signature, size_t *signature_length) + uint8_t *message_signature, + size_t *signature_length) { /* Encode */ int ret = 0; @@ -89,9 +90,10 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, * raw_key_length: input, the buffer size of the raw_key */ int32_t crypto_hal_der_decode(uint8_t *raw_key, uint8_t *raw_sig, - const unsigned char *pub_key, size_t key_length, - const uint8_t *message_signature, size_t signature_length, - size_t raw_key_length, size_t raw_sig_length) + const unsigned char *pub_key, size_t key_length, + const uint8_t *message_signature, + size_t signature_length, size_t raw_key_length, + size_t raw_sig_length) { size_t buff_size; int ret = 0; diff --git a/crypto/openssl/openssl_ECDSAVerifyRoutines.c b/crypto/openssl/openssl_ECDSAVerifyRoutines.c deleted file mode 100644 index ae73defc..00000000 --- a/crypto/openssl/openssl_ECDSAVerifyRoutines.c +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright 2020 Intel Corporation - * SPDX-License-Identifier: Apache 2.0 - */ - -/*! - * \file - * \brief Abstraction layer for ECDSA signature verification - * \ APIs of openssl library. - */ - -#include -#include -#include -#include -#include "fdoCryptoHal.h" -#include "util.h" -#include "storage_al.h" -#include "safe_lib.h" - -/** - * Verify an ECC P-256/P-384 signature using provided ECDSA Public Keys. - * @param key_encoding - encoding typee. - * @param key_algorithm - public key algorithm. - * @param message - pointer of type uint8_t, holds the encoded message. - * @param message_length - size of message, type size_t. - * @param message_signature - pointer of type uint8_t, holds a valid - * ecdsa signature in big-endian format - * @param signature_length - size of signature, type unsigned int. - * @param key_param1 - pointer of type uint8_t, holds the public key. - * @param key_param1Length - size of public key, type size_t. - * @param key_param2 - not used. - * @param key_param2Length - not used - * @return 0 if true, else -1. - - */ -int32_t crypto_hal_sig_verify(uint8_t key_encoding, int key_algorithm, - const uint8_t *message, uint32_t message_length, - const uint8_t *message_signature, - uint32_t signature_length, - const uint8_t *key_param1, - uint32_t key_param1Length, - const uint8_t *key_param2, - uint32_t key_param2Length) -{ - int32_t ret = -1; - EC_KEY *eckey = NULL; - uint8_t hash[SHA512_DIGEST_LENGTH] = {0}; - size_t hash_length = 0; - const unsigned char *pub_key = (const unsigned char *)key_param1; - unsigned char *sig_r = NULL; - unsigned char *sig_s = NULL; - BIGNUM *x = NULL; - BIGNUM *y = NULL; - BIGNUM *r = NULL; - BIGNUM *s = NULL; - ECDSA_SIG *sig = NULL; - - /* Check validity of key type. */ - // Only COSEKEY and X509 are currently supported - if ((key_encoding != FDO_CRYPTO_PUB_KEY_ENCODING_X509 && - key_encoding != FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY) || - (key_algorithm != FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256 && - key_algorithm != FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384)) { - LOG(LOG_ERROR, "Incorrect key type\n"); - goto end; - } - - if (NULL == message_signature || 0 == signature_length || - 0 != (signature_length % 2) || - NULL == message || 0 == message_length) { - LOG(LOG_ERROR, "Invalid arguments!\n"); - goto end; - } - - /* generate required EC_KEY based on type */ - if (key_algorithm == FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256) { // P-256 NIST - eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); - if (NULL == eckey) { - LOG(LOG_ERROR, "EC_KEY allocation failed!\n"); - goto end; - } - /* Perform SHA-256 digest of the message */ - if (SHA256((const unsigned char *)message, message_length, - hash) == NULL) { - LOG(LOG_ERROR, "SHA-256 calculation failed!\n"); - goto end; - } - hash_length = SHA256_DIGEST_LENGTH; - - } else { // P-384 - eckey = EC_KEY_new_by_curve_name(NID_secp384r1); - if (NULL == eckey) { - LOG(LOG_ERROR, "EC_KEY allocation failed!\n"); - goto end; - } - /* Perform SHA-384 digest of the message */ - if (SHA384((const unsigned char *)message, message_length, - hash) == NULL) { - LOG(LOG_ERROR, "SHA-384 calculation failed!\n"); - goto end; - } - hash_length = SHA384_DIGEST_LENGTH; - } - - if (key_encoding == FDO_CRYPTO_PUB_KEY_ENCODING_X509) { - - if (NULL == pub_key || 0 == key_param1Length) { - LOG(LOG_ERROR, "Invalid params!\n"); - goto end; - } - /* Unused parameter */ - (void)key_param2; - (void)key_param2Length; - - /* decode EC_KEY struct from DER encoded EC public key */ - if (d2i_EC_PUBKEY(&eckey, &pub_key, (long)key_param1Length) == NULL) { - LOG(LOG_ERROR, "DER to EC_KEY struct decoding failed!\n"); - goto end; - } - } else if (key_encoding == FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY) { - if (NULL == key_param1 || 0 == key_param1Length || - NULL == key_param2 || 0 == key_param2Length) { - LOG(LOG_ERROR, "Invalid params!\n"); - goto end; - } - /* decode EC_KEY struct using Affine X and Y co-ordinates */ - x = BN_bin2bn((const unsigned char*) key_param1, key_param1Length, NULL); - y = BN_bin2bn((const unsigned char*) key_param2, key_param2Length, NULL); - if (!x || !y) { - LOG(LOG_ERROR, "Failed to convert affine-x and/or affine-y\n"); - goto end; - } - if (EC_KEY_set_public_key_affine_coordinates(eckey, x, y) == 0) { - LOG(LOG_ERROR, "Failed to create EC Key from affine-x and affine-y!\n"); - goto end; - } - } - - // assemble r and s into a signature object - sig = ECDSA_SIG_new(); - if (!sig) { - LOG(LOG_ERROR, "ECDSA Sig create failed\n"); - goto end; - } - - sig_r = fdo_alloc(signature_length/2); - if (!sig_r) { - LOG(LOG_ERROR, "Alloc of sig-r failed!\n"); - goto end; - } - if (0 != memcpy_s(sig_r, signature_length/2, - message_signature, signature_length/2)) { - LOG(LOG_ERROR, "Copy of sig-r failed!\n"); - goto end; - } - sig_s = fdo_alloc(signature_length/2); - if (!sig_s) { - LOG(LOG_ERROR, "Alloc of sig-s failed!\n"); - goto end; - } - if (0 != memcpy_s(sig_s, signature_length/2, - message_signature + signature_length/2, signature_length/2)) { - LOG(LOG_ERROR, "Copy of sig-s failed!\n"); - goto end; - } - // get r and s from buffers as BIGNUMs - r = BN_bin2bn((const unsigned char*) sig_r, signature_length/2, NULL); - if (!r) { - LOG(LOG_ERROR, "Failed to convert r\n"); - goto end; - } - s = BN_bin2bn((const unsigned char*) sig_s, signature_length/2, NULL); - if (!s) { - LOG(LOG_ERROR, "Failed to convert s\n"); - BN_free(r); - goto end; - } - - // once set, this maintains r and s, no need to free explicitly - // free only in case of an error - if (1 != ECDSA_SIG_set0(sig, r, s)) { - LOG(LOG_ERROR, "ECDSA Sig set failed\n"); - BN_free(r); - BN_free(s); - goto end; - } - - if (1 != ECDSA_do_verify(hash, hash_length, sig, eckey)) { - LOG(LOG_ERROR, "ECDSA Sig verification failed\n"); - goto end; - } - - ret = 0; - -end: - if (eckey) { - EC_KEY_free(eckey); - } - if (sig) { - // this method also frees BIGNUMs r and s - ECDSA_SIG_free(sig); - } - if (x) { - BN_free(x); - } - if (y) { - BN_free(y); - } - if (sig_r) { - fdo_free(sig_r); - } - if (sig_s) { - fdo_free(sig_s); - } - return ret; -} diff --git a/crypto/openssl/openssl_ECDSASignRoutines.c b/crypto/openssl/openssl_ECDSA_sign_routines.c similarity index 54% rename from crypto/openssl/openssl_ECDSASignRoutines.c rename to crypto/openssl/openssl_ECDSA_sign_routines.c index a41bd147..07da1d28 100644 --- a/crypto/openssl/openssl_ECDSASignRoutines.c +++ b/crypto/openssl/openssl_ECDSA_sign_routines.c @@ -13,7 +13,7 @@ #include #include #include -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "storage_al.h" #include "safe_lib.h" @@ -29,60 +29,79 @@ * @return 0 if true, else -1. */ int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, - unsigned char *message_signature, - size_t *signature_length) + unsigned char *message_signature, + size_t *signature_length) { int ret = -1; - EC_KEY *eckey = NULL; - unsigned char hash[SHA512_DIGEST_SIZE] = {0}; - unsigned int sig_len = 0; - size_t hash_length = 0; - ECDSA_SIG *sig = NULL; - unsigned char *sig_r = NULL; + EVP_PKEY *evpKey = NULL; + unsigned char *der_sig = NULL; + size_t der_sig_len = 0; + EVP_MD_CTX *mdctx = NULL; int sig_r_len = 0; - unsigned char *sig_s = NULL; int sig_s_len = 0; + unsigned char *sig_r = NULL; + unsigned char *sig_s = NULL; + ECDSA_SIG *sig = NULL; if (!data || !data_len || !message_signature || !signature_length) { LOG(LOG_ERROR, "fdo_cryptoECDSASign params not valid\n"); goto end; } - eckey = get_ec_key(); - if (!eckey) { - LOG(LOG_ERROR, "Failed to get the EC key\n"); + evpKey = get_evp_key(); + if (!evpKey) { + LOG(LOG_ERROR, "Failed to get the EVP EC key\n"); goto end; } - // this provides DER-encoded signature length - // the received concatenated r|s would be of lesser length - sig_len = ECDSA_size(eckey); - - /* Supplied buffer is enough ? */ - if (sig_len > *signature_length) { - LOG(LOG_ERROR, - "Supplied signature buffer is not enough, " - "supplied: %zu bytes, required: %d bytes!\n", - *signature_length, sig_len); + // Create the Message Digest Context + mdctx = EVP_MD_CTX_create(); + if (!mdctx) { + LOG(LOG_ERROR, "Failed to create message digest context\n"); goto end; } - #if defined(ECDSA256_DA) - hash_length = SHA256_DIGEST_SIZE; - if (SHA256(data, data_len, hash) == NULL) { + if (1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, evpKey)) { + LOG(LOG_ERROR, "EVP sign init failed \n"); goto end; } #elif defined(ECDSA384_DA) - hash_length = SHA384_DIGEST_SIZE; - if (SHA384(data, data_len, hash) == NULL) { + if (1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha384(), NULL, evpKey)) { + LOG(LOG_ERROR, "EVP sign init failed \n"); goto end; } #endif + if (1 != EVP_DigestSignUpdate(mdctx, data, data_len)) { + LOG(LOG_ERROR, "EVP sign update failed \n"); + goto end; + } + // First call with NULL param to obtain the DER encoded signature length + if (1 != EVP_DigestSignFinal(mdctx, NULL, &der_sig_len)) { + LOG(LOG_ERROR, "EVP sign final for size failed \n"); + goto end; + } + if (der_sig_len <= 0) { + LOG(LOG_ERROR, + "EVP_DigestSignFinal returned invalid signature length.\n"); + goto end; + } + + der_sig = fdo_alloc(der_sig_len); + if (!der_sig) { + LOG(LOG_ERROR, "Signature alloc Failed\n"); + goto end; + } + // second call with actual param to obtain the DEr encoded signature + if (1 != EVP_DigestSignFinal(mdctx, der_sig, &der_sig_len)) { + LOG(LOG_ERROR, "EVP sign final failed \n"); + goto end; + } - // ECDSA_sign return 1 on success, 0 on failure - sig = ECDSA_do_sign(hash, hash_length, eckey); - if (!sig) { - LOG(LOG_ERROR, "ECDSA signature generation failed!\n"); + // Decode DER encoded signature to convert to raw format + sig = ECDSA_SIG_new(); + const unsigned char *sig_input = der_sig; + if (!sig || d2i_ECDSA_SIG(&sig, &sig_input, der_sig_len) == NULL) { + LOG(LOG_ERROR, "DER to EC_KEY struct decoding failed!\n"); goto end; } @@ -125,13 +144,18 @@ int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, } *signature_length = sig_r_len + sig_s_len; + if (*signature_length > ECDSA_SIGNATURE_MAX_LEN) { + LOG(LOG_ERROR, "Invalid signature length\n"); + goto end; + } + if (memcpy_s(message_signature, *signature_length, (char *)sig_r, (size_t)sig_r_len) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto end; } - if (memcpy_s(message_signature + sig_r_len, *signature_length, (char *)sig_s, - (size_t)sig_s_len) != 0) { + if (memcpy_s(message_signature + sig_r_len, *signature_length, + (char *)sig_s, (size_t)sig_s_len) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto end; } @@ -141,14 +165,23 @@ int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, if (sig) { ECDSA_SIG_free(sig); } - if (eckey) { - EC_KEY_free(eckey); - } if (sig_r) { fdo_free(sig_r); } if (sig_s) { fdo_free(sig_s); } + if (der_sig) { + fdo_free(der_sig); + sig_input = NULL; + } + if (mdctx) { + EVP_MD_CTX_free(mdctx); + mdctx = NULL; + } + if (evpKey) { + EVP_PKEY_free(evpKey); + evpKey = NULL; + } return ret; } diff --git a/crypto/openssl/openssl_ECDSA_verify_routines.c b/crypto/openssl/openssl_ECDSA_verify_routines.c new file mode 100644 index 00000000..4f3a99bd --- /dev/null +++ b/crypto/openssl/openssl_ECDSA_verify_routines.c @@ -0,0 +1,213 @@ +/* + * Copyright 2020 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +/*! + * \file + * \brief Abstraction layer for ECDSA signature verification + * \ APIs of openssl library. + */ + +#include +#include +#include +#include +#include +#include "fdo_crypto_hal.h" +#include "util.h" +#include "storage_al.h" +#include "safe_lib.h" + +/** + * Verify an ECC P-256/P-384 signature using provided ECDSA Public Keys. + * @param key_encoding - encoding typee. + * @param key_algorithm - public key algorithm. + * @param message - pointer of type uint8_t, holds the encoded message. + * @param message_length - size of message, type size_t. + * @param message_signature - pointer of type uint8_t, holds a valid + * ecdsa signature in big-endian format + * @param signature_length - size of signature, type unsigned int. + * @param key_param1 - pointer of type uint8_t, holds the public key. + * @param key_param1Length - size of public key, type size_t. + * @param key_param2 - not used. + * @param key_param2Length - not used + * @return 0 if true, else -1. + +*/ +int32_t crypto_hal_sig_verify(uint8_t key_encoding, int key_algorithm, + const uint8_t *message, uint32_t message_length, + const uint8_t *message_signature, + uint32_t signature_length, + const uint8_t *key_param1, + uint32_t key_param1Length, + const uint8_t *key_param2, + uint32_t key_param2Length) +{ + int32_t ret = -1; + EVP_PKEY *eckey = NULL; + EVP_PKEY_CTX *evp_ctx = NULL; + EVP_MD_CTX *mdctx = NULL; + uint32_t group_name_nid; + const unsigned char *pub_key = (const unsigned char *)key_param1; + BIGNUM *x = NULL; + BIGNUM *y = NULL; + uint32_t der_sig_len = 0; + uint8_t *der_sig = NULL; + ECDSA_SIG *sig = NULL; + + /* Check validity of key type. */ + // Only COSEKEY and X509 are currently supported + if ((key_encoding != FDO_CRYPTO_PUB_KEY_ENCODING_X509 && + key_encoding != FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY) || + (key_algorithm != FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256 && + key_algorithm != FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384)) { + LOG(LOG_ERROR, "Incorrect key type\n"); + goto end; + } + + if (NULL == message_signature || 0 == signature_length || + 0 != (signature_length % 2) || NULL == message || + 0 == message_length) { + LOG(LOG_ERROR, "Invalid arguments!\n"); + goto end; + } + + if (key_encoding == FDO_CRYPTO_PUB_KEY_ENCODING_X509) { + + if (NULL == pub_key || 0 == key_param1Length) { + LOG(LOG_ERROR, "Invalid params!\n"); + goto end; + } + /* Unused parameter */ + (void)key_param2; + (void)key_param2Length; + + /* decode EC_KEY struct from DER encoded EC public key */ + if (d2i_PUBKEY(&eckey, &pub_key, (long)key_param1Length) == + NULL) { + LOG(LOG_ERROR, + "DER to EC_KEY struct decoding failed!\n"); + goto end; + } + } else if (key_encoding == FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY) { + /* generate required EC_KEY based on type */ + if (key_algorithm == FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256) { + group_name_nid = NID_X9_62_prime256v1; + } else { // P-384 + group_name_nid = NID_secp384r1; + } + const char *group_name = OBJ_nid2sn(group_name_nid); + evp_ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); + if (!evp_ctx) { + LOG(LOG_ERROR, "Failed to create evp ctx context \n"); + goto end; + } + + if (NULL == key_param1 || 0 == key_param1Length || + NULL == key_param2 || 0 == key_param2Length) { + LOG(LOG_ERROR, "Invalid params!\n"); + goto end; + } + /* decode EC_KEY struct using Affine X and Y co-ordinates */ + x = BN_bin2bn((const unsigned char *)key_param1, + key_param1Length, NULL); + y = BN_bin2bn((const unsigned char *)key_param2, + key_param2Length, NULL); + if (!x || !y) { + LOG(LOG_ERROR, + "Failed to convert affine-x and/or affine-y\n"); + goto end; + } + OSSL_PARAM params[] = { + OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_PUB_X, &x, sizeof(x)), + OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_PUB_Y, &y, sizeof(y)), + OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, + (char *)group_name, + strlen(group_name)), + OSSL_PARAM_END}; + if (EVP_PKEY_fromdata_init(evp_ctx) <= 0 || + EVP_PKEY_fromdata(evp_ctx, &eckey, EVP_PKEY_KEYPAIR, + params) <= 0) { + LOG(LOG_ERROR, "Failed to create EC Key from affine-x " + "and affine-y!\n"); + goto end; + } + } + + if (!(mdctx = EVP_MD_CTX_create())) { + LOG(LOG_ERROR, "Msg Digest init failed \n"); + goto end; + } + if (key_algorithm == FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256) { + if (1 != EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, + eckey)) { + LOG(LOG_ERROR, "EVP verify init failed \n"); + goto end; + } + } else { + if (1 != EVP_DigestVerifyInit(mdctx, NULL, EVP_sha384(), NULL, + eckey)) { + LOG(LOG_ERROR, "EVP verify init failed \n"); + goto end; + } + } + + if (1 != EVP_DigestVerifyUpdate(mdctx, message, message_length)) { + LOG(LOG_ERROR, "EVP verify update failed \n"); + goto end; + } + + // Convert the raw signature to DER encoded format + sig = ECDSA_SIG_new(); + BIGNUM *r = BN_bin2bn(message_signature, signature_length / 2, NULL); + BIGNUM *s = BN_bin2bn(message_signature + signature_length / 2, + signature_length / 2, NULL); + if (!sig || !r || !s || (1 != ECDSA_SIG_set0(sig, r, s))) { + LOG(LOG_ERROR, "Failure in parsing the signature \n"); + goto end; + } + der_sig_len = i2d_ECDSA_SIG(sig, NULL); + if (!der_sig_len) { + LOG(LOG_ERROR, "Failure in format conversion of signature \n"); + goto end; + } + der_sig_len = i2d_ECDSA_SIG(sig, &der_sig); + if (!der_sig_len || !der_sig) { + LOG(LOG_ERROR, "Failure in format conversion of signature \n"); + goto end; + } + + if (1 != EVP_DigestVerifyFinal(mdctx, der_sig, der_sig_len)) { + LOG(LOG_ERROR, "ECDSA Sig verification failed\n"); + goto end; + } + ret = 0; + +end: + if (eckey) { + EVP_PKEY_free(eckey); + eckey = NULL; + } + if (evp_ctx) { + EVP_PKEY_CTX_free(evp_ctx); + evp_ctx = NULL; + } + if (mdctx) { + EVP_MD_CTX_free(mdctx); + mdctx = NULL; + } + if (x) { + BN_free(x); + } + if (y) { + BN_free(y); + } + if (sig) { + ECDSA_SIG_free(sig); + } + if (der_sig) { + fdo_free(der_sig); + } + return ret; +} diff --git a/crypto/openssl/openssl_SSLRoutines.c b/crypto/openssl/openssl_SSL_routines.c similarity index 98% rename from crypto/openssl/openssl_SSLRoutines.c rename to crypto/openssl/openssl_SSL_routines.c index b46ec512..5eadcef7 100644 --- a/crypto/openssl/openssl_SSLRoutines.c +++ b/crypto/openssl/openssl_SSL_routines.c @@ -8,7 +8,7 @@ * \brief Abstraction layer for SSL setup and send/recv APIs of openssl library. */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "crypto_utils.h" #include @@ -64,7 +64,7 @@ void *fdo_ssl_setup(int sock) return (void *)ssl; err: - if(ctx) { + if (ctx) { SSL_CTX_free(ctx); ctx = NULL; } @@ -109,7 +109,7 @@ int fdo_ssl_connect(void *ssl) */ int fdo_ssl_close(void *ssl) { - if(NULL == ssl) { + if (NULL == ssl) { return -1; } @@ -135,7 +135,7 @@ int fdo_ssl_close(void *ssl) } end: SSL_free((SSL *)ssl); - if(ctx) { + if (ctx) { SSL_CTX_free(ctx); ctx = NULL; } diff --git a/crypto/openssl/openssl_cryptoSupport.c b/crypto/openssl/openssl_crypto_support.c similarity index 96% rename from crypto/openssl/openssl_cryptoSupport.c rename to crypto/openssl/openssl_crypto_support.c index ee25794b..6845d854 100644 --- a/crypto/openssl/openssl_cryptoSupport.c +++ b/crypto/openssl/openssl_crypto_support.c @@ -20,13 +20,13 @@ #include #include #include -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #ifndef SECURE_ELEMENT static bool g_random_initialised; #endif /* SECURE_ELEMENT */ -ENGINE * engine; +ENGINE *engine; int32_t inc_rollover_ctr(uint8_t *first_iv, uint8_t *new_iv, uint8_t iv_len, size_t aesblocks) @@ -244,20 +244,16 @@ int32_t crypto_close(void) * return 0 on success. -ve value on failure. */ -int32_t crypto_hal_hash(uint8_t _hash_type, const uint8_t *buffer, - size_t buffer_length, uint8_t *output, - size_t output_length) +int32_t crypto_hal_hash(int _hash_type, const uint8_t *buffer, + size_t buffer_length, uint8_t *output, + size_t output_length) { - int hash_type = FDO_CRYPTO_HASH_TYPE_USED; - - (void)_hash_type; /* Unused parameter */ - if (NULL == output || 0 == output_length || NULL == buffer || 0 == buffer_length) { return -1; } - switch (hash_type) { + switch (_hash_type) { case FDO_CRYPTO_HASH_TYPE_SHA_256: if (output_length < SHA256_DIGEST_SIZE) { return -1; diff --git a/crypto/openssl/openssl_csr.c b/crypto/openssl/openssl_csr.c index b66f7b74..6fa2f2c5 100644 --- a/crypto/openssl/openssl_csr.c +++ b/crypto/openssl/openssl_csr.c @@ -10,13 +10,14 @@ #include #include +#include #include "fdotypes.h" #include "util.h" #include "safe_lib.h" #include "ec_key.h" #include "fdocred.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" /** * crypto_hal_get_device_csr() - get the device CSR @@ -26,26 +27,29 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) int ret = -1; uint8_t *csr_data = NULL; size_t csr_size = 0; - EC_KEY *ec_key = NULL; + EVP_PKEY *evp_key = NULL; + size_t group_name_size; + char group_name[64]; + size_t pub_key_size; + fdo_byte_array_t *octet_pub_key = NULL; - const EC_GROUP *ec_grp = NULL; + EC_GROUP *ec_grp = NULL; BIO *csr_mem_bio = NULL; EC_POINT *pub_key = NULL; - const BIGNUM *privkey_bn = NULL; + BIGNUM *privkey_bn = NULL; X509_NAME *x509_name = NULL; - EVP_PKEY *ec_pkey = EVP_PKEY_new(); X509_REQ *x509_req = X509_REQ_new(); fdo_byte_array_t *csr_byte_arr = NULL; - if (!ec_pkey || !x509_req) { + if (!x509_req) { ret = -1; goto err; } /* Get the EC private key from storage */ - ec_key = get_ec_key(); - if (!ec_key) { + evp_key = get_evp_key(); + if (!evp_key) { LOG(LOG_ERROR, "Failed to load the ec key for CSR\n"); ret = -1; goto err; @@ -57,9 +61,25 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) * b. Generate a new point * c. Create the public key */ - ec_grp = EC_KEY_get0_group(ec_key); - if (!ec_grp) { - LOG(LOG_ERROR, "Failed to create a group on ec curve\n"); + EVP_PKEY_get_utf8_string_param(evp_key, OSSL_PKEY_PARAM_GROUP_NAME, + NULL, 0, &group_name_size); + if (group_name_size >= sizeof(group_name)) { + LOG(LOG_ERROR, "Unexpected long group name : %zu for EC key\n", + group_name_size); + ret = -1; + goto err; + } + if (!EVP_PKEY_get_utf8_string_param(evp_key, OSSL_PKEY_PARAM_GROUP_NAME, + group_name, sizeof(group_name), + &group_name_size)) { + LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); + ret = -1; + goto err; + } + int group_nid = OBJ_sn2nid(group_name); + ec_grp = EC_GROUP_new_by_curve_name(group_nid); + if (ec_grp == NULL) { + LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); ret = -1; goto err; } @@ -71,8 +91,8 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) goto err; } - privkey_bn = EC_KEY_get0_private_key(ec_key); - if (!privkey_bn) { + if (!EVP_PKEY_get_bn_param(evp_key, OSSL_PKEY_PARAM_PRIV_KEY, + &privkey_bn)) { LOG(LOG_ERROR, "Failed to get private key bn\n"); ret = -1; goto err; @@ -85,14 +105,35 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) goto err; } - /* Set the ec_key instance with both public/private key */ - ret = EC_KEY_set_public_key(ec_key, pub_key); - if (!ret) { - LOG(LOG_ERROR, "Failed to set the public key\n"); + pub_key_size = EC_POINT_point2oct( + ec_grp, pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); + if (!pub_key_size) { + LOG(LOG_ERROR, "Failed to get public key size\n"); ret = -1; goto err; } + octet_pub_key = fdo_byte_array_alloc(pub_key_size); + if (!octet_pub_key) { + LOG(LOG_ERROR, "Alloc failed!\n"); + ret = -1; + goto err; + } + if (!EC_POINT_point2oct(ec_grp, pub_key, POINT_CONVERSION_UNCOMPRESSED, + octet_pub_key->bytes, octet_pub_key->byte_sz, + NULL)) { + LOG(LOG_ERROR, "Failed to process public key\n"); + ret = -1; + goto err; + } + // Set the evp_key instance with public key + if (!EVP_PKEY_set_octet_string_param( + evp_key, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, + octet_pub_key->bytes, octet_pub_key->byte_sz)) { + LOG(LOG_ERROR, "Failed to set the public key\n"); + ret = -1; + goto err; + } /* Fill in the the data associated with this device */ x509_name = X509_REQ_get_subject_name(x509_req); if (!x509_name) { @@ -117,15 +158,8 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) goto err; } - ret = EVP_PKEY_assign_EC_KEY(ec_pkey, ec_key); - if (!ret) { - LOG(LOG_ERROR, "Failed to get ec_key reference\n"); - ret = -1; - goto err; - } - /* Set the public key on the CSR */ - ret = X509_REQ_set_pubkey(x509_req, ec_pkey); + ret = X509_REQ_set_pubkey(x509_req, evp_key); if (!ret) { LOG(LOG_ERROR, "Failed to set the public key in CSR\n"); ret = -1; @@ -133,7 +167,7 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) } /* Sign to generate the final CSR */ - ret = X509_REQ_sign(x509_req, ec_pkey, EVP_sha256()); + ret = X509_REQ_sign(x509_req, evp_key, EVP_sha256()); if (!ret) { LOG(LOG_ERROR, "Failed to generate CSR data\n"); ret = -1; @@ -193,16 +227,21 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) if (csr_mem_bio) { BIO_free(csr_mem_bio); } - if (ec_pkey) { - EVP_PKEY_free(ec_pkey); - ec_key = NULL; // evp_pkey_free clears attached ec_key too - } - if (ec_key) { - EC_KEY_free(ec_key); + if (evp_key) { + EVP_PKEY_free(evp_key); } if (pub_key) { EC_POINT_free(pub_key); } + if (ec_grp) { + EC_GROUP_free(ec_grp); + } + if (octet_pub_key) { + fdo_byte_array_free(octet_pub_key); + } + if (privkey_bn) { + BN_clear_free(privkey_bn); + } if (x509_req) { X509_REQ_free(x509_req); } diff --git a/crypto/openssl/openssl_key_exchange_ecdh.c b/crypto/openssl/openssl_key_exchange_ecdh.c index 2f0d5f72..d500655a 100644 --- a/crypto/openssl/openssl_key_exchange_ecdh.c +++ b/crypto/openssl/openssl_key_exchange_ecdh.c @@ -10,11 +10,12 @@ */ #include "util.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "crypto_utils.h" #include "BN_support.h" #include "openssl/ec.h" #include "openssl/objects.h" +#include "openssl/core_names.h" #include "safe_lib.h" #define DECLARE_BIGNUM(bn) bignum_t *bn @@ -29,10 +30,11 @@ typedef struct { DECLARE_BIGNUM(_Device_random); DECLARE_BIGNUM(_publicA); /* The server's A public value */ - EC_KEY *_key; + uint32_t group_name_nid; + EVP_PKEY *_key; - const DECLARE_BIGNUM(_secretb); /* Out bit secret */ - DECLARE_BIGNUM(_publicB); /* Our B public value */ + DECLARE_BIGNUM(_secretb); /* Out bit secret */ + DECLARE_BIGNUM(_publicB); /* Our B public value */ DECLARE_BIGNUM(_shared_secret); uint8_t *_pubB; uint8_t _publicB_length; @@ -49,7 +51,6 @@ static bool compute_publicBECDH(ecdh_context_t *key_ex_data); int32_t crypto_hal_kex_init(void **context) { ecdh_context_t *key_ex_data = NULL; - EC_KEY *key = NULL; if (!context) { LOG(LOG_ERROR, "Invalid parameters\n"); @@ -77,19 +78,13 @@ int32_t crypto_hal_kex_init(void **context) goto error; } - key = EC_KEY_new_by_curve_name(KEY_CURVE); + key_ex_data->group_name_nid = KEY_CURVE; + /* Generate Device Random bits(384) */ if (bn_rand(key_ex_data->_Device_random, BN_RANDOM_SIZE)) { goto error; } - if (key == NULL) { - LOG(LOG_ERROR, "failed to get the curve parameters\n"); - goto error; - } - - key_ex_data->_key = key; - if (compute_publicBECDH(key_ex_data) == false) { goto error; } @@ -127,11 +122,14 @@ int32_t crypto_hal_kex_close(void **context) if (key_ex_data->_shared_secret) { BN_clear_free(key_ex_data->_shared_secret); } + if (key_ex_data->_secretb) { + BN_clear_free(key_ex_data->_secretb); + } if (key_ex_data->_Device_random) { BN_clear_free(key_ex_data->_Device_random); } if (key_ex_data->_key != NULL) { - EC_KEY_free(key_ex_data->_key); + EVP_PKEY_free(key_ex_data->_key); key_ex_data->_key = NULL; } if (key_ex_data->_pubB) { @@ -151,10 +149,7 @@ static bool compute_publicBECDH(ecdh_context_t *key_ex_data) { BN_CTX *ctx = NULL; - const EC_GROUP *group = NULL; - EC_KEY *key = NULL; - - const EC_POINT *point = NULL; + EC_GROUP *group = NULL; BIGNUM *x = NULL, *y = NULL; unsigned char *temp = NULL; int size = 0; @@ -180,64 +175,48 @@ static bool compute_publicBECDH(ecdh_context_t *key_ex_data) goto exit; } - key = key_ex_data->_key; - if (!key) { - LOG(LOG_ERROR, "EC key is wrong\n"); - goto exit; - } - group = EC_KEY_get0_group(key); - if (!group) { - LOG(LOG_ERROR, "EC group get failed\n"); + group = EC_GROUP_new_by_curve_name(key_ex_data->group_name_nid); + if (group == NULL) { + LOG(LOG_ERROR, "Failed to get the EC group\n"); goto exit; } /* generate the public key and private key */ - if (EC_KEY_generate_key(key) == 0) { + key_ex_data->_key = EVP_EC_gen(OBJ_nid2sn(key_ex_data->group_name_nid)); + if (!key_ex_data->_key) { LOG(LOG_ERROR, "EC key generation failed\n"); goto exit; } /* Store the private key */ - key_ex_data->_secretb = EC_KEY_get0_private_key(key); - if (!key_ex_data->_secretb) { + if (!EVP_PKEY_get_bn_param(key_ex_data->_key, OSSL_PKEY_PARAM_PRIV_KEY, + &(key_ex_data->_secretb))) { LOG(LOG_ERROR, "EC private key get failed\n"); goto exit; } - /* Get the public key */ - point = EC_KEY_get0_public_key(key); - if (!point) { - LOG(LOG_ERROR, "EC public key get failed\n"); - goto exit; - } - if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y, ctx) == 0) { + /* Get the public key co-ordinates in x and y*/ + if (!EVP_PKEY_get_bn_param(key_ex_data->_key, OSSL_PKEY_PARAM_EC_PUB_X, + &x) || + !EVP_PKEY_get_bn_param(key_ex_data->_key, OSSL_PKEY_PARAM_EC_PUB_Y, + &y)) { LOG(LOG_ERROR, "EC cordinate get failed\n"); goto exit; } #if LOG_LEVEL == LOG_MAX_LEVEL /* Print the co-ordinates */ - char *hexbuf1 = BN_bn2hex(x); - - LOG(LOG_DEBUG, "Bx %s : bytes %d, %s\n", - BN_is_negative(x) ? "Negative" : "Positive", bn_num_bytes(x), - hexbuf1); - OPENSSL_free(hexbuf1); - char *hexbuf2 = BN_bn2hex(y); + LOG(LOG_DEBUG, "Bx %s : bytes %d\n", + BN_is_negative(x) ? "Negative" : "Positive", bn_num_bytes(x)); - LOG(LOG_DEBUG, "By %s : bytes %d, %s\n", - BN_is_negative(y) ? "Negative" : "Positive", bn_num_bytes(y), - hexbuf2); - OPENSSL_free(hexbuf2); + LOG(LOG_DEBUG, "By %s : bytes %d\n", + BN_is_negative(y) ? "Negative" : "Positive", bn_num_bytes(y)); - char *hexbuf3 = BN_bn2hex(key_ex_data->_Device_random); - - LOG(LOG_DEBUG, "Device Random %s : bytes %d, %s\n", + LOG(LOG_DEBUG, "Device Random %s : bytes %d\n", BN_is_negative(key_ex_data->_Device_random) ? "Negative" : "Positive", - bn_num_bytes(key_ex_data->_Device_random), hexbuf3); - OPENSSL_free(hexbuf3); + bn_num_bytes(key_ex_data->_Device_random)); #endif /* 2byte for each blen 3x2 =6 */ @@ -294,17 +273,18 @@ static bool compute_publicBECDH(ecdh_context_t *key_ex_data) hexdump("_publicB::", key_ex_data->_publicB, key_ex_data->_publicB_length); { - char *hexbuf = BN_bn2hex(key_ex_data->_publicB); - LOG(LOG_DEBUG, "key_ex_data->_publicB %s : bytes %d, %s\n", + LOG(LOG_DEBUG, "key_ex_data->_publicB %s : bytes %d\n", BN_is_negative(key_ex_data->_publicB) ? "Negative" : "Positive", - bn_num_bytes(key_ex_data->_publicB), hexbuf); - OPENSSL_free(hexbuf); + bn_num_bytes(key_ex_data->_publicB)); } #endif ret = true; exit: + if (group) { + EC_GROUP_free(group); + } if (temp) { fdo_free(temp); } @@ -383,10 +363,9 @@ int32_t crypto_hal_set_peer_random(void *context, int size = 0; BIGNUM *Ax_bn = NULL, *Ay_bn = NULL, *owner_random_bn = NULL; BIGNUM *Shx_bn = NULL, *Shy_bn = NULL; - const EC_GROUP *group = NULL; + EC_GROUP *group = NULL; EC_POINT *point = NULL; EC_POINT *Sh_se_point = NULL; - EC_KEY *key = NULL; int ret = -1; Ax_bn = BN_new(); @@ -404,25 +383,20 @@ int32_t crypto_hal_set_peer_random(void *context, LOG(LOG_DEBUG, "set_publicA : bytes : %u\n", peer_rand_length); hexdump("Public A", peer_rand_value, peer_rand_length); /* Display public - B */ - char *hexbuf = BN_bn2hex(key_ex_data->_publicB); - LOG(LOG_DEBUG, "key_ex_data->_publicB %s : bytes %d, 0x%s\n", + LOG(LOG_DEBUG, "key_ex_data->_publicB %s : bytes %d\n", BN_is_negative(key_ex_data->_publicB) ? "Negative" : "Positive", - bn_num_bytes(key_ex_data->_publicB), hexbuf); - OPENSSL_free(hexbuf); + bn_num_bytes(key_ex_data->_publicB)); #endif bn_bin2bn(peer_rand_value, peer_rand_length, key_ex_data->_publicA); #if LOG_LEVEL == LOG_MAX_LEVEL /* Display Public - A */ - char *hexbuf1 = BN_bn2hex(key_ex_data->_publicA); - LOG(LOG_DEBUG, "Device Received: key_ex_data->_publicA %s : " - "bytes %d, 0x%s\n", + "bytes %d\n", BN_is_negative(key_ex_data->_publicA) ? "Negative" : "Positive", - bn_num_bytes(key_ex_data->_publicA), hexbuf1); - OPENSSL_free(hexbuf1); + bn_num_bytes(key_ex_data->_publicA)); #endif temp = peer_rand_value; @@ -443,24 +417,18 @@ int32_t crypto_hal_set_peer_random(void *context, BN_bin2bn(&temp[size], size_owner_random, owner_random_bn); #if LOG_LEVEL == LOG_MAX_LEVEL - char *hexbuf2 = BN_bn2hex(Ax_bn); - LOG(LOG_DEBUG, "Device Reveived: Ax %s : bytes %d, %s\n", + LOG(LOG_DEBUG, "Device Reveived: Ax %s : bytes %d\n", BN_is_negative(Ax_bn) ? "Negative" : "Positive", - bn_num_bytes(Ax_bn), hexbuf2); - OPENSSL_free(hexbuf2); - char *hexbuf3 = BN_bn2hex(Ay_bn); + bn_num_bytes(Ax_bn)); - LOG(LOG_DEBUG, "Device Received: Ay %s : bytes %d, %s\n", + LOG(LOG_DEBUG, "Device Received: Ay %s : bytes %d\n", BN_is_negative(Ay_bn) ? "Negative" : "Positive", - bn_num_bytes(Ay_bn), hexbuf3); - OPENSSL_free(hexbuf3); - char *hexbuf4 = BN_bn2hex(owner_random_bn); + bn_num_bytes(Ay_bn)); - LOG(LOG_DEBUG, "Device Reveived: Owner Random %s : bytes %d, %s\n", + LOG(LOG_DEBUG, "Device Reveived: Owner Random %s : bytes %d\n", BN_is_negative(owner_random_bn) ? "Negative" : "Positive", - bn_num_bytes(owner_random_bn), hexbuf4); - OPENSSL_free(hexbuf4); + bn_num_bytes(owner_random_bn)); #endif ctx = BN_CTX_new(); if (!ctx) { @@ -468,14 +436,17 @@ int32_t crypto_hal_set_peer_random(void *context, goto error; } - key = key_ex_data->_key; - group = EC_KEY_get0_group(key); + group = EC_GROUP_new_by_curve_name(key_ex_data->group_name_nid); + if (group == NULL) { + LOG(LOG_ERROR, "Failed to get the EC group\n"); + goto error; + } point = EC_POINT_new(group); - if (group == NULL || point == NULL || key == NULL) { + if (group == NULL || point == NULL) { LOG(LOG_ERROR, "Error curve parameters are NULL\n"); goto error; } - EC_POINT_set_affine_coordinates_GFp(group, point, Ax_bn, Ay_bn, ctx); + EC_POINT_set_affine_coordinates(group, point, Ax_bn, Ay_bn, ctx); shx = fdo_alloc(bn_num_bytes(Ax_bn)); if (!shx) { goto error; @@ -505,8 +476,8 @@ int32_t crypto_hal_set_peer_random(void *context, EC_POINT_free(Sh_se_point); goto error; } - if (EC_POINT_get_affine_coordinates_GFp(group, Sh_se_point, Shx_bn, - Shy_bn, ctx) == 0) { + if (EC_POINT_get_affine_coordinates(group, Sh_se_point, Shx_bn, Shy_bn, + ctx) == 0) { EC_POINT_free(Sh_se_point); goto error; } @@ -549,6 +520,9 @@ int32_t crypto_hal_set_peer_random(void *context, ret = 0; error: + if (group) { + EC_GROUP_free(group); + } if (point) { EC_POINT_free(point); } diff --git a/crypto/openssl/tpm20_ECDSASignRoutines.c b/crypto/openssl/tpm20_ECDSASignRoutines.c deleted file mode 100644 index 5ca82d96..00000000 --- a/crypto/openssl/tpm20_ECDSASignRoutines.c +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2020 Intel Corporation - * SPDX-License-Identifier: Apache 2.0 - */ - -/*! - * \file - * \ brief Abstraction layer for ECDSA signing routine using - * \ tpm2.0(tpm-tss & tpm-tss-engine) and openssl library. - */ - -#include -#include -#include -#include -#include "safe_lib.h" -#include "util.h" -#include "fdoCryptoHal.h" - -/** - * Sign a message using provided ECDSA Private Keys. - * @param data - pointer of type uint8_t, holds the plaintext message. - * @param data_len - size of message, type size_t. - * @param message_signature - pointer of type unsigned char, which will be - * by filled with signature. - * @param signature_length - size of signature, pointer of type size_t. - * @return 0 if success, else -1. - */ -int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, - unsigned char *message_signature, - size_t *signature_length) -{ - int32_t ret = -1; - const char *engine_id = "dynamic"; - EVP_PKEY *pkey = NULL; - EC_KEY *eckey = NULL; - ECDSA_SIG *sig = NULL; - uint8_t digest[SHA384_DIGEST_SIZE] = {0}; - ENGINE *engine = NULL; - size_t hash_length = 0; - unsigned char *sig_r = NULL; - int sig_r_len = 0; - unsigned char *sig_s = NULL; - int sig_s_len = 0; - - if (!data || !data_len || !message_signature || !signature_length) { - LOG(LOG_ERROR, "Invalid Parameters received."); - goto error; - } -#if defined(ECDSA256_DA) - hash_length = SHA256_DIGEST_SIZE; - if (SHA256(data, data_len, digest) == NULL) { - LOG(LOG_DEBUG, "SHA256 digest generation failed."); - goto error; - } -#elif defined(ECDSA384_DA) - hash_length = SHA384_DIGEST_SIZE; - if (SHA384(data, data_len, digest) == NULL) { - LOG(LOG_DEBUG, "SHA384 digest generation failed."); - goto error; - } -#endif - - ENGINE_load_dynamic(); - - engine = ENGINE_by_id(engine_id); - if (engine == NULL) { - LOG(LOG_ERROR, "Could not find external engine.\n"); - goto error; - } - - if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", TPM2_TSS_ENGINE_SO_PATH, - 0)) { - LOG(LOG_ERROR, "Could not set TPM Engine path.\n"); - goto error; - } - - if (!ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0)) { - LOG(LOG_ERROR, "Could not load TPM engine.\n"); - goto error; - } - - LOG(LOG_DEBUG, "TPM Engine successfully loaded.\n"); - - if (!ENGINE_init(engine)) { - LOG(LOG_ERROR, "Could not initialize TPM engine.\n"); - goto error; - } - - pkey = - ENGINE_load_private_key(engine, TPM_ECDSA_DEVICE_KEY, NULL, NULL); - if (NULL == pkey) { - LOG(LOG_DEBUG, - "Could not load private Key in TPM Engine format.\n"); - goto error; - } - - LOG(LOG_DEBUG, - "Private key successfully loaded in TPM Engine format.\n"); - - eckey = EVP_PKEY_get1_EC_KEY(pkey); - if (NULL == eckey) { - LOG(LOG_DEBUG, "Could not Load ECC Key.\n"); - goto error; - } - - LOG(LOG_DEBUG, "ECDSA signature generation - " - "ECC key successfully loaded.\n"); - - sig = ECDSA_do_sign(digest, hash_length, eckey); - if (!sig) { - LOG(LOG_DEBUG, "Failed to generate ECDSA signature.\n"); - goto error; - } - - // both r and s are maintained by sig, no need to free explicitly - const BIGNUM *r = ECDSA_SIG_get0_r(sig); - const BIGNUM *s = ECDSA_SIG_get0_s(sig); - if (!r || !s) { - LOG(LOG_ERROR, "Failed to read r and/or s\n"); - goto error; - } - - sig_r_len = BN_num_bytes(r); - if (sig_r_len <= 0) { - LOG(LOG_ERROR, "Sig r len invalid\n"); - goto error; - } - sig_r = fdo_alloc(sig_r_len); - if (!sig_r) { - LOG(LOG_ERROR, "Sig r alloc Failed\n"); - goto error; - } - if (BN_bn2bin(r, sig_r) <= 0) { - LOG(LOG_ERROR, "Sig r conversion Failed\n"); - goto error; - } - - sig_s_len = BN_num_bytes(s); - if (sig_r_len <= 0) { - LOG(LOG_ERROR, "Sig s len invalid\n"); - goto error; - } - sig_s = fdo_alloc(sig_s_len); - if (!sig_s) { - LOG(LOG_ERROR, "Sig s alloc Failed\n"); - goto error; - } - if (BN_bn2bin(s, sig_s) <= 0) { - LOG(LOG_ERROR, "Sig s conversion Failed\n"); - goto error; - } - - *signature_length = sig_r_len + sig_s_len; - if (memcpy_s(message_signature, *signature_length, (char *)sig_r, - (size_t)sig_r_len) != 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto error; - } - if (memcpy_s(message_signature + sig_r_len, *signature_length, (char *)sig_s, - (size_t)sig_s_len) != 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto error; - } - - ret = 0; - -error: - if (engine) { - ENGINE_finish(engine); - ENGINE_free(engine); - ENGINE_cleanup(); - } - if (pkey) { - EVP_PKEY_free(pkey); - } - if (eckey) { - EC_KEY_free(eckey); - } - if (sig) { - ECDSA_SIG_free(sig); - } - if (sig_r) { - fdo_free(sig_r); - } - if (sig_s) { - fdo_free(sig_s); - } - return ret; -} diff --git a/crypto/openssl/tpm20_ECDSA_sign_routines.c b/crypto/openssl/tpm20_ECDSA_sign_routines.c new file mode 100644 index 00000000..738b3fd2 --- /dev/null +++ b/crypto/openssl/tpm20_ECDSA_sign_routines.c @@ -0,0 +1,162 @@ +/* + * Copyright 2020 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +/*! + * \file + * \ brief Abstraction layer for ECDSA signing routine using + * \ tpm2.0(tpm-tss & tpm-tss-engine) and openssl library. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "safe_lib.h" +#include "util.h" +#include "fdo_crypto_hal.h" +#include "tpm20_Utils.h" +#include "tpm2_nv_storage.h" + +/** + * Sign a message using provided ECDSA Private Keys. + * @param data - pointer of type uint8_t, holds the plaintext message. + * @param data_len - size of message, type size_t. + * @param message_signature - pointer of type unsigned char, which will be + * by filled with signature. + * @param signature_length - size of signature, pointer of type size_t. + * @return 0 if success, else -1. + */ +int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, + unsigned char *message_signature, + size_t *signature_length) +{ + + int32_t ret = -1; + TSS2_RC ret_val = TPM2_RC_FAILURE; + ESYS_CONTEXT *esys_context = NULL; + ESYS_TR primary_key_handle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + ESYS_TR tpm_ec_key_handle = ESYS_TR_NONE; + int sig_r_len = 0; + int sig_s_len = 0; + TPM2B_DIGEST *digest = NULL; + TPMT_TK_HASHCHECK *validation = NULL; + TPMT_SIGNATURE *signature = NULL; + TPM2B_MAX_BUFFER input_data; + // Set the signature scheme to ECDSA with SHA256 + TPMT_SIG_SCHEME inScheme = { + .scheme = TPM2_ALG_ECDSA, + .details = {.rsapss = {.hashAlg = FDO_TPM2_ALG_SHA}}}; + + if (!data || !data_len || !message_signature || !signature_length) { + LOG(LOG_ERROR, "Invalid Parameters received."); + goto error; + } + + input_data.size = data_len; + if (memcpy_s(input_data.buffer, input_data.size, (char *)data, + (size_t)data_len) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto error; + } + + if (0 != fdoTPMGenerate_primary_key_context(&esys_context, + &primary_key_handle, + &auth_session_handle)) { + LOG(LOG_ERROR, + "Failed to create primary key context from TPM.\n"); + goto error; + } + + ret_val = Esys_TR_FromTPMPublic( + esys_context, TPM_DEVICE_KEY_PERSISTANT_HANDLE, ESYS_TR_NONE, + ESYS_TR_NONE, ESYS_TR_NONE, &tpm_ec_key_handle); + + if (ret_val != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to load EC Key Context.\n"); + goto error; + } + + ret_val = Esys_Hash(esys_context, ESYS_TR_NONE, ESYS_TR_NONE, + ESYS_TR_NONE, &input_data, FDO_TPM2_ALG_SHA, + ESYS_TR_RH_OWNER, &digest, &validation); + if (ret_val != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to create hash.\n"); + goto error; + } + ret_val = Esys_Sign(esys_context, tpm_ec_key_handle, + auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, + digest, &inScheme, validation, &signature); + if (ret_val != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to create Sign Key.\n"); + goto error; + } + + sig_r_len = signature->signature.ecdsa.signatureR.size; + if (sig_r_len <= 0) { + LOG(LOG_ERROR, "Sig r len invalid\n"); + goto error; + } + + sig_s_len = signature->signature.ecdsa.signatureS.size; + if (sig_r_len <= 0) { + LOG(LOG_ERROR, "Sig s len invalid\n"); + goto error; + } + + *signature_length = sig_r_len + sig_s_len; + if (*signature_length > ECDSA_SIGNATURE_MAX_LEN) { + LOG(LOG_ERROR, "Invalid signature length\n"); + goto error; + } + + if (memcpy_s(message_signature, *signature_length, + (char *)signature->signature.ecdsa.signatureR.buffer, + (size_t)sig_r_len) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto error; + } + if (memcpy_s(message_signature + sig_r_len, *signature_length, + (char *)signature->signature.ecdsa.signatureS.buffer, + (size_t)sig_s_len) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto error; + } + ret = 0; + +error: + if (esys_context) { + if (tpm_ec_key_handle != ESYS_TR_NONE) { + if (Esys_TR_Close(esys_context, &tpm_ec_key_handle) != + TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, + "Failed to flush HMAC key handle.\n"); + ret = -1; + } else { + LOG(LOG_DEBUG, + "HMAC key handle flushed successfully.\n"); + tpm_ec_key_handle = ESYS_TR_NONE; + } + } + if (0 != fdoTPMTSSContext_clean_up(&esys_context, + &auth_session_handle, + &primary_key_handle)) { + LOG(LOG_ERROR, + "Failed to tear down all the TSS context.\n"); + ret = -1; + } else { + LOG(LOG_DEBUG, "TSS context flushed successfully.\n"); + } + } + + TPM2_ZEROISE_FREE(digest); + TPM2_ZEROISE_FREE(validation); + TPM2_ZEROISE_FREE(signature); + + return ret; +} \ No newline at end of file diff --git a/crypto/openssl/tpm20_Utils.c b/crypto/openssl/tpm20_Utils.c index 6b1ac664..ed680caf 100644 --- a/crypto/openssl/tpm20_Utils.c +++ b/crypto/openssl/tpm20_Utils.c @@ -10,51 +10,36 @@ */ #include "util.h" #include "safe_lib.h" +#include "tpm2_nv_storage.h" #include "tpm20_Utils.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "storage_al.h" -static int32_t fdoTPMEsys_context_init(ESYS_CONTEXT **esys_context); -static int32_t fdoTPMEsys_auth_session_init(ESYS_CONTEXT *esys_context, - ESYS_TR *session_handle); -static int32_t fdoTPMTSSContext_clean_up(ESYS_CONTEXT **esys_context, - ESYS_TR *auth_session_handle, - ESYS_TR *primary_handle); -static int32_t fdoTPMGenerate_primary_key_context(ESYS_CONTEXT **esys_context, - ESYS_TR *primary_handle, - ESYS_TR *auth_session_handle); - /** * Generates HMAC using TPM * * @param data: pointer to the input data * @param data_length: length of the input data * @param hmac: output buffer to save the HMAC - * @param hmac_length: length of the output HMAC buffer, equal to the SHA256 + * @param hmac_length: length of the output HMAC buffer *hash length - * @param tpmHMACPub_key: File name of the TPM HMAC public key - * @param tpmHMACPriv_key: File name of the TPM HMAC private key + * @param persistent_handle: Persistent handle of the TPM HMAC public key * @return * 0, on success * -1, on failure */ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, - size_t hmac_length, char *tpmHMACPub_key, - char *tpmHMACPriv_key) + size_t hmac_length, + TPMI_DH_PERSISTENT persistent_handle) { - int32_t ret = -1, ret_val = -1, file_size = 0; + int32_t ret = -1, ret_val = -1; size_t hashed_length = 0; - size_t offset = 0; - uint8_t bufferTPMHMACPriv_key[TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_160] = {0}; - uint8_t bufferTPMHMACPub_key[TPM_HMAC_PUB_KEY_CONTEXT_SIZE] = {0}; ESYS_CONTEXT *esys_context = NULL; ESYS_TR primary_key_handle = ESYS_TR_NONE; ESYS_TR auth_session_handle = ESYS_TR_NONE; ESYS_TR hmac_key_handle = ESYS_TR_NONE; ESYS_TR sequence_handle = ESYS_TR_NONE; TPMT_TK_HASHCHECK *validation = NULL; - TPM2B_PUBLIC unmarshalHMACPub_key = {0}; - TPM2B_PRIVATE unmarshalHMACPriv_key = {0}; TPM2B_DIGEST *outHMAC = NULL; TPM2B_MAX_BUFFER block = {0}; TPM2B_AUTH null_auth = {0}; @@ -63,8 +48,8 @@ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, /* Validating all input parameters are passed in the function call*/ - if (!data || !data_length || !tpmHMACPub_key || !tpmHMACPriv_key || - !hmac || (hmac_length != SHA256_DIGEST_SIZE)) { + if (!data || !data_length || !persistent_handle || !hmac || + (hmac_length != PLATFORM_HMAC_SIZE)) { LOG(LOG_ERROR, "Failed to generate HMAC from TPM, invalid parameter" " received.\n"); @@ -85,86 +70,12 @@ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, LOG(LOG_DEBUG, "TPM Primary Key Context created successfully.\n"); - /* Unmarshalling the HMAC Private key from the HMAC Private key file*/ - - file_size = get_file_size(tpmHMACPriv_key); - - if (file_size != TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_128 && - file_size != TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_160) { - LOG(LOG_ERROR, "TPM HMAC Private Key file size incorrect.\n"); - goto err; - } - - LOG(LOG_DEBUG, - "TPM HMAC Private Key file size retreived successfully.\n"); - - ret_val = read_buffer_from_file(tpmHMACPriv_key, bufferTPMHMACPriv_key, - file_size); - - if (ret_val != 0) { - LOG(LOG_ERROR, - "Failed to load TPM HMAC Private Key into buffer.\n"); - goto err; - } - - LOG(LOG_DEBUG, "TPM HMAC Private Key file content copied successfully" - " to buffer.\n"); - - ret_val = Tss2_MU_TPM2B_PRIVATE_Unmarshal( - bufferTPMHMACPriv_key, file_size, &offset, &unmarshalHMACPriv_key); - - if (ret_val != TSS2_RC_SUCCESS) { - LOG(LOG_ERROR, "Failed to unmarshal TPM HMAC Private Key.\n"); - goto err; - } - - LOG(LOG_DEBUG, - "TPM HMAC Private Key Unmarshal complete successfully.\n"); - - /* Unmarshalling the HMAC Public key from the HMAC public key file*/ - - file_size = get_file_size(tpmHMACPub_key); - - if (file_size != TPM_HMAC_PUB_KEY_CONTEXT_SIZE) { - LOG(LOG_ERROR, "TPM HMAC Private Key file size incorrect.\n"); - goto err; - } - - LOG(LOG_DEBUG, - "TPM HMAC Public Key file size retreived successfully.\n"); - - ret_val = read_buffer_from_file(tpmHMACPub_key, bufferTPMHMACPub_key, - file_size); - - if (ret_val != 0) { - LOG(LOG_ERROR, - "Failed to load TPM HMAC Public key into buffer.\n"); - goto err; - } - - LOG(LOG_DEBUG, "TPM HMAC Public Key file content copied successfully" - " to buffer.\n"); - - offset = 0; - - ret_val = Tss2_MU_TPM2B_PUBLIC_Unmarshal( - bufferTPMHMACPub_key, file_size, &offset, &unmarshalHMACPub_key); - - if (ret_val != TSS2_RC_SUCCESS) { - LOG(LOG_ERROR, "Failed to unmarshal TPM HMAC Public Key.\n"); - goto err; - } - - LOG(LOG_DEBUG, - "TPM HMAC Public Key Unmarshal complete successfully.\n"); - /* Loading the TPM Primary key, HMAC public key and HMAC Private Key to * generate the HMAC Key Context */ ret_val = - Esys_Load(esys_context, primary_key_handle, auth_session_handle, - ESYS_TR_NONE, ESYS_TR_NONE, &unmarshalHMACPriv_key, - &unmarshalHMACPub_key, &hmac_key_handle); + Esys_TR_FromTPMPublic(esys_context, persistent_handle, ESYS_TR_NONE, + ESYS_TR_NONE, ESYS_TR_NONE, &hmac_key_handle); if (ret_val != TSS2_RC_SUCCESS) { LOG(LOG_ERROR, "Failed to load HMAC Key Context.\n"); @@ -192,7 +103,7 @@ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, ret_val = Esys_HMAC(esys_context, hmac_key_handle, auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, - &block, TPM2_ALG_SHA256, &outHMAC); + &block, FDO_TPM2_ALG_SHA, &outHMAC); if (ret_val != TSS2_RC_SUCCESS) { LOG(LOG_ERROR, "Failed to create HMAC.\n"); @@ -206,7 +117,7 @@ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, ret_val = Esys_HMAC_Start(esys_context, hmac_key_handle, auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, &null_auth, - TPM2_ALG_SHA256, &sequence_handle); + FDO_TPM2_ALG_SHA, &sequence_handle); if (ret_val != TSS2_RC_SUCCESS) { LOG(LOG_ERROR, "Failed to create HMAC.\n"); @@ -313,7 +224,7 @@ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, err: if (esys_context) { if (hmac_key_handle != ESYS_TR_NONE) { - if (Esys_FlushContext(esys_context, hmac_key_handle) != + if (Esys_TR_Close(esys_context, &hmac_key_handle) != TSS2_RC_SUCCESS) { LOG(LOG_ERROR, "Failed to flush HMAC key handle.\n"); @@ -336,10 +247,6 @@ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, } TPM2_ZEROISE_FREE(validation); TPM2_ZEROISE_FREE(outHMAC); - memset_s(&unmarshalHMACPriv_key, sizeof(unmarshalHMACPriv_key), 0); - memset_s(&unmarshalHMACPub_key, sizeof(unmarshalHMACPub_key), 0); - memset_s(bufferTPMHMACPriv_key, sizeof(bufferTPMHMACPriv_key), 0); - memset_s(bufferTPMHMACPub_key, sizeof(bufferTPMHMACPub_key), 0); return ret; } @@ -347,19 +254,21 @@ int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, /** * Generates HMAC Key inside TPM * - * @param tpmHMACPub_key: File name of the TPM HMAC public key - * @param tpmHMACPriv_key: File name of the TPM HMAC private key + * @param persistent_handle: Persistent handle of the TPM HMAC key * @return * 0, on success * -1, on failure */ -int32_t fdo_tpm_generate_hmac_key(char *tpmHMACPub_key, char *tpmHMACPriv_key) +int32_t fdo_tpm_generate_hmac_key(TPMI_DH_PERSISTENT persistent_handle) { int32_t ret = -1; TSS2_RC ret_val = TPM2_RC_FAILURE; ESYS_CONTEXT *esys_context = NULL; ESYS_TR primary_key_handle = ESYS_TR_NONE; ESYS_TR auth_session_handle = ESYS_TR_NONE; + ESYS_TR object_handle = ESYS_TR_NONE; + ESYS_TR pub_object_handle = ESYS_TR_NONE; + ESYS_TR persistentHandle = ESYS_TR_NONE; TPM2B_PUBLIC *out_public = NULL; TPM2B_PRIVATE *out_private = NULL; TPM2B_CREATION_DATA *creation_data = NULL; @@ -371,25 +280,13 @@ int32_t fdo_tpm_generate_hmac_key(char *tpmHMACPub_key, char *tpmHMACPriv_key) TPML_PCR_SELECTION creationPCR = {0}; /* Using same buffer for both public and private context, private context size > public context size */ - uint8_t buffer[TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_160] = {0}; - size_t offset = 0; - if (!tpmHMACPub_key || !tpmHMACPriv_key) { + if (!persistent_handle) { LOG(LOG_ERROR, "Failed to generate HMAC Key," "invalid parameters received.\n"); goto err; } - if ((file_exists(tpmHMACPub_key) && !remove(tpmHMACPub_key)) && - (file_exists(tpmHMACPriv_key) && !remove(tpmHMACPriv_key))) { - LOG(LOG_DEBUG, "Successfully deleted old HMAC key.\n"); - } else if (file_exists(tpmHMACPub_key) || - file_exists(tpmHMACPriv_key)) { - LOG(LOG_DEBUG, "HMAC key generation failed," - "failed to delete the old HMAC key.\n"); - goto err; - } - if (0 != fdoTPMGenerate_primary_key_context(&esys_context, &primary_key_handle, &auth_session_handle)) { @@ -409,38 +306,62 @@ int32_t fdo_tpm_generate_hmac_key(char *tpmHMACPub_key, char *tpmHMACPriv_key) goto err; } - ret_val = Tss2_MU_TPM2B_PUBLIC_Marshal(out_public, buffer, - sizeof(buffer), &offset); + ret_val = Esys_Load(esys_context, primary_key_handle, + auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, + out_private, out_public, &object_handle); if (ret_val != TSS2_RC_SUCCESS) { - LOG(LOG_ERROR, - "Failed to serialize the public HMAC key context.\n"); + LOG(LOG_ERROR, "Esys_Load failed: 0x%x\n", ret_val); + Esys_Finalize(&esys_context); goto err; } - if ((int32_t)offset != - fdo_blob_write(tpmHMACPub_key, FDO_SDK_RAW_DATA, buffer, offset)) { - LOG(LOG_ERROR, "Failed to save the public HMAC key context.\n"); + // Search the persistent Handle + TPMS_CAPABILITY_DATA *capability_data = NULL; + ret_val = Esys_GetCapability( + esys_context, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, + TPM2_CAP_HANDLES, persistent_handle, 1, NULL, &capability_data); + if (ret_val != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Esys_GetCapability failed!\n"); goto err; } - LOG(LOG_DEBUG, "Saved HMAC public key context of size %zu.\n", offset); - offset = 0; - ret_val = Tss2_MU_TPM2B_PRIVATE_Marshal(out_private, buffer, - sizeof(buffer), &offset); - if (ret_val != TSS2_RC_SUCCESS) { - LOG(LOG_ERROR, - "Failed to serialize the private HMAC key context.\n"); - goto err; + int exists = + (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == persistent_handle); + if (exists == 1) { + ret_val = Esys_TR_FromTPMPublic( + esys_context, persistent_handle, ESYS_TR_NONE, ESYS_TR_NONE, + ESYS_TR_NONE, &persistentHandle); + + if (ret_val != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to load HMAC Key Context.\n"); + goto err; + } + + ret_val = Esys_EvictControl( + esys_context, ESYS_TR_RH_OWNER, persistentHandle, + auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, 0, + &pub_object_handle); + if (ret_val != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Esys_EvictControl failed: 0x%x\n", + ret_val); + Esys_Finalize(&esys_context); + goto err; + } } - if ((int32_t)offset != - fdo_blob_write(tpmHMACPriv_key, FDO_SDK_RAW_DATA, buffer, offset)) { - LOG(LOG_ERROR, - "Failed to save the private HMAC key context.\n"); + ret_val = Esys_EvictControl( + esys_context, ESYS_TR_RH_OWNER, object_handle, auth_session_handle, + ESYS_TR_NONE, ESYS_TR_NONE, persistent_handle, &pub_object_handle); + if (ret_val != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Esys_EvictControl failed: 0x%x\n", ret_val); goto err; } - LOG(LOG_DEBUG, "Saved HMAC private key context of size %zu.\n", offset); + LOG(LOG_DEBUG, + "Saved HMAC private key context inside persistance memory at " + "%d.\n", + persistent_handle); LOG(LOG_DEBUG, "HMAC Key generated successfully!.\n"); ret = 0; @@ -452,10 +373,54 @@ int32_t fdo_tpm_generate_hmac_key(char *tpmHMACPub_key, char *tpmHMACPriv_key) TPM2_ZEROISE_FREE(creation_hash); TPM2_ZEROISE_FREE(creation_ticket); - if (esys_context && - (0 != fdoTPMTSSContext_clean_up(&esys_context, &auth_session_handle, - &primary_key_handle))) { - LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + if (esys_context) { + if (object_handle != ESYS_TR_NONE) { + if (Esys_TR_Close(esys_context, &object_handle) != + TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, + "Failed to flush object_handle.\n"); + ret = -1; + } else { + LOG(LOG_DEBUG, + "object_handle flushed successfully.\n"); + object_handle = ESYS_TR_NONE; + } + } + + if (pub_object_handle != ESYS_TR_NONE) { + if (Esys_TR_Close(esys_context, &pub_object_handle) != + TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, + "Failed to flush pub_object_handle.\n"); + ret = -1; + } else { + LOG(LOG_DEBUG, "pub_object_handle flushed " + "successfully.\n"); + pub_object_handle = ESYS_TR_NONE; + } + } + + if (persistentHandle != ESYS_TR_NONE) { + if (Esys_TR_Close(esys_context, &persistentHandle) != + TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, + "Failed to flush persistent handle.\n"); + ret = -1; + } else { + LOG(LOG_DEBUG, "persistent handle flushed " + "successfully.\n"); + persistentHandle = ESYS_TR_NONE; + } + } + if (0 != fdoTPMTSSContext_clean_up(&esys_context, + &auth_session_handle, + &primary_key_handle)) { + LOG(LOG_ERROR, + "Failed to tear down all the TSS context.\n"); + ret = -1; + } else { + LOG(LOG_DEBUG, "TSS context flushed successfully.\n"); + } } return ret; @@ -471,9 +436,9 @@ int32_t fdo_tpm_generate_hmac_key(char *tpmHMACPub_key, char *tpmHMACPriv_key) * 0, on success * -1, on failure */ -static int32_t fdoTPMGenerate_primary_key_context(ESYS_CONTEXT **esys_context, - ESYS_TR *primary_key_handle, - ESYS_TR *auth_session_handle) +int32_t fdoTPMGenerate_primary_key_context(ESYS_CONTEXT **esys_context, + ESYS_TR *primary_key_handle, + ESYS_TR *auth_session_handle) { int ret = -1; TSS2_RC ret_val = TPM2_RC_FAILURE; @@ -544,7 +509,7 @@ static int32_t fdoTPMGenerate_primary_key_context(ESYS_CONTEXT **esys_context, * 0, on success * -1, on failure */ -static int32_t fdoTPMEsys_context_init(ESYS_CONTEXT **esys_context) +int32_t fdoTPMEsys_context_init(ESYS_CONTEXT **esys_context) { int ret = -1; TSS2_TCTI_CONTEXT *tcti_context = NULL; @@ -588,8 +553,8 @@ static int32_t fdoTPMEsys_context_init(ESYS_CONTEXT **esys_context) * 0, on success * -1, on failure */ -static int32_t fdoTPMEsys_auth_session_init(ESYS_CONTEXT *esys_context, - ESYS_TR *session_handle) +int32_t fdoTPMEsys_auth_session_init(ESYS_CONTEXT *esys_context, + ESYS_TR *session_handle) { int ret = -1; TPMT_SYM_DEF symmetric = {0}; @@ -598,7 +563,8 @@ static int32_t fdoTPMEsys_auth_session_init(ESYS_CONTEXT *esys_context, TSS2_RC rval = Esys_StartAuthSession( esys_context, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, NULL, TPM2_SE_HMAC, &symmetric, - TPM2_ALG_SHA256, session_handle); + FDO_TPM2_ALG_SHA, session_handle); + if (rval != TSS2_RC_SUCCESS) { LOG(LOG_ERROR, "Failed to start the auth session.\n"); return ret; @@ -617,9 +583,9 @@ static int32_t fdoTPMEsys_auth_session_init(ESYS_CONTEXT *esys_context, * 0, on success * -1, on failure */ -static int32_t fdoTPMTSSContext_clean_up(ESYS_CONTEXT **esys_context, - ESYS_TR *auth_session_handle, - ESYS_TR *primary_handle) +int32_t fdoTPMTSSContext_clean_up(ESYS_CONTEXT **esys_context, + ESYS_TR *auth_session_handle, + ESYS_TR *primary_handle) { int ret = -1, is_failed = 0; TSS2_TCTI_CONTEXT *tcti_context = NULL; @@ -676,125 +642,3 @@ static int32_t fdoTPMTSSContext_clean_up(ESYS_CONTEXT **esys_context, return 0; } - -/** - * Replace the TPM_HMAC_PRIV_KEY with TPM_HMAC_REPLACEMENT_PRIV_KEY and - * TPM_HMAC_PUB_KEY with TPM_HMAC_REPLACEMENT_PUB_KEY. - * - * @return - * -1, error - * 0, success - */ -int32_t fdo_tpm_commit_replacement_hmac_key(void) -{ - size_t file_size = 0; - // internal return value - int32_t ret_val = -1; - // function return value - int32_t ret = -1; - uint8_t bufferTPMHMACPriv_key[TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_160] = {0}; - uint8_t bufferTPMHMACPub_key[TPM_HMAC_PUB_KEY_CONTEXT_SIZE] = {0}; - - if (!file_exists(TPM_HMAC_PRIV_KEY) || - !file_exists(TPM_HMAC_PUB_KEY) || - !file_exists(TPM_HMAC_REPLACEMENT_PRIV_KEY) || - !file_exists(TPM_HMAC_REPLACEMENT_PUB_KEY)) { - LOG(LOG_ERROR, "One or more HMAC objects are missing.\n"); - goto err; - } - - // read TPM_HMAC_REPLACEMENT_PRIV_KEY contents and write it into TPM_HMAC_PRIV_KEY - file_size = get_file_size(TPM_HMAC_REPLACEMENT_PRIV_KEY); - - if (file_size != TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_128 && - file_size != TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_160) { - LOG(LOG_ERROR, "TPM HMAC Replacement Private Key file size incorrect.\n"); - goto err; - } - - LOG(LOG_DEBUG, - "TPM HMAC Replacement Private Key file size retreived successfully.\n"); - - ret_val = read_buffer_from_file(TPM_HMAC_REPLACEMENT_PRIV_KEY, bufferTPMHMACPriv_key, - file_size); - - if (ret_val != 0) { - LOG(LOG_ERROR, - "Failed to load TPM HMAC Replacement Private Key into buffer.\n"); - goto err; - } - - if ((int32_t)file_size != - fdo_blob_write(TPM_HMAC_PRIV_KEY, FDO_SDK_RAW_DATA, - bufferTPMHMACPriv_key, file_size)) { - LOG(LOG_ERROR, "Failed to save the private HMAC key context.\n"); - goto err; - } - - // now, read TPM_HMAC_REPLACEMENT_PUB_KEY contents and write it into TPM_HMAC_PUB_KEY - file_size = get_file_size(TPM_HMAC_REPLACEMENT_PUB_KEY); - - if (file_size != TPM_HMAC_PUB_KEY_CONTEXT_SIZE) { - LOG(LOG_ERROR, "TPM HMAC Replacement Public Key file size incorrect.\n"); - goto err; - } - - LOG(LOG_DEBUG, - "TPM HMAC Replacement Public Key file size retreived successfully.\n"); - - ret_val = read_buffer_from_file(TPM_HMAC_REPLACEMENT_PUB_KEY, bufferTPMHMACPub_key, - file_size); - - if (ret_val != 0) { - LOG(LOG_ERROR, - "Failed to load TPM HMAC Replacement Public key into buffer.\n"); - goto err; - } - - if ((int32_t)file_size != - fdo_blob_write(TPM_HMAC_PUB_KEY, FDO_SDK_RAW_DATA, - bufferTPMHMACPub_key, file_size)) { - LOG(LOG_ERROR, "Failed to save the public HMAC key context.\n"); - goto err; - } - ret = 0; -err: - return ret; -} - -/** - * Clear the Replacement TPM HMAC key objects, if they exist. - * - */ -void fdo_tpm_clear_replacement_hmac_key(void) { - // remove the files if they exist, else return - if (file_exists(TPM_HMAC_REPLACEMENT_PRIV_KEY)) { - if (0 != remove(TPM_HMAC_REPLACEMENT_PRIV_KEY)) { - LOG(LOG_ERROR, "Failed to cleanup private object\n"); - } - } - if (file_exists(TPM_HMAC_REPLACEMENT_PUB_KEY)) { - if (0 != remove(TPM_HMAC_REPLACEMENT_PUB_KEY)) { - LOG(LOG_ERROR, "Failed to cleanup public object\n"); - } - } -} - -/** - * Check whether valid data integrity protection HMAC key is present or not. - * - * @return - * 1, present - * 0, not present - */ -int32_t is_valid_tpm_data_protection_key_present(void) -{ - return (file_exists(TPM_HMAC_DATA_PUB_KEY) && - (TPM_HMAC_PUB_KEY_CONTEXT_SIZE == - get_file_size(TPM_HMAC_DATA_PUB_KEY)) && - file_exists(TPM_HMAC_DATA_PRIV_KEY) && - (TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_128 == - get_file_size(TPM_HMAC_DATA_PRIV_KEY) || - TPM_HMAC_PRIV_KEY_CONTEXT_SIZE_160 == - get_file_size(TPM_HMAC_DATA_PRIV_KEY))); -} diff --git a/crypto/se/se_AESGCMRoutines.c b/crypto/se/se_AES_GCM_routines.c similarity index 87% rename from crypto/se/se_AESGCMRoutines.c rename to crypto/se/se_AES_GCM_routines.c index f6d40dbd..1734fe83 100644 --- a/crypto/se/se_AESGCMRoutines.c +++ b/crypto/se/se_AES_GCM_routines.c @@ -9,7 +9,7 @@ * openssl library. */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "crypto_utils.h" #include "safe_lib.h" @@ -44,13 +44,10 @@ * @return ret * return cipher_length in bytes during success and -1 during any error. */ -int32_t fdo_crypto_aes_gcm_encrypt(const uint8_t *plain_text, - uint32_t plain_text_length, - uint8_t *cipher_text, - uint32_t cipher_text_length, - const uint8_t *iv, uint32_t iv_length, - const uint8_t *key, uint32_t key_length, - uint8_t *tag, uint32_t tag_length) +int32_t fdo_crypto_aes_gcm_encrypt( + const uint8_t *plain_text, uint32_t plain_text_length, uint8_t *cipher_text, + uint32_t cipher_text_length, const uint8_t *iv, uint32_t iv_length, + const uint8_t *key, uint32_t key_length, uint8_t *tag, uint32_t tag_length) { atca_aes_gcm_ctx_t ctx; @@ -122,13 +119,10 @@ int32_t fdo_crypto_aes_gcm_encrypt(const uint8_t *plain_text, * return clear_text_length in bytes during success and -1 during any * error. */ -int32_t fdo_crypto_aes_gcm_decrypt(uint8_t *clear_text, - uint32_t clear_text_length, - const uint8_t *cipher_text, - uint32_t cipher_text_length, - const uint8_t *iv, uint32_t iv_length, - const uint8_t *key, uint32_t key_length, - uint8_t *tag, uint32_t tag_length) +int32_t fdo_crypto_aes_gcm_decrypt( + uint8_t *clear_text, uint32_t clear_text_length, const uint8_t *cipher_text, + uint32_t cipher_text_length, const uint8_t *iv, uint32_t iv_length, + const uint8_t *key, uint32_t key_length, uint8_t *tag, uint32_t tag_length) { atca_aes_gcm_ctx_t ctx; bool verified; diff --git a/crypto/se/se_ECDSASignRoutines.c b/crypto/se/se_ECDSA_sign_routines.c similarity index 87% rename from crypto/se/se_ECDSASignRoutines.c rename to crypto/se/se_ECDSA_sign_routines.c index fbac4076..fcd1c7c0 100644 --- a/crypto/se/se_ECDSASignRoutines.c +++ b/crypto/se/se_ECDSA_sign_routines.c @@ -8,11 +8,11 @@ * \ brief Abstraction layer for ECDSA signing routine using SE */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "storage_al.h" #include "safe_lib.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include #include "se_config.h" @@ -26,7 +26,7 @@ * @return 0 if true, else -1. */ int32_t crypto_hal_ecdsa_sign(const uint8_t *message, size_t message_len, - unsigned char *signature, size_t *signature_len) + unsigned char *signature, size_t *signature_len) { unsigned char hash[SHA256_DIGEST_SIZE] = {0}; uint8_t raw_signature[BUFF_SIZE_64_BYTES]; @@ -55,8 +55,8 @@ int32_t crypto_hal_ecdsa_sign(const uint8_t *message, size_t message_len, /* The signature returned by the SE is in R and S format which needs * to get converted to DER format for transmission. */ - ret = crypto_hal_der_encode(raw_signature, BUFF_SIZE_64_BYTES, signature, - signature_len); + ret = crypto_hal_der_encode(raw_signature, BUFF_SIZE_64_BYTES, + signature, signature_len); err: if (-1 == ret) { diff --git a/crypto/se/se_ECDSAVerifyRoutines.c b/crypto/se/se_ECDSA_verify_routines.c similarity index 91% rename from crypto/se/se_ECDSAVerifyRoutines.c rename to crypto/se/se_ECDSA_verify_routines.c index 48679ebf..888a1672 100644 --- a/crypto/se/se_ECDSAVerifyRoutines.c +++ b/crypto/se/se_ECDSA_verify_routines.c @@ -8,12 +8,12 @@ * \brief Abstraction layer for ECDSA signature verification */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "storage_al.h" #include "safe_lib.h" #include "se_config.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include #include @@ -49,8 +49,8 @@ int32_t crypto_hal_sig_verify(uint8_t key_encoding, int key_algorithm, uint8_t raw_sig[BUFF_SIZE_64_BYTES]; int ret = 0; - (void) key_param2; - (void) key_param2Length; + (void)key_param2; + (void)key_param2Length; /* Check validity of key type. */ if (key_encoding != FDO_CRYPTO_PUB_KEY_ENCODING_X509 || @@ -78,9 +78,10 @@ int32_t crypto_hal_sig_verify(uint8_t key_encoding, int key_algorithm, * required API calls from openssl/mbedtls for the decoding operation * and then pass the raw key and signature to the SE for verification. */ - if (0 != crypto_hal_der_decode(raw_key, raw_sig, pub_key, key_param1Length, - message_signature, signature_length, - BUFF_SIZE_64_BYTES, BUFF_SIZE_64_BYTES)) { + if (0 != crypto_hal_der_decode(raw_key, raw_sig, pub_key, + key_param1Length, message_signature, + signature_length, BUFF_SIZE_64_BYTES, + BUFF_SIZE_64_BYTES)) { LOG(LOG_ERROR, "Failed to decode from DER to raw format\n"); ret = -1; goto err; diff --git a/crypto/se/se_cryptoSupport.c b/crypto/se/se_crypto_support.c similarity index 97% rename from crypto/se/se_cryptoSupport.c rename to crypto/se/se_crypto_support.c index 523bb983..fd906350 100644 --- a/crypto/se/se_cryptoSupport.c +++ b/crypto/se/se_crypto_support.c @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache 2.0 */ -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "safe_lib.h" #include "util.h" #include @@ -86,8 +86,8 @@ int32_t crypto_hal_random_bytes(uint8_t *random_buffer, size_t num_bytes) return -1; } else if (32 < num_bytes) { - /* TODO loop over the rand number generation for bigger chunks. - */ + /* TODO loop over the rand number generation for bigger chunks. + */ return -1; } else if (ATCA_SUCCESS != atcab_random(local_buffer)) { @@ -116,8 +116,8 @@ int32_t crypto_hal_random_bytes(uint8_t *random_buffer, size_t num_bytes) * return 0 on success. -ve value on failure. */ int32_t crypto_hal_hash(uint8_t hash_type, const uint8_t *buffer, - size_t buffer_length, uint8_t *output, - size_t output_length) + size_t buffer_length, uint8_t *output, + size_t output_length) { if (NULL == output || 0 == output_length || NULL == buffer || 0 == buffer_length) { diff --git a/crypto/se/se_csr.c b/crypto/se/se_csr.c index 39636196..3c625eff 100644 --- a/crypto/se/se_csr.c +++ b/crypto/se/se_csr.c @@ -9,7 +9,7 @@ */ #include "fdotypes.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "safe_lib.h" #include "se_config.h" @@ -22,96 +22,68 @@ #define SE_CSR_PK_BYTE_LOCATION 64 #define SE_CSR_LOCATION_SELECT DEVZONE_NONE - const uint8_t csr_template_device[] = { - 0x30, 0x82, 0x01, 0x1f, 0x30, 0x81, 0xc7, 0x02, - 0x01, 0x00, 0x30, 0x65, 0x31, 0x0b, 0x30, 0x09, - 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x49, - 0x4e, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, - 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, - 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x0c, - 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, - 0x03, 0x53, 0x44, 0x4f, 0x31, 0x13, 0x30, 0x11, - 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x0a, 0x43, - 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2d, 0x53, 0x44, - 0x4b, 0x31, 0x1e, 0x30, 0x1c, 0x06, 0x03, 0x55, - 0x04, 0x03, 0x0c, 0x15, 0x44, 0x65, 0x76, 0x69, - 0x63, 0x65, 0x2d, 0x53, 0x44, 0x4f, 0x2d, 0x43, - 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2d, 0x53, 0x44, - 0x4b, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, - 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, - 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, - 0x03, 0x42, 0x00, 0x04, 0xad, 0xef, 0x17, 0x96, - 0xf7, 0x3b, 0x08, 0x2f, 0xcf, 0xc4, 0x2d, 0x8f, - 0x75, 0x99, 0x9a, 0x29, 0xd8, 0x2f, 0x9c, 0x58, - 0x6e, 0xbf, 0xf8, 0xff, 0x92, 0x96, 0x99, 0x28, - 0x80, 0x8a, 0xe7, 0x4d, 0xb9, 0x1c, 0x7a, 0xe2, - 0x4b, 0x7c, 0xc7, 0xb3, 0x7a, 0x14, 0xfc, 0x83, - 0x52, 0x6e, 0xff, 0x51, 0xfc, 0xa9, 0x87, 0x05, - 0xe6, 0xd2, 0x14, 0xf7, 0x35, 0x48, 0xbf, 0x34, - 0xce, 0x83, 0x72, 0x7e, 0xa0, 0x00, 0x30, 0x0a, - 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, - 0x03, 0x02, 0x03, 0x47, 0x00, 0x30, 0x44, 0x02, - 0x20, 0x15, 0xba, 0x7f, 0xb8, 0x94, 0xae, 0x9c, - 0x47, 0x11, 0x6f, 0xa8, 0x7d, 0x58, 0xc5, 0x43, - 0x98, 0xd1, 0xe8, 0x19, 0x5c, 0x6e, 0x4f, 0xa7, - 0xec, 0x6d, 0xd2, 0x34, 0x51, 0xe3, 0x33, 0x3b, - 0x93, 0x02, 0x20, 0x13, 0xe9, 0x05, 0x51, 0x11, - 0x6f, 0x18, 0x5e, 0x91, 0x6f, 0x12, 0x78, 0x0d, - 0x4f, 0x52, 0x27, 0xa0, 0xd5, 0xd6, 0x6e, 0x30, - 0xb7, 0x7e, 0x88, 0xbc, 0x49, 0xf8, 0x50, 0x14, - 0x8e, 0x82, 0x64 -}; + 0x30, 0x82, 0x01, 0x1f, 0x30, 0x81, 0xc7, 0x02, 0x01, 0x00, 0x30, 0x65, + 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x49, + 0x4e, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, + 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x0c, + 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x03, 0x53, 0x44, 0x4f, + 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x0a, 0x43, + 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2d, 0x53, 0x44, 0x4b, 0x31, 0x1e, 0x30, + 0x1c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x15, 0x44, 0x65, 0x76, 0x69, + 0x63, 0x65, 0x2d, 0x53, 0x44, 0x4f, 0x2d, 0x43, 0x6c, 0x69, 0x65, 0x6e, + 0x74, 0x2d, 0x53, 0x44, 0x4b, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, + 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xad, 0xef, 0x17, 0x96, + 0xf7, 0x3b, 0x08, 0x2f, 0xcf, 0xc4, 0x2d, 0x8f, 0x75, 0x99, 0x9a, 0x29, + 0xd8, 0x2f, 0x9c, 0x58, 0x6e, 0xbf, 0xf8, 0xff, 0x92, 0x96, 0x99, 0x28, + 0x80, 0x8a, 0xe7, 0x4d, 0xb9, 0x1c, 0x7a, 0xe2, 0x4b, 0x7c, 0xc7, 0xb3, + 0x7a, 0x14, 0xfc, 0x83, 0x52, 0x6e, 0xff, 0x51, 0xfc, 0xa9, 0x87, 0x05, + 0xe6, 0xd2, 0x14, 0xf7, 0x35, 0x48, 0xbf, 0x34, 0xce, 0x83, 0x72, 0x7e, + 0xa0, 0x00, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, + 0x03, 0x02, 0x03, 0x47, 0x00, 0x30, 0x44, 0x02, 0x20, 0x15, 0xba, 0x7f, + 0xb8, 0x94, 0xae, 0x9c, 0x47, 0x11, 0x6f, 0xa8, 0x7d, 0x58, 0xc5, 0x43, + 0x98, 0xd1, 0xe8, 0x19, 0x5c, 0x6e, 0x4f, 0xa7, 0xec, 0x6d, 0xd2, 0x34, + 0x51, 0xe3, 0x33, 0x3b, 0x93, 0x02, 0x20, 0x13, 0xe9, 0x05, 0x51, 0x11, + 0x6f, 0x18, 0x5e, 0x91, 0x6f, 0x12, 0x78, 0x0d, 0x4f, 0x52, 0x27, 0xa0, + 0xd5, 0xd6, 0x6e, 0x30, 0xb7, 0x7e, 0x88, 0xbc, 0x49, 0xf8, 0x50, 0x14, + 0x8e, 0x82, 0x64}; const atcacert_def_t csr_def_device = { - .type = 0, /* x509 certificate */ - .template_id = SE_CSR_TEMPLATE_ID, - .chain_id = 0, - .private_key_slot = 0, - .sn_source = SE_CSR_PK_HASH_ID, - .cert_sn_dev_loc = { - .zone = SE_CSR_LOCATION_SELECT, - .slot = 0, - .is_genkey = 0, - .offset = 0, - .count = 0 - }, - .issue_date_format = 1, - .expire_date_format = 1, - .tbs_cert_loc = { - .offset = 4, - .count = 202 - }, - .expire_years = 0, - .public_key_dev_loc = { - .zone = SE_CSR_LOCATION_SELECT, - .slot = 0, - .is_genkey = 1, - .offset = 0, - .count = SE_CSR_PK_BYTE_LOCATION - }, - .comp_cert_dev_loc = { - .zone = SE_CSR_LOCATION_SELECT, - .slot = 0, - .is_genkey = 0, - .offset = 0, - .count = 0 - }, - .std_cert_elements = { - { /* PUBLIC_KEY */ - .offset = 140, - .count = 64 - }, - { /* SIGNATURE */ - .offset = 218, - .count = 73 - } - }, - .cert_elements = NULL, - .cert_elements_count = 0, - .cert_template = csr_template_device, - .cert_template_size = sizeof(csr_template_device) -}; + .type = 0, /* x509 certificate */ + .template_id = SE_CSR_TEMPLATE_ID, + .chain_id = 0, + .private_key_slot = 0, + .sn_source = SE_CSR_PK_HASH_ID, + .cert_sn_dev_loc = {.zone = SE_CSR_LOCATION_SELECT, + .slot = 0, + .is_genkey = 0, + .offset = 0, + .count = 0}, + .issue_date_format = 1, + .expire_date_format = 1, + .tbs_cert_loc = {.offset = 4, .count = 202}, + .expire_years = 0, + .public_key_dev_loc = {.zone = SE_CSR_LOCATION_SELECT, + .slot = 0, + .is_genkey = 1, + .offset = 0, + .count = SE_CSR_PK_BYTE_LOCATION}, + .comp_cert_dev_loc = {.zone = SE_CSR_LOCATION_SELECT, + .slot = 0, + .is_genkey = 0, + .offset = 0, + .count = 0}, + .std_cert_elements = {{/* PUBLIC_KEY */ + .offset = 140, + .count = 64}, + {/* SIGNATURE */ + .offset = 218, + .count = 73}}, + .cert_elements = NULL, + .cert_elements_count = 0, + .cert_template = csr_template_device, + .cert_template_size = sizeof(csr_template_device)}; /** * fdo_get_device_csr() - get the device CSR @@ -127,7 +99,7 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) LOG(LOG_ERROR, "Failed to allocate data.\n"); goto err; } - size_t csr_size = SE_CSR_SIZE; + size_t csr_size = SE_CSR_SIZE; /* Creates a DER formatted CSR from the SE. */ if (ATCA_SUCCESS != diff --git a/cse/clear_cse.c b/cse/clear_cse.c index 5f8855f7..904be8d6 100644 --- a/cse/clear_cse.c +++ b/cse/clear_cse.c @@ -10,9 +10,8 @@ #include #include - -#define MEI_FDO UUID_LE(0x125405E0, 0xFCA9, 0x4110, 0x8F, 0x88, 0xB4, 0xDB,\ - 0xCD, 0xCB, 0x87, 0x6F) +DEFINE_GUID(MEI_FDO, 0x125405E0, 0xFCA9, 0x4110, 0x8F, 0x88, 0xB4, 0xDB, 0xCD, + 0xCB, 0x87, 0x6F); /** * Initialize HECI @@ -54,22 +53,23 @@ void heci_deinit(TEEHANDLE *cl) * @param fdo_status - status of the HECI call * @return status for API function */ -TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status) +TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status) { fdo_heci_clear_file_request FDORequest; - fdo_heci_clear_file_response* FDOResponseMessage; + fdo_heci_clear_file_response *FDOResponseMessage; TEESTATUS status = -1; FDORequest.header.command = FDO_HECI_CLEAR_FILE; FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = sizeof(FDORequest) - sizeof(FDORequest.header); + FDORequest.header.length = + sizeof(FDORequest) - sizeof(FDORequest.header); FDORequest.file_id = file_id; const size_t sz = sizeof(FDORequest); unsigned char *buf = NULL; size_t rsz, wsz = 0; - rsz = cl->maxMsgLen; //sets maxMsgLen + rsz = cl->maxMsgLen; // sets maxMsgLen buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); if (buf == NULL) { printf("calloc(%u) failed\n", (unsigned)rsz); @@ -78,8 +78,8 @@ TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); if (status != TEE_SUCCESS) { - printf("TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, - (unsigned)sizeof(FDORequest)); + printf("TeeWrite failed (%u) [attempted %u cmd bytes]\n", + status, (unsigned)sizeof(FDORequest)); goto out; } @@ -91,7 +91,7 @@ TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS size_t NumOfBytesRead = 0; memset(buf, 0, rsz); - FDOResponseMessage = (fdo_heci_clear_file_response*)(buf); + FDOResponseMessage = (fdo_heci_clear_file_response *)(buf); status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); if (status != TEE_SUCCESS) { @@ -107,7 +107,8 @@ TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS return status; } -int main(void) { +int main(void) +{ TEEHANDLE cl; FDO_STATUS fdo_status; @@ -117,7 +118,7 @@ int main(void) { } if (TEE_SUCCESS != fdo_heci_clear_file(&cl, DS_FILE_ID, &fdo_status) || - FDO_STATUS_SUCCESS != fdo_status) { + FDO_STATUS_SUCCESS != fdo_status) { if (FDO_STATUS_API_INTERFACE_IS_CLOSED == fdo_status) { printf("CSE Interface is Closed!! Reboot required.\n"); goto end; @@ -127,7 +128,7 @@ int main(void) { } if (TEE_SUCCESS != fdo_heci_clear_file(&cl, OVH_FILE_ID, &fdo_status) || - FDO_STATUS_SUCCESS != fdo_status) { + FDO_STATUS_SUCCESS != fdo_status) { printf("HECI CLEAR OVH failed!!\n"); goto end; } diff --git a/cse/cse_tools.c b/cse/cse_tools.c index 1f3de892..571a96ae 100644 --- a/cse/cse_tools.c +++ b/cse/cse_tools.c @@ -21,14 +21,15 @@ int32_t cse_get_cert_chain(fdo_byte_array_t **cse_cert) int ret = -1; uint16_t lengths_of_certificates[FDO_ODCA_CHAIN_LEN]; uint8_t certificate_chain[FDO_MAX_CERT_CHAIN_SIZE]; - uint8_t *cert_chain = (uint8_t*)&certificate_chain; - uint16_t *len_cert = (uint16_t*)&lengths_of_certificates; + uint8_t *cert_chain = (uint8_t *)&certificate_chain; + uint16_t *len_cert = (uint16_t *)&lengths_of_certificates; uint16_t total_cert_len = 0; uint16_t total_cert_size = 0; uint8_t *formatted_cert_chain = NULL; if (TEE_SUCCESS != fdo_heci_get_cert_chain(&fdo_cse_handle, cert_chain, - len_cert, &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + len_cert, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO GET CERT CHAIN failed!! %u\n", fdo_status); goto err; } @@ -41,7 +42,8 @@ int32_t cse_get_cert_chain(fdo_byte_array_t **cse_cert) total_cert_size = total_cert_len + 2 + sizeof(lengths_of_certificates); formatted_cert_chain = calloc(total_cert_size, 1); if (formatted_cert_chain == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)total_cert_size); + LOG(LOG_ERROR, "calloc(%u) failed\n", + (unsigned)total_cert_size); goto err; } @@ -53,19 +55,19 @@ int32_t cse_get_cert_chain(fdo_byte_array_t **cse_cert) for (int it = 1; it <= FDO_ODCA_CHAIN_LEN; it++) { - *tmp_formatted_cert_chain = __builtin_bswap16(lengths_of_certificates - [it - 1]); + *tmp_formatted_cert_chain = + __builtin_bswap16(lengths_of_certificates[it - 1]); tmp_formatted_cert_chain++; } - if (memcpy_s(tmp_formatted_cert_chain, total_cert_len, certificate_chain, - total_cert_len) != 0) { + if (memcpy_s(tmp_formatted_cert_chain, total_cert_len, + certificate_chain, total_cert_len) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto err; } if (memcpy_s((*cse_cert)->bytes, (*cse_cert)->byte_sz, - formatted_cert_chain, total_cert_size) != 0) { + formatted_cert_chain, total_cert_size) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto err; } @@ -88,8 +90,8 @@ int32_t cse_get_cert_chain(fdo_byte_array_t **cse_cert) * @param data_len - size of message, type uint32_t. * @return pointer to a byte_array holding a cose signature structure. */ -int32_t cse_get_cose_sig_structure(fdo_byte_array_t **cose_sig_structure, uint8_t - *data, size_t data_len) +int32_t cse_get_cose_sig_structure(fdo_byte_array_t **cose_sig_structure, + uint8_t *data, size_t data_len) { if (!data || !data_len) { return -1; @@ -119,13 +121,14 @@ int32_t cse_get_cose_sig_structure(fdo_byte_array_t **cose_sig_structure, uint8_ cose->cose_ph->ph_sig_alg = FDO_CRYPTO_SIG_TYPE_ECSDAp384; if (memcpy_s(cose->cose_payload->bytes, cose->cose_payload->byte_sz, - data, data_len) != 0) { + data, data_len) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto err; } - if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, NULL, - &cose_sig_byte_arr) || !cose_sig_byte_arr) { + if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, + NULL, &cose_sig_byte_arr) || + !cose_sig_byte_arr) { LOG(LOG_ERROR, "Failed to write COSE Sig_structure\n"); goto err; } @@ -155,12 +158,13 @@ int32_t cse_get_cose_sig_structure(fdo_byte_array_t **cose_sig_structure, uint8_ * @param data_len - size of message, type uint32_t. * @return pointer to a byte_array holding a valid device CSE test signature. */ -int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, fdo_byte_array_t - **cse_maroeprefix, fdo_byte_array_t *cose_sig_structure, uint8_t - *data, size_t data_len) +int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, + fdo_byte_array_t **cse_maroeprefix, + fdo_byte_array_t *cose_sig_structure, uint8_t *data, + size_t data_len) { if (!cse_signature || !cse_maroeprefix || !cose_sig_structure || - !data || !data_len) { + !data || !data_len) { return -1; } @@ -168,22 +172,25 @@ int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, fdo_byte_array_t int ret = -1; uint32_t mp_len; - if (TEE_SUCCESS != fdo_heci_load_file(&fdo_cse_handle, OVH_FILE_ID, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + if (TEE_SUCCESS != + fdo_heci_load_file(&fdo_cse_handle, OVH_FILE_ID, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI LOAD failed!! %u\n", fdo_status); goto err; } if (TEE_SUCCESS != fdo_heci_update_file(&fdo_cse_handle, OVH_FILE_ID, - data, (uint32_t)data_len, NULL, 0, &fdo_status) || - FDO_STATUS_SUCCESS != fdo_status) { + data, (uint32_t)data_len, NULL, + 0, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI UPDATE failed!! %u\n", fdo_status); goto err; } LOG(LOG_DEBUG, "FDO HECI UPDATE succeeded %u\n", fdo_status); if (TEE_SUCCESS != fdo_heci_commit_file(&fdo_cse_handle, OVH_FILE_ID, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO OVH COMMIT failed!! %u\n", fdo_status); goto err; } @@ -194,12 +201,15 @@ int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, fdo_byte_array_t * sample data (Here Device serial) to enable test signature generation */ - if (TEE_SUCCESS != fdo_heci_ecdsa_device_sign_challenge(&fdo_cse_handle, - cose_sig_structure->bytes, cose_sig_structure->byte_sz, - (*cse_signature)->bytes, (*cse_signature)->byte_sz, - (*cse_maroeprefix)->bytes, &mp_len, &fdo_status) || - FDO_STATUS_SUCCESS != fdo_status) { - LOG(LOG_ERROR, "FDO HECI ECDSA DEVICE SIGN failed!! %u\n", fdo_status); + if (TEE_SUCCESS != + fdo_heci_ecdsa_device_sign_challenge( + &fdo_cse_handle, cose_sig_structure->bytes, + cose_sig_structure->byte_sz, (*cse_signature)->bytes, + (*cse_signature)->byte_sz, (*cse_maroeprefix)->bytes, + &mp_len, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { + LOG(LOG_ERROR, "FDO HECI ECDSA DEVICE SIGN failed!! %u\n", + fdo_status); goto err; } (*cse_maroeprefix)->byte_sz = mp_len; @@ -207,7 +217,6 @@ int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, fdo_byte_array_t ret = 0; err: return ret; - } /** @@ -220,8 +229,8 @@ int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, fdo_byte_array_t * @param hmac_size - size of the HMAC * @return status for API function */ -int32_t cse_load_file(uint32_t file_id, uint8_t *data_ptr, uint32_t - *data_length, uint8_t *hmac_ptr, size_t hmac_sz) +int32_t cse_load_file(uint32_t file_id, uint8_t *data_ptr, + uint32_t *data_length, uint8_t *hmac_ptr, size_t hmac_sz) { if (!data_ptr || !data_length) { return -1; @@ -230,15 +239,17 @@ int32_t cse_load_file(uint32_t file_id, uint8_t *data_ptr, uint32_t FDO_STATUS fdo_status; int ret = -1; - if (TEE_SUCCESS != fdo_heci_load_file(&fdo_cse_handle, file_id, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + if (TEE_SUCCESS != + fdo_heci_load_file(&fdo_cse_handle, file_id, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI LOAD failed!! %u\n", fdo_status); goto err; } - if (TEE_SUCCESS != fdo_heci_read_file(&fdo_cse_handle, file_id, data_ptr, - data_length, hmac_ptr, hmac_sz, &fdo_status) || FDO_STATUS_SUCCESS != - fdo_status) { + if (TEE_SUCCESS != fdo_heci_read_file(&fdo_cse_handle, file_id, + data_ptr, data_length, hmac_ptr, + hmac_sz, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI READ FILE failed!! %u\n", fdo_status); goto err; } @@ -247,5 +258,4 @@ int32_t cse_load_file(uint32_t file_id, uint8_t *data_ptr, uint32_t ret = 0; err: return ret; - } diff --git a/cse/cse_utils.c b/cse/cse_utils.c index 1305e5cb..577019ba 100644 --- a/cse/cse_utils.c +++ b/cse/cse_utils.c @@ -11,8 +11,8 @@ #include #include -#define MEI_FDO UUID_LE(0x125405E0, 0xFCA9, 0x4110, 0x8F, 0x88, 0xB4, 0xDB,\ - 0xCD, 0xCB, 0x87, 0x6F) +DEFINE_GUID(MEI_FDO, 0x125405E0, 0xFCA9, 0x4110, 0x8F, 0x88, 0xB4, 0xDB, 0xCD, + 0xCB, 0x87, 0x6F); /** * Initialize HECI @@ -22,18 +22,18 @@ TEESTATUS heci_init(TEEHANDLE *cl) { - TEESTATUS status = -1; - status = TeeInit(cl, &MEI_FDO, NULL); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR,"TeeInit failed!\n"); - return status; - } - - status = TeeConnect(cl); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR,"TeeConnect failed!\n"); - return status; - } + TEESTATUS status = -1; + status = TeeInit(cl, &MEI_FDO, NULL); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeInit failed!\n"); + return status; + } + + status = TeeConnect(cl); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeConnect failed!\n"); + return status; + } return status; } @@ -44,7 +44,7 @@ TEESTATUS heci_init(TEEHANDLE *cl) */ void heci_deinit(TEEHANDLE *cl) { - TeeDisconnect(cl); + TeeDisconnect(cl); } /** @@ -56,56 +56,57 @@ void heci_deinit(TEEHANDLE *cl) * @return status for API function */ -TEESTATUS fdo_heci_get_version(TEEHANDLE *cl, uint16_t *major_v, uint16_t - *minor_v, FDO_STATUS *fdo_status) +TEESTATUS fdo_heci_get_version(TEEHANDLE *cl, uint16_t *major_v, + uint16_t *minor_v, FDO_STATUS *fdo_status) { - fdo_heci_get_version_request FDORequest; - fdo_heci_get_version_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_GET_VERSION; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = 0; - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - FDOResponseMessage = (fdo_heci_get_version_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *major_v = FDOResponseMessage->version.major_version; - *minor_v = FDOResponseMessage->version.minor_version; - *fdo_status = FDOResponseMessage->status; + fdo_heci_get_version_request FDORequest; + fdo_heci_get_version_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_GET_VERSION; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = 0; + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + FDOResponseMessage = (fdo_heci_get_version_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *major_v = FDOResponseMessage->version.major_version; + *minor_v = FDOResponseMessage->version.minor_version; + *fdo_status = FDOResponseMessage->status; out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -117,72 +118,75 @@ TEESTATUS fdo_heci_get_version(TEEHANDLE *cl, uint16_t *major_v, uint16_t * @param fdo_status - status of the HECI call * @return status for API function */ -TEESTATUS fdo_heci_get_cert_chain(TEEHANDLE *cl, uint8_t *cert_chain, uint16_t - *len_cert, FDO_STATUS *fdo_status) +TEESTATUS fdo_heci_get_cert_chain(TEEHANDLE *cl, uint8_t *cert_chain, + uint16_t *len_cert, FDO_STATUS *fdo_status) { - if (!cert_chain || !len_cert) { - return -1; - } - - fdo_heci_get_certificate_chain_request FDORequest; - fdo_heci_get_certificate_chain_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_GET_CERTIFICATE_CHAIN; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = sizeof(FDORequest) - sizeof(FDORequest.header); - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - FDOResponseMessage = (fdo_heci_get_certificate_chain_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; - - if (memcpy_s(len_cert, sizeof(FDOResponseMessage->lengths_of_certificates), - FDOResponseMessage->lengths_of_certificates, - sizeof(FDOResponseMessage->lengths_of_certificates)) != 0) { + if (!cert_chain || !len_cert) { + return -1; + } + + fdo_heci_get_certificate_chain_request FDORequest; + fdo_heci_get_certificate_chain_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_GET_CERTIFICATE_CHAIN; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = + sizeof(FDORequest) - sizeof(FDORequest.header); + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + FDOResponseMessage = (fdo_heci_get_certificate_chain_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; + + if (memcpy_s( + len_cert, sizeof(FDOResponseMessage->lengths_of_certificates), + FDOResponseMessage->lengths_of_certificates, + sizeof(FDOResponseMessage->lengths_of_certificates)) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto out; } - if (memcpy_s(cert_chain, FDO_MAX_CERT_CHAIN_SIZE, - FDOResponseMessage->certificate_chain, - sizeof(FDOResponseMessage->certificate_chain)) != 0) { + if (memcpy_s(cert_chain, FDO_MAX_CERT_CHAIN_SIZE, + FDOResponseMessage->certificate_chain, + sizeof(FDOResponseMessage->certificate_chain)) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto out; } out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -200,89 +204,90 @@ TEESTATUS fdo_heci_get_cert_chain(TEEHANDLE *cl, uint8_t *cert_chain, uint16_t * @param fdo_status - status of the HECI call * @return status for API function */ -TEESTATUS fdo_heci_ecdsa_device_sign_challenge(TEEHANDLE *cl, uint8_t *data, - uint32_t data_length, uint8_t *sig_ptr, size_t sig_len, uint8_t - *mp_ptr, uint32_t *mp_len, FDO_STATUS *fdo_status) +TEESTATUS fdo_heci_ecdsa_device_sign_challenge( + TEEHANDLE *cl, uint8_t *data, uint32_t data_length, uint8_t *sig_ptr, + size_t sig_len, uint8_t *mp_ptr, uint32_t *mp_len, FDO_STATUS *fdo_status) { - if (!data || !data_length || !sig_ptr || !sig_len || - !mp_ptr) { - LOG(LOG_ERROR, "fdo_heci_ecdsa_device_sign_challenge params not valid\n"); + if (!data || !data_length || !sig_ptr || !sig_len || !mp_ptr) { + LOG(LOG_ERROR, + "fdo_heci_ecdsa_device_sign_challenge params not valid\n"); return -1; } - if (data_length > FDO_MAX_FILE_SIZE || data_length < 0) { - LOG(LOG_ERROR, "Invalid data length!\n"); + if (data_length > FDO_MAX_DATA_TO_SIGN) { + LOG(LOG_ERROR, "Invalid data length!\n"); return -1; - } + } - fdo_heci_ecdsa_device_sign_challenge_request FDORequest; - fdo_heci_ecdsa_device_sign_challenge_response* FDOResponseMessage; - TEESTATUS status = -1; - unsigned char *buf = NULL; - size_t rsz, wsz = 0; + fdo_heci_ecdsa_device_sign_challenge_request FDORequest; + fdo_heci_ecdsa_device_sign_challenge_response *FDOResponseMessage; + TEESTATUS status = -1; + unsigned char *buf = NULL; + size_t rsz, wsz = 0; - FDORequest.header.command = FDO_HECI_ECDSA_DEVICE_SIGN_CHALLENGE; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.data_length = data_length; + FDORequest.header.command = FDO_HECI_ECDSA_DEVICE_SIGN_CHALLENGE; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.data_length = data_length; - if (memcpy_s(FDORequest.data, FDORequest.data_length, data, data_length) != - 0) { + if (memcpy_s(FDORequest.data, FDORequest.data_length, data, + data_length) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto out; } - FDORequest.header.length = sizeof(FDORequest.data_length) + data_length; - const size_t sz = sizeof(FDORequest.header) + FDORequest.header.length; - + FDORequest.header.length = sizeof(FDORequest.data_length) + data_length; + const size_t sz = sizeof(FDORequest.header) + FDORequest.header.length; - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } - if (wsz != sz) { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } - size_t NumOfBytesRead = 0; - FDOResponseMessage = (fdo_heci_ecdsa_device_sign_challenge_response*)(buf); + size_t NumOfBytesRead = 0; + FDOResponseMessage = + (fdo_heci_ecdsa_device_sign_challenge_response *)(buf); - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } - *fdo_status = FDOResponseMessage->status; - *mp_len = FDOResponseMessage->maroeprefix_length; + *fdo_status = FDOResponseMessage->status; + *mp_len = FDOResponseMessage->maroeprefix_length; - if (memcpy_s(mp_ptr, FDO_MAX_MAROE_PREFIX_SIZE, - FDOResponseMessage->maroeprefix, - FDOResponseMessage->maroeprefix_length) != 0) { + if (memcpy_s(mp_ptr, FDO_MAX_MAROE_PREFIX_SIZE, + FDOResponseMessage->maroeprefix, + FDOResponseMessage->maroeprefix_length) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto out; } - if (memcpy_s(sig_ptr, sig_len, FDOResponseMessage->signature, - FDO_SIGNATURE_LENGTH) != 0) { + if (memcpy_s(sig_ptr, sig_len, FDOResponseMessage->signature, + FDO_SIGNATURE_LENGTH) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); goto out; } out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -295,69 +300,70 @@ TEESTATUS fdo_heci_ecdsa_device_sign_challenge(TEEHANDLE *cl, uint8_t *data, * @return status for API function */ TEESTATUS fdo_heci_generate_random(TEEHANDLE *cl, uint8_t *random_bytes, - uint32_t length, FDO_STATUS *fdo_status) + uint32_t length, FDO_STATUS *fdo_status) { - if (!random_bytes || !length) { - return -1; - } - - if (length > FDO_MAX_RANDOM || length < 0) { - return -1; - } - - fdo_heci_generate_random_request FDORequest; - fdo_heci_generate_random_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_GENERATE_RANDOM; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = sizeof(FDORequest) - sizeof(FDORequest.header); - FDORequest.length = length; - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - FDOResponseMessage = (fdo_heci_generate_random_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; - - if (memcpy_s(random_bytes, length, - FDOResponseMessage->random_bytes, FDOResponseMessage->length) != - 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto out; - } + if (!random_bytes || !length) { + return -1; + } + + if (length > FDO_MAX_RANDOM || length == 0) { + return -1; + } + + fdo_heci_generate_random_request FDORequest; + fdo_heci_generate_random_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_GENERATE_RANDOM; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = + sizeof(FDORequest) - sizeof(FDORequest.header); + FDORequest.length = length; + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + FDOResponseMessage = (fdo_heci_generate_random_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; + + if (memcpy_s(random_bytes, length, FDOResponseMessage->random_bytes, + FDOResponseMessage->length) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto out; + } out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -368,63 +374,63 @@ TEESTATUS fdo_heci_generate_random(TEEHANDLE *cl, uint8_t *random_bytes, * @param fdo_status - status of the HECI call * @return status for API function */ -TEESTATUS fdo_heci_load_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status) +TEESTATUS fdo_heci_load_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status) { - if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { - LOG(LOG_ERROR,"Invalid file id!\n"); - return -1; - } - - fdo_heci_load_file_request FDORequest; - fdo_heci_load_file_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_LOAD_FILE; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = sizeof(FDORequest) - sizeof(FDORequest.header); - FDORequest.file_id = file_id; - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) - { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - - - FDOResponseMessage = (fdo_heci_load_file_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; + if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { + LOG(LOG_ERROR, "Invalid file id!\n"); + return -1; + } + + fdo_heci_load_file_request FDORequest; + fdo_heci_load_file_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_LOAD_FILE; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = + sizeof(FDORequest) - sizeof(FDORequest.header); + FDORequest.file_id = file_id; + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + + FDOResponseMessage = (fdo_heci_load_file_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -441,89 +447,91 @@ TEESTATUS fdo_heci_load_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS * @return status for API function */ TEESTATUS fdo_heci_update_file(TEEHANDLE *cl, uint32_t file_id, uint8_t *data, - uint32_t data_length, uint8_t *hmac_ptr, size_t hmac_length, FDO_STATUS - *fdo_status) + uint32_t data_length, uint8_t *hmac_ptr, + size_t hmac_length, FDO_STATUS *fdo_status) { - if (!data || !data_length) { + if (!data || !data_length) { + return -1; + } + + if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { + LOG(LOG_ERROR, "Invalid file id!\n"); return -1; } - if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { - LOG(LOG_ERROR,"Invalid file id!\n"); - return -1; - } - - fdo_heci_update_file_request FDORequest; - fdo_heci_update_file_response* FDOResponseMessage; - TEESTATUS status = -1; - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - FDORequest.header.command = FDO_HECI_UPDATE_FILE; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.file_id = file_id; - FDORequest.data_length = data_length; - FDORequest.header.length = sizeof(FDORequest.data_length) + - sizeof(FDORequest.file_id) + FDORequest.data_length; - - if (file_id == OVH_FILE_ID) { - if (memcpy_s(FDORequest.data, FDORequest.data_length, data, - data_length) != 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto out; - } - } else { - FDORequest.data[0] = *data; - } - - const size_t sz = sizeof(FDORequest.header) + FDORequest.header.length; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - - - FDOResponseMessage = (fdo_heci_update_file_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; - - if (file_id == OVH_FILE_ID) { - if (hmac_ptr) { - if (memcpy_s(hmac_ptr, FDO_HMAC_384_SIZE, FDOResponseMessage->HMAC, - hmac_length) != 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto out; - } - } - } + fdo_heci_update_file_request FDORequest; + fdo_heci_update_file_response *FDOResponseMessage; + TEESTATUS status = -1; + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + FDORequest.header.command = FDO_HECI_UPDATE_FILE; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.file_id = file_id; + FDORequest.data_length = data_length; + FDORequest.header.length = sizeof(FDORequest.data_length) + + sizeof(FDORequest.file_id) + + FDORequest.data_length; + + if (file_id == OVH_FILE_ID) { + if (memcpy_s(FDORequest.data, FDORequest.data_length, data, + data_length) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto out; + } + } else { + FDORequest.data[0] = *data; + } + + const size_t sz = sizeof(FDORequest.header) + FDORequest.header.length; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + + FDOResponseMessage = (fdo_heci_update_file_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; + + if (file_id == OVH_FILE_ID) { + if (hmac_ptr) { + if (memcpy_s(hmac_ptr, FDO_HMAC_384_SIZE, + FDOResponseMessage->HMAC, + hmac_length) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto out; + } + } + } out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -534,64 +542,63 @@ TEESTATUS fdo_heci_update_file(TEEHANDLE *cl, uint32_t file_id, uint8_t *data, * @param fdo_status - status of the HECI call * @return status for API function */ -TEESTATUS fdo_heci_commit_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status) +TEESTATUS fdo_heci_commit_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status) { - if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { - LOG(LOG_ERROR,"Invalid file id!\n"); - return -1; - } - - fdo_heci_commit_file_request FDORequest; - fdo_heci_commit_file_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_COMMIT_FILE; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = sizeof(FDORequest) - sizeof(FDORequest.header); - FDORequest.file_id = file_id; - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) - { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - - - FDOResponseMessage = (fdo_heci_commit_file_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) - { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; + if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { + LOG(LOG_ERROR, "Invalid file id!\n"); + return -1; + } + + fdo_heci_commit_file_request FDORequest; + fdo_heci_commit_file_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_COMMIT_FILE; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = + sizeof(FDORequest) - sizeof(FDORequest.header); + FDORequest.file_id = file_id; + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + + FDOResponseMessage = (fdo_heci_commit_file_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -607,90 +614,89 @@ TEESTATUS fdo_heci_commit_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS * @param fdo_status - status of the HECI call * @return status for API function */ -TEESTATUS fdo_heci_read_file(TEEHANDLE *cl, uint32_t file_id, uint8_t - *data_ptr, uint32_t *data_length, uint8_t *hmac_ptr, size_t hmac_sz, - FDO_STATUS *fdo_status) +TEESTATUS fdo_heci_read_file(TEEHANDLE *cl, uint32_t file_id, uint8_t *data_ptr, + uint32_t *data_length, uint8_t *hmac_ptr, + size_t hmac_sz, FDO_STATUS *fdo_status) { - if (!data_ptr || !data_length) { + if (!data_ptr || !data_length) { return -1; } - if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { - LOG(LOG_ERROR,"Invalid file id!\n"); - return -1; - } - - fdo_heci_read_file_request FDORequest; - fdo_heci_read_file_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_READ_FILE; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = sizeof(FDORequest) - sizeof(FDORequest.header); - FDORequest.file_id = file_id; - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - - - FDOResponseMessage = (fdo_heci_read_file_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; - *data_length = FDOResponseMessage->data_length; - - if (file_id == OVH_FILE_ID && *data_length) { - if (memcpy_s(data_ptr, *data_length, - FDOResponseMessage->data, FDOResponseMessage->data_length) != - 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto out; - } - - if (memcpy_s(hmac_ptr, hmac_sz, FDOResponseMessage->HMAC, - FDO_HMAC_384_SIZE) != 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto out; - } - } else if (*data_length) { - if (memcpy_s(data_ptr, *data_length, - FDOResponseMessage->data, FDOResponseMessage->data_length) != - 0) { - LOG(LOG_ERROR, "Memcpy Failed\n"); - goto out; - } - } + if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { + LOG(LOG_ERROR, "Invalid file id!\n"); + return -1; + } + + fdo_heci_read_file_request FDORequest; + fdo_heci_read_file_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_READ_FILE; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = + sizeof(FDORequest) - sizeof(FDORequest.header); + FDORequest.file_id = file_id; + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + + FDOResponseMessage = (fdo_heci_read_file_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; + *data_length = FDOResponseMessage->data_length; + + if (file_id == OVH_FILE_ID && *data_length) { + if (memcpy_s(data_ptr, *data_length, FDOResponseMessage->data, + FDOResponseMessage->data_length) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto out; + } + + if (memcpy_s(hmac_ptr, hmac_sz, FDOResponseMessage->HMAC, + FDO_HMAC_384_SIZE) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto out; + } + } else if (*data_length) { + if (memcpy_s(data_ptr, *data_length, FDOResponseMessage->data, + FDOResponseMessage->data_length) != 0) { + LOG(LOG_ERROR, "Memcpy Failed\n"); + goto out; + } + } out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -701,63 +707,63 @@ TEESTATUS fdo_heci_read_file(TEEHANDLE *cl, uint32_t file_id, uint8_t * @param fdo_status - status of the HECI call * @return status for API function */ -TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status) +TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status) { - if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { - LOG(LOG_ERROR,"Invalid file id!\n"); - return -1; - } - - fdo_heci_clear_file_request FDORequest; - fdo_heci_clear_file_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_CLEAR_FILE; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = sizeof(FDORequest) - sizeof(FDORequest.header); - FDORequest.file_id = file_id; - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) - { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - - - FDOResponseMessage = (fdo_heci_clear_file_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; + if (file_id != OVH_FILE_ID && file_id != DS_FILE_ID) { + LOG(LOG_ERROR, "Invalid file id!\n"); + return -1; + } + + fdo_heci_clear_file_request FDORequest; + fdo_heci_clear_file_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_CLEAR_FILE; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = + sizeof(FDORequest) - sizeof(FDORequest.header); + FDORequest.file_id = file_id; + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + + FDOResponseMessage = (fdo_heci_clear_file_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } @@ -769,54 +775,52 @@ TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS */ TEESTATUS fdo_heci_close_interface(TEEHANDLE *cl, FDO_STATUS *fdo_status) { - fdo_heci_close_interface_request FDORequest; - fdo_heci_close_interface_response* FDOResponseMessage; - TEESTATUS status = -1; - - FDORequest.header.command = FDO_HECI_CLOSE_INTERFACE; - FDORequest.header.app_id = FDO_APP_ID; - FDORequest.header.length = 0; - const size_t sz = sizeof(FDORequest); - unsigned char *buf = NULL; - size_t rsz, wsz = 0; - - rsz = cl->maxMsgLen; //sets maxMsgLen - buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); - if (buf == NULL) { - LOG(LOG_ERROR,"calloc(%u) failed\n", (unsigned)rsz); - goto out; - } - - status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); - if (status != TEE_SUCCESS) { - LOG(LOG_ERROR, "TeeWrite failed (%u) [attempted %u cmd bytes]\n", - status, (unsigned)sizeof(FDORequest)); - goto out; - } - - if (wsz != sz) - { - status = TEE_UNABLE_TO_COMPLETE_OPERATION; - goto out; - } - - size_t NumOfBytesRead = 0; - - - FDOResponseMessage = (fdo_heci_close_interface_response*)(buf); - - status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); - if (status != TEE_SUCCESS) - { - LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); - goto out; - } - - *fdo_status = FDOResponseMessage->status; + fdo_heci_close_interface_request FDORequest; + fdo_heci_close_interface_response *FDOResponseMessage; + TEESTATUS status = -1; + + FDORequest.header.command = FDO_HECI_CLOSE_INTERFACE; + FDORequest.header.app_id = FDO_APP_ID; + FDORequest.header.length = 0; + const size_t sz = sizeof(FDORequest); + unsigned char *buf = NULL; + size_t rsz, wsz = 0; + + rsz = cl->maxMsgLen; // sets maxMsgLen + buf = (unsigned char *)calloc(rsz, sizeof(unsigned char)); + if (buf == NULL) { + LOG(LOG_ERROR, "calloc(%u) failed\n", (unsigned)rsz); + goto out; + } + + status = TeeWrite(cl, &FDORequest, sz, &wsz, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, + "TeeWrite failed (%u) [attempted %u cmd bytes]\n", status, + (unsigned)sizeof(FDORequest)); + goto out; + } + + if (wsz != sz) { + status = TEE_UNABLE_TO_COMPLETE_OPERATION; + goto out; + } + + size_t NumOfBytesRead = 0; + + FDOResponseMessage = (fdo_heci_close_interface_response *)(buf); + + status = TeeRead(cl, buf, rsz, &NumOfBytesRead, 0); + if (status != TEE_SUCCESS) { + LOG(LOG_ERROR, "TeeRead failed (%u)\n", status); + goto out; + } + + *fdo_status = FDOResponseMessage->status; out: if (buf) { - fdo_free(buf); - } + fdo_free(buf); + } return status; } diff --git a/cse/include/clear_cse.h b/cse/include/clear_cse.h index 29186b9f..8ce2ac90 100644 --- a/cse/include/clear_cse.h +++ b/cse/include/clear_cse.h @@ -11,8 +11,8 @@ TEESTATUS heci_init(TEEHANDLE *cl); void heci_deinit(TEEHANDLE *cl); -TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status); +TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status); int main(void); #endif /* __FDO_CLEAR_CSE_H__ */ \ No newline at end of file diff --git a/cse/include/cse_tools.h b/cse/include/cse_tools.h index 7e5135fe..4a6f579c 100644 --- a/cse/include/cse_tools.h +++ b/cse/include/cse_tools.h @@ -7,18 +7,18 @@ #define __FDO_CSE_H__ #include "safe_lib.h" -#include "fdoCrypto.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto.h" +#include "fdo_crypto_hal.h" #include "cse_utils.h" int32_t cse_get_cert_chain(fdo_byte_array_t **cse_cert); int32_t cse_get_cose_sig_structure(fdo_byte_array_t **cose_sig_structure, - uint8_t *data, size_t data_len); -int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, fdo_byte_array_t - **cse_maroeprefix, fdo_byte_array_t *cose_sig_structure, - uint8_t *data, size_t data_len); -int32_t cse_load_file(uint32_t file_id, uint8_t *data_ptr, uint32_t - *data_length, uint8_t *hmac_ptr, size_t hmac_sz); - + uint8_t *data, size_t data_len); +int32_t cse_get_test_sig(fdo_byte_array_t **cse_signature, + fdo_byte_array_t **cse_maroeprefix, + fdo_byte_array_t *cose_sig_structure, uint8_t *data, + size_t data_len); +int32_t cse_load_file(uint32_t file_id, uint8_t *data_ptr, + uint32_t *data_length, uint8_t *hmac_ptr, size_t hmac_sz); #endif /* __FDO_CSE_H__ */ \ No newline at end of file diff --git a/cse/include/cse_utils.h b/cse/include/cse_utils.h index a0ec898e..60669f4e 100644 --- a/cse/include/cse_utils.h +++ b/cse/include/cse_utils.h @@ -33,27 +33,27 @@ TEESTATUS heci_init(TEEHANDLE *cl); void heci_deinit(TEEHANDLE *cl); -TEESTATUS fdo_heci_get_version(TEEHANDLE *cl, uint16_t *major_v, uint16_t - *minor_v, FDO_STATUS *fdo_status); -TEESTATUS fdo_heci_get_cert_chain(TEEHANDLE *cl, uint8_t *cert_chain, uint16_t - *len_cert, FDO_STATUS *fdo_status); -TEESTATUS fdo_heci_ecdsa_device_sign_challenge(TEEHANDLE *cl, uint8_t *data, - uint32_t data_length, uint8_t *sig_ptr, size_t sig_len, uint8_t - *mp_ptr, uint32_t *mp_len, FDO_STATUS *fdo_status); +TEESTATUS fdo_heci_get_version(TEEHANDLE *cl, uint16_t *major_v, + uint16_t *minor_v, FDO_STATUS *fdo_status); +TEESTATUS fdo_heci_get_cert_chain(TEEHANDLE *cl, uint8_t *cert_chain, + uint16_t *len_cert, FDO_STATUS *fdo_status); +TEESTATUS fdo_heci_ecdsa_device_sign_challenge( + TEEHANDLE *cl, uint8_t *data, uint32_t data_length, uint8_t *sig_ptr, + size_t sig_len, uint8_t *mp_ptr, uint32_t *mp_len, FDO_STATUS *fdo_status); TEESTATUS fdo_heci_generate_random(TEEHANDLE *cl, uint8_t *random_bytes, - uint32_t length, FDO_STATUS *fdo_status); -TEESTATUS fdo_heci_load_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status); + uint32_t length, FDO_STATUS *fdo_status); +TEESTATUS fdo_heci_load_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status); TEESTATUS fdo_heci_update_file(TEEHANDLE *cl, uint32_t file_id, uint8_t *data, - uint32_t data_length, uint8_t *hmac_ptr, size_t hmac_length, FDO_STATUS - *fdo_status); -TEESTATUS fdo_heci_commit_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status); -TEESTATUS fdo_heci_read_file(TEEHANDLE *cl, uint32_t file_id, uint8_t - *data_ptr, uint32_t *data_length, uint8_t *hmac_ptr, size_t hmac_sz, - FDO_STATUS *fdo_status); -TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, FDO_STATUS - *fdo_status); + uint32_t data_length, uint8_t *hmac_ptr, + size_t hmac_length, FDO_STATUS *fdo_status); +TEESTATUS fdo_heci_commit_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status); +TEESTATUS fdo_heci_read_file(TEEHANDLE *cl, uint32_t file_id, uint8_t *data_ptr, + uint32_t *data_length, uint8_t *hmac_ptr, + size_t hmac_sz, FDO_STATUS *fdo_status); +TEESTATUS fdo_heci_clear_file(TEEHANDLE *cl, uint32_t file_id, + FDO_STATUS *fdo_status); TEESTATUS fdo_heci_close_interface(TEEHANDLE *cl, FDO_STATUS *fdo_status); #endif /* __FDOCSE_H__ */ \ No newline at end of file diff --git a/cse/include/fdo_cse.h b/cse/include/fdo_cse.h index 399e5182..2d360f79 100644 --- a/cse/include/fdo_cse.h +++ b/cse/include/fdo_cse.h @@ -23,272 +23,229 @@ writing. --*/ - #ifndef _FDO_DEFS_H_ #define _FDO_DEFS_H_ #include #include -#define FDO_MAX_CERT_CHAIN_SIZE 3200 //4*800 -#define FDO_ODCA_CHAIN_LEN 4 -#define FDO_MAX_SIGNATURE_LENGTH 1024 -#define FDO_MAX_DATA_TO_SIGN 1024 -#define FDO_HMAC_384_SIZE 48 -#define FDO_MAX_FILE_SIZE 8*1024 //8k -#define FDO_SIGNATURE_LENGTH 96 // FDO uses 384 curve so signature length will be 384/4 = 96 +#define FDO_MAX_CERT_CHAIN_SIZE 3200 // 4*800 +#define FDO_ODCA_CHAIN_LEN 4 +#define FDO_MAX_SIGNATURE_LENGTH 1024 +#define FDO_MAX_DATA_TO_SIGN 1024 +#define FDO_HMAC_384_SIZE 48 +#define FDO_MAX_FILE_SIZE 8 * 1024 // 8k +#define FDO_SIGNATURE_LENGTH \ + 96 // FDO uses 384 curve so signature length will be 384/4 = 96 #define FDO_MAX_MAROE_PREFIX_SIZE 100 -#define FDO_MAX_RANDOM 256 -#define FDO_DATA_LENGTH_SIZE 4 -#define FDO_APP_NAME "FDO" -#define FDO_APP_NAME_MAX_LENGTH 3 //temp gil??? - - -typedef enum -{ - FDO_ID =1, -} -App_ID; - - -typedef enum -{ - FDO_HECI_GET_VERSION = 1, - FDO_HECI_GET_CERTIFICATE_CHAIN = 4, - FDO_HECI_ECDSA_DEVICE_SIGN_CHALLENGE, - FDO_HECI_GENERATE_RANDOM, - FDO_HECI_LOAD_FILE = 11, - FDO_HECI_UPDATE_FILE, - FDO_HECI_COMMIT_FILE, - FDO_HECI_READ_FILE, - FDO_HECI_CLEAR_FILE, - FDO_HECI_CLOSE_INTERFACE = 20, +#define FDO_MAX_RANDOM 256 +#define FDO_DATA_LENGTH_SIZE 4 +#define FDO_APP_NAME "FDO" +#define FDO_APP_NAME_MAX_LENGTH 3 // temp gil??? + +typedef enum { + FDO_ID = 1, +} App_ID; + +typedef enum { + FDO_HECI_GET_VERSION = 1, + FDO_HECI_GET_CERTIFICATE_CHAIN = 4, + FDO_HECI_ECDSA_DEVICE_SIGN_CHALLENGE, + FDO_HECI_GENERATE_RANDOM, + FDO_HECI_LOAD_FILE = 11, + FDO_HECI_UPDATE_FILE, + FDO_HECI_COMMIT_FILE, + FDO_HECI_READ_FILE, + FDO_HECI_CLEAR_FILE, + FDO_HECI_CLOSE_INTERFACE = 20, } FDO_HECI_COMMANDS; -typedef enum -{ - FDO_STATUS_SUCCESS, - FDO_STATUS_FEATURE_NOT_SUPPORTED, - FDO_STATUS_ACTION_NOT_ALLOWED, - FDO_STATUS_INVALID_INPUT_PARAMETER, - FDO_STATUS_INTERNAL_ERROR, - FDO_STATUS_FAIL_TO_LOAD_FILE, - FDO_STATUS_API_INTERFACE_IS_CLOSED, +typedef enum { + FDO_STATUS_SUCCESS, + FDO_STATUS_FEATURE_NOT_SUPPORTED, + FDO_STATUS_ACTION_NOT_ALLOWED, + FDO_STATUS_INVALID_INPUT_PARAMETER, + FDO_STATUS_INTERNAL_ERROR, + FDO_STATUS_FAIL_TO_LOAD_FILE, + FDO_STATUS_API_INTERFACE_IS_CLOSED, } FDO_STATUS; - - -typedef enum -{ - FDO_SIGN_ECDSA384_WITH_SHA384 = 0, +typedef enum { + FDO_SIGN_ECDSA384_WITH_SHA384 = 0, } FDO_SIGNING_MECHANISM; -typedef enum -{ - FDO_FILE_ID_OVH = 0, - FDO_FILE_ID_DEVICE_STATE, - FDO_FILE_ID_END, +typedef enum { + FDO_FILE_ID_OVH = 0, + FDO_FILE_ID_DEVICE_STATE, + FDO_FILE_ID_END, } FDO_FILE_ID; // HECI interface #pragma pack(1) -typedef struct -{ - uint16_t major_version; - uint16_t minor_version; -}fdo_heci_version; - +typedef struct { + uint16_t major_version; + uint16_t minor_version; +} fdo_heci_version; -typedef struct -{ - fdo_heci_version version; - uint8_t command; - uint8_t app_id; // 1 for FDO. - uint16_t length; //length of the command -}fdo_heci_header; +typedef struct { + fdo_heci_version version; + uint8_t command; + uint8_t app_id; // 1 for FDO. + uint16_t length; // length of the command +} fdo_heci_header; -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; -}fdo_heci_default_response; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; +} fdo_heci_default_response; /***********************************************/ /***** FDO_HECI_GET_VERSION = 1 *****/ /***********************************************/ -typedef struct -{ - fdo_heci_header header; -}fdo_heci_get_version_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; - fdo_heci_version version; -}fdo_heci_get_version_response; - +typedef struct { + fdo_heci_header header; +} fdo_heci_get_version_request; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; + fdo_heci_version version; +} fdo_heci_get_version_response; /***********************************************/ /***** FDO_HECI_GET_CERTIFICATE_CHAIN = 4 *****/ /***********************************************/ -typedef struct -{ - fdo_heci_header header; -}fdo_heci_get_certificate_chain_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; - uint16_t lengths_of_certificates[FDO_ODCA_CHAIN_LEN]; - uint8_t certificate_chain[FDO_MAX_CERT_CHAIN_SIZE]; -}fdo_heci_get_certificate_chain_response; +typedef struct { + fdo_heci_header header; +} fdo_heci_get_certificate_chain_request; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; + uint16_t lengths_of_certificates[FDO_ODCA_CHAIN_LEN]; + uint8_t certificate_chain[FDO_MAX_CERT_CHAIN_SIZE]; +} fdo_heci_get_certificate_chain_response; /****************************************************/ /***** FDO_HECI_ECDSA_DEVICE_SIGN_CHALLENGE = 5 *****/ /****************************************************/ -typedef struct -{ - fdo_heci_header header; - uint32_t data_length; //max length of 1024Byte ? - uint8_t data[FDO_MAX_DATA_TO_SIGN]; -}fdo_heci_ecdsa_device_sign_challenge_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; - FDO_SIGNING_MECHANISM signature_mechanism; - uint32_t maroeprefix_length; - uint8_t maroeprefix[FDO_MAX_MAROE_PREFIX_SIZE]; - uint8_t signature[FDO_MAX_SIGNATURE_LENGTH]; -}fdo_heci_ecdsa_device_sign_challenge_response; - +typedef struct { + fdo_heci_header header; + uint32_t data_length; // max length of 1024Byte ? + uint8_t data[FDO_MAX_DATA_TO_SIGN]; +} fdo_heci_ecdsa_device_sign_challenge_request; + +typedef struct { + fdo_heci_header header; + FDO_STATUS status; + FDO_SIGNING_MECHANISM signature_mechanism; + uint32_t maroeprefix_length; + uint8_t maroeprefix[FDO_MAX_MAROE_PREFIX_SIZE]; + uint8_t signature[FDO_MAX_SIGNATURE_LENGTH]; +} fdo_heci_ecdsa_device_sign_challenge_response; /************************************************/ /***** FDO_HECI_GENERATE_RANDOM = 6 *****/ /************************************************/ -typedef struct -{ - fdo_heci_header header; - uint32_t length; //MAX is 256 -}fdo_heci_generate_random_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; - uint32_t length; //MAX is 256, same value as input - uint8_t random_bytes[FDO_MAX_RANDOM]; -}fdo_heci_generate_random_response; +typedef struct { + fdo_heci_header header; + uint32_t length; // MAX is 256 +} fdo_heci_generate_random_request; + +typedef struct { + fdo_heci_header header; + FDO_STATUS status; + uint32_t length; // MAX is 256, same value as input + uint8_t random_bytes[FDO_MAX_RANDOM]; +} fdo_heci_generate_random_response; /********************************************/ /***** FDO_HECI_LOAD_FILE = 11 *****/ /********************************************/ -typedef struct -{ - fdo_heci_header header; - uint32_t file_id; //0 or 1 -}fdo_heci_load_file_request; +typedef struct { + fdo_heci_header header; + uint32_t file_id; // 0 or 1 +} fdo_heci_load_file_request; -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; -}fdo_heci_load_file_response; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; +} fdo_heci_load_file_response; /********************************************/ /***** FDO_HECI_UPDATE_FILE = 12 *****/ /********************************************/ -typedef struct -{ - fdo_heci_header header; - uint32_t file_id; //0 or 1 - uint32_t data_length; - uint8_t data[FDO_MAX_FILE_SIZE]; -} fdo_heci_update_file_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; - uint8_t HMAC[FDO_HMAC_384_SIZE]; -} fdo_heci_update_file_response; +typedef struct { + fdo_heci_header header; + uint32_t file_id; // 0 or 1 + uint32_t data_length; + uint8_t data[FDO_MAX_FILE_SIZE]; +} fdo_heci_update_file_request; + +typedef struct { + fdo_heci_header header; + FDO_STATUS status; + uint8_t HMAC[FDO_HMAC_384_SIZE]; +} fdo_heci_update_file_response; /********************************************/ /***** FDO_HECI_COMMIT_FILE = 13 *****/ /********************************************/ -typedef struct -{ - fdo_heci_header header; - uint32_t file_id; //0 or 1 -} fdo_heci_commit_file_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; -} fdo_heci_commit_file_response; +typedef struct { + fdo_heci_header header; + uint32_t file_id; // 0 or 1 +} fdo_heci_commit_file_request; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; +} fdo_heci_commit_file_response; /********************************************/ /***** FDO_HECI_READ_FILE = 14 *****/ /********************************************/ -typedef struct -{ - fdo_heci_header header; - uint32_t file_id; //0 or 1 +typedef struct { + fdo_heci_header header; + uint32_t file_id; // 0 or 1 -} fdo_heci_read_file_request; +} fdo_heci_read_file_request; -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; - uint32_t data_length; - uint8_t data[FDO_MAX_FILE_SIZE]; - uint8_t HMAC[FDO_HMAC_384_SIZE]; -} fdo_heci_read_file_response; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; + uint32_t data_length; + uint8_t data[FDO_MAX_FILE_SIZE]; + uint8_t HMAC[FDO_HMAC_384_SIZE]; +} fdo_heci_read_file_response; /********************************************/ /***** FDO_HECI_CLEAR_FILE = 15 *****/ /********************************************/ -typedef struct -{ - fdo_heci_header header; - uint32_t file_id; //0 or 1 -} fdo_heci_clear_file_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; -} fdo_heci_clear_file_response; - +typedef struct { + fdo_heci_header header; + uint32_t file_id; // 0 or 1 +} fdo_heci_clear_file_request; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; +} fdo_heci_clear_file_response; /************************************************/ /***** FDO_HECI_CLOSE_INTERFACE = 20 *****/ /************************************************/ -typedef struct -{ - fdo_heci_header header; -} fdo_heci_close_interface_request; - -typedef struct -{ - fdo_heci_header header; - FDO_STATUS status; -} fdo_heci_close_interface_response; - +typedef struct { + fdo_heci_header header; +} fdo_heci_close_interface_request; +typedef struct { + fdo_heci_header header; + FDO_STATUS status; +} fdo_heci_close_interface_response; #pragma pack() diff --git a/data/client.conf b/data/client.conf new file mode 100644 index 00000000..32d5fc3d --- /dev/null +++ b/data/client.conf @@ -0,0 +1,21 @@ +[req] +distinguished_name=req_distinguished_name +x509_extensions=v3_req +prompt=no + +[req_distinguished_name] +CN=apiUser +OU=FDO project +O=LF Edge +L=Hillsboro +ST=OR +C=US + +[v3_req] +basicConstraints = CA:FALSE +nsCertType = client, email +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid,issuer +keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment +extendedKeyUsage = clientAuth, emailProtection + diff --git a/device_modules/CMakeLists.txt b/device_modules/CMakeLists.txt index 638948cf..302d6eea 100644 --- a/device_modules/CMakeLists.txt +++ b/device_modules/CMakeLists.txt @@ -6,11 +6,16 @@ client_sdk_include_directories( fdo_sys + fdo_sim ) client_sdk_sources( fdo_sys/fdo_sys.c fdo_sys/sys_utils_linux.c + fdo_sim/fdo_sim.c + fdo_sim/fdo_sim_download.c + fdo_sim/fdo_sim_command.c + fdo_sim/sim_utils_linux.c ) diff --git a/device_modules/fdo_sim/fdo_sim.c b/device_modules/fdo_sim/fdo_sim.c new file mode 100644 index 00000000..00de7515 --- /dev/null +++ b/device_modules/fdo_sim/fdo_sim.c @@ -0,0 +1,291 @@ +/* + * Copyright 2023 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +#include "util.h" +#include "fdo_sim.h" +#include "safe_lib.h" +#include +#include +#include +#include "fdo_sim_utils.h" + +// position/offset on the file from which data will be read +static size_t file_seek_pos = 0; +// size of the file from which data will be read +static size_t file_sz = 0; +// EOT value whose value is 0 for 'fetch-data'success, and 1 for failure +static int fetch_data_status = 1; + +/** + * Write CBOR-encoded fdo.download:done content into FDOW with given data. + */ +static bool write_done(fdow_t *fdow, char *module_message, size_t bin_len) +{ + + if (!module_message || !bin_len) { + LOG(LOG_ERROR, + "Module fdo_sim - Invalid params for fdo.download:done\n"); + return false; + } + + const char message[] = "done"; + if (memcpy_s(module_message, sizeof(message), message, + sizeof(message)) != 0) { + LOG(LOG_ERROR, + "Module fdo_sim - Failed to copy module message data\n"); + return false; + } + + if (!fdow_signed_int(fdow, bin_len)) { + LOG(LOG_ERROR, "Module fdo_sim - Failed to write " + "fdo.download:done content\n"); + return false; + } + + return true; +} + +/** + * Write CBOR-encoded fdo.command:exitcode content into FDOW with given data. + */ +static bool write_exitcode(fdow_t *fdow, char *module_message, size_t bin_len) +{ + + if (!module_message) { + LOG(LOG_ERROR, "Module fdo_sim - Invalid params for " + "fdo.command:exitcode\n"); + return false; + } + + const char message[] = "exitcode"; + if (memcpy_s(module_message, sizeof(message), message, + sizeof(message)) != 0) { + LOG(LOG_ERROR, + "Module fdo_sim - Failed to copy module message data\n"); + return false; + } + + if (!fdow_signed_int(fdow, bin_len)) { + LOG(LOG_ERROR, "Module fdo_sim - Failed to write " + "fdo.command:exitcode content\n"); + return false; + } + + return true; +} + +/** + * List of helper functions used in switch case + * + * fdo_sim_start + * fdo_sim_failure + * fdo_sim_has_more_dsi + * fdo_sim_is_more_dsi + * fdo_sim_get_dsi_count + * fdo_sim_get_dsi + * fdo_sim_end + */ + +int fdo_sim_start(fdor_t **fdor, fdow_t **fdow) +{ + int result = FDO_SI_INTERNAL_ERROR; + + // Initialize module's CBOR Reader/Writer objects. + *fdow = FSIMModuleAlloc(sizeof(fdow_t)); + if (!fdow_init(*fdow) || + !fdo_block_alloc_with_size(&(*fdow)->b, MOD_MAX_BUFF_SIZE)) { + LOG(LOG_ERROR, "Module fdo_sim - FDOW " + "Initialization/Allocation failed!\n"); + result = FDO_SI_CONTENT_ERROR; + FSIMModuleFree(*fdow); + goto end; + } + + *fdor = FSIMModuleAlloc(sizeof(fdor_t)); + if (!fdor_init(*fdor) || + !fdo_block_alloc_with_size(&(*fdor)->b, MOD_MAX_BUFF_SIZE)) { + LOG(LOG_ERROR, "Module fdo_sim - FDOR " + "Initialization/Allocation failed!\n"); + FSIMModuleFree(*fdor); + goto end; + } + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_failure(fdor_t **fdor, fdow_t **fdow) +{ + // perform clean-ups as needed + if (!fsim_process_data(FDO_SIM_MOD_MSG_EXIT, NULL, 0, NULL, NULL)) { + LOG(LOG_ERROR, "Module fdo_sim - Failed to perform " + "clean-up operations\n"); + return FDO_SI_INTERNAL_ERROR; + } + + if (*fdow) { + fdow_flush(*fdow); + FSIMModuleFree(*fdow); + } + if (*fdor) { + fdor_flush(*fdor); + FSIMModuleFree(*fdor); + } + return FDO_SI_SUCCESS; +} + +int fdo_sim_has_more_dsi(bool *has_more, bool hasmore) +{ + // calculate whether there is ServiceInfo to send NOW and update + // 'has_more'. For testing purposes, set this to true here, and + // false once first write is done. + if (!has_more) { + return FDO_SI_CONTENT_ERROR; + } + + *has_more = hasmore; + if (*has_more) { + LOG(LOG_INFO, + "Module fdo_sim - There is ServiceInfo to send\n"); + } + return FDO_SI_SUCCESS; +} + +int fdo_sim_is_more_dsi(bool *is_more, bool ismore) +{ + // calculate whether there is ServiceInfo to send in the NEXT + // iteration and update 'is_more'. + if (!is_more) { + LOG(LOG_ERROR, "is_more is NULL\n"); + return FDO_SI_CONTENT_ERROR; + } + + // sending either true or false is valid + // for simplicity, setting this to 'false' always, + // since managing 'ismore' by looking-ahead can be error-prone + *is_more = ismore; + return FDO_SI_SUCCESS; +} + +int fdo_sim_get_dsi_count(uint16_t *num_module_messages) +{ + // calculate the number of ServiceInfo items to send NOW and update + // 'num_module_messages'. For testing purposes, set this to 1 here, and + // 0 once first write is done. + if (!num_module_messages) { + return FDO_SI_CONTENT_ERROR; + } + *num_module_messages = 1; + return FDO_SI_SUCCESS; +} + +int fdo_sim_get_dsi(fdow_t **fdow, size_t mtu, char *module_message, + uint8_t *module_val, size_t *module_val_sz, size_t bin_len, + uint8_t *bin_data, size_t temp_module_val_sz, bool *hasmore, + fdoSimModMsg *write_type, char *filename) +{ + // write Device ServiceInfo using 'fdow' by partitioning the + // messages as per MTU, here. + if (mtu == 0 || !module_message || !module_val || !module_val_sz) { + return FDO_SI_CONTENT_ERROR; + } + + int result = FDO_SI_INTERNAL_ERROR; + + (void)filename; + + // reset and initialize FDOW's encoder for usage + fdo_block_reset(&(*fdow)->b); + if (!fdow_encoder_init(*fdow)) { + LOG(LOG_ERROR, "Module fdo_sim - Failed to initialize " + "FDOW encoder\n"); + goto end; + } + + if (!*hasmore || *write_type == FDO_SIM_MOD_MSG_EXIT) { + LOG(LOG_ERROR, "Module fdo_sim - Invalid state\n"); + goto end; + } + + if (*write_type == FDO_SIM_MOD_MSG_DONE) { + if (!write_done(*fdow, module_message, bin_len)) { + LOG(LOG_ERROR, "Module fdo_sim - Failed to " + "respond with fdo.download:done\n"); + goto end; + } + *hasmore = false; + LOG(LOG_DEBUG, + "Module fdo_sim - Responded with fdo.download:done\n"); + } else if (*write_type == FDO_SIM_MOD_MSG_EXIT_CODE) { + if (!write_exitcode(*fdow, module_message, bin_len)) { + LOG(LOG_ERROR, "Module fdo_sim - Failed to " + "respond with fdo.command:exitcode\n"); + goto end; + } + *hasmore = false; + LOG(LOG_DEBUG, + "Module fdo_sim - Responded with fdo.command:exitcode\n"); + } else if (*write_type == FDO_SIM_MOD_MSG_NONE) { + // shouldn't reach here, if we do, it might a logical + // error log and fail + LOG(LOG_ERROR, "Module fdo_sim - Invalid module write state\n"); + goto end; + } + + if (!fdow_encoded_length(*fdow, &temp_module_val_sz)) { + LOG(LOG_ERROR, + "Module fdo_sim - Failed to get encoded length\n"); + goto end; + } + *module_val_sz = temp_module_val_sz; + if (memcpy_s(module_val, *module_val_sz, (*fdow)->b.block, + *module_val_sz) != 0) { + LOG(LOG_ERROR, "Module fdo_sim - Failed to copy " + "CBOR-encoded module value\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + result = fdo_sim_end(NULL, fdow, result, bin_data, NULL, 0, hasmore, + write_type); + return result; +} + +int fdo_sim_end(fdor_t **fdor, fdow_t **fdow, int result, uint8_t *bin_data, + uint8_t **exec_instr, size_t total_exec_array_length, + bool *hasmore, fdoSimModMsg *write_type) +{ + // End of function, clean-up state variables/objects + if (bin_data) { + FSIMModuleFree(bin_data); + } + if (exec_instr && total_exec_array_length > 0) { + int exec_counter = total_exec_array_length - 1; + while (exec_counter >= 0) { + FSIMModuleFree(exec_instr[exec_counter]); + --exec_counter; + } + FSIMModuleFree(exec_instr); + total_exec_array_length = 0; + } + if (result != FDO_SI_SUCCESS) { + // clean-up state variables/objects + *hasmore = false; + file_sz = 0; + file_seek_pos = 0; + fetch_data_status = 1; + *write_type = FDO_SIM_MOD_MSG_EXIT; + + if (*fdow) { + fdow_flush(*fdow); + FSIMModuleFree(*fdow); + } + if (*fdor) { + fdor_flush(*fdor); + FSIMModuleFree(*fdor); + } + } + return result; +} diff --git a/device_modules/fdo_sim/fdo_sim.h b/device_modules/fdo_sim/fdo_sim.h new file mode 100644 index 00000000..7439ad5a --- /dev/null +++ b/device_modules/fdo_sim/fdo_sim.h @@ -0,0 +1,129 @@ +/* + * Copyright 2023 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +#ifndef __FDO_SYS_H__ +#define __FDO_SYS_H__ + +#include +#include +#include "fdomodules.h" +#include "fdo_sim_utils.h" + +// Maximum buffer size to be used for reading/writing CBOR data +#define MOD_MAX_BUFF_SIZE 8192 + +// file path could also be supplied +#define FILE_NAME_LEN 150 + +#define MOD_ACTIVE_TAG "active" +#define MOD_ACTIVE_STATUS "1" + +// maximum length of exec command after combining all arguments of received exec +// array +#define MOD_MAX_EXEC_LEN 1024 +// maximum length of the individual text arguments in the received exec array +#define MOD_MAX_EXEC_ARG_LEN 100 + +/** + * The registered callback method for 'fdo_sim' ServiceInfo module. + * The implementation is responsible for handling the received Owner + * ServiceInfo, and for generating the Device ServiceInfo to send. + * + * When module_message, module_val and module_val_sz are used as inputs in type + * 'FDO_SI_SET_OSI', these represent the moduleMessage, CBOR-encoded + * (bstr-unwrapped) module value i.e ServiceInfoVal cbor.bytes, as received in + * TO2.OwnerServiceInfo (Type 69), and its length. The implementation must parse + * and process the input module value depending on the given module message, and + * return. + * + * However, the same set of variables are used as output parameters in type + * 'FDO_SI_GET_DSI', wherein, module_message stores the current moduleMessage, + * module_val stores the response CBOR-encoded module value (ServiceInfoVal), + * and module_val_sz stores the corresponding length. The implementation is + * responsible for generating the CBOR-encoded module value using any + * mechanisms/third-party library. In the current implementation, the + * CBOR-encoder/decoder from 'lib/fdoblockio.c' is used. These 3 parameters are + * then, used to generate ServiceInfoKV at TO2.DeviceServiceInfo (Type 68), and + * sent to the Owner. + * + * The input FDOW object to be used to write the desired 'ServiceInfo' structure + * as per the specification, that will be sent to the Owner. The FDOW can also + * be used for other purposes such as ServiceInfo message partitioning (fit + * within MTU), or, determining has_more/is_more etc. The module implemenation + * is responsible for maintaining any internal state information, as needed. + * + * The input fdo_sdk_si_type can be used to do specific tasks depending on the + * use-case. (The types could be updated in the future) + * + * @param type - [IN] enum value to describe the operation to be done. + * @param module_message - [IN/OUT] moduleMessage that decides how + * ServiceInfoVal is processed. + * @param module_val - [IN/OUT] bstr-unwrapped ServiceInfoVal corresponding to + * the moduleMessage. + * @param module_val_sz - [IN/OUT] ServiceInfoVal length corresponding to the + * moduleMessage. + * @param num_module_messages - [OUT] Number of ServiceInfoKVs to be sent. + * Currently UNUSED. + * @param has_more - [OUT] pointer to bool whose value must be set to + * 'true' if there is Device ServiceInfo to send NOW/immediately, OR, + * 'false' if there is no Device ServiceInfo to send NOW/immediately. + * @param is_more - [OUT] pointer to bool whose value must be set to + * 'true' if there is Device ServiceInfo to send in the NEXT ietration, OR, + * 'false' if there is no Device ServiceInfo to send in the NEXT iteration. + * @param mtu - [IN] MTU value to be used as the upper bound for the ServiceInfo + * length. + * @return integer value FDO_SI_CONTENT_ERROR (0), FDO_SI_INTERNAL_ERROR (1), + * FDO_SI_SUCCESS (2). + */ +int fdo_sim_download(fdo_sdk_si_type type, char *module_message, + uint8_t *module_val, size_t *module_val_sz, + uint16_t *num_module_messages, bool *has_more, + bool *is_more, size_t mtu); + +int fdo_sim_command(fdo_sdk_si_type type, char *module_message, + uint8_t *module_val, size_t *module_val_sz, + uint16_t *num_module_messages, bool *has_more, + bool *is_more, size_t mtu); + +// Prototype definitions for functions that are implemented in the module +int fdo_sim_start(fdor_t **fdor, fdow_t **fdow); +int fdo_sim_failure(fdor_t **fdor, fdow_t **fdow); +int fdo_sim_has_more_dsi(bool *has_more, bool hasmore); +int fdo_sim_is_more_dsi(bool *is_more, bool ismore); +int fdo_sim_get_dsi_count(uint16_t *num_module_messages); +int fdo_sim_get_dsi(fdow_t **fdow, size_t mtu, char *module_message, + uint8_t *module_val, size_t *module_val_sz, size_t bin_len, + uint8_t *bin_data, size_t temp_module_val_sz, bool *hasmore, + fdoSimModMsg *write_type, char *filename); + +int fdo_sim_set_osi_download(char *module_message, uint8_t *module_val, + size_t *module_val_sz, int *strcmp_filedesc, + int *strcmp_length, int *strcmp_sha_384, + int *strcmp_write); + +int fdo_sim_set_osi_command(char *module_message, uint8_t *module_val, + size_t *module_val_sz, int *strcmp_cmd, + int *strcmp_args, int *strcmp_may_fail, + int *strcmp_return_stdout, + int *strcmp_return_stderr, int *strcmp_sig, + int *strcmp_exec); + +int fdo_sim_set_osi_strcmp(size_t bin_len, uint8_t *bin_data); +int fdo_sim_set_osi_sha_384(size_t bin_len, uint8_t *bin_data); +int fdo_sim_set_osi_length(size_t bin_len); +int fdo_sim_set_osi_write(size_t bin_len, uint8_t *bin_data); +int fdo_sim_set_osi_may_fail(void); +int fdo_sim_set_osi_return_stdout(void); +int fdo_sim_set_osi_return_stderr(void); +int fdo_sim_set_osi_cmd(size_t bin_len, uint8_t *bin_data); +int fdo_sim_set_osi_sig(size_t sigValue); +int fdo_sim_set_osi_args(int exec_array_index, size_t *exec_instructions_sz); +int fdo_sim_set_osi_exec(uint8_t **exec_instr); +int fdo_sim_set_osi_status_cb(size_t *status_cb_array_length); +int fdo_sim_set_osi_fetch(size_t bin_len); +int fdo_sim_end(fdor_t **fdor, fdow_t **fdow, int result, uint8_t *bin_data, + uint8_t **exec_instr, size_t total_exec_array_length, + bool *hasmore, fdoSimModMsg *write_type); +#endif /* __FDO_SYS_H__ */ diff --git a/device_modules/fdo_sim/fdo_sim_command.c b/device_modules/fdo_sim/fdo_sim_command.c new file mode 100644 index 00000000..538e9d10 --- /dev/null +++ b/device_modules/fdo_sim/fdo_sim_command.c @@ -0,0 +1,490 @@ +/* + * Copyright 2023 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +#include "util.h" +#include "fdo_sim.h" +#include "safe_lib.h" +#include +#include +#include + +// CBOR-decoder. Interchangeable with any other CBOR implementation. +static fdor_t *fdor = NULL; +// CBOR-encoder. Interchangeable with any other CBOR implementation. +static fdow_t *fdow = NULL; + +// filename that will either be read from or written onto +static char filename[FILE_NAME_LEN]; +// Number of items in the exec/exec_cb array +// used to perform clean-up on memory allocated for exec/exec_cb instructions +static size_t total_exec_array_length = 0; +// local hasMore flag that represents whether the module has data/response to +// send NOW 'true' if there is data to send, 'false' otherwise +static bool hasmore = false; +// local isMore flag that represents whether the module has data/response to +// send in the NEXT messege SHOULD be 'true' if there is data to send, 'false' +// otherwise For simplicity, it is 'false' always (also a valid value) +static bool ismore = false; +static fdoSimModMsg write_type = FDO_SIM_MOD_MSG_EXIT; +static uint8_t *fdo_cmd = NULL; +static size_t fdo_cmd_len = 0; +static uint8_t **fdo_exec_instr = NULL; +static int fdo_sim_command_queue[MOD_MAX_BUFF_SIZE]; +static int front = -1; +static int rear = -1; + +int fdo_sim_command(fdo_sdk_si_type type, char *module_message, + uint8_t *module_val, size_t *module_val_sz, + uint16_t *num_module_messages, bool *has_more, + bool *is_more, size_t mtu) +{ + int strcmp_cmd = 1; + int strcmp_args = 1; + int strcmp_may_fail = 1; + int strcmp_return_stdout = 1; + int strcmp_return_stderr = 1; + int strcmp_sig = 1; + int strcmp_exec = 1; + int result = FDO_SI_INTERNAL_ERROR; + uint8_t *bin_data = NULL; + size_t bin_len = 0; + size_t exec_array_index = 0; + uint8_t **exec_instr = NULL; + size_t exec_instructions_sz = 0; + size_t temp_module_val_sz = 0; + int exit_code = -1; + + switch (type) { + case FDO_SI_START: + result = fdo_sim_start(&fdor, &fdow); + goto end; + case FDO_SI_END: + case FDO_SI_FAILURE: + result = fdo_sim_failure(&fdor, &fdow); + goto end; + case FDO_SI_HAS_MORE_DSI: + result = fdo_sim_has_more_dsi(has_more, hasmore); + goto end; + case FDO_SI_IS_MORE_DSI: + result = fdo_sim_is_more_dsi(is_more, ismore); + goto end; + case FDO_SI_GET_DSI_COUNT: + result = fdo_sim_get_dsi_count(num_module_messages); + goto end; + case FDO_SI_GET_DSI: + exit_code = (front == -1 || front > rear) + ? -1 + : fdo_sim_command_queue[front++]; + result = fdo_sim_get_dsi(&fdow, mtu, module_message, module_val, + module_val_sz, exit_code, bin_data, + temp_module_val_sz, &hasmore, + &write_type, filename); + hasmore = (front > rear) ? false : true; + goto end; + case FDO_SI_SET_OSI: + result = fdo_sim_set_osi_command( + module_message, module_val, module_val_sz, &strcmp_cmd, + &strcmp_args, &strcmp_may_fail, &strcmp_return_stdout, + &strcmp_return_stderr, &strcmp_sig, &strcmp_exec); + + if (result != FDO_SI_SUCCESS) { + goto end; + } + + if (strcmp_cmd == 0) { + result = fdo_sim_set_osi_cmd(bin_len, bin_data); + goto end; + } else if (strcmp_args == 0) { + result = fdo_sim_set_osi_args(exec_array_index, + &exec_instructions_sz); + goto end; + } else if (strcmp_may_fail == 0) { + result = fdo_sim_set_osi_may_fail(); + goto end; + } else if (strcmp_return_stdout == 0) { + result = fdo_sim_set_osi_return_stdout(); + goto end; + } else if (strcmp_return_stderr == 0) { + result = fdo_sim_set_osi_return_stderr(); + goto end; + } else if (strcmp_sig == 0) { + result = fdo_sim_set_osi_sig(bin_len); + goto end; + } else if (strcmp_exec == 0) { + result = fdo_sim_set_osi_exec(fdo_exec_instr); + goto end; + } + default: + result = FDO_SI_FAILURE; + } + +end: + result = fdo_sim_end(&fdor, &fdow, result, bin_data, exec_instr, + total_exec_array_length, &hasmore, &write_type); + return result; +} + +int fdo_sim_set_osi_command(char *module_message, uint8_t *module_val, + size_t *module_val_sz, int *strcmp_cmd, + int *strcmp_args, int *strcmp_may_fail, + int *strcmp_return_stdout, + int *strcmp_return_stderr, int *strcmp_sig, + int *strcmp_exec) +{ + if (!module_message || !module_val || !module_val_sz || + *module_val_sz > MOD_MAX_BUFF_SIZE) { + return FDO_SI_CONTENT_ERROR; + } + + int result = FDO_SI_INTERNAL_ERROR; + + // Process the received Owner ServiceInfo contained within + // 'fdor', here. + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "command", strcmp_cmd); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "execute", strcmp_exec); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "may_fail", + strcmp_may_fail); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "return_stdout", + strcmp_return_stdout); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "return_stderr", + strcmp_return_stderr); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "args", strcmp_args); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "sig", strcmp_sig); + + if (*strcmp_exec && *strcmp_may_fail && *strcmp_return_stdout && + *strcmp_return_stderr && *strcmp_cmd && *strcmp_args && + *strcmp_sig) { + LOG(LOG_ERROR, "Module fdo.command - Invalid moduleMessage\n"); + result = FDO_SI_CONTENT_ERROR; + goto end; + } + + // reset, copy CBOR data and initialize Parser. + fdo_block_reset(&fdor->b); + if (0 != memcpy_s(fdor->b.block, *module_val_sz, module_val, + *module_val_sz)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to copy buffer " + "into temporary FDOR\n"); + goto end; + } + fdor->b.block_size = *module_val_sz; + + if (!fdor_parser_init(fdor)) { + LOG(LOG_ERROR, + "Module fdo.command - Failed to init FDOR parser\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_set_osi_may_fail(void) +{ + bool may_fail; + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_boolean(fdor, &may_fail)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:may_fail\n"); + goto end; + } + + // if (may_fail == false) { + // TO-DO - implement functionality + // } + + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_set_osi_return_stdout(void) +{ + bool return_stdout; + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_boolean(fdor, &return_stdout)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:return_stdout\n"); + goto end; + } + + if (return_stdout == true) { + // TO-DO - implement functionality + } + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_set_osi_return_stderr(void) +{ + bool return_stderr; + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_boolean(fdor, &return_stderr)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:return_stderr\n"); + goto end; + } + + if (return_stderr == true) { + // TO-DO - implement functionality + } + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_set_osi_sig(size_t sigValue) +{ + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_unsigned_int(fdor, &sigValue)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to process " + "fdo.command:sig\n"); + goto end; + } + + if (sigValue == 0) { + LOG(LOG_ERROR, "Module fdo.command - Empty value received for " + "fdo.command:sig\n"); + // received file name cannot be empty + result = FDO_SI_CONTENT_ERROR; + goto end; + } + LOG(LOG_INFO, + "Module fdo.command:sig - Process Signal received : %ld\n", + sigValue); + + if (sigValue == 9 || sigValue == 15) { + result = fdo_sim_failure(&fdor, &fdow); + goto end; + } + + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_set_osi_cmd(size_t bin_len, uint8_t *bin_data) +{ + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_string_length(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:command length\n"); + goto end; + } + + if (bin_len == 0) { + LOG(LOG_ERROR, "Module fdo.command - Empty value received for " + "fdo.command:command\n"); + // received file name cannot be empty + result = FDO_SI_CONTENT_ERROR; + goto end; + } + + bin_data = FSIMModuleAlloc(bin_len * sizeof(uint8_t)); + if (!bin_data) { + LOG(LOG_ERROR, "Module fdo.command - Failed to " + "alloc for fdo.command:command\n"); + goto end; + } + + if (!fdor_text_string(fdor, (char *)bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to " + "read fdo.command:command\n"); + goto end; + } + + fdo_cmd_len = bin_len; + fdo_cmd = FSIMModuleAlloc(fdo_cmd_len * sizeof(uint8_t)); + if (!fdo_cmd) { + LOG(LOG_DEBUG, "Module fdo.command - Failed to " + "alloc for fdo.command:command\n"); + goto end; + } + + if (0 != memcpy_s(fdo_cmd, fdo_cmd_len, (char *)bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to copy command\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + result = fdo_sim_end(&fdor, &fdow, result, bin_data, NULL, + total_exec_array_length, &hasmore, &write_type); + return result; +} + +int fdo_sim_set_osi_args(int exec_array_index, size_t *exec_instructions_sz) +{ + int result = FDO_SI_INTERNAL_ERROR; + int flag = 0; + size_t exec_array_length = 0; + + if (!fdor_array_length(fdor, &exec_array_length)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:args array length\n"); + goto end; + } + + if (exec_array_length == 0) { + LOG(LOG_ERROR, "Module fdo.command - Empty array received for " + "fdo.command:args\n"); + // received exec array cannot be empty + result = FDO_SI_CONTENT_ERROR; + goto end; + } + + if (!fdor_start_array(fdor)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to start " + "fdo.command:args array\n"); + goto end; + } + + total_exec_array_length = exec_array_length + 1; + // allocate memory for exec_instr + fdo_exec_instr = (uint8_t **)FSIMModuleAlloc( + sizeof(uint8_t *) * (total_exec_array_length + 1)); + if (!fdo_exec_instr) { + LOG(LOG_ERROR, "Module fdo.command - Failed to alloc for " + "fdo.command:args instructions\n"); + goto end; + } + + fdo_exec_instr[0] = + (uint8_t *)FSIMModuleAlloc(sizeof(uint8_t) * MOD_MAX_EXEC_ARG_LEN); + if (!fdo_exec_instr[0]) { + LOG(LOG_ERROR, "Module fdo.command - Failed to alloc " + "for single fdo.command:args" + " instruction\n"); + goto end; + } + + if (0 != memset_s(fdo_exec_instr[0], + sizeof(sizeof(uint8_t) * MOD_MAX_EXEC_ARG_LEN), 0)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to clear " + "single fdo.command:args" + " instruction\n"); + goto end; + } + + if (0 != memcpy_s(fdo_exec_instr[0], MOD_MAX_EXEC_ARG_LEN, + (char *)fdo_cmd, fdo_cmd_len)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to copy command\n"); + goto end; + } + + for (exec_array_index = 1; exec_array_index <= (int)exec_array_length; + exec_array_index++) { + fdo_exec_instr[exec_array_index] = (uint8_t *)FSIMModuleAlloc( + sizeof(uint8_t) * MOD_MAX_EXEC_ARG_LEN); + if (!fdo_exec_instr[exec_array_index]) { + LOG(LOG_ERROR, "Module fdo.command - Failed to alloc " + "for single fdo.command:args" + " instruction\n"); + goto end; + } + if (0 != + memset_s(fdo_exec_instr[exec_array_index], + sizeof(sizeof(uint8_t) * MOD_MAX_EXEC_ARG_LEN), + 0)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to clear " + "single fdo.command:args" + " instruction\n"); + goto end; + } + if (!fdor_string_length(fdor, exec_instructions_sz) || + *exec_instructions_sz > MOD_MAX_EXEC_ARG_LEN) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:args text " + "length\n"); + goto end; + } + if (!fdor_text_string(fdor, + (char *)fdo_exec_instr[exec_array_index], + *exec_instructions_sz)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:args text\n"); + goto end; + } + + // last argument is the filename + if (exec_array_index == ((int)exec_array_length - 1)) { + if (memset_s(filename, sizeof(filename), 0) != 0) { + LOG(LOG_ERROR, "Module fdo.command - Failed " + "to clear filename for" + " fdo.command:args\n"); + goto end; + } + if (0 != + strncpy_s(filename, FILE_NAME_LEN, + (char *)fdo_exec_instr[exec_array_index], + *exec_instructions_sz)) { + LOG(LOG_ERROR, "Module fdo.command - Failed " + "to copy filename for" + " fdo.command:args\n"); + goto end; + } + } + } + fdo_exec_instr[exec_array_index] = NULL; + + if (!fdor_end_array(fdor)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to end " + "fdo.command:args array\n"); + goto end; + } + + flag = 1; + result = FDO_SI_SUCCESS; +end: + if (!flag) { + result = + fdo_sim_end(&fdor, &fdow, result, fdo_cmd, fdo_exec_instr, + total_exec_array_length, &hasmore, &write_type); + } else { + result = + fdo_sim_end(&fdor, &fdow, result, fdo_cmd, NULL, + total_exec_array_length, &hasmore, &write_type); + } + return result; +} + +int fdo_sim_set_osi_exec(uint8_t **exec_instr) +{ + int result = FDO_SI_INTERNAL_ERROR; + int exit_code = -1; + + if (front == -1) { + front = 0; + } + + if (fdor_is_value_null(fdor)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to read " + "fdo.command:execute array length\n"); + goto end; + } + + if (exec_instr) { + if (!fsim_process_data(FDO_SIM_MOD_MSG_EXEC, NULL, 0, filename, + (char **)exec_instr)) { + LOG(LOG_ERROR, "Module fdo.command - Failed to " + "process fdo.command:execute\n"); + goto end; + } + exit_code = 0; + hasmore = true; + write_type = FDO_SIM_MOD_MSG_EXIT_CODE; + } + fdo_sim_command_queue[++rear] = exit_code; + result = FDO_SI_SUCCESS; +end: + result = fdo_sim_end(&fdor, &fdow, result, NULL, exec_instr, + total_exec_array_length, &hasmore, &write_type); + return result; +} diff --git a/device_modules/fdo_sim/fdo_sim_download.c b/device_modules/fdo_sim/fdo_sim_download.c new file mode 100644 index 00000000..0945fd4f --- /dev/null +++ b/device_modules/fdo_sim/fdo_sim_download.c @@ -0,0 +1,414 @@ +/* + * Copyright 2023 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +#include "util.h" +#include "fdo_sim.h" +#include "safe_lib.h" +#include +#include +#include +#include "fdo_crypto_hal.h" +#include "fdo_crypto.h" + +// CBOR-decoder. Interchangeable with any other CBOR implementation. +static fdor_t *fdor = NULL; +// // CBOR-encoder. Interchangeable with any other CBOR implementation. +static fdow_t *fdow = NULL; + +// filename that will either be read from or written onto +static char filename[FILE_NAME_LEN]; +// local hasMore flag that represents whether the module has data/response to +// send NOW 'true' if there is data to send, 'false' otherwise +static bool hasmore = false; +// local isMore flag that represents whether the module has data/response to +// send in the NEXT messege SHOULD be 'true' if there is data to send, 'false' +// otherwise For simplicity, it is 'false' always (also a valid value) +static bool ismore = false; +// the type of operation to perform, generally used to manage responses +static fdoSimModMsg write_type = FDO_SIM_MOD_MSG_NONE; + +static fdo_hash_t *expectedCheckSum = NULL; +static size_t expected_len = -1; +static size_t bytes_received = 0; +static int fdo_sim_download_queue[MOD_MAX_BUFF_SIZE]; +static int front = -1; +static int rear = -1; + +int fdo_sim_download(fdo_sdk_si_type type, char *module_message, + uint8_t *module_val, size_t *module_val_sz, + uint16_t *num_module_messages, bool *has_more, + bool *is_more, size_t mtu) +{ + int strcmp_filedesc = 1; + int strcmp_sha_384 = 1; + int strcmp_length = 1; + int strcmp_write = 1; + int result = FDO_SI_INTERNAL_ERROR; + uint8_t *bin_data = NULL; + size_t bin_len = 0; + size_t temp_module_val_sz = 0; + int return_code = -1; + + switch (type) { + case FDO_SI_START: + result = fdo_sim_start(&fdor, &fdow); + goto end; + case FDO_SI_END: + case FDO_SI_FAILURE: + result = fdo_sim_failure(&fdor, &fdow); + goto end; + case FDO_SI_HAS_MORE_DSI: + result = fdo_sim_has_more_dsi(has_more, hasmore); + goto end; + case FDO_SI_IS_MORE_DSI: + result = fdo_sim_is_more_dsi(is_more, ismore); + goto end; + case FDO_SI_GET_DSI_COUNT: + result = fdo_sim_get_dsi_count(num_module_messages); + goto end; + case FDO_SI_GET_DSI: + return_code = (front == -1 || front > rear) + ? -1 + : fdo_sim_download_queue[front++]; + result = fdo_sim_get_dsi(&fdow, mtu, module_message, module_val, + module_val_sz, return_code, bin_data, + temp_module_val_sz, &hasmore, + &write_type, filename); + hasmore = (front > rear) ? false : true; + goto end; + case FDO_SI_SET_OSI: + result = fdo_sim_set_osi_download( + module_message, module_val, module_val_sz, &strcmp_filedesc, + &strcmp_length, &strcmp_sha_384, &strcmp_write); + + if (result != FDO_SI_SUCCESS) { + goto end; + } + + if (strcmp_filedesc == 0) { + result = fdo_sim_set_osi_strcmp(bin_len, bin_data); + goto end; + } else if (strcmp_length == 0) { + result = fdo_sim_set_osi_length(bin_len); + goto end; + } else if (strcmp_sha_384 == 0) { + result = fdo_sim_set_osi_sha_384(bin_len, bin_data); + goto end; + } else if (strcmp_write == 0) { + result = fdo_sim_set_osi_write(bin_len, bin_data); + goto end; + } + default: + result = FDO_SI_FAILURE; + } + +end: + result = fdo_sim_end(&fdor, &fdow, result, bin_data, NULL, 0, &hasmore, + &write_type); + return result; +} + +int fdo_sim_set_osi_download(char *module_message, uint8_t *module_val, + size_t *module_val_sz, int *strcmp_filedesc, + int *strcmp_length, int *strcmp_sha_384, + int *strcmp_write) +{ + if (!module_message || !module_val || !module_val_sz || + *module_val_sz > MOD_MAX_BUFF_SIZE) { + return FDO_SI_CONTENT_ERROR; + } + + int result = FDO_SI_INTERNAL_ERROR; + + // Process the received Owner ServiceInfo contained within + // 'fdor', here. + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "name", strcmp_filedesc); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "length", strcmp_length); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "sha-384", strcmp_sha_384); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "data", strcmp_write); + + if (*strcmp_filedesc && *strcmp_length && *strcmp_sha_384 && + *strcmp_write) { + LOG(LOG_ERROR, "Module fdo.download - Invalid moduleMessage\n"); + result = FDO_SI_CONTENT_ERROR; + goto end; + } + // reset, copy CBOR data and initialize Parser. + fdo_block_reset(&fdow->b); + if (0 != memcpy_s(fdor->b.block, *module_val_sz, module_val, + *module_val_sz)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to copy buffer " + "into temporary FDOR\n"); + goto end; + } + fdor->b.block_size = *module_val_sz; + + if (!fdor_parser_init(fdor)) { + LOG(LOG_ERROR, + "Module fdo.download - Failed to init FDOR parser\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_set_osi_strcmp(size_t bin_len, uint8_t *bin_data) +{ + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_string_length(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to read " + "fdo.download:name length\n"); + goto end; + } + + if (bin_len == 0) { + LOG(LOG_ERROR, "Module fdo.download - Empty value received for " + "fdo.download:name\n"); + // received file name cannot be empty + result = FDO_SI_CONTENT_ERROR; + goto end; + } + + bin_data = FSIMModuleAlloc(bin_len * sizeof(uint8_t)); + if (!bin_data) { + LOG(LOG_ERROR, "Module fdo.download - Failed to " + "alloc for fdo.download:name\n"); + goto end; + } + + if (!fdor_text_string(fdor, (char *)bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to " + "read fdo.download:name\n"); + goto end; + } + + if (memset_s(filename, sizeof(filename), 0) != 0) { + LOG(LOG_ERROR, "Module fdo.download - Failed to clear " + "fdo.download:name buffer\n"); + goto end; + } + + if (0 != + strncpy_s(filename, FILE_NAME_LEN, (char *)bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to " + "copy fdo.download:name\n"); + goto end; + } + + if (true == fsim_delete_old_file((const char *)filename)) { + result = FDO_SI_SUCCESS; + } + LOG(LOG_INFO, "Module fdo.download - File created on path: %s\n", + filename); +end: + result = fdo_sim_end(&fdor, &fdow, result, bin_data, NULL, 0, &hasmore, + &write_type); + return result; +} + +int fdo_sim_set_osi_length(size_t bin_len) +{ + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_unsigned_int(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to process " + "fdo.download:length\n"); + goto end; + } + + expected_len = bin_len; + + LOG(LOG_INFO, "Module fdo.download - expected file length %ld\n", + expected_len); + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_sim_set_osi_sha_384(size_t bin_len, uint8_t *bin_data) +{ + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_string_length(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to " + "read fdo.download:sha384 length\n"); + goto end; + } + + if (bin_len == 0) { + LOG(LOG_DEBUG, "Module fdo.download - Empty value " + "received for fdo.download:sha384\n"); + // received file content can be empty for an + // empty file do not allocate for the same and + // skip reading the entry + if (!fdor_next(fdor)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to read " + "fdo.download:sha384\n"); + result = FDO_SI_CONTENT_ERROR; + goto end; + } + result = FDO_SI_SUCCESS; + goto end; + } + + bin_data = FSIMModuleAlloc(bin_len * sizeof(uint8_t)); + if (!bin_data) { + LOG(LOG_ERROR, "Module fdo.download - Failed to " + "alloc for fdo.download:sha384\n"); + goto end; + } + + if (!fdor_byte_string(fdor, bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to read value for " + "fdo.download:sha384\n"); + goto end; + } + + expectedCheckSum = + fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_SHA_384, SHA384_DIGEST_SIZE); + if (!expectedCheckSum) { + LOG(LOG_ERROR, + "Module fdo.download - Failed to alloc expectedCheckSum\n"); + goto end; + } + + if (0 != memcpy_s(expectedCheckSum->hash->bytes, SHA384_DIGEST_SIZE, + (char *)bin_data, bin_len)) { + LOG(LOG_ERROR, + "Module fdo.download - Failed to copy expectedCheckSum\n"); + fdo_hash_free(expectedCheckSum); + goto end; + } + result = FDO_SI_SUCCESS; +end: + result = fdo_sim_end(&fdor, &fdow, result, bin_data, NULL, 0, &hasmore, + &write_type); + return result; +} + +int fdo_sim_set_osi_write(size_t bin_len, uint8_t *bin_data) +{ + int result = FDO_SI_INTERNAL_ERROR; + fdo_hash_t *hash = NULL; + size_t file_len = 0; + uint8_t *file_data = NULL; + + if (!fdor_string_length(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to " + "read fdo.download:data length\n"); + goto end; + } + + if (bytes_received == expected_len || !bin_len) { + // Entire file has been sent + bytes_received = 0; + result = FDO_SI_SUCCESS; + goto end; + } + + bytes_received += bin_len; + + bin_data = FSIMModuleAlloc(bin_len * sizeof(uint8_t)); + if (!bin_data) { + LOG(LOG_ERROR, "Module fdo.download - Failed to " + "alloc for fdo.download:data\n"); + goto end; + } + + if (!fdor_byte_string(fdor, bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to read value for " + "fdo.download:data\n"); + goto end; + } + + if (!fsim_process_data(FDO_SIM_MOD_MSG_WRITE, bin_data, bin_len, + filename, NULL)) { + LOG(LOG_ERROR, "Module fdo.download - Failed to process value " + "for fdo.download:data\n"); + goto end; + } + + if (bytes_received == expected_len) { + // Entire file has been sent + // Validate hash of received file + file_len = fsim_get_file_sz(filename); + + if (file_len == expected_len) { + file_data = FSIMModuleAlloc(file_len * sizeof(uint8_t)); + if (!file_data) { + LOG(LOG_ERROR, + "Module fdo.download - Failed to " + "alloc for fdo.download:data\n"); + goto end; + } + + if (!fsim_read_buffer_from_file_from_pos( + filename, file_data, file_len, 0)) { + LOG(LOG_ERROR, + "Module fdo.download - Failed to read " + "fdo.download:data content from %s\n", + filename); + goto end; + } + + hash = fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_SHA_384, + SHA384_DIGEST_SIZE); + if (!hash) { + LOG(LOG_ERROR, "Module fdo.download - Failed " + "to alloc hash\n"); + goto end; + } + + if ((0 != crypto_hal_hash(FDO_CRYPTO_HASH_TYPE_SHA_384, + file_data, file_len, + hash->hash->bytes, + hash->hash->byte_sz))) { + LOG(LOG_ERROR, "Module fdo.download - Failed " + "to calculate hash\n"); + fdo_hash_free(hash); + goto end; + } + + if (front == -1) { + front = 0; + } + + if (fdo_compare_hashes(hash, expectedCheckSum)) { + LOG(LOG_DEBUG, + "Module fdo.download - Hash matched \n"); + fdo_sim_download_queue[++rear] = file_len; + } else { + LOG(LOG_ERROR, + "Module fdo.download: Failed to verify " + " hash\n"); + fdo_sim_download_queue[++rear] = -1; + } + } + hasmore = true; + write_type = FDO_SIM_MOD_MSG_DONE; + } + + result = FDO_SI_SUCCESS; +end: + if (bytes_received == expected_len) { + if (hash) { + fdo_hash_free(hash); + hash = NULL; + } + if (expectedCheckSum) { + fdo_hash_free(expectedCheckSum); + expectedCheckSum = NULL; + } + if (file_data) { + FSIMModuleFree(file_data); + } + } + + result = fdo_sim_end(&fdor, &fdow, result, bin_data, NULL, 0, &hasmore, + &write_type); + return result; +} diff --git a/device_modules/fdo_sim/fdo_sim_utils.h b/device_modules/fdo_sim/fdo_sim_utils.h new file mode 100644 index 00000000..0a4fd03e --- /dev/null +++ b/device_modules/fdo_sim/fdo_sim_utils.h @@ -0,0 +1,48 @@ +/* + * Copyright 2023 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +#ifndef __SYS_UTILS_H__ +#define __SYS_UTILS_H__ + +#include +#include + +#ifdef TARGET_OS_OPTEE +#include +#define FSIMModuleFree(x) \ + { \ + TEE_Free(x); \ + x = NULL; \ + } + +#else +#define FSIMModuleFree(x) \ + { \ + free(x); \ + x = NULL; \ + } +#endif + +typedef enum { + FDO_SIM_MOD_MSG_WRITE, + FDO_SIM_MOD_MSG_EXEC, + FDO_SIM_MOD_MSG_EXEC_CB, + FDO_SIM_MOD_MSG_STATUS_CB, + FDO_SIM_MOD_MSG_DATA, + FDO_SIM_MOD_MSG_DONE, + FDO_SIM_MOD_MSG_EXIT_CODE, + FDO_SIM_MOD_MSG_EXIT, + FDO_SIM_MOD_MSG_NONE +} fdoSimModMsg; + +void *FSIMModuleAlloc(int size); +bool fsim_process_data(fdoSimModMsg type, uint8_t *data, uint32_t dataLen, + char *file_name, char **command); + +size_t fsim_get_file_sz(char const *filename); +bool fsim_read_buffer_from_file_from_pos(const char *filename, uint8_t *buffer, + size_t size, int from); +bool fsim_delete_old_file(const char *file_name); +#endif /* __SYS_UTILS_H__ */ diff --git a/device_modules/fdo_sim/sim_utils_linux.c b/device_modules/fdo_sim/sim_utils_linux.c new file mode 100644 index 00000000..c934cdc2 --- /dev/null +++ b/device_modules/fdo_sim/sim_utils_linux.c @@ -0,0 +1,276 @@ +/* + * Copyright 2023 Intel Corporation + * SPDX-License-Identifier: Apache 2.0 + */ + +#include "safe_lib.h" +#include +#include +#include +#include +#include +#include "fdo_sim_utils.h" +#include "fdo_sim.h" + +// Process ID of the process created by Module:exec_cb +static pid_t exec_pid = -1; + +void *FSIMModuleAlloc(int size) +{ + if (size <= 0) { + return NULL; + } + void *buf = malloc(size); + if (!buf) { + printf("fdoAlloc failed to allocate\n"); + goto end; + } + + if (memset_s(buf, size, 0) != 0) { + printf("Memset Failed\n"); + free(buf); + buf = NULL; + goto end; + } + +end: + return buf; +} + +bool fsim_process_data(fdoSimModMsg type, uint8_t *data, uint32_t data_len, + char *file_name, char **command) +{ + bool ret = false; + FILE *fp = NULL; + int status = -1; + + // For writing to a file + if (type == FDO_SIM_MOD_MSG_WRITE) { + + if (!data || !data_len) { +#ifdef DEBUG_LOGS + printf("Module fdo.download:data write : Invalid " + "params\n"); +#endif + return false; + } + if (!file_name) { +#ifdef DEBUG_LOGS + printf("Module fdo.download:data write : No filename " + "present for " + "Module fdo.download:data\n"); +#endif + return false; + } + fp = fopen(file_name, "a"); + if (!fp) { +#ifdef DEBUG_LOGS + printf("Module fdo.download:data write : Failed to " + "open file(path): %s\n", + file_name); +#endif + return false; + } + + printf("Module fdo.download:data write : %" PRIu32 + " bytes being written to the file %s\n", + data_len, file_name); + + if (fwrite(data, sizeof(char), data_len, fp) != + (size_t)data_len) { +#ifdef DEBUG_LOGS + printf("Module fdo.download:data write : Failed to " + "write\n"); +#endif + goto end; + } + ret = true; + goto end; + } + + // For exec/exec_cb call + if (type == FDO_SIM_MOD_MSG_EXEC) { + + if (!file_name) { +#ifdef DEBUG_LOGS + printf( + "Module fdo.commmand:execute : Invalid filename\n"); +#endif + return false; + } + + if (!command) { +#ifdef DEBUG_LOGS + printf( + "Module fdo.commmand:execute : Missing command\n"); +#endif + return false; + } + + if (exec_pid != -1) { +#ifdef DEBUG_LOGS + printf("Module fdo.commmand:execute : An exec " + "instruction is " + "currently in progress\n"); +#endif + return false; + } + + printf("Module fdo.commmand:execute : Executing command...\n"); + exec_pid = fork(); + if (exec_pid < 0) { + // error +#ifdef DEBUG_LOGS + printf( + "Module fdo.commmand:execute : Failed to fork.\n"); +#endif + return false; + } else if (exec_pid == 0) { + // child process + status = execvp(command[0], command); + if (status == -1) { +#ifdef DEBUG_LOGS + printf("Module fdo.commmand:execute : Failed " + "to execute " + "command.\n"); +#endif + goto end; + } + } else { + // parent process + // if exec, block until process completes + if (type == FDO_SIM_MOD_MSG_EXEC) { + waitpid(exec_pid, &status, 0); + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) != 0) { +#ifdef DEBUG_LOGS + printf("Module " + "fdo.commmand:execute : " + "Proces " + "execution failed.\n"); +#endif + goto end; + + } else { +#ifdef DEBUG_LOGS + printf( + "Module " + "fdo.commmand:execute : " + "Process " + "execution completed.\n"); +#endif + // reset the process ID since + // execution is done + exec_pid = -1; + ret = true; + goto end; + } + } + } + } + ret = true; + } + + // For performing clean-up operations of module exit + if (type == FDO_SIM_MOD_MSG_EXIT) { + if (exec_pid > 0) { + // kill the process as a part of clea-up operations + kill(exec_pid, SIGTERM); + } + ret = true; + } +end: + + if (fp) { + if (fclose(fp) == EOF) { +#ifdef DEBUG_LOGS + printf("Fclose failed\n"); +#endif + } + } + // upon error, kill the forked process + if (!ret && exec_pid > 0) { + kill(exec_pid, SIGTERM); + exec_pid = -1; + } + return ret; +} + +bool fsim_delete_old_file(const char *filename) +{ + FILE *file = NULL; + bool ret = false; + + file = fopen(filename, "w"); + if (file) { + if (!fclose(file)) { + ret = true; + } + } else { + ret = true; + } + return ret; +} + +/** + * Return the length of the given file. + */ +size_t fsim_get_file_sz(char const *filename) +{ + if (!filename || !filename[0]) { + return 0; + } + size_t file_length = 0; + FILE *fp = fopen(filename, "rb"); + + if (fp) { + if (fseek(fp, 0, SEEK_END) != 0) { + printf("fseek() failed in the file"); + if (fclose(fp) == EOF) { + printf("Fclose Failed"); + } + return 0; + } + file_length = ftell(fp); + if (fclose(fp) == EOF) { + printf("Fclose Failed"); + } + } + return file_length; +} + +/** + * Read the filename's content (size bytes) into the given buffer (pre-allocated + * memory) starting at the specified offset (from). + */ +bool fsim_read_buffer_from_file_from_pos(const char *filename, uint8_t *buffer, + size_t size, int from) +{ + FILE *file = NULL; + size_t bytes_read = 0; + + file = fopen(filename, "rb"); + if (!file) { + return false; + } + + if (fseek(file, from, SEEK_SET) != 0) { + printf("fseek() failed in the file"); + if (fclose(file) == EOF) { + printf("Fclose Failed"); + } + return false; + } + bytes_read = fread(buffer, 1, size, file); + if (bytes_read != size) { + if (fclose(file) == EOF) { + printf("Fclose Failed"); + } + return false; + } + + if (fclose(file) == EOF) { + printf("Fclose Failed"); + } + return true; +} diff --git a/device_modules/fdo_sys/fdo_sys.c b/device_modules/fdo_sys/fdo_sys.c index 05f0329a..f102c4de 100644 --- a/device_modules/fdo_sys/fdo_sys.c +++ b/device_modules/fdo_sys/fdo_sys.c @@ -33,25 +33,23 @@ static bool status_cb_iscomplete = false; static int status_cb_resultcode = -1; // status_cb waitSec value static uint64_t status_cb_waitsec = -1; -// local hasMore flag that represents whether the module has data/response to send NOW -// 'true' if there is data to send, 'false' otherwise +// local hasMore flag that represents whether the module has data/response to +// send NOW 'true' if there is data to send, 'false' otherwise static bool hasmore = false; -// local isMore flag that represents whether the module has data/response to send in -// the NEXT messege -// SHOULD be 'true' if there is data to send, 'false' otherwise -// For simplicity, it is 'false' always (also a valid value) +// local isMore flag that represents whether the module has data/response to +// send in the NEXT messege SHOULD be 'true' if there is data to send, 'false' +// otherwise For simplicity, it is 'false' always (also a valid value) static bool ismore = false; // the type of operation to perform, generally used to manage responses static fdoSysModMsg write_type = FDO_SYS_MOD_MSG_NONE; static bool write_status_cb(char *module_message); -static bool write_data(char *module_message, - uint8_t *bin_data, size_t bin_len); +static bool write_data(char *module_message, uint8_t *bin_data, size_t bin_len); static bool write_eot(char *module_message, int status); -int fdo_sys(fdo_sdk_si_type type, - char *module_message, uint8_t *module_val, size_t *module_val_sz, - uint16_t *num_module_messages, bool *has_more, bool *is_more, size_t mtu) +int fdo_sys(fdo_sdk_si_type type, char *module_message, uint8_t *module_val, + size_t *module_val_sz, uint16_t *num_module_messages, + bool *has_more, bool *is_more, size_t mtu) { int strcmp_filedesc = 1; int strcmp_write = 1; @@ -70,641 +68,881 @@ int fdo_sys(fdo_sdk_si_type type, size_t temp_module_val_sz = 0; switch (type) { - case FDO_SI_START: - // Initialize module's CBOR Reader/Writer objects. - fdow = ModuleAlloc(sizeof(fdow_t)); - if (!fdow_init(fdow) || !fdo_block_alloc_with_size(&fdow->b, MOD_MAX_BUFF_SIZE)) { - LOG(LOG_DEBUG, - "Module fdo_sys - FDOW Initialization/Allocation failed!\n"); - result = FDO_SI_CONTENT_ERROR; - goto end; - } - - fdor = ModuleAlloc(sizeof(fdor_t)); - if (!fdor_init(fdor) || - !fdo_block_alloc_with_size(&fdor->b, MOD_MAX_BUFF_SIZE)) { - LOG(LOG_DEBUG,"Module fdo_sys - FDOR Initialization/Allocation failed!\n"); - goto end; - } - result = FDO_SI_SUCCESS; + case FDO_SI_START: + result = fdo_si_start(); + goto end; + case FDO_SI_END: + case FDO_SI_FAILURE: + result = fdo_si_failure(); + goto end; + case FDO_SI_HAS_MORE_DSI: + result = fdo_si_has_more_dsi(has_more); + goto end; + case FDO_SI_IS_MORE_DSI: + result = fdo_si_is_more_dsi(is_more); + goto end; + case FDO_SI_GET_DSI_COUNT: + result = fdo_si_get_dsi_count(num_module_messages); + goto end; + case FDO_SI_GET_DSI: + result = fdo_si_get_dsi(mtu, module_message, module_val, + module_val_sz, file_remaining, bin_len, + bin_data, temp_module_val_sz); + goto end; + case FDO_SI_SET_OSI: + result = fdo_si_set_osi( + module_message, module_val, module_val_sz, &strcmp_filedesc, + &strcmp_write, &strcmp_exec, &strcmp_execcb, + &strcmp_statuscb, &strcmp_fetch); + + if (result != FDO_SI_SUCCESS) { goto end; - case FDO_SI_END: - case FDO_SI_FAILURE: - // perform clean-ups as needed - if (!process_data(FDO_SYS_MOD_MSG_EXIT, NULL, 0, NULL, - NULL, NULL, NULL, NULL)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to perform clean-up operations\n"); - goto end; - } + } - if (fdow) { - fdow_flush(fdow); - ModuleFree(fdow); - } - if (fdor) { - fdor_flush(fdor); - ModuleFree(fdor); - } - result = FDO_SI_SUCCESS; + if (strcmp_filedesc == 0) { + result = fdo_si_set_osi_strcmp(bin_len, bin_data); goto end; - case FDO_SI_HAS_MORE_DSI: - // calculate whether there is ServiceInfo to send NOW and update 'has_more'. - // For testing purposes, set this to true here, and false once first write is done. - if (!has_more) { - result = FDO_SI_CONTENT_ERROR; - goto end; - } - - *has_more = hasmore; - if (*has_more) { - LOG(LOG_DEBUG,"Module fdo_sys - There is ServiceInfo to send\n"); - } - result = FDO_SI_SUCCESS; + } else if (strcmp_write == 0) { + result = fdo_si_set_osi_write(bin_len, bin_data); goto end; - case FDO_SI_IS_MORE_DSI: - // calculate whether there is ServiceInfo to send in the NEXT iteration - // and update 'is_more'. - if (!is_more) { - result = FDO_SI_CONTENT_ERROR; - goto end; - } - // sending either true or false is valid - // for simplicity, setting this to 'false' always, - // since managing 'ismore' by looking-ahead can be error-prone - *is_more = ismore; - result = FDO_SI_SUCCESS; + } else if (strcmp_exec == 0 || strcmp_execcb == 0) { + result = fdo_si_set_osi_exec( + exec_instr, exec_array_index, &exec_instructions_sz, + &strcmp_exec, &strcmp_execcb); goto end; - case FDO_SI_GET_DSI_COUNT: - // return the total number of messages that will be sent in THIS message alone - // we are always sending 1 message at all times. - // However, this flag 'case' won't be encountered since this is not invoked - // by the 'lib/' as of now. - if (!num_module_messages) { - result = FDO_SI_CONTENT_ERROR; - goto end; - } - *num_module_messages = 1; - result = FDO_SI_SUCCESS; + } else if (strcmp_statuscb == 0) { + result = + fdo_si_set_osi_status_cb(&status_cb_array_length); goto end; - case FDO_SI_GET_DSI: - // write Device ServiceInfo using 'fdow' by partitioning the messages as per MTU, here. - if (mtu == 0 || !module_message || !module_val || !module_val_sz) { - result = FDO_SI_CONTENT_ERROR; - goto end; - } + } else if (strcmp_fetch == 0) { + result = fdo_si_set_osi_fetch(bin_len); + goto end; + } + default: + result = FDO_SI_FAILURE; + } - // reset and initialize FDOW's encoder for usage - fdo_block_reset(&fdow->b); - if (!fdow_encoder_init(fdow)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to initialize FDOW encoder\n"); - goto end; - } +end: + result = fdo_end(result, bin_data, exec_instr); + return result; +} - if (!hasmore || write_type == FDO_SYS_MOD_MSG_NONE) { - LOG(LOG_DEBUG,"Module fdo_sys - Invalid state\n"); - goto end; - } +/** + * Write CBOR-encoded fdo_sys:status_cb content into FDOW. + */ +static bool write_status_cb(char *module_message) +{ - if (write_type == FDO_SYS_MOD_MSG_STATUS_CB) { + if (!module_message) { + LOG(LOG_ERROR, "Module fdo_sys - Invalid params for " + "fdo_sys:status_cb array\n"); + return false; + } - if (!write_status_cb(module_message)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to respond with fdo_sys:status_cb\n"); - goto end; - } - // reset this because module has nothing else left to send - hasmore = false; - LOG(LOG_DEBUG,"Module fdo_sys - Responded with fdo_sys:status_cb" - " [%d, %d, %"PRIu64"]\n", - status_cb_iscomplete, status_cb_resultcode, status_cb_waitsec); - - } else if (write_type == FDO_SYS_MOD_MSG_DATA) { - - // if an error occcurs EOT is sent next with failure status code - fetch_data_status = 1; - - // it's ok to not be able to send data here - // if anything goes wrong, EOT will be sent now/next, regardless - result = FDO_SI_SUCCESS; - - // if file size is 0 or has changed since first read or the seek/offset - // point is more that file size (maybe file is corrupted), finish file transfer - if (file_sz == 0 || file_sz != get_file_sz(filename) || - file_seek_pos > file_sz) { - // file is empty or doesn't exist - LOG(LOG_DEBUG,"Module fdo_sys - Empty/Invalid content for fdo_sys:data in %s\n", - filename); - if (!write_eot(module_message, fetch_data_status)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to respond with fdo_sys:eot\n"); - goto end; - } - result = FDO_SI_SUCCESS; - } else { - - file_remaining = file_sz - file_seek_pos; - bin_len = file_remaining > mtu ? mtu : file_remaining; - bin_data = ModuleAlloc(bin_len * sizeof(uint8_t)); - if (!bin_data) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to alloc for fdo_sys:data buffer\n"); - goto end; - } - if (memset_s(bin_data, bin_len, 0) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to clear fdo_sys:data buffer\n"); - goto end; - } - - if (!read_buffer_from_file_from_pos(filename, bin_data, bin_len, file_seek_pos)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:data content from %s\n", - filename); - if (!write_eot(module_message, fetch_data_status)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to respond with fdo_sys:eot\n"); - goto end; - } - result = FDO_SI_SUCCESS; - } else { - - file_seek_pos += bin_len; - - if (!write_data(module_message, bin_data, bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to respond with fdo_sys:data\n"); - goto end; - } - hasmore = true; - - // if file is sent completely, then send EOT next - fetch_data_status = 0; - if (file_sz == file_seek_pos) { - write_type = FDO_SYS_MOD_MSG_EOT; - } - } - } + const char message[] = "status_cb"; + if (memcpy_s(module_message, sizeof(message), message, + sizeof(message)) != 0) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to copy module message " + "status_cb\n"); + return false; + } - LOG(LOG_DEBUG,"Module fdo_sys - Responded with fdo_sys:data containing\n"); - } else if (write_type == FDO_SYS_MOD_MSG_EOT) { - if (!write_eot(module_message, fetch_data_status)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to respond with fdo_sys:eot\n"); - goto end; - } - hasmore = false; - LOG(LOG_DEBUG,"Module fdo_sys - Responded with fdo_sys:eot\n"); - } else if (write_type == FDO_SYS_MOD_MSG_NONE) { - // shouldn't reach here, if we do, it might a logical error - // log and fail - LOG(LOG_DEBUG,"Module fdo_sys - Invalid module write state\n"); - goto end; - } + if (!fdow_start_array(fdow, 3)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to start inner " + "fdo_sys:status_cb array\n"); + return false; + } - if (!fdow_encoded_length(fdow, &temp_module_val_sz)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to get encoded length\n"); - goto end; - } - *module_val_sz = temp_module_val_sz; - if (memcpy_s(module_val, *module_val_sz, - fdow->b.block, *module_val_sz) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to copy CBOR-encoded module value\n"); - goto end; - } - result = FDO_SI_SUCCESS; - goto end; - case FDO_SI_SET_OSI: + if (!fdow_boolean(fdow, status_cb_iscomplete)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to write " + "fdo_sys:status_cb isComplete\n"); + return false; + } - if (!module_message || !module_val || !module_val_sz || - *module_val_sz > MOD_MAX_BUFF_SIZE) { - result = FDO_SI_CONTENT_ERROR; - goto end; - } - // Process the received Owner ServiceInfo contained within 'fdor', here. - strcmp_s(module_message, FDO_MODULE_MSG_LEN, "filedesc", - &strcmp_filedesc); - strcmp_s(module_message, FDO_MODULE_MSG_LEN, "write", &strcmp_write); - strcmp_s(module_message, FDO_MODULE_MSG_LEN, "exec", &strcmp_exec); - strcmp_s(module_message, FDO_MODULE_MSG_LEN, "exec_cb", &strcmp_execcb); - strcmp_s(module_message, FDO_MODULE_MSG_LEN, "status_cb", &strcmp_statuscb); - strcmp_s(module_message, FDO_MODULE_MSG_LEN, "fetch", &strcmp_fetch); - - if (strcmp_filedesc != 0 && strcmp_exec != 0 && - strcmp_write != 0 && strcmp_execcb != 0 && - strcmp_statuscb != 0 && strcmp_fetch != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Invalid moduleMessage\n"); - return FDO_SI_CONTENT_ERROR; - } + if (!fdow_signed_int(fdow, status_cb_resultcode)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to write " + "fdo_sys:status_cb resultCode\n"); + return false; + } - // reset, copy CBOR data and initialize Parser. - fdo_block_reset(&fdor->b); - if (0 != memcpy_s(fdor->b.block, *module_val_sz, - module_val, *module_val_sz)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to copy buffer into temporary FDOR\n"); - goto end; - } - fdor->b.block_size = *module_val_sz; + if (!fdow_unsigned_int(fdow, status_cb_waitsec)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to write " + "fdo_sys:status_cb waitSec\n"); + return false; + } - if (!fdor_parser_init(fdor)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to init FDOR parser\n"); - goto end; - } + if (!fdow_end_array(fdow)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to end inner " + "fdo_sys:status_cb array\n"); + return false; + } - if (strcmp_filedesc == 0) { + return true; +} - if (!fdor_string_length(fdor, &bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:filedesc length\n"); - goto end; - } +/** + * Write CBOR-encoded fdo_sys:data content into FDOW with given data. + */ +static bool write_data(char *module_message, uint8_t *bin_data, size_t bin_len) +{ - if (bin_len == 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Empty value received for fdo_sys:filedesc\n"); - // received file name cannot be empty - return FDO_SI_CONTENT_ERROR; - } + if (!module_message || !bin_data) { + LOG(LOG_ERROR, + "Module fdo_sys - Invalid params for fdo_sys:data\n"); + return false; + } - bin_data = ModuleAlloc(bin_len * sizeof(uint8_t)); - if (!bin_data) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to alloc for fdo_sys:filedesc\n"); - goto end; - } + const char message[] = "data"; + if (memcpy_s(module_message, sizeof(message), message, + sizeof(message)) != 0) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to copy module message data\n"); + return false; + } - if (memset_s(bin_data, bin_len, 0) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to clear fdo_sys:filedesc buffer\n"); - goto end; - } + if (!fdow_byte_string(fdow, bin_data, bin_len)) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to write fdo_sys:data content\n"); + return false; + } - if (!fdor_text_string(fdor, (char *)bin_data, bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:filedesc\n"); - goto end; - } + return true; +} - if (memset_s(filename, sizeof(filename), 0) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to clear fdo_sys:filedesc buffer\n"); - goto end; - } +/** + * Write CBOR-encoded fdo_sys:eot content into FDOW with given status. + */ +static bool write_eot(char *module_message, int status) +{ - if (0 != strncpy_s(filename, FILE_NAME_LEN, - (char *)bin_data, bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to copy fdo:sys:filedesc\n"); - goto end; - } + if (!module_message) { + LOG(LOG_ERROR, + "Module fdo_sys - Invalid params for fdo_sys:eot\n"); + return false; + } - if (true == - delete_old_file((const char *)filename)) { - result = FDO_SI_SUCCESS; - } + const char message[] = "eot"; + if (memcpy_s(module_message, sizeof(message), message, + sizeof(message)) != 0) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to copy module message eot\n"); + return false; + } - goto end; - } else if (strcmp_write == 0) { + if (!fdow_start_array(fdow, 1)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to start inner array " + "in fdo_sys:eot\n"); + return false; + } - if (!fdor_string_length(fdor, &bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:write length\n"); - goto end; - } + if (!fdow_signed_int(fdow, status)) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to write fdo_sys:eot status\n"); + return false; + } - if (bin_len == 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Empty value received for fdo_sys:write\n"); - // received file content can be empty for an empty file - // do not allocate for the same and skip reading the entry - if (!fdor_next(fdor)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:write\n"); - goto end; - } - return FDO_SI_SUCCESS; - } + if (!fdow_end_array(fdow)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to end inner array in " + "fdo_sys:eot\n"); + return false; + } - bin_data = ModuleAlloc(bin_len * sizeof(uint8_t)); - if (!bin_data) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to alloc for fdo_sys:write\n"); - goto end; - } - if (memset_s(bin_data, bin_len, 0) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to clear fdo_sys:write buffer\n"); - goto end; - } + return true; +} - if (!fdor_byte_string(fdor, bin_data, bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read value for fdo_sys:write\n"); - goto end; - } +/** + * List of helper functions used in switch case + * + * fdo_si_start + * fdo_si_failure + * fdo_si_has_more_dsi + * fdo_si_is_more_dsi + * fdo_si_get_dsi_count + * fdo_si_get_dsi + * fdo_si_set_osi + * fdo_si_set_osi_strcmp + * fdo_si_set_osi_write + * fdo_si_set_osi_exec + * fdo_si_set_osi_status_cb + * fdo_si_set_osi_fetch + * fdo_end + */ - if (!process_data(FDO_SYS_MOD_MSG_WRITE, bin_data, bin_len, filename, - NULL, NULL, NULL, NULL)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process value for fdo_sys:write\n"); - goto end; - } - result = FDO_SI_SUCCESS; - goto end; - } else if (strcmp_exec == 0 || strcmp_execcb == 0) { +int fdo_si_start(void) +{ + int result = FDO_SI_INTERNAL_ERROR; - if (!fdor_array_length(fdor, &exec_array_length)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:exec/exec_cb array length\n"); - goto end; - } + // Initialize module's CBOR Reader/Writer objects. + fdow = ModuleAlloc(sizeof(fdow_t)); + if (!fdow_init(fdow) || + !fdo_block_alloc_with_size(&fdow->b, MOD_MAX_BUFF_SIZE)) { + LOG(LOG_ERROR, "Module fdo_sim - FDOW " + "Initialization/Allocation failed!\n"); + result = FDO_SI_CONTENT_ERROR; + goto end; + } - if (exec_array_length == 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Empty array received for fdo_sys:exec/exec_cb\n"); - // received exec array cannot be empty - result = FDO_SI_CONTENT_ERROR; - goto end; - } + fdor = ModuleAlloc(sizeof(fdor_t)); + if (!fdor_init(fdor) || + !fdo_block_alloc_with_size(&fdor->b, MOD_MAX_BUFF_SIZE)) { + LOG(LOG_ERROR, "Module fdo_sim - FDOR " + "Initialization/Allocation failed!\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + return result; +} - if (!fdor_start_array(fdor)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to start fdo_sys:exec/exec_cb array\n"); - goto end; - } +int fdo_si_failure(void) +{ + // perform clean-ups as needed + if (!process_data(FDO_SYS_MOD_MSG_EXIT, NULL, 0, NULL, NULL, NULL, NULL, + NULL)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to perform " + "clean-up operations\n"); + return FDO_SI_CONTENT_ERROR; + } - // allocate memory for exec_instr - exec_instr = (char**)ModuleAlloc(sizeof(char*) * (exec_array_length + 1)); - if (!exec_instr) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to alloc for fdo_sys:exec/exec_cb instructions\n"); - goto end; - } + if (fdow) { + fdow_flush(fdow); + ModuleFree(fdow); + } + if (fdor) { + fdor_flush(fdor); + ModuleFree(fdor); + } + return FDO_SI_SUCCESS; +} - for (exec_array_index = 0; exec_array_index < exec_array_length; exec_array_index++) { - exec_instr[exec_array_index] = - (char *)ModuleAlloc(sizeof(char) * MOD_MAX_EXEC_ARG_LEN); - if (!exec_instr[exec_array_index]) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to alloc for single fdo_sys:exec /exec_cb" - " instruction\n"); - goto end; - } - if (0 != memset_s(exec_instr[exec_array_index], - sizeof(sizeof(char) * MOD_MAX_EXEC_ARG_LEN), 0)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to clear single fdo_sys:exec/exec_cb" - " instruction\n"); - goto end; - } - if (!fdor_string_length(fdor, &exec_instructions_sz) || - exec_instructions_sz > MOD_MAX_EXEC_ARG_LEN) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:exec/exec_cb text length\n"); - goto end; - } - if (!fdor_text_string(fdor, exec_instr[exec_array_index], exec_instructions_sz)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:exec/exec_cb text\n"); - goto end; - } +int fdo_si_has_more_dsi(bool *has_more) +{ + // calculate whether there is ServiceInfo to send NOW and update + // 'has_more'. For testing purposes, set this to true here, and + // false once first write is done. + if (!has_more) { + return FDO_SI_CONTENT_ERROR; + } - // 2nd argument is the filename - if (exec_array_index == 1) { - if (memset_s(filename, sizeof(filename), 0) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to clear filename for" - " fdo_sys:exec/exec_cb\n"); - goto end; - } - if (0 != strncpy_s(filename, FILE_NAME_LEN, - exec_instr[exec_array_index], exec_instructions_sz)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to copy filename for" - " fdo_sys:exec/exec_cb\n"); - goto end; - } - } - } - exec_instr[exec_array_index] = NULL; + *has_more = hasmore; + if (*has_more) { + LOG(LOG_DEBUG, + "Module fdo_sys - There is ServiceInfo to send\n"); + } + return FDO_SI_SUCCESS; +} + +int fdo_si_is_more_dsi(bool *is_more) +{ + // calculate whether there is ServiceInfo to send in the NEXT + // iteration and update 'is_more'. + if (!is_more) { + LOG(LOG_ERROR, "is_more is NULL\n"); + return FDO_SI_CONTENT_ERROR; + } + + // sending either true or false is valid + // for simplicity, setting this to 'false' always, + // since managing 'ismore' by looking-ahead can be error-prone + *is_more = ismore; + return FDO_SI_SUCCESS; +} + +int fdo_si_get_dsi_count(uint16_t *num_module_messages) +{ + // calculate the number of ServiceInfo items to send NOW and update + // 'num_module_messages'. For testing purposes, set this to 1 here, and + // 0 once first write is done. + if (!num_module_messages) { + return FDO_SI_CONTENT_ERROR; + } + *num_module_messages = 1; + return FDO_SI_SUCCESS; +} + +int fdo_si_get_dsi(size_t mtu, char *module_message, uint8_t *module_val, + size_t *module_val_sz, size_t file_remaining, size_t bin_len, + uint8_t *bin_data, size_t temp_module_val_sz) +{ + // write Device ServiceInfo using 'fdow' by partitioning the + // messages as per MTU, here. + if (mtu == 0 || !module_message || !module_val || !module_val_sz) { + return FDO_SI_CONTENT_ERROR; + } + + int result = FDO_SI_INTERNAL_ERROR; + + // reset and initialize FDOW's encoder for usage + fdo_block_reset(&fdow->b); + if (!fdow_encoder_init(fdow)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to initialize " + "FDOW encoder\n"); + goto end; + } + + if (!hasmore || write_type == FDO_SYS_MOD_MSG_NONE) { + LOG(LOG_ERROR, "Module fdo_sys - Invalid state\n"); + goto end; + } + + if (write_type == FDO_SYS_MOD_MSG_STATUS_CB) { + + if (!write_status_cb(module_message)) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to respond with " + "fdo_sys:status_cb\n"); + goto end; + } + // reset this because module has nothing else left to + // send + hasmore = false; + LOG(LOG_DEBUG, + "Module fdo_sys - Responded with fdo_sys:status_cb" + " [%d, %d, %" PRIu64 "]\n", + status_cb_iscomplete, status_cb_resultcode, + status_cb_waitsec); + + } else if (write_type == FDO_SYS_MOD_MSG_DATA) { - if (!fdor_end_array(fdor)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to start fdo_sys:exec/exec_cb array\n"); + // if an error occcurs EOT is sent next with failure + // status code + fetch_data_status = 1; + + // it's ok to not be able to send data here + // if anything goes wrong, EOT will be sent now/next, + // regardless + result = FDO_SI_SUCCESS; + + // if file size is 0 or has changed since first read or + // the seek/offset point is more that file size (maybe + // file is corrupted), finish file transfer + if (file_sz == 0 || file_sz != get_file_sz(filename) || + file_seek_pos > file_sz) { + // file is empty or doesn't exist + LOG(LOG_DEBUG, + "Module fdo_sys - Empty/Invalid content " + "for fdo_sys:data in %s\n", + filename); + if (!write_eot(module_message, fetch_data_status)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "respond with fdo_sys:eot\n"); + goto end; + } + } else { + + file_remaining = file_sz - file_seek_pos; + bin_len = file_remaining > mtu ? mtu : file_remaining; + bin_data = ModuleAlloc(bin_len * sizeof(uint8_t)); + if (!bin_data) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to alloc " + "for fdo_sys:data buffer\n"); goto end; } - - if (strcmp_exec == 0) { - if (!process_data(FDO_SYS_MOD_MSG_EXEC, NULL, 0, filename, - exec_instr, NULL, NULL, NULL)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process fdo_sys:exec\n"); + if (memset_s(bin_data, bin_len, 0) != 0) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to clear " + "fdo_sys:data buffer\n"); + goto end; + } + + if (!read_buffer_from_file_from_pos( + filename, bin_data, bin_len, file_seek_pos)) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to read " + "fdo_sys:data content from %s\n", + filename); + if (!write_eot(module_message, + fetch_data_status)) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed " + "to respond with " + "fdo_sys:eot\n"); goto end; } - } else if (strcmp_execcb == 0) { - if (!process_data(FDO_SYS_MOD_MSG_EXEC_CB, NULL, 0, filename, - exec_instr, &status_cb_iscomplete, &status_cb_resultcode, - &status_cb_waitsec)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process fdo_sys:exec_cb\n"); + } else { + + file_seek_pos += bin_len; + + if (!write_data(module_message, bin_data, + bin_len)) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed " + "to respond with " + "fdo_sys:data\n"); goto end; } - - // respond with initial fdo_sys:status_cb message hasmore = true; - write_type = FDO_SYS_MOD_MSG_STATUS_CB; + + // if file is sent completely, then send + // EOT next + fetch_data_status = 0; + if (file_sz == file_seek_pos) { + write_type = FDO_SYS_MOD_MSG_EOT; + } } - result = FDO_SI_SUCCESS; + } + + LOG(LOG_DEBUG, "Module fdo_sys - Responded with " + "fdo_sys:data containing\n"); + } else if (write_type == FDO_SYS_MOD_MSG_EOT) { + if (!write_eot(module_message, fetch_data_status)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "respond with fdo_sys:eot\n"); goto end; + } + hasmore = false; + LOG(LOG_DEBUG, "Module fdo_sys - Responded with fdo_sys:eot\n"); + } else if (write_type == FDO_SYS_MOD_MSG_NONE) { + // shouldn't reach here, if we do, it might a logical + // error log and fail + LOG(LOG_ERROR, "Module fdo_sys - Invalid module write state\n"); + goto end; + } - } else if (strcmp_statuscb == 0) { - if (!fdor_array_length(fdor, &status_cb_array_length)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process fdo_sys:status_cb array length\n"); - goto end; - } - if (status_cb_array_length != 3) { - LOG(LOG_DEBUG,"Module fdo_sys - Invalid number of items in fdo_sys:status_cb\n"); - goto end; - } + if (!fdow_encoded_length(fdow, &temp_module_val_sz)) { + LOG(LOG_ERROR, + "Module fdo_sys - Failed to get encoded length\n"); + goto end; + } + *module_val_sz = temp_module_val_sz; + if (memcpy_s(module_val, *module_val_sz, fdow->b.block, + *module_val_sz) != 0) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to copy " + "CBOR-encoded module value\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + result = fdo_end(result, bin_data, NULL); + return result; +} - if (!fdor_start_array(fdor)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to start fdo_sys:status_cb array\n"); - goto end; - } +int fdo_si_set_osi(char *module_message, uint8_t *module_val, + size_t *module_val_sz, int *strcmp_filedesc, + int *strcmp_write, int *strcmp_exec, int *strcmp_execcb, + int *strcmp_statuscb, int *strcmp_fetch) +{ + if (!module_message || !module_val || !module_val_sz || + *module_val_sz > MOD_MAX_BUFF_SIZE) { + return FDO_SI_CONTENT_ERROR; + } - if (!fdor_boolean(fdor, &status_cb_iscomplete)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process fdo_sys:status_cb isComplete\n"); - goto end; - } + int result = FDO_SI_INTERNAL_ERROR; - if (!fdor_signed_int(fdor, &status_cb_resultcode)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process fdo_sys:status_cb resultCode\n"); - goto end; - } + // Process the received Owner ServiceInfo contained within + // 'fdor', here. + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "filedesc", + strcmp_filedesc); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "write", strcmp_write); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "exec", strcmp_exec); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "exec_cb", strcmp_execcb); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "status_cb", + strcmp_statuscb); + strcmp_s(module_message, FDO_MODULE_MSG_LEN, "fetch", strcmp_fetch); + + if (*strcmp_filedesc != 0 && *strcmp_exec != 0 && *strcmp_write != 0 && + *strcmp_execcb != 0 && *strcmp_statuscb != 0 && + *strcmp_fetch != 0) { + LOG(LOG_ERROR, "Module fdo_sys - Invalid moduleMessage\n"); + result = FDO_SI_CONTENT_ERROR; + goto end; + } - if (!fdor_unsigned_int(fdor, &status_cb_waitsec)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process fdo_sys:status_cb waitSec\n"); - goto end; - } + // reset, copy CBOR data and initialize Parser. + fdo_block_reset(&fdor->b); + if (0 != memcpy_s(fdor->b.block, *module_val_sz, module_val, + *module_val_sz)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to copy buffer " + "into temporary FDOR\n"); + goto end; + } + fdor->b.block_size = *module_val_sz; - if (!fdor_end_array(fdor)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to end fdo_sys:status_cb array\n"); - goto end; - } + if (!fdor_parser_init(fdor)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to init FDOR parser\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + return result; +} - // if isComplete is true from Owner, then there is going to be no response - // from the device, Else respond with fdo_sys:status_cb - if (status_cb_iscomplete) { - hasmore = false; - write_type = FDO_SYS_MOD_MSG_NONE; - } else { - hasmore = true; - write_type = FDO_SYS_MOD_MSG_STATUS_CB; - } +int fdo_si_set_osi_strcmp(size_t bin_len, uint8_t *bin_data) +{ + int result = FDO_SI_INTERNAL_ERROR; - LOG(LOG_DEBUG,"Module fdo_sys - fdo_sys:status_cb [%d, %d, %"PRIu64"]\n", - status_cb_iscomplete, status_cb_resultcode, status_cb_waitsec); + if (!fdor_string_length(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read " + "fdo_sys:filedesc length\n"); + goto end; + } - if (!process_data(FDO_SYS_MOD_MSG_STATUS_CB, bin_data, bin_len, NULL, - NULL, &status_cb_iscomplete, &status_cb_resultcode, &status_cb_waitsec)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to process fdo_sys:status_cb\n"); - goto end; - } + if (bin_len == 0) { + LOG(LOG_ERROR, "Module fdo_sys - Empty value received for " + "fdo_sys:filedesc\n"); + // received file name cannot be empty + result = FDO_SI_CONTENT_ERROR; + goto end; + } - result = FDO_SI_SUCCESS; - goto end; + bin_data = ModuleAlloc(bin_len * sizeof(uint8_t)); + if (!bin_data) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "alloc for fdo_sys:filedesc\n"); + goto end; + } - } else if (strcmp_fetch == 0) { - if (!fdor_string_length(fdor, &bin_len) ) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:fetch length\n"); - goto end; - } + if (!fdor_text_string(fdor, (char *)bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "read fdo_sys:filedesc\n"); + goto end; + } - if (bin_len == 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Empty value received for fdo_sys:fetch\n"); - // received file name to be read cannot be empty - // do not allocate for the same and skip reading the entry - if (!fdor_next(fdor)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read fdo_sys:fetch\n"); - goto end; - } - return FDO_SI_CONTENT_ERROR; - } + if (memset_s(filename, sizeof(filename), 0) != 0) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to clear " + "fdo_sys:filedesc buffer\n"); + goto end; + } - if (memset_s(filename, sizeof(filename), 0) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to clear fdo_sys:fetch filename buffer\n"); - goto end; - } + if (0 != + strncpy_s(filename, FILE_NAME_LEN, (char *)bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "copy fdo:sys:filedesc\n"); + goto end; + } - if (!fdor_text_string(fdor, &filename[0], bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to read value for fdo_sys:fetch\n"); - goto end; - } + if (true == delete_old_file((const char *)filename)) { + result = FDO_SI_SUCCESS; + } +end: + result = fdo_end(result, bin_data, NULL); + return result; +} - // set the file size here so that we don't read any more than what we initially saw - file_sz = get_file_sz(filename); - hasmore = true; - // reset the file offset to read a new file - file_seek_pos = 0; - write_type = FDO_SYS_MOD_MSG_DATA; - result = FDO_SI_SUCCESS; +int fdo_si_set_osi_write(size_t bin_len, uint8_t *bin_data) +{ + int result = FDO_SI_INTERNAL_ERROR; + + if (!fdor_string_length(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "read fdo_sys:write length\n"); + goto end; + } + + if (bin_len == 0) { + LOG(LOG_DEBUG, "Module fdo_sys - Empty value " + "received for fdo_sys:write\n"); + // received file content can be empty for an + // empty file do not allocate for the same and + // skip reading the entry + if (!fdor_next(fdor)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read " + "fdo_sys:write\n"); goto end; } - - default: - result = FDO_SI_FAILURE; + result = FDO_SI_SUCCESS; + goto end; } -end: - if (bin_data) { - ModuleFree(bin_data); + bin_data = ModuleAlloc(bin_len * sizeof(uint8_t)); + if (!bin_data) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "alloc for fdo_sys:write\n"); + goto end; } - if (exec_instr && exec_array_length > 0) { - int exec_counter = exec_array_length - 1; - while (exec_counter >= 0) { - ModuleFree(exec_instr[exec_counter]); - --exec_counter; - } - ModuleFree(exec_instr); - exec_array_length = 0; + + if (!fdor_byte_string(fdor, bin_data, bin_len)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read value for " + "fdo_sys:write\n"); + goto end; } - if (result != FDO_SI_SUCCESS) { - // clean-up state variables/objects - hasmore = false; - file_sz = 0; - file_seek_pos = 0; - fetch_data_status = 1; - write_type = FDO_SYS_MOD_MSG_NONE; + + if (!process_data(FDO_SYS_MOD_MSG_WRITE, bin_data, bin_len, filename, + NULL, NULL, NULL, NULL)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to process value " + "for fdo_sys:write\n"); + goto end; } + result = FDO_SI_SUCCESS; +end: + result = fdo_end(result, bin_data, NULL); return result; } -/** - * Write CBOR-encoded fdo_sys:status_cb content into FDOW. - */ -static bool write_status_cb(char *module_message) { +int fdo_si_set_osi_exec(char **exec_instr, int exec_array_index, + size_t *exec_instructions_sz, int *strcmp_exec, + int *strcmp_execcb) +{ + int result = FDO_SI_INTERNAL_ERROR; - if (!module_message) { - LOG(LOG_DEBUG,"Module fdo_sys - Invalid params for fdo_sys:status_cb array\n"); - return false; + if (!fdor_array_length(fdor, &exec_array_length)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read " + "fdo_sys:exec/exec_cb array length\n"); + goto end; } - const char message[] = "status_cb"; - if (memcpy_s(module_message, sizeof(message), - message, sizeof(message)) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to copy module message status_cb\n"); - return false; + if (exec_array_length == 0) { + LOG(LOG_ERROR, "Module fdo_sys - Empty array received for " + "fdo_sys:exec/exec_cb\n"); + // received exec array cannot be empty + result = FDO_SI_CONTENT_ERROR; + goto end; } - if (!fdow_start_array(fdow, 3)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to start inner fdo_sys:status_cb array\n"); - return false; + if (!fdor_start_array(fdor)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to start " + "fdo_sys:exec/exec_cb array\n"); + goto end; } - if (!fdow_boolean(fdow, status_cb_iscomplete)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to write fdo_sys:status_cb isComplete\n"); - return false; + // allocate memory for exec_instr + exec_instr = + (char **)ModuleAlloc(sizeof(char *) * (exec_array_length + 1)); + if (!exec_instr) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to alloc for " + "fdo_sys:exec/exec_cb instructions\n"); + goto end; } - if (!fdow_signed_int(fdow, status_cb_resultcode)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to write fdo_sys:status_cb resultCode\n"); - return false; - } + for (exec_array_index = 0; exec_array_index < (int)exec_array_length; + exec_array_index++) { + exec_instr[exec_array_index] = + (char *)ModuleAlloc(sizeof(char) * MOD_MAX_EXEC_ARG_LEN); + if (!exec_instr[exec_array_index]) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to alloc " + "for single fdo_sys:exec /exec_cb" + " instruction\n"); + goto end; + } + if (0 != memset_s(exec_instr[exec_array_index], + sizeof(sizeof(char) * MOD_MAX_EXEC_ARG_LEN), + 0)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to clear " + "single fdo_sys:exec/exec_cb" + " instruction\n"); + goto end; + } + if (!fdor_string_length(fdor, exec_instructions_sz) || + *exec_instructions_sz > MOD_MAX_EXEC_ARG_LEN) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read " + "fdo_sys:exec/exec_cb text " + "length\n"); + goto end; + } + if (!fdor_text_string(fdor, exec_instr[exec_array_index], + *exec_instructions_sz)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read " + "fdo_sys:exec/exec_cb text\n"); + goto end; + } - if (!fdow_unsigned_int(fdow, status_cb_waitsec)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to write fdo_sys:status_cb waitSec\n"); - return false; + // last argument is the filename + if (exec_array_index == ((int)exec_array_length - 1)) { + if (memset_s(filename, sizeof(filename), 0) != 0) { + LOG(LOG_ERROR, "Module fdo_sys - Failed " + "to clear filename for" + " fdo_sys:exec/exec_cb\n"); + goto end; + } + if (0 != strncpy_s(filename, FILE_NAME_LEN, + exec_instr[exec_array_index], + *exec_instructions_sz)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed " + "to copy filename for" + " fdo_sys:exec/exec_cb\n"); + goto end; + } + } } + exec_instr[exec_array_index] = NULL; - if (!fdow_end_array(fdow)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to end inner fdo_sys:status_cb array\n"); - return false; + if (!fdor_end_array(fdor)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to start " + "fdo_sys:exec/exec_cb array\n"); + goto end; } - return true; + if (*strcmp_exec == 0) { + if (!process_data(FDO_SYS_MOD_MSG_EXEC, NULL, 0, filename, + exec_instr, NULL, NULL, NULL)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "process fdo_sys:exec\n"); + goto end; + } + } else if (*strcmp_execcb == 0) { + if (!process_data(FDO_SYS_MOD_MSG_EXEC_CB, NULL, 0, filename, + exec_instr, &status_cb_iscomplete, + &status_cb_resultcode, &status_cb_waitsec)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "process fdo_sys:exec_cb\n"); + goto end; + } + + // respond with initial fdo_sys:status_cb + // message + hasmore = true; + write_type = FDO_SYS_MOD_MSG_STATUS_CB; + } + result = FDO_SI_SUCCESS; +end: + result = fdo_end(result, NULL, exec_instr); + return result; } -/** - * Write CBOR-encoded fdo_sys:data content into FDOW with given data. - */ -static bool write_data(char *module_message, - uint8_t *bin_data, size_t bin_len) { +int fdo_si_set_osi_status_cb(size_t *status_cb_array_length) +{ + int result = FDO_SI_INTERNAL_ERROR; - if (!module_message || !bin_data) { - LOG(LOG_DEBUG,"Module fdo_sys - Invalid params for fdo_sys:data\n"); - return false; + if (!fdor_array_length(fdor, status_cb_array_length)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to process " + "fdo_sys:status_cb array length\n"); + goto end; + } + if (*status_cb_array_length != 3) { + LOG(LOG_ERROR, "Module fdo_sys - Invalid number of items " + "in fdo_sys:status_cb\n"); + goto end; } - const char message[] = "data"; - if (memcpy_s(module_message, sizeof(message), - message, sizeof(message)) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to copy module message data\n"); - return false; + if (!fdor_start_array(fdor)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to start " + "fdo_sys:status_cb array\n"); + goto end; } - if (!fdow_byte_string(fdow, bin_data, bin_len)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to write fdo_sys:data content\n"); - return false; + if (!fdor_boolean(fdor, &status_cb_iscomplete)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to process " + "fdo_sys:status_cb isComplete\n"); + goto end; } - return true; + if (!fdor_signed_int(fdor, &status_cb_resultcode)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to process " + "fdo_sys:status_cb resultCode\n"); + goto end; + } + + if (!fdor_unsigned_int(fdor, &status_cb_waitsec)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to process " + "fdo_sys:status_cb waitSec\n"); + goto end; + } + + if (!fdor_end_array(fdor)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to end " + "fdo_sys:status_cb array\n"); + goto end; + } + + // if isComplete is true from Owner, then there is going + // to be no response from the device, Else respond with + // fdo_sys:status_cb + if (status_cb_iscomplete) { + hasmore = false; + write_type = FDO_SYS_MOD_MSG_NONE; + } else { + hasmore = true; + write_type = FDO_SYS_MOD_MSG_STATUS_CB; + } + + LOG(LOG_DEBUG, + "Module fdo_sys - fdo_sys:status_cb [%d, %d, " + "%" PRIu64 "]\n", + status_cb_iscomplete, status_cb_resultcode, status_cb_waitsec); + + if (!process_data(FDO_SYS_MOD_MSG_STATUS_CB, NULL, 0, NULL, NULL, + &status_cb_iscomplete, &status_cb_resultcode, + &status_cb_waitsec)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "process fdo_sys:status_cb\n"); + goto end; + } + result = FDO_SI_SUCCESS; +end: + return result; } -/** - * Write CBOR-encoded fdo_sys:eot content into FDOW with given status. - */ -static bool write_eot(char *module_message, int status) { +int fdo_si_set_osi_fetch(size_t bin_len) +{ + int result = FDO_SI_INTERNAL_ERROR; - if (!module_message) { - LOG(LOG_DEBUG,"Module fdo_sys - Invalid params for fdo_sys:eot\n"); - return false; + if (!fdor_string_length(fdor, &bin_len)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to " + "read fdo_sys:fetch length\n"); + goto end; } - const char message[] = "eot"; - if (memcpy_s(module_message, sizeof(message), - message, sizeof(message)) != 0) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to copy module message eot\n"); - return false; + if (bin_len == 0) { + LOG(LOG_DEBUG, "Module fdo_sys - Empty value " + "received for fdo_sys:fetch\n"); + // received file name to be read cannot be empty + // do not allocate for the same and skip reading + // the entry + if (!fdor_next(fdor)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read " + "fdo_sys:fetch\n"); + goto end; + } + result = FDO_SI_CONTENT_ERROR; + goto end; } - if (!fdow_start_array(fdow, 1)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to start inner array in fdo_sys:eot\n"); - return false; + if (memset_s(filename, sizeof(filename), 0) != 0) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to clear " + "fdo_sys:fetch filename buffer\n"); + goto end; } - if (!fdow_signed_int(fdow, status)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to write fdo_sys:eot status\n"); - return false; + if (!fdor_text_string(fdor, &filename[0], bin_len)) { + LOG(LOG_ERROR, "Module fdo_sys - Failed to read value for " + "fdo_sys:fetch\n"); + goto end; } - if (!fdow_end_array(fdow)) { - LOG(LOG_DEBUG,"Module fdo_sys - Failed to end inner array in fdo_sys:eot\n"); - return false; + // set the file size here so that we don't read any more + // than what we initially saw + file_sz = get_file_sz(filename); + hasmore = true; + // reset the file offset to read a new file + file_seek_pos = 0; + write_type = FDO_SYS_MOD_MSG_DATA; + result = FDO_SI_SUCCESS; +end: + return result; +} + +int fdo_end(int result, uint8_t *bin_data, char **exec_instr) +{ + // End of function, clean-up state variables/objects + if (bin_data) { + ModuleFree(bin_data); + } + if (exec_instr && exec_array_length > 0) { + int exec_counter = exec_array_length - 1; + while (exec_counter >= 0) { + ModuleFree(exec_instr[exec_counter]); + --exec_counter; + } + ModuleFree(exec_instr); + exec_array_length = 0; } + if (result != FDO_SI_SUCCESS) { + // clean-up state variables/objects + hasmore = false; + file_sz = 0; + file_seek_pos = 0; + fetch_data_status = 1; + write_type = FDO_SYS_MOD_MSG_NONE; - return true; -} \ No newline at end of file + if (fdow) { + fdow_flush(fdow); + ModuleFree(fdow); + } + if (fdor) { + fdor_flush(fdor); + ModuleFree(fdor); + } + } + return result; +} diff --git a/device_modules/fdo_sys/fdo_sys.h b/device_modules/fdo_sys/fdo_sys.h index f1cef55d..e28dfd53 100644 --- a/device_modules/fdo_sys/fdo_sys.h +++ b/device_modules/fdo_sys/fdo_sys.h @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache 2.0 */ - #ifndef __FDO_SYS_H__ #define __FDO_SYS_H__ @@ -20,57 +19,92 @@ #define MOD_ACTIVE_TAG "active" #define MOD_ACTIVE_STATUS "1" -// maximum length of exec command after combining all arguments of received exec array +// maximum length of exec command after combining all arguments of received exec +// array #define MOD_MAX_EXEC_LEN 1024 // maximum length of the individual text arguments in the received exec array #define MOD_MAX_EXEC_ARG_LEN 100 /** * The registered callback method for 'fdo_sys' ServiceInfo module. - * The implementation is responsible for handling the received Owner ServiceInfo, - * and for generating the Device ServiceInfo to send. - * + * The implementation is responsible for handling the received Owner + * ServiceInfo, and for generating the Device ServiceInfo to send. + * * When module_message, module_val and module_val_sz are used as inputs in type - * 'FDO_SI_SET_OSI', these represent the moduleMessage, CBOR-encoded (bstr-unwrapped) - * module value i.e ServiceInfoVal cbor.bytes, as received in TO2.OwnerServiceInfo (Type 69), - * and its length. - * The implementation must parse and process the input module value - * depending on the given module message, and return. + * 'FDO_SI_SET_OSI', these represent the moduleMessage, CBOR-encoded + * (bstr-unwrapped) module value i.e ServiceInfoVal cbor.bytes, as received in + * TO2.OwnerServiceInfo (Type 69), and its length. The implementation must parse + * and process the input module value depending on the given module message, and + * return. * - * However, the same set of variables are used as output parameters in type 'FDO_SI_GET_DSI', - * wherein, module_message stores the current moduleMessage, - * module_val stores the response CBOR-encoded module value (ServiceInfoVal), and - * module_val_sz stores the corresponding length. - * The implementation is responsible for generating the CBOR-encoded module value using - * any mechanisms/third-party library. In the current implementation, - * the CBOR-encoder/decoder from 'lib/fdoblockio.c' is used. - * These 3 parameters are then, used to generate ServiceInfoKV at TO2.DeviceServiceInfo (Type 68), - * and sent to the Owner. + * However, the same set of variables are used as output parameters in type + * 'FDO_SI_GET_DSI', wherein, module_message stores the current moduleMessage, + * module_val stores the response CBOR-encoded module value (ServiceInfoVal), + * and module_val_sz stores the corresponding length. The implementation is + * responsible for generating the CBOR-encoded module value using any + * mechanisms/third-party library. In the current implementation, the + * CBOR-encoder/decoder from 'lib/fdoblockio.c' is used. These 3 parameters are + * then, used to generate ServiceInfoKV at TO2.DeviceServiceInfo (Type 68), and + * sent to the Owner. * * The input FDOW object to be used to write the desired 'ServiceInfo' structure - * as per the specification, that will be sent to the Owner. The FDOW can also be used - * for other purposes such as ServiceInfo message partitioning (fit within MTU), or, - * determining has_more/is_more etc. The module implemenation is responsible for maintaining - * any internal state information, as needed. - * - * The input fdo_sdk_si_type can be used to do specific tasks depending on the use-case. - * (The types could be updated in the future) - * + * as per the specification, that will be sent to the Owner. The FDOW can also + * be used for other purposes such as ServiceInfo message partitioning (fit + * within MTU), or, determining has_more/is_more etc. The module implemenation + * is responsible for maintaining any internal state information, as needed. + * + * The input fdo_sdk_si_type can be used to do specific tasks depending on the + * use-case. (The types could be updated in the future) + * * @param type - [IN] enum value to describe the operation to be done. - * @param module_message - [IN/OUT] moduleMessage that decides how ServiceInfoVal is processed. - * @param module_val - [IN/OUT] bstr-unwrapped ServiceInfoVal corresponding to the moduleMessage. - * @param module_val_sz - [IN/OUT] ServiceInfoVal length corresponding to the moduleMessage. - * @param num_module_messages - [OUT] Number of ServiceInfoKVs to be sent. Currently UNUSED. + * @param module_message - [IN/OUT] moduleMessage that decides how + * ServiceInfoVal is processed. + * @param module_val - [IN/OUT] bstr-unwrapped ServiceInfoVal corresponding to + * the moduleMessage. + * @param module_val_sz - [IN/OUT] ServiceInfoVal length corresponding to the + * moduleMessage. + * @param num_module_messages - [OUT] Number of ServiceInfoKVs to be sent. + * Currently UNUSED. * @param has_more - [OUT] pointer to bool whose value must be set to * 'true' if there is Device ServiceInfo to send NOW/immediately, OR, * 'false' if there is no Device ServiceInfo to send NOW/immediately. * @param is_more - [OUT] pointer to bool whose value must be set to * 'true' if there is Device ServiceInfo to send in the NEXT ietration, OR, * 'false' if there is no Device ServiceInfo to send in the NEXT iteration. - * @param mtu - [IN] MTU value to be used as the upper bound for the ServiceInfo length. - * @return integer value FDO_SI_CONTENT_ERROR (0), FDO_SI_INTERNAL_ERROR (1), FDO_SI_SUCCESS (2). + * @param mtu - [IN] MTU value to be used as the upper bound for the ServiceInfo + * length. + * @return integer value FDO_SI_CONTENT_ERROR (0), FDO_SI_INTERNAL_ERROR (1), + * FDO_SI_SUCCESS (2). */ -int fdo_sys(fdo_sdk_si_type type, char *module_message, uint8_t *module_val, size_t *module_val_sz, - uint16_t *num_module_messages, bool *has_more, bool *is_more, size_t mtu); +int fdo_sys(fdo_sdk_si_type type, char *module_message, uint8_t *module_val, + size_t *module_val_sz, uint16_t *num_module_messages, + bool *has_more, bool *is_more, size_t mtu); + +// Prototype definitions for functions that are implemented in the module +int fdo_si_start(void); +int fdo_si_failure(void); +int fdo_si_has_more_dsi(bool *has_more); +int fdo_si_is_more_dsi(bool *is_more); +int fdo_si_get_dsi_count(uint16_t *num_module_messages); +int fdo_si_get_dsi(size_t mtu, char *module_message, uint8_t *module_val, + size_t *module_val_sz, size_t file_remaining, size_t bin_len, + uint8_t *bin_data, size_t temp_module_val_sz); + +int fdo_si_set_osi(char *module_message, uint8_t *module_val, + size_t *module_val_sz, int *strcmp_filedesc, + int *strcmp_write, int *strcmp_exec, int *strcmp_execcb, + int *strcmp_statuscb, int *strcmp_fetch); + +int fdo_si_set_osi_strcmp(size_t bin_len, uint8_t *bin_data); +int fdo_si_set_osi_write(size_t bin_len, uint8_t *bin_data); + +int fdo_si_set_osi_exec(char **exec_instr, + int exec_array_index, size_t *exec_instructions_sz, + int *strcmp_exec, int *strcmp_execcb); + +int fdo_si_set_osi_status_cb(size_t *status_cb_array_length); + +int fdo_si_set_osi_fetch(size_t bin_len); +int fdo_end(int result, uint8_t *bin_data, char **exec_instr); #endif /* __FDO_SYS_H__ */ diff --git a/device_modules/fdo_sys/fdo_sys_utils.h b/device_modules/fdo_sys/fdo_sys_utils.h index 04f43c94..5ff5596d 100644 --- a/device_modules/fdo_sys/fdo_sys_utils.h +++ b/device_modules/fdo_sys/fdo_sys_utils.h @@ -19,9 +19,9 @@ #else #define ModuleFree(x) \ - { \ + { \ free(x); \ - x = NULL; \ + x = NULL; \ } #endif @@ -38,11 +38,11 @@ typedef enum { void *ModuleAlloc(int size); bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t dataLen, - char *file_name, char **command, - bool *status_iscomplete, int *status_resultcode, - uint64_t *status_waitsec); + char *file_name, char **command, bool *status_iscomplete, + int *status_resultcode, uint64_t *status_waitsec); size_t get_file_sz(char const *filename); -bool read_buffer_from_file_from_pos(const char *filename, uint8_t *buffer, size_t size, int from); +bool read_buffer_from_file_from_pos(const char *filename, uint8_t *buffer, + size_t size, int from); bool delete_old_file(const char *file_name); #endif /* __SYS_UTILS_H__ */ diff --git a/device_modules/fdo_sys/sys_utils_linux.c b/device_modules/fdo_sys/sys_utils_linux.c index 09f191b1..62f3aab8 100644 --- a/device_modules/fdo_sys/sys_utils_linux.c +++ b/device_modules/fdo_sys/sys_utils_linux.c @@ -15,81 +15,6 @@ // Process ID of the process created by fdo_sys:exec_cb static pid_t exec_pid = -1; -/* Allow only alphanumeric file name either shell or python script*/ -static bool is_valid_filename(const char *fname) -{ - bool ret = false; - int strcmp_result = -1; - uint8_t i = 0; - static const char * const whitelisted[] = {"sh", "py"}; - char *substring = NULL, *t1 = NULL; - char filenme_woextension[FILE_NAME_LEN] = {0}; - size_t fname_len = 0; - size_t ext_len = 0; - const size_t EXT_MAX_LEN = 3; - - if (fname == NULL) { - goto end; - } - - fname_len = strnlen_s(fname, FILE_NAME_LEN); - if (!fname_len || fname_len == FILE_NAME_LEN) { - printf("ERROR: Didn't receive valid filename\n"); - goto end; - } - - if (strncpy_s(filenme_woextension, FILE_NAME_LEN, fname, fname_len)) { - goto end; - } - - if (strlastchar_s(filenme_woextension, FILE_NAME_LEN, '.', &substring)) { - goto end; - } - - *substring = '\0'; // Nullify the pointer - - // Now the array is as follow - // "TEST FILENAME" "ext" - - // check the whitelisted extension type - substring++; - for (i = 0; i < (sizeof(whitelisted) / sizeof(whitelisted[0])); i++) { - ext_len = strnlen_s(substring, EXT_MAX_LEN); - if (!ext_len || ext_len == EXT_MAX_LEN) { - printf("Couldn't find file extension\n"); - ret = false; - break; - } - strcmp_s(substring, ext_len, whitelisted[i], - &strcmp_result); - if (!strcmp_result) { - // extension matched - ret = true; - break; - } - } - if (ret != true) { - goto end; - } - ret = false; - t1 = filenme_woextension; - - // check for only alphanumeric no special char except underscore '_' and hyphen '-' - while (*t1 != '\0') { - if ((*t1 >= 'a' && *t1 <= 'z') || (*t1 >= 'A' && *t1 <= 'Z') || - (*t1 >= '0' && *t1 <= '9') || (*t1 == '_') || (*t1 == '-')) { - t1++; - } else { - goto end; - } - } - - ret = true; -end: - return ret; -} - - void *ModuleAlloc(int size) { if (size <= 0) { @@ -113,8 +38,8 @@ void *ModuleAlloc(int size) } bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, - char *file_name, char **command, bool *status_iscomplete, int *status_resultcode, - uint64_t *status_waitsec) + char *file_name, char **command, bool *status_iscomplete, + int *status_resultcode, uint64_t *status_waitsec) { bool ret = false; FILE *fp = NULL; @@ -131,20 +56,24 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, } if (!file_name) { #ifdef DEBUG_LOGS - printf("fdo_sys write : No filename present for fdo_sys:write\n"); + printf("fdo_sys write : No filename present for " + "fdo_sys:write\n"); #endif return false; } fp = fopen(file_name, "a"); if (!fp) { #ifdef DEBUG_LOGS - printf("fdo_sys write : Failed to open file(path): %s\n", file_name); + printf( + "fdo_sys write : Failed to open file(path): %s\n", + file_name); #endif return false; } - printf("fdo_sys write : %"PRIu32 " bytes being written to the file %s\n", - data_len, file_name); + printf("fdo_sys write : %" PRIu32 + " bytes being written to the file %s\n", + data_len, file_name); if (fwrite(data, sizeof(char), data_len, fp) != (size_t)data_len) { @@ -160,7 +89,7 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, // For exec/exec_cb call if (type == FDO_SYS_MOD_MSG_EXEC || type == FDO_SYS_MOD_MSG_EXEC_CB) { - if (!file_name || !is_valid_filename((const char *) file_name)) { + if (!file_name) { #ifdef DEBUG_LOGS printf("fdo_sys exec/exec_cb : Invalid filename\n"); #endif @@ -176,7 +105,8 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, if (exec_pid != -1) { #ifdef DEBUG_LOGS - printf("fdo_sys exec/exec_cb : An exec instruction is currently in progress\n"); + printf("fdo_sys exec/exec_cb : An exec instruction is " + "currently in progress\n"); #endif return false; } @@ -191,10 +121,11 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, return false; } else if (exec_pid == 0) { // child process - status = execv(command[0], command); + status = execvp(command[0], command); if (status == -1) { #ifdef DEBUG_LOGS - printf("fdo_sys exec : Failed to execute command.\n"); + printf("fdo_sys exec : Failed to execute " + "command.\n"); #endif goto end; } @@ -206,24 +137,30 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) { #ifdef DEBUG_LOGS - printf("fdo_sys exec : Proces execution failed.\n"); + printf("fdo_sys exec : Proces " + "execution failed.\n"); #endif goto end; } else { #ifdef DEBUG_LOGS - printf("fdo_sys exec : Process execution completed.\n"); + printf( + "fdo_sys exec : Process " + "execution completed.\n"); #endif - // reset the process ID since execution is done + // reset the process ID since + // execution is done exec_pid = -1; ret = true; goto end; } } } else { - if (!status_iscomplete || !status_resultcode || !status_waitsec) { + if (!status_iscomplete || !status_resultcode || + !status_waitsec) { #ifdef DEBUG_LOGS - printf("fdo_sys exec_cb : Invalid params\n"); + printf("fdo_sys exec_cb : Invalid " + "params\n"); #endif return ret; } @@ -232,7 +169,8 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, *status_waitsec = 5; ret = true; #ifdef DEBUG_LOGS - printf("fdo_sys exec_cb : Process execution started\n"); + printf("fdo_sys exec_cb : Process execution " + "started\n"); #endif } } @@ -243,7 +181,8 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, // For status_cb if (type == FDO_SYS_MOD_MSG_STATUS_CB) { - if (!status_iscomplete || !status_resultcode || !status_waitsec) { + if (!status_iscomplete || !status_resultcode || + !status_waitsec) { #ifdef DEBUG_LOGS printf("fdo_sys status_cb : Invalid params\n"); #endif @@ -263,23 +202,29 @@ bool process_data(fdoSysModMsg type, uint8_t *data, uint32_t data_len, ret = true; goto end; } else { - // check for process status every second, until the given waitsec + // check for process status every second, until the + // given waitsec int wait_timer = *status_waitsec; while (wait_timer > 0) { if (waitpid(exec_pid, &status, WNOHANG) == -1) { #ifdef DEBUG_LOGS - printf("fdo_sys status_cb : Error occurred while checking process status\n"); + printf("fdo_sys status_cb : Error " + "occurred while checking " + "process status\n"); #endif return ret; } if (WIFEXITED(status)) { - *status_resultcode = WEXITSTATUS(status); + *status_resultcode = + WEXITSTATUS(status); *status_iscomplete = true; *status_waitsec = 0; #ifdef DEBUG_LOGS - printf("fdo_sys status_cb: Process execution completed\n"); + printf("fdo_sys status_cb: Process " + "execution completed\n"); #endif - // reset the process ID since execution is done + // reset the process ID since execution + // is done exec_pid = -1; ret = true; goto end; @@ -363,10 +308,11 @@ size_t get_file_sz(char const *filename) } /** - * Read the filename's content (size bytes) into the given buffer (pre-allocated memory) - * starting at the specified offset (from). + * Read the filename's content (size bytes) into the given buffer (pre-allocated + * memory) starting at the specified offset (from). */ -bool read_buffer_from_file_from_pos(const char *filename, uint8_t *buffer, size_t size, int from) +bool read_buffer_from_file_from_pos(const char *filename, uint8_t *buffer, + size_t size, int from) { FILE *file = NULL; size_t bytes_read = 0; @@ -382,7 +328,7 @@ bool read_buffer_from_file_from_pos(const char *filename, uint8_t *buffer, size_ printf("Fclose Failed"); } return false; - } + } bytes_read = fread(buffer, 1, size, file); if (bytes_read != size) { if (fclose(file) == EOF) { diff --git a/docs/DI_setup.md b/docs/DI_setup.md index 2752ed85..395ffe54 100644 --- a/docs/DI_setup.md +++ b/docs/DI_setup.md @@ -5,7 +5,7 @@ Open a terminal and start the FDO PRI Manufacturer. After this step, an ownershi is generated so that the new owner can initiate the TO0 protocol. Detailed steps and configuration needed to start FDO PRI Manufacturer are in -[README](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md) document. +[README](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md) document. # Device Initialization Device Setup diff --git a/docs/build_conf.md b/docs/build_conf.md index d58a7472..8927763c 100644 --- a/docs/build_conf.md +++ b/docs/build_conf.md @@ -1,4 +1,5 @@ + # Build Configuration Following are some of the options to choose when building the device: - BUILD: Release or debug mode @@ -35,7 +36,7 @@ $ make -j4 For available build options: ```shell List of build modes: -BUILD=debug # Debug mode +BUILD=debug # Debug mode BUILD=release # Release mode (default) List of supported TARGET_OS: @@ -54,6 +55,7 @@ List of Device Attestation options: DA=ecdsa256 # Use ECDSA P256 based device attestation DA=ecdsa384 # Use ECDSA-P384 based device attestation(default) DA=tpm20_ecdsa256 # Use ECDSA-P256 based device attestation with TPM2.0 support +DA=tpm20_ecdsa384 # Use ECDSA-P384 based device attestation with TPM2.0 support DA_FILE=pem # only Use if ECDSA private keys are PEM encoded Underlying crypto library to be used: @@ -76,7 +78,18 @@ $ ./build/linux-client -ss ``` > ***WARN***: Accepting Self Signed Certificates is not recommended. If compromised, self-signed certificates can pose serious security risks. +```shell +Option to enable SNI(Server Name Indication extension in client(device) msgs to server): +SNI=true # SNI support is enabled. (default) +SNI=false # SNI support is disabled. ``` +> ***Note***: If you have server IP configured in no_proxy environment variable, also add the +server name in that list for SNI enablement to work as expected. +```shell +Option to enable/disable mTLS connection: +MTLS=true # mTLS connection enabled +MTLS=false # mTLS connection disabled (default) + Option to enable/disable Device credential resue and resale feature: REUSE=true # Reuse feature enabled (default) REUSE=false # Reuse feature disabled @@ -87,6 +100,15 @@ Option to enable/disable Error Recovery: RETRY=true # Error Recovery enabled (default) RETRY=false # Error Recovery disabled +Option to get device serial from system BIOS table: +GET_DEV_SERIAL=true # get device serial enabled +GET_DEV_SERIAL=false # get device serial disabled (default) +NOTE: linux-client required elevated privileges to get device serial from system BIOS table. Use 'sudo' to execute. + +Option to lock TPM for futher reads and writes: +LOCK_TPM=true # TPM Locked for futher reads and writes (default) +LOCK_TPM=false # TPM not locked for futher reads and writes + List of options to clean targets: pristine # cleanup by remove generated files diff --git a/docs/cse.md b/docs/cse.md index ff699563..4dcd840e 100644 --- a/docs/cse.md +++ b/docs/cse.md @@ -1,40 +1,48 @@ +# Intel® CSE Implementation +The development and execution OS used was `Ubuntu* OS version [20.04|22.04] / RHEL* OS version [8.4|8.6|8.8] / Debian 11.4` on x86. Follow these steps to compile and execute FIDO Device Onboard (FDO). +The Intel® CSE (Intel® Converged Security Engine) enabled FDO Client SDK execution depends on OpenSSL* toolkit 3.0.14 version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. +# Prerequisites for Intel® CSE support +The system hardware should have the support for Intel® CSE FDO client with UUID: 125405e0-fca9-4110-8f88-b4dbcdcb876f - -# Linux* CSE* Implementation -The development and execution OS used was `Ubuntu* OS version 20.04 or 22.04 / RHEL* OS version 8.4 or 8.6 / Debian 11.4` on x86. Follow these steps to compile and execute FIDO Device Onboard (FDO). - -The CSE* enabled FDO Client SDK execution depends on OpenSSL* toolkit 1.1.1t version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. - -# Prerequisites for CSE support -The system hardware should have the support for CSE FDO client with UUID: 125405e0-fca9-4110-8f88-b4dbcdcb876f - -The linux kernel should have the support to enable the CSE clients and have FDO in that list. This support is available in intel-next kernel version 5.9 onwards and is upstreamed in kernel.org version 6.2-rc7 onwards. +The linux kernel should have the support to enable the Intel® CSE clients and have FDO in that list. This support is available in intel-next kernel version 5.9 onwards and is upstreamed in kernel.org version 6.2-rc7 onwards. ## 1. Packages Requirements when Building Binaries: -* For Ubuntu* OS version 20.04 or 22.04 / Debian 11.4: +* For Ubuntu* OS version [20.04|22.04] / Debian 11.4: ```shell -sudo apt-get install build-essential python-setuptools clang-format dos2unix ruby build-essential \ - libglib2.0-dev libpcap-dev autoconf libtool libproxy-dev doxygen cmake libssl-dev mercurial +sudo apt-get install build-essential python-setuptools clang-format dos2unix ruby \ + libglib2.0-dev libpcap-dev autoconf libtool libproxy-dev doxygen cmake libssl-dev mercurial nghttp2 libnghttp2-dev ``` -* For RHEL* OS version 8.4 or 8.6: +* For RHEL* OS version [8.4|8.6|8.8]: ```shell sudo subscription-manager repos --enable codeready-builder-for-rhel-8-x86_64-rpms sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm ``` ``` -sudo yum -y install gcc gcc-c++ python3-setuptools git-clang-format dos2unix ruby gcc gcc-c++ make perl glibc-static \ - glib2-devel libpcap-devel autoconf libtool libproxy-devel mozjs52-devel doxygen cmake openssl-devel make mercurial perl +sudo yum -y install gcc gcc-c++ python3-setuptools git-clang-format dos2unix ruby perl glibc-static \ + glib2-devel libpcap-devel autoconf libtool libproxy-devel mozjs52-devel doxygen cmake openssl-devel make mercurial perl nghttp2 libnghttp2-devel ``` + ## 2. Packages Requirements when Executing Binaries: -OpenSSL* toolkit version 1.1.1t +OpenSSL* toolkit version 3.0.14 GCC version > 7.5 -Curl version 7.88 +Curl version 8.8.0 + +Following steps will replace the existing versions of OpenSSL and Curl from the system. If you want to keep the existing versions then use [Installation-Script](../utils/install_openssl_curl.sh) script to install Openssl and Curl at a different location. +> ***NOTE***: [Installation-Script](../utils/install_openssl_curl.sh) will install OpenSSL and Curl at /opt/ by default. To provide different path, modify these variables in the script +> OPENSSL_ROOT=/opt/openssl +> CURL_ROOT=/opt/curl +> +**Script usage command** +* Command to install OpenSSL and Curl + ``` + sudo ./install_openssl_curl.sh -i -v 3.0.14 + ``` #### Steps to remove the older curl packages 1. If curl and libcurl are already installed, uninstall it: @@ -46,19 +54,19 @@ Curl version 7.88 yum remove curl libcurl-devel ``` -#### Steps to Upgrade the OpenSSL* Toolkit to Version 1.1.1t +#### Steps to Upgrade the OpenSSL* Toolkit to Version 3.0.14 1. Pull the tarball: ``` - wget https://www.openssl.org/source/openssl-1.1.1t.tar.gz + wget https://www.openssl.org/source/openssl-3.0.14.tar.gz ``` 2. Unpack the tarball with: ``` - tar -zxf openssl-1.1.1t.tar.gz && cd openssl-1.1.1t + tar -zxf openssl-3.0.14.tar.gz && cd openssl-3.0.14 ``` 3. Issue the command: ``` - ./config + ./config --libdir=/usr/local/lib ``` 4. Issue the command: ``` @@ -83,6 +91,7 @@ Curl version 7.88 ``` 9. Run the command to update symlinks and rebuild the library cache: ``` + grep -qxF '/usr/local/lib/' /etc/ld.so.conf.d/libc.conf || echo /usr/local/lib/ | sudo tee -a /etc/ld.so.conf.d/libc.conf sudo ldconfig ``` 10. Assuming no errors in executing steps 4 through 10, you should have successfully installed the new version of the OpenSSL* toolkit. @@ -92,24 +101,24 @@ Issue the following command from the terminal: ``` Your output should be as follows: ``` - OpenSSL* 1.1.1t 7 Feb 2023 + OpenSSL* 3.0.14 04 Jun 2024 ``` -#### Steps to install curl version 7.88 configured with openssl +#### Steps to install curl version 8.8.0 configured with openssl After installing openssl, proceed with the installation of curl. 1. Pull the tarball: ``` - wget https://github.com/curl/curl/releases/download/curl-7.88_0/curl-7.88.0.tar.gz + wget https://curl.se/download/curl-8.8.0.tar.gz ``` 2. Unpack the tarball with: ``` - tar -zxf curl-7.88.0.tar.gz && cd curl-7.88.0 + tar -zxf curl-8.8.0.tar.gz && cd curl-8.8.0 ``` -3. Issue the command to configure the curl with openssl: +3. Issue the command to configure the curl with openssl and nghttp2: ``` - ./configure --with-openssl="OpenSSL Path" --enable-versioned-symbols + ./configure --with-openssl="OpenSSL Path" --with-nghttp2 --enable-versioned-symbols --without-libpsl ``` 4. Issue the command to build curl: ``` @@ -128,39 +137,39 @@ Issue the following command from the terminal: ``` Your output should point to the openssl version which you installed. ``` - curl 7.88.0 (x86_64-pc-linux-gnu) libcurl/7.88.0 OpenSSL/1.1.1t zlib/1.2.11 + curl 8.8.0 (x86_64-pc-linux-gnu) libcurl/8.8.0 OpenSSL/3.0.14 zlib/1.2.11 ``` Alternatively, execute [Installation-Script](../utils/install_openssl_curl.sh) which can be used for both installation and uninstallation of OpenSSL and Curl. +> ***NOTE***: [Installation-Script](../utils/install_openssl_curl.sh) will install OpenSSL and Curl to /opt/ by default. To provide different path, modify these variables in the script +> OPENSSL_ROOT=/opt/openssl +> CURL_ROOT=/opt/curl + **Script usage command** * Command to install OpenSSL and Curl ``` - sudo ./install_openssl_curl.sh -i -v 1.1.1t + sudo ./install_openssl_curl.sh -i -v 3.0.14 ``` * Command to uninstall OpenSSL ``` - sudo ./install_openssl_curl.sh -u -v 1.1.1t - ``` -Note 1: If above command is not successful, then link the path where curl is installed to the system path - ``` - sudo ln -s /usr/local/bin/curl /usr/bin/curl + sudo ./install_openssl_curl.sh -u -v 3.0.14 ``` -Note 2: If you are using no_proxy environment variable to exclude proxying for any FDO server IP addresses along with curl 7.88 in your setup, ensure to use CIDR notation (https://datatracker.ietf.org/doc/html/rfc1519) as given in below examples. +Note 1: If you are using no_proxy environment variable to exclude proxying for any FDO server IP addresses along with curl 8.8.0 in your setup, ensure to use CIDR notation (https://datatracker.ietf.org/doc/html/rfc1519) as given in below examples. Single IP address example: no_proxy="10.60.132.45/32" Two IP addresses example: no_proxy="10.60.132.45/32,10.60.132.46/32" Range of IP addresses example: no_proxy="10.60.0.0/16" -Note 3: On RHEL, Curl could also be installed using yum package manager as shown below: +Note 2: On RHEL, Curl could also be installed using yum package manager as shown below: ``` sudo yum -y install libcurl-devel ``` ## 3. Compiling Intel safestringlib -CSE* enabled FDO Client SDK uses safestringlib for string and memory operations to prevent serious security vulnerabilities (For example, buffer overflows). Download safestringlib from intel-safestringlib and follow these instructions to build: +FDO Client SDK uses safestringlib for string and memory operations to prevent serious security vulnerabilities (For example, buffer overflows). Download safestringlib from intel-safestringlib, checkout to the tag `v1.2.0` and follow these instructions to build: From the root of the safestringlib, do the following: ```shell mkdir obj @@ -169,13 +178,13 @@ From the root of the safestringlib, do the following: After this step, `libsafestring.a` library will be created. ## 4. Compiling Intel TinyCBOR -CSE* enabled FDO Client SDK uses TinyCBOR library for Concise Binary Object Representation (CBOR) encoding and decoding. Download TinyCBOR from TinyCBOR, checkout to the tag `v0.5.3` and follow these instructions to build: +FDO Client SDK uses TinyCBOR library for Concise Binary Object Representation (CBOR) encoding and decoding. Download TinyCBOR from TinyCBOR, checkout to the tag `v0.6.0` and follow these instructions to build: From the root of the TinyCBOR (named `tinycbor`), do the following: ```shell make ``` ## 5. Compiling Intel ME TEE -CSE* enabled FDO Client SDK uses ME TEE library to communicate with CSE through HECI. Download ME TEE from METEE, and follow these instructions to build: +Intel® CSE enabled FDO Client SDK uses ME TEE library to communicate with CSE through HECI. Download ME TEE from METEE, and follow these instructions to build: From the root of the METEE(named `metee`), do the following: ```shell cmake . @@ -185,16 +194,18 @@ From the root of the METEE(named `metee`), do the following: ## 6. Environment Variables Add these environment variables to ~/.bashrc or similar (replace with actual paths). -Provide safestringlib and tinycbor paths: +Provide OpenSSL, Curl, safestringlib, tinycbor and metee paths: ```shell +export OPENSSL3_ROOT=path/to/openssl (can be /usr or /usr/local or default provide /opt/openssl) +export CURL_ROOT=path/to/curl (can be /usr or /usr/local or default provide /opt/curl) export SAFESTRING_ROOT=path/to/safestringlib export TINYCBOR_ROOT=path/to/tinycbor export METEE_ROOT=path/to/metee ``` -## 7. Compiling CSE* enabled FDO Client SDK +## 7. Compiling Intel® CSE enabled FDO Client SDK -The CSE* enabled FDO Client SDK build system is based on GNU make. It assumes that all the requirements are set up according to [ FDO Compilation Setup ](setup.md). The application is built using the `cmake [options]` in the root of the repository for all supported platforms. The debug and release build modes are supported in building the CSE* enabled FDO Client SDK. +The Intel® CSE enabled FDO Client SDK build system is based on GNU make. It assumes that all the requirements are set up according to [ FDO Compilation Setup ](setup.md). The application is built using the `cmake [options]` in the root of the repository for all supported platforms. The debug and release build modes are supported in building the Intel® CSE enabled FDO Client SDK. For an advanced build configuration, refer to [ Advanced Build Configuration ](build_conf.md). @@ -203,18 +214,24 @@ make pristine cmake -DDA=cse_ecdsa384 . make -j$(nproc) ``` +> ***NOTE***: To run with mTLS connection, +> 1. Compile the code with `-DMTLS=true` flag. +> 2. If signing with external CA, copy CA cert and CA key to `data` folder. +> 3. Execute `bash utils/user_csr_req.sh .` +> This will generate client CSR and private key. +> Refer to the section [FDO Build configurations](build_conf.md) for more build options. ## 8. Running the Application -The CSE* enabled FDO Client SDK Linux device is compatible with FDO PRI components namely: Manufacturer, Rendezvous, and Owner. +The Intel® CSE enabled FDO Client SDK Linux device is compatible with FDO PRI components namely: Manufacturer, Rendezvous, and Owner. -To test the CSE* enabled FDO Client SDK Linux device, setup the [FDO PRI Manufacturer](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md), -[FDO PRI Rendezvous](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md), and -[FDO PRI Owner](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md). +To test the Intel® CSE enabled FDO Client SDK Linux device, setup the [FDO PRI Manufacturer](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md), +[FDO PRI Rendezvous](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md), and +[FDO PRI Owner](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md). -After a successful compilation, the CSE* enabled FDO Client SDK Linux device executable can be found at `/build/linux-client`. +After a successful compilation, the Intel® CSE enabled FDO Client SDK Linux device executable can be found at `/build/linux-client`. > ***NOTE***: Built binary can be either `debug` or `release` based on the compilation step. - Before executing `linux-client`, prepare for Device Initialization (DI) by starting the FDO PRI Manufacturer. @@ -232,6 +249,16 @@ After a successful compilation, the CSE* enabled FDO Client SDK Linux device exe ```shell sudo ./build/linux-client ``` + +> ***NOTE***: Usage: +> +> ``` +>./build/linux-client -ip ://: +>if -ip not specified, manufacturer_addr.bin will be used +>-ss: specify if backend servers are using self-signed certificates +>-r: enable resale +>``` +> > ***NOTE***: To do the DI again we need to clear the Device status from CSE storage. > To clear the storage, compile the code with "-DCSE_CLEAR=true" flag and then execute the following command ```shell diff --git a/docs/linux.md b/docs/linux.md index bf637557..37f9247a 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -1,58 +1,73 @@ - - # Linux* OS -The development and execution OS used was `Ubuntu* OS version 20.04 or 22.04 / RHEL* OS version 8.4 or 8.6 / Debian 11.4` on x86. Follow these steps to compile and execute FIDO Device Onboard (FDO). +The development and execution OS used was `Ubuntu* OS version [20.04|22.04] / RHEL* OS version [8.4|8.6|8.8] / Debian 11.4` on x86. Follow these steps to compile and execute FIDO Device Onboard (FDO). -The FDO Client SDK execution depends on OpenSSL* toolkit 1.1.1t version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. +The FDO Client SDK execution depends on OpenSSL* toolkit 3.0.14 version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. ## 1. Packages Requirements when Building Binaries: -* For Ubuntu* OS version 20.04 or 22.04 / Debian 11.4: +* For Ubuntu* OS version [20.04|22.04] / Debian 11.4: ```shell -sudo apt-get install build-essential python-setuptools clang-format dos2unix ruby build-essential \ - libglib2.0-dev libpcap-dev autoconf libtool libproxy-dev doxygen cmake libssl-dev mercurial +sudo apt-get install build-essential python-setuptools clang-format dos2unix ruby \ + libglib2.0-dev libpcap-dev autoconf libtool libproxy-dev doxygen cmake mercurial nghttp2 libnghttp2-dev ``` -* For RHEL* OS version 8.4 or 8.6: +* For RHEL* OS version [8.4|8.6|8.8]: ```shell sudo subscription-manager repos --enable codeready-builder-for-rhel-8-x86_64-rpms sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm ``` ``` -sudo yum -y install gcc gcc-c++ python3-setuptools git-clang-format dos2unix ruby gcc gcc-c++ make perl glibc-static \ - glib2-devel libpcap-devel autoconf libtool libproxy-devel mozjs52-devel doxygen cmake openssl-devel make mercurial perl +sudo yum -y install gcc gcc-c++ python3-setuptools git-clang-format dos2unix ruby perl glibc-static \ + glib2-devel libpcap-devel autoconf libtool libproxy-devel mozjs52-devel doxygen cmake make mercurial perl nghttp2 libnghttp2-devel ``` ## 2. Packages Requirements when Executing Binaries: -OpenSSL* toolkit version 1.1.1t +OpenSSL* toolkit version 3.0.14 GCC version > 7.5 -Curl version 7.88 +Curl version 8.8.0 + +Following steps will replace the existing versions of OpenSSL and Curl from the system. If you want to keep the existing versions then use [Installation-Script](../utils/install_openssl_curl.sh) script to install Openssl and Curl at a different location. +> ***NOTE***: [Installation-Script](../utils/install_openssl_curl.sh) will install OpenSSL and Curl at /opt/ by default. To provide different path, modify these variables in the script +> OPENSSL_ROOT=/opt/openssl +> CURL_ROOT=/opt/curl +> +**Script usage command** + +* Command to install OpenSSL and Curl + ``` + sudo ./install_openssl_curl.sh -i -v 3.0.14 + ``` -#### Steps to remove the older curl packages +#### Steps to remove the older OpenSSL and curl packages + +1. If libssl-dev, curl and libcurl are installed, uninstall it: -1. If curl and libcurl are already installed, uninstall it: ``` + sudo apt-get remove --auto-remove libssl-dev + sudo apt-get remove --auto-remove libssl-dev:i386 sudo apt remove curl libcurl4-openssl-dev ``` In case of RHEL OS, use below commands to uninstall: + ``` - yum remove curl libcurl-devel + sudo yum remove libcurl-devel openssl-devel ``` -#### Steps to Upgrade the OpenSSL* Toolkit to Version 1.1.1t +#### Steps to Upgrade the OpenSSL* Toolkit to Version 3.0.14 1. Pull the tarball: ``` - wget https://www.openssl.org/source/openssl-1.1.1t.tar.gz + wget https://www.openssl.org/source/openssl-3.0.14.tar.gz ``` 2. Unpack the tarball with: ``` - tar -zxf openssl-1.1.1t.tar.gz && cd openssl-1.1.1t + tar -zxf openssl-3.0.14.tar.gz && cd openssl-3.0.14 ``` 3. Issue the command: ``` - ./config + ./config --libdir=/usr/local/lib ``` + 4. Issue the command: ``` make @@ -76,6 +91,7 @@ Curl version 7.88 ``` 9. Run the command to update symlinks and rebuild the library cache: ``` + grep -qxF '/usr/local/lib/' /etc/ld.so.conf.d/libc.conf || echo /usr/local/lib/ | sudo tee -a /etc/ld.so.conf.d/libc.conf sudo ldconfig ``` 10. Assuming no errors in executing steps 4 through 10, you should have successfully installed the new version of the OpenSSL* toolkit. @@ -85,24 +101,24 @@ Issue the following command from the terminal: ``` Your output should be as follows: ``` - OpenSSL* 1.1.1t 7 Feb 2023 + OpenSSL* 3.0.14 04 Jun 2024 ``` -#### Steps to install curl version 7.88 configured with openssl +#### Steps to install curl version 8.8.0 configured with openssl After installing openssl, proceed with the installation of curl. 1. Pull the tarball: ``` - wget https://github.com/curl/curl/releases/download/curl-7.88_0/curl-7.88.0.tar.gz + wget https://curl.se/download/curl-8.8.0.tar.gz ``` 2. Unpack the tarball with: ``` - tar -zxf curl-7.88.0.tar.gz && cd curl-7.88.0 + tar -zxf curl-8.8.0.tar.gz && cd curl-8.8.0 ``` -3. Issue the command to configure the curl with openssl: +3. Issue the command to configure the curl with openssl and nghttp2: ``` - ./configure --with-openssl --enable-versioned-symbols + ./configure --with-openssl="OpenSSL Path" --with-nghttp2 --enable-versioned-symbols --without-libpsl ``` 4. Issue the command to build curl: ``` @@ -121,27 +137,22 @@ Issue the following command from the terminal: ``` Your output should point to the openssl version which you installed. ``` - curl 7.88.0 (x86_64-pc-linux-gnu) libcurl/7.88.0 OpenSSL/1.1.1t zlib/1.2.11 + curl 8.8.0 (x86_64-pc-linux-gnu) libcurl/8.8.0 OpenSSL/3.0.14 zlib/1.2.11 ``` -Note 1: If above command is not successful, then link the path where curl is installed to the system path - ``` - sudo ln -s /usr/local/bin/curl /usr/bin/curl - ``` - -Note 2: If you are using no_proxy environment variable to exclude proxying for any FDO server IP addresses along with curl 7.88 in your setup, ensure to use CIDR notation (https://datatracker.ietf.org/doc/html/rfc1519) as given in below examples. +Note 1: If you are using no_proxy environment variable to exclude proxying for any FDO server IP addresses along with curl 8.8.0 in your setup, ensure to use CIDR notation (https://datatracker.ietf.org/doc/html/rfc1519) as given in below examples. Single IP address example: no_proxy="10.60.132.45/32" Two IP addresses example: no_proxy="10.60.132.45/32,10.60.132.46/32" Range of IP addresses example: no_proxy="10.60.0.0/16" -Note 3: On RHEL, Curl could also be installed using yum package manager as shown below: +Note 2: On RHEL, Curl could also be installed using yum package manager as shown below: ``` sudo yum -y install libcurl-devel ``` ## 3. Compiling Intel safestringlib -FDO Client SDK uses safestringlib for string and memory operations to prevent serious security vulnerabilities (For example, buffer overflows). Download safestringlib from intel-safestringlib and follow these instructions to build: +FDO Client SDK uses safestringlib for string and memory operations to prevent serious security vulnerabilities (For example, buffer overflows). Download safestringlib from intel-safestringlib, checkout to the tag `v1.2.0` and follow these instructions to build: From the root of the safestringlib, do the following: ```shell mkdir obj @@ -150,7 +161,7 @@ From the root of the safestringlib, do the following: After this step, `libsafestring.a` library will be created. ## 4. Compiling Intel TinyCBOR -FDO Client SDK uses TinyCBOR library for Concise Binary Object Representation (CBOR) encoding and decoding. Download TinyCBOR from TinyCBOR, checkout to the tag `v0.5.3` and follow these instructions to build: +FDO Client SDK uses TinyCBOR library for Concise Binary Object Representation (CBOR) encoding and decoding. Download TinyCBOR from TinyCBOR, checkout to the tag `v0.6.0` and follow these instructions to build: From the root of the TinyCBOR (named `tinycbor`), do the following: ```shell make @@ -158,8 +169,10 @@ From the root of the TinyCBOR (named `tinycbor`), do the following: ## 5. Environment Variables Add these environment variables to ~/.bashrc or similar (replace with actual paths). -Provide safestringlib and tinycbor paths: +Provide OpenSSL, Curl, safestringlib and tinycbor paths: ```shell +export OPENSSL3_ROOT=path/to/openssl (can be /usr or /usr/local or default provide /opt/openssl) +export CURL_ROOT=path/to/curl (can be /usr or /usr/local or default provide /opt/curl) export SAFESTRING_ROOT=path/to/safestringlib export TINYCBOR_ROOT=path/to/tinycbor ``` @@ -176,7 +189,15 @@ cmake . make bash utils/keys_gen.sh . ``` - +> ***NOTE***: [Keys_Gen](../utils/keys_gen.sh) script will use OpenSSL from `/opt/` by default. To provide a different path, use `which openssl` command to get the exact path of OpenSSL and modify this variable in the script +> OPENSSL3_BIN=/opt/openssl/bin (can be /usr/bin or /usr/local/bin) +> +> ***NOTE***: To run with mTLS connection, +> 1. Compile the code with `-DMTLS=true` flag. +> 2. If signing with external CA, copy CA cert and CA key to `data` folder. +> 3. Execute `bash utils/user_csr_req.sh .` +> This will generate client CSR and private key. +> Several other options to choose when building the device are, but not limited to, the following: device-attestation (DA) methods, Advanced Encryption Standard (AES) encryption modes (AES_MODE), and underlying cryptography library to use (TLS). Refer to the section. [FDO Build configurations](build_conf.md) @@ -185,9 +206,9 @@ Refer to the section. [FDO Build configurations](build_conf.md) ## 7. Running the Application The FDO Client SDK Linux device is compatible with FDO PRI components namely: Manufacturer, Rendezvous, and Owner. -To test the FDO Client SDK Linux device, setup the [FDO PRI Manufacturer](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md), -[FDO PRI Rendezvous](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md), and -[FDO PRI Owner](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md). +To test the FDO Client SDK Linux device, setup the [FDO PRI Manufacturer](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md), +[FDO PRI Rendezvous](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md), and +[FDO PRI Owner](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md). After a successful compilation, the FDO Client SDK Linux device executable can be found at `/build/linux-client`. > ***NOTE***: Built binary can be either `debug` or `release` based on the compilation step. @@ -207,12 +228,12 @@ After a successful compilation, the FDO Client SDK Linux device executable can b ```shell ./build/linux-client ``` -- If the client-sdk binary is built on openssl 1.1.1t environment and then executed with openssl 3 environment, it may fail with "libssl.so.1.1 not found" error. In order to successfully execute it, build the specific 1.1.1 version dependent libraries and make it available as well: -``` - wget https://www.openssl.org/source/openssl-1.1.1t.tar.gz - tar -zxf openssl-1.1.1t.tar.gz && cd openssl-1.1.1t - ./config - make - cp libssl.so.1.1 /usr/lib/x86_64-linux-gnu/ - cp libcrypto.so.1.1 /usr/lib/x86_64-linux-gnu/ -``` + +> ***NOTE***: Usage: +> +> ``` +>./build/linux-client -ip ://: +>if -ip not specified, manufacturer_addr.bin will be used +>-ss: specify if backend servers are using self-signed certificates +>-r: enable resale +>``` diff --git a/docs/mbed_linux.md b/docs/mbed_linux.md index bc760fc5..233d2b54 100644 --- a/docs/mbed_linux.md +++ b/docs/mbed_linux.md @@ -54,7 +54,7 @@ The FDO Client SDK for Arm Cortex-A7 platform is built using the Yocto Project-b IMAGE_INSTALL_APPEND = "clientsdk-mbedtls" ``` -6. Re-run the build command as you did in the [Building Arm Mbed Linux OS](#building-mbed-linux) step. +6. Re-run the build command as you did in the [Building Arm Mbed Linux OS](#building-arm-mbed-linux-os) step. > ***NOTE***: If the `imx7s-warp.dtb` file is not generated during build, refer to [this](https://github.com/WaRP7/linux-fslc/) link to generate the file. ## Flashing and Preparing the Device diff --git a/docs/ownership_transfer.md b/docs/ownership_transfer.md index e6f7c3ef..3ffdcd9f 100644 --- a/docs/ownership_transfer.md +++ b/docs/ownership_transfer.md @@ -4,5 +4,5 @@ Server, that is, TO0 is successful. FDO Client SDK, then connects to FDO PRI Ren If the RendezvousInfo in the Ownership Voucher contains RendezvousInstr `RVBYPASS`, then TO0 completion is not required. In such a scenario, FDO Client SDK skips TO1 protocol and connects directly to the FDO PRI Owner to execute TO2 protocol. -Refer to the [FDO PRI Rendezvous](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md) and -[FDO PRI Owner](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md) for details on setup and configuration. +Refer to the [FDO PRI Rendezvous](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md) and +[FDO PRI Owner](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md) for details on setup and configuration. diff --git a/docs/security_implications.md b/docs/security_implications.md index b8a4acf1..808e637f 100644 --- a/docs/security_implications.md +++ b/docs/security_implications.md @@ -16,15 +16,15 @@ The Nonce length 'N' is thus fixed at 7 octets (i.e 15-8). As per FDO and COSE [RFC8152](https://datatracker.ietf.org/doc/html/rfc8152) specifications, L=2 could also be used. N=13 MUST be used in this case. Affected file(s): - - `crypto/openssl/openssl_AESRoutines.c` + - `crypto/openssl/openssl_AES_routines.c` - `lib/fdotypes.h` ## Linux* OS (OpenSSL* toolkit as the cryptography library) 1. The random number needs to be seeded with an entropy source. Affected file(s): - - `crypto/openssl/openssl_cryptoSupport.c` + - `crypto/openssl/openssl_crypto_support.c` - `crypto/mbedtls/mbedtls_cryptoSupport.c` (Not supported) - - `crypto/se/se_cryptoSupport.c` (Not supported) + - `crypto/se/se_crypto_support.c` (Not supported) 2. In the reference implementation, the device key and the keys that encrypt or protect the integrity of the FIDO Device Onboard (FDO) data are stored in clear text on the file system. @@ -45,7 +45,7 @@ L=2 could also be used. N=13 MUST be used in this case. ## NUCLEO-F429ZI board: Arm Cortex* -M4/Arm Mbed* OS (mbedTLS as the cryptography library) 1. The mbedTLS library must use the True Random Number Generator (TRNG) hardware for the entropy source. Refer to - [mbedTLS Hardware Entropy Source](#mbedtls_entropy) for more information. + [mbedTLS Hardware Entropy Source](#mbedtls-hardware-entropy-source) for more information. 2. In the reference implementation, the device key and the keys that encrypt or protect the integrity of the FDO data are stored in clear text on the file system. @@ -70,7 +70,7 @@ L=2 could also be used. N=13 MUST be used in this case. ## NUCLEO-F767ZI board: Arm Cortex-M7/Arm Mbed OS (mbedTLS as the cryptography library) 1. The mbedTLS library must use the TRNG hardware for the entropy source. Refer to - [mbedTLS Hardware Entropy Source](#mbedtls_entropy) for more information. + [mbedTLS Hardware Entropy Source](#mbedtls-hardware-entropy-source) for more information. 2. In the reference implementation, the device key and the keys that encrypt or protect the integrity of the FDO data are stored in clear text on the file system. @@ -96,7 +96,7 @@ L=2 could also be used. N=13 MUST be used in this case. ## WaRP7 board: Arm Cortex-A7/Linux OS (mbedTLS as the cryptography library) 1. The mbedTLS library must use the True Random Number Generator (TRNG) hardware for the entropy source. Refer to - [mbedTLS Hardware Entropy Source](#mbedtls_entropy) for more information. + [mbedTLS Hardware Entropy Source](#mbedtls-hardware-entropy-source) for more information. 2. In the reference implementation, the device key and the keys that encrypt or protect the integrity of the FDO data are stored in clear text on the file system. @@ -136,7 +136,7 @@ L=2 could also be used. N=13 MUST be used in this case. ## mbedTLS Hardware Entropy Source To enable the TRNG hardware as the entropy source, the `MBEDTLS_ENTROPY_HARDWARE_ALT` macro must be uncommented in -`include/mbedtls/config.h` in the mbedTLS source code. The +`include/mbedtls/config.h` in the mbedTLS source code. The ` mbedtls_hardware_poll()` function, with prototype declared in `entropy_poll.h`, must be implemented to collect entropy from the hardware source. diff --git a/docs/tpm.md b/docs/tpm.md index d1df77dc..8fb926a8 100644 --- a/docs/tpm.md +++ b/docs/tpm.md @@ -1,59 +1,68 @@ - - - # Linux* TPM* Implementation -`Ubuntu* OS version 20.04 or 22.04 / RHEL* OS version 8.4 or 8.6 / Debian 11.4` on x86 was used as a development and execution OS. Follow these steps to compile and execute FIDO Device Onboard (FDO). +`Ubuntu* OS version 20.04 or 22.04 / RHEL* OS version [8.4|8.6|8.8] / Debian 11.4` on x86 was used as a development and execution OS. Follow these steps to compile and execute FIDO Device Onboard (FDO). -The FDO Client SDK execution depends on OpenSSL* toolkit 1.1.1t version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. +The FDO Client SDK execution depends on OpenSSL* toolkit 3.0.14 version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. ## 1. Packages Requirements when Building Binaries with TPM* 2.0: -* For Ubuntu* OS version 20.04 or 22.04 / Debian 11.4: +* For Ubuntu* OS version [20.04|22.04] / Debian 11.4: ```shell -sudo apt-get install build-essential python-setuptools clang-format dos2unix ruby build-essential \ - libglib2.0-dev libpcap-dev autoconf libtool libproxy-dev doxygen cmake mercurial +sudo apt-get install build-essential python-setuptools clang-format dos2unix ruby \ + libglib2.0-dev libpcap-dev autoconf libtool libproxy-dev doxygen cmake mercurial nghttp2 libnghttp2-dev ``` -* For RHEL* OS version 8.4 or 8.6: +* For RHEL* OS version [8.4|8.6|8.8]: ```shell sudo subscription-manager repos --enable codeready-builder-for-rhel-8-x86_64-rpms sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm ``` ``` -sudo yum -y install gcc gcc-c++ python3-setuptools git-clang-format dos2unix ruby gcc gcc-c++ make perl glibc-static \ - glib2-devel libpcap-devel autoconf libtool libproxy-devel mozjs52-devel doxygen cmake make mercurial perl +sudo yum -y install gcc gcc-c++ python3-setuptools git-clang-format dos2unix ruby perl glibc-static \ + glib2-devel libpcap-devel autoconf libtool libproxy-devel mozjs52-devel doxygen cmake make mercurial nghttp2 libnghttp2-devel ``` -OpenSSL* toolkit version 1.1.1t. -Curl version 7.88 +OpenSSL* toolkit version 3.0.14. +Curl version 8.8.0 + +#### Steps to Upgrade the OpenSSL* Toolkit to Version 3.0.14 -#### Steps to Upgrade the OpenSSL* Toolkit to Version 1.1.1t +Following steps will replace the existing versions of OpenSSL and Curl from the system. If you want to keep the existing versions then use [Installation-Script](../utils/install_openssl_curl.sh) script to install Openssl and Curl at a different location. +> ***NOTE***: [Installation-Script](../utils/install_openssl_curl.sh) will install OpenSSL and Curl at /opt/ by default. To provide different path, modify these variables in the script +> OPENSSL_ROOT=/opt/openssl +> CURL_ROOT=/opt/curl +> +**Script usage command** + +* Command to install OpenSSL and Curl + ``` + sudo ./install_openssl_curl.sh -i -v 3.0.14 + ``` 1. If libssl-dev, curl and libcurl are installed, uninstall it: - + ``` sudo apt-get remove --auto-remove libssl-dev sudo apt-get remove --auto-remove libssl-dev:i386 sudo apt remove curl libcurl4-openssl-dev ``` In case of RHEL OS, use below commands to uninstall: - + ``` sudo yum remove libcurl-devel openssl-devel ``` 2. Pull the tarball: ``` - wget https://www.openssl.org/source/openssl-1.1.1t.tar.gz + wget https://www.openssl.org/source/openssl-3.0.14.tar.gz ``` 3. Unpack the tarball with: ``` - tar -zxf openssl-1.1.1t.tar.gz && cd openssl-1.1.1t + tar -zxf openssl-3.0.14.tar.gz && cd openssl-3.0.14 ``` 4. Issue the command: ``` - ./config + ./config --libdir=/usr/local/lib ``` 5. Issue the command: ``` @@ -78,6 +87,7 @@ Curl version 7.88 ``` 10. Run the command to update symlinks and rebuild the library cache: ``` + grep -qxF '/usr/local/lib/' /etc/ld.so.conf.d/libc.conf || echo /usr/local/lib/ | sudo tee -a /etc/ld.so.conf.d/libc.conf sudo ldconfig ``` 11. Assuming no errors in executing steps 4 through 10, you should have successfully installed the new version of the OpenSSL* toolkit. @@ -87,24 +97,24 @@ Issue the following command from the terminal: ``` Your output should be as follows: ``` - OpenSSL* 1.1.1t 7 Feb 2023 + OpenSSL* 3.0.14 04 Jun 2024 ``` -#### Steps to install curl version 7.88 configured with openssl +#### Steps to install curl version 8.8.0 configured with openssl After installing openssl, proceed with the installation of curl. 1. Pull the tarball: ``` - wget https://github.com/curl/curl/releases/download/curl-7.88_0/curl-7.88.0.tar.gz + wget https://curl.se/download/curl-8.8.0.tar.gz ``` 2. Unpack the tarball with: ``` - tar -zxf curl-7.88.0.tar.gz && cd curl-7.88.0 + tar -zxf curl-8.8.0.tar.gz && cd curl-8.8.0 ``` -3. Issue the command to configure the curl with openssl: +3. Issue the command to configure the curl with openssl and nghttp2: ``` - ./configure --with-openssl --enable-versioned-symbols + ./configure --with-openssl="OpenSSL Path" --with-nghttp2 --enable-versioned-symbols --without-libpsl ``` 4. Issue the command to build curl: ``` @@ -123,20 +133,16 @@ Issue the following command from the terminal: ``` Your output should point to the openssl version which you installed. ``` - curl 7.88.0 (x86_64-pc-linux-gnu) libcurl/7.88.0 OpenSSL/1.1.1t zlib/1.2.11 + curl 8.8.0 (x86_64-pc-linux-gnu) libcurl/8.8.0 OpenSSL/3.0.14 zlib/1.2.11 ``` -Note 1: If above command is not successful, then link the path where curl is installed to the system path - ``` - sudo ln -s /usr/local/bin/curl /usr/bin/curl - ``` -Note 2: If you are using no_proxy environment variable to exclude proxying for any FDO server IP addresses, it may not work with curl 7.88. Workaround for this is to ensure the no_proxy IP is specified in CIDR notation (https://datatracker.ietf.org/doc/html/rfc1519) +Note 1: If you are using no_proxy environment variable to exclude proxying for any FDO server IP addresses, it may not work with curl 8.8.0. Workaround for this is to ensure the no_proxy IP is specified in CIDR notation (https://datatracker.ietf.org/doc/html/rfc1519) Single IP address example: no_proxy="10.60.132.45/32" Two IP addresses example: no_proxy="10.60.132.45/32,10.60.132.46/32" Range of IP addresses example: no_proxy="10.60.0.0/16" -Note 3: On RHEL, Curl could also be installed using yum package manager as shown below: +Note 2: On RHEL, Curl could also be installed using yum package manager as shown below: ``` sudo yum -y install libcurl-devel ``` @@ -144,15 +150,15 @@ Note 3: On RHEL, Curl could also be installed using yum package manager as shown ## 2. TPM* Library Installation -TPM* enabled FDO Client SDK uses TPM-TSS 3.0.3, TPM2-ABRMD 2.4.0, and TPM2-TOOLS 5.0 libraries for key and cryptography related operations. The TPM-TSS library is required for compiling the code while all 3 libraries are required for running the code. Create an empty directory, download and execute FDO TPM* [TPM-Library-Installation-Script](../utils/install_tpm_libs.sh) which can be used for both installation and uninstallation of TPM* libraries. Alternatively, perform steps listed in section 2.1 to setup TPM* library without using the TPM* [TPM-Library-Installation-Script](../utils/install_tpm_libs.sh). +TPM* enabled FDO Client SDK uses TPM-TSS 4.0.1, TPM2-ABRMD 3.0.0, and TPM2-TOOLS 5.5 libraries for key and cryptography related operations. The TPM-TSS library is required for compiling the code while all 3 libraries are required for running the code. Create an empty directory, download and execute FDO TPM* [TPM-Library-Installation-Script](../utils/install_tpm_libs.sh) which can be used for both installation and uninstallation of TPM* libraries. Alternatively, perform steps listed in section 2.1 to setup TPM* library without using the TPM* [TPM-Library-Installation-Script](../utils/install_tpm_libs.sh). To compile and execute TPM* enabled FDO Client SDK use one of the appropriate commands: **Script usage command** * **On Ubuntu OS version 20.04 or 22.04 / Debian 11.4:** -```shell -sudo ./install_tpm_libs.sh -h -``` + ```shell + sudo ./install_tpm_libs.sh -h + ``` * TPM-TSS library setup to enable TPM* enabled FDO Client SDK code compilation @@ -176,8 +182,13 @@ sudo ./install_tpm_libs.sh -h ``` sudo ./install_tpm_libs.sh -u ``` + > ***NOTE***: [TPM-Library-Installation-Script](../utils/install_tpm_libs.sh) will use OpenSSL and Curl from /opt/ by default. If you have installed OpenSSL and Curl other than `/opt` path, use `openssl version -a` and `which curl` commands to get the exact path of OpenSSL and Curl and modify these variables in the script OPENSSL3_INCLUDE=/opt/openssl/include (can be /usr/include or /usr/local/include) +CURL_INCLUDE=/opt/curl/include (can be /usr/include or /usr/local/include) +OPENSSL3_LIB=/opt/openssl/lib64 (can be /usr/lib or /usr/local/lib or /usr/lib/x86_64-linux-gnu) +CURL_LIB=/opt/curl/lib (can be /usr/lib or /usr/local/lib or /usr/lib/x86_64-linux-gnu) * **On RHEL\* OS version 8.4 or 8.6:** > ***NOTE***: Use [TPM-Library-Installation-Script-RHEL](../utils/install_tpm_libs_rhel.sh) for RHEL 8.4 or 8.6. +> Before executing [TPM-Library-Installation-Script-RHEL](../utils/install_tpm_libs_rhel.sh), make sure OpenSSL v3 and Curl is installed on the system (at /usr/local/ path). Use steps in section 1 to install OpenSSL and Curl on the system. ```shell sudo ./install_tpm_libs_rhel.sh -h ``` @@ -205,63 +216,64 @@ sudo ./install_tpm_libs_rhel.sh -h sudo ./install_tpm_libs_rhel.sh -u ``` + ### 2.1 Building and Installing Libraries for Trusted Platform Module (TPM*) Following steps should be performed if FDO TPM* [TPM-Library-Installation-Script](../utils/install_tpm_libs.sh) script is not used to setup FDO TPM* libraries. Install only tpm2-tss library to enable TPM* enabled FDO Client SDK code compilation. To enable compilation and execution of TPM* enabled FDO Client SDK code, install all libraries namely: tpm2-tss, tpm2-abrmd, tpm2-tools, and tpm2-tss-engine. -- tpm2-tss-3.0.3 +- tpm2-tss-4.0.1 - This is the main library that creates commands per Trusted Computing Group (TCG) specification to use the TPM*. It uses release version 3.0.3 of the library. + This is the main library that creates commands per Trusted Computing Group (TCG) specification to use the TPM*. It uses release version 4.0.1 of the library. - Source Code - The library can be downloaded from [tpm2-tss-3.0.3-download](https://github.com/tpm2-software/tpm2-tss/releases/download/3.0.3/tpm2-tss-3.0.3.tar.gz) + The library can be downloaded from [tpm2-tss-4.0.1-download](https://github.com/tpm2-software/tpm2-tss/releases/download/4.0.1/tpm2-tss-4.0.1.tar.gz) - Build and Installation Process - The build and installation process can be found at [tpm2-tss-3.0.3-install](https://github.com/tpm2-software/tpm2-tss/blob/2.3.x/INSTALL.md) + The build and installation process can be found at [tpm2-tss-4.0.1-install](https://github.com/tpm2-software/tpm2-tss/blob/4.0.1/INSTALL.md) -- tpm2-abrmd-2.4.0 +- tpm2-abrmd-3.0.0 - This is an optional but recommended library (daemon) to use TPM* in the device. This daemon will act as a resource manager for the TPM*, for all I/O calls that happen with the device. It uses release version 2.4.0 of the library. + This is an optional but recommended library (daemon) to use TPM* in the device. This daemon will act as a resource manager for the TPM*, for all I/O calls that happen with the device. It uses release version 3.0.0 of the library. - Source Code - The library can be downloaded from [tpm2-abrmd-2.4.0-download](https://github.com/tpm2-software/tpm2-abrmd/releases/download/2.4.0/tpm2-abrmd-2.4.0.tar.gz) + The library can be downloaded from [tpm2-abrmd-3.0.0-download](https://github.com/tpm2-software/tpm2-abrmd/releases/download/3.0.0/tpm2-abrmd-3.0.0.tar.gz) Alternatively, the in-kernel RM /dev/tpmrm0 can be used. Please see section on Compiling FDO. - Build and Installation Process - The build and installation process found at [tpm2-abrmd-2.4.0-install](https://github.com/tpm2-software/tpm2-abrmd/blob/master/INSTALL.md) + The build and installation process found at [tpm2-abrmd-3.0.0-install](https://github.com/tpm2-software/tpm2-abrmd/blob/master/INSTALL.md) -- tpm2-tools-5.0 +- tpm2-tools-5.5 - This library provides the necessary tools to interact and perform operations using the TPM*, to the users. It uses release version 5.0 of the library. + This library provides the necessary tools to interact and perform operations using the TPM*, to the users. It uses release version 5.5 of the library. - Source Code - The library can be downloaded from [tpm2-tools-5.0-download](https://github.com/tpm2-software/tpm2-tools/releases/download/5.0/tpm2-tools-5.0.tar.gz) + The library can be downloaded from [tpm2-tools-5.5-download](https://github.com/tpm2-software/tpm2-tools/releases/download/5.5/tpm2-tools-5.5.tar.gz) - Build and Installation Process - The build and installation process can be found at [tpm2-tools-5.0-install](https://github.com/tpm2-software/tpm2-tools/blob/4.0.X/INSTALL.md) + The build and installation process can be found at [tpm2-tools-5.5-install](https://github.com/tpm2-software/tpm2-tools/blob/4.0.X/INSTALL.md) -- tpm2-tss-engine-1.1.0 +- tpm2-openssl-1.1.1 - This library provides the OpenSSL* engine, which performs the OpenSSL* cryptography operation using the keys inside the TPM*. It uses release version 1.1.0 of the library. + This library implements a provider that integrates the TPM 2.0 operations to the OpenSSL 3.0 to perform the OpenSSL* cryptography operation using the keys inside the TPM*. It uses release version 1.1.1 of the library. - Source Code - The library can be downloaded from [tpm2-tss-engine-download](https://github.com/tpm2-software/tpm2-tss-engine/archive/v1.1.0.zip) + The library can be downloaded from [tpm2-openssl-download](https://github.com/tpm2-software/tpm2-openssl/releases/download/1.1.1/tpm2-openssl-1.1.1.tar.gz) - Build and Installation Process - The build and installation process can be found at [tpm2-tss-engine-install](https://github.com/tpm2-software/tpm2-tss-engine/blob/v1.1.0/INSTALL.md) + The build and installation process can be found at [tpm2-openssl](https://github.com/tpm2-software/tpm2-openssl/blob/master/docs/INSTALL.md) ## 3. Compiling Intel safestringlib -FDO Client SDK uses safestringlib for string and memory operations to prevent serious security vulnerabilities (For example, buffer overflows). Download safestringlib from intel-safestringlib and follow these instructions to build: +FDO Client SDK uses safestringlib for string and memory operations to prevent serious security vulnerabilities (For example, buffer overflows). Download safestringlib from intel-safestringlib, checkout to the tag `v1.2.0` and follow these instructions to build: From the root of the safestringlib, do the following: ```shell mkdir obj @@ -270,7 +282,7 @@ From the root of the safestringlib, do the following: After this step, `libsafestring.a` library will be created. ## 4. Compiling Intel TinyCBOR -FDO Client SDK uses TinyCBOR library for Concise Binary Object Representation (CBOR) encoding and decoding. Download TinyCBOR from TinyCBOR, checkout to the tag `v0.5.3` and follow these instructions to build: +FDO Client SDK uses TinyCBOR library for Concise Binary Object Representation (CBOR) encoding and decoding. Download TinyCBOR from TinyCBOR, checkout to the tag `v0.6.0` and follow these instructions to build: From the root of the TinyCBOR (named `tinycbor`), do the following: ```shell make @@ -279,8 +291,10 @@ From the root of the TinyCBOR (named `tinycbor`), do the following: ## 5. Environment Variables Add these environment variables to ~/.bashrc or similar (replace with actual paths). -Provide safestringlib and tinycbor path: +Provide OpenSSL, Curl, safestringlib and tinycbor paths: ```shell +export OPENSSL3_ROOT=path/to/openssl (can be /usr or /usr/local or default provide /opt/openssl) +export CURL_ROOT=path/to/curl (can be /usr or /usr/local or default provide /opt/curl) export SAFESTRING_ROOT=path/to/safestringlib export TINYCBOR_ROOT=path/to/tinycbor ``` @@ -289,9 +303,9 @@ export TINYCBOR_ROOT=path/to/tinycbor The FDO Client SDK build system is based on GNU make. It assumes that all the requirements are set up according to [ FDO Compilation Setup ](setup.md). The application is built using the `make [options]` in the root of the repository for all supported platforms. The debug and release build modes are supported in building the FDO Client SDK. -Refer the TPM* Library Setup steps given in section 2 to compile TPM* enabled FDO Client SDK. +Refer the TPM* Library Setup steps given in section 2 to compile TPM* enabled FDO Client SDK. -For an advanced build configuration, refer to [ Advanced Build Configuration ](build_conf.md). +For an advanced build configuration, refer to [ Advanced Build Configuration ](build_conf.md). Example command to build TPM* enabled FDO Client SDK with the Resource Manager as TPM2-ABRMD (tabrmd) @@ -307,18 +321,22 @@ make pristine cmake -DDA=tpm20_ecdsa256 -DTPM2_TCTI_TYPE=tpmrm0 . make -j$(nproc) ``` - +> ***NOTE***: To run with mTLS connection, +> 1. Compile the code with `-DMTLS=true` flag. +> 2. If signing with external CA, copy CA cert and CA key to `data` folder. +> 3. Execute `bash utils/user_csr_req.sh .` +> This will generate client CSR and private key. +> Several other options to choose when building the device are, but not limited to, the following: device-attestation (DA) methods, Advanced Encryption Standard (AES) encryption modes (AES_MODE), and underlying cryptography library to use (TLS). Refer to the section [FDO Build configurations](build_conf.md) -> ***NOTE***: Currently, only Elliptic-Curve (EC) cryptography keys based on `NIST P-256` or `secp256r1` are supported for TPM* enabled FDO Client SDK due to limitations on testing with the available hardware that does not support keys based on `NIST P-384`. Consequently, this configuration only supports usage of 128-bit key for AES operations (GCM/CCM) and generates 256-bit HMAC. ## 7. Running the Application The TPM* enabled FDO Client SDK Linux device is compatible with FDO PRI components - Manufacturer, Reseller, Rendezvous, and Owner. -To test the FDO Client SDK Linux device, setup the [FDO PRI Manufacturer](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md), [FDO PRI Rendezvous](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md) and [FDO PRI Owner](https://github.com/secure-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md). +To test the FDO Client SDK Linux device, setup the [FDO PRI Manufacturer](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/manufacturer/README.md), [FDO PRI Rendezvous](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/rv/README.md) and [FDO PRI Owner](https://github.com/fido-device-onboard/pri-fidoiot/blob/master/component-samples/demo/owner/README.md). Refer the TPM* Library Setup steps given in section 2 to compile and execute TPM* enabled FDO Client SDK. @@ -332,9 +350,13 @@ After a successful compilation, the FDO Client SDK Linux device executable can b Script execution command: ```shell - ./tpm_make_ready_ecdsa.sh -p + sudo ./tpm_make_ready_ecdsa.sh -e -p ``` - +> ***NOTE 1***: [TPM Make Ready](../utils/tpm_make_ready_ecdsa.sh) script will use OpenSSL from `/opt/` by default. To provide a different path, use `which openssl` command to get the exact path of OpenSSL and modify this variable in the script +> OPENSSL3_BIN=/opt/openssl/bin (can be /usr/bin or /usr/local/bin) +> +> ***NOTE 2***: Some platforms do not have the support for ECDSA 384 in TPM. [TPM Make Ready](../utils/tpm_make_ready_ecdsa.sh) script with option "-e 384" will fail in those platforms. Please use ECDSA 256 in that case. +> - Once the TPM* make ready script is executed successfully, the device is now initialized with the credentials and is ready for ownership transfer. To run the device against the FDO PRI Manufacturer for the DI protocol, do the following: ```shell ./build/linux-client @@ -343,47 +365,70 @@ After a successful compilation, the FDO Client SDK Linux device executable can b - To enable the device for Transfer Ownership protocol (TO1 and TO2), configure the FDO PRI Rendezvous and Owner. Refer to [ Ownership Transfer Setup ](ownership_transfer.md). After these are set up, execute `linux-client` again. - + ```shell ./build/linux-client ``` -> ***NOTE***: If the `linux-client` was built with flag TPM2_TCTI_TYPE=tpmrm0, running the it along with tpm_make_ready_ecdsa.sh, may require elevated privileges. Please use 'sudo' to execute. +> ***NOTE***: Usage: +> +> ``` +>./build/linux-client -ip ://: +>if -ip not specified, manufacturer_addr.bin will be used +>-ss: specify if backend servers are using self-signed certificates +>-r: enable resale +>``` + +> ***NOTE***: linux-client may require elevated privileges. Please use 'sudo' to execute. +> ***NOTE***: To do the DI again we need to clear the Device status from TPM storage. +> To clear the TPM storage, execute the clear TPM* script. Refer to [Clear TPM](../utils/clear_tpm_nv.sh). + +```shell +sudo ./utils/clear_tpm_nv.sh +``` + +> ***NOTE***: Enabling LOCK_TPM flag in cmake/cli_input.cmake will lock TPM for further reads/writes. +> This flag is enabled by default. But note that this may require the user to reboot the system before any consecutive execution of linux-client. ### 7.1 Prepare FDO Client SDK Data Folder - Persistent Storage Index in TPM* - Find a persistent storage index that is unused in the TPM* and note it down. It usually starts from 0x81000000. To see the indexes that are already being used, use the following command. FDO uses the 0x81000001 index for the following command examples. - - ```shell - tpm2_getcap handles-persistent - ``` +Find a persistent storage index that is unused in the TPM* and note it down. It usually starts from 0x81000000. To see the indexes that are already being used, use the following command. FDO uses the indexes mentioned in the [TPM spec](https://fidoalliance.org/specs/FDO/securing-fdo-in-tpm-v1.0-rd-20231010/securing-fdo-in-tpm-v1.0-rd-20231010.html#Handles_LABEL) for the following command examples. +```shell +sudo tpm2_getcap handles-persistent +sudo tpm2_getcap handles-nv-index +``` +> ***NOTE***: Please note that the [FIDO Alliance specification "Securing FDO Credentials in the TPM"](https://fidoalliance.org/specs/FDO/securing-fdo-in-tpm-v1.0-rd-20231010/securing-fdo-in-tpm-v1.0-rd-20231010.html) has been published as a Review Draft by the FIDO Alliance, and is still subject to comment and change. With respect to [section 4.2, Handles for FDO Credentials](https://fidoalliance.org/specs/FDO/securing-fdo-in-tpm-v1.0-rd-20231010/securing-fdo-in-tpm-v1.0-rd-20231010.html#Handles_LABEL), Trusted Computing Group (TCG) has allocated the NVRAM addresses referenced, and is moving towards approval of the persistent object handles. - Primary Key Generation from Endorsement Hierarchy - ```shell - tpm2_createprimary -C e -g sha256 -G ecc256:aes128cfb -c data/tpm_primary_key.ctx -V - ``` +```shell +sudo tpm2_createprimary -C e -g sha256 -G ecc256:aes128cfb -c data/tpm_primary_key.ctx -V +sudo tpm2_create -g sha256 -G ecc256 -u data/tpm_ecdsa_pub.key -r data/tpm_ecdsa_priv.key -C data/tpm_primary_key.ctx -a "fixedtpm|sensitivedataorigin|fixedparent|sign|userwithauth" -V +``` -- Load the Primary Key into TPM* Persistent Memory +- Device ECDSA Key-Pair Generation and Load the Primary Key into TPM* Persistent Memory - ```shell - tpm2_evictcontrol -C o 0x81000001 -c data/tpm_primary_key.ctx -V - ``` +```shell +sudo tpm2_load -C data/tpm_primary_key.ctx -u data/tpm_ecdsa_pub.key -r data/tpm_ecdsa_priv.key -c data/tpm_ecdsa_key.ctx -V +sudo tpm2_evictcontrol -C o 0x81020002 -c data/tpm_primary_key.ctx -V +``` -- Device ECDSA Key-Pair Generation +- Generate Device MString - ```shell - tpm2tss-genkey -a ecdsa -c nist_p256 data/tpm_ecdsa_priv_pub_blob.key -v -P 0x81000001 - ``` +```shell +sudo openssl req -new -provider tpm2 -provider default -outform DER -out data/tpm_device_csr -key handle:0x81020002 -subj "/CN=fdo-tpm-device" -verbose +``` -- Generate Device MString +- Define a TPM Non-Volatile (NV) index for TPM Device CSR and Write TPM Device CSR to a Non-Volatile (NV) index - ```shell - export OPENSSL_ENGINES=/usr/local/lib/engines-1.1/; openssl req -new -engine tpm2tss -keyform engine -out data/device_mstring -key data/tpm_ecdsa_priv_pub_blob.key -subj "/CN=www.fdoDevice1.intel.com" -verbose; truncate -s -1 data/device_mstring; echo -n "13" > /tmp/m_string.txt; truncate -s +1 /tmp/m_string.txt; echo -n "intel-1234" >> /tmp/m_string.txt; truncate -s +1 /tmp/m_string.txt; echo -n "model-123456" >> /tmp/m_string.txt; truncate -s +1 /tmp/m_string.txt; cat data/device_mstring >> /tmp/m_string.txt; base64 -w 0 /tmp/m_string.txt > data/device_mstring; rm -f /tmp/m_string.txt - ``` +```shell +csr_size=$(wc -c < data/tpm_device_csr) +sudo tpm2_nvdefine -Q 0x01D10005 -C o -s csr_size -a "ownerwrite|authwrite|ownerread|authread|no_da|read_stclear|writedefine" +sudo tpm2_nvwrite -Q 0x01D10005 -C o -i data/tpm_device_csr +``` ## 8. Troubleshooting Details @@ -393,19 +438,19 @@ Clear TPM* from the BIOS. To run the TPM* enabled FDO Client SDK implementation, - Clear the Used Persistent Index in TPM*.
Use the tpm2_evictcontrol command to delete the content or clear TPM* from the BIOS. To run the TPM* based FDO implementation, the TPM* on the device should not be owned. To reset the TPM*, go to your device BIOS and clear the TPM*. To find the location of the option in the BIOS of your device, refer to your device manual. - Assuming that the index is 0x81000001, run the following command to delete the keys. +To clear the TPM storage, execute the clear TPM* script. Refer to [Clear TPM](../utils/clear_tpm_nv.sh). - ```shell - tpm2_evictcontrol -C o -c 0x81000001 -V - ``` +```shell +sudo ./utils/clear_tpm_nv.sh +``` - OpenSSL* Toolkit Library Linking Related Error While Building FDO Client SDK.
- There is a dependency on the OpenSSL* toolkit version 1.1.1t for building and running the FDO Client SDK. + There is a dependency on the OpenSSL* toolkit version 3.0.14 for building and running the FDO Client SDK. Check the version of the OpenSSL* toolkit installed in your machine with the command - ```shell +```shell openssl version - ``` - If the OpenSSL* toolkit version in your machine is earlier than version 1.1.1t, follow the steps given in section 1 to update the OpenSSL* version to 1.1.1t. +``` + If the OpenSSL* toolkit version in your machine is earlier than version 3.0.14, follow the steps given in section 1 to update the OpenSSL* version to 3.0.14. diff --git a/include/fdo.h b/include/fdo.h index ea8b8eff..9a3416e4 100644 --- a/include/fdo.h +++ b/include/fdo.h @@ -43,6 +43,9 @@ typedef enum { FDO_STATE_ERROR } fdo_sdk_device_state; +extern char *mfg_addr; +extern bool use_mfg_addr_bin; + #if defined(SELF_SIGNED_CERTS_SUPPORTED) extern bool useSelfSignedCerts; #endif diff --git a/include/fdomodules.h b/include/fdomodules.h index 655829cc..b4f6cec1 100644 --- a/include/fdomodules.h +++ b/include/fdomodules.h @@ -17,7 +17,7 @@ #ifdef EXTRA_MODULES #define FDO_MAX_MODULES 4 #else -#define FDO_MAX_MODULES 1 +#define FDO_MAX_MODULES 3 #endif #define FDO_MODULE_MESSAGE_ACTIVE "active" @@ -39,7 +39,12 @@ typedef enum { } fdo_sdk_si_type; // enum for Sv_info module CB return value -enum { FDO_SI_CONTENT_ERROR, FDO_SI_INTERNAL_ERROR, FDO_SI_SUCCESS, FDO_SI_INVALID_MOD_ERROR }; +enum { + FDO_SI_CONTENT_ERROR, + FDO_SI_INTERNAL_ERROR, + FDO_SI_SUCCESS, + FDO_SI_INVALID_MOD_ERROR +}; typedef struct fdo_sdk_si_key_value { char *key; @@ -48,8 +53,11 @@ typedef struct fdo_sdk_si_key_value { // callback to module typedef int (*fdo_sdk_service_infoCB)(fdo_sdk_si_type type, - char *module_message, uint8_t *module_val, size_t *module_val_sz, - uint16_t *num_module_messages, bool *has_more, bool *is_more, size_t mtu); + char *module_message, uint8_t *module_val, + size_t *module_val_sz, + uint16_t *num_module_messages, + bool *has_more, bool *is_more, + size_t mtu); /* module struct for modules */ typedef struct { @@ -58,8 +66,19 @@ typedef struct { fdo_sdk_service_infoCB service_info_callback; } fdo_sdk_service_info_module; -extern int fdo_sys(fdo_sdk_si_type type, - char *module_message, uint8_t *module_val, size_t *module_val_sz, - uint16_t *num_module_messages, bool *has_more, bool *is_more, size_t mtu); +extern int fdo_sys(fdo_sdk_si_type type, char *module_message, + uint8_t *module_val, size_t *module_val_sz, + uint16_t *num_module_messages, bool *has_more, bool *is_more, + size_t mtu); + +extern int fdo_sim_download(fdo_sdk_si_type type, char *module_message, + uint8_t *module_val, size_t *module_val_sz, + uint16_t *num_module_messages, bool *has_more, + bool *is_more, size_t mtu); + +extern int fdo_sim_command(fdo_sdk_si_type type, char *module_message, + uint8_t *module_val, size_t *module_val_sz, + uint16_t *num_module_messages, bool *has_more, + bool *is_more, size_t mtu); #endif /* __FDOTYPES_H__ */ diff --git a/lib/credentials_from_file.c b/lib/credentials_from_file.c index 9030d08e..406c83d7 100644 --- a/lib/credentials_from_file.c +++ b/lib/credentials_from_file.c @@ -16,15 +16,18 @@ #include #include #include "util.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" #if defined(DEVICE_CSE_ENABLED) #include "cse_utils.h" #include "cse_tools.h" #endif +#if defined(DEVICE_TPM20_ENABLED) +#include "tpm2_nv_storage.h" +#endif static bool validate_state(fdo_sdk_device_status current_status); -#if !defined(DEVICE_CSE_ENABLED) +#if !defined(DEVICE_CSE_ENABLED) && !defined(DEVICE_TPM20_ENABLED) /** * Write the Device Credentials blob, contains our state * @param dev_cred_file - pointer of type const char to which credentails are @@ -38,8 +41,8 @@ static bool validate_state(fdo_sdk_device_status current_status); */ bool write_normal_device_credentials(const char *dev_cred_file, - fdo_sdk_blob_flags flags, - fdo_dev_cred_t *ocred) + fdo_sdk_blob_flags flags, + fdo_dev_cred_t *ocred) { bool ret = true; @@ -50,20 +53,17 @@ bool write_normal_device_credentials(const char *dev_cred_file, fdow_t *fdow = fdo_alloc(sizeof(fdow_t)); if (!fdow || !fdow_init(fdow) || - !fdo_block_alloc_with_size(&fdow->b, BUFF_SIZE_4K_BYTES) || - !fdow_encoder_init(fdow)) { + !fdo_block_alloc_with_size(&fdow->b, BUFF_SIZE_4K_BYTES) || + !fdow_encoder_init(fdow)) { LOG(LOG_ERROR, "FDOW Initialization/Allocation failed!\n"); ret = false; goto end; } /** - * Blob format: Complete DeviceCredential as per Section 3.4.1 of FDO Specification, - * except the DeviceCredential.DCHmacSecret, and addition of 'State'. - * DeviceCredential = [ - * State, - * DCActive, - * DCProtVer, + * Blob format: Complete DeviceCredential as per Section 3.4.1 of FDO + *Specification, except the DeviceCredential.DCHmacSecret, and addition + *of 'State'. DeviceCredential = [ State, DCActive, DCProtVer, * DCDeviceInfo, * DCGuid, * DCRVInfo, @@ -88,11 +88,13 @@ bool write_normal_device_credentials(const char *dev_cred_file, goto end; } - if (!fdow_text_string(fdow, ocred->mfg_blk->d->bytes, ocred->mfg_blk->d->byte_sz)) { + if (!fdow_text_string(fdow, ocred->mfg_blk->d->bytes, + ocred->mfg_blk->d->byte_sz)) { ret = false; goto end; } - if (!fdow_byte_string(fdow, ocred->owner_blk->guid->bytes, ocred->owner_blk->guid->byte_sz)) { + if (!fdow_byte_string(fdow, ocred->owner_blk->guid->bytes, + ocred->owner_blk->guid->byte_sz)) { ret = false; goto end; } @@ -109,15 +111,17 @@ bool write_normal_device_credentials(const char *dev_cred_file, goto end; } size_t encoded_cred_length = 0; - if (!fdow_encoded_length(fdow, &encoded_cred_length) || encoded_cred_length == 0) { - LOG(LOG_ERROR, "Failed to get DeviceCredential encoded length\n"); + if (!fdow_encoded_length(fdow, &encoded_cred_length) || + encoded_cred_length == 0) { + LOG(LOG_ERROR, + "Failed to get DeviceCredential encoded length\n"); ret = false; goto end; } fdow->b.block_size = encoded_cred_length; if (fdo_blob_write((char *)dev_cred_file, flags, fdow->b.block, - fdow->b.block_size) == -1) { + fdow->b.block_size) == -1) { LOG(LOG_ERROR, "Failed to write DeviceCredential blob\n"); ret = false; goto end; @@ -143,10 +147,11 @@ bool write_normal_device_credentials(const char *dev_cred_file, */ bool write_secure_device_credentials(const char *dev_cred_file, - fdo_sdk_blob_flags flags, fdo_dev_cred_t *ocred) + fdo_sdk_blob_flags flags, + fdo_dev_cred_t *ocred) { bool ret = true; - (void) *ocred; + (void)*ocred; if (!dev_cred_file) { return false; @@ -156,13 +161,13 @@ bool write_secure_device_credentials(const char *dev_cred_file, fdow_t *fdow = fdo_alloc(sizeof(fdow_t)); if (!fdow || !fdow_init(fdow) || - !fdo_block_alloc_with_size(&fdow->b, BUFF_SIZE_128_BYTES) || - !fdow_encoder_init(fdow)) { + !fdo_block_alloc_with_size(&fdow->b, BUFF_SIZE_128_BYTES) || + !fdow_encoder_init(fdow)) { LOG(LOG_ERROR, "FDOW Initialization/Allocation failed!\n"); ret = false; goto end; } - fdo_byte_array_t **ovkey = getOVKey(); + fdo_byte_array_t **ovkey = get_OV_key(); if (!ovkey || !*ovkey) { ret = false; goto end; @@ -170,18 +175,25 @@ bool write_secure_device_credentials(const char *dev_cred_file, /** * Blob format: DeviceCredential.DCHmacSecret as bstr. */ - fdow_byte_string(fdow, (*ovkey)->bytes, (*ovkey)->byte_sz); + if (!fdow_byte_string(fdow, (*ovkey)->bytes, (*ovkey)->byte_sz)) { + ret = false; + goto end; + } + size_t encoded_secret_length = 0; - if (!fdow_encoded_length(fdow, &encoded_secret_length) || encoded_secret_length == 0) { - LOG(LOG_ERROR, "Failed to get encoded DeviceCredential.DCHmacSecret length\n"); + if (!fdow_encoded_length(fdow, &encoded_secret_length) || + encoded_secret_length == 0) { + LOG(LOG_ERROR, "Failed to get encoded " + "DeviceCredential.DCHmacSecret length\n"); ret = false; goto end; } fdow->b.block_size = encoded_secret_length; if (fdo_blob_write((char *)dev_cred_file, flags, fdow->b.block, - fdow->b.block_size) == -1) { - LOG(LOG_ERROR, "Failed to write DeviceCredential.DCHmacSecret blob\n"); + fdow->b.block_size) == -1) { + LOG(LOG_ERROR, + "Failed to write DeviceCredential.DCHmacSecret blob\n"); ret = false; goto end; } @@ -202,8 +214,8 @@ bool write_secure_device_credentials(const char *dev_cred_file, * @return true if read and parsed correctly, otherwise false. */ bool read_normal_device_credentials(const char *dev_cred_file, - fdo_sdk_blob_flags flags, - fdo_dev_cred_t *our_dev_cred) + fdo_sdk_blob_flags flags, + fdo_dev_cred_t *our_dev_cred) { bool ret = false; size_t dev_cred_len = 0; @@ -231,22 +243,26 @@ bool read_normal_device_credentials(const char *dev_cred_file, // Device has not yet been initialized. // Since, Normal.blob is empty, the file size will be 0 if (dev_cred_len == 0) { - LOG(LOG_DEBUG, "DeviceCredential not found. Proceeding with DI\n"); + LOG(LOG_DEBUG, + "DeviceCredential not found. Proceeding with DI\n"); our_dev_cred->ST = FDO_DEVICE_STATE_PC; return true; } - LOG(LOG_DEBUG, "Reading DeviceCredential blob of length %"PRIu64"\n", dev_cred_len); + LOG(LOG_DEBUG, "Reading DeviceCredential blob of length %" PRIu64 "\n", + dev_cred_len); fdor = fdo_alloc(sizeof(fdor_t)); - if (!fdor || !fdor_init(fdor) || !fdo_block_alloc_with_size(&fdor->b, dev_cred_len)) { + if (!fdor || !fdor_init(fdor) || + !fdo_block_alloc_with_size(&fdor->b, dev_cred_len)) { LOG(LOG_ERROR, "FDOR Initialization/Allocation failed!\n"); goto end; } if (fdo_blob_read((char *)dev_cred_file, flags, fdor->b.block, - fdor->b.block_size) == -1) { - LOG(LOG_ERROR, "Failed to read DeviceCredential blob : Normal.blob\n"); + fdor->b.block_size) == -1) { + LOG(LOG_ERROR, + "Failed to read DeviceCredential blob : Normal.blob\n"); goto end; } @@ -256,7 +272,8 @@ bool read_normal_device_credentials(const char *dev_cred_file, } if (!fdor_start_array(fdor)) { - LOG(LOG_ERROR, "DeviceCredential read: Begin Array not found\n"); + LOG(LOG_ERROR, + "DeviceCredential read: Begin Array not found\n"); goto end; } @@ -282,51 +299,57 @@ bool read_normal_device_credentials(const char *dev_cred_file, } size_t device_info_length = 0; - if (!fdor_string_length(fdor, &device_info_length) || device_info_length == 0) { - LOG(LOG_ERROR, "DeviceCredential read: Invalid DCDeviceInfo length\n"); + if (!fdor_string_length(fdor, &device_info_length) || + device_info_length == 0) { + LOG(LOG_ERROR, + "DeviceCredential read: Invalid DCDeviceInfo length\n"); goto end; } our_dev_cred->mfg_blk = fdo_cred_mfg_alloc(); if (!our_dev_cred->mfg_blk) { - LOG(LOG_ERROR, "DeviceCredential read: Malloc for DCDeviceInfo failed"); + LOG(LOG_ERROR, + "DeviceCredential read: Malloc for DCDeviceInfo failed"); goto end; } our_dev_cred->mfg_blk->d = fdo_string_alloc_size(device_info_length); if (!our_dev_cred->mfg_blk->d || - !fdor_text_string(fdor, our_dev_cred->mfg_blk->d->bytes, - our_dev_cred->mfg_blk->d->byte_sz)) { - LOG(LOG_ERROR, "DeviceCredential read: DCDeviceInfo not found\n"); + !fdor_text_string(fdor, our_dev_cred->mfg_blk->d->bytes, + our_dev_cred->mfg_blk->d->byte_sz)) { + LOG(LOG_ERROR, + "DeviceCredential read: DCDeviceInfo not found\n"); goto end; } our_dev_cred->mfg_blk->d->bytes[device_info_length] = '\0'; size_t guid_length = 0; if (!fdor_string_length(fdor, &guid_length) || guid_length == 0) { - LOG(LOG_ERROR, "DeviceCredential read: Invalid DCGuid length\n"); + LOG(LOG_ERROR, + "DeviceCredential read: Invalid DCGuid length\n"); goto end; } our_dev_cred->owner_blk->guid = fdo_byte_array_alloc(guid_length); if (!our_dev_cred->owner_blk->guid || - !fdor_byte_string(fdor, our_dev_cred->owner_blk->guid->bytes, - our_dev_cred->owner_blk->guid->byte_sz)) { + !fdor_byte_string(fdor, our_dev_cred->owner_blk->guid->bytes, + our_dev_cred->owner_blk->guid->byte_sz)) { LOG(LOG_ERROR, "DeviceCredential read: DCGuid not found\n"); goto end; } our_dev_cred->owner_blk->rvlst = fdo_rendezvous_list_alloc(); if (!our_dev_cred->owner_blk->rvlst || - !fdo_rendezvous_list_read(fdor, our_dev_cred->owner_blk->rvlst)) { + !fdo_rendezvous_list_read(fdor, our_dev_cred->owner_blk->rvlst)) { LOG(LOG_ERROR, "DeviceCredential read: DCRVInfo not found\n"); goto end; } our_dev_cred->owner_blk->pkh = - fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); + fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); if (!our_dev_cred->owner_blk->pkh || - !fdo_hash_read(fdor, our_dev_cred->owner_blk->pkh)) { - LOG(LOG_ERROR, "DeviceCredential read: DCPubKeyHash not found\n"); + !fdo_hash_read(fdor, our_dev_cred->owner_blk->pkh)) { + LOG(LOG_ERROR, + "DeviceCredential read: DCPubKeyHash not found\n"); goto end; } @@ -351,8 +374,8 @@ bool read_normal_device_credentials(const char *dev_cred_file, * @return true if read and parsed correctly, otherwise false. */ bool read_secure_device_credentials(const char *dev_cred_file, - fdo_sdk_blob_flags flags, - fdo_dev_cred_t *our_dev_cred) + fdo_sdk_blob_flags flags, + fdo_dev_cred_t *our_dev_cred) { bool ret = false; size_t dev_cred_len = 0; @@ -367,19 +390,22 @@ bool read_secure_device_credentials(const char *dev_cred_file, dev_cred_len = fdo_blob_size((char *)dev_cred_file, flags); if (dev_cred_len == 0) { - LOG(LOG_DEBUG, "DeviceCredential.DCHmacSecret not found. Proceeding with DI\n"); + LOG(LOG_DEBUG, "DeviceCredential.DCHmacSecret not found. " + "Proceeding with DI\n"); return true; } fdor_t *fdor = fdo_alloc(sizeof(fdor_t)); - if (!fdor || !fdor_init(fdor) || !fdo_block_alloc_with_size(&fdor->b, dev_cred_len)) { + if (!fdor || !fdor_init(fdor) || + !fdo_block_alloc_with_size(&fdor->b, dev_cred_len)) { LOG(LOG_ERROR, "FDOR Initialization/Allocation failed!\n"); goto end; } if (fdo_blob_read((char *)dev_cred_file, flags, fdor->b.block, - fdor->b.block_size) == -1) { - LOG(LOG_ERROR, "Failed to read DeviceCredential blob: Secure.blob\n"); + fdor->b.block_size) == -1) { + LOG(LOG_ERROR, + "Failed to read DeviceCredential blob: Secure.blob\n"); goto end; } @@ -395,7 +421,8 @@ bool read_secure_device_credentials(const char *dev_cred_file, } if (!fdor_byte_string(fdor, secret->bytes, secret->byte_sz)) { - LOG(LOG_ERROR, "DeviceCredential read: DCHmacSecret not found\n"); + LOG(LOG_ERROR, + "DeviceCredential read: DCHmacSecret not found\n"); goto end; } @@ -425,28 +452,325 @@ int store_credential(fdo_dev_cred_t *ocred) /* Write in the file and save the Normal device credentials */ LOG(LOG_DEBUG, "Writing to %s blob\n", "Normal.blob"); if (!write_normal_device_credentials((char *)FDO_CRED_NORMAL, - FDO_SDK_NORMAL_DATA, ocred)) { + FDO_SDK_NORMAL_DATA, ocred)) { LOG(LOG_ERROR, "Could not write to Normal Credentials blob\n"); return -1; } -#if !defined(DEVICE_TPM20_ENABLED) /* Write in the file and save the Secure device credentials */ LOG(LOG_DEBUG, "Writing to %s blob\n", "Secure.blob"); if (!write_secure_device_credentials((char *)FDO_CRED_SECURE, - FDO_SDK_SECURE_DATA, ocred)) { + FDO_SDK_SECURE_DATA, ocred)) { LOG(LOG_ERROR, "Could not write to Secure Credentials blob\n"); return -1; } + + return 0; +} #endif +#if defined(DEVICE_TPM20_ENABLED) +/** + * Write the Device Credentials to nv, contains our state + * @param nv - tpm nv index to be written. + * @param ocred - pointer of type fdo_dev_cred_t, holds the credentials for + * writing to dev_cred_file. + * @return true if write and parsed correctly, otherwise false + */ + +bool write_tpm_device_credentials(uint32_t nv, fdo_dev_cred_t *ocred) +{ + bool ret = true; + + if (!ocred || !nv) { + return false; + } +#ifndef NO_PERSISTENT_STORAGE + + fdow_t *fdow = fdo_alloc(sizeof(fdow_t)); + if (!fdow || !fdow_init(fdow) || + !fdo_block_alloc_with_size(&fdow->b, BUFF_SIZE_4K_BYTES) || + !fdow_encoder_init(fdow)) { + LOG(LOG_ERROR, "FDOW Initialization/Allocation failed!\n"); + ret = false; + goto end; + } + + /** + * Format: Complete DeviceCredential as per Section 3.4.1 of FDO + *Specification, except the DeviceCredential.DCHmacSecret, and addition + *of 'State'. DeviceCredential = [ State, DCProtVer, + * DCDeviceInfo, + * DCGuid, + * DCRVInfo, + * DCPubKeyHash + * ] + */ + fdow_next_block(fdow, FDO_DI_SET_CREDENTIALS); + if (!fdow_start_array(fdow, 6)) { + ret = false; + goto end; + } + if (!fdow_signed_int(fdow, ocred->ST)) { + ret = false; + goto end; + } + + if (!fdow_signed_int(fdow, ocred->owner_blk->pv)) { + ret = false; + goto end; + } + + if (!fdow_text_string(fdow, ocred->mfg_blk->d->bytes, + ocred->mfg_blk->d->byte_sz)) { + ret = false; + goto end; + } + if (!fdow_byte_string(fdow, ocred->owner_blk->guid->bytes, + ocred->owner_blk->guid->byte_sz)) { + ret = false; + goto end; + } + if (!fdo_rendezvous_list_write(fdow, ocred->owner_blk->rvlst)) { + ret = false; + goto end; + } + if (!fdo_hash_write(fdow, ocred->owner_blk->pkh)) { + ret = false; + goto end; + } + if (!fdow_end_array(fdow)) { + ret = false; + goto end; + } + size_t encoded_cred_length = 0; + if (!fdow_encoded_length(fdow, &encoded_cred_length) || + encoded_cred_length == 0) { + LOG(LOG_ERROR, + "Failed to get DeviceCredential encoded length\n"); + ret = false; + goto end; + } + fdow->b.block_size = encoded_cred_length; + + if (fdo_tpm_write_nv(nv, fdow->b.block, fdow->b.block_size) == -1) { + LOG(LOG_ERROR, "Failed to write DeviceCredential in TPM\n"); + ret = false; + goto end; + } + +end: + if (fdow) { + fdow_flush(fdow); + fdo_free(fdow); + } +#endif + return ret; +} + +/** + * Read the Device Credentials from tpm nv, contains our state & owner_blk + * @param nv - tpm nv index to be read. + * @param our_dev_cred - pointer to the device credentials block, + * @return true if read and parsed correctly, otherwise false. + */ +bool read_tpm_device_credentials(uint32_t nv, fdo_dev_cred_t *our_dev_cred) +{ + bool ret = false; + size_t dev_cred_len = 0; + fdor_t *fdor = NULL; + int dev_state = -1; + + if (!nv || !our_dev_cred) { + LOG(LOG_ERROR, "Invalid params\n"); + return false; + } + + if (our_dev_cred->owner_blk != NULL) { + fdo_cred_owner_free(our_dev_cred->owner_blk); + our_dev_cred->owner_blk = NULL; + } + + /* Memory allocating data.inside dev_cred. */ + our_dev_cred->owner_blk = fdo_cred_owner_alloc(); + if (!our_dev_cred->owner_blk) { + LOG(LOG_ERROR, "dev_cred's owner_blk allocation failed\n"); + goto end; + } + + dev_cred_len = fdo_tpm_size_nv(nv); + // Device has not yet been initialized. + if (dev_cred_len == 0) { + LOG(LOG_DEBUG, + "DeviceCredential not found. Proceeding with DI\n"); + our_dev_cred->ST = FDO_DEVICE_STATE_PC; + return true; + } + + LOG(LOG_DEBUG, "Reading DeviceCredential of length %" PRIu64 "\n", + dev_cred_len); + + fdor = fdo_alloc(sizeof(fdor_t)); + if (!fdor || !fdor_init(fdor) || + !fdo_block_alloc_with_size(&fdor->b, dev_cred_len)) { + LOG(LOG_ERROR, "FDOR Initialization/Allocation failed!\n"); + goto end; + } + + if (fdo_tpm_read_nv(nv, fdor->b.block, fdor->b.block_size) == -1) { + LOG(LOG_ERROR, "Failed to read TPM DeviceCredential\n"); + goto end; + } + + if (!fdor_parser_init(fdor)) { + LOG(LOG_ERROR, "FDOR Parser Initialization failed!\n"); + goto end; + } + + if (!fdor_start_array(fdor)) { + LOG(LOG_ERROR, + "DeviceCredential read: Begin Array not found\n"); + goto end; + } + + if (!fdor_signed_int(fdor, &dev_state)) { + LOG(LOG_ERROR, "DeviceCredential read: ST not found\n"); + goto end; + } + our_dev_cred->ST = dev_state; + + if (!validate_state(our_dev_cred->ST)) { + LOG(LOG_ERROR, "DeviceCredential read: Invalid ST\n"); + goto end; + } + + if (!fdor_signed_int(fdor, &our_dev_cred->owner_blk->pv)) { + LOG(LOG_ERROR, "DeviceCredential read: DCProtVer not found\n"); + goto end; + } + + size_t device_info_length = 0; + if (!fdor_string_length(fdor, &device_info_length) || + device_info_length == 0) { + LOG(LOG_ERROR, + "DeviceCredential read: Invalid DCDeviceInfo length\n"); + goto end; + } + + our_dev_cred->mfg_blk = fdo_cred_mfg_alloc(); + if (!our_dev_cred->mfg_blk) { + LOG(LOG_ERROR, + "DeviceCredential read: Malloc for DCDeviceInfo failed"); + goto end; + } + + our_dev_cred->mfg_blk->d = fdo_string_alloc_size(device_info_length); + if (!our_dev_cred->mfg_blk->d || + !fdor_text_string(fdor, our_dev_cred->mfg_blk->d->bytes, + our_dev_cred->mfg_blk->d->byte_sz)) { + LOG(LOG_ERROR, + "DeviceCredential read: DCDeviceInfo not found\n"); + goto end; + } + our_dev_cred->mfg_blk->d->bytes[device_info_length] = '\0'; + + size_t guid_length = 0; + if (!fdor_string_length(fdor, &guid_length) || guid_length == 0) { + LOG(LOG_ERROR, + "DeviceCredential read: Invalid DCGuid length\n"); + goto end; + } + our_dev_cred->owner_blk->guid = fdo_byte_array_alloc(guid_length); + if (!our_dev_cred->owner_blk->guid || + !fdor_byte_string(fdor, our_dev_cred->owner_blk->guid->bytes, + our_dev_cred->owner_blk->guid->byte_sz)) { + LOG(LOG_ERROR, "DeviceCredential read: DCGuid not found\n"); + goto end; + } + + our_dev_cred->owner_blk->rvlst = fdo_rendezvous_list_alloc(); + if (!our_dev_cred->owner_blk->rvlst || + !fdo_rendezvous_list_read(fdor, our_dev_cred->owner_blk->rvlst)) { + LOG(LOG_ERROR, "DeviceCredential read: DCRVInfo not found\n"); + goto end; + } + + our_dev_cred->owner_blk->pkh = + fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); + if (!our_dev_cred->owner_blk->pkh || + !fdo_hash_read(fdor, our_dev_cred->owner_blk->pkh)) { + LOG(LOG_ERROR, + "DeviceCredential read: DCPubKeyHash not found\n"); + goto end; + } + + if (!fdor_end_array(fdor)) { + LOG(LOG_ERROR, "DeviceCredential read: End Array not found\n"); + goto end; + } + ret = true; +end: + if (fdor) { + fdor_flush(fdor); + fdo_free(fdor); + } + return ret; +} + +/** + * Write and save the device credentials passed as an parameter ocred of type + * fdo_dev_cred_t. + * @param ocred - Pointer of type fdo_dev_cred_t, credentials to be copied + * @return 0 if success, else -1 on failure. + */ +int store_tpm_credential(fdo_dev_cred_t *ocred) +{ + /* Write in the file and save the Normal device credentials */ + LOG(LOG_DEBUG, "Writing to TPM NV storage\n"); + + uint8_t *dc_active = NULL; + size_t dc_active_len = sizeof(uint8_t); + dc_active = fdo_alloc(dc_active_len); + if (NULL == dc_active) { + LOG(LOG_ERROR, "Malloc Failed in %s!\n", __func__); + return -1; + } + + *dc_active = ocred->dc_active; + + if (fdo_tpm_nvwrite(dc_active, dc_active_len, FDO_DCActive_NV_IDX)) { + LOG(LOG_ERROR, "Failed to write DeviceCredential Active\n"); + fdo_free(dc_active); + return -1; + } + + if (dc_active) { + fdo_free(dc_active); + } + + if (!write_tpm_device_credentials(FDO_CRED_NV_IDX, ocred)) { + LOG(LOG_ERROR, "Could not write to Normal Credentials\n"); + return -1; + } +#if defined(LOCK_TPM) + if (fdo_tpm_nvwrite_lock(FDO_CRED_NV_IDX)) { + LOG(LOG_ERROR, "Failed to lock file!\n"); + return -1; + } + + if (fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)) { + LOG(LOG_ERROR, "Failed to lock file!\n"); + return -1; + } +#endif return 0; } #endif #if defined(DEVICE_CSE_ENABLED) /** - * Populates the dev_cred structure by loading the OVH and DS file data from CSE flash. + * Populates the dev_cred structure by loading the OVH and DS file data from CSE + * flash. * @param our_dev_cred - pointer to the device credentials block, * @return true if read and parsed correctly, otherwise false. */ @@ -456,7 +780,7 @@ bool read_cse_device_credentials(fdo_dev_cred_t *our_dev_cred) uint32_t dev_cred_len = 0; uint32_t dev_state_len = 0; uint8_t dev_state[1] = {-1}; - uint8_t *ds_ptr = (uint8_t*)&dev_state; + uint8_t *ds_ptr = (uint8_t *)&dev_state; fdo_ownership_voucher_t *ov = NULL; fdo_byte_array_t *ovheader = NULL; fdo_byte_array_t *hmac_ptr = NULL; @@ -491,36 +815,42 @@ bool read_cse_device_credentials(fdo_dev_cred_t *our_dev_cred) ovheader = fdo_byte_array_alloc(FDO_MAX_FILE_SIZE); if (!ovheader) { - LOG(LOG_ERROR,"DeviceCredential read: Failed to allocate data for storing OVH data\n"); + LOG(LOG_ERROR, "DeviceCredential read: Failed to allocate data " + "for storing OVH data\n"); goto end; } hmac_ptr = fdo_byte_array_alloc(FDO_HMAC_384_SIZE); if (!hmac_ptr) { - LOG(LOG_ERROR, "DeviceCredential read: Failed to allocate data for storing HMAC data \n"); + LOG(LOG_ERROR, "DeviceCredential read: Failed to allocate data " + "for storing HMAC data \n"); goto end; } if (0 != cse_load_file(OVH_FILE_ID, ovheader->bytes, &dev_cred_len, - hmac_ptr->bytes, hmac_ptr->byte_sz)) { - LOG(LOG_ERROR, "DeviceCredential read: Unable to load file form CSE\n"); + hmac_ptr->bytes, hmac_ptr->byte_sz)) { + LOG(LOG_ERROR, + "DeviceCredential read: Unable to load file form CSE\n"); goto end; } // Device has not yet been initialized. if (dev_cred_len == 0) { - LOG(LOG_DEBUG, "DeviceCredential not found. Proceeding with DI\n"); + LOG(LOG_DEBUG, + "DeviceCredential not found. Proceeding with DI\n"); our_dev_cred->ST = FDO_DEVICE_STATE_PC; ret = true; goto end; } - LOG(LOG_DEBUG, "Reading DeviceCredential blob of length %u\n", dev_cred_len); + LOG(LOG_DEBUG, "Reading DeviceCredential blob of length %u\n", + dev_cred_len); ovheader->byte_sz = dev_cred_len; ov = fdo_ov_hdr_read(ovheader); if (!ov) { - LOG(LOG_ERROR, "DeviceCredential read: Failed to read OVHeader\n"); + LOG(LOG_ERROR, + "DeviceCredential read: Failed to read OVHeader\n"); goto end; } @@ -531,7 +861,8 @@ bool read_cse_device_credentials(fdo_dev_cred_t *our_dev_cred) } if (0 != cse_load_file(DS_FILE_ID, ds_ptr, &dev_state_len, NULL, 0)) { - LOG(LOG_ERROR, "DeviceCredential read: Unable to load file form CSE\n"); + LOG(LOG_ERROR, + "DeviceCredential read: Unable to load file form CSE\n"); goto end; } @@ -542,7 +873,8 @@ bool read_cse_device_credentials(fdo_dev_cred_t *our_dev_cred) our_dev_cred->owner_blk->guid = ov->g2; our_dev_cred->mfg_blk->d = ov->dev_info; our_dev_cred->owner_blk->pk = ov->mfg_pub_key; - our_dev_cred->owner_blk->pkh = fdo_pub_key_hash(our_dev_cred->owner_blk->pk); + our_dev_cred->owner_blk->pkh = + fdo_pub_key_hash(our_dev_cred->owner_blk->pk); if (ov->hdc) { fdo_hash_free(ov->hdc); @@ -575,8 +907,8 @@ bool read_cse_device_credentials(fdo_dev_cred_t *our_dev_cred) #endif /** - * load_credentials function loads the State, Owner and Manufacturer credentials from - * storage + * load_credentials function loads the State, Owner and Manufacturer credentials + * from storage * * @return * return 0 on success. -1 on failure. @@ -590,13 +922,50 @@ int load_credential(fdo_dev_cred_t *ocred) #if defined(DEVICE_CSE_ENABLED) /* Read the device credentials from CSE*/ if (!read_cse_device_credentials(ocred)) { - LOG(LOG_ERROR, "Could not parse the Device Credentials form CSE\n"); + LOG(LOG_ERROR, + "Could not parse the Device Credentials form CSE\n"); + return -1; + } +#elif defined(DEVICE_TPM20_ENABLED) + /* Read and save the device credentials */ + uint8_t *dc_active = NULL; + size_t dc_active_len = fdo_tpm_nvread_size(FDO_DCActive_NV_IDX); + if (dc_active_len == 0) { + LOG(LOG_ERROR, "DeviceCredential Active not found.\n"); + return -1; + } + + dc_active = fdo_alloc(dc_active_len); + if (NULL == dc_active) { + LOG(LOG_ERROR, "Malloc Failed in %s!\n", __func__); return -1; } + + if (fdo_tpm_nvread(FDO_DCActive_NV_IDX, dc_active_len, &dc_active)) { + LOG(LOG_ERROR, "Failed to read file!\n"); + fdo_free(dc_active); + return -1; + } + + if (*dc_active == 1) { + ocred->dc_active = true; + if (!read_tpm_device_credentials(FDO_CRED_NV_IDX, ocred)) { + LOG(LOG_ERROR, + "Could not read the Device Credentials from TPM\n"); + fdo_free(dc_active); + return -1; + } + } else { + ocred->dc_active = false; + } + + if (dc_active) { + fdo_free(dc_active); + } #else /* Read in the blob and save the device credentials */ if (!read_normal_device_credentials((char *)FDO_CRED_NORMAL, - FDO_SDK_NORMAL_DATA, ocred)) { + FDO_SDK_NORMAL_DATA, ocred)) { LOG(LOG_ERROR, "Could not parse the Device Credentials blob\n"); return -1; } @@ -618,7 +987,7 @@ int load_device_secret(void) #if !defined(DEVICE_TPM20_ENABLED) // ReadHMAC Credentials if (!read_secure_device_credentials((char *)FDO_CRED_SECURE, - FDO_SDK_SECURE_DATA, NULL)) { + FDO_SDK_SECURE_DATA, NULL)) { LOG(LOG_ERROR, "Could not parse the Device Credentials blob\n"); return -1; } @@ -633,7 +1002,8 @@ int load_device_secret(void) * @return * return true on success. false on failure. */ -bool load_device_status(fdo_sdk_device_status *state) { +bool load_device_status(fdo_sdk_device_status *state) +{ if (!state) { return false; @@ -642,22 +1012,28 @@ bool load_device_status(fdo_sdk_device_status *state) { #if defined(DEVICE_CSE_ENABLED) uint32_t dev_cred_len; uint8_t dev_state[1] = {-1}; - uint8_t *ds_ptr = (uint8_t*)&dev_state; + uint8_t *ds_ptr = (uint8_t *)&dev_state; if (0 != cse_load_file(DS_FILE_ID, ds_ptr, &dev_cred_len, NULL, 0)) { - LOG(LOG_ERROR, "DeviceCredential read: Unable to load file form CSE\n"); + LOG(LOG_ERROR, + "DeviceCredential read: Unable to load file form CSE\n"); return false; } +#elif defined(DEVICE_TPM20_ENABLED) + size_t dev_cred_len = fdo_tpm_size_nv(FDO_CRED_NV_IDX); #else - size_t dev_cred_len = fdo_blob_size((char *)FDO_CRED_NORMAL, FDO_SDK_NORMAL_DATA); + size_t dev_cred_len = + fdo_blob_size((char *)FDO_CRED_NORMAL, FDO_SDK_NORMAL_DATA); #endif // Device has not yet been initialized. // Since, Normal.blob is empty, the file size will be 0 if (dev_cred_len == 0) { - LOG(LOG_DEBUG, "DeviceCredential is empty. Set state to run DI\n"); + LOG(LOG_DEBUG, + "DeviceCredential is empty. Set state to run DI\n"); *state = FDO_DEVICE_STATE_PC; } else { - LOG(LOG_DEBUG, "DeviceCredential is non-empty. Set state to run TO1/TO2\n"); + LOG(LOG_DEBUG, "DeviceCredential is non-empty. Set state to " + "run TO1/TO2\n"); // No Device state is being set currently } return true; @@ -667,34 +1043,38 @@ bool load_device_status(fdo_sdk_device_status *state) { * Store the Device status given by the variable 'state'. * @return return true on success. false on failure. */ -bool store_device_status(fdo_sdk_device_status *state) { +bool store_device_status(fdo_sdk_device_status *state) +{ #if defined(DEVICE_CSE_ENABLED) FDO_STATUS fdo_status; - if (TEE_SUCCESS != fdo_heci_load_file(&fdo_cse_handle, DS_FILE_ID, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + if (TEE_SUCCESS != + fdo_heci_load_file(&fdo_cse_handle, DS_FILE_ID, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI LOAD DS failed!! %u\n", fdo_status); return false; } LOG(LOG_DEBUG, "FDO HECI LOAD DS succeeded %u\n", fdo_status); if (TEE_SUCCESS != fdo_heci_update_file(&fdo_cse_handle, DS_FILE_ID, - (uint8_t *)state, 1, NULL, 0, &fdo_status) || FDO_STATUS_SUCCESS != - fdo_status) { + (uint8_t *)state, 1, NULL, 0, + &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO HECI UPDATE DS failed!! %u\n", fdo_status); return false; } LOG(LOG_DEBUG, "FDO HECI UPDATE DS succeeded %u\n", fdo_status); if (TEE_SUCCESS != fdo_heci_commit_file(&fdo_cse_handle, DS_FILE_ID, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO DS COMMIT failed!! %u\n", fdo_status); return false; } LOG(LOG_DEBUG, "FDO DS COMMIT succeeded %u\n", fdo_status); #else - /** NOTE: Currently, it does nothing. This is a provision to store status separately - * and is unused in this specific implementation. + /** NOTE: Currently, it does nothing. This is a provision to store + * status separately and is unused in this specific implementation. */ (void)state; #endif @@ -704,13 +1084,14 @@ bool store_device_status(fdo_sdk_device_status *state) { /** * Validate the current status of the device. */ -static bool validate_state(fdo_sdk_device_status current_status) { +static bool validate_state(fdo_sdk_device_status current_status) +{ if (current_status == FDO_DEVICE_STATE_READY1 || - current_status == FDO_DEVICE_STATE_D1 || - current_status == FDO_DEVICE_STATE_IDLE || - current_status == FDO_DEVICE_STATE_READYN || - current_status == FDO_DEVICE_STATE_DN) { + current_status == FDO_DEVICE_STATE_D1 || + current_status == FDO_DEVICE_STATE_IDLE || + current_status == FDO_DEVICE_STATE_READYN || + current_status == FDO_DEVICE_STATE_DN) { return true; } return false; diff --git a/lib/crypto_utils.c b/lib/crypto_utils.c index 8758060a..b7a14cd7 100644 --- a/lib/crypto_utils.c +++ b/lib/crypto_utils.c @@ -13,7 +13,7 @@ #include #include "safe_lib.h" #include "snprintf_s.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" /** * Encrypt the characters in the clear_txt buffer, place the result @@ -33,9 +33,11 @@ * return 0 on success. -1 on failure. */ int aes_encrypt_packet(fdo_encrypted_packet_t *cipher_txt, uint8_t *clear_txt, - size_t clear_txt_size, const uint8_t *aad, size_t aad_length) + size_t clear_txt_size, const uint8_t *aad, + size_t aad_length) { - if (!cipher_txt || !clear_txt || 0 == clear_txt_size || !aad || 0 == aad_length) { + if (!cipher_txt || !clear_txt || 0 == clear_txt_size || !aad || + 0 == aad_length) { return -1; } @@ -63,8 +65,8 @@ int aes_encrypt_packet(fdo_encrypted_packet_t *cipher_txt, uint8_t *clear_txt, // get encryted data if (0 != fdo_msg_encrypt(ct, clear_txt_size, cipher_text, &cipher_length, cipher_txt->iv, - cipher_txt->tag, sizeof(cipher_txt->tag), - aad, aad_length)) { + cipher_txt->tag, sizeof(cipher_txt->tag), aad, + aad_length)) { LOG(LOG_ERROR, "Failed to get encrypt.\n"); goto end; } @@ -127,10 +129,11 @@ int aes_decrypt_packet(fdo_encrypted_packet_t *cipher_txt, goto end; } - if (0 != fdo_msg_decrypt( - cleartext, &clear_text_length, cipher_txt->em_body->bytes, - cipher_txt->em_body->byte_sz, cipher_txt->iv, - cipher_txt->tag, sizeof(cipher_txt->tag), aad, aad_length)) { + if (0 != fdo_msg_decrypt(cleartext, &clear_text_length, + cipher_txt->em_body->bytes, + cipher_txt->em_body->byte_sz, cipher_txt->iv, + cipher_txt->tag, sizeof(cipher_txt->tag), aad, + aad_length)) { LOG(LOG_ERROR, "Failed to Decrypt\n"); goto end; } diff --git a/lib/fdo.c b/lib/fdo.c index 86bd3566..58748752 100644 --- a/lib/fdo.c +++ b/lib/fdo.c @@ -17,7 +17,7 @@ #include "fdoprot.h" #include "load_credentials.h" #include "network_al.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include "util.h" #include #include @@ -55,6 +55,9 @@ static app_data_t *g_fdo_data = NULL; extern int g_argc; extern char **g_argv; +char *mfg_addr = NULL; +bool use_mfg_addr_bin = true; + #if defined(DEVICE_CSE_ENABLED) TEEHANDLE fdo_cse_handle; #endif @@ -86,7 +89,8 @@ static bool _STATE_Shutdown_Error(void); static fdo_sdk_status app_initialize(void); static void app_close(void); bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, - fdo_ip_address_t **mfg_ip, char *mfg_dns, size_t mfg_dns_sz, int *mfg_port); + fdo_ip_address_t **mfg_ip, char *mfg_dns, + size_t mfg_dns_sz, int *mfg_port); #define ERROR() \ { \ @@ -137,13 +141,17 @@ fdo_sdk_status fdo_sdk_run(void) ret = FDO_ERROR; ++error_count; if (error_count == ERROR_RETRY_COUNT) { - LOG(LOG_INFO, "*********Retry(s) done*********\n"); + LOG(LOG_INFO, + "*********Retry(s) done*********\n"); g_fdo_data->state_fn = &_STATE_Shutdown_Error; } else if (error_count > ERROR_RETRY_COUNT) { - // reach here when all retries have been completed + // reach here when all retries have been + // completed goto end; } else { - LOG(LOG_INFO, "*********Retry count : %u*********\n", error_count); + LOG(LOG_INFO, + "*********Retry count : %u*********\n", + error_count); } } } @@ -163,7 +171,7 @@ fdo_sdk_status fdo_sdk_run(void) * @return ret * None. */ -static void fdo_protDIExit(app_data_t *app_data) +static void fdo_prot_di_exit(app_data_t *app_data) { fdo_prot_t *ps = &app_data->prot; @@ -185,7 +193,7 @@ static void fdo_protDIExit(app_data_t *app_data) * @return ret * None. */ -static void fdo_protTO1Exit(app_data_t *app_data) +static void fdo_prot_to1_exit(app_data_t *app_data) { fdo_prot_t *ps = &app_data->prot; @@ -210,7 +218,7 @@ static void fdo_protTO1Exit(app_data_t *app_data) * @return ret * None. */ -static void fdo_protTO2Exit(app_data_t *app_data) +static void fdo_prot_to2_exit(app_data_t *app_data) { fdo_prot_t *ps = &app_data->prot; @@ -289,7 +297,8 @@ static void fdo_protTO2Exit(app_data_t *app_data) } if (ps->serviceinfo_invalid_modnames) { - fdo_serviceinfo_invalid_modname_free(ps->serviceinfo_invalid_modnames); + fdo_serviceinfo_invalid_modname_free( + ps->serviceinfo_invalid_modnames); fdo_free(ps->serviceinfo_invalid_modnames); } @@ -389,29 +398,35 @@ static fdo_sdk_status app_initialize(void) // ServiceInfo size that will be supported for both Owner and Device // ServiceInfo. // - // Default to MIN_SERVICEINFO_SZ if the file is non-existent, or if the file - // content is not a valid number between MIN_SERVICEINFO_SZ and + // Default to MIN_SERVICEINFO_SZ if the file is non-existent, or if the + // file content is not a valid number between MIN_SERVICEINFO_SZ and // MAX_SERVICEINFO_SZ - fsize = fdo_blob_size((char *)MAX_SERVICEINFO_SZ_FILE, FDO_SDK_RAW_DATA); + fsize = + fdo_blob_size((char *)MAX_SERVICEINFO_SZ_FILE, FDO_SDK_RAW_DATA); if (fsize == 0) { g_fdo_data->prot.maxDeviceServiceInfoSz = MIN_SERVICEINFO_SZ; g_fdo_data->prot.maxOwnerServiceInfoSz = MIN_SERVICEINFO_SZ; - g_fdo_data->prot.prot_buff_sz = MSG_BUFFER_SZ + MSG_METADATA_SIZE; + g_fdo_data->prot.prot_buff_sz = + MSG_BUFFER_SZ + MSG_METADATA_SIZE; } else { buffer = fdo_alloc(fsize + 1); if (!buffer) { LOG(LOG_ERROR, "malloc failed\n"); } else { - if (fdo_blob_read((char *)MAX_SERVICEINFO_SZ_FILE, FDO_SDK_RAW_DATA, - (uint8_t *)buffer, fsize) == -1) { - LOG(LOG_ERROR, "Failed to read Manufacture DN\n"); + if (fdo_blob_read((char *)MAX_SERVICEINFO_SZ_FILE, + FDO_SDK_RAW_DATA, (uint8_t *)buffer, + fsize) == -1) { + LOG(LOG_ERROR, + "Failed to read Manufacture DN\n"); } // set to 0 explicitly errno = 0; buffer_as_long = strtol(buffer, &eptr, 10); if (!eptr || eptr == buffer || errno != 0) { - LOG(LOG_INFO, "Invalid maximum ServiceInfo size, " - "defaulting to %d\n", MIN_SERVICEINFO_SZ); + LOG(LOG_INFO, + "Invalid maximum ServiceInfo size, " + "defaulting to %d\n", + MIN_SERVICEINFO_SZ); max_serviceinfo_sz = MIN_SERVICEINFO_SZ; } @@ -423,53 +438,62 @@ static fdo_sdk_status app_initialize(void) max_serviceinfo_sz = buffer_as_long; } if (max_serviceinfo_sz > MSG_BUFFER_SZ) { - g_fdo_data->prot.prot_buff_sz = max_serviceinfo_sz + MSG_METADATA_SIZE; + g_fdo_data->prot.prot_buff_sz = + max_serviceinfo_sz + MSG_METADATA_SIZE; } else { - g_fdo_data->prot.prot_buff_sz = MSG_BUFFER_SZ + MSG_METADATA_SIZE; + g_fdo_data->prot.prot_buff_sz = + MSG_BUFFER_SZ + MSG_METADATA_SIZE; } - g_fdo_data->prot.maxDeviceServiceInfoSz = max_serviceinfo_sz; - g_fdo_data->prot.maxOwnerServiceInfoSz = max_serviceinfo_sz; + g_fdo_data->prot.maxDeviceServiceInfoSz = + max_serviceinfo_sz; + g_fdo_data->prot.maxOwnerServiceInfoSz = + max_serviceinfo_sz; } } // maxDeviceMessageSize that is to be sent during msg/60 - g_fdo_data->prot.max_device_message_size = g_fdo_data->prot.prot_buff_sz; + g_fdo_data->prot.max_device_message_size = + g_fdo_data->prot.prot_buff_sz; if (buffer != NULL) { fdo_free(buffer); } - LOG(LOG_INFO, "Maximum supported DeviceServiceInfo size: %"PRIu64" bytes\n", - g_fdo_data->prot.maxDeviceServiceInfoSz); - LOG(LOG_INFO, "Maximum supported OwnerServiceInfo size: %"PRIu64" bytes\n", - g_fdo_data->prot.maxOwnerServiceInfoSz); + LOG(LOG_INFO, + "Maximum supported DeviceServiceInfo size: %" PRIu64 " bytes\n", + g_fdo_data->prot.maxDeviceServiceInfoSz); + LOG(LOG_INFO, + "Maximum supported OwnerServiceInfo size: %" PRIu64 " bytes\n", + g_fdo_data->prot.maxOwnerServiceInfoSz); /* - * Initialize and allocate memory for the FDOW/FDOR blocks before starting the spec's - * protocol execution. Reuse the allocated memory by emptying the contents. - */ + * Initialize and allocate memory for the FDOW/FDOR blocks before + * starting the spec's protocol execution. Reuse the allocated memory by + * emptying the contents. + */ if (!fdow_init(&g_fdo_data->prot.fdow) || - !fdo_block_alloc_with_size(&g_fdo_data->prot.fdow.b, - g_fdo_data->prot.prot_buff_sz)) { + !fdo_block_alloc_with_size(&g_fdo_data->prot.fdow.b, + g_fdo_data->prot.prot_buff_sz)) { LOG(LOG_ERROR, "fdow_init() failed!\n"); return FDO_ERROR; } if (!fdor_init(&g_fdo_data->prot.fdor) || - !fdo_block_alloc_with_size(&g_fdo_data->prot.fdor.b, - g_fdo_data->prot.prot_buff_sz)) { + !fdo_block_alloc_with_size(&g_fdo_data->prot.fdor.b, + g_fdo_data->prot.prot_buff_sz)) { LOG(LOG_ERROR, "fdor_init() failed!\n"); return FDO_ERROR; } if ((g_fdo_data->devcred->ST == FDO_DEVICE_STATE_READY1) || - (g_fdo_data->devcred->ST == FDO_DEVICE_STATE_READYN)) { - #if defined(DEVICE_CSE_ENABLED) + (g_fdo_data->devcred->ST == FDO_DEVICE_STATE_READYN)) { +#if defined(DEVICE_CSE_ENABLED) if (!read_cse_device_credentials(g_fdo_data->devcred)) { - LOG(LOG_ERROR, "Could not parse the Device Credentials form CSE\n"); + LOG(LOG_ERROR, "Could not parse the Device Credentials " + "form CSE\n"); return -1; } ret = 0; - #else +#else ret = load_device_secret(); - #endif +#endif if (ret == -1) { LOG(LOG_ERROR, "Load HMAC Secret failed\n"); return FDO_ERROR; @@ -592,7 +616,8 @@ void fdo_sdk_service_info_register_module(fdo_sdk_service_info_module *module) /** * Create 'devmod' module and initialize it with the key-value pairs. */ -static bool add_module_devmod(void) { +static bool add_module_devmod(void) +{ // Build up default 'devmod' ServiceInfo list g_fdo_data->service_info = fdo_service_info_alloc(); @@ -601,88 +626,88 @@ static bool add_module_devmod(void) { return false; } - if (!fdo_service_info_add_kv_bool(g_fdo_data->service_info, "devmod:active", - true)) { + if (!fdo_service_info_add_kv_bool(g_fdo_data->service_info, + "devmod:active", true)) { LOG(LOG_ERROR, "Failed to add devmod:active\n"); return false; } if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:os", - OS_NAME)) { + OS_NAME)) { LOG(LOG_ERROR, "Failed to add devmod:os\n"); return false; } - if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:arch", - ARCH)) { + if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, + "devmod:arch", ARCH)) { LOG(LOG_ERROR, "Failed to add devmod:arch\n"); return false; } - if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:version", - OS_VERSION)) { + if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, + "devmod:version", OS_VERSION)) { LOG(LOG_ERROR, "Failed to add devmod:version\n"); return false; } - if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:device", - (char *)get_device_model())) { + if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, + "devmod:device", + (char *)get_device_model())) { LOG(LOG_ERROR, "Failed to add devmod:device\n"); return false; } if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:sn", - (char *)get_device_serial_number())) { + (char *)get_device_serial_number())) { LOG(LOG_ERROR, "Failed to add devmod:sn\n"); return false; } - if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:pathsep", - PATH_SEPARATOR)) { + if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, + "devmod:pathsep", PATH_SEPARATOR)) { LOG(LOG_ERROR, "Failed to add devmod:pathsep\n"); return false; } if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:sep", - SEPARATOR)) { + SEPARATOR)) { LOG(LOG_ERROR, "Failed to add devmod:sep\n"); return false; } if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:nl", - NEWLINE)) { + NEWLINE)) { LOG(LOG_ERROR, "Failed to add devmod:nl\n"); return false; } if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:tmp", - "")) { + "")) { LOG(LOG_ERROR, "Failed to add devmod:tmp\n"); return false; } if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:dir", - "")) { + "")) { LOG(LOG_ERROR, "Failed to add devmod:dir\n"); return false; } - if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:progenv", - PROGENV)) { + if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, + "devmod:progenv", PROGENV)) { LOG(LOG_ERROR, "Failed to add devmod:progenv\n"); return false; } if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:bin", - BIN_TYPE)) { + BIN_TYPE)) { LOG(LOG_ERROR, "Failed to add devmod:bin\n"); return false; } - if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:mudurl", - "")) { + if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, + "devmod:mudurl", "")) { LOG(LOG_ERROR, "Failed to add devmod:mudurl\n"); return false; } - // should ideally contain supported ServiceInfo module list and its count. - // for now, set this to 1, since we've only 1 module 'fdo_sys' - // TO-DO : Move this to fdotypes later when multiple Device ServiceInfo module - // support is added. - if (!fdo_service_info_add_kv_int(g_fdo_data->service_info, "devmod:nummodules", - 1)) { + // should ideally contain supported ServiceInfo module list and its + // count. + if (!fdo_service_info_add_kv_int(g_fdo_data->service_info, + "devmod:nummodules", 3)) { LOG(LOG_ERROR, "Failed to add devmod:nummodules\n"); return false; } - if (!fdo_service_info_add_kv_str(g_fdo_data->service_info, "devmod:modules", - g_fdo_data->module_list->module.module_name)) { + if (!fdo_service_info_add_kv_str( + g_fdo_data->service_info, "devmod:modules", + g_fdo_data->module_list->module.module_name)) { LOG(LOG_ERROR, "Failed to add devmod:modules\n"); return false; } @@ -729,16 +754,18 @@ void fdo_sdk_deinit(void) (void)fdo_crypto_close(); #if defined(DEVICE_CSE_ENABLED) - #if defined(CSE_SHUTDOWN) - FDO_STATUS fdo_status; - if (TEE_SUCCESS != fdo_heci_close_interface(&fdo_cse_handle, &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { - if (FDO_STATUS_API_INTERFACE_IS_CLOSED == fdo_status) { - LOG(LOG_ERROR, "CSE Interface is already Closed!!\n"); - } else { - LOG(LOG_ERROR, "HECI GET CLOSE INTERFACE failed!!\n"); - } +#if defined(CSE_SHUTDOWN) + FDO_STATUS fdo_status; + if (TEE_SUCCESS != + fdo_heci_close_interface(&fdo_cse_handle, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { + if (FDO_STATUS_API_INTERFACE_IS_CLOSED == fdo_status) { + LOG(LOG_ERROR, "CSE Interface is already Closed!!\n"); + } else { + LOG(LOG_ERROR, "HECI GET CLOSE INTERFACE failed!!\n"); } - #endif + } +#endif heci_deinit(&fdo_cse_handle); #endif app_close(); @@ -770,7 +797,7 @@ fdo_sdk_status fdo_sdk_init(fdo_sdk_errorCB error_handling_callback, int ret; fdo_sdk_device_status state = FDO_DEVICE_STATE_D; - /* fdo Global data initialization */ + /* FDO Global data initialization */ g_fdo_data = fdo_alloc(sizeof(app_data_t)); if (!g_fdo_data) { @@ -806,9 +833,12 @@ fdo_sdk_status fdo_sdk_init(fdo_sdk_errorCB error_handling_callback, uint16_t minor_v = 0; FDO_STATUS fdo_status; - if (TEE_SUCCESS != fdo_heci_get_version(&fdo_cse_handle, &major_v, &minor_v, &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + if (TEE_SUCCESS != fdo_heci_get_version(&fdo_cse_handle, &major_v, + &minor_v, &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { if (FDO_STATUS_API_INTERFACE_IS_CLOSED == fdo_status) { - LOG(LOG_ERROR, "CSE Interface is Closed!! Reboot required.\n"); + LOG(LOG_ERROR, + "CSE Interface is Closed!! Reboot required.\n"); } else { LOG(LOG_ERROR, "HECI GET VERSION failed!!\n"); } @@ -816,7 +846,7 @@ fdo_sdk_status fdo_sdk_init(fdo_sdk_errorCB error_handling_callback, } LOG(LOG_INFO, "FDO CSE major_version (%u)\n", major_v); - LOG(LOG_INFO, "FDO CSE minor_version (%u)\n", minor_v); + LOG(LOG_INFO, "FDO CSE minor_version (%u)\n", minor_v); #endif /* Load credentials */ @@ -840,12 +870,18 @@ fdo_sdk_status fdo_sdk_init(fdo_sdk_errorCB error_handling_callback, return FDO_ERROR; } } - +#if defined(DEVICE_TPM20_ENABLED) + if (g_fdo_data->devcred->ST != FDO_DEVICE_STATE_PC && + g_fdo_data->devcred->dc_active == false) { + g_fdo_data->devcred->ST = FDO_DEVICE_STATE_IDLE; + return FDO_SUCCESS; + } +#endif if ((num_modules == 0) || (num_modules > FDO_MAX_MODULES) || (module_information == NULL) || (module_information->service_info_callback == NULL)) { return FDO_ERROR; - } + } /* register service-info modules */ for (uint32_t i = 0; i < num_modules; i++) { @@ -862,16 +898,18 @@ fdo_sdk_status fdo_sdk_init(fdo_sdk_errorCB error_handling_callback, } /** - * Parse the manufacturer network address in the given buffer, and extract and save - * the TLS/IP/DNS/Port values. + * Parse the manufacturer network address in the given buffer, and extract and + * save the TLS/IP/DNS/Port values. * * @param buffer Buffer containing the network address * @param buffer_sz Size of the above buffer - * @param tls Output flag describing whether HTTP (false) or HTTPS (true) is used + * @param tls Output flag describing whether HTTP (false) or HTTPS (true) is + * used * @param mfg_ip * Output structure to store IP. Memory allocation is done in this method. - * If IP address is found while parsing, this allocated structure is returned that must - * be freed by the caller after use. Otherwise, a NULL object is returned. + * If IP address is found while parsing, this allocated structure is returned + * that must be freed by the caller after use. Otherwise, a NULL object is + * returned. * @param mfg_dns Output pre-allocated buffer to store DNS * @param mfg_dns_sz Size of the DNS buffer (minimum 100) * @param mfg_port Output variable to store port @@ -879,8 +917,9 @@ fdo_sdk_status fdo_sdk_init(fdo_sdk_errorCB error_handling_callback, * Return true if parse was successful, false otherwise. */ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, - fdo_ip_address_t **mfg_ip, char *mfg_dns, size_t mfg_dns_sz, - int *mfg_port) { + fdo_ip_address_t **mfg_ip, char *mfg_dns, + size_t mfg_dns_sz, int *mfg_port) +{ char transport_prot[6] = {0}; char port[6] = {0}; @@ -894,7 +933,7 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, const char transport_https[6] = "https"; if (!buffer || buffer_sz == 0 || !tls || !mfg_ip || !mfg_dns || - mfg_dns_sz == 0 || !mfg_port) { + mfg_dns_sz == 0 || !mfg_port) { LOG(LOG_ERROR, "Invalid params\n"); return false; } @@ -902,10 +941,12 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, // the expected format is '{http/https}://{IP/DNS}:port' // parse transport protocol until ':' - while (buffer[index] != ':' && index < sizeof(transport_prot) - 1 && index < buffer_sz) { + while (buffer[index] != ':' && index < sizeof(transport_prot) - 1 && + index < buffer_sz) { if (!isalpha(buffer[index])) { - LOG(LOG_ERROR, "Invalid Transport protocol or missing separator" - " in Manufacturer address\n"); + LOG(LOG_ERROR, + "Invalid Transport protocol or missing separator" + " in Manufacturer address\n"); goto end; } else { transport_prot[index] = buffer[index]; @@ -914,8 +955,10 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, } // parse separator "://" - if (buffer[index] != ':' || buffer[index + 1] != '/' || buffer[index + 2] != '/') { - LOG(LOG_ERROR, "Invalid/missing DNS/IP separator in Manufacturer address\n"); + if (buffer[index] != ':' || buffer[index + 1] != '/' || + buffer[index + 2] != '/') { + LOG(LOG_ERROR, "Invalid/missing DNS/IP separator in " + "Manufacturer address\n"); goto end; } else { index += 3; @@ -926,9 +969,12 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, LOG(LOG_ERROR, "memset failed\n"); goto end; } - while (buffer[index] != ':' && (dns_index < mfg_dns_sz - 1) && index < buffer_sz) { - if (!isalnum(buffer[index]) && buffer[index] != '-' && buffer[index] != '.') { - LOG(LOG_ERROR, "Invalid DNS/IP or missing separator in Manufacturer address\n"); + while (buffer[index] != ':' && (dns_index < mfg_dns_sz - 1) && + index < buffer_sz) { + if (!isalnum(buffer[index]) && buffer[index] != '-' && + buffer[index] != '.') { + LOG(LOG_ERROR, "Invalid DNS/IP or missing separator in " + "Manufacturer address\n"); goto end; } else { mfg_dns[dns_index] = buffer[index]; @@ -947,14 +993,16 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, // parse separator ':' if (buffer[index] != ':') { - LOG(LOG_ERROR, "Missing port separator in Manufacturer address\n"); + LOG(LOG_ERROR, + "Missing port separator in Manufacturer address\n"); goto end; } else { index += 1; } // parse port for atmost 5 characters - while (port_index < sizeof(port) -1 && index < buffer_sz && isdigit(buffer[index])) { + while (port_index < sizeof(port) - 1 && index < buffer_sz && + isdigit(buffer[index])) { port[port_index] = buffer[index]; index++; port_index++; @@ -970,8 +1018,9 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, index++; } // check for new-line or EOF or null-character - if (index < buffer_sz && (buffer[index] == EOF || buffer[index] == '\n' || - buffer[index] == '\0')) { + if (index < buffer_sz && + (buffer[index] == EOF || buffer[index] == '\n' || + buffer[index] == '\0')) { index++; } @@ -983,21 +1032,25 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, // validate transport protocol. check for 'http' first, then 'https' *tls = false; if (memcmp_s(transport_prot, sizeof(transport_prot), transport_http, - sizeof(transport_http), &result) != 0) { + sizeof(transport_http), &result) != 0) { LOG(LOG_ERROR, "Failed to compare transport protocol\n"); goto end; } if (0 != result) { - if (memcmp_s(transport_prot, sizeof(transport_prot), transport_https, - sizeof(transport_https), &result) != 0) { - LOG(LOG_ERROR, "Failed to compare transport protocol\n"); + if (memcmp_s(transport_prot, sizeof(transport_prot), + transport_https, sizeof(transport_https), + &result) != 0) { + LOG(LOG_ERROR, + "Failed to compare transport protocol\n"); goto end; } if (0 == result) { *tls = true; - LOG(LOG_DEBUG, "Manufacturer Transport protocol: HTTPS\n"); + LOG(LOG_DEBUG, + "Manufacturer Transport protocol: HTTPS\n"); } else { - LOG(LOG_ERROR, "Invalid Manufacturer Transport protocol specified.\n"); + LOG(LOG_ERROR, "Invalid Manufacturer Transport " + "protocol specified.\n"); goto end; } } else { @@ -1006,8 +1059,9 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, // validate IP/DNS, check for IP first, if it fails, treat it as DNS // allocate IP structure here - // if a valid IP is found, return the IP structure conatining IP, that must be freed by caller - // if a valid IP is not found, free the IP structure immediately and return NULL IP structure + // if a valid IP is found, return the IP structure conatining IP, that + // must be freed by caller if a valid IP is not found, free the IP + // structure immediately and return NULL IP structure *mfg_ip = fdo_ipaddress_alloc(); if (!*mfg_ip) { LOG(LOG_ERROR, "Failed to alloc memory\n"); @@ -1038,7 +1092,7 @@ bool parse_manufacturer_address(char *buffer, size_t buffer_sz, bool *tls, LOG(LOG_ERROR, "Manufacturer port is not a number.\n"); goto end; } else if (!((*mfg_port >= FDO_PORT_MIN_VALUE) && - (*mfg_port <= FDO_PORT_MAX_VALUE))) { + (*mfg_port <= FDO_PORT_MAX_VALUE))) { LOG(LOG_ERROR, "Manufacturer port value should be between " "[%d-%d].\n", @@ -1098,20 +1152,24 @@ fdo_sdk_status fdo_sdk_resale(void) if (g_fdo_data->devcred->ST == FDO_DEVICE_STATE_IDLE) { g_fdo_data->devcred->ST = FDO_DEVICE_STATE_READYN; - #if defined(DEVICE_CSE_ENABLED) +#if defined(DEVICE_CSE_ENABLED) if (!store_device_status(&g_fdo_data->devcred->ST)) { - LOG(LOG_ERROR, "Failed to store updated device status\n"); + LOG(LOG_ERROR, + "Failed to store updated device status\n"); return FDO_ERROR; } ret = 0; - #else +#else if (load_device_secret()) { LOG(LOG_ERROR, "Reading {Mfg|Secret} blob failied!\n"); return FDO_ERROR; } - +#if defined(DEVICE_TPM20_ENABLED) + ret = store_tpm_credential(g_fdo_data->devcred); +#else ret = store_credential(g_fdo_data->devcred); - #endif +#endif +#endif if (!ret) { LOG(LOG_INFO, "Set Resale complete\n"); r = FDO_SUCCESS; @@ -1123,7 +1181,7 @@ fdo_sdk_status fdo_sdk_resale(void) if (r == FDO_ERROR) { LOG(LOG_ERROR, "Failed to set Resale\n"); } else if (r == FDO_RESALE_NOT_READY) { - LOG(LOG_DEBUG, "Device is not ready for Resale\n"); + LOG(LOG_INFO, "Device is not ready for Resale\n"); } if (g_fdo_data->devcred) { fdo_dev_cred_free(g_fdo_data->devcred); @@ -1208,36 +1266,54 @@ static bool _STATE_DI(void) fdo_prot_di_init(&g_fdo_data->prot, g_fdo_data->devcred); - fsize = fdo_blob_size((char *)MANUFACTURER_ADDR, FDO_SDK_RAW_DATA); - if (fsize > 0) { - buffer = fdo_alloc(fsize + 1); - if (buffer == NULL) { - LOG(LOG_ERROR, "malloc failed\n"); - goto end; - } + if (use_mfg_addr_bin) { + fsize = + fdo_blob_size((char *)MANUFACTURER_ADDR, FDO_SDK_RAW_DATA); + if (fsize > 0) { + buffer = fdo_alloc(fsize + 1); + if (buffer == NULL) { + LOG(LOG_ERROR, "malloc failed\n"); + goto end; + } - if (fdo_blob_read((char *)MANUFACTURER_ADDR, FDO_SDK_RAW_DATA, - (uint8_t *)buffer, fsize) == -1) { - LOG(LOG_ERROR, "Failed to read Manufacturer address\n"); - goto end; - } + if (fdo_blob_read((char *)MANUFACTURER_ADDR, + FDO_SDK_RAW_DATA, (uint8_t *)buffer, + fsize) == -1) { + LOG(LOG_ERROR, + "Failed to read Manufacturer address\n"); + goto end; + } - buffer[fsize] = '\0'; + buffer[fsize] = '\0'; - if (!parse_manufacturer_address(buffer, fsize, &tls, &mfg_ip, - mfg_dns, sizeof(mfg_dns), &mfg_port)) { - LOG(LOG_ERROR, "Failed to parse Manufacturer Network address.\n"); + if (!parse_manufacturer_address( + buffer, fsize, &tls, &mfg_ip, mfg_dns, + sizeof(mfg_dns), &mfg_port)) { + LOG(LOG_ERROR, "Failed to parse Manufacturer " + "Network address.\n"); + goto end; + } + } else { + LOG(LOG_ERROR, + "Manufacturer Network address file is empty.\n"); goto end; } } else { - LOG(LOG_ERROR, "Manufacturer Network address file is empty.\n"); - goto end; + fsize = strnlen_s(mfg_addr, FDO_MAX_STR_SIZE); + if (!parse_manufacturer_address(mfg_addr, fsize, &tls, &mfg_ip, + mfg_dns, sizeof(mfg_dns), + &mfg_port)) { + LOG(LOG_ERROR, + "Failed to parse Manufacturer Network address.\n"); + goto end; + } } g_fdo_data->delaysec = default_delay; - prot_ctx = fdo_prot_ctx_alloc(fdo_process_states, &g_fdo_data->prot, - mfg_ip, mfg_ip ? NULL : mfg_dns, mfg_port, tls); + prot_ctx = + fdo_prot_ctx_alloc(fdo_process_states, &g_fdo_data->prot, mfg_ip, + mfg_ip ? NULL : mfg_dns, mfg_port, tls); if (prot_ctx == NULL) { ERROR(); goto end; @@ -1247,7 +1323,8 @@ static bool _STATE_DI(void) LOG(LOG_ERROR, "DI failed.\n"); if (g_fdo_data->error_recovery) { g_fdo_data->state_fn = &_STATE_DI; - LOG(LOG_INFO, "\nDelaying for %"PRIu64" seconds\n\n", g_fdo_data->delaysec); + LOG(LOG_INFO, "\nDelaying for %" PRIu64 " seconds\n\n", + g_fdo_data->delaysec); fdo_sleep(g_fdo_data->delaysec); LOG(LOG_INFO, "Retrying.....\n"); goto end; @@ -1271,7 +1348,7 @@ static bool _STATE_DI(void) #endif ret = true; end: - fdo_protDIExit(g_fdo_data); + fdo_prot_di_exit(g_fdo_data); if (prot_ctx) { fdo_prot_ctx_free(prot_ctx); fdo_free(prot_ctx); @@ -1290,8 +1367,9 @@ static bool _STATE_DI(void) * initializse state variables and runs the TO1 protocol. * * @return ret - * true if TO1 completes successfully, or if RVBypass was encountered in RendezvousInfo - * false if all RendezvousDirectives have been tried and TO1 resulted in failure. + * true if TO1 completes successfully, or if RVBypass was encountered in + * RendezvousInfo false if all RendezvousDirectives have been tried and TO1 + * resulted in failure. */ static bool _STATE_TO1(void) { @@ -1325,19 +1403,21 @@ static bool _STATE_TO1(void) // Try TO1 for all available RVDirectives. // Only checking for RVIP/RVDNS/RVPort/RVBypass/RVOwnerOnly flags. - // Depending on the requirement, check for more flags should be added here. - // If we encounter RVBYPASS, skip directly to TO2. - // TO-DO: Integrate TO2 flow into this and fix it to start from the - // next directive always in case of failure (ex: RVBypass) + // Depending on the requirement, check for more flags should be added + // here. If we encounter RVBYPASS, skip directly to TO2. TO-DO: + // Integrate TO2 flow into this and fix it to start from the next + // directive always in case of failure (ex: RVBypass) int port = 0; fdo_ip_address_t *ip = NULL; fdo_string_t *dns = NULL; if (g_fdo_data->current_rvdirective == NULL) { - // keep track of current directive in use with the help of stored RendezvousInfo from DI. - // it is NULL at 2 points: during 1st TO1 run, and, - // when all RVDirectives have been used and we're re-trying - g_fdo_data->current_rvdirective = g_fdo_data->devcred->owner_blk->rvlst->rv_directives; + // keep track of current directive in use with the help of + // stored RendezvousInfo from DI. it is NULL at 2 points: during + // 1st TO1 run, and, when all RVDirectives have been used and + // we're re-trying + g_fdo_data->current_rvdirective = + g_fdo_data->devcred->owner_blk->rvlst->rv_directives; } // delay if we came back from RVBypass or re-try RVInfo with some value, @@ -1345,7 +1425,8 @@ static bool _STATE_TO1(void) fdo_sleep(g_fdo_data->delaysec); while (!ret && g_fdo_data->current_rvdirective) { - fdo_rendezvous_t *rv = g_fdo_data->current_rvdirective->rv_entries; + fdo_rendezvous_t *rv = + g_fdo_data->current_rvdirective->rv_entries; // reset for next use. port = 0; ip = NULL; @@ -1361,7 +1442,8 @@ static bool _STATE_TO1(void) rvbypass = true; break; } else if (rv->owner_only && *rv->owner_only) { - LOG(LOG_DEBUG, "Found RVOwnerOnly. Skipping the directive...\n"); + LOG(LOG_DEBUG, "Found RVOwnerOnly. Skipping " + "the directive...\n"); skip_rv = true; break; } else if (rv->ip) { @@ -1373,53 +1455,63 @@ static bool _STATE_TO1(void) } else if (rv->pr) { if (*rv->pr == RVPROTHTTP) { tls = false; - } else if (*rv->pr == RVPROTHTTPS || *rv->pr == RVPROTTLS) { + } else if (*rv->pr == RVPROTHTTPS || + *rv->pr == RVPROTTLS) { // nothing to do. TLS is already set } else { - LOG(LOG_ERROR, "Unsupported/Invalid value found for RVProtocolValue. " - "Skipping the directive...\n"); + LOG(LOG_ERROR, + "Unsupported/Invalid value found " + "for RVProtocolValue. " + "Skipping the directive...\n"); skip_rv = true; break; } } else if (rv->delaysec) { g_fdo_data->delaysec = *rv->delaysec; - LOG(LOG_INFO, "DelaySec set, Delay: %"PRIu64"s\n", g_fdo_data->delaysec); + LOG(LOG_INFO, + "DelaySec set, Delay: %" PRIu64 "s\n", + g_fdo_data->delaysec); } - // ignore the other RendezvousInstr as they are not used for making requests + // ignore the other RendezvousInstr as they are not used + // for making requests rv = rv->next; } if (rvbypass) { ret = true; - LOG(LOG_DEBUG, "Found RVBYPASS in the RendezvousDirective. Skipping TO1...\n"); + LOG(LOG_DEBUG, + "Found RVBYPASS in the RendezvousDirective. " + "Skipping TO1...\n"); g_fdo_data->state_fn = &_STATE_TO2; goto end; } - // Found the needed entries of the current directive. Prepare to move to next. - g_fdo_data->current_rvdirective = g_fdo_data->current_rvdirective->next; + // Found the needed entries of the current directive. Prepare + // to move to next. + g_fdo_data->current_rvdirective = + g_fdo_data->current_rvdirective->next; if (0 == port) { if (tls) { port = 443; - } - else { + } else { port = 80; - } - LOG(LOG_INFO, "Assigned default port: %d \n", port); } + LOG(LOG_INFO, "Assigned default port: %d \n", port); + } if (skip_rv || (!ip && !dns)) { // If all of the IP/DNS values are missing, or - // if RVOwnerOnly is present in the current directive, or - // if unsupported/invalid RVProtocolValue was found - // skip the current directive and check for the same in the next directives. + // if RVOwnerOnly is present in the current directive, + // or if unsupported/invalid RVProtocolValue was found + // skip the current directive and check for the same in + // the next directives. continue; } prot_ctx = - fdo_prot_ctx_alloc(fdo_process_states, &g_fdo_data->prot, ip, - dns ? dns->bytes : NULL, port, tls); + fdo_prot_ctx_alloc(fdo_process_states, &g_fdo_data->prot, + ip, dns ? dns->bytes : NULL, port, tls); if (prot_ctx == NULL) { ERROR(); goto end; @@ -1429,39 +1521,50 @@ static bool _STATE_TO1(void) LOG(LOG_ERROR, "TO1 failed.\n"); // clear contents for a fresh start. - fdo_protTO1Exit(g_fdo_data); + fdo_prot_to1_exit(g_fdo_data); fdo_prot_ctx_free(prot_ctx); fdo_free(prot_ctx); - // check if there is another RV location to try. if yes, try it - // the delay interval is conditional + // check if there is another RV location to try. if yes, + // try it the delay interval is conditional if (g_fdo_data->current_rvdirective) { - if (g_fdo_data->delaysec == 0 || g_fdo_data->delaysec > max_delay) { + if (g_fdo_data->delaysec == 0 || + g_fdo_data->delaysec > max_delay) { g_fdo_data->delaysec = default_delay; } - LOG(LOG_INFO, "\nDelaying for %"PRIu64" seconds\n\n", g_fdo_data->delaysec); + LOG(LOG_INFO, + "\nDelaying for %" PRIu64 " seconds\n\n", + g_fdo_data->delaysec); fdo_sleep(g_fdo_data->delaysec); continue; } - // there are no more RV locations left, so check if retry is enabled. - // if yes, proceed with retrying all the RV locations - // if not, return immediately since there is nothing else left to do. + // there are no more RV locations left, so check if + // retry is enabled. if yes, proceed with retrying all + // the RV locations if not, return immediately since + // there is nothing else left to do. if (g_fdo_data->error_recovery) { - if (g_fdo_data->delaysec == 0 || g_fdo_data->delaysec > max_delay) { - g_fdo_data->delaysec = default_delay_rvinfo_retries; + if (g_fdo_data->delaysec == 0 || + g_fdo_data->delaysec > max_delay) { + g_fdo_data->delaysec = + default_delay_rvinfo_retries; } - LOG(LOG_INFO, "\nDelaying for %"PRIu64" seconds\n\n", g_fdo_data->delaysec); + LOG(LOG_INFO, + "\nDelaying for %" PRIu64 " seconds\n\n", + g_fdo_data->delaysec); g_fdo_data->state_fn = &_STATE_TO1; LOG(LOG_INFO, "Retrying.....\n"); return ret; } else { - LOG(LOG_INFO, "Retry is disabled. Aborting.....\n"); + LOG(LOG_INFO, + "Retry is disabled. Aborting.....\n"); return ret; } } else { - LOG(LOG_DEBUG, "\n------------------------------------ TO1 Successful " - "--------------------------------------\n"); + LOG(LOG_DEBUG, + "\n------------------------------------ TO1 " + "Successful " + "--------------------------------------\n"); ret = true; g_fdo_data->state_fn = &_STATE_TO2; goto end; @@ -1469,7 +1572,7 @@ static bool _STATE_TO1(void) } end: - fdo_protTO1Exit(g_fdo_data); + fdo_prot_to1_exit(g_fdo_data); if (prot_ctx) { fdo_prot_ctx_free(prot_ctx); fdo_free(prot_ctx); @@ -1482,9 +1585,9 @@ static bool _STATE_TO1(void) * initializse state variables and runs the TO2 protocol. * * @return ret - * true if TO2 completes successfully, or if there are more RendezvousDirectives that - * need to be processed, - * false if all RendezvousDirectives have been tried and TO2 resulted in failure. + * true if TO2 completes successfully, or if there are more + * RendezvousDirectives that need to be processed, false if all + * RendezvousDirectives have been tried and TO2 resulted in failure. */ static bool _STATE_TO2(void) { @@ -1526,7 +1629,8 @@ static bool _STATE_TO2(void) LOG(LOG_ERROR, "RVTO2Addr list is empty!\n"); return FDO_ERROR; } - g_fdo_data->current_rvto2addrentry = rvto2addr->rv_to2addr_entry; + g_fdo_data->current_rvto2addrentry = + rvto2addr->rv_to2addr_entry; } int port = 0; @@ -1537,19 +1641,21 @@ static bool _STATE_TO2(void) // if thers is RVBYPASS enabled, we set 'rvbypass' flag to false // otherwise, there'll be RVTO2AddrEntry(s), and we iterate through it. - // Only one of the conditions will satisfy, which is ensured by resetting of the 'rvbypass' flag, - // and, eventual Nulling of the 'g_fdo_data->current_rvto2addrentry' - // because we keep on moving to next. - // Run the TO2 protocol regardless. + // Only one of the conditions will satisfy, which is ensured by + // resetting of the 'rvbypass' flag, and, eventual Nulling of the + // 'g_fdo_data->current_rvto2addrentry' because we keep on moving to + // next. Run the TO2 protocol regardless. if (rvbypass || g_fdo_data->current_rvto2addrentry) { tls = true; skip_rv = false; g_fdo_data->delaysec = 0; - // if rvbypass is set by TO1, then pick the Owner's address from RendezvousInfo. - // otherwise, pick the address from RVTO2AddrEntry. + // if rvbypass is set by TO1, then pick the Owner's address from + // RendezvousInfo. otherwise, pick the address from + // RVTO2AddrEntry. if (rvbypass) { - fdo_rendezvous_t *rv = g_fdo_data->current_rvdirective->rv_entries; + fdo_rendezvous_t *rv = + g_fdo_data->current_rvdirective->rv_entries; while (rv) { if (rv->ip) { ip = rv->ip; @@ -1560,32 +1666,43 @@ static bool _STATE_TO2(void) } else if (rv->pr) { if (*rv->pr == RVPROTHTTP) { tls = false; - } else if (*rv->pr == RVPROTHTTPS || *rv->pr == RVPROTTLS) { - // nothing to do. TLS is already set + } else if (*rv->pr == RVPROTHTTPS || + *rv->pr == RVPROTTLS) { + // nothing to do. TLS is already + // set } else { - LOG(LOG_ERROR, "Unsupported/Invalid value found for RVProtocolValue. " - "Skipping the directive...\n"); + LOG(LOG_ERROR, + "Unsupported/Invalid value " + "found for " + "RVProtocolValue. " + "Skipping the " + "directive...\n"); skip_rv = true; break; } } else if (rv->delaysec) { g_fdo_data->delaysec = *rv->delaysec; - LOG(LOG_INFO, "DelaySec set, Delay: %"PRIu64"s\n", g_fdo_data->delaysec); + LOG(LOG_INFO, + "DelaySec set, Delay: %" PRIu64 + "s\n", + g_fdo_data->delaysec); } - // no need to check for RVBYPASS here again, since we used it - // to get here in the first place - // ignore the other RendezvousInstr as they are not used for making requests + // no need to check for RVBYPASS here again, + // since we used it to get here in the first + // place ignore the other RendezvousInstr as + // they are not used for making requests rv = rv->next; } // Found the needed entries of the current directive. // Prepare to move to next in case of failure - g_fdo_data->current_rvdirective = g_fdo_data->current_rvdirective->next; + g_fdo_data->current_rvdirective = + g_fdo_data->current_rvdirective->next; // clear to1d, if present. - // if this is null at 'TO2.ProveOVHdr, Type 61',then to1d COSE Signature - // verification is avoided. - // Else, COSE Signature verification is done. + // if this is null at 'TO2.ProveOVHdr, Type 61',then + // to1d COSE Signature verification is avoided. Else, + // COSE Signature verification is done. if (g_fdo_data->prot.to1d_cose != NULL) { fdo_cose_free(g_fdo_data->prot.to1d_cose); } @@ -1593,122 +1710,151 @@ static bool _STATE_TO2(void) } else { ip = fdo_ipaddress_alloc(); - if (g_fdo_data->current_rvto2addrentry->rvip && !fdo_convert_to_ipaddress(g_fdo_data->current_rvto2addrentry->rvip, ip)) { - LOG(LOG_ERROR, "Failed to convert IP from RVTO2Addr into IPAddress!\n"); + if (g_fdo_data->current_rvto2addrentry->rvip && + !fdo_convert_to_ipaddress( + g_fdo_data->current_rvto2addrentry->rvip, ip)) { + LOG(LOG_ERROR, "Failed to convert IP from " + "RVTO2Addr into IPAddress!\n"); } dns = g_fdo_data->current_rvto2addrentry->rvdns; port = g_fdo_data->current_rvto2addrentry->rvport; - if (g_fdo_data->current_rvto2addrentry->rvprotocol == PROTHTTP) { + if (g_fdo_data->current_rvto2addrentry->rvprotocol == + PROTHTTP) { tls = false; - } else if (g_fdo_data->current_rvto2addrentry->rvprotocol == PROTHTTPS || - g_fdo_data->current_rvto2addrentry->rvprotocol == PROTTLS) { + } else if (g_fdo_data->current_rvto2addrentry + ->rvprotocol == PROTHTTPS || + g_fdo_data->current_rvto2addrentry + ->rvprotocol == PROTTLS) { // nothing to do. TLS is already set } else { - LOG(LOG_ERROR, "Unsupported/Invalid value found for RVProtocol. " - "Skipping the RVTO2AddrEntry...\n"); + LOG(LOG_ERROR, + "Unsupported/Invalid value found for " + "RVProtocol. " + "Skipping the RVTO2AddrEntry...\n"); skip_rv = true; } // prepare for next iteration beforehand - g_fdo_data->current_rvto2addrentry = g_fdo_data->current_rvto2addrentry->next; - + g_fdo_data->current_rvto2addrentry = + g_fdo_data->current_rvto2addrentry->next; } if (0 == port) { if (tls) { port = 443; - } - else { + } else { port = 80; - } - LOG(LOG_INFO, "Assigned default port: %d \n", port); } + LOG(LOG_INFO, "Assigned default port: %d \n", port); + } if (skip_rv || (!ip && !dns)) { // If all of the IP/DNS values are missing, or - // if RVOwnerOnly is present in the current directive, or - // if unsupported/invalid RVProtocolValue/RVProtocol was found - // for rvbypass, goto TO1 - // else, skip the directive + // if RVOwnerOnly is present in the current directive, + // or if unsupported/invalid RVProtocolValue/RVProtocol + // was found for rvbypass, goto TO1 else, skip the + // directive if (!rvbypass) { - // free only when rvbypass is false, since the allocation was done then. - // Note: This may be unreachable. + // free only when rvbypass is false, since the + // allocation was done then. Note: This may be + // unreachable. if (ip) { fdo_free(ip); } ip = NULL; } else { - // set the global rvbypass flag to false so that we don't continue the loop - // because of rvbypass + // set the global rvbypass flag to false so that + // we don't continue the loop because of + // rvbypass rvbypass = false; g_fdo_data->state_fn = &_STATE_TO1; - // return true so that TO1 is processed with the remaining directives + // return true so that TO1 is processed with the + // remaining directives ret = true; return ret; } g_fdo_data->state_fn = &_STATE_TO2; - // return true so that TO2 is processed with the remaining directives + // return true so that TO2 is processed with the + // remaining directives ret = true; return ret; } - prot_ctx = fdo_prot_ctx_alloc( - fdo_process_states, &g_fdo_data->prot, ip, dns ? dns->bytes : NULL, port, tls); + prot_ctx = + fdo_prot_ctx_alloc(fdo_process_states, &g_fdo_data->prot, + ip, dns ? dns->bytes : NULL, port, tls); if (prot_ctx == NULL) { ERROR(); return FDO_ABORT; } - if (fdo_prot_ctx_run(prot_ctx) != 0 || g_fdo_data->prot.success == false) { + if (fdo_prot_ctx_run(prot_ctx) != 0 || + g_fdo_data->prot.success == false) { LOG(LOG_ERROR, "TO2 failed.\n"); /* Execute Sv_info type=FAILURE */ if (!fdo_mod_exec_sv_infotype( g_fdo_data->prot.sv_info_mod_list_head, FDO_SI_FAILURE)) { - LOG(LOG_ERROR, "Sv_info: One or more module's FAILURE " - "CB failed\n"); + LOG(LOG_ERROR, + "Sv_info: One or more module's FAILURE " + "CB failed\n"); } - fdo_protTO2Exit(g_fdo_data); + fdo_prot_to2_exit(g_fdo_data); fdo_prot_ctx_free(prot_ctx); fdo_free(prot_ctx); - // Repeat some of the same operations as the failure case above - // when processing RendezvousInfo/RVTO2Addr and they need to be skipped + // Repeat some of the same operations as the failure + // case above when processing RendezvousInfo/RVTO2Addr + // and they need to be skipped if (!rvbypass) { if (ip) { fdo_free(ip); } ip = NULL; - LOG(LOG_INFO, "\nDelaying for %"PRIu64" seconds\n\n", default_delay); + LOG(LOG_INFO, + "\nDelaying for %" PRIu64 " seconds\n\n", + default_delay); fdo_sleep(default_delay); - // if there is another Owner location present, try it - // the execution reaches here only if rvbypass was never set + // if there is another Owner location present, + // try it the execution reaches here only if + // rvbypass was never set if (g_fdo_data->current_rvto2addrentry) { - LOG(LOG_ERROR, "Retrying TO2 using the next RVTO2AddrEntry\n"); + LOG(LOG_ERROR, "Retrying TO2 using the " + "next RVTO2AddrEntry\n"); g_fdo_data->state_fn = &_STATE_TO2; - // return true so that TO2 is processed with the remaining directives + // return true so that TO2 is processed + // with the remaining directives ret = true; return ret; } // there's no more owner locations left to try, - // so start retrying with TO1, if retry is enabled. + // so start retrying with TO1, if retry is + // enabled. if (g_fdo_data->error_recovery) { g_fdo_data->state_fn = &_STATE_TO1; - LOG(LOG_ERROR, "All RVTO2AddreEntry(s) exhausted. " - "Retrying TO1 using the next RendezvousDirective\n"); + LOG(LOG_ERROR, + "All RVTO2AddreEntry(s) exhausted. " + "Retrying TO1 using the next " + "RendezvousDirective\n"); } } else { rvbypass = false; g_fdo_data->state_fn = &_STATE_TO1; - if (g_fdo_data->delaysec == 0 || g_fdo_data->delaysec > max_delay) { + if (g_fdo_data->delaysec == 0 || + g_fdo_data->delaysec > max_delay) { if (!g_fdo_data->current_rvdirective) { - g_fdo_data->delaysec = default_delay_rvinfo_retries; + g_fdo_data->delaysec = + default_delay_rvinfo_retries; } else { - g_fdo_data->delaysec = default_delay; + g_fdo_data->delaysec = + default_delay; } } - LOG(LOG_INFO, "\nDelaying for %"PRIu64" seconds\n\n", g_fdo_data->delaysec); + LOG(LOG_INFO, + "\nDelaying for %" PRIu64 " seconds\n\n", + g_fdo_data->delaysec); } - // if this is last directive (NULL), return false to mark end of 1 retry - // else if there are more directives left, return true for trying those + // if this is last directive (NULL), return false to + // mark end of 1 retry else if there are more directives + // left, return true for trying those if (!g_fdo_data->current_rvdirective) { ret = false; } else { @@ -1720,24 +1866,26 @@ static bool _STATE_TO2(void) // if we reach here no failures occurred and TO2 has completed. // So proceed for shutdown and break. g_fdo_data->state_fn = &_STATE_Shutdown; - fdo_protTO2Exit(g_fdo_data); + fdo_prot_to2_exit(g_fdo_data); fdo_prot_ctx_free(prot_ctx); fdo_free(prot_ctx); if (!rvbypass) { - // free only when rvbypass is false, since the allocation was done then. + // free only when rvbypass is false, since the + // allocation was done then. if (ip) { fdo_free(ip); } ip = NULL; } else { - // set the global rvbypass flag to false so that we don't continue the loop - // because of rvbypass + // set the global rvbypass flag to false so that we + // don't continue the loop because of rvbypass rvbypass = false; } - LOG(LOG_DEBUG, "\n------------------------------------ TO2 Successful " - "--------------------------------------\n\n"); + LOG(LOG_DEBUG, + "\n------------------------------------ TO2 Successful " + "--------------------------------------\n\n"); LOG(LOG_INFO, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"); LOG(LOG_INFO, "@FIDO Device Onboard Complete@\n"); LOG(LOG_INFO, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"); diff --git a/lib/fdoblockio.c b/lib/fdoblockio.c index 3f74bda5..22b3b0cb 100644 --- a/lib/fdoblockio.c +++ b/lib/fdoblockio.c @@ -18,8 +18,8 @@ #include "snprintf_s.h" /** - * Clear the internal buffer of the given fdo_block_t struct by setting the contents to 0, - * upto the internal block size. + * Clear the internal buffer of the given fdo_block_t struct by setting the + * contents to 0, upto the internal block size. * * @param fdo_block_t - struct containg the buffer and its size */ @@ -29,14 +29,16 @@ void fdo_block_reset(fdo_block_t *fdob) return; } if (fdob->block) { - if (fdob->block_size && memset_s(fdob->block, fdob->block_size, 0)) { + if (fdob->block_size && + memset_s(fdob->block, fdob->block_size, 0)) { LOG(LOG_ERROR, "Failed to clear memory\n"); } } } /** - * Allocate memory for the underlying block with default size of 'CBOR_BUFFER_LENGTH'. + * Allocate memory for the underlying block with default size of + * 'CBOR_BUFFER_LENGTH'. * * @param fdo_block_t - struct containg the buffer and its size * @return true if the operation was a success, false otherwise @@ -65,18 +67,19 @@ bool fdo_block_alloc_with_size(fdo_block_t *fdob, size_t block_sz) if (fdob->block != NULL) { fdo_free(fdob->block); } - //Ensure that unsigned integer operations do not wrap + // Ensure that unsigned integer operations do not wrap if (block_sz > SIZE_MAX / sizeof(uint8_t)) { LOG(LOG_ERROR, "FDOBlock alloc() failed!\n"); return false; } fdob->block = fdo_alloc(block_sz * sizeof(uint8_t)); - fdob->block_size = block_sz; if (fdob->block == NULL) { LOG(LOG_ERROR, "FDOBlock alloc() failed!\n"); return false; } + fdob->block_size = block_sz; + if (memset_s(fdob->block, fdob->block_size, 0) != 0) { LOG(LOG_ERROR, "FDOBlock memset() failed!\n"); return false; @@ -89,8 +92,9 @@ bool fdo_block_alloc_with_size(fdo_block_t *fdob, size_t block_sz) // /** - * Clear the contents of the given fdow_t struct alongwith its internal fdo_block_t buffer. - * Memory must have been previously allocated for both fdow_t struct and its internal fdo_block_t. + * Clear the contents of the given fdow_t struct alongwith its internal + * fdo_block_t buffer. Memory must have been previously allocated for both + * fdow_t struct and its internal fdo_block_t. * * @param fdow_t - struct fdow_t * @return true if the operation was a success, false otherwise @@ -111,7 +115,8 @@ bool fdow_init(fdow_t *fdow) } /** - * Set the FDO Type for the given fdow_t struct to prepare for the next CBOR-encode operation. + * Set the FDO Type for the given fdow_t struct to prepare for the next + * CBOR-encode operation. * * @param fdow_t - struct fdow_t * @return 1 if the operation was a success, false otherwise @@ -127,12 +132,12 @@ int fdow_next_block(fdow_t *fdow, int type) } /** - * Allocates for the internal fdow_cbor_encoder_t struct to initialize TinyCBOR's CborEncoder that - * actually does the CBOR encoding. The newly initialized CborEncoder is provided with the - * buffer that will be used to store the CBOR-encoded data, and its maximum size. - * It is the root encoder onto which other CBOR encoders can be added. - * The next and previous pointers to NULL. After this, - * the given fdow_t struct is ready to do CBOR encoding. + * Allocates for the internal fdow_cbor_encoder_t struct to initialize + * TinyCBOR's CborEncoder that actually does the CBOR encoding. The newly + * initialized CborEncoder is provided with the buffer that will be used to + * store the CBOR-encoded data, and its maximum size. It is the root encoder + * onto which other CBOR encoders can be added. The next and previous pointers + * to NULL. After this, the given fdow_t struct is ready to do CBOR encoding. * * @param fdow_t - struct fdow_t * @return true if the operation was a success, false otherwise @@ -158,7 +163,8 @@ bool fdow_encoder_init(fdow_t *fdow) fdow->current->next = NULL; fdow->current->previous = NULL; - cbor_encoder_init(&fdow->current->cbor_encoder, fdow->b.block, fdow->b.block_size, 0); + cbor_encoder_init(&fdow->current->cbor_encoder, fdow->b.block, + fdow->b.block_size, 0); return true; } @@ -167,10 +173,10 @@ bool fdow_encoder_init(fdow_t *fdow) * * It does so by allocating for the internal next pointer and moving to it * (and keeping a refernce in previous) to create a new CborEncoder that - * writes the tag into the pre-initialized buffer. At the end of this, every write operation - * would be done using the newly created CborEncoder making them the items of this array, - * until all the items are written. - * The array needs to be closed using the method fdow_end_array(). + * writes the tag into the pre-initialized buffer. At the end of this, every + * write operation would be done using the newly created CborEncoder making them + * the items of this array, until all the items are written. The array needs to + * be closed using the method fdow_end_array(). * * @param fdow_t - struct fdow_t * @param array_items - total number of elements in the array @@ -190,8 +196,10 @@ bool fdow_start_array(fdow_t *fdow, size_t array_items) fdow->current->next->previous = fdow->current; fdow->current = fdow->current->next; if (cbor_encoder_create_array(&fdow->current->previous->cbor_encoder, - &fdow->current->cbor_encoder, array_items) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to start Major Type 4 (array)\n"); + &fdow->current->cbor_encoder, + array_items) != CborNoError) { + LOG(LOG_ERROR, + "CBOR encoder: Failed to start Major Type 4 (array)\n"); return false; } return true; @@ -202,10 +210,10 @@ bool fdow_start_array(fdow_t *fdow, size_t array_items) * * It does so by allocating for the internal next pointer and moving to it * (and keeping a refernce in previous) to create a new CborEncoder that - * writes the tag into the pre-initialized buffer. At the end of this, every write operation - * would be done using the newly created CborEncoder making them the key-value pairs of this map, - * until all the items are written. - * The map needs to be closed using the method fdow_end_map(). + * writes the tag into the pre-initialized buffer. At the end of this, every + * write operation would be done using the newly created CborEncoder making them + * the key-value pairs of this map, until all the items are written. The map + * needs to be closed using the method fdow_end_map(). * * @param fdow_t - struct fdow_t * @param array_items - total number of key-value pairs in the map @@ -225,8 +233,10 @@ bool fdow_start_map(fdow_t *fdow, size_t map_items) fdow->current->next->previous = fdow->current; fdow->current = fdow->current->next; if (cbor_encoder_create_map(&fdow->current->previous->cbor_encoder, - &fdow->current->cbor_encoder, map_items) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to start Major Type 5 (map)\n"); + &fdow->current->cbor_encoder, + map_items) != CborNoError) { + LOG(LOG_ERROR, + "CBOR encoder: Failed to start Major Type 5 (map)\n"); return false; } return true; @@ -240,15 +250,17 @@ bool fdow_start_map(fdow_t *fdow, size_t map_items) * @param byte_sz - size of the buffer * @return true if the operation was a success, false otherwise */ -bool fdow_byte_string(fdow_t *fdow, uint8_t *bytes , size_t byte_sz) +bool fdow_byte_string(fdow_t *fdow, uint8_t *bytes, size_t byte_sz) { // bytes can be NULL to write empty bstr if (!fdow || !fdow->current) { LOG(LOG_ERROR, "CBOR encoder: Invalid params\n"); return false; } - if (cbor_encode_byte_string(&fdow->current->cbor_encoder, bytes, byte_sz) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to write Major Type 2 (bstr)\n"); + if (cbor_encode_byte_string(&fdow->current->cbor_encoder, bytes, + byte_sz) != CborNoError) { + LOG(LOG_ERROR, + "CBOR encoder: Failed to write Major Type 2 (bstr)\n"); return false; } return true; @@ -262,15 +274,17 @@ bool fdow_byte_string(fdow_t *fdow, uint8_t *bytes , size_t byte_sz) * @param byte_sz - size of the buffer * @return true if the operation was a success, false otherwise */ -bool fdow_text_string(fdow_t *fdow, char *bytes , size_t byte_sz) +bool fdow_text_string(fdow_t *fdow, char *bytes, size_t byte_sz) { // bytes can be NULL to write empty tstr if (!fdow || !fdow->current) { LOG(LOG_ERROR, "CBOR encoder: Invalid params\n"); return false; } - if (cbor_encode_text_string(&fdow->current->cbor_encoder, bytes, byte_sz) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to write Major Type 3 (tstr)\n"); + if (cbor_encode_text_string(&fdow->current->cbor_encoder, bytes, + byte_sz) != CborNoError) { + LOG(LOG_ERROR, + "CBOR encoder: Failed to write Major Type 3 (tstr)\n"); return false; } return true; @@ -289,8 +303,10 @@ bool fdow_signed_int(fdow_t *fdow, int value) LOG(LOG_ERROR, "CBOR encoder: Invalid params\n"); return false; } - if (cbor_encode_int(&fdow->current->cbor_encoder, value) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to write Major Type 1 (negative int)\n"); + if (cbor_encode_int(&fdow->current->cbor_encoder, value) != + CborNoError) { + LOG(LOG_ERROR, "CBOR encoder: Failed to write Major Type 1 " + "(negative int)\n"); return false; } return true; @@ -309,8 +325,10 @@ bool fdow_unsigned_int(fdow_t *fdow, uint64_t value) LOG(LOG_ERROR, "CBOR encoder: Invalid params\n"); return false; } - if (cbor_encode_uint(&fdow->current->cbor_encoder, value) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to write Major Type 0 (uint)\n"); + if (cbor_encode_uint(&fdow->current->cbor_encoder, value) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR encoder: Failed to write Major Type 0 (uint)\n"); return false; } return true; @@ -329,8 +347,10 @@ bool fdow_boolean(fdow_t *fdow, bool value) LOG(LOG_ERROR, "CBOR encoder: Invalid params\n"); return false; } - if (cbor_encode_boolean(&fdow->current->cbor_encoder, value) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to write Major Type 7 (bool)\n"); + if (cbor_encode_boolean(&fdow->current->cbor_encoder, value) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR encoder: Failed to write Major Type 7 (bool)\n"); return false; } return true; @@ -349,7 +369,8 @@ bool fdow_null(fdow_t *fdow) return false; } if (cbor_encode_null(&fdow->current->cbor_encoder) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to write Major Type 7 (NULL)\n"); + LOG(LOG_ERROR, + "CBOR encoder: Failed to write Major Type 7 (NULL)\n"); return false; } return true; @@ -378,9 +399,10 @@ bool fdow_tag(fdow_t *fdow, uint64_t tag) /** * Mark the completion of writing elements into a CBOR array (Major Type 4). * - * It moves back to previous CborEncoder and frees the node containing the current - * CborEncoder (next), closing the array. At the end of this, every write operation - * would be done using the previous CborEncoder (represented by current). + * It moves back to previous CborEncoder and frees the node containing the + * current CborEncoder (next), closing the array. At the end of this, every + * write operation would be done using the previous CborEncoder (represented by + * current). * * @param fdow_t - struct fdow_t * @return true if the operation was a success, false otherwise @@ -394,7 +416,8 @@ bool fdow_end_array(fdow_t *fdow) if (cbor_encoder_close_container_checked( &fdow->current->previous->cbor_encoder, &fdow->current->cbor_encoder) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to end Major Type 4 (array)\n"); + LOG(LOG_ERROR, + "CBOR encoder: Failed to end Major Type 4 (array)\n"); return false; } // move backwards and free next @@ -406,9 +429,10 @@ bool fdow_end_array(fdow_t *fdow) /** * Mark the completion of writing elements into a CBOR map (Major Type 5). * - * It moves back to previous CborEncoder and frees the node containing the current - * CborEncoder (next), closing the map. At the end of this, every write operation - * would be done using the previous CborEncoder (represented by current). + * It moves back to previous CborEncoder and frees the node containing the + * current CborEncoder (next), closing the map. At the end of this, every write + * operation would be done using the previous CborEncoder (represented by + * current). * * @param fdow_t - struct fdow_t * @return true if the operation was a success, false otherwise @@ -422,7 +446,8 @@ bool fdow_end_map(fdow_t *fdow) if (cbor_encoder_close_container_checked( &fdow->current->previous->cbor_encoder, &fdow->current->cbor_encoder) != CborNoError) { - LOG(LOG_ERROR, "CBOR encoder: Failed to end Major Type 5 (map)\n"); + LOG(LOG_ERROR, + "CBOR encoder: Failed to end Major Type 5 (map)\n"); return false; } // move backwards and free next @@ -432,24 +457,27 @@ bool fdow_end_map(fdow_t *fdow) } /** - * Store the length of the CBOR data that has been written so far to the supplied buffer - * (fdow_t.fdo_block_t.block) in the output size_t variable. + * Store the length of the CBOR data that has been written so far to the + * supplied buffer (fdow_t.fdo_block_t.block) in the output size_t variable. * * @param fdow_t - struct fdow_t * @param length out pointer where the length will stored * @return true if the operation was a success, false otherwise */ -bool fdow_encoded_length(fdow_t *fdow, size_t *length) { +bool fdow_encoded_length(fdow_t *fdow, size_t *length) +{ if (!fdow || !fdow->current || !length) { LOG(LOG_ERROR, "CBOR encoder: Invalid params\n"); return false; } - *length = cbor_encoder_get_buffer_size(&fdow->current->cbor_encoder, fdow->b.block); + *length = cbor_encoder_get_buffer_size(&fdow->current->cbor_encoder, + fdow->b.block); return true; } /** - * Clear and deallocate the internal buffer (fdow_t.fdo_block_t.block) alongwith the current node. + * Clear and deallocate the internal buffer (fdow_t.fdo_block_t.block) alongwith + * the current node. * * @param fdow_t - struct fdow_t */ @@ -476,8 +504,9 @@ void fdow_flush(fdow_t *fdow) // /** - * Clear the contents of the given fdor_t struct alongwith its internal fdo_block_t buffer. - * Memory must have been previously allocated for both fdor_t struct and its internal fdo_block_t. + * Clear the contents of the given fdor_t struct alongwith its internal + * fdo_block_t buffer. Memory must have been previously allocated for both + * fdor_t struct and its internal fdo_block_t. * * @param fdor_t - struct fdor_t * @return true if the operation was a success, false otherwise @@ -497,24 +526,25 @@ bool fdor_init(fdor_t *fdor) } /** - * Allocates for the internal fdor_cbor_decoder_t struct to initialize TinyCBOR's CborParser that - * actually does the CBOR decoding. The newly initialized CborDecoder is provided with the - * buffer that contains the CBOR-encoded data (the data to be decoded), its maximum size, - * and TinyCbor's CborValue. - * It is the root decoder that takes as many CborValue's as the number of arrays/maps to be read. - * The next and previous pointers to NULL. After this, - * the given fdor_t struct is ready to do CBOR decoding. + * Allocates for the internal fdor_cbor_decoder_t struct to initialize + * TinyCBOR's CborParser that actually does the CBOR decoding. The newly + * initialized CborDecoder is provided with the buffer that contains the + * CBOR-encoded data (the data to be decoded), its maximum size, and TinyCbor's + * CborValue. It is the root decoder that takes as many CborValue's as the + * number of arrays/maps to be read. The next and previous pointers to NULL. + * After this, the given fdor_t struct is ready to do CBOR decoding. * * @param fdor_t - struct fdor_t * @return true if the operation was a success, false otherwise */ -bool fdor_parser_init(fdor_t *fdor) { +bool fdor_parser_init(fdor_t *fdor) +{ if (!fdor) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } // if there's a current block, free and then alloc - if (fdor->current){ + if (fdor->current) { while (fdor->current->previous) { fdor->current = fdor->current->previous; fdo_free(fdor->current->next); @@ -528,9 +558,11 @@ bool fdor_parser_init(fdor_t *fdor) { fdor->current->next = NULL; fdor->current->previous = NULL; - if (cbor_parser_init(fdor->b.block, fdor->b.block_size, 0, &fdor->cbor_parser, - &fdor->current->cbor_value) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to initialize CBOR Parser\n"); + if (cbor_parser_init(fdor->b.block, fdor->b.block_size, 0, + &fdor->cbor_parser, + &fdor->current->cbor_value) != CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to initialize CBOR Parser\n"); return false; } return true; @@ -542,13 +574,14 @@ bool fdor_parser_init(fdor_t *fdor) { * It does so by allocating for the internal next pointer and moving to it * (and keeping a refernce in previous) to create a new CborValue that * reads the tag from the input buffer. At the end of this, every read operation - * would be done using the newly created CborValue treating them as the items of this array. - * The array needs to be closed using the method fdor_end_array(). + * would be done using the newly created CborValue treating them as the items of + * this array. The array needs to be closed using the method fdor_end_array(). * * @param fdor_t - struct fdor_t * @return true if the operation was a success, false otherwise */ -bool fdor_start_array(fdor_t *fdor) { +bool fdor_start_array(fdor_t *fdor) +{ if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; @@ -561,9 +594,11 @@ bool fdor_start_array(fdor_t *fdor) { fdor->current->next->previous = fdor->current; fdor->current = fdor->current->next; if (!cbor_value_is_array(&fdor->current->previous->cbor_value) || - cbor_value_enter_container(&fdor->current->previous->cbor_value, - &fdor->current->cbor_value) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to start Major Type 4 (array)\n"); + cbor_value_enter_container(&fdor->current->previous->cbor_value, + &fdor->current->cbor_value) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to start Major Type 4 (array)\n"); return false; } return true; @@ -575,13 +610,14 @@ bool fdor_start_array(fdor_t *fdor) { * It does so by allocating for the internal next pointer and moving to it * (and keeping a refernce in previous) to create a new CborValue that * reads the tag from the input buffer. At the end of this, every read operation - * would be done using the newly created CborValue treating them as the items of this map. - * The map needs to be closed using the method fdor_end_map(). + * would be done using the newly created CborValue treating them as the items of + * this map. The map needs to be closed using the method fdor_end_map(). * * @param fdor_t - struct fdor_t * @return true if the operation was a success, false otherwise */ -bool fdor_start_map(fdor_t *fdor) { +bool fdor_start_map(fdor_t *fdor) +{ if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; @@ -594,73 +630,86 @@ bool fdor_start_map(fdor_t *fdor) { fdor->current->next->previous = fdor->current; fdor->current = fdor->current->next; if (!cbor_value_is_map(&fdor->current->previous->cbor_value) || - cbor_value_enter_container(&fdor->current->previous->cbor_value, - &fdor->current->cbor_value) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to start Major Type 4 (array)\n"); + cbor_value_enter_container(&fdor->current->previous->cbor_value, + &fdor->current->cbor_value) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to start Major Type 4 (array)\n"); return false; } return true; } /** - * Store the number of items in the CBOR array (Major Type 4) into the supplied size_t variable. + * Store the number of items in the CBOR array (Major Type 4) into the supplied + * size_t variable. * * @param fdor_t - struct fdor_t - * @param length - output variable where the array's number of items will be stored + * @param length - output variable where the array's number of items will be + * stored * @return true if the operation was a success, false otherwise */ -bool fdor_array_length(fdor_t *fdor, size_t *length) { +bool fdor_array_length(fdor_t *fdor, size_t *length) +{ if (!fdor || !fdor->current || !length) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_array(&fdor->current->cbor_value) || - cbor_value_get_array_length(&fdor->current->cbor_value, - length) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to read length of Major Type 4 (array)\n"); + cbor_value_get_array_length(&fdor->current->cbor_value, length) != + CborNoError) { + LOG(LOG_ERROR, "CBOR decoder: Failed to read length of Major " + "Type 4 (array)\n"); return false; } return true; } /** - * Store the number of items in the CBOR map (Major Type 5) into the supplied size_t variable. + * Store the number of items in the CBOR map (Major Type 5) into the supplied + * size_t variable. * * @param fdor_t - struct fdor_t - * @param length - output variable where the array's number of items will be stored + * @param length - output variable where the array's number of items will be + * stored * @return true if the operation was a success, false otherwise */ -bool fdor_map_length(fdor_t *fdor, size_t *length) { +bool fdor_map_length(fdor_t *fdor, size_t *length) +{ if (!fdor || !fdor->current || !length) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_map(&fdor->current->cbor_value) || - cbor_value_get_map_length(&fdor->current->cbor_value, - length) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to read length of Major Type 5 (map)\n"); + cbor_value_get_map_length(&fdor->current->cbor_value, length) != + CborNoError) { + LOG(LOG_ERROR, "CBOR decoder: Failed to read length of Major " + "Type 5 (map)\n"); return false; } return true; } /** - * Store the CBOR bstr/tstr (Major Type 2/3) length into the supplied size_t variable. + * Store the CBOR bstr/tstr (Major Type 2/3) length into the supplied size_t + * variable. * * @param fdor_t - struct fdor_t * @param length - output variable where the string length will be stored * @return true if the operation was a success, false otherwise */ -bool fdor_string_length(fdor_t *fdor, size_t *length) { +bool fdor_string_length(fdor_t *fdor, size_t *length) +{ if (!fdor || !fdor->current || !length) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if ((!cbor_value_is_byte_string(&fdor->current->cbor_value) && - !cbor_value_is_text_string(&fdor->current->cbor_value)) || - cbor_value_calculate_string_length(&fdor->current->cbor_value, - length) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to read length of Major Type 2/3 (bstr/tstr)\n"); + !cbor_value_is_text_string(&fdor->current->cbor_value)) || + cbor_value_calculate_string_length(&fdor->current->cbor_value, + length) != CborNoError) { + LOG(LOG_ERROR, "CBOR decoder: Failed to read length of Major " + "Type 2/3 (bstr/tstr)\n"); return false; } return true; @@ -674,16 +723,18 @@ bool fdor_string_length(fdor_t *fdor, size_t *length) { * @param buffer_length - size of the buffer * @return true if the operation was a success, false otherwise */ -bool fdor_byte_string(fdor_t *fdor, uint8_t *buffer, size_t buffer_length) { +bool fdor_byte_string(fdor_t *fdor, uint8_t *buffer, size_t buffer_length) +{ // buffer can be NULL to read empty bstr if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_byte_string(&fdor->current->cbor_value) || - cbor_value_copy_byte_string(&fdor->current->cbor_value, buffer, &buffer_length, NULL) - != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to read Major Type 2 (bstr)\n"); + cbor_value_copy_byte_string(&fdor->current->cbor_value, buffer, + &buffer_length, NULL) != CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to read Major Type 2 (bstr)\n"); return false; } if (!fdor_next(fdor)) { @@ -700,16 +751,18 @@ bool fdor_byte_string(fdor_t *fdor, uint8_t *buffer, size_t buffer_length) { * @param buffer_length - size of the buffer * @return true if the operation was a success, false otherwise */ -bool fdor_text_string(fdor_t *fdor, char *buffer, size_t buffer_length) { +bool fdor_text_string(fdor_t *fdor, char *buffer, size_t buffer_length) +{ // buffer can be NULL to read empty tstr if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_text_string(&fdor->current->cbor_value) || - cbor_value_copy_text_string(&fdor->current->cbor_value, buffer, &buffer_length, NULL) - != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to read Major Type 3 (tstr)\n"); + cbor_value_copy_text_string(&fdor->current->cbor_value, buffer, + &buffer_length, NULL) != CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to read Major Type 3 (tstr)\n"); return false; } if (!fdor_next(fdor)) { @@ -719,12 +772,14 @@ bool fdor_text_string(fdor_t *fdor, char *buffer, size_t buffer_length) { } /** - * Check if the current value is CBOR NULL (Major Type 7, Additional Info 22) value. + * Check if the current value is CBOR NULL (Major Type 7, Additional Info 22) + * value. * * @param fdor_t - struct fdor_t * @return true if value is CBOR NULL, false otherwise */ -bool fdor_is_value_null(fdor_t *fdor) { +bool fdor_is_value_null(fdor_t *fdor) +{ if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; @@ -738,7 +793,8 @@ bool fdor_is_value_null(fdor_t *fdor) { * @param fdor_t - struct fdor_t * @return true if the current value is integer, false otherwise */ -bool fdor_is_value_signed_int(fdor_t *fdor) { +bool fdor_is_value_signed_int(fdor_t *fdor) +{ if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; @@ -753,15 +809,17 @@ bool fdor_is_value_signed_int(fdor_t *fdor) { * @param result - output variable where the read integer will be stored * @return true if the operation was a success, false otherwise */ -bool fdor_signed_int(fdor_t *fdor, int *result) { +bool fdor_signed_int(fdor_t *fdor, int *result) +{ if (!fdor || !fdor->current || !result) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_integer(&fdor->current->cbor_value) || - cbor_value_get_int(&fdor->current->cbor_value, result) - != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to read Major Type 1 (negative int)\n"); + cbor_value_get_int(&fdor->current->cbor_value, result) != + CborNoError) { + LOG(LOG_ERROR, "CBOR decoder: Failed to read Major Type 1 " + "(negative int)\n"); return false; } if (!fdor_next(fdor)) { @@ -777,15 +835,17 @@ bool fdor_signed_int(fdor_t *fdor, int *result) { * @param result - output variable where the read integer will be stored * @return true if the operation was a success, false otherwise */ -bool fdor_unsigned_int(fdor_t *fdor, uint64_t *result) { +bool fdor_unsigned_int(fdor_t *fdor, uint64_t *result) +{ if (!fdor || !fdor->current || !result) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_unsigned_integer(&fdor->current->cbor_value) || - cbor_value_get_uint64(&fdor->current->cbor_value, result) - != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to read Major Type 0 (uint)\n"); + cbor_value_get_uint64(&fdor->current->cbor_value, result) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to read Major Type 0 (uint)\n"); return false; } if (!fdor_next(fdor)) { @@ -801,15 +861,17 @@ bool fdor_unsigned_int(fdor_t *fdor, uint64_t *result) { * @param result - output variable where the read bool will be stored * @return true if the operation was a success, false otherwise */ -bool fdor_boolean(fdor_t *fdor, bool *result) { +bool fdor_boolean(fdor_t *fdor, bool *result) +{ if (!fdor || !fdor->current || !result) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_boolean(&fdor->current->cbor_value) || - cbor_value_get_boolean(&fdor->current->cbor_value, result) - != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to start Major Type 7 (bool)\n"); + cbor_value_get_boolean(&fdor->current->cbor_value, result) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to start Major Type 7 (bool)\n"); return false; } if (!fdor_next(fdor)) { @@ -825,14 +887,15 @@ bool fdor_boolean(fdor_t *fdor, bool *result) { * @param result - output variable where the read Tag will be stored * @return true if the operation was a success, false otherwise */ -bool fdor_tag(fdor_t *fdor, uint64_t *result) { +bool fdor_tag(fdor_t *fdor, uint64_t *result) +{ if (!fdor || !fdor->current || !result) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_tag(&fdor->current->cbor_value) || - cbor_value_get_tag(&fdor->current->cbor_value, result) - != CborNoError) { + cbor_value_get_tag(&fdor->current->cbor_value, result) != + CborNoError) { LOG(LOG_ERROR, "CBOR decoder: Failed to read Tag\n"); return false; } @@ -852,16 +915,19 @@ bool fdor_tag(fdor_t *fdor, uint64_t *result) { * @param fdor_t - struct fdor_t * @return true if the operation was a success, false otherwise */ -bool fdor_end_array(fdor_t *fdor) { +bool fdor_end_array(fdor_t *fdor) +{ if (!fdor || !fdor->current || !fdor->current->previous) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_array(&fdor->current->previous->cbor_value) || - !cbor_value_at_end(&fdor->current->cbor_value) || - cbor_value_leave_container(&fdor->current->previous->cbor_value, - &fdor->current->cbor_value) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to end Major Type 4 (array)\n"); + !cbor_value_at_end(&fdor->current->cbor_value) || + cbor_value_leave_container(&fdor->current->previous->cbor_value, + &fdor->current->cbor_value) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to end Major Type 4 (array)\n"); return false; } // move backwards and free next @@ -880,16 +946,19 @@ bool fdor_end_array(fdor_t *fdor) { * @param fdor_t - struct fdor_t * @return true if the operation was a success, false otherwise */ -bool fdor_end_map(fdor_t *fdor) { +bool fdor_end_map(fdor_t *fdor) +{ if (!fdor || !fdor->current || !fdor->current->previous) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } if (!cbor_value_is_map(&fdor->current->previous->cbor_value) || - !cbor_value_at_end(&fdor->current->cbor_value) || - cbor_value_leave_container(&fdor->current->previous->cbor_value, - &fdor->current->cbor_value) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Failed to end Major Type 4 (array)\n"); + !cbor_value_at_end(&fdor->current->cbor_value) || + cbor_value_leave_container(&fdor->current->previous->cbor_value, + &fdor->current->cbor_value) != + CborNoError) { + LOG(LOG_ERROR, + "CBOR decoder: Failed to end Major Type 4 (array)\n"); return false; } // move backwards and free next @@ -899,13 +968,15 @@ bool fdor_end_map(fdor_t *fdor) { } /** - * Determine if the given buffer points to a map and whether it contains unread/unparsed - * elements (keys/values). + * Determine if the given buffer points to a map and whether it contains + * unread/unparsed elements (keys/values). * * @param fdor_t - struct fdor_t - * @return true if the map contains keys/values to be read/parsed, false otherwise + * @return true if the map contains keys/values to be read/parsed, false + * otherwise */ -bool fdor_map_has_more(fdor_t *fdor) { +bool fdor_map_has_more(fdor_t *fdor) +{ if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; @@ -923,7 +994,8 @@ bool fdor_map_has_more(fdor_t *fdor) { * @param fdor_t - struct fdor_t * @return true if the operation was a success, false otherwise */ -bool fdor_next(fdor_t *fdor) { +bool fdor_next(fdor_t *fdor) +{ if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; @@ -941,20 +1013,24 @@ bool fdor_next(fdor_t *fdor) { * @param fdor_t - struct fdor_t * @return true if the stream is CBOR-encoded correctly, false otherwise */ -bool fdor_is_valid_cbor(fdor_t *fdor) { +bool fdor_is_valid_cbor(fdor_t *fdor) +{ if (!fdor || !fdor->current) { LOG(LOG_ERROR, "CBOR decoder: Invalid params\n"); return false; } - if (cbor_value_validate(&fdor->current->cbor_value, CborValidateBasic) != CborNoError) { - LOG(LOG_ERROR, "CBOR decoder: Incorrectly or non-CBOR encoded stream encountered.\n"); + if (cbor_value_validate(&fdor->current->cbor_value, + CborValidateBasic) != CborNoError) { + LOG(LOG_ERROR, "CBOR decoder: Incorrectly or non-CBOR encoded " + "stream encountered.\n"); return false; } return true; } /** - * Clear and deallocate the internal buffer (fdor_t.fdo_block_t.block) alongwith the current node. + * Clear and deallocate the internal buffer (fdor_t.fdo_block_t.block) alongwith + * the current node. * * @param fdor_t - struct fdor_t */ diff --git a/lib/fdocred.c b/lib/fdocred.c index 93c3c001..d28030f3 100644 --- a/lib/fdocred.c +++ b/lib/fdocred.c @@ -9,7 +9,7 @@ * defined format. */ -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include "util.h" #include "fdoprot.h" #include "fdocred.h" @@ -152,27 +152,29 @@ fdo_hash_t *fdo_pub_key_hash(fdo_public_key_t *pub_key) // Calculate the hash of the mfg_pub_key fdow_t *fdow = fdo_alloc(sizeof(fdow_t)); if (!fdow_init(fdow) || - !fdo_block_alloc_with_size(&fdow->b, pub_key->key1->byte_sz + BUFF_SIZE_128_BYTES) || - !fdow_encoder_init(fdow)) { + !fdo_block_alloc_with_size(&fdow->b, pub_key->key1->byte_sz + + BUFF_SIZE_128_BYTES) || + !fdow_encoder_init(fdow)) { LOG(LOG_ERROR, "Failed to initialize FDOW\n"); return NULL; } - fdo_hash_t *hash = fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); + fdo_hash_t *hash = + fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); if (!hash) { return NULL; } fdo_public_key_write(fdow, pub_key); size_t encoded_pk_length = 0; - if (!fdow_encoded_length(fdow, &encoded_pk_length) || encoded_pk_length == 0) { + if (!fdow_encoded_length(fdow, &encoded_pk_length) || + encoded_pk_length == 0) { LOG(LOG_ERROR, "Failed to get PubKey encoded length\n"); fdo_hash_free(hash); return NULL; } fdow->b.block_size = encoded_pk_length; - if ((0 != fdo_crypto_hash(fdow->b.block, - fdow->b.block_size, + if ((0 != fdo_crypto_hash(fdow->b.block, fdow->b.block_size, hash->hash->bytes, hash->hash->byte_sz))) { fdo_hash_free(hash); return NULL; @@ -297,32 +299,33 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader) } if (memset_s(&fdor, sizeof(fdor_t), 0) != 0) { - LOG(LOG_ERROR, "OVheader: Failed to intialize temporary FDOR\n"); + LOG(LOG_ERROR, + "OVheader: Failed to intialize temporary FDOR\n"); return NULL; } if (!fdor_init(&fdor) || - !fdo_block_alloc_with_size(&fdor.b, ovheader->byte_sz)) { - LOG(LOG_ERROR, - "OVHeader: Failed to setup temporary FDOR\n"); + !fdo_block_alloc_with_size(&fdor.b, ovheader->byte_sz)) { + LOG(LOG_ERROR, "OVHeader: Failed to setup temporary FDOR\n"); goto exit; } - if (0 != memcpy_s(fdor.b.block, fdor.b.block_size, - ovheader->bytes, ovheader->byte_sz)) { - LOG(LOG_ERROR, - "OVHeader: Failed to copy temporary data\n"); + if (0 != memcpy_s(fdor.b.block, fdor.b.block_size, ovheader->bytes, + ovheader->byte_sz)) { + LOG(LOG_ERROR, "OVHeader: Failed to copy temporary data\n"); goto exit; } if (!fdor_parser_init(&fdor)) { LOG(LOG_ERROR, - "OVHeader: Failed to init temporary FDOR parser\n"); + "OVHeader: Failed to init temporary FDOR parser\n"); goto exit; } // OVHeader is of size 6 always. if (!fdor_array_length(&fdor, &num_ov_items) || num_ov_items != 6) { - LOG(LOG_ERROR, "%s Invalid OVHeader: Invalid OVHeader array length\n", __func__); + LOG(LOG_ERROR, + "%s Invalid OVHeader: Invalid OVHeader array length\n", + __func__); goto exit; } @@ -331,15 +334,19 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader) goto exit; } - if (!fdor_signed_int(&fdor, &ov->prot_version) || ov->prot_version != FDO_PROT_SPEC_VERSION) { + if (!fdor_signed_int(&fdor, &ov->prot_version) || + ov->prot_version != FDO_PROT_SPEC_VERSION) { // Protocol Version - LOG(LOG_ERROR, "%s Invalid OVHeader: Invalid OVProtVer\n", __func__); + LOG(LOG_ERROR, "%s Invalid OVHeader: Invalid OVProtVer\n", + __func__); goto exit; } size_t ov_guid_length; - if (!fdor_string_length(&fdor, &ov_guid_length) || ov_guid_length != FDO_GUID_BYTES) { - LOG(LOG_ERROR, "%s Invalid OVHeader: Invalid OVGuid Length\n", __func__); + if (!fdor_string_length(&fdor, &ov_guid_length) || + ov_guid_length != FDO_GUID_BYTES) { + LOG(LOG_ERROR, "%s Invalid OVHeader: Invalid OVGuid Length\n", + __func__); goto exit; } ov->g2 = fdo_byte_array_alloc(ov_guid_length); @@ -348,7 +355,8 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader) } ov->g2->byte_sz = ov_guid_length; if (!fdor_byte_string(&fdor, ov->g2->bytes, ov->g2->byte_sz)) { - LOG(LOG_ERROR, "%s Invalid OVHeader: Unable to decode OVGuid\n", __func__); + LOG(LOG_ERROR, "%s Invalid OVHeader: Unable to decode OVGuid\n", + __func__); goto exit; } @@ -356,27 +364,34 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader) ov->rvlst2 = fdo_rendezvous_list_alloc(); if (!ov->rvlst2 || !fdo_rendezvous_list_read(&fdor, ov->rvlst2)) { - LOG(LOG_ERROR, "%s Invalid OVHeader: Unable to decode OVRvInfo\n", __func__); + LOG(LOG_ERROR, + "%s Invalid OVHeader: Unable to decode OVRvInfo\n", + __func__); goto exit; } /* There must be at-least 1 valid rv entry, if not its a error-case */ if (ov->rvlst2->num_rv_directives == 0) { - LOG(LOG_ERROR, - "Invalid OVHeader: All rendezvous entries are invalid for the device!\n"); + LOG(LOG_ERROR, "Invalid OVHeader: All rendezvous entries are " + "invalid for the device!\n"); goto exit; } // Device_info String size_t dev_info_length; if (!fdor_string_length(&fdor, &dev_info_length)) { - LOG(LOG_ERROR, "%s Invalid OVHeader: Unable to decode OVDeviceInfo length\n", __func__); + LOG(LOG_ERROR, + "%s Invalid OVHeader: Unable to decode OVDeviceInfo " + "length\n", + __func__); goto exit; } ov->dev_info = fdo_string_alloc_size(dev_info_length); if (!ov->dev_info || - !fdor_text_string(&fdor, ov->dev_info->bytes, dev_info_length)) { - LOG(LOG_ERROR, "%s Invalid OVHeader: Unable to decode OVDeviceInfo\n", __func__); + !fdor_text_string(&fdor, ov->dev_info->bytes, dev_info_length)) { + LOG(LOG_ERROR, + "%s Invalid OVHeader: Unable to decode OVDeviceInfo\n", + __func__); goto exit; } ov->dev_info->bytes[dev_info_length] = '\0'; @@ -388,7 +403,8 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader) ov->mfg_pub_key = fdo_public_key_read(&fdor); // Creates a Public key and fills it in if (ov->mfg_pub_key == NULL) { - LOG(LOG_ERROR, "%s Invalid OVHeader: Unable to decode PubKey\n", __func__); + LOG(LOG_ERROR, "%s Invalid OVHeader: Unable to decode PubKey\n", + __func__); goto exit; } @@ -400,7 +416,8 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader) } if (!fdo_hash_read(&fdor, ov->hdc)) { - LOG(LOG_ERROR, "Invalid OVHeader: Unable to decode OVDevCertChainHash\n"); + LOG(LOG_ERROR, + "Invalid OVHeader: Unable to decode OVDevCertChainHash\n"); goto exit; } @@ -421,8 +438,9 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader) #if defined(DEVICE_CSE_ENABLED) /** - * Given an OwnershipVoucher header (OVHeader), proceed to load and compares with - * stored OVHeader from CSE. If verfication succeed it returns the stored HMAC. + * Given an OwnershipVoucher header (OVHeader), proceed to load and compares + * with stored OVHeader from CSE. If verfication succeed it returns the stored + * HMAC. * @param ovheader - the received CBOR-encoded OVHeader * @param hmac a place top store the resulting HMAC * @return true if hmac was successfully load and verified, false otherwise. @@ -439,7 +457,8 @@ bool fdo_ov_hdr_cse_load_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac) int result_memcmp = 0; fdo_byte_array_t *ovh_data = NULL; - *hmac = fdo_hash_alloc(FDO_CRYPTO_HMAC_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); + *hmac = + fdo_hash_alloc(FDO_CRYPTO_HMAC_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); if (!*hmac) { LOG(LOG_ERROR, "Failed to alloc for OVHeaderHmac\n"); goto exit; @@ -447,23 +466,24 @@ bool fdo_ov_hdr_cse_load_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac) ovh_data = fdo_byte_array_alloc(FDO_MAX_FILE_SIZE); if (!ovh_data) { - LOG(LOG_ERROR,"Invalid OVHeader read: Failed to allocate data for storing OVH data\n"); + LOG(LOG_ERROR, "Invalid OVHeader read: Failed to allocate data " + "for storing OVH data\n"); goto exit; } if (0 != cse_load_file(OVH_FILE_ID, ovh_data->bytes, &ovh_len, - (*hmac)->hash->bytes, (*hmac)->hash->byte_sz)) { - LOG(LOG_ERROR, "Invalid OVHeader read: Unable to load file form CSE\n"); + (*hmac)->hash->bytes, (*hmac)->hash->byte_sz)) { + LOG(LOG_ERROR, + "Invalid OVHeader read: Unable to load file form CSE\n"); goto exit; } ovh_data->byte_sz = ovh_len; - ret = memcmp_s(ovh_data->bytes, - ovh_data->byte_sz, - ovheader->bytes, + ret = memcmp_s(ovh_data->bytes, ovh_data->byte_sz, ovheader->bytes, ovheader->byte_sz, &result_memcmp); if (ret || result_memcmp != 0) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Invalid OVH received over OVHeader\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Invalid OVH received over OVHeader\n"); ret = false; goto exit; } @@ -477,7 +497,6 @@ bool fdo_ov_hdr_cse_load_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac) } return ret; - } #endif /** @@ -486,7 +505,8 @@ bool fdo_ov_hdr_cse_load_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac) * @param hmac a place top store the resulting HMAC * @return true if hmac was successfully generated, false otherwise. */ -bool fdo_ov_hdr_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac) { +bool fdo_ov_hdr_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac) +{ if (!ovheader || !hmac) { return false; @@ -510,7 +530,7 @@ bool fdo_ov_hdr_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac) { } ret = true; -exit : +exit: return ret; } @@ -529,8 +549,10 @@ exit : * @param num_ov_items - number of items in ownership voucher header * @return true if hmac was successfully generated, false otherwise. */ -bool fdo_ovheader_write(fdow_t *fdow, int protver, fdo_byte_array_t *guid, fdo_rendezvous_list_t *rvlst, - fdo_string_t *dev_info, fdo_public_key_t *pubkey, fdo_hash_t *hdc) { +bool fdo_ovheader_write(fdow_t *fdow, int protver, fdo_byte_array_t *guid, + fdo_rendezvous_list_t *rvlst, fdo_string_t *dev_info, + fdo_public_key_t *pubkey, fdo_hash_t *hdc) +{ if (!fdow_start_array(fdow, 6)) { LOG(LOG_ERROR, "OVHeader: Failed to start array\n"); @@ -557,7 +579,8 @@ bool fdo_ovheader_write(fdow_t *fdow, int protver, fdo_byte_array_t *guid, fdo_r return false; } if (!fdo_hash_write(fdow, hdc)) { - LOG(LOG_ERROR, "OVHeader: Failed to write OVDevCertChainHash\n"); + LOG(LOG_ERROR, + "OVHeader: Failed to write OVDevCertChainHash\n"); return false; } if (!fdow_end_array(fdow)) { @@ -575,36 +598,42 @@ bool fdo_ovheader_write(fdow_t *fdow, int protver, fdo_byte_array_t *guid, fdo_r * @param ov - pointer to the fdo_ownership_voucher_t object * @return true if operation is a success, false otherwise */ -bool fdo_ove_hash_hdr_info_save(fdo_ownership_voucher_t *ov) { +bool fdo_ove_hash_hdr_info_save(fdo_ownership_voucher_t *ov) +{ bool ret = false; // calculate and save OVEHashHdrInfo (hash[GUID||DeviceInfo]) // Header Hash Info is of length OVGuid length + OVDeviceInfo length - uint8_t *hash_hdr_info = fdo_alloc(ov->g2->byte_sz + ov->dev_info->byte_sz); + uint8_t *hash_hdr_info = + fdo_alloc(ov->g2->byte_sz + ov->dev_info->byte_sz); if (!hash_hdr_info) { - LOG(LOG_ERROR, "OVEHashHdrInfo: Failed to alloc for OVEHashHdrInfo\n"); + LOG(LOG_ERROR, + "OVEHashHdrInfo: Failed to alloc for OVEHashHdrInfo\n"); goto exit; } - if (0 != memcpy_s(hash_hdr_info, ov->g2->byte_sz, - ov->g2->bytes, ov->g2->byte_sz)) { + if (0 != memcpy_s(hash_hdr_info, ov->g2->byte_sz, ov->g2->bytes, + ov->g2->byte_sz)) { LOG(LOG_ERROR, "OVEHashHdrInfo: Failed to copy GUID\n"); goto exit; } - if (0 != memcpy_s(hash_hdr_info + ov->g2->byte_sz, ov->dev_info->byte_sz, - ov->dev_info->bytes, ov->dev_info->byte_sz)) { + if (0 != memcpy_s(hash_hdr_info + ov->g2->byte_sz, + ov->dev_info->byte_sz, ov->dev_info->bytes, + ov->dev_info->byte_sz)) { LOG(LOG_ERROR, "OVEHashHdrInfo: Failed to copy DeviceInfo\n"); goto exit; } - ov->ov_entries->hc_hash = fdo_hash_alloc( - FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); - if (!ov->ov_entries->hc_hash){ - LOG(LOG_ERROR, "OVEHashHdrInfo: Failed to alloc OVEHashHdrInfo in storage\n"); + ov->ov_entries->hc_hash = + fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); + if (!ov->ov_entries->hc_hash) { + LOG(LOG_ERROR, "OVEHashHdrInfo: Failed to alloc OVEHashHdrInfo " + "in storage\n"); goto exit; } - if (0 != fdo_crypto_hash(hash_hdr_info, ov->g2->byte_sz + ov->dev_info->byte_sz, - ov->ov_entries->hc_hash->hash->bytes, - ov->ov_entries->hc_hash->hash->byte_sz)) { + if (0 != fdo_crypto_hash(hash_hdr_info, + ov->g2->byte_sz + ov->dev_info->byte_sz, + ov->ov_entries->hc_hash->hash->bytes, + ov->ov_entries->hc_hash->hash->byte_sz)) { LOG(LOG_ERROR, "OVEHashHdrInfo: Failed to generate hash\n"); goto exit; } @@ -627,7 +656,8 @@ bool fdo_ove_hash_hdr_info_save(fdo_ownership_voucher_t *ov) { * @return true if operation is a success, false otherwise */ bool fdo_ove_hash_prev_entry_save(fdow_t *fdow, fdo_ownership_voucher_t *ov, - fdo_hash_t *hmac) { + fdo_hash_t *hmac) +{ bool ret = false; fdo_byte_array_t *enc_ovheader = NULL; @@ -640,19 +670,22 @@ bool fdo_ove_hash_prev_entry_save(fdow_t *fdow, fdo_ownership_voucher_t *ov, fdo_block_reset(&fdow->b); fdow->b.block_size = fdow_buff_default_sz; if (!fdow_encoder_init(fdow)) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, + "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); goto exit; } // write OVHeader if (!fdo_ovheader_write(fdow, ov->prot_version, ov->g2, ov->rvlst2, - ov->dev_info, ov->mfg_pub_key, ov->hdc)) { + ov->dev_info, ov->mfg_pub_key, ov->hdc)) { LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to write OVHeader\n"); goto exit; } - enc_ovheader = fdo_byte_array_alloc_with_byte_array(fdow->b.block, fdow->b.block_size); + enc_ovheader = fdo_byte_array_alloc_with_byte_array(fdow->b.block, + fdow->b.block_size); if (!enc_ovheader) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to copy encoded OVHeader\n"); + LOG(LOG_ERROR, + "OVEHashPrevEntry: Failed to copy encoded OVHeader\n"); goto exit; } @@ -660,7 +693,8 @@ bool fdo_ove_hash_prev_entry_save(fdow_t *fdow, fdo_ownership_voucher_t *ov, fdo_block_reset(&fdow->b); fdow->b.block_size = fdow_buff_default_sz; if (!fdow_encoder_init(fdow)) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, + "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); goto exit; } @@ -673,38 +707,44 @@ bool fdo_ove_hash_prev_entry_save(fdow_t *fdow, fdo_ownership_voucher_t *ov, LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to get HMac length\n"); goto exit; } - enc_hmac = fdo_byte_array_alloc_with_byte_array(fdow->b.block, fdow->b.block_size); + enc_hmac = fdo_byte_array_alloc_with_byte_array(fdow->b.block, + fdow->b.block_size); if (!enc_hmac) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to copy encoded HMac\n"); + LOG(LOG_ERROR, + "OVEHashPrevEntry: Failed to copy encoded HMac\n"); goto exit; } // calculate and save OVEHashPrevEntry (hash[OVHeader||HMac]) // Prev Entry Hash is of length OVHeader length + HMac length hash_prev_entry = fdo_alloc(enc_ovheader->byte_sz + enc_hmac->byte_sz); if (!hash_prev_entry) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to alloc for OVEHashPrevEntry\n"); + LOG(LOG_ERROR, + "OVEHashPrevEntry: Failed to alloc for OVEHashPrevEntry\n"); goto exit; } if (0 != memcpy_s(hash_prev_entry, enc_ovheader->byte_sz, - enc_ovheader->bytes, enc_ovheader->byte_sz)) { + enc_ovheader->bytes, enc_ovheader->byte_sz)) { LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to copy OVHeader\n"); goto exit; } - if (0 != memcpy_s(hash_prev_entry + enc_ovheader->byte_sz, enc_hmac->byte_sz, - enc_hmac->bytes, enc_hmac->byte_sz)) { + if (0 != memcpy_s(hash_prev_entry + enc_ovheader->byte_sz, + enc_hmac->byte_sz, enc_hmac->bytes, + enc_hmac->byte_sz)) { LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to copy HMac\n"); goto exit; } - ov->ov_entries->hp_hash = fdo_hash_alloc( - FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); + ov->ov_entries->hp_hash = + fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); if (!ov->ov_entries->hp_hash) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to alloc for OVEHashPrevEntry in storage\n"); + LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to alloc for " + "OVEHashPrevEntry in storage\n"); goto exit; } - if (0 != fdo_crypto_hash(hash_prev_entry, enc_ovheader->byte_sz + enc_hmac->byte_sz, - ov->ov_entries->hp_hash->hash->bytes, - ov->ov_entries->hp_hash->hash->byte_sz)) { + if (0 != fdo_crypto_hash(hash_prev_entry, + enc_ovheader->byte_sz + enc_hmac->byte_sz, + ov->ov_entries->hp_hash->hash->bytes, + ov->ov_entries->hp_hash->hash->byte_sz)) { LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to generate hash\n"); goto exit; } @@ -714,7 +754,8 @@ bool fdo_ove_hash_prev_entry_save(fdow_t *fdow, fdo_ownership_voucher_t *ov, fdo_block_reset(&fdow->b); fdow->b.block_size = fdow_buff_default_sz; if (!fdow_encoder_init(fdow)) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, + "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); goto exit; } exit: @@ -734,15 +775,16 @@ bool fdo_ove_hash_prev_entry_save(fdow_t *fdow, fdo_ownership_voucher_t *ov, } /** - * Take the the values of old OVHeader contents and newly supplied replacement credentials - * and create a new HMAC. + * Take the the values of old OVHeader contents and newly supplied replacement + * credentials and create a new HMAC. * @param dev_cred - pointer to the Device_credential to source * @param new_pub_key - the public key to use in the signature * @param hdc - device cert-chain hash * @return pointer to a new fdo_hash_t object containing the HMAC */ fdo_hash_t *fdo_new_ov_hdr_sign(fdo_dev_cred_t *dev_cred, - fdo_owner_supplied_credentials_t *osc, fdo_hash_t *hdc) + fdo_owner_supplied_credentials_t *osc, + fdo_hash_t *hdc) { bool ret = false; @@ -750,23 +792,24 @@ fdo_hash_t *fdo_new_ov_hdr_sign(fdo_dev_cred_t *dev_cred, // fdow_t to generate CBOR encoded OVHeader. Used to generate HMAC. fdow_t *fdow = fdo_alloc(sizeof(fdow_t)); if (!fdow_init(fdow) || - !fdo_block_alloc_with_size(&fdow->b, BUFF_SIZE_8K_BYTES) || - !fdow_encoder_init(fdow)) { + !fdo_block_alloc_with_size(&fdow->b, BUFF_SIZE_8K_BYTES) || + !fdow_encoder_init(fdow)) { LOG(LOG_ERROR, "Failed to initialize FDOW\n"); goto exit; } - if (!fdo_ovheader_write(fdow, dev_cred->owner_blk->pv, osc->guid, osc->rvlst, - dev_cred->mfg_blk->d, osc->pubkey, hdc)) { + if (!fdo_ovheader_write(fdow, dev_cred->owner_blk->pv, osc->guid, + osc->rvlst, dev_cred->mfg_blk->d, osc->pubkey, + hdc)) { goto exit; } fdo_hash_t *hmac = fdo_hash_alloc(FDO_CRYPTO_HMAC_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); - if (hmac && - (0 != fdo_device_ov_hmac(fdow->b.block, fdow->b.block_size, - hmac->hash->bytes, hmac->hash->byte_sz, true))) { + if (hmac && (0 != fdo_device_ov_hmac(fdow->b.block, fdow->b.block_size, + hmac->hash->bytes, + hmac->hash->byte_sz, true))) { fdo_hash_free(hmac); goto exit; } diff --git a/lib/fdonet.c b/lib/fdonet.c index e8d9c2a1..9c9e0b2b 100644 --- a/lib/fdonet.c +++ b/lib/fdonet.c @@ -87,8 +87,9 @@ bool is_owner_proxy_defined(void) */ /* internal api - * proxydata: proxy data as asscii string. e.g."http://theproxy.mycompany.com:123" - * return resolved dns, as ip in network format and port + * proxydata: proxy data as asscii string. + * e.g."http://theproxy.mycompany.com:123" return resolved dns, as ip in network + * format and port */ static bool get_netip_port(const char *proxydata, uint8_t proxydatsize, uint8_t *netip, uint16_t *proxy_port) @@ -136,7 +137,7 @@ static bool get_netip_port(const char *proxydata, uint8_t proxydatsize, // set to 0 explicitly errno = 0; *proxy_port = strtol((char *)&proxy[i + 1], &eptr, 10); - if (!eptr || eptr == (char *)&proxy[i+1] || errno != 0) { + if (!eptr || eptr == (char *)&proxy[i + 1] || errno != 0) { LOG(LOG_ERROR, "Proxy Port read failed\n"); goto err; } @@ -261,7 +262,8 @@ bool setup_http_proxy(const char *filename, fdo_ip_address_t *fdoip, if (nread > 0) { proxydata = fdo_alloc(nread + 1); if (!proxydata) { - LOG(LOG_ERROR, "Could not allocate memory to read proxy information.\n"); + LOG(LOG_ERROR, "Could not allocate memory to read " + "proxy information.\n"); goto err; } if (fdo_blob_read((char *)filename, FDO_SDK_RAW_DATA, proxydata, @@ -359,12 +361,12 @@ void fdo_net_init(void) * @return ret * true if successful. false in case of error. */ -bool resolve_dn(const char *dn, fdo_ip_address_t **ip, uint16_t port, - bool tls, bool proxy) +bool resolve_dn(const char *dn, fdo_ip_address_t **ip, uint16_t port, bool tls, + bool proxy) { bool ret = false; + int connect_ok = -1; uint32_t num_ofIPs = 0; - fdo_con_handle sock_hdl = FDO_CON_INVALID_HANDLE; fdo_ip_address_t *ip_list = NULL; rest_ctx_t *rest = NULL; @@ -398,26 +400,28 @@ bool resolve_dn(const char *dn, fdo_ip_address_t **ip, uint16_t port, goto end; } - curl = curl_easy_init(); - if (ip_list && num_ofIPs > 0) { // Iterate over IP-list to connect uint32_t iter = 0; - while (iter != num_ofIPs && - sock_hdl == FDO_CON_INVALID_HANDLE) { + while (iter != num_ofIPs && connect_ok == -1) { - sock_hdl = fdo_con_connect((ip_list + iter), port, - tls); - if (sock_hdl == FDO_CON_INVALID_HANDLE) { + curl = curl_easy_init(); + connect_ok = + fdo_con_connect((ip_list + iter), dn, port, tls); + if (connect_ok == -1) { LOG(LOG_ERROR, "Failed to connect to " "server: retrying...\n"); } iter++; } - if (FDO_CON_INVALID_HANDLE != sock_hdl) { - fdo_con_disconnect(sock_hdl); + if (connect_ok != -1) { + if (fdo_con_disconnect()) { + LOG(LOG_ERROR, + "Error during connection close()\n"); + goto end; + } if (!cache_host_dns(dn)) { LOG(LOG_ERROR, "REST DNS caching failed!\n"); goto end; @@ -449,18 +453,19 @@ bool resolve_dn(const char *dn, fdo_ip_address_t **ip, uint16_t port, * programmed into device by the manufacturer. * * @param ip: IP address of the server to connect to. + * @param dn: Domain name of the server * @param port: Port number of the server instance to connect to. - * @param sock_hdl: Sock struct for subsequent read/write/close. * @param tls: flag describing whether HTTP (false) or HTTPS (true) is * * @return ret * true if successful. false in case of error. */ -bool connect_to_manufacturer(fdo_ip_address_t *ip, uint16_t port, - fdo_con_handle *sock_hdl, bool tls) +bool connect_to_manufacturer(fdo_ip_address_t *ip, const char *dn, + uint16_t port, bool tls) { bool ret = false; int retries = MANUFACTURER_CONNECT_RETRIES; + int connect_ok = -1; curl = curl_easy_init(); LOG(LOG_DEBUG, "Connecting to manufacturer Server\n"); @@ -469,15 +474,9 @@ bool connect_to_manufacturer(fdo_ip_address_t *ip, uint16_t port, goto end; } - if (!sock_hdl) { - LOG(LOG_ERROR, "Connection handle (socket) is NULL\n"); - goto end; - } - /* cache ip/dns and port to REST */ if (!cache_host_ip(ip)) { - LOG(LOG_ERROR, - "Mfg IP-address caching to REST failed!\n"); + LOG(LOG_ERROR, "Mfg IP-address caching to REST failed!\n"); goto end; } @@ -495,24 +494,21 @@ bool connect_to_manufacturer(fdo_ip_address_t *ip, uint16_t port, if (is_mfg_proxy_defined()) { #if defined HTTPPROXY - if (!fdo_curl_proxy(&mfgproxy_ip, mfgproxy_port)) { - LOG(LOG_ERROR, - "Failed to setup Proxy Connection info for Manufacturer server!\n"); - goto end; - } + if (!fdo_curl_proxy(&mfgproxy_ip, mfgproxy_port)) { + LOG(LOG_ERROR, "Failed to setup Proxy Connection info " + "for Manufacturer server!\n"); + goto end; + } - LOG(LOG_DEBUG, "via HTTP proxy <%u.%u.%u.%u:%u>\n", + LOG(LOG_DEBUG, "via HTTP proxy <%u.%u.%u.%u:%u>\n", mfgproxy_ip.addr[0], mfgproxy_ip.addr[1], mfgproxy_ip.addr[2], mfgproxy_ip.addr[3], mfgproxy_port); #endif } if (ip && ip->length > 0) { - LOG(LOG_DEBUG, "using IP\n"); - - *sock_hdl = fdo_con_connect(ip, port, tls); - if ((*sock_hdl == FDO_CON_INVALID_HANDLE) && - retries--) { + connect_ok = fdo_con_connect(ip, dn, port, tls); + if ((connect_ok == -1) && retries--) { LOG(LOG_INFO, "Failed to connect to Manufacturer " "server: retrying...\n"); fdo_sleep(RETRY_DELAY); @@ -523,7 +519,7 @@ bool connect_to_manufacturer(fdo_ip_address_t *ip, uint16_t port, goto end; } - if (FDO_CON_INVALID_HANDLE == *sock_hdl) { + if (connect_ok == -1) { LOG(LOG_ERROR, "Failed to connect to Manufacturer server: Giving up...\n"); goto end; @@ -538,17 +534,18 @@ bool connect_to_manufacturer(fdo_ip_address_t *ip, uint16_t port, * from RV list stored in device credentials. * * @param ip: IP address of the server to connect to. + * @param dn: Domain name of the server * @param port: Port number of the server instance to connect to. - * @param sock_hdl: Sock struct for subsequent read/write/close. * @param tls: flag describing whether HTTP (false) or HTTPS (true) is * * @return ret * true if successful. false in case of error. */ -bool connect_to_rendezvous(fdo_ip_address_t *ip, uint16_t port, - fdo_con_handle *sock_hdl, bool tls) +bool connect_to_rendezvous(fdo_ip_address_t *ip, const char *dn, uint16_t port, + bool tls) { bool ret = false; + int connect_ok = -1; int retries = RENDEZVOUS_CONNECT_RETRIES; curl = curl_easy_init(); @@ -558,11 +555,6 @@ bool connect_to_rendezvous(fdo_ip_address_t *ip, uint16_t port, goto end; } - if (!sock_hdl) { - LOG(LOG_ERROR, "Connection handle (socket) is NULL\n"); - goto end; - } - /* cache ip/dns and port to REST */ if (!cache_host_ip(ip)) { LOG(LOG_ERROR, "REST IP-address caching failed!\n"); @@ -583,24 +575,21 @@ bool connect_to_rendezvous(fdo_ip_address_t *ip, uint16_t port, if (is_rv_proxy_defined()) { #if defined HTTPPROXY - if (!fdo_curl_proxy(&rvproxy_ip, rvproxy_port)) { - LOG(LOG_ERROR, - "Failed to setup Proxy Connection info for Rendezvous server!\n"); - goto end; - } + if (!fdo_curl_proxy(&rvproxy_ip, rvproxy_port)) { + LOG(LOG_ERROR, "Failed to setup Proxy Connection info " + "for Rendezvous server!\n"); + goto end; + } - LOG(LOG_DEBUG, "via HTTP proxy <%u.%u.%u.%u:%u>\n", + LOG(LOG_DEBUG, "via HTTP proxy <%u.%u.%u.%u:%u>\n", rvproxy_ip.addr[0], rvproxy_ip.addr[1], rvproxy_ip.addr[2], rvproxy_ip.addr[3], rvproxy_port); #endif } if (ip && ip->length > 0) { - LOG(LOG_DEBUG, "using IP\n"); - - *sock_hdl = fdo_con_connect(ip, port, tls); - if ((*sock_hdl == FDO_CON_INVALID_HANDLE) && - retries--) { + connect_ok = fdo_con_connect(ip, dn, port, tls); + if ((connect_ok == -1) && retries--) { LOG(LOG_INFO, "Failed to connect to Rendezvous server: " "retrying...\n"); fdo_sleep(RETRY_DELAY); @@ -611,7 +600,7 @@ bool connect_to_rendezvous(fdo_ip_address_t *ip, uint16_t port, goto end; } - if (FDO_CON_INVALID_HANDLE == *sock_hdl) { + if (connect_ok == -1) { LOG(LOG_ERROR, "Failed to connect to rendezvous: Giving up...\n"); goto end; @@ -627,17 +616,18 @@ bool connect_to_rendezvous(fdo_ip_address_t *ip, uint16_t port, * received by Rendezvous stored in device credentials. * * @param ip: IP address of the server to connect to. + * @param dn: Domain name of the server * @param port: Port number of the server instance to connect to. - * @param sock_hdl: Sock struct for subsequent read/write/close. * @param tls: flag describing whether HTTP (false) or HTTPS (true) is * * @return ret * true if successful. false in case of error. */ -bool connect_to_owner(fdo_ip_address_t *ip, uint16_t port, - fdo_con_handle *sock_hdl, bool tls) +bool connect_to_owner(fdo_ip_address_t *ip, const char *dn, uint16_t port, + bool tls) { bool ret = false; + int connect_ok = -1; int retries = OWNER_CONNECT_RETRIES; curl = curl_easy_init(); @@ -647,15 +637,9 @@ bool connect_to_owner(fdo_ip_address_t *ip, uint16_t port, goto end; } - if (!sock_hdl) { - LOG(LOG_ERROR, "Connection handle (socket) is NULL\n"); - goto end; - } - /* cache ip/dns and port to REST */ if (!cache_host_ip(ip)) { - LOG(LOG_ERROR, - "Owner IP-address caching to REST failed!\n"); + LOG(LOG_ERROR, "Owner IP-address caching to REST failed!\n"); goto end; } @@ -673,13 +657,13 @@ bool connect_to_owner(fdo_ip_address_t *ip, uint16_t port, if (is_owner_proxy_defined()) { #if defined HTTPPROXY - if (!fdo_curl_proxy(&ownerproxy_ip, ownerproxy_port)) { - LOG(LOG_ERROR, - "Failed to setup Proxy Connection info for Owner server!\n"); - goto end; - } + if (!fdo_curl_proxy(&ownerproxy_ip, ownerproxy_port)) { + LOG(LOG_ERROR, "Failed to setup Proxy Connection info " + "for Owner server!\n"); + goto end; + } - LOG(LOG_DEBUG, "via HTTP proxy <%u.%u.%u.%u:%u>\n", + LOG(LOG_DEBUG, "via HTTP proxy <%u.%u.%u.%u:%u>\n", ownerproxy_ip.addr[0], ownerproxy_ip.addr[1], ownerproxy_ip.addr[2], ownerproxy_ip.addr[3], ownerproxy_port); @@ -687,11 +671,8 @@ bool connect_to_owner(fdo_ip_address_t *ip, uint16_t port, } if (ip && ip->length > 0) { - LOG(LOG_DEBUG, "using IP\n"); - - *sock_hdl = fdo_con_connect(ip, port, tls); - if ((*sock_hdl == FDO_CON_INVALID_HANDLE) && - retries--) { + connect_ok = fdo_con_connect(ip, dn, port, tls); + if ((connect_ok == -1) && retries--) { LOG(LOG_INFO, "Failed to connect to Owner server: retrying...\n"); fdo_sleep(RETRY_DELAY); @@ -701,7 +682,7 @@ bool connect_to_owner(fdo_ip_address_t *ip, uint16_t port, goto end; } - if (FDO_CON_INVALID_HANDLE == *sock_hdl) { + if (connect_ok == -1) { LOG(LOG_ERROR, "Failed to connect to Owner: Giving up...\n"); goto end; } @@ -722,18 +703,20 @@ bool connect_to_owner(fdo_ip_address_t *ip, uint16_t port, */ int fdo_connection_restablish(fdo_prot_ctx_t *prot_ctx) { + int connect_ok = -1; int retries = OWNER_CONNECT_RETRIES; + curl = curl_easy_init(); /* re-connect using server-IP */ - while (((prot_ctx->sock_hdl = fdo_con_connect( - prot_ctx->host_ip, prot_ctx->host_port, prot_ctx->tls)) == - FDO_CON_INVALID_HANDLE) && + while (((connect_ok = fdo_con_connect( + prot_ctx->host_ip, prot_ctx->host_dns, prot_ctx->host_port, + prot_ctx->tls)) == -1) && retries--) { LOG(LOG_INFO, "Failed reconnecting to server: retrying..."); fdo_sleep(RETRY_DELAY); } - if (prot_ctx->sock_hdl == FDO_CON_INVALID_HANDLE) { + if (connect_ok == -1) { LOG(LOG_ERROR, "Failed reconnecting to server: Giving up..."); return -1; } else { diff --git a/lib/fdoprot.c b/lib/fdoprot.c index 08862288..b5d89d5f 100644 --- a/lib/fdoprot.c +++ b/lib/fdoprot.c @@ -9,7 +9,7 @@ * various aspects of FDO protcol. */ -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include "util.h" #include "fdoprot.h" #include "load_credentials.h" @@ -191,7 +191,9 @@ bool fdo_process_states(fdo_prot_t *ps) } if (ps->state != FDO_STATE_DONE && state_fn && state_fn(ps)) { - LOG(LOG_ERROR, "Error occurred while processing Type %d\n", ps->state); + LOG(LOG_ERROR, + "Error occurred while processing Type %d\n", + ps->state); char err_msg[64] = {0}; size_t err_msg_sz = 0; @@ -200,13 +202,15 @@ bool fdo_process_states(fdo_prot_t *ps) ps->state); err_msg_sz = strnlen_s(err_msg, sizeof(err_msg)); if (!err_msg_sz || err_msg_sz == sizeof(err_msg)) { - LOG(LOG_ERROR, "Failed to get error message length\n"); + LOG(LOG_ERROR, + "Failed to get error message length\n"); break; } // clear the block contents to write error message fdo_block_reset(&ps->fdow.b); if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "Failed to initilize FDOW encoder\n"); + LOG(LOG_ERROR, + "Failed to initilize FDOW encoder\n"); break; } fdo_send_error_message(&ps->fdow, MESSAGE_BODY_ERROR, @@ -283,7 +287,8 @@ bool fdo_prot_to2_init(fdo_prot_t *ps, fdo_service_info_t *si, ps->dev_cred = dev_cred; ps->g2 = dev_cred->owner_blk->guid; ps->round_trip_count = 0; - ps->hello_device_hash = fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); + ps->hello_device_hash = + fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); if (!ps->hello_device_hash) { return false; } @@ -299,7 +304,8 @@ bool fdo_prot_to2_init(fdo_prot_t *ps, fdo_service_info_t *si, } ps->sv_info_mod_list_head = module_list; - if (!fdo_serviceinfo_deactivate_modules(ps->sv_info_mod_list_head)) { + if (!fdo_serviceinfo_deactivate_modules( + ps->sv_info_mod_list_head)) { return false; } ps->dsi_info = fdo_alloc(sizeof(fdo_sv_info_dsi_info_t)); @@ -347,8 +353,7 @@ bool fdo_check_to2_round_trips(fdo_prot_t *ps) LOG(LOG_ERROR, "Exceeded maximum number of TO2 rounds\n"); char err_msg[] = "Exceeded max number of rounds"; fdo_send_error_message(&ps->fdow, INTERNAL_SERVER_ERROR, - ps->state, - err_msg, sizeof(err_msg)); + ps->state, err_msg, sizeof(err_msg)); ps->state = FDO_STATE_ERROR; return false; } @@ -378,12 +383,12 @@ bool fdo_prot_rcv_msg(fdor_t *fdor, fdow_t *fdow, char *prot_name, int *statep) if (!fdor->have_block) { /* - * The way this method is used to maintain the state, - * it's not an error scenario if there's no block to read. - * have_block false means that the response has not yet come since the - * requet has not been sent. - * TO-DO : Investigate for a better approach than this. - */ + * The way this method is used to maintain the state, + * it's not an error scenario if there's no block to read. + * have_block false means that the response has not yet come + * since the requet has not been sent. TO-DO : Investigate for a + * better approach than this. + */ return false; } @@ -398,8 +403,8 @@ bool fdo_prot_rcv_msg(fdor_t *fdor, fdow_t *fdow, char *prot_name, int *statep) * * Internal API */ -void fdo_send_error_message(fdow_t *fdow, int ecode, int msgnum, - char *errmsg, size_t errmsg_sz) +void fdo_send_error_message(fdow_t *fdow, int ecode, int msgnum, char *errmsg, + size_t errmsg_sz) { LOG(LOG_ERROR, "Sending Error Message\n"); @@ -416,11 +421,11 @@ void fdo_send_error_message(fdow_t *fdow, int ecode, int msgnum, LOG(LOG_ERROR, "Error Message: Failed to write EMPrevMsgID\n"); return; } - if (!fdow_text_string(fdow, errmsg , errmsg_sz)) { + if (!fdow_text_string(fdow, errmsg, errmsg_sz)) { LOG(LOG_ERROR, "Error Message: Failed to write EMErrorStr"); return; } - if (!fdow_signed_int(fdow, (int) time(NULL))) { + if (!fdow_signed_int(fdow, (int)time(NULL))) { LOG(LOG_ERROR, "Error Message: Failed to write EMErrorTs\n"); return; } diff --git a/lib/fdoprotctx.c b/lib/fdoprotctx.c index f3bfab97..8c41e7af 100644 --- a/lib/fdoprotctx.c +++ b/lib/fdoprotctx.c @@ -64,8 +64,9 @@ fdo_prot_ctx_t *fdo_prot_ctx_alloc(bool (*protrun)(fdo_prot_t *ps), goto err; } prot_ctx->host_ip->length = host_ip->length; - if (0 != memcpy_s(prot_ctx->host_ip->addr, sizeof(host_ip->addr), - host_ip->addr, sizeof(host_ip->addr))) { + if (0 != memcpy_s(prot_ctx->host_ip->addr, + sizeof(host_ip->addr), host_ip->addr, + sizeof(host_ip->addr))) { LOG(LOG_ERROR, "Failed to copy host IP\n"); goto err; } @@ -74,7 +75,17 @@ fdo_prot_ctx_t *fdo_prot_ctx_alloc(bool (*protrun)(fdo_prot_t *ps), // use the DNS directly, since the DNS is resolved and cached, // and the resolved IP is used directly if (host_dns) { - prot_ctx->host_dns = host_dns; + size_t host_dns_len = strnlen_s(host_dns, FDO_MAX_STR_SIZE); + prot_ctx->host_dns = fdo_alloc(host_dns_len + 1); + if (!prot_ctx->host_dns) { + LOG(LOG_ERROR, "Failed to alloc host DNS\n"); + goto err; + } + if (0 != strncpy_s((char *)prot_ctx->host_dns, FDO_MAX_STR_SIZE, + host_dns, host_dns_len)) { + LOG(LOG_ERROR, "Failed to copy host DNS\n"); + goto err; + } } prot_ctx->protdata = protdata; @@ -87,6 +98,9 @@ fdo_prot_ctx_t *fdo_prot_ctx_alloc(bool (*protrun)(fdo_prot_t *ps), if (prot_ctx->host_ip) { fdo_free(prot_ctx->host_ip); } + if (prot_ctx->host_dns) { + fdo_free(prot_ctx->host_dns); + } return NULL; } @@ -102,6 +116,9 @@ void fdo_prot_ctx_free(fdo_prot_ctx_t *prot_ctx) if (prot_ctx->host_ip) { fdo_free(prot_ctx->host_ip); } + if (prot_ctx->host_dns) { + fdo_free(prot_ctx->host_dns); + } } } @@ -127,8 +144,7 @@ static bool fdo_prot_ctx_connect(fdo_prot_ctx_t *prot_ctx) } if (!resolve_dn(prot_ctx->host_dns, &prot_ctx->resolved_ip, - prot_ctx->host_port, - prot_ctx->tls, + prot_ctx->host_port, prot_ctx->tls, is_mfg_proxy_defined())) { ret = false; break; @@ -139,10 +155,9 @@ static bool fdo_prot_ctx_connect(fdo_prot_ctx_t *prot_ctx) ATTRIBUTE_FALLTHROUGH; case FDO_STATE_DI_DONE: /* type 13 */ ret = connect_to_manufacturer( - prot_ctx->resolved_ip ? prot_ctx->resolved_ip : prot_ctx->host_ip, - prot_ctx->host_port, - &prot_ctx->sock_hdl, - prot_ctx->tls); + prot_ctx->resolved_ip ? prot_ctx->resolved_ip + : prot_ctx->host_ip, + prot_ctx->host_dns, prot_ctx->host_port, prot_ctx->tls); break; case FDO_STATE_T01_SND_HELLO_FDO: /* type 30 */ ATTRIBUTE_FALLTHROUGH; @@ -153,8 +168,7 @@ static bool fdo_prot_ctx_connect(fdo_prot_ctx_t *prot_ctx) } if (!resolve_dn(prot_ctx->host_dns, &prot_ctx->resolved_ip, - prot_ctx->host_port, - prot_ctx->tls, + prot_ctx->host_port, prot_ctx->tls, is_rv_proxy_defined())) { ret = false; fdo_free(prot_ctx->resolved_ip); @@ -164,14 +178,16 @@ static bool fdo_prot_ctx_connect(fdo_prot_ctx_t *prot_ctx) case FDO_STATE_TO1_SND_PROVE_TO_FDO: /* type 32 */ ATTRIBUTE_FALLTHROUGH; case FDO_STATE_TO1_RCV_FDO_REDIRECT: /* type 33 */ - // try DNS's resolved IP first, if it fails, try given IP address - ret = connect_to_rendezvous( - prot_ctx->resolved_ip, prot_ctx->host_port, &prot_ctx->sock_hdl, - prot_ctx->tls); + // try DNS's resolved IP first, if it fails, try given IP + // address + ret = connect_to_rendezvous(prot_ctx->resolved_ip, + prot_ctx->host_dns, + prot_ctx->host_port, prot_ctx->tls); if (!ret) { - ret = connect_to_rendezvous( - prot_ctx->host_ip, prot_ctx->host_port, &prot_ctx->sock_hdl, - prot_ctx->tls); + LOG(LOG_DEBUG, "Invalid DNS. Using IP\n"); + ret = connect_to_rendezvous(prot_ctx->host_ip, NULL, + prot_ctx->host_port, + prot_ctx->tls); } break; case FDO_STATE_T02_SND_HELLO_DEVICE: /* type 60 */ @@ -183,8 +199,7 @@ static bool fdo_prot_ctx_connect(fdo_prot_ctx_t *prot_ctx) } if (!resolve_dn(prot_ctx->host_dns, &prot_ctx->resolved_ip, - prot_ctx->host_port, - prot_ctx->tls, + prot_ctx->host_port, prot_ctx->tls, is_owner_proxy_defined())) { ret = false; fdo_free(prot_ctx->resolved_ip); @@ -210,12 +225,16 @@ static bool fdo_prot_ctx_connect(fdo_prot_ctx_t *prot_ctx) case FDO_STATE_TO2_SND_DONE: /* type 70 */ ATTRIBUTE_FALLTHROUGH; case FDO_STATE_TO2_RCV_DONE_2: /* type 71 */ - // try DNS's resolved IP first, if it fails, try given IP address - ret = connect_to_owner(prot_ctx->resolved_ip, prot_ctx->host_port, - &prot_ctx->sock_hdl, prot_ctx->tls); + // try DNS's resolved IP first, if it fails, try given IP + // address + ret = + connect_to_owner(prot_ctx->resolved_ip, prot_ctx->host_dns, + prot_ctx->host_port, prot_ctx->tls); if (!ret) { - ret = connect_to_owner(prot_ctx->host_ip, prot_ctx->host_port, - &prot_ctx->sock_hdl, prot_ctx->tls); + LOG(LOG_DEBUG, "Invalid DNS. Using IP\n"); + ret = connect_to_owner(prot_ctx->host_ip, NULL, + prot_ctx->host_port, + prot_ctx->tls); } break; default: @@ -274,7 +293,6 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) /* ========================================================== */ /* Transmit outbound packet */ - /* Protocol sets State as FDO_STATE_DONE at the end of the*/ /* protocol(DI/T01/TO2) */ /* Hence, when state = FDO_STATE_DONE, we have nothing more*/ @@ -291,13 +309,16 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) break; } - // update the final encoded length in the FDOW block after every successfull write. + // update the final encoded length in the FDOW block after every + // successfull write. if (!fdow_encoded_length(fdow, &fdow->b.block_size)) { - LOG(LOG_ERROR, "Failed to get encoded length in FDOW\n"); + LOG(LOG_ERROR, + "Failed to get encoded length in FDOW\n"); ret = -1; break; } - LOG(LOG_DEBUG, "%s Tx Request Body length: %zu\n", __func__, fdow->b.block_size); + LOG(LOG_DEBUG, "%s Tx Request Body length: %zu\n", __func__, + fdow->b.block_size); LOG(LOG_DEBUG, "%s Tx Request Body:\n", __func__); fdo_log_block(&fdow->b); @@ -313,16 +334,32 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) fdow->b.block[size] = 0; retries = CONNECTION_RETRY; + char hdr_buf[REST_MAX_MSGHDR_SIZE]; + char body_buf[REST_MAX_MSGBODY_SIZE]; + + if (memset_s(hdr_buf, REST_MAX_MSGHDR_SIZE, 0) != 0) { + LOG(LOG_ERROR, "Memset() failed!\n"); + ret = -1; + break; + } + + if (memset_s(body_buf, REST_MAX_MSGBODY_SIZE, 0) != 0) { + LOG(LOG_ERROR, "Memset() failed!\n"); + ret = -1; + break; + } + + n = -1; do { - n = fdo_con_send_message( - prot_ctx->sock_hdl, FDO_PROT_SPEC_VERSION, - fdow->msg_type, &fdow->b.block[0], size, - prot_ctx->tls); - - if (n <= 0) { - if (fdo_con_disconnect(prot_ctx->sock_hdl)) { - LOG(LOG_ERROR, - "Error during socket close()\n"); + n = fdo_con_send_recv_message( + FDO_PROT_SPEC_VERSION, fdow->msg_type, + &fdow->b.block[0], size, prot_ctx->tls, hdr_buf, + body_buf); + + if (n < 0) { + if (fdo_con_disconnect()) { + LOG(LOG_ERROR, "Error during " + "connection close()\n"); ret = -1; break; } @@ -342,7 +379,8 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) break; } - // clear the block contents in preparation for the next FDOW write operation + // clear the block contents in preparation for the next FDOW + // write operation fdo_block_reset(&fdow->b); fdow->b.block_size = prot_ctx->protdata->prot_buff_sz; @@ -351,39 +389,36 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) uint32_t msglen = 0; uint32_t protver = 0; - char curl_buf[REST_MAX_MSGBODY_SIZE]; - size_t curl_buf_offset = 0; - - if (memset_s(curl_buf, REST_MAX_MSGBODY_SIZE, 0) != 0) { - LOG(LOG_ERROR, "Memset() failed!\n"); - return false; - } - ret = fdo_con_recv_msg_header(prot_ctx->sock_hdl, &protver, - (uint32_t *)&fdor->msg_type, - &msglen, curl_buf, &curl_buf_offset); + ret = fdo_con_parse_msg_header( + &protver, (uint32_t *)&fdor->msg_type, &msglen, hdr_buf); if (ret == -1) { LOG(LOG_ERROR, "fdo_con_recv_msg_header() Failed!\n"); ret = -1; break; } - // clear the block contents in preparation for the next FDOR read operation + if ((fdor->msg_type < FDO_DI_APP_START) || + (fdor->msg_type > FDO_TYPE_ERROR)) { + msglen = 0; + } + + // clear the block contents in preparation for the next FDOR + // read operation fdo_block_reset(&fdor->b); // set the received msg length in the block fdor->b.block_size = msglen; if (msglen > 0 && msglen <= prot_ctx->protdata->prot_buff_sz) { retries = CONNECTION_RETRY; - n = 0; + n = -1; do { - n = fdo_con_recv_msg_body(&fdor->b.block[0], msglen, - curl_buf, curl_buf_offset); + n = fdo_con_parse_msg_body(&fdor->b.block[0], + msglen, body_buf); if (n < 0) { - if (fdo_con_disconnect( - prot_ctx->sock_hdl)) { + if (fdo_con_disconnect()) { LOG(LOG_ERROR, "Error during " - "socket " + "network " "close()\n"); ret = -1; break; @@ -400,8 +435,8 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) } } while (n < 0 && retries--); - if (n <= 0) { - LOG(LOG_ERROR, "Socket read not successful " + if (n < 0) { + LOG(LOG_ERROR, "Buffer read not successful " "after retries!\n"); fdo_block_reset(&fdor->b); ret = -1; @@ -409,14 +444,15 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) } } - if (fdo_con_disconnect(prot_ctx->sock_hdl)) { - LOG(LOG_ERROR, "Error during socket close()\n"); + if (fdo_con_disconnect()) { + LOG(LOG_ERROR, "Error during connection close()\n"); ret = -1; break; } if (msglen > prot_ctx->protdata->prot_buff_sz) { - LOG(LOG_ERROR, "Response body size is more than allocated memory\n"); + LOG(LOG_ERROR, "Response body size is more than " + "allocated memory\n"); ret = -1; break; } @@ -432,15 +468,15 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) ret = -1; break; } - /* ERROR case ? */ + /* ERROR case ? */ if (fdor->msg_type == FDO_TYPE_ERROR) { ret = -1; break; } /* - * Now that we have the received buffer, initialize the parser for next FDOR read - * operation and set the have_block flag. + * Now that we have the received buffer, initialize the parser + * for next FDOR read operation and set the have_block flag. */ if (!fdor_parser_init(fdor)) { LOG(LOG_ERROR, "Failed to initilize FDOR parser\n"); diff --git a/lib/fdotypes.c b/lib/fdotypes.c index 9c469ba1..14c79070 100644 --- a/lib/fdotypes.c +++ b/lib/fdotypes.c @@ -12,7 +12,7 @@ #include "fdoprot.h" #include "fdotypes.h" #include "network_al.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include "util.h" #include "fdo.h" #include @@ -303,7 +303,8 @@ fdo_string_t *fdo_string_alloc(void) * * @return an allocated fdo_string_t object */ -fdo_string_t *fdo_string_alloc_size(size_t byte_sz) { +fdo_string_t *fdo_string_alloc_size(size_t byte_sz) +{ if (byte_sz == 0) { return NULL; @@ -385,7 +386,7 @@ fdo_string_t *fdo_string_alloc_with_str(const char *data) if (!str_sz || str_sz == FDO_MAX_STR_SIZE) { LOG(LOG_ERROR, "data is either 'NULL' or 'isn't" - " NULL-terminated'\n"); + " NULL-terminated'\n"); return NULL; } return fdo_string_alloc_with(data, str_sz); @@ -502,7 +503,8 @@ bool fdo_siginfo_write(fdow_t *fdow) return false; } - if (!fdow_byte_string(fdow, empty_byte_array->bytes, empty_byte_array->byte_sz)) { + if (!fdow_byte_string(fdow, empty_byte_array->bytes, + empty_byte_array->byte_sz)) { LOG(LOG_ERROR, "SigInfo: Failed to write Info\n"); goto end; } @@ -553,16 +555,16 @@ bool fdo_siginfo_read(fdor_t *fdor) if (type != exptype) { LOG(LOG_ERROR, - "SigInfo: Invalid sgType. Expected %d, Received %d\n", exptype, - type); + "SigInfo: Invalid sgType. Expected %d, Received %d\n", + exptype, type); goto end; } size_t info_length = 1; if (!fdor_string_length(fdor, &info_length) || info_length != 0) { LOG(LOG_ERROR, - "SigInfo: Invalid Info length. Expected %d, Received %zu\n", 0, - info_length); + "SigInfo: Invalid Info length. Expected %d, Received %zu\n", + 0, info_length); goto end; } @@ -635,9 +637,9 @@ char *fdo_guid_to_string(fdo_byte_array_t *g, char *buf, int buf_sz) char *a = NULL; char hyphen = '-'; - // buffer size must be (2*16 + 4 + 1), where 2*16 is for holding GUID chars, - // +4 for holding hyphens and +1 for \0 - // return empty string, in case pre-requisites are not met + // buffer size must be (2*16 + 4 + 1), where 2*16 is for holding GUID + // chars, +4 for holding hyphens and +1 for \0 return empty string, in + // case pre-requisites are not met if (!g || !g->bytes || !buf || buf_sz < ((2 * FDO_GUID_BYTES) + 1)) { return ""; } @@ -748,8 +750,10 @@ int fdo_hash_read(fdor_t *fdor, fdo_hash_t *hp) // Read the bin character length size_t mbin_len_reported; - if (!fdor_string_length(fdor, &mbin_len_reported) || mbin_len_reported <= 0) { - LOG(LOG_ERROR, "Invalid Hash: Unable to decode length of hash!\n"); + if (!fdor_string_length(fdor, &mbin_len_reported) || + mbin_len_reported <= 0) { + LOG(LOG_ERROR, + "Invalid Hash: Unable to decode length of hash!\n"); return 0; } @@ -832,7 +836,6 @@ fdo_ip_address_t *fdo_ipaddress_alloc(void) fdo_free(fdoip); return NULL; - } /** @@ -997,7 +1000,8 @@ bool fdo_read_ipaddress(fdor_t *fdor, fdo_ip_address_t *fdoip) } size_t ip_length; - if (!fdor_string_length(fdor, &ip_length) || ip_length != IPV4_ADDR_LEN) { + if (!fdor_string_length(fdor, &ip_length) || + ip_length != IPV4_ADDR_LEN) { LOG(LOG_ERROR, "Invalid IP Address length\n"); fdo_byte_array_free(IP); return false; @@ -1023,19 +1027,21 @@ bool fdo_read_ipaddress(fdor_t *fdor, fdo_ip_address_t *fdoip) * Copy the IP Address contents stored in the input fdo_byte_array_t, into * the pre-initialized fdo_ip_address_t struct. * - * @param ip_bytes source byte array containing IP Address and its length to copy + * @param ip_bytes source byte array containing IP Address and its length to + * copy * @param fdoip pre-initialized IP Address struct as destination * @return true if the operation was a success, false otherwise */ -bool fdo_convert_to_ipaddress(fdo_byte_array_t *ip_bytes, fdo_ip_address_t *fdoip) +bool fdo_convert_to_ipaddress(fdo_byte_array_t *ip_bytes, + fdo_ip_address_t *fdoip) { if (!ip_bytes || !fdoip) { return false; } fdoip->length = ip_bytes->byte_sz; - if (memcpy_s(&fdoip->addr[0], fdoip->length, ip_bytes->bytes, ip_bytes->byte_sz) != - 0) { + if (memcpy_s(&fdoip->addr[0], fdoip->length, ip_bytes->bytes, + ip_bytes->byte_sz) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); return false; } @@ -1201,63 +1207,72 @@ bool fdo_public_key_write(fdow_t *fdow, fdo_public_key_t *pk) LOG(LOG_ERROR, "PublicKey write: Failed to write pkEnc.\n"); return false; } - switch (pk->pkenc) - { + switch (pk->pkenc) { case FDO_CRYPTO_PUB_KEY_ENCODING_CRYPTO: - LOG(LOG_ERROR, "PublicKey write: pkEnc.Crypto is not supported.\n"); + LOG(LOG_ERROR, + "PublicKey write: pkEnc.Crypto is not supported.\n"); return false; case FDO_CRYPTO_PUB_KEY_ENCODING_X509: - if (!fdow_byte_string(fdow, pk->key1->bytes, pk->key1->byte_sz)) { - LOG(LOG_ERROR, "PublicKey write: Failed to write in bytes (x509).\n"); + if (!fdow_byte_string(fdow, pk->key1->bytes, + pk->key1->byte_sz)) { + LOG(LOG_ERROR, "PublicKey write: Failed to write in " + "bytes (x509).\n"); return false; } break; case FDO_CRYPTO_PUB_KEY_ENCODING_X5CHAIN: - LOG(LOG_ERROR, "PublicKey write: pkEnc.X5CHAIN is not supported.\n"); + LOG(LOG_ERROR, + "PublicKey write: pkEnc.X5CHAIN is not supported.\n"); return false; - case FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY: - ; + case FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY:; int crv = 0; if (!fdow_start_map(fdow, 3)) { - LOG(LOG_ERROR, "PublicKey write: Failed to start COSEKey Map\n"); + LOG(LOG_ERROR, + "PublicKey write: Failed to start COSEKey Map\n"); return false; } if (!fdow_signed_int(fdow, FDO_COSE_ENC_COSEKEY_CURVE_KEY)) { - LOG(LOG_ERROR, "PublicKey write: Failed to write COSEKey key\n"); + LOG(LOG_ERROR, + "PublicKey write: Failed to write COSEKey key\n"); return false; } - crv = pk->pkalg == FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256 ? - FDO_COSE_ENC_COSEKEY_CRV_EC2_P256 : FDO_COSE_ENC_COSEKEY_CRV_EC2_P384; + crv = pk->pkalg == FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256 + ? FDO_COSE_ENC_COSEKEY_CRV_EC2_P256 + : FDO_COSE_ENC_COSEKEY_CRV_EC2_P384; if (!fdow_signed_int(fdow, crv)) { - LOG(LOG_ERROR, - "PublicKey write: Failed to write COSEKey Type value\n"); + LOG(LOG_ERROR, "PublicKey write: Failed to write " + "COSEKey Type value\n"); return false; } if (!fdow_signed_int(fdow, FDO_COSE_ENC_COSEKEY_ECX_KEY)) { - LOG(LOG_ERROR, "PublicKey write: Failed to write COSEKey X key\n"); + LOG(LOG_ERROR, + "PublicKey write: Failed to write COSEKey X key\n"); return false; } - if (!fdow_byte_string(fdow, pk->key1->bytes, pk->key1->byte_sz)) { - LOG(LOG_ERROR, - "PublicKey write: Failed to write COSEKey X value\n"); + if (!fdow_byte_string(fdow, pk->key1->bytes, + pk->key1->byte_sz)) { + LOG(LOG_ERROR, "PublicKey write: Failed to write " + "COSEKey X value\n"); return false; } if (!fdow_signed_int(fdow, FDO_COSE_ENC_COSEKEY_ECY_KEY)) { - LOG(LOG_ERROR, "PublicKey write: Failed to write COSEKey Y key\n"); + LOG(LOG_ERROR, + "PublicKey write: Failed to write COSEKey Y key\n"); return false; } - if (!fdow_byte_string(fdow, pk->key2->bytes, pk->key2->byte_sz)) { - LOG(LOG_ERROR, - "PublicKey write: Failed to write COSEKey Y value\n"); + if (!fdow_byte_string(fdow, pk->key2->bytes, + pk->key2->byte_sz)) { + LOG(LOG_ERROR, "PublicKey write: Failed to write " + "COSEKey Y value\n"); return false; } if (!fdow_end_map(fdow)) { LOG(LOG_ERROR, - "PublicKey write: Failed to end COSEKey map\n"); + "PublicKey write: Failed to end COSEKey map\n"); return false; } break; @@ -1293,12 +1308,14 @@ fdo_public_key_t *fdo_public_key_read(fdor_t *fdor) } size_t num_public_key_items, public_key_length = 0; - fdo_public_key_t *pk = fdo_public_key_alloc_empty(); // Create a Public Key + fdo_public_key_t *pk = + fdo_public_key_alloc_empty(); // Create a Public Key if (!pk) { goto err; } - if (!fdor_array_length(fdor, &num_public_key_items) || num_public_key_items != 3) { + if (!fdor_array_length(fdor, &num_public_key_items) || + num_public_key_items != 3) { LOG(LOG_ERROR, "Invalid PublicKey: Array length\n"); goto err; } @@ -1306,7 +1323,7 @@ fdo_public_key_t *fdo_public_key_read(fdor_t *fdor) LOG(LOG_ERROR, "Invalid PublicKey: Start array not found\n"); goto err; } - if (!fdor_signed_int(fdor, &pk->pkalg) || pk->pkalg != FDO_PK_ALGO) { + if (!fdor_signed_int(fdor, &pk->pkalg)) { LOG(LOG_ERROR, "Invalid PublicKey: Unable to decode pkType\n"); goto err; } @@ -1315,29 +1332,35 @@ fdo_public_key_t *fdo_public_key_read(fdor_t *fdor) goto err; } - switch (pk->pkenc) - { + switch (pk->pkenc) { case FDO_CRYPTO_PUB_KEY_ENCODING_CRYPTO: - LOG(LOG_ERROR, "Invalid PublicKey: pkEnc.Crypto is not supported.\n"); + LOG(LOG_ERROR, + "Invalid PublicKey: pkEnc.Crypto is not supported.\n"); goto err; case FDO_CRYPTO_PUB_KEY_ENCODING_X509: - if (!fdor_string_length(fdor, &public_key_length) || public_key_length <= 0) { - LOG(LOG_ERROR, "Invalid PublicKey: Unable to decode pkBody length\n"); + if (!fdor_string_length(fdor, &public_key_length) || + public_key_length <= 0) { + LOG(LOG_ERROR, "Invalid PublicKey: Unable to decode " + "pkBody length\n"); goto err; } - LOG(LOG_DEBUG, "PublicKey.pkBody length: %zu bytes\n", public_key_length); + LOG(LOG_DEBUG, "PublicKey.pkBody length: %zu bytes\n", + public_key_length); pk->key1 = fdo_byte_array_alloc(public_key_length); - if (!pk->key1 || !fdor_byte_string(fdor, pk->key1->bytes, public_key_length)) { - LOG(LOG_ERROR, "Invalid PublicKey: Unable to decode pkBody\n"); + if (!pk->key1 || !fdor_byte_string(fdor, pk->key1->bytes, + public_key_length)) { + LOG(LOG_ERROR, + "Invalid PublicKey: Unable to decode pkBody\n"); goto err; } pk->key1->byte_sz = public_key_length; break; case FDO_CRYPTO_PUB_KEY_ENCODING_X5CHAIN: - LOG(LOG_ERROR, "Invalid PublicKey: pkEnc.X5CHAIN is not supported.\n"); + LOG(LOG_ERROR, + "Invalid PublicKey: pkEnc.X5CHAIN is not supported.\n"); goto err; - case FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY: ; + case FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY:; size_t map_items = 0; int map_key = 0; int map_val_int = 0; @@ -1350,13 +1373,16 @@ fdo_public_key_t *fdo_public_key_read(fdor_t *fdor) exp_crv_val = FDO_COSE_ENC_COSEKEY_CRV_EC2_P384; #endif - if (!fdor_map_length(fdor, &map_items) || (map_items != 0 && map_items != 3)) { - LOG(LOG_ERROR, "Invalid PublicKey: Unable to decode pkBody COSEKey Map length\n"); + if (!fdor_map_length(fdor, &map_items) || + (map_items != 0 && map_items != 3)) { + LOG(LOG_ERROR, "Invalid PublicKey: Unable to decode " + "pkBody COSEKey Map length\n"); goto err; } if (!fdor_start_map(fdor)) { - LOG(LOG_ERROR, "Invalid PublicKey: Unable to start pkBody COSEKey Map\n"); + LOG(LOG_ERROR, "Invalid PublicKey: Unable to start " + "pkBody COSEKey Map\n"); goto err; } @@ -1369,66 +1395,91 @@ fdo_public_key_t *fdo_public_key_read(fdor_t *fdor) if (!fdor_is_value_signed_int(fdor)) { LOG(LOG_ERROR, - "Invalid PublicKey: Found a non-integer unknown/unsupported COSEKey key.\n"); + "Invalid PublicKey: Found a non-integer " + "unknown/unsupported COSEKey key.\n"); goto err; } if (!fdor_signed_int(fdor, &map_key) || map_key == 0) { - LOG(LOG_ERROR, "Invalid PublicKey: Failed to read COSEKey key\n"); + LOG(LOG_ERROR, "Invalid PublicKey: Failed to " + "read COSEKey key\n"); goto err; } if (map_key == FDO_COSE_ENC_COSEKEY_CURVE_KEY) { - if (!fdor_signed_int(fdor, &map_val_int) || map_val_int != exp_crv_val) { - LOG(LOG_ERROR, - "Invalid PublicKey: Failed to read/Invalid COSEKey Type value\n"); + if (!fdor_signed_int(fdor, &map_val_int) || + map_val_int != exp_crv_val) { + LOG(LOG_ERROR, "Invalid PublicKey: " + "Failed to read/Invalid " + "COSEKey Type value\n"); goto err; } } else if (map_key == FDO_COSE_ENC_COSEKEY_ECX_KEY) { - if (!fdor_string_length(fdor, &map_val_bytes_sz) || map_val_bytes_sz == 0) { - if (!fdor_byte_string(fdor, pk->key2->bytes, pk->key2->byte_sz)) { + if (!fdor_string_length(fdor, + &map_val_bytes_sz) || + map_val_bytes_sz == 0) { + if (!fdor_byte_string( + fdor, pk->key2->bytes, + pk->key2->byte_sz)) { LOG(LOG_ERROR, - "Invalid PublicKey: Failed to read COSEKey X value length\n"); + "Invalid PublicKey: Failed " + "to read COSEKey X value " + "length\n"); goto err; } } - pk->key1 = fdo_byte_array_alloc(map_val_bytes_sz); + pk->key1 = + fdo_byte_array_alloc(map_val_bytes_sz); if (!pk->key1) { - LOG(LOG_ERROR, "PublicKey1 alloc failed\n"); + LOG(LOG_ERROR, + "PublicKey1 alloc failed\n"); goto err; } - if (!fdor_byte_string(fdor, pk->key1->bytes, pk->key1->byte_sz)) { + if (!fdor_byte_string(fdor, pk->key1->bytes, + pk->key1->byte_sz)) { LOG(LOG_ERROR, - "Invalid PublicKey: Failed to read COSEKey X value\n"); + "Invalid PublicKey: Failed to read " + "COSEKey X value\n"); goto err; } } else if (map_key == FDO_COSE_ENC_COSEKEY_ECY_KEY) { - if (!fdor_string_length(fdor, &map_val_bytes_sz) || map_val_bytes_sz == 0) { - if (!fdor_byte_string(fdor, pk->key2->bytes, pk->key2->byte_sz)) { + if (!fdor_string_length(fdor, + &map_val_bytes_sz) || + map_val_bytes_sz == 0) { + if (!fdor_byte_string( + fdor, pk->key2->bytes, + pk->key2->byte_sz)) { LOG(LOG_ERROR, - "Invalid PublicKey: Failed to read COSEKey Y value length\n"); + "Invalid PublicKey: Failed " + "to read COSEKey Y value " + "length\n"); goto err; } } - pk->key2 = fdo_byte_array_alloc(map_val_bytes_sz); + pk->key2 = + fdo_byte_array_alloc(map_val_bytes_sz); if (!pk->key2) { - LOG(LOG_ERROR, "PublicKey2 alloc failed\n"); + LOG(LOG_ERROR, + "PublicKey2 alloc failed\n"); goto err; } - if (!fdor_byte_string(fdor, pk->key2->bytes, pk->key2->byte_sz)) { + if (!fdor_byte_string(fdor, pk->key2->bytes, + pk->key2->byte_sz)) { LOG(LOG_ERROR, - "Invalid PublicKey: Failed to read COSEKey Y value\n"); + "Invalid PublicKey: Failed to read " + "COSEKey Y value\n"); goto err; } } else { LOG(LOG_ERROR, - "Invalid PublicKey: Found unknown/unsupported COSEKey key\n"); + "Invalid PublicKey: Found " + "unknown/unsupported COSEKey key\n"); goto err; } } if (!fdor_end_map(fdor)) { LOG(LOG_ERROR, - "Invalid PublicKey: Failed to end COSEKey map\n"); + "Invalid PublicKey: Failed to end COSEKey map\n"); goto err; } break; @@ -1558,14 +1609,14 @@ bool fdo_rendezvous_write(fdow_t *fdow, fdo_rendezvous_t *rv) bool ret = false; - // use this temporary FDOW to CBOR-encode RVValue(512 bytes should be enough, update if needed) - // the resulting RVValue is, then bstr-encoded + // use this temporary FDOW to CBOR-encode RVValue(512 bytes should be + // enough, update if needed) the resulting RVValue is, then bstr-encoded fdow_t temp_fdow = {0}; if (!fdow_init(&temp_fdow) || - !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_512_BYTES) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, - "RendezvousInstr: FDOW Initialization/Allocation failed!\n"); + !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_512_BYTES) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "RendezvousInstr: FDOW " + "Initialization/Allocation failed!\n"); goto end; } @@ -1576,129 +1627,151 @@ bool fdo_rendezvous_write(fdow_t *fdow, fdo_rendezvous_t *rv) if (rv->dev_only != NULL && *rv->dev_only == true) { if (!fdow_signed_int(fdow, RVDEVONLY)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVDevOnly\n"); + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVDevOnly\n"); goto end; } } if (rv->owner_only != NULL && *rv->owner_only == true) { if (!fdow_signed_int(fdow, RVOWNERONLY)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVOwnerOnly\n"); + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVOwnerOnly\n"); goto end; } } if (rv->ip != NULL) { if (!fdow_signed_int(fdow, RVIPADDRESS) || - !fdow_byte_string(&temp_fdow, (uint8_t *) &rv->ip->addr, rv->ip->length)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVIPAddress\n"); + !fdow_byte_string(&temp_fdow, (uint8_t *)&rv->ip->addr, + rv->ip->length)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVIPAddress\n"); goto end; } } if (rv->po != NULL) { if (!fdow_signed_int(fdow, RVDEVPORT) || - !fdow_signed_int(&temp_fdow, *rv->po)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVDevPort\n"); + !fdow_signed_int(&temp_fdow, *rv->po)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVDevPort\n"); goto end; } } if (rv->pow != NULL) { if (!fdow_unsigned_int(fdow, RVOWNERPORT) || - !fdow_signed_int(&temp_fdow, *rv->pow)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVOwnerPort\n"); + !fdow_signed_int(&temp_fdow, *rv->pow)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVOwnerPort\n"); goto end; } } if (rv->dn != NULL) { if (!fdow_signed_int(fdow, RVDNS) || - !fdow_text_string(&temp_fdow, rv->dn->bytes, rv->dn->byte_sz)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVDns\n"); + !fdow_text_string(&temp_fdow, rv->dn->bytes, + rv->dn->byte_sz)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVDns\n"); goto end; } } if (rv->sch != NULL) { if (!fdow_signed_int(fdow, RVSVCERTHASH) || - !fdo_hash_write(&temp_fdow, rv->sch)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVSvCertHash\n"); + !fdo_hash_write(&temp_fdow, rv->sch)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVSvCertHash\n"); goto end; } } if (rv->cch != NULL) { if (!fdow_signed_int(fdow, RVCLCERTHASH) || - !fdo_hash_write(&temp_fdow, rv->cch)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVClCertHash\n"); + !fdo_hash_write(&temp_fdow, rv->cch)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVClCertHash\n"); goto end; } } if (rv->ui != NULL) { if (!fdow_signed_int(fdow, RVUSERINPUT) || - !fdow_boolean(&temp_fdow, *rv->ui)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVUserInput\n"); + !fdow_boolean(&temp_fdow, *rv->ui)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVUserInput\n"); goto end; } } if (rv->ss != NULL) { if (!fdow_signed_int(fdow, RVWIFISSID) || - !fdow_text_string(&temp_fdow, rv->ss->bytes, rv->ss->byte_sz)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVWiFiSsid\n"); + !fdow_text_string(&temp_fdow, rv->ss->bytes, + rv->ss->byte_sz)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVWiFiSsid\n"); goto end; } } if (rv->pw != NULL) { if (!fdow_signed_int(fdow, RVWIFIPW) || - !fdow_text_string(&temp_fdow, rv->pw->bytes, rv->pw->byte_sz)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVWifiPw\n"); + !fdow_text_string(&temp_fdow, rv->pw->bytes, + rv->pw->byte_sz)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVWifiPw\n"); goto end; } } if (rv->me != NULL) { if (!fdow_signed_int(fdow, RVMEDIUM) || - !fdow_unsigned_int(&temp_fdow, *rv->me)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVMedium\n"); + !fdow_unsigned_int(&temp_fdow, *rv->me)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVMedium\n"); goto end; } } if (rv->pr != NULL) { if (!fdow_signed_int(fdow, RVPROTOCOL) || - !fdow_unsigned_int(&temp_fdow, *rv->pr)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVProtocol\n"); + !fdow_unsigned_int(&temp_fdow, *rv->pr)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVProtocol\n"); goto end; } } if (rv->delaysec != NULL) { if (!fdow_signed_int(fdow, RVDELAYSEC) || - !fdow_unsigned_int(&temp_fdow, *rv->delaysec)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVDelaysec\n"); + !fdow_unsigned_int(&temp_fdow, *rv->delaysec)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVDelaysec\n"); goto end; } } if (rv->bypass != NULL && *rv->bypass == true) { if (!fdow_signed_int(fdow, RVBYPASS)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVBypass\n"); + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVBypass\n"); goto end; } } if (rv->num_params == 2) { if (!fdow_encoded_length(&temp_fdow, &temp_fdow.b.block_size) || - temp_fdow.b.block_size == 0) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to find encoded length\n"); + temp_fdow.b.block_size == 0) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to find encoded length\n"); goto end; } - if (!fdow_byte_string(fdow, temp_fdow.b.block, temp_fdow.b.block_size)) { - LOG(LOG_ERROR, "RendezvousInstr: Failed to write RVValue\n"); + if (!fdow_byte_string(fdow, temp_fdow.b.block, + temp_fdow.b.block_size)) { + LOG(LOG_ERROR, + "RendezvousInstr: Failed to write RVValue\n"); ret = false; } } @@ -1736,7 +1809,8 @@ bool fdo_rendezvous_read(fdor_t *fdor, fdo_rendezvous_t *rv) } size_t num_rv_instr_items = 0; - if (!fdor_array_length(fdor, &num_rv_instr_items) || num_rv_instr_items <= 0) { + if (!fdor_array_length(fdor, &num_rv_instr_items) || + num_rv_instr_items <= 0) { LOG(LOG_ERROR, "RendezvousInstr is empty\n"); return false; } @@ -1771,16 +1845,18 @@ bool fdo_rendezvous_read(fdor_t *fdor, fdo_rendezvous_t *rv) return false; } - // bstr-unwrap RVValue, and then parse the same same using temporary FDOR - // the 3 keys don't have RVValue + // bstr-unwrap RVValue, and then parse the same same using temporary + // FDOR the 3 keys don't have RVValue if (key != RVDEVONLY && key != RVOWNERONLY && key != RVBYPASS) { if (!fdor_string_length(fdor, &rvvalue_sz) || rvvalue_sz == 0) { - LOG(LOG_ERROR, "RendezvousInstr RVValue length read error\n"); + LOG(LOG_ERROR, + "RendezvousInstr RVValue length read error\n"); return false; } rvvalue = fdo_alloc(sizeof(uint8_t) * rvvalue_sz); if (memset_s(rvvalue, rvvalue_sz, 0) != 0) { - LOG(LOG_ERROR, "RendezvousInstr RVValue Memset error\n"); + LOG(LOG_ERROR, + "RendezvousInstr RVValue Memset error\n"); return false; } if (!fdor_byte_string(fdor, rvvalue, rvvalue_sz)) { @@ -1791,22 +1867,21 @@ bool fdo_rendezvous_read(fdor_t *fdor, fdo_rendezvous_t *rv) if (rvvalue) { if (!fdor_init(&temp_fdor) || - !fdo_block_alloc_with_size(&temp_fdor.b, rvvalue_sz)) { - LOG(LOG_ERROR, - "Failed to setup temporary FDOR\n"); + !fdo_block_alloc_with_size(&temp_fdor.b, rvvalue_sz)) { + LOG(LOG_ERROR, "Failed to setup temporary FDOR\n"); goto end; } if (0 != memcpy_s(temp_fdor.b.block, temp_fdor.b.block_size, - rvvalue, rvvalue_sz)) { - LOG(LOG_ERROR, - "Failed to copy temporary unwrapped Header content\n"); + rvvalue, rvvalue_sz)) { + LOG(LOG_ERROR, "Failed to copy temporary unwrapped " + "Header content\n"); goto end; } if (!fdor_parser_init(&temp_fdor)) { LOG(LOG_ERROR, - "Failed to init temporary FDOR parser\n"); + "Failed to init temporary FDOR parser\n"); goto end; } } @@ -2040,7 +2115,8 @@ bool fdo_rendezvous_read(fdor_t *fdor, fdo_rendezvous_t *rv) LOG(LOG_ERROR, "RVDELAYSEC Alloc failed\n"); goto end; } - if (!fdor_unsigned_int(&temp_fdor, rv->delaysec) || !rv->delaysec) { + if (!fdor_unsigned_int(&temp_fdor, rv->delaysec) || + !rv->delaysec) { LOG(LOG_ERROR, "RVDELAYSEC read failed\n"); goto end; } @@ -2063,9 +2139,8 @@ bool fdo_rendezvous_read(fdor_t *fdor, fdo_rendezvous_t *rv) break; default: - LOG(LOG_ERROR, - "%s : Invalid RendezvousInstr Entry Type %s\n", - __func__, key_buf); + LOG(LOG_ERROR, "%s : Invalid RendezvousInstr Entry Type %s\n", + __func__, key_buf); goto end; // Abort due to unexpected value for key } @@ -2137,7 +2212,8 @@ void fdo_rendezvous_list_free(fdo_rendezvous_list_t *list) * @return number of entries added if success else error code */ int fdo_rendezvous_directive_add(fdo_rendezvous_list_t *list, - fdo_rendezvous_directive_t *directive) { + fdo_rendezvous_directive_t *directive) +{ if (list == NULL || directive == NULL) { return 0; } @@ -2151,14 +2227,16 @@ int fdo_rendezvous_directive_add(fdo_rendezvous_list_t *list, fdo_rendezvous_directive_t *entry_ptr = list->rv_directives; // Find the last entry while (entry_ptr->next != NULL) { - entry_ptr = (fdo_rendezvous_directive_t *)entry_ptr->next; + entry_ptr = + (fdo_rendezvous_directive_t *)entry_ptr->next; } // Now the enty_ptr is pointing to the last entry // Add the directive entry onto the end entry_ptr->next = directive; list->num_rv_directives++; } - LOG(LOG_DEBUG, "Added RendezvousDirective entry %d\n", list->num_rv_directives); + LOG(LOG_DEBUG, "Added RendezvousDirective entry %d\n", + list->num_rv_directives); return list->num_rv_directives; } @@ -2168,7 +2246,8 @@ int fdo_rendezvous_directive_add(fdo_rendezvous_list_t *list, * @param rv - pointer to the RendezvousInstr to be added to the list * @return number of entries added if success else error code */ -int fdo_rendezvous_list_add(fdo_rendezvous_directive_t *directives, fdo_rendezvous_t *rv) +int fdo_rendezvous_list_add(fdo_rendezvous_directive_t *directives, + fdo_rendezvous_t *rv) { if (directives == NULL || rv == NULL) { return 0; @@ -2190,7 +2269,8 @@ int fdo_rendezvous_list_add(fdo_rendezvous_directive_t *directives, fdo_rendezvo entry_ptr->next = rv; directives->num_entries++; } - LOG(LOG_DEBUG, "Added RendezvousInstr entry %d\n", directives->num_entries); + LOG(LOG_DEBUG, "Added RendezvousInstr entry %d\n", + directives->num_entries); return directives->num_entries; } @@ -2200,7 +2280,8 @@ int fdo_rendezvous_list_add(fdo_rendezvous_directive_t *directives, fdo_rendezvo * @param num - index of which entry (RendezvousDirective) to return. * @return fdo_rendezvous_directive_t object. */ -fdo_rendezvous_directive_t *fdo_rendezvous_directive_get(fdo_rendezvous_list_t *list, int num) +fdo_rendezvous_directive_t * +fdo_rendezvous_directive_get(fdo_rendezvous_list_t *list, int num) { int index; @@ -2216,7 +2297,9 @@ fdo_rendezvous_directive_t *fdo_rendezvous_directive_get(fdo_rendezvous_list_t * } else { // this should ideally no happen since for 'num' times, // there should be a directive present. - LOG(LOG_DEBUG, "RendezvousDirective not found for index %d\n", index); + LOG(LOG_DEBUG, + "RendezvousDirective not found for index %d\n", + index); return NULL; } } @@ -2229,7 +2312,8 @@ fdo_rendezvous_directive_t *fdo_rendezvous_directive_get(fdo_rendezvous_list_t * * @param num - index of which entry (RendezvousInstr) to return. * @return fdo_rendezvous_t object. */ -fdo_rendezvous_t *fdo_rendezvous_list_get(fdo_rendezvous_directive_t *directive, int num) +fdo_rendezvous_t *fdo_rendezvous_list_get(fdo_rendezvous_directive_t *directive, + int num) { int index; @@ -2245,7 +2329,8 @@ fdo_rendezvous_t *fdo_rendezvous_list_get(fdo_rendezvous_directive_t *directive, } else { // this should ideally no happen since for 'num' times, // there should be a directive present. - LOG(LOG_DEBUG, "RendezvousInstr not found for index %d\n", index); + LOG(LOG_DEBUG, + "RendezvousInstr not found for index %d\n", index); return NULL; } } @@ -2277,53 +2362,62 @@ int fdo_rendezvous_list_read(fdor_t *fdor, fdo_rendezvous_list_t *list) // Find out the number of RendezvousDirective(s) size_t num_rv_directives = 0; - if (!fdor_array_length(fdor, &num_rv_directives) || num_rv_directives <= 0) { - LOG(LOG_ERROR, - "%s : No RendezvousDirective(s) found\n", __func__); + if (!fdor_array_length(fdor, &num_rv_directives) || + num_rv_directives <= 0) { + LOG(LOG_ERROR, "%s : No RendezvousDirective(s) found\n", + __func__); return false; } if (!fdor_start_array(fdor)) { - LOG(LOG_ERROR, - "%s : RendezvousInfo start array not found\n", __func__); + LOG(LOG_ERROR, "%s : RendezvousInfo start array not found\n", + __func__); return false; } - LOG(LOG_DEBUG, "There are %zu RendezvousDirective(s) in the RendezvousInfo\n", - num_rv_directives); + LOG(LOG_DEBUG, + "There are %zu RendezvousDirective(s) in the RendezvousInfo\n", + num_rv_directives); size_t rv_directive_index; - for (rv_directive_index = 0; rv_directive_index < num_rv_directives; rv_directive_index++) { - LOG(LOG_DEBUG, "Processing RendezvousDirective Index %zu\n", rv_directive_index); + for (rv_directive_index = 0; rv_directive_index < num_rv_directives; + rv_directive_index++) { + LOG(LOG_DEBUG, "Processing RendezvousDirective Index %zu\n", + rv_directive_index); // Find out the number of RendezvousInstr(s) size_t num_rv_instr = 0; - if (!fdor_array_length(fdor, &num_rv_instr) || num_rv_instr <= 0) { - LOG(LOG_ERROR, - "%s : No RendezvousInstr(s) found\n", __func__); + if (!fdor_array_length(fdor, &num_rv_instr) || + num_rv_instr <= 0) { + LOG(LOG_ERROR, "%s : No RendezvousInstr(s) found\n", + __func__); return false; } LOG(LOG_DEBUG, "There are %zu RendezvousInstr(s)\n", - num_rv_instr); + num_rv_instr); if (!fdor_start_array(fdor)) { LOG(LOG_ERROR, - "%s : RendezvousDirective start array not found\n", __func__); + "%s : RendezvousDirective start array not found\n", + __func__); return false; } fdo_rendezvous_directive_t *rv_directive = - fdo_alloc(sizeof(fdo_rendezvous_directive_t)); + fdo_alloc(sizeof(fdo_rendezvous_directive_t)); if (!rv_directive) { LOG(LOG_ERROR, - "%s : RendezvousDirective alloc failed\n", __func__); + "%s : RendezvousDirective alloc failed\n", + __func__); return false; } size_t rv_instr_index; - for (rv_instr_index = 0; rv_instr_index < num_rv_instr; rv_instr_index++) { + for (rv_instr_index = 0; rv_instr_index < num_rv_instr; + rv_instr_index++) { // Read each rv entry and add to the rv list - LOG(LOG_DEBUG, "Processing RendezvousInstr Index %zu\n", rv_instr_index); + LOG(LOG_DEBUG, "Processing RendezvousInstr Index %zu\n", + rv_instr_index); fdo_rendezvous_t *rv_entry = fdo_rendezvous_alloc(); @@ -2337,14 +2431,15 @@ int fdo_rendezvous_list_read(fdor_t *fdor, fdo_rendezvous_list_t *list) } if (!fdor_end_array(fdor)) { LOG(LOG_ERROR, - "%s : RendezvousDirective end array not found\n", __func__); + "%s : RendezvousDirective end array not found\n", + __func__); return false; } fdo_rendezvous_directive_add(list, rv_directive); } if (!fdor_end_array(fdor)) { - LOG(LOG_ERROR, - "%s : RendezvousInfo end array not found\n", __func__); + LOG(LOG_ERROR, "%s : RendezvousInfo end array not found\n", + __func__); return false; } @@ -2375,27 +2470,51 @@ bool fdo_rendezvous_list_write(fdow_t *fdow, fdo_rendezvous_list_t *list) return false; } - fdow_start_array(fdow, list->num_rv_directives); + if (!fdow_start_array(fdow, list->num_rv_directives)) { + LOG(LOG_ERROR, "Failed to start array\n"); + return false; + } int rv_directive_index; - for (rv_directive_index = 0; rv_directive_index < list->num_rv_directives; - rv_directive_index++) { - fdo_rendezvous_directive_t *directive = fdo_rendezvous_directive_get(list, rv_directive_index); + for (rv_directive_index = 0; + rv_directive_index < list->num_rv_directives; + rv_directive_index++) { + fdo_rendezvous_directive_t *directive = + fdo_rendezvous_directive_get(list, rv_directive_index); if (!directive) { continue; } - fdow_start_array(fdow, directive->num_entries); + + if (!fdow_start_array(fdow, directive->num_entries)) { + LOG(LOG_ERROR, "Failed to start array\n"); + return false; + } + int rv_instr_index; - for (rv_instr_index = 0; rv_instr_index < directive->num_entries; rv_instr_index++) { - fdo_rendezvous_t *entry_Ptr = fdo_rendezvous_list_get(directive, rv_instr_index); + for (rv_instr_index = 0; + rv_instr_index < directive->num_entries; + rv_instr_index++) { + fdo_rendezvous_t *entry_Ptr = + fdo_rendezvous_list_get(directive, rv_instr_index); if (entry_Ptr == NULL) { continue; } fdo_rendezvous_write(fdow, entry_Ptr); } - fdow_end_array(fdow); + + if (!fdow_end_array(fdow)) { + LOG(LOG_ERROR, + "%s : RendezvousInfo end array not found\n", + __func__); + return false; + } + } + + if (!fdow_end_array(fdow)) { + LOG(LOG_ERROR, "%s : RendezvousInfo end array not found\n", + __func__); + return false; } - fdow_end_array(fdow); return true; } @@ -2454,57 +2573,66 @@ fdo_encrypted_packet_t *fdo_encrypted_packet_read(fdor_t *fdor) fdo_cose_encrypt0_t *cose_encrypt0 = NULL; int expected_aes_alg_type = -1; - if (!fdor){ + if (!fdor) { LOG(LOG_ERROR, "Encrypted Message Read: Invalid FDOR\n"); goto err; } pkt = fdo_encrypted_packet_alloc(); if (!pkt) { - LOG(LOG_ERROR, "Encrypted Message Read: Failed to alloc Encrypted structure\n"); + LOG(LOG_ERROR, "Encrypted Message Read: Failed to alloc " + "Encrypted structure\n"); goto err; } cose_encrypt0 = fdo_alloc(sizeof(fdo_cose_encrypt0_t)); if (!cose_encrypt0) { - LOG(LOG_ERROR, "Encrypted Message Read: Failed to alloc COSE_Encrypt0\n"); + LOG(LOG_ERROR, + "Encrypted Message Read: Failed to alloc COSE_Encrypt0\n"); goto err; } if (!fdo_cose_encrypt0_read(fdor, cose_encrypt0)) { - LOG(LOG_ERROR, "Encrypted Message Read: Failed to read COSE_Encrypt0\n"); + LOG(LOG_ERROR, + "Encrypted Message Read: Failed to read COSE_Encrypt0\n"); goto err; } // Encrypted payload that contains cipher||tag // Allocate for cipher, discarding the tag length - pkt->em_body = fdo_byte_array_alloc(cose_encrypt0->payload->byte_sz - sizeof(pkt->tag)); + pkt->em_body = fdo_byte_array_alloc(cose_encrypt0->payload->byte_sz - + sizeof(pkt->tag)); if (!pkt->em_body) { - LOG(LOG_ERROR, "Encrypted Message Read: Failed to copy COSE_Encrypt0.Payload\n"); + LOG(LOG_ERROR, "Encrypted Message Read: Failed to copy " + "COSE_Encrypt0.Payload\n"); goto err; } // copy the cipher if (memcpy_s(pkt->em_body->bytes, pkt->em_body->byte_sz, - cose_encrypt0->payload->bytes, - cose_encrypt0->payload->byte_sz - sizeof(pkt->tag)) != 0) { - LOG(LOG_ERROR, "Encrypted Message Read: Failed to copy cipher data\n"); + cose_encrypt0->payload->bytes, + cose_encrypt0->payload->byte_sz - sizeof(pkt->tag)) != 0) { + LOG(LOG_ERROR, + "Encrypted Message Read: Failed to copy cipher data\n"); goto err; } // copy the tag if (0 != memcpy_s(&pkt->tag, sizeof(pkt->tag), - cose_encrypt0->payload->bytes + pkt->em_body->byte_sz, sizeof(pkt->tag))) { + cose_encrypt0->payload->bytes + pkt->em_body->byte_sz, + sizeof(pkt->tag))) { LOG(LOG_ERROR, "Encrypted Message Read: Failed to copy tag\n"); goto err; } // copy IV that is used to decrypt the encrypted payload - // even though the IV buffer length is 16 bytes, the actual IV length is different - // for GCM vs CCM - // however, while actually using the IV, only the appropriate length of IV is read/used + // even though the IV buffer length is 16 bytes, the actual IV length is + // different for GCM vs CCM however, while actually using the IV, only + // the appropriate length of IV is read/used if (0 != memcpy_s(&pkt->iv, sizeof(pkt->iv), - &cose_encrypt0->unprotected_header->aes_iv, sizeof(cose_encrypt0->unprotected_header->aes_iv))) { - LOG(LOG_ERROR, "Encrypted Message Read: Failed to copy COSE_Encrypt0.Unprotected.AESIV\n"); + &cose_encrypt0->unprotected_header->aes_iv, + sizeof(cose_encrypt0->unprotected_header->aes_iv))) { + LOG(LOG_ERROR, "Encrypted Message Read: Failed to copy " + "COSE_Encrypt0.Unprotected.AESIV\n"); goto err; } @@ -2515,15 +2643,18 @@ fdo_encrypted_packet_t *fdo_encrypted_packet_read(fdor_t *fdor) goto err; #endif - if (cose_encrypt0->protected_header->aes_plain_type != expected_aes_alg_type) { - LOG(LOG_ERROR, "Encrypted Message Read: Unexpected AESPlainType\n"); + if (cose_encrypt0->protected_header->aes_plain_type != + expected_aes_alg_type) { + LOG(LOG_ERROR, + "Encrypted Message Read: Unexpected AESPlainType\n"); goto err; } pkt->aes_plain_type = cose_encrypt0->protected_header->aes_plain_type; fdo_cose_encrypt0_free(cose_encrypt0); cose_encrypt0 = NULL; - LOG(LOG_DEBUG, "Encrypted Message Read: Encrypted Message parsed successfully\n"); + LOG(LOG_DEBUG, + "Encrypted Message Read: Encrypted Message parsed successfully\n"); return pkt; err: fdo_encrypted_packet_free(pkt); @@ -2535,18 +2666,17 @@ fdo_encrypted_packet_t *fdo_encrypted_packet_read(fdor_t *fdor) } /** - * Write the Enc_structure (RFC 8152) used as Addditional Authenticated Data (AAD) - * for AES GCM/CCM, in the FDOW buffer. - * Enc_structure = [ - * context: "Encrypt0" - * protected: { 1:COSEEncType }, - * external_aad: bstr + * Write the Enc_structure (RFC 8152) used as Addditional Authenticated Data + *(AAD) for AES GCM/CCM, in the FDOW buffer. Enc_structure = [ context: + *"Encrypt0" protected: { 1:COSEEncType }, external_aad: bstr *] - * @param fdow - fdow_t object containing the buffer where CBOR data will be written to + * @param fdow - fdow_t object containing the buffer where CBOR data will be + *written to * @param alg_type - COSEEncType value to be used in protected header * @return true if write is successful, false otherwise. */ -bool fdo_aad_write(fdow_t *fdow, int alg_type) { +bool fdo_aad_write(fdow_t *fdow, int alg_type) +{ bool ret = false; @@ -2563,22 +2693,27 @@ bool fdo_aad_write(fdow_t *fdow, int alg_type) { goto err; } - // context is a constant chosen from a list of available values, as per RFC 8152 - // ignore the NULL terminator in the 'Context' string - if (!fdow_text_string(fdow, &enc_structure_context[0], sizeof(enc_structure_context) - 1)) { + // context is a constant chosen from a list of available values, as per + // RFC 8152 ignore the NULL terminator in the 'Context' string + if (!fdow_text_string(fdow, &enc_structure_context[0], + sizeof(enc_structure_context) - 1)) { LOG(LOG_ERROR, "Enc_Structure: Failed to write Context\n"); goto err; } - // protected header is the same as "Encrypt0" protected header structure, thus reuse - protected_header = fdo_alloc(sizeof(fdo_cose_encrypt0_protected_header_t)); + // protected header is the same as "Encrypt0" protected header + // structure, thus reuse + protected_header = + fdo_alloc(sizeof(fdo_cose_encrypt0_protected_header_t)); if (!protected_header) { - LOG(LOG_ERROR, "Enc_Structure: Failed to alloc protected header\n"); + LOG(LOG_ERROR, + "Enc_Structure: Failed to alloc protected header\n"); goto err; } protected_header->aes_plain_type = alg_type; if (!fdo_cose_encrypt0_write_protected_header(fdow, protected_header)) { - LOG(LOG_ERROR, "Enc_Structure: Failed to write protected header\n"); + LOG(LOG_ERROR, + "Enc_Structure: Failed to write protected header\n"); goto err; } @@ -2590,7 +2725,7 @@ bool fdo_aad_write(fdow_t *fdow, int alg_type) { } if (!fdow_byte_string(fdow, enc_structure_external_aad->bytes, - enc_structure_external_aad->byte_sz)) { + enc_structure_external_aad->byte_sz)) { LOG(LOG_ERROR, "Enc_Structure: Failed to write external_aad\n"); goto err; } @@ -2613,14 +2748,12 @@ bool fdo_aad_write(fdow_t *fdow, int alg_type) { } /** - * Write the EMBlock stucture (COSE_Encrypt0) in the FDOW buffer using the contents - * of fdo_encrypted_packet_t. - * ETMInnerBlock = [ - * protected: { 1:COSEEncType }, - * unprotected: { 5:AESIV } - * payload: ProtocolMessage + * Write the EMBlock stucture (COSE_Encrypt0) in the FDOW buffer using the + *contents of fdo_encrypted_packet_t. ETMInnerBlock = [ protected: { + *1:COSEEncType }, unprotected: { 5:AESIV } payload: ProtocolMessage *] - * @param fdow - fdow_t object containing the buffer where CBOR data will be written to + * @param fdow - fdow_t object containing the buffer where CBOR data will be + *written to * @param pkt - fdo_encrypted_packet_t object * @return true if write is successful, false otherwise. */ @@ -2634,8 +2767,8 @@ bool fdo_emblock_write(fdow_t *fdow, fdo_encrypted_packet_t *pkt) cose_encrypt0 = fdo_cose_encrypt0_alloc(); if (!cose_encrypt0) { - LOG(LOG_ERROR, - "Encrypted Message write: Failed to alloc COSE_Encrypt0 (ETMInnerBlock)\n"); + LOG(LOG_ERROR, "Encrypted Message write: Failed to alloc " + "COSE_Encrypt0 (ETMInnerBlock)\n"); goto err; } @@ -2643,38 +2776,39 @@ bool fdo_emblock_write(fdow_t *fdow, fdo_encrypted_packet_t *pkt) cose_encrypt0->protected_header->aes_plain_type = pkt->aes_plain_type; if (0 != memcpy_s(&cose_encrypt0->unprotected_header->aes_iv, - sizeof(cose_encrypt0->unprotected_header->aes_iv), - &pkt->iv, sizeof(pkt->iv))) { - LOG(LOG_ERROR, - "Encrypted Message write: Failed to copy IV\n"); + sizeof(cose_encrypt0->unprotected_header->aes_iv), + &pkt->iv, sizeof(pkt->iv))) { + LOG(LOG_ERROR, "Encrypted Message write: Failed to copy IV\n"); goto err; } // Allocate for payload that contains cipher||tag - cose_encrypt0->payload = fdo_byte_array_alloc(pkt->em_body->byte_sz + sizeof(pkt->tag)); + cose_encrypt0->payload = + fdo_byte_array_alloc(pkt->em_body->byte_sz + sizeof(pkt->tag)); if (!cose_encrypt0->payload) { - LOG(LOG_ERROR, - "Encrypted Message write: Failed to alloc COSE_Encrypt0.Payload\n"); + LOG(LOG_ERROR, "Encrypted Message write: Failed to alloc " + "COSE_Encrypt0.Payload\n"); goto err; } // copy the cipher data if (0 != memcpy_s(cose_encrypt0->payload->bytes, pkt->em_body->byte_sz, - pkt->em_body->bytes, pkt->em_body->byte_sz)) { - LOG(LOG_ERROR, "Encrypted Message write: Failed to copy cipher data\n"); + pkt->em_body->bytes, pkt->em_body->byte_sz)) { + LOG(LOG_ERROR, + "Encrypted Message write: Failed to copy cipher data\n"); goto err; } // copy the tag - if (0 != memcpy_s(cose_encrypt0->payload->bytes + pkt->em_body->byte_sz, sizeof(pkt->tag), - pkt->tag, sizeof(pkt->tag))) { + if (0 != memcpy_s(cose_encrypt0->payload->bytes + pkt->em_body->byte_sz, + sizeof(pkt->tag), pkt->tag, sizeof(pkt->tag))) { LOG(LOG_ERROR, "Encrypted Message write: Failed to copy tag\n"); goto err; } if (!fdo_cose_encrypt0_write(fdow, cose_encrypt0)) { LOG(LOG_ERROR, - "Encrypted Message write: Failed to write COSE_Encrypt0\n"); + "Encrypted Message write: Failed to write COSE_Encrypt0\n"); goto err; } @@ -2712,47 +2846,53 @@ bool fdo_encrypted_packet_unwind(fdor_t *fdor, fdo_encrypted_packet_t *pkt) cleartext = fdo_byte_array_alloc(0); if (cleartext == NULL) { - LOG(LOG_ERROR, "Encrypted Message (decrypt): Failed to alloc clear data\n"); + LOG(LOG_ERROR, "Encrypted Message (decrypt): Failed to alloc " + "clear data\n"); goto err; } // create temporary FDOW, use it to create AAD and then clear it. - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_256_BYTES) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, - "Encrypted Message write: FDOW Initialization/Allocation failed!\n"); + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_256_BYTES) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "Encrypted Message write: FDOW " + "Initialization/Allocation failed!\n"); goto err; } if (!fdo_aad_write(&temp_fdow, pkt->aes_plain_type)) { LOG(LOG_ERROR, - "Encrypted Message write: Failed to generate AAD\n"); + "Encrypted Message write: Failed to generate AAD\n"); goto err; } // update the final encoded length in temporary FDOW if (!fdow_encoded_length(&temp_fdow, &temp_fdow.b.block_size)) { LOG(LOG_ERROR, - "Encrypted Message write: Failed to read AAD length\n"); + "Encrypted Message write: Failed to read AAD length\n"); goto err; } /* New iv is used for each new decryption which comes from pkt*/ - if (0 != aes_decrypt_packet(pkt, cleartext, temp_fdow.b.block, temp_fdow.b.block_size)) { - LOG(LOG_ERROR, "Encrypted Message (decrypt): Failed to decrypt\n"); + if (0 != aes_decrypt_packet(pkt, cleartext, temp_fdow.b.block, + temp_fdow.b.block_size)) { + LOG(LOG_ERROR, + "Encrypted Message (decrypt): Failed to decrypt\n"); goto err; } // clear the FDOR buffer and push decrypted payload into it fdo_block_reset(&fdor->b); fdor->b.block_size = cleartext->byte_sz; - if (0 != memcpy_s(fdor->b.block, cleartext->byte_sz, - cleartext->bytes, cleartext->byte_sz)) { + if (0 != memcpy_s(fdor->b.block, cleartext->byte_sz, cleartext->bytes, + cleartext->byte_sz)) { LOG(LOG_ERROR, "Encrypted Message (decrypt): Failed to copy\n"); goto err; } - // initialize the parser once the buffer contains COSE payload to be decoded. + // initialize the parser once the buffer contains COSE payload to be + // decoded. if (!fdor_parser_init(fdor)) { - LOG(LOG_ERROR, "Encrypted Message (decrypt): Failed to initialize FDOR parser\n"); + LOG(LOG_ERROR, "Encrypted Message (decrypt): Failed to " + "initialize FDOR parser\n"); goto err; } LOG(LOG_DEBUG, "Encrypted Message (decrypt): Decryption done\n"); @@ -2775,45 +2915,50 @@ bool fdo_encrypted_packet_unwind(fdor_t *fdor, fdo_encrypted_packet_t *pkt) * At the end of this method, structure EMBlock is generated. * * @param pkt - Pointer to the Encrypted packet pkt that has to be processed. - * @param fdow - fdow_t object containing the buffer where CBOR data will be written to + * @param fdow - fdow_t object containing the buffer where CBOR data will be + * written to * @param fdow_buff_default_sz - default buffer length of fdow.b.block * @return true if all goes well, otherwise false */ bool fdo_prep_simple_encrypted_message(fdo_encrypted_packet_t *pkt, - fdow_t *fdow, size_t fdow_buff_default_sz) { + fdow_t *fdow, + size_t fdow_buff_default_sz) +{ bool ret = false; - // create temporary FDOW, use it to create Protected header map and then clear it. + // create temporary FDOW, use it to create Protected header map and then + // clear it. fdow_t temp_fdow = {0}; - if (!pkt || ! fdow) { - LOG(LOG_ERROR, - "Encrypted Message write: Invalid params\n"); + if (!pkt || !fdow) { + LOG(LOG_ERROR, "Encrypted Message write: Invalid params\n"); return false; } - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_256_BYTES) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, - "Encrypted Message write: FDOW Initialization/Allocation failed!\n"); + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_256_BYTES) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "Encrypted Message write: FDOW " + "Initialization/Allocation failed!\n"); goto exit; } if (!fdo_aad_write(&temp_fdow, pkt->aes_plain_type)) { - LOG(LOG_ERROR, - "Encrypted Message write: Failed to read COSE_Encrypt0 (EMBlock) length\n"); + LOG(LOG_ERROR, "Encrypted Message write: Failed to read " + "COSE_Encrypt0 (EMBlock) length\n"); goto exit; } // update the final encoded length in temporary FDOW if (!fdow_encoded_length(&temp_fdow, &temp_fdow.b.block_size)) { - LOG(LOG_ERROR, - "Encrypted Message write: Failed to read COSE_Encrypt0 (EMBlock) length\n"); + LOG(LOG_ERROR, "Encrypted Message write: Failed to read " + "COSE_Encrypt0 (EMBlock) length\n"); goto exit; } - if (0 != aes_encrypt_packet(pkt, fdow->b.block, fdow->b.block_size, temp_fdow.b.block, - temp_fdow.b.block_size)) { + if (0 != aes_encrypt_packet(pkt, fdow->b.block, fdow->b.block_size, + temp_fdow.b.block, + temp_fdow.b.block_size)) { LOG(LOG_ERROR, - "Encrypted Message (encrypt): Failed to encrypt\n"); + "Encrypted Message (encrypt): Failed to encrypt\n"); goto exit; } @@ -2822,15 +2967,15 @@ bool fdo_prep_simple_encrypted_message(fdo_encrypted_packet_t *pkt, fdo_block_reset(&fdow->b); fdow->b.block_size = fdow_buff_default_sz; if (!fdow_encoder_init(fdow)) { - LOG(LOG_ERROR, - "Encrypted Message (encrypt): Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, "Encrypted Message (encrypt): Failed to " + "initialize FDOW encoder\n"); goto exit; } // write the EMBlock containing the cipher text || tag as payload if (!fdo_emblock_write(fdow, pkt)) { - LOG(LOG_ERROR, - "Encrypted Message (encrypt): Failed to write COSE_Encrypt0 (EMBlock)\n"); + LOG(LOG_ERROR, "Encrypted Message (encrypt): Failed to write " + "COSE_Encrypt0 (EMBlock)\n"); goto exit; } ret = true; @@ -2843,8 +2988,8 @@ bool fdo_prep_simple_encrypted_message(fdo_encrypted_packet_t *pkt, fdo_block_reset(&fdow->b); fdow->b.block_size = fdow_buff_default_sz; if (!fdow_encoder_init(fdow)) { - LOG(LOG_ERROR, - "Encrypted Message (encrypt): Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, "Encrypted Message (encrypt): Failed to " + "initialize FDOW encoder\n"); } } return ret; @@ -2877,30 +3022,32 @@ bool fdo_encrypted_packet_windup(fdow_t *fdow, int type) // find the encoded cleartext length size_t payload_length = 0; - if (!fdow_encoded_length(fdow, &payload_length) || payload_length == 0) { - LOG(LOG_ERROR, - "Encrypted Message (encrypt): Failed to read encoded message length\n"); + if (!fdow_encoded_length(fdow, &payload_length) || + payload_length == 0) { + LOG(LOG_ERROR, "Encrypted Message (encrypt): Failed to read " + "encoded message length\n"); return ret; } fdow->b.block_size = payload_length; fdo_encrypted_packet_t *pkt = fdo_encrypted_packet_alloc(); if (!pkt) { - LOG(LOG_ERROR, - "Encrypted Message (encrypt): Failed to alloc for Encrypted message struct\n"); + LOG(LOG_ERROR, "Encrypted Message (encrypt): Failed to alloc " + "for Encrypted message struct\n"); return ret; } #if defined(COSE_ENC_TYPE) pkt->aes_plain_type = COSE_ENC_TYPE; - if (!fdo_prep_simple_encrypted_message(pkt, fdow, fdow_buff_default_sz)) { - LOG(LOG_ERROR, - "Encrypted Message (encrypt): Failed to generate Simple Encrypted Message\n"); + if (!fdo_prep_simple_encrypted_message(pkt, fdow, + fdow_buff_default_sz)) { + LOG(LOG_ERROR, "Encrypted Message (encrypt): Failed to " + "generate Simple Encrypted Message\n"); goto exit; } #else LOG(LOG_ERROR, - "Encrypted Message (encrypt): Invalid AES algorithm type\n"); + "Encrypted Message (encrypt): Invalid AES algorithm type\n"); goto exit; #endif @@ -2920,10 +3067,11 @@ bool fdo_encrypted_packet_windup(fdow_t *fdow, int type) /** * Create an EAT object with memory allocated for Protected header, * Unprotected header and Payload. - * Signature alongwith EATMAROEPREFIX and EATNonce are set to NULL initally, which - * should be initialized when needed. + * Signature alongwith EATMAROEPREFIX and EATNonce are set to NULL initally, + * which should be initialized when needed. */ -fdo_eat_t* fdo_eat_alloc(void) { +fdo_eat_t *fdo_eat_alloc(void) +{ fdo_eat_t *eat = fdo_alloc(sizeof(fdo_eat_t)); if (!eat) { @@ -2932,19 +3080,22 @@ fdo_eat_t* fdo_eat_alloc(void) { } eat->eat_ph = fdo_alloc(sizeof(fdo_eat_protected_header_t)); if (!eat->eat_ph) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to alloc Protected Header\n"); + LOG(LOG_ERROR, "Entity Attestation Token: Failed to alloc " + "Protected Header\n"); goto err; } eat->eat_uph = fdo_alloc(sizeof(fdo_eat_unprotected_header_t)); if (!eat->eat_uph) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to alloc Unprotected header\n"); + LOG(LOG_ERROR, "Entity Attestation Token: Failed to alloc " + "Unprotected header\n"); goto err; } eat->eat_uph->eatmaroeprefix = NULL; eat->eat_uph->euphnonce = NULL; - // set the payload and signature to NULL, since there's no use to allocate for them here. + // set the payload and signature to NULL, since there's no use to + // allocate for them here. eat->eat_payload = NULL; eat->eat_signature = NULL; return eat; @@ -2958,7 +3109,8 @@ fdo_eat_t* fdo_eat_alloc(void) { /** * Free an EAT object for which memory has been allocated previously. */ -void fdo_eat_free(fdo_eat_t *eat) { +void fdo_eat_free(fdo_eat_t *eat) +{ if (!eat) { return; @@ -2987,18 +3139,21 @@ void fdo_eat_free(fdo_eat_t *eat) { } /** - * Write an Entity Attestation Token by CBOR encoding the contents of the given EAT object. + * Write an Entity Attestation Token by CBOR encoding the contents of the given + * EAT object. * [ * protected header, * unprotected header, * payload, // bstr * signature // bstr * ] - * @param fdow - fdow_t object holding the buffer where CBOR data will be written to + * @param fdow - fdow_t object holding the buffer where CBOR data will be + * written to * @param eat - fdo_eat_t object that holds the EAT parameters * @return true, if write was a success. False otherwise. */ -bool fdo_eat_write(fdow_t *fdow, fdo_eat_t *eat) { +bool fdo_eat_write(fdow_t *fdow, fdo_eat_t *eat) +{ if (!fdow || !eat) { LOG(LOG_ERROR, "Entity Attestation Token: Invalid params\n"); @@ -3006,112 +3161,129 @@ bool fdo_eat_write(fdow_t *fdow, fdo_eat_t *eat) { } if (!fdow_tag(fdow, FDO_COSE_TAG_SIGN1)) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to write Tag\n"); + LOG(LOG_ERROR, + "Entity Attestation Token: Failed to write Tag\n"); return false; } if (!fdow_start_array(fdow, 4)) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to write start array\n"); + LOG(LOG_ERROR, + "Entity Attestation Token: Failed to write start array\n"); return false; } if (!fdo_eat_write_protected_header(fdow, eat->eat_ph)) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to write protected header\n"); + LOG(LOG_ERROR, "Entity Attestation Token: Failed to write " + "protected header\n"); return false; } if (!fdo_eat_write_unprotected_header(fdow, eat->eat_uph)) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to write unprotected header\n"); + LOG(LOG_ERROR, "Entity Attestation Token: Failed to write " + "unprotected header\n"); return false; } - if (!fdow_byte_string(fdow, eat->eat_payload->bytes, eat->eat_payload->byte_sz)) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to write payload\n"); + if (!fdow_byte_string(fdow, eat->eat_payload->bytes, + eat->eat_payload->byte_sz)) { + LOG(LOG_ERROR, + "Entity Attestation Token: Failed to write payload\n"); return false; } - if (!fdow_byte_string(fdow, eat->eat_signature->bytes, eat->eat_signature->byte_sz)) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to write signature\n"); + if (!fdow_byte_string(fdow, eat->eat_signature->bytes, + eat->eat_signature->byte_sz)) { + LOG(LOG_ERROR, + "Entity Attestation Token: Failed to write signature\n"); return false; } if (!fdow_end_array(fdow)) { - LOG(LOG_ERROR, "Entity Attestation Token: Failed to write end array\n"); + LOG(LOG_ERROR, + "Entity Attestation Token: Failed to write end array\n"); return false; } return true; } /** - * Create EAT.EATProtectedHeaders (CBOR map) as CBOR bytes using the given contents. + * Create EAT.EATProtectedHeaders (CBOR map) as CBOR bytes using the given + * contents. * { * keyAlg: * } * Return true, if write was a success. False otherwise. */ -bool fdo_eat_write_protected_header(fdow_t *fdow, fdo_eat_protected_header_t *eat_ph) { +bool fdo_eat_write_protected_header(fdow_t *fdow, + fdo_eat_protected_header_t *eat_ph) +{ bool ret = false; fdo_byte_array_t *enc_ph = NULL; - // create temporary FDOW, use it to create Protected header map and then clear it. + // create temporary FDOW, use it to create Protected header map and then + // clear it. fdow_t temp_fdow = {0}; if (!fdow || !eat_ph) { - LOG(LOG_ERROR, - "Entity Attestation Token Protected header: Invalid params\n"); + LOG(LOG_ERROR, "Entity Attestation Token Protected header: " + "Invalid params\n"); return false; } - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_128_BYTES) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, - "Entity Attestation Token Protected header: FDOW Initialization/Allocation failed!\n"); + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_128_BYTES) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "Entity Attestation Token Protected header: " + "FDOW Initialization/Allocation failed!\n"); goto end; } if (!fdow_start_map(&temp_fdow, 1)) { - LOG(LOG_ERROR, - "Entity Attestation Token Protected header: Failed to write start map\n"); + LOG(LOG_ERROR, "Entity Attestation Token Protected header: " + "Failed to write start map\n"); goto end; } if (!fdow_signed_int(&temp_fdow, FDO_COSE_ALG_KEY)) { - LOG(LOG_ERROR, - "Entity Attestation Token Protected header: Failed to write CoseAlg Key\n"); + LOG(LOG_ERROR, "Entity Attestation Token Protected header: " + "Failed to write CoseAlg Key\n"); goto end; } if (!fdow_signed_int(&temp_fdow, eat_ph->ph_sig_alg)) { - LOG(LOG_ERROR, - "Entity Attestation Token Protected header: Failed to write CoseAlg Value\n"); + LOG(LOG_ERROR, "Entity Attestation Token Protected header: " + "Failed to write CoseAlg Value\n"); goto end; } if (!fdow_end_map(&temp_fdow)) { - LOG(LOG_ERROR, - "Entity Attestation Token Protected header: Failed to write end map\n"); + LOG(LOG_ERROR, "Entity Attestation Token Protected header: " + "Failed to write end map\n"); goto end; } size_t enc_ph_length = 0; - if (!fdow_encoded_length(&temp_fdow, &enc_ph_length) || enc_ph_length == 0) { - LOG(LOG_ERROR, "Entity Attestation Token Protected header:: Failed to find encoded length\n"); + if (!fdow_encoded_length(&temp_fdow, &enc_ph_length) || + enc_ph_length == 0) { + LOG(LOG_ERROR, "Entity Attestation Token Protected header:: " + "Failed to find encoded length\n"); goto end; } temp_fdow.b.block_size = enc_ph_length; // Set the encoded payload into buffer - enc_ph = - fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, temp_fdow.b.block_size); + enc_ph = fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, + temp_fdow.b.block_size); if (!enc_ph) { LOG(LOG_ERROR, - "Entity Attestation Token Protected header: Failed to alloc for encoded Protected header\n"); + "Entity Attestation Token Protected header: Failed to " + "alloc for encoded Protected header\n"); goto end; } // finally, wrap the protected header into a bstr if (!fdow_byte_string(fdow, enc_ph->bytes, enc_ph->byte_sz)) { - LOG(LOG_ERROR, - "Entity Attestation Token Protected header: Failed to write Protected header as bstr\n"); + LOG(LOG_ERROR, "Entity Attestation Token Protected header: " + "Failed to write Protected header as bstr\n"); goto end; } ret = true; @@ -3126,18 +3298,21 @@ bool fdo_eat_write_protected_header(fdow_t *fdow, fdo_eat_protected_header_t *ea } /** - * Create EAT.EATUnprotectedHeaders (CBOR Map) as CBOR bytes using the given contents. + * Create EAT.EATUnprotectedHeaders (CBOR Map) as CBOR bytes using the given + * contents. * { * EATMAROEPrefix:, // optional element * EUPHNonce: // optional element * } * Return true, if write was a success. False otherwise. */ -bool fdo_eat_write_unprotected_header(fdow_t *fdow, fdo_eat_unprotected_header_t *eat_uph) { +bool fdo_eat_write_unprotected_header(fdow_t *fdow, + fdo_eat_unprotected_header_t *eat_uph) +{ if (!fdow || !eat_uph) { - LOG(LOG_ERROR, - "Entity Attestation Token Unprotected header: Invalid params\n"); + LOG(LOG_ERROR, "Entity Attestation Token Unprotected header: " + "Invalid params\n"); return false; } @@ -3150,8 +3325,8 @@ bool fdo_eat_write_unprotected_header(fdow_t *fdow, fdo_eat_unprotected_header_t num_uph_elements++; } if (!fdow_start_map(fdow, num_uph_elements)) { - LOG(LOG_ERROR, - "Entity Attestation Token Unprotected header: Failed to write start map\n"); + LOG(LOG_ERROR, "Entity Attestation Token Unprotected header: " + "Failed to write start map\n"); return false; } @@ -3159,13 +3334,16 @@ bool fdo_eat_write_unprotected_header(fdow_t *fdow, fdo_eat_unprotected_header_t if (eat_uph->eatmaroeprefix) { if (!fdow_signed_int(fdow, FDO_EAT_MAROE_PREFIX_KEY)) { LOG(LOG_ERROR, - "Entity Attestation Token Unprotected header: Failed to write EATMAROEPrefix Key\n"); + "Entity Attestation Token Unprotected header: " + "Failed to write EATMAROEPrefix Key\n"); return false; } - if (!fdow_byte_string(fdow, eat_uph->eatmaroeprefix->bytes, eat_uph->eatmaroeprefix->byte_sz)) { + if (!fdow_byte_string(fdow, eat_uph->eatmaroeprefix->bytes, + eat_uph->eatmaroeprefix->byte_sz)) { LOG(LOG_ERROR, - "Entity Attestation Token Unprotected header: Failed to write EATMAROEPrefix value\n"); + "Entity Attestation Token Unprotected header: " + "Failed to write EATMAROEPrefix value\n"); return false; } } @@ -3174,29 +3352,32 @@ bool fdo_eat_write_unprotected_header(fdow_t *fdow, fdo_eat_unprotected_header_t if (eat_uph->euphnonce) { if (!fdow_signed_int(fdow, FDO_EAT_EUPHNONCE_KEY)) { LOG(LOG_ERROR, - "Entity Attestation Token Unprotected header: Failed to write EUPHNonce Key\n"); + "Entity Attestation Token Unprotected header: " + "Failed to write EUPHNonce Key\n"); return false; } - if (!fdow_byte_string(fdow, eat_uph->euphnonce->bytes, eat_uph->euphnonce->byte_sz)) { + if (!fdow_byte_string(fdow, eat_uph->euphnonce->bytes, + eat_uph->euphnonce->byte_sz)) { LOG(LOG_ERROR, - "Entity Attestation Token Unprotected header: Failed to write EUPHNonce Value\n"); + "Entity Attestation Token Unprotected header: " + "Failed to write EUPHNonce Value\n"); return false; } } if (!fdow_end_map(fdow)) { - LOG(LOG_ERROR, - "Entity Attestation Token Unprotected header: Failed to write end map\n"); + LOG(LOG_ERROR, "Entity Attestation Token Unprotected header: " + "Failed to write end map\n"); return false; } return true; } /** - * Create EAT.EATPayloadBaseMap (CBOR Map) as CBOR bytes using the given contents. - * Before sending it across, the resulting encoded contents need to be CBOR encoded again - * into a bstr CBOR type. + * Create EAT.EATPayloadBaseMap (CBOR Map) as CBOR bytes using the given + * contents. Before sending it across, the resulting encoded contents need to be + * CBOR encoded again into a bstr CBOR type. * { * EAT-UEID:, * EAT-NONCE:, @@ -3204,80 +3385,89 @@ bool fdo_eat_write_unprotected_header(fdow_t *fdow, fdo_eat_unprotected_header_t * } * Return true, if write was a success. False otherwise. */ -bool fdo_eat_write_payloadbasemap(fdow_t *fdow, fdo_eat_payload_base_map_t *eat_payload) { +bool fdo_eat_write_payloadbasemap(fdow_t *fdow, + fdo_eat_payload_base_map_t *eat_payload) +{ size_t num_payload_elements = 2; if (!fdow) { - LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Invalid params\n"); + LOG(LOG_ERROR, "Entity Attestation Token PayloadBaseMap: " + "Invalid params\n"); return false; } if (eat_payload->eatpayloads) { - LOG(LOG_DEBUG, - "Entity Attestation Token PayloadBaseMap: EATPayload to be written\n"); + LOG(LOG_DEBUG, "Entity Attestation Token PayloadBaseMap: " + "EATPayload to be written\n"); num_payload_elements = 3; } if (!fdow_start_map(fdow, num_payload_elements)) { - LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write start map\n"); + LOG(LOG_ERROR, "Entity Attestation Token PayloadBaseMap: " + "Failed to write start map\n"); return false; } if (!fdow_signed_int(fdow, FDO_EATUEID_KEY)) { - LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write EAT-UEID Key\n"); + LOG(LOG_ERROR, "Entity Attestation Token PayloadBaseMap: " + "Failed to write EAT-UEID Key\n"); return false; } - if (!fdow_byte_string(fdow, eat_payload->eatueid, sizeof(eat_payload->eatueid))) { - LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write EAT-UEID value\n"); + if (!fdow_byte_string(fdow, eat_payload->eatueid, + sizeof(eat_payload->eatueid))) { + LOG(LOG_ERROR, "Entity Attestation Token PayloadBaseMap: " + "Failed to write EAT-UEID value\n"); return false; } if (!fdow_signed_int(fdow, FDO_EATNONCE_KEY)) { - LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write EAT-NONCE Key\n"); + LOG(LOG_ERROR, "Entity Attestation Token PayloadBaseMap: " + "Failed to write EAT-NONCE Key\n"); return false; } - if (!fdow_byte_string(fdow, eat_payload->eatnonce, sizeof(eat_payload->eatnonce))) { - LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write EAT-NONCE value\n"); + if (!fdow_byte_string(fdow, eat_payload->eatnonce, + sizeof(eat_payload->eatnonce))) { + LOG(LOG_ERROR, "Entity Attestation Token PayloadBaseMap: " + "Failed to write EAT-NONCE value\n"); return false; } if (num_payload_elements == 3) { if (!fdow_signed_int(fdow, FDO_EATFDO)) { LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write EAT-FDO Key\n"); + "Entity Attestation Token PayloadBaseMap: Failed " + "to write EAT-FDO Key\n"); return false; } - // EATPayloads is an array of size 1 as per the usage in the FDO specification. + // EATPayloads is an array of size 1 as per the usage in the FDO + // specification. if (!fdow_start_array(fdow, 1)) { LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write start array\n"); + "Entity Attestation Token PayloadBaseMap: Failed " + "to write start array\n"); return false; } - if (!fdow_byte_string(fdow, - eat_payload->eatpayloads->bytes, eat_payload->eatpayloads->byte_sz)) { + if (!fdow_byte_string(fdow, eat_payload->eatpayloads->bytes, + eat_payload->eatpayloads->byte_sz)) { LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write EAT-FDO value\n"); + "Entity Attestation Token PayloadBaseMap: Failed " + "to write EAT-FDO value\n"); return false; } if (!fdow_end_array(fdow)) { LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write end array\n"); + "Entity Attestation Token PayloadBaseMap: Failed " + "to write end array\n"); return false; } } if (!fdow_end_map(fdow)) { - LOG(LOG_ERROR, - "Entity Attestation Token PayloadBaseMap: Failed to write end map\n"); + LOG(LOG_ERROR, "Entity Attestation Token PayloadBaseMap: " + "Failed to write end map\n"); return false; } return true; @@ -3297,14 +3487,16 @@ bool fdo_eat_write_payloadbasemap(fdow_t *fdow, fdo_eat_payload_base_map_t *eat_ * @param eat_payload - EAT Payload * @param external_aad - External AAD. If NULL, empty bstr will be written, else * the AAD bytes will be written - * @param sig_structure - Out buffer to store the constructred CBOR encoded Sig_structure. - * Memory allocation will be done inside this method, if the operation is successful. - * It will be NULL otherwise. + * @param sig_structure - Out buffer to store the constructred CBOR encoded + * Sig_structure. Memory allocation will be done inside this method, if the + * operation is successful. It will be NULL otherwise. * @return true, if read was a success. False otherwise. */ bool fdo_eat_write_sigstructure(fdo_eat_protected_header_t *eat_ph, - fdo_byte_array_t *eat_payload, fdo_byte_array_t *external_aad, - fdo_byte_array_t **sig_structure) { + fdo_byte_array_t *eat_payload, + fdo_byte_array_t *external_aad, + fdo_byte_array_t **sig_structure) +{ bool ret = false; char context[] = "Signature1"; @@ -3318,21 +3510,26 @@ bool fdo_eat_write_sigstructure(fdo_eat_protected_header_t *eat_ph, } // size of the Sigstruct CBOR encoded buffer - // provide buffer of 128 bytes for protected header + context + additional CBOR encoding + // provide buffer of 128 bytes for protected header + context + + // additional CBOR encoding if (external_aad) { - sig_struct_sz = eat_payload->byte_sz + external_aad->byte_sz + BUFF_SIZE_128_BYTES; + sig_struct_sz = eat_payload->byte_sz + external_aad->byte_sz + + BUFF_SIZE_128_BYTES; } else { sig_struct_sz = eat_payload->byte_sz + BUFF_SIZE_128_BYTES; } - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, sig_struct_sz) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, "EAT Sig_structure: FDOW Initialization/Allocation failed!\n"); + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, sig_struct_sz) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "EAT Sig_structure: FDOW " + "Initialization/Allocation failed!\n"); goto end; } if (!fdow_start_array(&temp_fdow, 4)) { - LOG(LOG_ERROR, "EAT Sig_structure: Failed to write start array\n"); + LOG(LOG_ERROR, + "EAT Sig_structure: Failed to write start array\n"); return false; } @@ -3342,51 +3539,60 @@ bool fdo_eat_write_sigstructure(fdo_eat_protected_header_t *eat_ph, } if (!fdo_eat_write_protected_header(&temp_fdow, eat_ph)) { - LOG(LOG_ERROR, "EAT Sig_structure: Failed to write protected header\n"); + LOG(LOG_ERROR, + "EAT Sig_structure: Failed to write protected header\n"); return false; } if (external_aad) { - if (!fdow_byte_string(&temp_fdow, external_aad->bytes, external_aad->byte_sz)) { - LOG(LOG_ERROR, "EAT Sig_structure: Failed to write external_aad\n"); + if (!fdow_byte_string(&temp_fdow, external_aad->bytes, + external_aad->byte_sz)) { + LOG(LOG_ERROR, "EAT Sig_structure: Failed to write " + "external_aad\n"); goto end; } } else { empty_byte_array = fdo_byte_array_alloc(0); if (!empty_byte_array) { - LOG(LOG_ERROR, "EAT Sig_structure: Byte Array Alloc failed\n"); + LOG(LOG_ERROR, + "EAT Sig_structure: Byte Array Alloc failed\n"); return false; } - if (!fdow_byte_string(&temp_fdow, empty_byte_array->bytes, empty_byte_array->byte_sz)) { - LOG(LOG_ERROR, "EAT Sig_structure: Failed to write external_aad\n"); + if (!fdow_byte_string(&temp_fdow, empty_byte_array->bytes, + empty_byte_array->byte_sz)) { + LOG(LOG_ERROR, "EAT Sig_structure: Failed to write " + "external_aad\n"); goto end; } } - if (!fdow_byte_string(&temp_fdow, eat_payload->bytes, eat_payload->byte_sz)) { + if (!fdow_byte_string(&temp_fdow, eat_payload->bytes, + eat_payload->byte_sz)) { LOG(LOG_ERROR, "EAT Sig_structure: Failed to write payload\n"); goto end; } if (!fdow_end_array(&temp_fdow)) { - LOG(LOG_ERROR, "EAT Sig_structure: Failed to write end array\n"); + LOG(LOG_ERROR, + "EAT Sig_structure: Failed to write end array\n"); goto end; } enc_length = 0; if (!fdow_encoded_length(&temp_fdow, &enc_length) || enc_length == 0) { - LOG(LOG_ERROR, "EAT Sig_structure: Failed to find encoded length of " - "Sig_structure array as bstr\n"); + LOG(LOG_ERROR, + "EAT Sig_structure: Failed to find encoded length of " + "Sig_structure array as bstr\n"); goto end; } // Alocate and copy the encoded Sig_sturcture bstr *sig_structure = - fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, enc_length); + fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, enc_length); if (!(*sig_structure)) { - LOG(LOG_ERROR, - "EAT Sig_structure: Failed to alloc output Sig_structure\n"); + LOG(LOG_ERROR, "EAT Sig_structure: Failed to alloc output " + "Sig_structure\n"); goto end; } @@ -3402,9 +3608,11 @@ bool fdo_eat_write_sigstructure(fdo_eat_protected_header_t *eat_ph, } /** - * Free the given COSE_Sign1 object for which memory has been allocated previously. + * Free the given COSE_Sign1 object for which memory has been allocated + * previously. */ -void fdo_cose_free(fdo_cose_t *cose) { +void fdo_cose_free(fdo_cose_t *cose) +{ if (!cose) { return; } @@ -3426,13 +3634,16 @@ void fdo_cose_free(fdo_cose_t *cose) { } /** - * Read CoseSignature.COSEProtectedHeaders (CBOR map) into the given fdo_cose_protected_header_t object. + * Read CoseSignature.COSEProtectedHeaders (CBOR map) into the given + * fdo_cose_protected_header_t object. * { * keyAlg: * } * Return true, if read was a success. False otherwise. */ -bool fdo_cose_read_protected_header(fdor_t *fdor, fdo_cose_protected_header_t *cose_ph) { +bool fdo_cose_read_protected_header(fdor_t *fdor, + fdo_cose_protected_header_t *cose_ph) +{ if (!fdor || !cose_ph) { LOG(LOG_ERROR, "COSE Protected header: Invalid params\n"); @@ -3441,71 +3652,72 @@ bool fdo_cose_read_protected_header(fdor_t *fdor, fdo_cose_protected_header_t *c fdor_t temp_fdor; if (memset_s(&temp_fdor, sizeof(fdor_t), 0) != 0) { - LOG(LOG_ERROR, "COSE Protected header: Failed to intialize temporary FDOR\n"); + LOG(LOG_ERROR, "COSE Protected header: Failed to intialize " + "temporary FDOR\n"); return false; } size_t var_length = 0; - if (!fdor_string_length(fdor, &var_length) || - var_length == 0) { - LOG(LOG_ERROR, "COSE Protected header: Failed to read payload length\n"); + if (!fdor_string_length(fdor, &var_length) || var_length == 0) { + LOG(LOG_ERROR, + "COSE Protected header: Failed to read payload length\n"); return false; } fdo_byte_array_t *ph_as_bstr = fdo_byte_array_alloc(var_length); if (!ph_as_bstr) { - LOG(LOG_ERROR, - "COSE Protected header: Failed to alloc for COSE Protected Header as bstr\n"); + LOG(LOG_ERROR, "COSE Protected header: Failed to alloc for " + "COSE Protected Header as bstr\n"); return false; } if (!fdor_byte_string(fdor, ph_as_bstr->bytes, ph_as_bstr->byte_sz)) { - LOG(LOG_ERROR, - "COSE Protected header: Failed to read COSE Protected Header as bstr\n"); + LOG(LOG_ERROR, "COSE Protected header: Failed to read COSE " + "Protected Header as bstr\n"); goto end; } // create a temporary FDOR to read (unwrap) the header contents as map if (!fdor_init(&temp_fdor) || - !fdo_block_alloc_with_size(&temp_fdor.b, ph_as_bstr->byte_sz)) { + !fdo_block_alloc_with_size(&temp_fdor.b, ph_as_bstr->byte_sz)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to setup temporary FDOR\n"); + "COSE Protected header: Failed to setup temporary FDOR\n"); goto end; } if (0 != memcpy_s(temp_fdor.b.block, temp_fdor.b.block_size, - ph_as_bstr->bytes, ph_as_bstr->byte_sz)) { - LOG(LOG_ERROR, - "COSE Protected header: Failed to copy temporary unwrapped Header content\n"); + ph_as_bstr->bytes, ph_as_bstr->byte_sz)) { + LOG(LOG_ERROR, "COSE Protected header: Failed to copy " + "temporary unwrapped Header content\n"); goto end; } if (!fdor_parser_init(&temp_fdor)) { - LOG(LOG_ERROR, - "COSE Protected header: Failed to init temporary FDOR parser\n"); + LOG(LOG_ERROR, "COSE Protected header: Failed to init " + "temporary FDOR parser\n"); goto end; } if (!fdor_start_map(&temp_fdor)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to read start map\n"); + "COSE Protected header: Failed to read start map\n"); goto end; } int cose_alg_key = 1; if (!fdor_signed_int(&temp_fdor, &cose_alg_key) || cose_alg_key != 1) { LOG(LOG_ERROR, - "COSE Protected header: Failed to read CoseAlg Key\n"); + "COSE Protected header: Failed to read CoseAlg Key\n"); goto end; } if (!fdor_signed_int(&temp_fdor, &cose_ph->ph_sig_alg)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to read CoseAlg Value\n"); + "COSE Protected header: Failed to read CoseAlg Value\n"); goto end; } if (!fdor_end_map(&temp_fdor)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to read end map\n"); + "COSE Protected header: Failed to read end map\n"); goto end; } end: @@ -3523,7 +3735,9 @@ bool fdo_cose_read_protected_header(fdor_t *fdor, fdo_cose_protected_header_t *c * Reads and pushes the fields CUPHOWNER and CUPHNONCE otherwise. * Return true, if read was a success. False otherwise. */ -bool fdo_cose_read_unprotected_header(fdor_t *fdor, fdo_cose_unprotected_header_t *cose_uph) { +bool fdo_cose_read_unprotected_header(fdor_t *fdor, + fdo_cose_unprotected_header_t *cose_uph) +{ int result = 0; size_t map_items = 0; @@ -3533,59 +3747,68 @@ bool fdo_cose_read_unprotected_header(fdor_t *fdor, fdo_cose_unprotected_header_ return false; } - if (!fdor_map_length(fdor, &map_items) || (map_items != 0 && map_items != 2)) { + if (!fdor_map_length(fdor, &map_items) || + (map_items != 0 && map_items != 2)) { LOG(LOG_ERROR, - "COSE Unprotected header: Invalid map length.\n"); + "COSE Unprotected header: Invalid map length.\n"); return false; } // either the header is expected to ne non-NULL and hold 2 items, or // the header is expected to be NULL and hold 0 items - // anything else means that the expectation from the header is not fulfilled, or - // the method is not called with correct parameters + // anything else means that the expectation from the header is not + // fulfilled, or the method is not called with correct parameters if ((cose_uph && map_items != 2) || (!cose_uph && map_items != 0)) { LOG(LOG_ERROR, - "COSE Unprotected header: Unexpected map parameters.\n"); + "COSE Unprotected header: Unexpected map parameters.\n"); return false; } if (!fdor_start_map(fdor)) { LOG(LOG_ERROR, - "COSE Unprotected header: Failed to read start map\n"); + "COSE Unprotected header: Failed to read start map\n"); return false; } - // if unprotected header is not an empty map, it will contain 2 items (key-value pairs) + // if unprotected header is not an empty map, it will contain 2 items + // (key-value pairs) if (cose_uph && map_items == 2) { // iterate through the map and look for 2 keys specifically // if any other key is found, throw an error while (fdor_map_has_more(fdor)) { if (!fdor_is_value_signed_int(fdor)) { LOG(LOG_ERROR, - "COSE Unprotected header: Found a non-integer unknown/unsupported key.\n"); + "COSE Unprotected header: Found a " + "non-integer unknown/unsupported key.\n"); return false; } result = 0; if (!fdor_signed_int(fdor, &result) || result == 0) { - LOG(LOG_ERROR, - "COSE Unprotected header: Failed to read key\n"); + LOG(LOG_ERROR, "COSE Unprotected header: " + "Failed to read key\n"); return false; } if (result == FDO_COSE_SIGN1_CUPHOWNERPUBKEY_KEY) { - cose_uph->cuphowner_public_key = fdo_public_key_read(fdor); + cose_uph->cuphowner_public_key = + fdo_public_key_read(fdor); if (!cose_uph->cuphowner_public_key) { - LOG(LOG_ERROR, "COSE: Failed to read CUPHOWNERPUBKEY value\n"); + LOG(LOG_ERROR, + "COSE: Failed to read " + "CUPHOWNERPUBKEY value\n"); return false; } } else if (result == FDO_COSE_SIGN1_CUPHNONCE_KEY) { - if (!fdor_byte_string(fdor, cose_uph->cuphnonce, sizeof(cose_uph->cuphnonce))) { + if (!fdor_byte_string( + fdor, cose_uph->cuphnonce, + sizeof(cose_uph->cuphnonce))) { LOG(LOG_ERROR, - "COSE Unprotected header: Failed to read CUPHNONCE value\n"); + "COSE Unprotected header: Failed " + "to read CUPHNONCE value\n"); return false; } } else { - LOG(LOG_ERROR, - "COSE Unprotected header: Found unknown/unsupported key\n"); + LOG(LOG_ERROR, "COSE Unprotected header: Found " + "unknown/unsupported key\n"); return false; } } @@ -3593,7 +3816,7 @@ bool fdo_cose_read_unprotected_header(fdor_t *fdor, fdo_cose_unprotected_header_ if (!fdor_end_map(fdor)) { LOG(LOG_ERROR, - "COSE Unprotected header: Failed to read end map\n"); + "COSE Unprotected header: Failed to read end map\n"); return false; } return true; @@ -3612,10 +3835,12 @@ bool fdo_cose_read_unprotected_header(fdor_t *fdor, fdo_cose_unprotected_header_ * ] * @param fdor - fdor_t object containing the buffer to read * @param cose - fdo_cose_t object that will hold the read COSE_Sign1 parameters - * @param empty_uph - true if the unprotected header is expected to be empty, false otherwise + * @param empty_uph - true if the unprotected header is expected to be empty, + * false otherwise * @return true, if read was a success. False otherwise. */ -bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph) { +bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph) +{ if (!fdor || !cose) { LOG(LOG_ERROR, "COSE: Invalid params\n"); @@ -3653,9 +3878,11 @@ bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph) { // this is a special case used only for message received from Type 61, // since it contains CUPHNONCE and CUPHOWNERPUBKEY if (!empty_uph) { - cose->cose_uph = fdo_alloc(sizeof(fdo_cose_unprotected_header_t)); + cose->cose_uph = + fdo_alloc(sizeof(fdo_cose_unprotected_header_t)); if (!cose->cose_uph) { - LOG(LOG_ERROR, "COSE: Failed to alloc unprotected Header\n"); + LOG(LOG_ERROR, + "COSE: Failed to alloc unprotected Header\n"); goto end; } } @@ -3665,8 +3892,7 @@ bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph) { } size_t var_length = 0; - if (!fdor_string_length(fdor, &var_length) || - var_length == 0) { + if (!fdor_string_length(fdor, &var_length) || var_length == 0) { LOG(LOG_ERROR, "COSE: Failed to read payload length\n"); goto end; } @@ -3675,14 +3901,14 @@ bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph) { LOG(LOG_ERROR, "COSE: Failed to alloc EATPayload\n"); goto end; } - if (!fdor_byte_string(fdor, cose->cose_payload->bytes, cose->cose_payload->byte_sz)) { + if (!fdor_byte_string(fdor, cose->cose_payload->bytes, + cose->cose_payload->byte_sz)) { LOG(LOG_ERROR, "COSE: Failed to read payload\n"); goto end; } var_length = 0; - if (!fdor_string_length(fdor, &var_length) || - var_length == 0) { + if (!fdor_string_length(fdor, &var_length) || var_length == 0) { LOG(LOG_ERROR, "COSE: Failed to read signature length\n"); goto end; } @@ -3691,7 +3917,8 @@ bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph) { LOG(LOG_ERROR, "COSE: Failed to alloc Signature\n"); goto end; } - if (!fdor_byte_string(fdor, cose->cose_signature->bytes, cose->cose_signature->byte_sz)) { + if (!fdor_byte_string(fdor, cose->cose_signature->bytes, + cose->cose_signature->byte_sz)) { LOG(LOG_ERROR, "COSE: Failed to read signature\n"); goto end; } @@ -3707,18 +3934,21 @@ bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph) { } /** - * Create COSESignature.COSEProtectedHeaders (CBOR map) as CBOR bytes using the given contents. - * This is wrapped in bstr. + * Create COSESignature.COSEProtectedHeaders (CBOR map) as CBOR bytes using the + * given contents. This is wrapped in bstr. * { * keyAlg: * } * Return true, if write was a success. False otherwise. */ -bool fdo_cose_write_protected_header(fdow_t *fdow, fdo_cose_protected_header_t *cose_ph) { +bool fdo_cose_write_protected_header(fdow_t *fdow, + fdo_cose_protected_header_t *cose_ph) +{ bool ret = false; fdo_byte_array_t *enc_ph = NULL; - // create temporary FDOW, use it to create Protected header map and then clear it. + // create temporary FDOW, use it to create Protected header map and then + // clear it. fdow_t temp_fdow = {0}; if (!fdow || !cose_ph) { @@ -3726,54 +3956,59 @@ bool fdo_cose_write_protected_header(fdow_t *fdow, fdo_cose_protected_header_t * return false; } - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_128_BYTES) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, "COSE Protected header: FDOW Initialization/Allocation failed!\n"); + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_128_BYTES) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "COSE Protected header: FDOW " + "Initialization/Allocation failed!\n"); goto end; } if (!fdow_start_map(&temp_fdow, 1)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to write start map\n"); + "COSE Protected header: Failed to write start map\n"); goto end; } if (!fdow_signed_int(&temp_fdow, FDO_COSE_ALG_KEY)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to write CoseAlg Key\n"); + "COSE Protected header: Failed to write CoseAlg Key\n"); goto end; } if (!fdow_signed_int(&temp_fdow, cose_ph->ph_sig_alg)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to write CoseAlg Value\n"); + "COSE Protected header: Failed to write CoseAlg Value\n"); goto end; } if (!fdow_end_map(&temp_fdow)) { LOG(LOG_ERROR, - "COSE Protected header: Failed to write end map\n"); + "COSE Protected header: Failed to write end map\n"); goto end; } size_t enc_ph_length = 0; - if (!fdow_encoded_length(&temp_fdow, &enc_ph_length) || enc_ph_length == 0) { - LOG(LOG_ERROR, "COSE Protected header:: Failed to find encoded length\n"); + if (!fdow_encoded_length(&temp_fdow, &enc_ph_length) || + enc_ph_length == 0) { + LOG(LOG_ERROR, + "COSE Protected header:: Failed to find encoded length\n"); goto end; } temp_fdow.b.block_size = enc_ph_length; // Set the encoded payload into buffer - enc_ph = - fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, temp_fdow.b.block_size); + enc_ph = fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, + temp_fdow.b.block_size); if (!enc_ph) { - LOG(LOG_ERROR, "COSE Protected header: Failed to alloc for encoded Protected header\n"); + LOG(LOG_ERROR, "COSE Protected header: Failed to alloc for " + "encoded Protected header\n"); goto end; } // finally, wrap the protected header into a bstr if (!fdow_byte_string(fdow, enc_ph->bytes, enc_ph->byte_sz)) { - LOG(LOG_ERROR, - "COSE Protected header: Failed to write Protected header as bstr\n"); + LOG(LOG_ERROR, "COSE Protected header: Failed to write " + "Protected header as bstr\n"); goto end; } ret = true; @@ -3793,41 +4028,45 @@ bool fdo_cose_write_protected_header(fdow_t *fdow, fdo_cose_protected_header_t * * * Return true, if write was a success. False otherwise. */ -bool fdo_cose_write_unprotected_header(fdow_t *fdow) { +bool fdo_cose_write_unprotected_header(fdow_t *fdow) +{ if (!fdow) { - LOG(LOG_ERROR, - "COSE Unprotected header: Invalid params\n"); + LOG(LOG_ERROR, "COSE Unprotected header: Invalid params\n"); return false; } // empty map for now if (!fdow_start_map(fdow, 0)) { LOG(LOG_ERROR, - "COSE Unprotected header: Failed to write start map\n"); + "COSE Unprotected header: Failed to write start map\n"); return false; } if (!fdow_end_map(fdow)) { LOG(LOG_ERROR, - "COSE Unprotected header: Failed to write end map\n"); + "COSE Unprotected header: Failed to write end map\n"); return false; } return true; } /** - * Write a COSESignature (COSE_Sign1) object by CBOR encoding the contents of the given cose object. + * Write a COSESignature (COSE_Sign1) object by CBOR encoding the contents of + * the given cose object. * [ * protected header, * unprotected header, * payload, // bstr * signature // bstr * ] - * @param fdow - fdow_t object containing the buffer where CBOR data will be written - * @param cose - fdo_cose_t object that holds the COSE_Sign1 parameters to encode + * @param fdow - fdow_t object containing the buffer where CBOR data will be + * written + * @param cose - fdo_cose_t object that holds the COSE_Sign1 parameters to + * encode * @return true, if write was a success. False otherwise. */ -bool fdo_cose_write(fdow_t *fdow, fdo_cose_t *cose) { +bool fdo_cose_write(fdow_t *fdow, fdo_cose_t *cose) +{ if (!fdow || !cose) { LOG(LOG_ERROR, "COSE: Invalid params\n"); return false; @@ -3853,12 +4092,14 @@ bool fdo_cose_write(fdow_t *fdow, fdo_cose_t *cose) { return false; } - if (!fdow_byte_string(fdow, cose->cose_payload->bytes, cose->cose_payload->byte_sz)) { + if (!fdow_byte_string(fdow, cose->cose_payload->bytes, + cose->cose_payload->byte_sz)) { LOG(LOG_ERROR, "COSE: Failed to write payload\n"); return false; } - if (!fdow_byte_string(fdow, cose->cose_signature->bytes, cose->cose_signature->byte_sz)) { + if (!fdow_byte_string(fdow, cose->cose_signature->bytes, + cose->cose_signature->byte_sz)) { LOG(LOG_ERROR, "COSE: Failed to write signature\n"); return false; } @@ -3884,14 +4125,16 @@ bool fdo_cose_write(fdow_t *fdow, fdo_cose_t *cose) { * @param cose_payload - COSE Payload * @param external_aad - External AAD. If NULL, empty bstr will be written, else * the AAD bytes will be written - * @param sig_structure - Out buffer to store the constructred CBOR encoded Sig_structure. - * Memory allocation will be done inside this method, if the operation is successful. - * It will be NULL otherwise. + * @param sig_structure - Out buffer to store the constructred CBOR encoded + * Sig_structure. Memory allocation will be done inside this method, if the + * operation is successful. It will be NULL otherwise. * @return true, if read was a success. False otherwise. */ bool fdo_cose_write_sigstructure(fdo_cose_protected_header_t *cose_ph, - fdo_byte_array_t *cose_payload, fdo_byte_array_t *external_aad, - fdo_byte_array_t **sig_structure) { + fdo_byte_array_t *cose_payload, + fdo_byte_array_t *external_aad, + fdo_byte_array_t **sig_structure) +{ bool ret = false; char context[] = "Signature1"; @@ -3905,21 +4148,26 @@ bool fdo_cose_write_sigstructure(fdo_cose_protected_header_t *cose_ph, } // size of the Sigstruct CBOR encoded buffer - // provide buffer of 128 bytes for protected header + context + additional CBOR encoding + // provide buffer of 128 bytes for protected header + context + + // additional CBOR encoding if (external_aad) { - sig_struct_sz = cose_payload->byte_sz + external_aad->byte_sz + BUFF_SIZE_128_BYTES; + sig_struct_sz = cose_payload->byte_sz + external_aad->byte_sz + + BUFF_SIZE_128_BYTES; } else { sig_struct_sz = cose_payload->byte_sz + BUFF_SIZE_128_BYTES; } - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, sig_struct_sz) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, "COSE Sig_structure: FDOW Initialization/Allocation failed!\n"); + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, sig_struct_sz) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "COSE Sig_structure: FDOW " + "Initialization/Allocation failed!\n"); goto end; } if (!fdow_start_array(&temp_fdow, 4)) { - LOG(LOG_ERROR, "COSE Sig_structure: Failed to write start array\n"); + LOG(LOG_ERROR, + "COSE Sig_structure: Failed to write start array\n"); return false; } @@ -3929,51 +4177,60 @@ bool fdo_cose_write_sigstructure(fdo_cose_protected_header_t *cose_ph, } if (!fdo_cose_write_protected_header(&temp_fdow, cose_ph)) { - LOG(LOG_ERROR, "COSE Sig_structure: Failed to write protected header\n"); + LOG(LOG_ERROR, + "COSE Sig_structure: Failed to write protected header\n"); return false; } if (external_aad) { - if (!fdow_byte_string(&temp_fdow, external_aad->bytes, external_aad->byte_sz)) { - LOG(LOG_ERROR, "COSE Sig_structure: Failed to write external_aad\n"); + if (!fdow_byte_string(&temp_fdow, external_aad->bytes, + external_aad->byte_sz)) { + LOG(LOG_ERROR, "COSE Sig_structure: Failed to write " + "external_aad\n"); goto end; } } else { empty_byte_array = fdo_byte_array_alloc(0); if (!empty_byte_array) { - LOG(LOG_ERROR, "COSE Sig_structure: Byte Array Alloc failed\n"); + LOG(LOG_ERROR, + "COSE Sig_structure: Byte Array Alloc failed\n"); return false; } - if (!fdow_byte_string(&temp_fdow, empty_byte_array->bytes, empty_byte_array->byte_sz)) { - LOG(LOG_ERROR, "COSE Sig_structure: Failed to write external_aad\n"); + if (!fdow_byte_string(&temp_fdow, empty_byte_array->bytes, + empty_byte_array->byte_sz)) { + LOG(LOG_ERROR, "COSE Sig_structure: Failed to write " + "external_aad\n"); goto end; } } - if (!fdow_byte_string(&temp_fdow, cose_payload->bytes, cose_payload->byte_sz)) { + if (!fdow_byte_string(&temp_fdow, cose_payload->bytes, + cose_payload->byte_sz)) { LOG(LOG_ERROR, "COSE Sig_structure: Failed to write payload\n"); goto end; } if (!fdow_end_array(&temp_fdow)) { - LOG(LOG_ERROR, "COSE Sig_structure: Failed to write end array\n"); + LOG(LOG_ERROR, + "COSE Sig_structure: Failed to write end array\n"); goto end; } enc_length = 0; if (!fdow_encoded_length(&temp_fdow, &enc_length) || enc_length == 0) { - LOG(LOG_ERROR, "COSE Sig_structure: Failed to find encoded length of " - "Sig_structure array as bstr\n"); + LOG(LOG_ERROR, + "COSE Sig_structure: Failed to find encoded length of " + "Sig_structure array as bstr\n"); goto end; } // Alocate and copy the encoded Sig_sturcture bstr *sig_structure = - fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, enc_length); + fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, enc_length); if (!(*sig_structure)) { - LOG(LOG_ERROR, - "COSE Sig_structure: Failed to alloc output Sig_structure\n"); + LOG(LOG_ERROR, "COSE Sig_structure: Failed to alloc output " + "Sig_structure\n"); goto end; } @@ -3989,9 +4246,11 @@ bool fdo_cose_write_sigstructure(fdo_cose_protected_header_t *cose_ph, } /** - * Free the given COSE_Encrypt0 object for which memory has been allocated previously. + * Free the given COSE_Encrypt0 object for which memory has been allocated + * previously. */ -void fdo_cose_encrypt0_free(fdo_cose_encrypt0_t *cose_encrypt0) { +void fdo_cose_encrypt0_free(fdo_cose_encrypt0_t *cose_encrypt0) +{ if (!cose_encrypt0) { return; } @@ -4017,21 +4276,27 @@ void fdo_cose_encrypt0_free(fdo_cose_encrypt0_t *cose_encrypt0) { * * return allocated fdo_cose_encrypt0_t object. */ -fdo_cose_encrypt0_t* fdo_cose_encrypt0_alloc(void) { - fdo_cose_encrypt0_t *cose_encrypt0 = fdo_alloc(sizeof(fdo_cose_encrypt0_t)); +fdo_cose_encrypt0_t *fdo_cose_encrypt0_alloc(void) +{ + fdo_cose_encrypt0_t *cose_encrypt0 = + fdo_alloc(sizeof(fdo_cose_encrypt0_t)); if (!cose_encrypt0) { LOG(LOG_ERROR, "COSE_Encrypt0: Failed to alloc\n"); goto err; } - cose_encrypt0->protected_header = fdo_alloc(sizeof(fdo_cose_encrypt0_protected_header_t)); + cose_encrypt0->protected_header = + fdo_alloc(sizeof(fdo_cose_encrypt0_protected_header_t)); if (!cose_encrypt0->protected_header) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to alloc Protected Header\n"); + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to alloc Protected Header\n"); goto err; } - cose_encrypt0->unprotected_header = fdo_alloc(sizeof(fdo_cose_encrypt0_unprotected_header_t)); + cose_encrypt0->unprotected_header = + fdo_alloc(sizeof(fdo_cose_encrypt0_unprotected_header_t)); if (!cose_encrypt0->unprotected_header) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to alloc Unprotected header\n"); + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to alloc Unprotected header\n"); goto err; } @@ -4054,78 +4319,80 @@ fdo_cose_encrypt0_t* fdo_cose_encrypt0_alloc(void) { * } * Return true, if read was a success. False otherwise. */ -bool fdo_cose_encrypt0_read_protected_header(fdor_t *fdor, - fdo_cose_encrypt0_protected_header_t *protected_header) { +bool fdo_cose_encrypt0_read_protected_header( + fdor_t *fdor, fdo_cose_encrypt0_protected_header_t *protected_header) +{ bool ret = false; fdor_t temp_fdor; if (memset_s(&temp_fdor, sizeof(fdor_t), 0) != 0) { - LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to intialize temporary FDOR\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "intialize temporary FDOR\n"); return false; } size_t var_length = 0; - if (!fdor_string_length(fdor, &var_length) || - var_length == 0) { - LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to read length\n"); + if (!fdor_string_length(fdor, &var_length) || var_length == 0) { + LOG(LOG_ERROR, + "COSE_Encrypt0 Protected header: Failed to read length\n"); return false; } fdo_byte_array_t *ph_as_bstr = fdo_byte_array_alloc(var_length); if (!ph_as_bstr) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to alloc for bstr\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "alloc for bstr\n"); return false; } if (!fdor_byte_string(fdor, ph_as_bstr->bytes, ph_as_bstr->byte_sz)) { LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to read as bstr\n"); + "COSE_Encrypt0 Protected header: Failed to read as bstr\n"); goto end; } // create a temporary FDOR to read (unwrap) the header contents as map if (!fdor_init(&temp_fdor) || - !fdo_block_alloc_with_size(&temp_fdor.b, ph_as_bstr->byte_sz)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to setup temporary FDOR\n"); + !fdo_block_alloc_with_size(&temp_fdor.b, ph_as_bstr->byte_sz)) { + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "setup temporary FDOR\n"); goto end; } if (0 != memcpy_s(temp_fdor.b.block, temp_fdor.b.block_size, - ph_as_bstr->bytes, ph_as_bstr->byte_sz)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to copy temporary unwrapped Header content\n"); + ph_as_bstr->bytes, ph_as_bstr->byte_sz)) { + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to copy " + "temporary unwrapped Header content\n"); goto end; } if (!fdor_parser_init(&temp_fdor)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to init temporary FDOR parser\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to init " + "temporary FDOR parser\n"); goto end; } if (!fdor_start_map(&temp_fdor)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to read start map\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to read " + "start map\n"); goto end; } int cose_aesplaintype_key = 0; if (!fdor_signed_int(&temp_fdor, &cose_aesplaintype_key) || - cose_aesplaintype_key != FDO_COSE_ENCRYPT0_AESPLAINTYPE_KEY) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to read AESPlainType Key\n"); + cose_aesplaintype_key != FDO_COSE_ENCRYPT0_AESPLAINTYPE_KEY) { + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to read " + "AESPlainType Key\n"); goto end; } if (!fdor_signed_int(&temp_fdor, &protected_header->aes_plain_type)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to read AESPlainType Value\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to read " + "AESPlainType Value\n"); goto end; } if (!fdor_end_map(&temp_fdor)) { LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to read end map\n"); + "COSE_Encrypt0 Protected header: Failed to read end map\n"); goto end; } ret = true; @@ -4146,39 +4413,40 @@ bool fdo_cose_encrypt0_read_protected_header(fdor_t *fdor, * } * Return true, if read was a success. False otherwise. */ -bool fdo_cose_encrypt0_read_unprotected_header(fdor_t *fdor, - fdo_cose_encrypt0_unprotected_header_t *unprotected_header) { +bool fdo_cose_encrypt0_read_unprotected_header( + fdor_t *fdor, fdo_cose_encrypt0_unprotected_header_t *unprotected_header) +{ if (!fdor_start_map(fdor)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to read start map\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "read start map\n"); return false; } int cose_aesiv_key = 0; if (!fdor_signed_int(fdor, &cose_aesiv_key) || - cose_aesiv_key != FDO_COSE_ENCRYPT0_AESIV_KEY) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to read AESIV Key\n"); + cose_aesiv_key != FDO_COSE_ENCRYPT0_AESIV_KEY) { + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "read AESIV Key\n"); return false; } size_t cose_aesiv_value_length = 0; if (!fdor_string_length(fdor, &cose_aesiv_value_length) || - cose_aesiv_value_length != sizeof(unprotected_header->aes_iv)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to read AESIV Value\n"); + cose_aesiv_value_length != sizeof(unprotected_header->aes_iv)) { + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "read AESIV Value\n"); return false; } if (!fdor_byte_string(fdor, unprotected_header->aes_iv, - sizeof(unprotected_header->aes_iv))) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to read AESIV Value\n"); + sizeof(unprotected_header->aes_iv))) { + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "read AESIV Value\n"); return false; } if (!fdor_end_map(fdor)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to read end map\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "read end map\n"); return false; } return true; @@ -4195,11 +4463,12 @@ bool fdo_cose_encrypt0_read_unprotected_header(fdor_t *fdor, * payload, // bstr * ] * @param fdor - fdor_t object containing the buffer to read - * @param cose_encrypt0 - fdo_cose_encrypt0_t object that will hold the read COSE_Encrypt0 - * parameters + * @param cose_encrypt0 - fdo_cose_encrypt0_t object that will hold the read + * COSE_Encrypt0 parameters * @return true, if read was a success. False otherwise. */ -bool fdo_cose_encrypt0_read(fdor_t *fdor, fdo_cose_encrypt0_t *cose_encrypt0) { +bool fdo_cose_encrypt0_read(fdor_t *fdor, fdo_cose_encrypt0_t *cose_encrypt0) +{ size_t num_cose_items = 3; uint64_t tag = 0; @@ -4223,30 +4492,37 @@ bool fdo_cose_encrypt0_read(fdor_t *fdor, fdo_cose_encrypt0_t *cose_encrypt0) { return false; } - cose_encrypt0->protected_header = fdo_alloc(sizeof(fdo_cose_encrypt0_protected_header_t)); + cose_encrypt0->protected_header = + fdo_alloc(sizeof(fdo_cose_encrypt0_protected_header_t)); if (!cose_encrypt0->protected_header) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to alloc Protected Header\n"); + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to alloc Protected Header\n"); goto end; } - if (!fdo_cose_encrypt0_read_protected_header(fdor, cose_encrypt0->protected_header)) { + if (!fdo_cose_encrypt0_read_protected_header( + fdor, cose_encrypt0->protected_header)) { LOG(LOG_ERROR, "COSE: Failed to read protected header\n"); goto end; } - cose_encrypt0->unprotected_header = fdo_alloc(sizeof(fdo_cose_encrypt0_unprotected_header_t)); + cose_encrypt0->unprotected_header = + fdo_alloc(sizeof(fdo_cose_encrypt0_unprotected_header_t)); if (!cose_encrypt0->unprotected_header) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to alloc Unprotected Header\n"); + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to alloc Unprotected Header\n"); goto end; } - if (!fdo_cose_encrypt0_read_unprotected_header(fdor, cose_encrypt0->unprotected_header)) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to read Unprotected header\n"); + if (!fdo_cose_encrypt0_read_unprotected_header( + fdor, cose_encrypt0->unprotected_header)) { + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to read Unprotected header\n"); goto end; } size_t payload_length = 0; - if (!fdor_string_length(fdor, &payload_length) || - payload_length == 0) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to read EATpayload length\n"); + if (!fdor_string_length(fdor, &payload_length) || payload_length == 0) { + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to read EATpayload length\n"); goto end; } cose_encrypt0->payload = fdo_byte_array_alloc(payload_length); @@ -4254,7 +4530,8 @@ bool fdo_cose_encrypt0_read(fdor_t *fdor, fdo_cose_encrypt0_t *cose_encrypt0) { LOG(LOG_ERROR, "COSE_Encrypt0: Failed to alloc EATPayload\n"); goto end; } - if (!fdor_byte_string(fdor, cose_encrypt0->payload->bytes, cose_encrypt0->payload->byte_sz)) { + if (!fdor_byte_string(fdor, cose_encrypt0->payload->bytes, + cose_encrypt0->payload->byte_sz)) { LOG(LOG_ERROR, "COSE_Encrypt0: Failed to read EATpayload\n"); goto end; } @@ -4277,12 +4554,14 @@ bool fdo_cose_encrypt0_read(fdor_t *fdor, fdo_cose_encrypt0_t *cose_encrypt0) { * } * Return true, if write was a success. False otherwise. */ -bool fdo_cose_encrypt0_write_protected_header(fdow_t *fdow, - fdo_cose_encrypt0_protected_header_t *protected_header) { +bool fdo_cose_encrypt0_write_protected_header( + fdow_t *fdow, fdo_cose_encrypt0_protected_header_t *protected_header) +{ bool ret = false; fdo_byte_array_t *enc_ph = NULL; - // create temporary FDOW, use it to create Protected header map and then clear it. + // create temporary FDOW, use it to create Protected header map and then + // clear it. fdow_t temp_fdow = {0}; if (!fdow || !protected_header) { @@ -4290,55 +4569,59 @@ bool fdo_cose_encrypt0_write_protected_header(fdow_t *fdow, return false; } - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_128_BYTES) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, "COSE Protected header: FDOW Initialization/Allocation failed!\n"); + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_128_BYTES) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "COSE Protected header: FDOW " + "Initialization/Allocation failed!\n"); goto end; } if (!fdow_start_map(&temp_fdow, 1)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to write start map\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "write start map\n"); goto end; } if (!fdow_signed_int(&temp_fdow, FDO_COSE_ENCRYPT0_AESPLAINTYPE_KEY)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to write AESPlainType Key\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "write AESPlainType Key\n"); goto end; } if (!fdow_signed_int(&temp_fdow, protected_header->aes_plain_type)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to write AESPlainType Value\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "write AESPlainType Value\n"); goto end; } if (!fdow_end_map(&temp_fdow)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to write end map\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "write end map\n"); goto end; } size_t enc_ph_length = 0; - if (!fdow_encoded_length(&temp_fdow, &enc_ph_length) || enc_ph_length == 0) { - LOG(LOG_ERROR, "COSE_Encrypt0 Protected header:: Failed to find encoded length\n"); + if (!fdow_encoded_length(&temp_fdow, &enc_ph_length) || + enc_ph_length == 0) { + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header:: Failed to " + "find encoded length\n"); goto end; } temp_fdow.b.block_size = enc_ph_length; // Set the encoded payload into buffer - enc_ph = - fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, temp_fdow.b.block_size); + enc_ph = fdo_byte_array_alloc_with_byte_array(temp_fdow.b.block, + temp_fdow.b.block_size); if (!enc_ph) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to alloc for encoded Protected header\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "alloc for encoded Protected header\n"); goto end; } // finally, wrap the protected header into a bstr if (!fdow_byte_string(fdow, enc_ph->bytes, enc_ph->byte_sz)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Protected header: Failed to write Protected header as bstr\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Protected header: Failed to " + "write Protected header as bstr\n"); goto end; } ret = true; @@ -4360,48 +4643,52 @@ bool fdo_cose_encrypt0_write_protected_header(fdow_t *fdow, * } * Return true, if write was a success. False otherwise. */ -bool fdo_cose_encrypt0_write_unprotected_header(fdow_t *fdow, - fdo_cose_encrypt0_unprotected_header_t *unprotected_header) { +bool fdo_cose_encrypt0_write_unprotected_header( + fdow_t *fdow, fdo_cose_encrypt0_unprotected_header_t *unprotected_header) +{ if (!fdow_start_map(fdow, 1)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to write start map\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "write start map\n"); return false; } if (!fdow_signed_int(fdow, FDO_COSE_ENCRYPT0_AESIV_KEY)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to write AESIV Key\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "write AESIV Key\n"); return false; } if (!fdow_byte_string(fdow, unprotected_header->aes_iv, - sizeof(unprotected_header->aes_iv))) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to write AESIV Value\n"); + sizeof(unprotected_header->aes_iv))) { + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "write AESIV Value\n"); return false; } if (!fdow_end_map(fdow)) { - LOG(LOG_ERROR, - "COSE_Encrypt0 Unprotected header: Failed to write end map\n"); + LOG(LOG_ERROR, "COSE_Encrypt0 Unprotected header: Failed to " + "write end map\n"); return false; } return true; } /** - * Write the given fdo_cose_encrypt0_t parameter into CBOR encoded COSE_Encrypt0. + * Write the given fdo_cose_encrypt0_t parameter into CBOR encoded + * COSE_Encrypt0. * [ * protected header, * unprotected header, * payload, // bstr * ] - * @param fdow - fdow_t object holding the buffer where CBOR data will be written to - * @param cose_encrypt0 - fdo_cose_encrypt0_t object that holds the COSE_Encrypt0 parameters to - * encode + * @param fdow - fdow_t object holding the buffer where CBOR data will be + * written to + * @param cose_encrypt0 - fdo_cose_encrypt0_t object that holds the + * COSE_Encrypt0 parameters to encode * @return true, if write was a success. False otherwise. */ -bool fdo_cose_encrypt0_write(fdow_t *fdow, fdo_cose_encrypt0_t *cose_encrypt0) { +bool fdo_cose_encrypt0_write(fdow_t *fdow, fdo_cose_encrypt0_t *cose_encrypt0) +{ if (!fdow_tag(fdow, FDO_COSE_TAG_ENCRYPT0)) { LOG(LOG_ERROR, "COSE_Encrypt0: Failed to write Tag\n"); @@ -4413,17 +4700,22 @@ bool fdo_cose_encrypt0_write(fdow_t *fdow, fdo_cose_encrypt0_t *cose_encrypt0) { return false; } - if (!fdo_cose_encrypt0_write_protected_header(fdow, cose_encrypt0->protected_header)) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to write protected header\n"); + if (!fdo_cose_encrypt0_write_protected_header( + fdow, cose_encrypt0->protected_header)) { + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to write protected header\n"); return false; } - if (!fdo_cose_encrypt0_write_unprotected_header(fdow, cose_encrypt0->unprotected_header)) { - LOG(LOG_ERROR, "COSE_Encrypt0: Failed to write unprotected header\n"); + if (!fdo_cose_encrypt0_write_unprotected_header( + fdow, cose_encrypt0->unprotected_header)) { + LOG(LOG_ERROR, + "COSE_Encrypt0: Failed to write unprotected header\n"); return false; } - if (!fdow_byte_string(fdow, cose_encrypt0->payload->bytes, cose_encrypt0->payload->byte_sz)) { + if (!fdow_byte_string(fdow, cose_encrypt0->payload->bytes, + cose_encrypt0->payload->byte_sz)) { LOG(LOG_ERROR, "COSE_Encrypt0: Failed to write payload\n"); return false; } @@ -4436,9 +4728,11 @@ bool fdo_cose_encrypt0_write(fdow_t *fdow, fdo_cose_encrypt0_t *cose_encrypt0) { } /** - * Free the given RVTO2AddrEntry object for which memory has been allocated previously. + * Free the given RVTO2AddrEntry object for which memory has been allocated + * previously. */ -void fdo_rvto2addr_entry_free(fdo_rvto2addr_entry_t *rvto2addr_entry) { +void fdo_rvto2addr_entry_free(fdo_rvto2addr_entry_t *rvto2addr_entry) +{ if (rvto2addr_entry->rvip) { fdo_byte_array_free(rvto2addr_entry->rvip); } @@ -4449,14 +4743,18 @@ void fdo_rvto2addr_entry_free(fdo_rvto2addr_entry_t *rvto2addr_entry) { } /** - * Free the given RVTO2Addr object for which memory has been allocated previously. + * Free the given RVTO2Addr object for which memory has been allocated + * previously. */ -void fdo_rvto2addr_free(fdo_rvto2addr_t *rvto2addr) { +void fdo_rvto2addr_free(fdo_rvto2addr_t *rvto2addr) +{ if (rvto2addr) { while (rvto2addr->rv_to2addr_entry) { - fdo_rvto2addr_entry_t *rv_to2addr_entry = rvto2addr->rv_to2addr_entry; + fdo_rvto2addr_entry_t *rv_to2addr_entry = + rvto2addr->rv_to2addr_entry; rvto2addr->rv_to2addr_entry = - (fdo_rvto2addr_entry_t *) rvto2addr->rv_to2addr_entry->next; + (fdo_rvto2addr_entry_t *) + rvto2addr->rv_to2addr_entry->next; fdo_rvto2addr_entry_free(rv_to2addr_entry); } fdo_free(rvto2addr); @@ -4476,18 +4774,21 @@ void fdo_rvto2addr_free(fdo_rvto2addr_t *rvto2addr) { * RVProtocol * ] * @param fdor - fdor_t object containing the buffer to read - * @param rvto2addr_entry - fdo_rvto2addr_entry_t object that will hold the read RVTO2AddrEntry - * parameters + * @param rvto2addr_entry - fdo_rvto2addr_entry_t object that will hold the read + * RVTO2AddrEntry parameters * @return true, if read was a success. False otherwise. */ -bool fdo_rvto2addr_entry_read(fdor_t *fdor, fdo_rvto2addr_entry_t *rvto2addr_entry) { +bool fdo_rvto2addr_entry_read(fdor_t *fdor, + fdo_rvto2addr_entry_t *rvto2addr_entry) +{ size_t num_rvto2addr_entry_items = 0; size_t rvip_length = 0; size_t rvdns_length = 0; if (!fdor_array_length(fdor, &num_rvto2addr_entry_items) || - num_rvto2addr_entry_items != 4) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read/Invalid array length\n"); + num_rvto2addr_entry_items != 4) { + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to read/Invalid array length\n"); return false; } @@ -4496,72 +4797,89 @@ bool fdo_rvto2addr_entry_read(fdor_t *fdor, fdo_rvto2addr_entry_t *rvto2addr_ent return false; } - if (fdor_is_value_null(fdor) || !fdor_string_length(fdor, &rvip_length) || rvip_length == 0) { + if (fdor_is_value_null(fdor) || + !fdor_string_length(fdor, &rvip_length) || rvip_length == 0) { if (!fdor_next(fdor)) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to skip NULL RVIP\n"); + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to skip NULL RVIP\n"); return false; } } else { rvip_length = 0; - if (!fdor_string_length(fdor, &rvip_length) || rvip_length == 0) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read RVIP length\n"); + if (!fdor_string_length(fdor, &rvip_length) || + rvip_length == 0) { + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to read RVIP length\n"); return false; } rvto2addr_entry->rvip = fdo_byte_array_alloc(rvip_length); if (!rvto2addr_entry->rvip) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to alloc RVIP\n"); + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to alloc RVIP\n"); return false; } - if (!fdor_byte_string(fdor, rvto2addr_entry->rvip->bytes, rvto2addr_entry->rvip->byte_sz)) { + if (!fdor_byte_string(fdor, rvto2addr_entry->rvip->bytes, + rvto2addr_entry->rvip->byte_sz)) { LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read RVIP\n"); return false; } } - if (fdor_is_value_null(fdor) || !fdor_string_length(fdor, &rvdns_length) || rvdns_length == 0) { + if (fdor_is_value_null(fdor) || + !fdor_string_length(fdor, &rvdns_length) || rvdns_length == 0) { if (!fdor_next(fdor)) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to skip NULL RVDNS\n"); + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to skip NULL RVDNS\n"); return false; } } else { rvdns_length = 0; - if (!fdor_string_length(fdor, &rvdns_length) || rvdns_length == 0) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read RVDNS length\n"); + if (!fdor_string_length(fdor, &rvdns_length) || + rvdns_length == 0) { + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to read RVDNS length\n"); return false; } rvto2addr_entry->rvdns = fdo_string_alloc_size(rvdns_length); if (!rvto2addr_entry->rvdns) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to alloc RVDNS\n"); + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to alloc RVDNS\n"); return false; } - if (!fdor_text_string(fdor, rvto2addr_entry->rvdns->bytes, rvdns_length)) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read RVDNS\n"); + if (!fdor_text_string(fdor, rvto2addr_entry->rvdns->bytes, + rvdns_length)) { + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to read RVDNS\n"); return false; } rvto2addr_entry->rvdns->bytes[rvdns_length] = '\0'; } if (!rvto2addr_entry->rvip && !rvto2addr_entry->rvdns) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Both RVIP and RVDNS can not be NULL\n"); - return false; + LOG(LOG_ERROR, + "RVTO2AddrEntry: Both RVIP and RVDNS can not be NULL\n"); + return false; } else { rvto2addr_entry->rvport = -1; if (!fdor_signed_int(fdor, &rvto2addr_entry->rvport) || - rvto2addr_entry->rvport == -1) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read RVPort\n"); + rvto2addr_entry->rvport == -1) { + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to read RVPort\n"); return false; } rvto2addr_entry->rvprotocol = -1; if (!fdor_signed_int(fdor, &rvto2addr_entry->rvprotocol) || - rvto2addr_entry->rvprotocol == -1) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read RVProtocol\n"); + rvto2addr_entry->rvprotocol == -1) { + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to read RVProtocol\n"); return false; } if (!fdor_end_array(fdor)) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read end array\n"); + LOG(LOG_ERROR, + "RVTO2AddrEntry: Failed to read end array\n"); goto end; } return true; @@ -4581,22 +4899,28 @@ bool fdo_rvto2addr_entry_read(fdor_t *fdor, fdo_rvto2addr_entry_t *rvto2addr_ent * +RVTO2AddrEntry // one or more RVTO2AddrEntry * ] * @param fdor - fdor_t object containing the buffer to read - * @param rvto2addr - fdo_rvto2addr_t object that will hold the read RVTO2Addr parameters + * @param rvto2addr - fdo_rvto2addr_t object that will hold the read RVTO2Addr + * parameters * @return true, if read was a success. False otherwise. */ -bool fdo_rvto2addr_read(fdor_t *fdor, fdo_rvto2addr_t *rvto2addr) { +bool fdo_rvto2addr_read(fdor_t *fdor, fdo_rvto2addr_t *rvto2addr) +{ size_t num_rvto2addr_items = 0; - if (!fdor_array_length(fdor, &num_rvto2addr_items) || num_rvto2addr_items == 0) { - LOG(LOG_ERROR, "RVTO2Addr: Failed to read/Invalid array length\n"); + if (!fdor_array_length(fdor, &num_rvto2addr_items) || + num_rvto2addr_items == 0) { + LOG(LOG_ERROR, + "RVTO2Addr: Failed to read/Invalid array length\n"); return false; } if (!fdor_start_array(fdor)) { - LOG(LOG_ERROR, "RVTO2Addr: Failed to read/Invalid array length\n"); + LOG(LOG_ERROR, + "RVTO2Addr: Failed to read/Invalid array length\n"); return false; } - LOG(LOG_DEBUG, "RVTO2Addr: There are %zu RVTO2AddrEntry(s)\n", num_rvto2addr_items); + LOG(LOG_DEBUG, "RVTO2Addr: There are %zu RVTO2AddrEntry(s)\n", + num_rvto2addr_items); rvto2addr->num_rvto2addr = num_rvto2addr_items; rvto2addr->rv_to2addr_entry = fdo_alloc(sizeof(fdo_rvto2addr_entry_t)); @@ -4610,13 +4934,15 @@ bool fdo_rvto2addr_read(fdor_t *fdor, fdo_rvto2addr_t *rvto2addr) { i++; if (!fdo_rvto2addr_entry_read(fdor, entry)) { - LOG(LOG_ERROR, "RVTO2Addr: Failed to read RVTO2AddrEntry\n"); + LOG(LOG_ERROR, + "RVTO2Addr: Failed to read RVTO2AddrEntry\n"); goto end; } if (i < num_rvto2addr_items) { entry->next = fdo_alloc(sizeof(fdo_rvto2addr_entry_t)); if (!entry->next) { - LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to read/Invalid array length\n"); + LOG(LOG_ERROR, "RVTO2AddrEntry: Failed to " + "read/Invalid array length\n"); goto end; } entry = entry->next; @@ -4668,7 +4994,7 @@ bool fdo_signature_verification(fdo_byte_array_t *plain_text, } LOG(LOG_ERROR, "Signature internal failure, or signature does " - "not verify.\n"); + "not verify.\n"); return false; } @@ -4702,9 +5028,11 @@ fdo_key_value_t *fdo_kv_alloc_with_str(const char *key, const char *val) int key_len = strnlen_s(key, FDO_MAX_STR_SIZE); if (!key_len || key_len == FDO_MAX_STR_SIZE) { - LOG(LOG_ERROR, "%s(): key is either " + LOG(LOG_ERROR, + "%s(): key is either " "'NULL' or 'isn't " - "NULL terminated'\n", __func__); + "NULL terminated'\n", + __func__); fdo_kv_free(kv); return NULL; } @@ -4716,7 +5044,8 @@ fdo_key_value_t *fdo_kv_alloc_with_str(const char *key, const char *val) if (val_len == FDO_MAX_STR_SIZE) { LOG(LOG_ERROR, "%s(): value is either " - "'NULL' or 'isn't NULL terminated'\n", __func__); + "'NULL' or 'isn't NULL terminated'\n", + __func__); printf("vallen:%d\t, buf:%s\n", val_len, val); fdo_kv_free(kv); return NULL; @@ -4748,9 +5077,11 @@ fdo_key_value_t *fdo_kv_alloc_key_only(const char *key) int key_len = strnlen_s(key, FDO_MAX_STR_SIZE); if (!key_len || key_len == FDO_MAX_STR_SIZE) { - LOG(LOG_ERROR, "%s(): key is either " + LOG(LOG_ERROR, + "%s(): key is either " "'NULL' or 'isn't " - "NULL terminated'\n", __func__); + "NULL terminated'\n", + __func__); fdo_kv_free(kv); return NULL; } @@ -4804,13 +5135,17 @@ void fdo_kv_free(fdo_key_value_t *kv) * ServiceInfoKey = moduleName:messageName * @param fdor - fdor_t object containing the buffer to read * @param module_list - Owner ServiceInfo module list - * @param cb_return_val - out value to hold the return value from the registered modules. - * @param serviceinfo_invalid_modnames - Structure to store list of unsupported module names - * for which an access request was made by the Owner. + * @param cb_return_val - out value to hold the return value from the registered + * modules. + * @param serviceinfo_invalid_modnames - Structure to store list of unsupported + * module names for which an access request was made by the Owner. * @return true if read was a success, false otherwise */ -bool fdo_serviceinfo_read(fdor_t *fdor, fdo_sdk_service_info_module_list_t *module_list, - int *cb_return_val, fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames) { +bool fdo_serviceinfo_read( + fdor_t *fdor, fdo_sdk_service_info_module_list_t *module_list, + int *cb_return_val, + fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames) +{ bool ret = false; char *serviceinfokey = NULL; @@ -4825,7 +5160,8 @@ bool fdo_serviceinfo_read(fdor_t *fdor, fdo_sdk_service_info_module_list_t *modu } if (!fdor_array_length(fdor, &num_serviceinfokv)) { - LOG(LOG_ERROR, "ServiceInfo read: Failed to find number of items\n"); + LOG(LOG_ERROR, + "ServiceInfo read: Failed to find number of items\n"); goto exit; } if (!fdor_start_array(fdor)) { @@ -4837,58 +5173,72 @@ bool fdo_serviceinfo_read(fdor_t *fdor, fdo_sdk_service_info_module_list_t *modu // ServiceInfoKV must contain 2 items: Key and Val size_t num_serviceinfokv_items = 0; if (!fdor_array_length(fdor, &num_serviceinfokv_items) || - num_serviceinfokv_items != 2) { - LOG(LOG_ERROR, "ServiceInfoKV read: Invalid number of items\n"); + num_serviceinfokv_items != 2) { + LOG(LOG_ERROR, + "ServiceInfoKV read: Invalid number of items\n"); goto exit; } if (!fdor_start_array(fdor)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to start array\n"); + LOG(LOG_ERROR, + "ServiceInfoKV read: Failed to start array\n"); goto exit; } size_t serviceinfokey_length = 0; size_t serviceinfoval_length = 0; if (!fdor_string_length(fdor, &serviceinfokey_length)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read ServiceInfoKey length\n"); + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read " + "ServiceInfoKey length\n"); goto exit; } if (serviceinfokey_length == 0 || - serviceinfokey_length >= FDO_MODULE_NAME_LEN + FDO_MODULE_MSG_LEN) { - LOG(LOG_ERROR, "ServiceInfoKV read: Received module name and message " - "length is invalid\n"); + serviceinfokey_length >= + FDO_MODULE_NAME_LEN + FDO_MODULE_MSG_LEN) { + LOG(LOG_ERROR, "ServiceInfoKV read: Received module " + "name and message " + "length is invalid\n"); goto exit; } - serviceinfokey = fdo_alloc(sizeof(char) * serviceinfokey_length); + serviceinfokey = + fdo_alloc(sizeof(char) * serviceinfokey_length); if (!serviceinfokey) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to alloc ServiceInfoKey\n"); + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to alloc " + "ServiceInfoKey\n"); goto exit; - } - if (!fdor_text_string(fdor, serviceinfokey, serviceinfokey_length)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read ServiceInfoKV\n"); + } + if (!fdor_text_string(fdor, serviceinfokey, + serviceinfokey_length)) { + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read " + "ServiceInfoKV\n"); goto exit; } if (0 != memset_s(&module_name, sizeof(module_name), 0)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to clear modulename\n"); + LOG(LOG_ERROR, + "ServiceInfoKV read: Failed to clear modulename\n"); goto exit; } if (0 != memset_s(&module_message, sizeof(module_message), 0)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to clear modulename\n"); + LOG(LOG_ERROR, + "ServiceInfoKV read: Failed to clear modulename\n"); goto exit; } - // find the index of separator ':' in ServiceInfoKey format of 'moduleName:messageName' - // copy moduleName:messageName and moduleName:messageName + // find the index of separator ':' in ServiceInfoKey format of + // 'moduleName:messageName' copy moduleName:messageName and + // moduleName:messageName size_t index = 0; if (serviceinfokey[index] == ':') { - LOG(LOG_ERROR, "ServiceInfoKV read: Invalid ServiceInfoKey\n"); + LOG(LOG_ERROR, + "ServiceInfoKV read: Invalid ServiceInfoKey\n"); *cb_return_val = MESSAGE_BODY_ERROR; goto exit; } while (':' != serviceinfokey[index]) { if (index >= sizeof(module_name) - 1) { - LOG(LOG_ERROR, "ServiceInfoKV read: Invalid ServiceInfoKey\n"); + LOG(LOG_ERROR, "ServiceInfoKV read: Invalid " + "ServiceInfoKey\n"); *cb_return_val = MESSAGE_BODY_ERROR; goto exit; } @@ -4898,43 +5248,52 @@ bool fdo_serviceinfo_read(fdor_t *fdor, fdo_sdk_service_info_module_list_t *modu } ++index; size_t module_msg_index = 0; - if (serviceinfokey_length - index >= sizeof(module_message) - 1) { - LOG(LOG_ERROR, "ServiceInfoKV read: Invalid ServiceInfoKey\n"); + if (serviceinfokey_length - index >= + sizeof(module_message) - 1) { + LOG(LOG_ERROR, + "ServiceInfoKV read: Invalid ServiceInfoKey\n"); *cb_return_val = MESSAGE_BODY_ERROR; goto exit; } while (index < serviceinfokey_length) { - module_message[module_msg_index] = serviceinfokey[index]; + module_message[module_msg_index] = + serviceinfokey[index]; ++module_msg_index; ++index; } // start parsing ServiceInfoVal now if (!fdor_string_length(fdor, &serviceinfoval_length)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read ServiceInfoKey length\n"); + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read " + "ServiceInfoKey length\n"); goto exit; } serviceinfoval = fdo_byte_array_alloc(serviceinfoval_length); if (!serviceinfoval) { - LOG(LOG_ERROR, - "ServiceInfoKV read: Failed to alloc ServiceInfoVal\n"); + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to alloc " + "ServiceInfoVal\n"); goto exit; } - if (!fdor_byte_string(fdor, serviceinfoval->bytes, serviceinfoval->byte_sz)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read ServiceInfoVal\n"); + if (!fdor_byte_string(fdor, serviceinfoval->bytes, + serviceinfoval->byte_sz)) { + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read " + "ServiceInfoVal\n"); goto exit; } if (!fdor_end_array(fdor)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to end array\n"); + LOG(LOG_ERROR, + "ServiceInfoKV read: Failed to end array\n"); goto exit; } - if (!fdo_supply_serviceinfoval(&module_name[0], &module_message[0], - serviceinfoval, module_list, cb_return_val)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read ServiceInfoVal\n"); + if (!fdo_supply_serviceinfoval( + &module_name[0], &module_message[0], serviceinfoval, + module_list, cb_return_val)) { + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to read " + "ServiceInfoVal\n"); goto exit; } @@ -4943,9 +5302,10 @@ bool fdo_serviceinfo_read(fdor_t *fdor, fdo_sdk_service_info_module_list_t *modu fdo_byte_array_free(serviceinfoval); serviceinfoval = NULL; if (*cb_return_val == FDO_SI_INVALID_MOD_ERROR) { - if (!fdo_serviceinfo_invalid_modname_add(module_name, - serviceinfo_invalid_modnames)) { - LOG(LOG_ERROR, "ServiceInfoKV read: Failed to add invalid module name\n"); + if (!fdo_serviceinfo_invalid_modname_add( + module_name, serviceinfo_invalid_modnames)) { + LOG(LOG_ERROR, "ServiceInfoKV read: Failed to " + "add invalid module name\n"); goto exit; } } @@ -4968,16 +5328,18 @@ bool fdo_serviceinfo_read(fdor_t *fdor, fdo_sdk_service_info_module_list_t *modu } /** - * Traverse through the structure containing the list of unsupported/invalid module names - * as accessed by the Owner, and add the given module name to the end of the list. + * Traverse through the structure containing the list of unsupported/invalid + * module names as accessed by the Owner, and add the given module name to the + * end of the list. * * @param module_name - Name of the unsupported module. - * @param serviceinfo_invalid_modnames - Structure to store list of unsupported module names - * for which an access request was made by the Owner. + * @param serviceinfo_invalid_modnames - Structure to store list of unsupported + * module names for which an access request was made by the Owner. * @return true if operations was a success, false otherwise */ -bool fdo_serviceinfo_invalid_modname_add(char *module_name, - fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames) { +bool fdo_serviceinfo_invalid_modname_add( + char *module_name, fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames) +{ int strcmp_diff = 0; size_t modname_sz_rcv = 0; @@ -4990,10 +5352,11 @@ bool fdo_serviceinfo_invalid_modname_add(char *module_name, // 1st module name being allocated if (!(*serviceinfo_invalid_modnames)) { - *serviceinfo_invalid_modnames = fdo_alloc(sizeof(fdo_sv_invalid_modnames_t)); + *serviceinfo_invalid_modnames = + fdo_alloc(sizeof(fdo_sv_invalid_modnames_t)); if (!(*serviceinfo_invalid_modnames)) { LOG(LOG_ERROR, - "Failed to alloc for unsupported modules\n"); + "Failed to alloc for unsupported modules\n"); return false; } temp_current = *serviceinfo_invalid_modnames; @@ -5004,18 +5367,20 @@ bool fdo_serviceinfo_invalid_modname_add(char *module_name, temp_next = *serviceinfo_invalid_modnames; while (temp_next) { - modname_sz_rcv = strnlen_s(temp_next->bytes, - FDO_MODULE_NAME_LEN); - if (modname_sz_rcv == 0 || modname_sz_rcv == FDO_MODULE_NAME_LEN) { - LOG(LOG_ERROR, "Module name may not be NULL-terminated\n"); + modname_sz_rcv = + strnlen_s(temp_next->bytes, FDO_MODULE_NAME_LEN); + if (modname_sz_rcv == 0 || + modname_sz_rcv == FDO_MODULE_NAME_LEN) { + LOG(LOG_ERROR, + "Module name may not be NULL-terminated\n"); return false; } - if (0 != strcmp_s(temp_next->bytes, - modname_sz_rcv, module_name, &strcmp_diff)) { - LOG(LOG_ERROR, - "Failed to compare module names for unsupported modules\n"); - return false; + if (0 != strcmp_s(temp_next->bytes, modname_sz_rcv, + module_name, &strcmp_diff)) { + LOG(LOG_ERROR, "Failed to compare module names " + "for unsupported modules\n"); + return false; } if (0 == strcmp_diff) { return true; @@ -5024,32 +5389,34 @@ bool fdo_serviceinfo_invalid_modname_add(char *module_name, temp_current = temp_next; temp_next = temp_next->next; } - temp_current->next = fdo_alloc(sizeof(fdo_sv_invalid_modnames_t)); - if (!temp_current) { + temp_current->next = + fdo_alloc(sizeof(fdo_sv_invalid_modnames_t)); + if (!temp_current->next) { LOG(LOG_ERROR, - "Failed to alloc for unsupported modules\n"); + "Failed to alloc for unsupported modules\n"); return false; } } - if (0 != strncpy_s(temp_current->bytes, - FDO_MODULE_NAME_LEN, module_name, FDO_MODULE_NAME_LEN)) { - LOG(LOG_ERROR, - "Failed to copy unsupported module name\n"); + if (0 != strncpy_s(temp_current->bytes, FDO_MODULE_NAME_LEN, + module_name, FDO_MODULE_NAME_LEN)) { + LOG(LOG_ERROR, "Failed to copy unsupported module name\n"); return false; } return true; } /** - * Traverse through the structure containing the list of unsupported/invalid module names - * as accessed by the Owner, and free them one-by-one. The structure itself is not freed. + * Traverse through the structure containing the list of unsupported/invalid + * module names as accessed by the Owner, and free them one-by-one. The + * structure itself is not freed. * - * @param serviceinfo_invalid_modnames - Structure that contains the list of unsupported module - * names to be freed. + * @param serviceinfo_invalid_modnames - Structure that contains the list of + * unsupported module names to be freed. */ void fdo_serviceinfo_invalid_modname_free( - fdo_sv_invalid_modnames_t *serviceinfo_invalid_modnames) { + fdo_sv_invalid_modnames_t *serviceinfo_invalid_modnames) +{ fdo_sv_invalid_modnames_t *next = NULL; fdo_sv_invalid_modnames_t *current = NULL; @@ -5070,26 +5437,28 @@ void fdo_serviceinfo_invalid_modname_free( * Traverse the Module list to check if the module name is supported and active. * If yes, call the registered callback method that processes the ServiceInfoVal * and return true/false depending on callback's execution. - * If the module name is not supported, set cb_return_val to 'FDO_SI_INVALID_MOD_ERROR' - * and return true. - * If the module name is not active, skip the ServiceInfoVal and return true. + * If the module name is not supported, set cb_return_val to + * 'FDO_SI_INVALID_MOD_ERROR' and return true. If the module name is not active, + * skip the ServiceInfoVal and return true. * * @param module_name - moduleName as received in Owner ServiceInfo * @param module_message - messageName as received in Owner ServiceInfo - * @param module_val - moduleVal (bstr-unwrapped) as received in Owner ServiceInfo + * @param module_val - moduleVal (bstr-unwrapped) as received in Owner + * ServiceInfo * @param module_list - Owner ServiceInfo module list - * @param cb_return_val - out value to hold the return value from the registered modules. + * @param cb_return_val - out value to hold the return value from the registered + * modules. * @return true if the operation was a success, false otherwise */ bool fdo_supply_serviceinfoval(char *module_name, char *module_message, - fdo_byte_array_t *module_val, - fdo_sdk_service_info_module_list_t *module_list, int *cb_return_val) + fdo_byte_array_t *module_val, + fdo_sdk_service_info_module_list_t *module_list, + int *cb_return_val) { int strcmp_result = 1; bool retval = false; bool module_name_found = false; bool active = false; - fdo_sdk_service_info_module_list_t *traverse_list = module_list; fdor_t temp_fdor = {0}; if (!cb_return_val) { @@ -5101,16 +5470,19 @@ bool fdo_supply_serviceinfoval(char *module_name, char *module_message, return retval; } - // create a temporary FDOR to read the received unwrapped (cbor.any) ServiceInfoVal + // create a temporary FDOR to read the received unwrapped (cbor.any) + // ServiceInfoVal if (!fdor_init(&temp_fdor) || - !fdo_block_alloc_with_size(&temp_fdor.b, module_val->byte_sz)) { - LOG(LOG_ERROR, "ServiceInfo - Failed to setup temporary FDOR\n"); + !fdo_block_alloc_with_size(&temp_fdor.b, module_val->byte_sz)) { + LOG(LOG_ERROR, + "ServiceInfo - Failed to setup temporary FDOR\n"); goto end; } if (0 != memcpy_s(temp_fdor.b.block, temp_fdor.b.block_size, - module_val->bytes, module_val->byte_sz)) { - LOG(LOG_ERROR, "ServiceInfo - Failed to copy buffer into temporary FDOR\n"); + module_val->bytes, module_val->byte_sz)) { + LOG(LOG_ERROR, "ServiceInfo - Failed to copy buffer into " + "temporary FDOR\n"); goto end; } @@ -5123,59 +5495,72 @@ bool fdo_supply_serviceinfoval(char *module_name, char *module_message, strcmp_s(module_list->module.module_name, FDO_MODULE_NAME_LEN, module_name, &strcmp_result); if (strcmp_result == 0) { - // found the module, now check if the message is 'active' - // if yes, read the value and activate/deactivate the module and return. + // found the module, now check if the message is + // 'active' if yes, read the value and + // activate/deactivate the module and return. module_name_found = true; strcmp_s(module_message, FDO_MODULE_MSG_LEN, - FDO_MODULE_MESSAGE_ACTIVE, &strcmp_result); + FDO_MODULE_MESSAGE_ACTIVE, &strcmp_result); if (strcmp_result == 0) { if (!fdor_boolean(&temp_fdor, &active)) { - LOG(LOG_ERROR, "ServiceInfoKey: Failed to read module message active %s\n", - module_list->module.module_name); + LOG(LOG_ERROR, + "ServiceInfoKey: Failed to read " + "module message active %s\n", + module_list->module.module_name); goto end; } if (active) { - // traverse the list to deactivate every module - while (traverse_list) { - traverse_list->module.active = false; - traverse_list = traverse_list->next; - } // now activate the current module module_list->module.active = active; - LOG(LOG_INFO, "ServiceInfo: Activated module %s\n", - module_list->module.module_name); + LOG(LOG_INFO, + "ServiceInfo: Activated module " + "%s\n", + module_list->module.module_name); } else { // now de-activate the current module module_list->module.active = active; - LOG(LOG_INFO, "ServiceInfo: De-activated module %s\n", - module_list->module.module_name); + LOG(LOG_INFO, + "ServiceInfo: De-activated module " + "%s\n", + module_list->module.module_name); } retval = true; break; } - // if the module is activated by the Owner, only then proceed with processing - // ServiceInfoVal via callback method + // if the module is activated by the Owner, only then + // proceed with processing ServiceInfoVal via callback + // method if (module_list->module.active) { // check if module callback is successful - *cb_return_val = module_list->module.service_info_callback( - FDO_SI_SET_OSI, module_message, module_val->bytes, - &module_val->byte_sz, NULL, NULL, NULL, 0); + *cb_return_val = + module_list->module.service_info_callback( + FDO_SI_SET_OSI, module_message, + module_val->bytes, &module_val->byte_sz, + NULL, NULL, NULL, 0); if (*cb_return_val != FDO_SI_SUCCESS) { LOG(LOG_ERROR, - "ServiceInfo: %s's CB Failed for type:%d\n", - module_list->module.module_name, - FDO_SI_SET_OSI); + "ServiceInfo: %s's CB Failed for " + "type:%d\n", + module_list->module.module_name, + FDO_SI_SET_OSI); break; } retval = true; } else { - LOG(LOG_ERROR, "ServiceInfo: Received ServiceInfo for an inactive module %s\n", + LOG(LOG_ERROR, + "ServiceInfo: Received ServiceInfo for an " + "inactive module %s\n", module_list->module.module_name); - // module is present, but is not the active module. skip this ServiceInfoVal - fdor_next(&temp_fdor); + // module is present, but is not the active + // module. skip this ServiceInfoVal + if (!fdor_next(&temp_fdor)) { + LOG(LOG_DEBUG, "ServiceInfo: Failed to " + "skip active module\n"); + goto end; + } retval = true; } break; @@ -5183,14 +5568,19 @@ bool fdo_supply_serviceinfoval(char *module_name, char *module_message, module_list = module_list->next; } if (!module_name_found) { - // module is not present. skip this ServiceInfoVal and - // set cb_return_val to 'FDO_SI_INVALID_MOD_ERROR' - LOG(LOG_ERROR, - "ServiceInfo: Received ServiceInfo for an unsupported module %s\n", - module_name); - fdor_next(&temp_fdor); - *cb_return_val = FDO_SI_INVALID_MOD_ERROR; - retval = true; + // module is not present. skip this ServiceInfoVal and + // set cb_return_val to 'FDO_SI_INVALID_MOD_ERROR' + LOG(LOG_ERROR, + "ServiceInfo: Received ServiceInfo for an unsupported " + "module %s\n", + module_name); + if (!fdor_next(&temp_fdor)) { + LOG(LOG_DEBUG, + "ServiceInfo: Failed to skip unsupported module\n"); + goto end; + } + *cb_return_val = FDO_SI_INVALID_MOD_ERROR; + retval = true; } end: @@ -5205,7 +5595,9 @@ bool fdo_supply_serviceinfoval(char *module_name, char *module_message, * * @param module_list - Owner ServiceInfo module list */ -bool fdo_serviceinfo_deactivate_modules(fdo_sdk_service_info_module_list_t *module_list) { +bool fdo_serviceinfo_deactivate_modules( + fdo_sdk_service_info_module_list_t *module_list) +{ if (!module_list) { return false; @@ -5323,19 +5715,19 @@ bool fdo_service_info_add_kv_str(fdo_service_info_t *si, const char *key, kvp = fdo_service_info_fetch(si, key); kv = *kvp; if (kv == NULL) { - /* Not found, at end of linked list, add a new entry */ + /* Not found, at end of linked list, add a new entry */ kv = fdo_kv_alloc_with_str(key, val); if (kv == NULL) { return false; } - *kvp = kv; /* Use this pointer to update the next value */ + *kvp = kv; /* Use this pointer to update the next value */ si->numKV++; return true; } - /* Found, update value */ + /* Found, update value */ if (kv->str_val == NULL) { - /* No allocated string present for value, make a new one */ + /* No allocated string present for value, make a new one */ kv->str_val = fdo_string_alloc_with_str(val); } else { int val_len = strnlen_s(val, FDO_MAX_STR_SIZE); @@ -5344,12 +5736,13 @@ bool fdo_service_info_add_kv_str(fdo_service_info_t *si, const char *key, LOG(LOG_ERROR, "%s(): val " "is either 'NULL' or" - "'isn't 'NULL-terminating'\n", __func__); + "'isn't 'NULL-terminating'\n", + __func__); fdo_string_free(kv->str_val); return false; } - /* Update the string */ + /* Update the string */ fdo_string_resize_with(kv->str_val, val_len, val); } // free other values of other type @@ -5389,23 +5782,25 @@ bool fdo_service_info_add_kv_bin(fdo_service_info_t *si, const char *key, kvp = fdo_service_info_fetch(si, key); kv = *kvp; if (kv == NULL) { - /* Not found, at end of linked list, add a new entry */ + /* Not found, at end of linked list, add a new entry */ kv = fdo_kv_alloc_key_only(key); if (kv == NULL) { return false; } - kv->bin_val = fdo_byte_array_alloc_with_byte_array(val->bytes, val->byte_sz); + kv->bin_val = fdo_byte_array_alloc_with_byte_array( + val->bytes, val->byte_sz); - *kvp = kv; /* Use this pointer to update the next value */ + *kvp = kv; /* Use this pointer to update the next value */ si->numKV++; return true; } - /* Found, free the current and update value */ + /* Found, free the current and update value */ if (kv->bin_val) { fdo_byte_array_free(kv->bin_val); } - kv->bin_val = fdo_byte_array_alloc_with_byte_array(val->bytes, val->byte_sz); + kv->bin_val = + fdo_byte_array_alloc_with_byte_array(val->bytes, val->byte_sz); // free other values of other type if (kv->str_val) { @@ -5433,7 +5828,7 @@ bool fdo_service_info_add_kv_bin(fdo_service_info_t *si, const char *key, * @return true if updated correctly else false. */ bool fdo_service_info_add_kv_bool(fdo_service_info_t *si, const char *key, - bool val) + bool val) { fdo_key_value_t **kvp = NULL, *kv = NULL; @@ -5444,18 +5839,19 @@ bool fdo_service_info_add_kv_bool(fdo_service_info_t *si, const char *key, kvp = fdo_service_info_fetch(si, key); kv = *kvp; if (kv == NULL) { - /* Not found, at end of linked list, add a new entry */ + /* Not found, at end of linked list, add a new entry */ kv = fdo_kv_alloc_key_only(key); if (kv == NULL) { return false; } kv->bool_val = fdo_alloc(sizeof(bool)); if (!kv->bool_val) { - LOG(LOG_ERROR, "Failed to alloc bool Device ServiceInfoVal"); + LOG(LOG_ERROR, + "Failed to alloc bool Device ServiceInfoVal"); return false; } *kv->bool_val = val; - *kvp = kv; /* Use this pointer to update the next value */ + *kvp = kv; /* Use this pointer to update the next value */ si->numKV++; return true; } @@ -5504,18 +5900,19 @@ bool fdo_service_info_add_kv_int(fdo_service_info_t *si, const char *key, kvp = fdo_service_info_fetch(si, key); kv = *kvp; if (kv == NULL) { - /* Not found, at end of linked list, add a new entry */ + /* Not found, at end of linked list, add a new entry */ kv = fdo_kv_alloc_key_only(key); if (kv == NULL) { return false; } kv->int_val = fdo_alloc(sizeof(int)); if (!kv->int_val) { - LOG(LOG_ERROR, "Failed to alloc int Device ServiceInfoVal"); + LOG(LOG_ERROR, + "Failed to alloc int Device ServiceInfoVal"); return false; } *kv->int_val = val; - *kvp = kv; /* Use this pointer to update the next value */ + *kvp = kv; /* Use this pointer to update the next value */ si->numKV++; return true; } @@ -5603,21 +6000,24 @@ bool fdo_serviceinfo_write(fdow_t *fdow, fdo_service_info_t *si, size_t mtu) } if (!fdow_start_array(fdow, si->sv_index_end - si->sv_index_begin)) { - LOG(LOG_ERROR, "Platform Device ServiceInfo: Failed to write start array\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfo: Failed to write " + "start array\n"); goto end; } num = si->sv_index_begin; // fetch all platfrom Device ServiceInfo's one-by-one while (num != si->sv_index_end) { if (!fdo_serviceinfo_kv_write(fdow, si, num, mtu)) { - LOG(LOG_ERROR, "Platform Device ServiceInfo: Failed to write ServiceInfoKV\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfo: Failed to " + "write ServiceInfoKV\n"); goto end; } num++; } if (!fdow_end_array(fdow)) { - LOG(LOG_ERROR, "Platform Device ServiceInfo: Failed to write end array\n"); + LOG(LOG_ERROR, + "Platform Device ServiceInfo: Failed to write end array\n"); goto end; } ret = true; @@ -5641,7 +6041,8 @@ bool fdo_serviceinfo_write(fdow_t *fdow, fdo_service_info_t *si, size_t mtu) * * @return true if the opration was a success, false otherwise */ -bool fdo_serviceinfo_kv_write(fdow_t *fdow, fdo_service_info_t *si, size_t num, size_t mtu) +bool fdo_serviceinfo_kv_write(fdow_t *fdow, fdo_service_info_t *si, size_t num, + size_t mtu) { fdo_key_value_t **kvp = NULL; fdo_key_value_t *kv = NULL; @@ -5658,85 +6059,112 @@ bool fdo_serviceinfo_kv_write(fdow_t *fdow, fdo_service_info_t *si, size_t num, kv = *kvp; if (!kv || !kv->key) { - LOG(LOG_ERROR, "Platform Device ServiceInfo: Key/Value not found\n"); + LOG(LOG_ERROR, + "Platform Device ServiceInfo: Key/Value not found\n"); goto end; } - // create temporary FDOW, use it to encode ServiceInfoVal array and then clear it. - if (!fdow_init(&temp_fdow) || !fdo_block_alloc_with_size(&temp_fdow.b, mtu) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, - "Platform Device ServiceInfo: FDOW Initialization/Allocation failed!\n"); + // create temporary FDOW, use it to encode ServiceInfoVal array and then + // clear it. + if (!fdow_init(&temp_fdow) || + !fdo_block_alloc_with_size(&temp_fdow.b, mtu) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, "Platform Device ServiceInfo: FDOW " + "Initialization/Allocation failed!\n"); goto end; } // start writing ServiceInfoKV if (!fdow_start_array(fdow, 2)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write start array\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "start array\n"); goto end; } if (!fdow_text_string(fdow, kv->key->bytes, kv->key->byte_sz)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write ServiceInfoKey\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "ServiceInfoKey\n"); goto end; } - if (0 != strcmp_s(kv->key->bytes, kv->key->byte_sz, "devmod:modules", &strcmp_diff)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to compare\n"); + if (0 != strcmp_s(kv->key->bytes, kv->key->byte_sz, "devmod:modules", + &strcmp_diff)) { + LOG(LOG_ERROR, + "Platform Device ServiceInfoKV: Failed to compare\n"); goto end; } if (strcmp_diff == 0) { - // write value "[1,1,"fdo_sys"]" for "devmod:modules" ServiceInfoKey - // TO-DO: Update this when multi-module support is added. + // write value "[1,1,"fdo_sys"]" for "devmod:modules" + // ServiceInfoKey TO-DO: Update this when multi-module support + // is added. if (!fdo_serviceinfo_modules_list_write(&temp_fdow)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKeyVal: Failed to write modules\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfoKeyVal: " + "Failed to write modules\n"); goto end; } } else { - // CBOR-encode the appropriate ServiceInfoVal using temporary FDOW + // CBOR-encode the appropriate ServiceInfoVal using temporary + // FDOW if (kv->str_val) { if (!fdow_text_string(&temp_fdow, kv->str_val->bytes, - si->sv_val_index == 0 ? (size_t) kv->str_val->byte_sz : si->sv_val_index)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write Text ServiceInfoVal\n"); + si->sv_val_index == 0 + ? (size_t)kv->str_val->byte_sz + : si->sv_val_index)) { + LOG(LOG_ERROR, + "Platform Device ServiceInfoKV: Failed to " + "write Text ServiceInfoVal\n"); goto end; } } else if (kv->bin_val) { if (!fdow_byte_string(&temp_fdow, kv->bin_val->bytes, - si->sv_val_index == 0 ? kv->bin_val->byte_sz : si->sv_val_index)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write Binary ServiceInfoVal\n"); + si->sv_val_index == 0 + ? kv->bin_val->byte_sz + : si->sv_val_index)) { + LOG(LOG_ERROR, + "Platform Device ServiceInfoKV: Failed to " + "write Binary ServiceInfoVal\n"); goto end; } } else if (kv->bool_val) { if (!fdow_boolean(&temp_fdow, *kv->bool_val)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write Bool ServiceInfoVal\n"); + LOG(LOG_ERROR, + "Platform Device ServiceInfoKV: Failed to " + "write Bool ServiceInfoVal\n"); goto end; } } else if (kv->int_val) { if (!fdow_signed_int(&temp_fdow, *kv->int_val)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write Int ServiceInfoVal\n"); + LOG(LOG_ERROR, + "Platform Device ServiceInfoKV: Failed to " + "write Int ServiceInfoVal\n"); goto end; } } else { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: No ServiceInfoVal found\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: No " + "ServiceInfoVal found\n"); goto end; } } if (!fdow_encoded_length(&temp_fdow, &temp_fdow.b.block_size)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to get encoded length\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to get " + "encoded length\n"); goto end; } - // Now, wrap the CBOR-encoded ServiceInfoVal at temporary FDOW, into a bstr - if (!fdow_byte_string(fdow, temp_fdow.b.block, temp_fdow.b.block_size)) { - LOG(LOG_ERROR, - "Platform Device ServiceInfoKV: Failed to write ServiceInfoVal as bstr\n"); + // Now, wrap the CBOR-encoded ServiceInfoVal at temporary FDOW, into a + // bstr + if (!fdow_byte_string(fdow, temp_fdow.b.block, + temp_fdow.b.block_size)) { + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "ServiceInfoVal as bstr\n"); goto end; } if (!fdow_end_array(fdow)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write end array\n"); + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "end array\n"); goto end; } ret = true; @@ -5749,37 +6177,56 @@ bool fdo_serviceinfo_kv_write(fdow_t *fdow, fdo_service_info_t *si, size_t num, /** * Write the key 'devmod:modules' with value of form [int, int, text,....] - * into the given FDOW object. Currently, it only writes 1 ServiceInfo module name - * 'fdo_sys', i.e [1,1,"fdo_sys"]. + * into the given FDOW object. Currently, it only writes 1 ServiceInfo module + * name 'fdo_sys', i.e [1,1,"fdo_sys"]. * @param fdow - Pointer to the writer. */ -bool fdo_serviceinfo_modules_list_write(fdow_t *fdow) { +bool fdo_serviceinfo_modules_list_write(fdow_t *fdow) +{ bool ret = false; - char module_value[8] = "fdo_sys"; + char module_value1[FDO_MODULE_NAME_LEN] = "fdo_sys"; + char module_value2[FDO_MODULE_NAME_LEN] = "fdo.download"; + char module_value3[FDO_MODULE_NAME_LEN] = "fdo.command"; - if (!fdow_start_array(fdow, 3)) { - LOG(LOG_ERROR, - "Platform Device ServiceInfoKV: Failed to start ServiceInfoVal (modules) array\n"); + if (!fdow_start_array(fdow, 5)) { + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to start " + "ServiceInfoVal (modules) array\n"); goto end; } - if (!fdow_signed_int(fdow, 1)) { - LOG(LOG_ERROR, - "Platform Device ServiceInfoKV: Failed to write ServiceInfoVal (modules) nummodules\n"); + if (!fdow_signed_int(fdow, 3)) { + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "ServiceInfoVal (modules) nummodules\n"); goto end; } - if (!fdow_signed_int(fdow, 1)) { - LOG(LOG_ERROR, - "Platform Device ServiceInfoKV: Failed to write ServiceInfoVal (modules) return count\n"); + if (!fdow_signed_int(fdow, 3)) { + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "ServiceInfoVal (modules) return count\n"); goto end; } - if (!fdow_text_string(fdow, module_value, strnlen_s(module_value, FDO_MAX_STR_SIZE))) { - LOG(LOG_ERROR, - "Platform Device ServiceInfoKV: Failed to write ServiceInfoVal (modules) module name\n"); + if (!fdow_text_string(fdow, module_value1, + strnlen_s(module_value1, FDO_MAX_STR_SIZE))) { + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "ServiceInfoVal (modules) module name\n"); + goto end; + } + + if (!fdow_text_string(fdow, module_value2, + strnlen_s(module_value2, FDO_MAX_STR_SIZE))) { + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "ServiceInfoVal (modules) module name\n"); + goto end; + } + + if (!fdow_text_string(fdow, module_value3, + strnlen_s(module_value3, FDO_MAX_STR_SIZE))) { + LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to write " + "ServiceInfoVal (modules) module name\n"); goto end; } if (!fdow_end_array(fdow)) { - LOG(LOG_ERROR, "Platform Device ServiceInfoKV: Failed to end array\n"); + LOG(LOG_ERROR, + "Platform Device ServiceInfoKV: Failed to end array\n"); goto end; } ret = true; @@ -5788,21 +6235,24 @@ bool fdo_serviceinfo_modules_list_write(fdow_t *fdow) { } /** - * Return bool value representing whether any external ServiceInfo module has message to - * send in the NEXT iteration. This determines the TO2.DeviceServiceInfo.IsMoreServiceInfo value - * for any currently active module. + * Return bool value representing whether any external ServiceInfo module has + * message to send in the NEXT iteration. This determines the + * TO2.DeviceServiceInfo.IsMoreServiceInfo value for any currently active + * module. * * @param fdow - Pointer to the writer. * @param module_list - Pointer to the ServiceInfo module list containing all * Device ServiceInfos modules. * @param mtu - MTU to be used for fitting the values. - * @param is_more - Out parameter (Pointer) that will store the callback's value for - * TO2.DeviceServiceInfo.IsMoreServiceInfo. + * @param is_more - Out parameter (Pointer) that will store the callback's value + * for TO2.DeviceServiceInfo.IsMoreServiceInfo. * * @return true the operation was a success, false otherwise. */ -bool fdo_serviceinfo_external_mod_is_more(fdow_t *fdow, - fdo_sdk_service_info_module_list_t *module_list, size_t mtu, bool *is_more) { +bool fdo_serviceinfo_external_mod_is_more( + fdow_t *fdow, fdo_sdk_service_info_module_list_t *module_list, size_t mtu, + bool *is_more) +{ if (!fdow || !module_list || !is_more) { return false; @@ -5812,10 +6262,12 @@ bool fdo_serviceinfo_external_mod_is_more(fdow_t *fdow, while (traverse_list) { if (traverse_list->module.active && - traverse_list->module.service_info_callback( - FDO_SI_IS_MORE_DSI, NULL, NULL, NULL, NULL, NULL, &more, mtu) != FDO_SI_SUCCESS) { + traverse_list->module.service_info_callback( + FDO_SI_IS_MORE_DSI, NULL, NULL, NULL, NULL, NULL, &more, + mtu) != FDO_SI_SUCCESS) { LOG(LOG_DEBUG, "Sv_info: %s's CB Failed for type:%d\n", - traverse_list->module.module_name, FDO_SI_HAS_MORE_DSI); + traverse_list->module.module_name, + FDO_SI_HAS_MORE_DSI); return false; } if (more) { @@ -5828,20 +6280,21 @@ bool fdo_serviceinfo_external_mod_is_more(fdow_t *fdow, } /** - * Return a module reference that has some ServiceInfo to be sent NOW/immediately, - * by making callbacks to each active module, to determine whether the module - * has something to send immediately. + * Return a module reference that has some ServiceInfo to be sent + * NOW/immediately, by making callbacks to each active module, to determine + * whether the module has something to send immediately. * * @param fdow - Pointer to the writer. * @param module_list - Pointer to the ServiceInfo module list containing all * Device ServiceInfos modules. * @param mtu - MTU to be used for fitting the values. * - * @return Pointer to/module reference (fdo_sdk_service_info_module *) if there is any module - * that has ServiceInfo to send NOW/immediately, else return NULL. + * @return Pointer to/module reference (fdo_sdk_service_info_module *) if there + * is any module that has ServiceInfo to send NOW/immediately, else return NULL. */ -fdo_sdk_service_info_module* fdo_serviceinfo_get_external_mod_to_write(fdow_t *fdow, - fdo_sdk_service_info_module_list_t *module_list, size_t mtu) { +fdo_sdk_service_info_module *fdo_serviceinfo_get_external_mod_to_write( + fdow_t *fdow, fdo_sdk_service_info_module_list_t *module_list, size_t mtu) +{ if (!fdow || !module_list) { return NULL; @@ -5851,10 +6304,12 @@ fdo_sdk_service_info_module* fdo_serviceinfo_get_external_mod_to_write(fdow_t *f while (traverse_list) { if (traverse_list->module.active && - traverse_list->module.service_info_callback( - FDO_SI_HAS_MORE_DSI, NULL, NULL, NULL, NULL, &has_more, NULL, mtu) != FDO_SI_SUCCESS) { + traverse_list->module.service_info_callback( + FDO_SI_HAS_MORE_DSI, NULL, NULL, NULL, NULL, &has_more, + NULL, mtu) != FDO_SI_SUCCESS) { LOG(LOG_DEBUG, "Sv_info: %s's CB Failed for type:%d\n", - traverse_list->module.module_name, FDO_SI_HAS_MORE_DSI); + traverse_list->module.module_name, + FDO_SI_HAS_MORE_DSI); return NULL; } if (has_more) { @@ -5867,15 +6322,17 @@ fdo_sdk_service_info_module* fdo_serviceinfo_get_external_mod_to_write(fdow_t *f /** * Given an active ServiceInfo module, invoke the callback on the same, - * to get the number of ServiceInfoKVs and CBOR-encoded ServiceInfoVal to be sent. - * Use the same to then write the 'ServiceInfo' structure. + * to get the number of ServiceInfoKVs and CBOR-encoded ServiceInfoVal to be + * sent. Use the same to then write the 'ServiceInfo' structure. * * NOTE: This currently writes ONLY 1 ServiceInfoKV inside ServiceInfo array. * This can be extended to write multiple ServiceInfoKVs, but would require us - * to fit those within MTU here (similar to devmod + unsupported module mtu fitting). + * to fit those within MTU here (similar to devmod + unsupported module mtu + * fitting). * * @param fdow - Pointer to the writer. - * @param ext_serviceinfo - Pointer to store CBOR-encoded ServiceInfoVal from the module. + * @param ext_serviceinfo - Pointer to store CBOR-encoded ServiceInfoVal from + * the module. * @param module - Pointer to the ServiceInfo module list containing all * Device ServiceInfos modules. * @param mtu - MTU to be used for fitting the values. @@ -5883,11 +6340,13 @@ fdo_sdk_service_info_module* fdo_serviceinfo_get_external_mod_to_write(fdow_t *f * @return Return true if the operation was successful, else return false. */ bool fdo_serviceinfo_external_mod_write(fdow_t *fdow, - fdo_byte_array_t *ext_serviceinfo, - fdo_sdk_service_info_module *module, - size_t mtu) { + fdo_byte_array_t *ext_serviceinfo, + fdo_sdk_service_info_module *module, + size_t mtu) +{ - char serviceinfokv_key[FDO_MODULE_NAME_LEN + FDO_MODULE_MSG_LEN + 1] = {0}; + char serviceinfokv_key[FDO_MODULE_NAME_LEN + FDO_MODULE_MSG_LEN + 1] = { + 0}; char module_message[FDO_MODULE_MSG_LEN] = {0}; size_t module_name_sz = 0; size_t module_message_sz = 0; @@ -5896,25 +6355,28 @@ bool fdo_serviceinfo_external_mod_write(fdow_t *fdow, return false; } - // clear for immmediate usage and use ext_serviceinfo.byte_sz to store the final length + // clear for immmediate usage and use ext_serviceinfo.byte_sz to store + // the final length if (memset_s(ext_serviceinfo->bytes, ext_serviceinfo->byte_sz, 0)) { - LOG(LOG_ERROR, - "Device ServiceInfoKV: Failed to clear memory for external ServiceInfoVal\n"); + LOG(LOG_ERROR, "Device ServiceInfoKV: Failed to clear memory " + "for external ServiceInfoVal\n"); return false; } // get the CBOR-encoded ServiceInfoVal from the external module if (module->service_info_callback(FDO_SI_GET_DSI, &module_message[0], - ext_serviceinfo->bytes, &ext_serviceinfo->byte_sz, - NULL, NULL, NULL, mtu) != FDO_SI_SUCCESS) { + ext_serviceinfo->bytes, + &ext_serviceinfo->byte_sz, NULL, NULL, + NULL, mtu) != FDO_SI_SUCCESS) { LOG(LOG_DEBUG, "Sv_info: %s's CB Failed for type:%d\n", - module->module_name, FDO_SI_GET_DSI); + module->module_name, FDO_SI_GET_DSI); return false; } // create 'modulename:modulemessage' - module_name_sz = strnlen_s(module->module_name, sizeof(module->module_name)); - if (memcpy_s(&serviceinfokv_key[0], module_name_sz, - module->module_name, module_name_sz) != 0) { + module_name_sz = + strnlen_s(module->module_name, sizeof(module->module_name)); + if (memcpy_s(&serviceinfokv_key[0], module_name_sz, module->module_name, + module_name_sz) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); return false; } @@ -5922,7 +6384,7 @@ bool fdo_serviceinfo_external_mod_write(fdow_t *fdow, // finally form "modulename:modulemessage" by appending 'modulemessage' module_message_sz = strnlen_s(module_message, sizeof(module_message)); if (memcpy_s(&serviceinfokv_key[module_name_sz + 1], module_message_sz, - module_message, module_message_sz) != 0) { + module_message, module_message_sz) != 0) { LOG(LOG_ERROR, "Memcpy Failed\n"); return false; } @@ -5930,35 +6392,43 @@ bool fdo_serviceinfo_external_mod_write(fdow_t *fdow, // start writing ServiceInfo array if (!fdow_start_array(fdow, 1)) { - LOG(LOG_ERROR, "Device ServiceInfo: Failed to write start ServiceInfo array\n"); + LOG(LOG_ERROR, "Device ServiceInfo: Failed to write start " + "ServiceInfo array\n"); return false; } // now start writing ServiceInfoKV array if (!fdow_start_array(fdow, 2)) { - LOG(LOG_ERROR, "Device ServiceInfoKV: Failed to write start ServiceInfoKV array\n"); + LOG(LOG_ERROR, "Device ServiceInfoKV: Failed to write start " + "ServiceInfoKV array\n"); return false; } // Write ServiceInfoKey - if (!fdow_text_string(fdow, serviceinfokv_key, module_name_sz + 1 + module_message_sz)) { - LOG(LOG_ERROR, "Device ServiceInfoKV: Failed to write ServiceInfoKey\n"); + if (!fdow_text_string(fdow, serviceinfokv_key, + module_name_sz + 1 + module_message_sz)) { + LOG(LOG_ERROR, + "Device ServiceInfoKV: Failed to write ServiceInfoKey\n"); return false; } // bstr-wrap ServiceInfoVal - if (!fdow_byte_string(fdow, ext_serviceinfo->bytes, ext_serviceinfo->byte_sz)) { - LOG(LOG_ERROR, "Device ServiceInfoKV: Failed to write ServiceInfoVal as bstr\n"); + if (!fdow_byte_string(fdow, ext_serviceinfo->bytes, + ext_serviceinfo->byte_sz)) { + LOG(LOG_ERROR, "Device ServiceInfoKV: Failed to write " + "ServiceInfoVal as bstr\n"); return false; } if (!fdow_end_array(fdow)) { - LOG(LOG_ERROR, "Device ServiceInfo: Failed to write ServiceInfoKV end array\n"); + LOG(LOG_ERROR, "Device ServiceInfo: Failed to write " + "ServiceInfoKV end array\n"); return false; } if (!fdow_end_array(fdow)) { - LOG(LOG_ERROR, "Device ServiceInfo: Failed to write ServiceInfo end array\n"); + LOG(LOG_ERROR, "Device ServiceInfo: Failed to write " + "ServiceInfo end array\n"); return false; } return true; @@ -5976,9 +6446,10 @@ bool fdo_serviceinfo_external_mod_write(fdow_t *fdow, * @param si - Pointer to the fdo_service_info_t list containing all platform * Device ServiceInfos. * @param mtu - MTU to be used for fitting the values -* @return Return true if operation was successful, else return false. + * @return Return true if operation was successful, else return false. */ -bool fdo_serviceinfo_fit_mtu(fdow_t *fdow, fdo_service_info_t *si, size_t mtu) { +bool fdo_serviceinfo_fit_mtu(fdow_t *fdow, fdo_service_info_t *si, size_t mtu) +{ bool ret = false; fdo_key_value_t *kv = NULL; @@ -6011,26 +6482,29 @@ bool fdo_serviceinfo_fit_mtu(fdow_t *fdow, fdo_service_info_t *si, size_t mtu) { LOG(LOG_ERROR, "Failed to write ServiceInfoKV\n"); goto end; } - if (!fdow_encoded_length(fdow, &encoded_length) || encoded_length == 0) { + if (!fdow_encoded_length(fdow, &encoded_length) || + encoded_length == 0) { LOG(LOG_ERROR, "Failed to read ServiceInfoKV length\n"); goto end; } if (encoded_length >= mtu) { // this key-value does not fit within the MTU - // now, check if atleast the key fits with some room for value + // now, check if atleast the key fits with some room for + // value kvp = fdo_service_info_get(si, num); kv = *kvp; if ((fit_so_far + kv->key->byte_sz + 10) < mtu) { - // the key fits and atleast 10 bytes of value fits - // the difference gives the exact length exceeding the MTU - // for the given key and partial value + // the key fits and atleast 10 bytes of value + // fits the difference gives the exact length + // exceeding the MTU for the given key and + // partial value si->sv_val_index = encoded_length - mtu; si->sv_index_end++; ret = true; goto end; } else { - // key and partial value cannot be fit within the MTU, - // ignore this key and value, return + // key and partial value cannot be fit within + // the MTU, ignore this key and value, return si->sv_val_index = 0; ret = true; goto end; @@ -6047,7 +6521,8 @@ bool fdo_serviceinfo_fit_mtu(fdow_t *fdow, fdo_service_info_t *si, size_t mtu) { end: while (fdow->current->previous) { // recursively move to previous and free current - // this is done because we cannot close the arrays created initially + // this is done because we cannot close the arrays created + // initially fdow->current = fdow->current->previous; fdo_free(fdow->current->next); } @@ -6065,7 +6540,8 @@ bool fdo_mod_exec_sv_infotype(fdo_sdk_service_info_module_list_t *module_list, { while (module_list) { if (module_list->module.service_info_callback( - type, NULL, NULL, NULL, NULL, NULL, NULL, 0) != FDO_SI_SUCCESS) { + type, NULL, NULL, NULL, NULL, NULL, NULL, 0) != + FDO_SI_SUCCESS) { LOG(LOG_DEBUG, "Sv_info: %s's CB Failed for type:%d\n", module_list->module.module_name, type); return false; @@ -6080,8 +6556,8 @@ bool fdo_mod_exec_sv_infotype(fdo_sdk_service_info_module_list_t *module_list, * @param module_list - Global Module List Head Pointer. * @return none */ -void fdo_sv_info_clear_module_psi_osi_index(fdo_sdk_service_info_module_list_t - *module_list) +void fdo_sv_info_clear_module_psi_osi_index( + fdo_sdk_service_info_module_list_t *module_list) { if (module_list) { while (module_list) { @@ -6183,33 +6659,41 @@ bool fdo_compare_rv_lists(fdo_rendezvous_list_t *rv_list1, goto end; } - if (rv_list1_traverse->num_rv_directives != rv_list2_traverse->num_rv_directives) { - LOG(LOG_ERROR, "Number of RendezvousDirective(s) do not match\n"); + if (rv_list1_traverse->num_rv_directives != + rv_list2_traverse->num_rv_directives) { + LOG(LOG_ERROR, + "Number of RendezvousDirective(s) do not match\n"); goto end; } while (rv_directive_index < rv_list1_traverse->num_rv_directives && - rv_directive_index < rv_list2_traverse->num_rv_directives) { + rv_directive_index < rv_list2_traverse->num_rv_directives) { fdo_rendezvous_directive_t *directive1 = - fdo_rendezvous_directive_get(rv_list1_traverse, rv_directive_index); + fdo_rendezvous_directive_get(rv_list1_traverse, + rv_directive_index); fdo_rendezvous_directive_t *directive2 = - fdo_rendezvous_directive_get(rv_list2_traverse, rv_directive_index); + fdo_rendezvous_directive_get(rv_list2_traverse, + rv_directive_index); if (!directive1 || !directive2) { - LOG(LOG_ERROR, "One of the RendezvousDirective(s) is empty\n"); + LOG(LOG_ERROR, + "One of the RendezvousDirective(s) is empty\n"); goto end; } rv_instr_index = 0; while (rv_instr_index < directive1->num_entries && - rv_instr_index < directive2->num_entries) { + rv_instr_index < directive2->num_entries) { fdo_rendezvous_t *entry_ptr1 = - fdo_rendezvous_list_get(directive1, rv_instr_index); + fdo_rendezvous_list_get(directive1, rv_instr_index); fdo_rendezvous_t *entry_ptr2 = - fdo_rendezvous_list_get(directive2, rv_instr_index); + fdo_rendezvous_list_get(directive2, rv_instr_index); if ((!entry_ptr1 || !entry_ptr2)) { - LOG(LOG_ERROR, "One of the RendezvousInstr(s) is empty\n"); + LOG(LOG_ERROR, + "One of the RendezvousInstr(s) is empty\n"); goto end; } - if (!fdo_rendezvous_instr_compare(entry_ptr1, entry_ptr2)) { - LOG(LOG_ERROR, "One of the RendezvousInstr(s) is empty\n"); + if (!fdo_rendezvous_instr_compare(entry_ptr1, + entry_ptr2)) { + LOG(LOG_ERROR, + "One of the RendezvousInstr(s) is empty\n"); goto end; } rv_instr_index++; @@ -6222,14 +6706,17 @@ bool fdo_compare_rv_lists(fdo_rendezvous_list_t *rv_list1, } /** - * Compare the given RendezvousInstr(s) represented by the two fdo_rendezvous_t, with one another. + * Compare the given RendezvousInstr(s) represented by the two fdo_rendezvous_t, + * with one another. * * @param entry1: pointer to input first fdo_rendezvous_t object * @param entry2: pointer to input second fdo_rendezvous_t object * @return * true if both RendexvousInstr(s) are same else false. */ -bool fdo_rendezvous_instr_compare(fdo_rendezvous_t *entry1, fdo_rendezvous_t *entry2) { +bool fdo_rendezvous_instr_compare(fdo_rendezvous_t *entry1, + fdo_rendezvous_t *entry2) +{ int memcmp_diff = -1; @@ -6239,95 +6726,102 @@ bool fdo_rendezvous_instr_compare(fdo_rendezvous_t *entry1, fdo_rendezvous_t *en } if (entry1->dev_only != NULL && entry2->dev_only != NULL && - *entry1->dev_only == *entry2->dev_only) { + *entry1->dev_only == *entry2->dev_only) { return true; } if (entry1->owner_only != NULL && entry2->owner_only != NULL && - *entry1->owner_only == *entry2->owner_only) { + *entry1->owner_only == *entry2->owner_only) { return true; } if (entry1->ip != NULL && entry2->ip != NULL) { - memcmp_s(entry1->ip->addr, entry1->ip->length, - entry2->ip->addr,entry1->ip->length, &memcmp_diff); - if (memcmp_diff == 0) { + if (!memcmp_s(entry1->ip->addr, entry1->ip->length, + entry2->ip->addr, entry1->ip->length, + &memcmp_diff) && + !memcmp_diff) { return true; + } else { + return false; } } if (entry1->po != NULL && entry2->po != NULL && - *entry1->po == *entry2->po) { + *entry1->po == *entry2->po) { return true; } if (entry1->pow != NULL && entry2->pow != NULL && - *entry1->pow == *entry2->pow) { + *entry1->pow == *entry2->pow) { return true; } if (entry1->dn != NULL && entry2->dn != NULL && - entry1->dn->byte_sz == entry2->dn->byte_sz && - 0 == strncmp(entry1->dn->bytes, entry2->dn->bytes, entry1->dn->byte_sz)) { + entry1->dn->byte_sz == entry2->dn->byte_sz && + 0 == strncmp(entry1->dn->bytes, entry2->dn->bytes, + entry1->dn->byte_sz)) { return true; } if (entry1->sch != NULL && entry2->sch != NULL && - fdo_compare_hashes(entry1->sch, entry2->sch)) { + fdo_compare_hashes(entry1->sch, entry2->sch)) { return true; } if (entry1->cch != NULL && entry2->cch != NULL && - fdo_compare_hashes(entry1->cch, entry2->cch)) { + fdo_compare_hashes(entry1->cch, entry2->cch)) { return true; } if (entry1->ui != NULL && entry2->ui != NULL && - *entry1->ui == *entry2->ui) { + *entry1->ui == *entry2->ui) { return true; } if (entry1->ss != NULL && entry2->ss != NULL && - entry1->ss->byte_sz == entry2->ss->byte_sz && - 0 == strncmp(entry1->ss->bytes, entry2->ss->bytes, entry1->ss->byte_sz)) { + entry1->ss->byte_sz == entry2->ss->byte_sz && + 0 == strncmp(entry1->ss->bytes, entry2->ss->bytes, + entry1->ss->byte_sz)) { return true; } if (entry1->pw != NULL && entry2->pw != NULL && - entry1->pw->byte_sz == entry2->pw->byte_sz && - 0 == strncmp(entry1->pw->bytes, entry2->pw->bytes, entry1->pw->byte_sz)) { + entry1->pw->byte_sz == entry2->pw->byte_sz && + 0 == strncmp(entry1->pw->bytes, entry2->pw->bytes, + entry1->pw->byte_sz)) { return true; } if (entry1->me != NULL && entry2->me != NULL && - *entry1->me == *entry2->me) { + *entry1->me == *entry2->me) { return true; } if (entry1->pr != NULL && entry2->pr != NULL && - *entry1->pr == *entry2->pr) { + *entry1->pr == *entry2->pr) { return true; } if (entry1->delaysec != NULL && entry2->delaysec != NULL && - *entry1->delaysec == *entry2->delaysec) { + *entry1->delaysec == *entry2->delaysec) { return true; } if (entry1->bypass != NULL && entry2->bypass != NULL && - *entry1->bypass == *entry2->bypass) { + *entry1->bypass == *entry2->bypass) { return true; } - LOG(LOG_ERROR, "RendezvousInstr: Received invalid RVVariable to compare\n"); + LOG(LOG_ERROR, + "RendezvousInstr: Received invalid RVVariable to compare\n"); return false; } -void fdo_log_block(fdo_block_t *fdob) { +void fdo_log_block(fdo_block_t *fdob) +{ size_t i; for (i = 0; i < fdob->block_size; i++) { LOG(LOG_DEBUGNTS, "%02x", fdob->block[i]); } LOG(LOG_DEBUGNTS, "\n"); } - diff --git a/lib/include/crypto_utils.h b/lib/include/crypto_utils.h index 4268f989..ee3ed30d 100644 --- a/lib/include/crypto_utils.h +++ b/lib/include/crypto_utils.h @@ -11,9 +11,11 @@ #include int aes_encrypt_packet(fdo_encrypted_packet_t *cipher_txt, uint8_t *clear_txt, - size_t clear_txt_size, const uint8_t *aad, size_t aad_length); + size_t clear_txt_size, const uint8_t *aad, + size_t aad_length); int aes_decrypt_packet(fdo_encrypted_packet_t *cipher_txt, - fdo_byte_array_t *clear_txt, const uint8_t *aad, size_t aad_length); + fdo_byte_array_t *clear_txt, const uint8_t *aad, + size_t aad_length); #endif /* __CRYPTO_UTILS_H__ */ diff --git a/lib/include/fdoblockio.h b/lib/include/fdoblockio.h index 67dec00f..0eee5958 100644 --- a/lib/include/fdoblockio.h +++ b/lib/include/fdoblockio.h @@ -10,7 +10,8 @@ #include #include "cbor.h" -static inline int INT2HEX(int i) { +static inline int INT2HEX(int i) +{ return (i <= 9 ? '0' + i : 'a' - 10 + i); } @@ -22,7 +23,8 @@ typedef struct { // Helper struct that encodes values into CBOR using TinyCBOR's CborEncoder. // the self-typed next pointer is used to go inside a container and encode. -// the self-typed previous pointer is used to come out of a container once encoding is done. +// the self-typed previous pointer is used to come out of a container once +// encoding is done. typedef struct _FDOW_CBOR_ENCODER { CborEncoder cbor_encoder; struct _FDOW_CBOR_ENCODER *next; @@ -31,18 +33,19 @@ typedef struct _FDOW_CBOR_ENCODER { // Helper struct that decodes CBOR data using TinyCBOR's CborValue. // the self-typed next pointer is used to go inside a container and decode. -// the self-typed previous pointer is used to come out of a container once decoding is done. +// the self-typed previous pointer is used to come out of a container once +// decoding is done. typedef struct _FDOR_CBOR_DECODER { CborValue cbor_value; struct _FDOR_CBOR_DECODER *next; struct _FDOR_CBOR_DECODER *previous; } fdor_cbor_decoder_t; -// FDO Reader (FDOR) struct that handles the CBOR decode operation using the _FDOR_CBOR_DECODER struct -// and TinyCBOR's CborParser, finally placing the CBOR-decoded data and its size into -// fdo_block_t struct. -// have_block signifies if there's more data to be decoded while the msg_type signifies -// FDO type (Type 1x/3x/6x/255) +// FDO Reader (FDOR) struct that handles the CBOR decode operation using the +// _FDOR_CBOR_DECODER struct and TinyCBOR's CborParser, finally placing the +// CBOR-decoded data and its size into fdo_block_t struct. have_block signifies +// if there's more data to be decoded while the msg_type signifies FDO type +// (Type 1x/3x/6x/255) typedef struct _FDOR_s { fdo_block_t b; int msg_type; @@ -53,9 +56,9 @@ typedef struct _FDOR_s { typedef int (*FDOReceive_fcn_ptr_t)(fdor_t *, int); -// FDO Writer (FDOW) struct that handles the CBOR encode operation using the _FDOR_CBOR_ENCODER struct, -// It CBOR-encodes the data present in fdo_block_t struct. -// msg_type signifies FDO type (Type 1x/3x/6x/255) +// FDO Writer (FDOW) struct that handles the CBOR encode operation using the +// _FDOR_CBOR_ENCODER struct, It CBOR-encodes the data present in fdo_block_t +// struct. msg_type signifies FDO type (Type 1x/3x/6x/255) typedef struct _FDOW_s { fdo_block_t b; int msg_type; @@ -76,8 +79,8 @@ int fdow_next_block(fdow_t *fdow, int type); bool fdow_encoder_init(fdow_t *fdow_cbor); bool fdow_start_array(fdow_t *fdow_cbor, size_t array_items); bool fdow_start_map(fdow_t *fdow_cbor, size_t map_items); -bool fdow_byte_string(fdow_t *fdow_cbor, uint8_t *bytes , size_t byte_sz); -bool fdow_text_string(fdow_t *fdow_cbor, char *bytes , size_t byte_sz); +bool fdow_byte_string(fdow_t *fdow_cbor, uint8_t *bytes, size_t byte_sz); +bool fdow_text_string(fdow_t *fdow_cbor, char *bytes, size_t byte_sz); bool fdow_signed_int(fdow_t *fdow_cbor, int value); bool fdow_unsigned_int(fdow_t *fdow_cbor, uint64_t value); bool fdow_boolean(fdow_t *fdow_cbor, bool value); diff --git a/lib/include/fdocred.h b/lib/include/fdocred.h index d92c4862..eb54d17d 100644 --- a/lib/include/fdocred.h +++ b/lib/include/fdocred.h @@ -12,28 +12,28 @@ typedef enum { FDO_DEVICE_STATE_PD = 0, // Permanently Disabled FDO_DEVICE_STATE_PC = 1, // Pre-Configured - FDO_DEVICE_STATE_D = 2, // Disabled + FDO_DEVICE_STATE_D = 2, // Disabled FDO_DEVICE_STATE_READY1 = 3, // Initial Transfer Ready FDO_DEVICE_STATE_D1 = 4, // Initial Transfer Disabled FDO_DEVICE_STATE_IDLE = 5, // FDO Idle FDO_DEVICE_STATE_READYN = 6, // Transfer Ready - FDO_DEVICE_STATE_DN = 7 // Transfer Disabled + FDO_DEVICE_STATE_DN = 7 // Transfer Disabled } fdo_sdk_device_status; fdo_hash_t *fdo_pub_key_hash(fdo_public_key_t *pub_key); // 3.4.1, Device Credential sub-values typedef struct _fdo_credowner_t { - int pv; // The protocol version (DCProtVer) - fdo_byte_array_t *guid; // Initial GUID (DCGuid) + int pv; // The protocol version (DCProtVer) + fdo_byte_array_t *guid; // Initial GUID (DCGuid) fdo_rendezvous_list_t *rvlst; // RendezvousInfo (DCRVInfo) - fdo_hash_t *pkh; // Hash of the group public key (DCPubKeyHash) + fdo_hash_t *pkh; // Hash of the group public key (DCPubKeyHash) fdo_public_key_t *pk; } fdo_cred_owner_t; // 3.4.1, Device Credential sub-values typedef struct _fdo_cred_mfg_block_t { - fdo_string_t *d; // Manufacturer's Device info (DCDeviceInfo) + fdo_string_t *d; // Manufacturer's Device info (DCDeviceInfo) } fdo_cred_mfg_t; // 3.4.1, Device Credential @@ -60,10 +60,10 @@ void fdo_cred_mfg_free(fdo_cred_mfg_t *ocred_mfg); typedef struct _fdo_oventry_t { struct _fdo_oventry_t *next; uint16_t enn; - fdo_hash_t *hp_hash; // Hash of previous entry (OVEHashPrevEntry) - fdo_hash_t *hc_hash; // Hash of header info (OVEHashHdrInfo) + fdo_hash_t *hp_hash; // Hash of previous entry (OVEHashPrevEntry) + fdo_hash_t *hc_hash; // Hash of header info (OVEHashHdrInfo) fdo_byte_array_t *ove_extra; // (OVEExtra) - fdo_public_key_t *pk; // public key (OVEPubKey) + fdo_public_key_t *pk; // public key (OVEPubKey) } fdo_ov_entry_t; fdo_ov_entry_t *fdo_ov_entry_alloc_empty(void); @@ -72,9 +72,9 @@ bool fdo_ov_entry_add(fdo_ov_entry_t *root_entry, fdo_ov_entry_t *e); // 5.5.7, Replacement info supplied by the Owner in TO2.SetupDevice, Type 65 typedef struct FDOOwner_supplied_credentials_s { - fdo_rendezvous_list_t *rvlst; // replacement RendezvousInfo - fdo_byte_array_t *guid; // replacement GUID - fdo_public_key_t *pubkey; // replacement PublicKey + fdo_rendezvous_list_t *rvlst; // replacement RendezvousInfo + fdo_byte_array_t *guid; // replacement GUID + fdo_public_key_t *pubkey; // replacement PublicKey } fdo_owner_supplied_credentials_t; fdo_owner_supplied_credentials_t *fdo_owner_supplied_credentials_alloc(void); @@ -82,15 +82,15 @@ void fdo_owner_supplied_credentials_free(fdo_owner_supplied_credentials_t *ocs); // 3.4.2 OwnershipVoucher typedef struct _fdo_ownershipvoucher_t { - int prot_version; // OVHeader.OVHProtVer - fdo_byte_array_t *g2; // OVHeader.OVGuid - fdo_rendezvous_list_t *rvlst2; // OVHeader.OVRVInfo - fdo_string_t *dev_info; // OVHeader.OVDeviceInfo - fdo_public_key_t *mfg_pub_key; // OVHeader.OVPubKey - fdo_hash_t *ovoucher_hdr_hash; // OVHeaderHMac - int num_ov_entries; // num of OVEntries - fdo_ov_entry_t *ov_entries; // OVEntries - fdo_hash_t *hdc; // used for both OVDevCertChain and OVDevCertChainHash + int prot_version; // OVHeader.OVHProtVer + fdo_byte_array_t *g2; // OVHeader.OVGuid + fdo_rendezvous_list_t *rvlst2; // OVHeader.OVRVInfo + fdo_string_t *dev_info; // OVHeader.OVDeviceInfo + fdo_public_key_t *mfg_pub_key; // OVHeader.OVPubKey + fdo_hash_t *ovoucher_hdr_hash; // OVHeaderHMac + int num_ov_entries; // num of OVEntries + fdo_ov_entry_t *ov_entries; // OVEntries + fdo_hash_t *hdc; // used for both OVDevCertChain and OVDevCertChainHash } fdo_ownership_voucher_t; fdo_ownership_voucher_t *fdo_ov_alloc(void); @@ -100,12 +100,13 @@ fdo_ownership_voucher_t *fdo_ov_hdr_read(fdo_byte_array_t *ovheader); bool fdo_ov_hdr_cse_load_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac); bool fdo_ov_hdr_hmac(fdo_byte_array_t *ovheader, fdo_hash_t **hmac); fdo_hash_t *fdo_new_ov_hdr_sign(fdo_dev_cred_t *dev_cred, - fdo_owner_supplied_credentials_t *osc, fdo_hash_t *hdc); + fdo_owner_supplied_credentials_t *osc, + fdo_hash_t *hdc); bool fdo_ove_hash_prev_entry_save(fdow_t *fdow, fdo_ownership_voucher_t *ov, - fdo_hash_t *hmac); + fdo_hash_t *hmac); bool fdo_ove_hash_hdr_info_save(fdo_ownership_voucher_t *ov); bool fdo_ovheader_write(fdow_t *fdow, int protver, fdo_byte_array_t *guid, - fdo_rendezvous_list_t *rvlst, fdo_string_t *dev_info, - fdo_public_key_t *pubkey, fdo_hash_t *hdc); + fdo_rendezvous_list_t *rvlst, fdo_string_t *dev_info, + fdo_public_key_t *pubkey, fdo_hash_t *hdc); #endif /* __FDOCRED_H__ */ diff --git a/lib/include/fdonet.h b/lib/include/fdonet.h index 7c80f9ce..306b9f6a 100644 --- a/lib/include/fdonet.h +++ b/lib/include/fdonet.h @@ -20,17 +20,17 @@ bool is_owner_proxy_defined(void); bool setup_http_proxy(const char *filename, fdo_ip_address_t *fdoip, uint16_t *port_num); -bool resolve_dn(const char *dn, fdo_ip_address_t **ip, uint16_t port, - bool tls, bool proxy); +bool resolve_dn(const char *dn, fdo_ip_address_t **ip, uint16_t port, bool tls, + bool proxy); -bool connect_to_manufacturer(fdo_ip_address_t *ip, uint16_t port, - fdo_con_handle *sock_hdl, bool tls); +bool connect_to_manufacturer(fdo_ip_address_t *ip, const char *dn, + uint16_t port, bool tls); -bool connect_to_rendezvous(fdo_ip_address_t *ip, uint16_t port, - fdo_con_handle *sock_hdl, bool tls); +bool connect_to_rendezvous(fdo_ip_address_t *ip, const char *dn, uint16_t port, + bool tls); -bool connect_to_owner(fdo_ip_address_t *ip, uint16_t port, - fdo_con_handle *sock_hdl, bool tls); +bool connect_to_owner(fdo_ip_address_t *ip, const char *dn, uint16_t port, + bool tls); /* Try reconnecting to server if connection lost */ int fdo_connection_restablish(fdo_prot_ctx_t *prot_ctx); diff --git a/lib/include/fdoprot.h b/lib/include/fdoprot.h index 7bf04b95..f45f80e6 100644 --- a/lib/include/fdoprot.h +++ b/lib/include/fdoprot.h @@ -96,19 +96,19 @@ #define FDO_PROT_SPEC_VERSION 101 // minimum ServiceInfo size -#define MIN_SERVICEINFO_SZ 256 +#define MIN_SERVICEINFO_SZ 1300 // maximum ServiceInfo size #define MAX_SERVICEINFO_SZ 64000 // the margin considered while trying to fit Device ServiceInfo within MTU // which allows us to avoid sending more than the MTU at all times -// For large numbers of ServiceInfoKeyVal to be sent, a larger number might be needed -// However, the current implementation writes only 1 ServiceInfoKeyVal containing -// any number of ServiceInfoKVs +// For large numbers of ServiceInfoKeyVal to be sent, a larger number might be +// needed However, the current implementation writes only 1 ServiceInfoKeyVal +// containing any number of ServiceInfoKVs #define SERVICEINFO_MTU_FIT_MARGIN 30 // minimum message buffer size to read/write protcol (DI/TO1/TO2) -// if user-configured MAX_SERVICEINFO_SZ is more than this, that is used as the buffer length -// else this is used as the message buffer length +// if user-configured MAX_SERVICEINFO_SZ is more than this, that is used as the +// buffer length else this is used as the message buffer length #if defined(DEVICE_CSE_ENABLED) #define MSG_BUFFER_SZ BUFF_SIZE_4K_BYTES #else @@ -150,10 +150,11 @@ typedef struct fdo_prot_s { int key_encoding; fdo_rvto2addr_t *rvto2addr; fdo_dev_cred_t *dev_cred; - fdo_public_key_t * - owner_public_key; // Owner's public key - fdo_service_info_t *service_info; // store System ServiceInfo (devmod+unsupported module list) - fdo_byte_array_t *ext_service_info; // store External module ServiceInfoVal (fdo_sys, for ex.) + fdo_public_key_t *owner_public_key; // Owner's public key + fdo_service_info_t *service_info; // store System ServiceInfo + // (devmod+unsupported module list) + fdo_byte_array_t *ext_service_info; // store External module + // ServiceInfoVal (fdo_sys, for ex.) fdo_public_key_t *tls_key; // unused for now int ov_entry_num; fdo_ownership_voucher_t *ovoucher; @@ -162,13 +163,15 @@ typedef struct fdo_prot_s { fdo_cose_t *to1d_cose; fdo_sv_invalid_modnames_t *serviceinfo_invalid_modnames; uint64_t max_device_message_size; // used to store maxDeviceMessageSize - uint64_t max_owner_message_size; // used to store maxOwnerMessageSize and not used thereafter + uint64_t max_owner_message_size; // used to store maxOwnerMessageSize + // and not used thereafter uint64_t maxOwnerServiceInfoSz; uint64_t maxDeviceServiceInfoSz; bool device_serviceinfo_ismore; bool owner_serviceinfo_ismore; bool owner_serviceinfo_isdone; - size_t prot_buff_sz; // protocol buffer size, same as maxDeviceMessageSize for now + size_t prot_buff_sz; // protocol buffer size, same as + // maxDeviceMessageSize for now fdo_owner_supplied_credentials_t *osc; fdo_byte_array_t *nonce_to1proof; fdo_byte_array_t *nonce_to2proveov; @@ -223,8 +226,8 @@ bool fdo_process_states(fdo_prot_t *ps); bool fdo_check_to2_round_trips(fdo_prot_t *ps); -void fdo_send_error_message(fdow_t *fdow, int ecode, int msgnum, - char *emsg, size_t errmsg_sz); +void fdo_send_error_message(fdow_t *fdow, int ecode, int msgnum, char *emsg, + size_t errmsg_sz); void fdo_receive_error_message(fdor_t *fdor, int *ecode, int *msgnum, char *emsg, int emsg_sz); bool fdo_prot_rcv_msg(fdor_t *fdor, fdow_t *fdow, char *prot_name, int *statep); diff --git a/lib/include/fdoprotctx.h b/lib/include/fdoprotctx.h index f7261dfb..3b5623ce 100644 --- a/lib/include/fdoprotctx.h +++ b/lib/include/fdoprotctx.h @@ -21,14 +21,13 @@ typedef struct { // FDO protocol context typedef struct fdo_prot_ctx_s { - fdo_con_handle sock_hdl; bool tls; int msg_type; fdo_prot_t *protdata; bool (*protrun)(fdo_prot_t *ps); fdo_ip_address_t *host_ip; uint16_t host_port; - const char *host_dns; + char *host_dns; fdo_ip_address_t *resolved_ip; } fdo_prot_ctx_t; diff --git a/lib/include/fdotypes.h b/lib/include/fdotypes.h index d5347b23..65d8eb9d 100644 --- a/lib/include/fdotypes.h +++ b/lib/include/fdotypes.h @@ -126,7 +126,8 @@ fdo_ip_address_t *fdo_ipaddress_alloc(void); bool fdo_null_ipaddress(fdo_ip_address_t *fdoip); void fdo_init_ipv4_address(fdo_ip_address_t *fdoip, uint8_t *ipv4); bool fdo_read_ipaddress(fdor_t *fdor, fdo_ip_address_t *fdoip); -bool fdo_convert_to_ipaddress(fdo_byte_array_t * ip_bytes, fdo_ip_address_t *fdoip); +bool fdo_convert_to_ipaddress(fdo_byte_array_t *ip_bytes, + fdo_ip_address_t *fdoip); char *fdo_ipaddress_to_string(fdo_ip_address_t *fdoip, char *buf, int buf_sz); typedef struct { @@ -208,13 +209,13 @@ fdo_public_key_t *fdo_public_key_clone(fdo_public_key_t *pk); #define AES_GCM_TAG_LEN 16 #define AES_TAG_LEN AES_GCM_TAG_LEN #else -// The IV/Nonce length 'N' for CCM mode is dependent on the maximum message length 'L' value -// and should be equal to 15-L (in octets). -// Refer to [RFC3610](https://datatracker.ietf.org/doc/html/rfc3610) for more information on -// trade-offs between 'L' and 'N' value. -// The current implementation uses L=8, and hence the IV/Nonce length N = 15-8 = 7 octets -// As per FDO and COSE [RFC8152](https://datatracker.ietf.org/doc/html/rfc8152) specifications, -// L=2 could also be used. N=13 MUST be used in this case. +// The IV/Nonce length 'N' for CCM mode is dependent on the maximum message +// length 'L' value and should be equal to 15-L (in octets). Refer to +// [RFC3610](https://datatracker.ietf.org/doc/html/rfc3610) for more information +// on trade-offs between 'L' and 'N' value. The current implementation uses L=8, +// and hence the IV/Nonce length N = 15-8 = 7 octets As per FDO and COSE +// [RFC8152](https://datatracker.ietf.org/doc/html/rfc8152) specifications, L=2 +// could also be used. N=13 MUST be used in this case. #define AES_CCM_IV_LEN 7 #define AES_IV_LEN AES_CCM_IV_LEN #define AES_CCM_TAG_LEN 16 @@ -226,8 +227,8 @@ typedef struct { fdo_byte_array_t *ct_string; fdo_byte_array_t *em_body; // Ciphertext of Encrypted Message Body uint8_t tag[AES_TAG_LEN]; - fdo_hash_t *hmac; // HMAC of ct body - uint8_t iv[AES_IV_LEN]; // iv of gcm/ccm. + fdo_hash_t *hmac; // HMAC of ct body + uint8_t iv[AES_IV_LEN]; // iv of gcm/ccm. uint32_t offset; int aes_plain_type; } fdo_encrypted_packet_t; @@ -237,14 +238,16 @@ void fdo_encrypted_packet_free(fdo_encrypted_packet_t *pkt); fdo_encrypted_packet_t *fdo_encrypted_packet_read(fdor_t *fdor); bool fdo_aad_write(fdow_t *fdow, int alg_type); bool fdo_emblock_write(fdow_t *fdow, fdo_encrypted_packet_t *pkt); -bool fdo_etminnerblock_write(fdow_t *fdow, fdo_encrypted_packet_t *pkt); -bool fdo_etmouterblock_write(fdow_t *fdow, fdo_encrypted_packet_t *pkt); +bool fdo_etm_innerblock_write(fdow_t *fdow, fdo_encrypted_packet_t *pkt); +bool fdo_etm_outerblock_write(fdow_t *fdow, fdo_encrypted_packet_t *pkt); bool fdo_encrypted_packet_unwind(fdor_t *fdor, fdo_encrypted_packet_t *pkt); bool fdo_encrypted_packet_windup(fdow_t *fdow, int type); bool fdo_prep_simple_encrypted_message(fdo_encrypted_packet_t *pkt, - fdow_t *fdow, size_t fdow_buff_default_sz); + fdow_t *fdow, + size_t fdow_buff_default_sz); bool fdo_prep_composed_encrypted_message(fdo_encrypted_packet_t *pkt, - fdow_t *fdow, size_t fdow_buff_default_sz); + fdow_t *fdow, + size_t fdow_buff_default_sz); typedef struct { int aes_plain_type; @@ -261,16 +264,16 @@ typedef struct { } fdo_cose_encrypt0_t; void fdo_cose_encrypt0_free(fdo_cose_encrypt0_t *cose_encrypt0); -fdo_cose_encrypt0_t* fdo_cose_encrypt0_alloc(void); -bool fdo_cose_encrypt0_read_protected_header(fdor_t *fdor, - fdo_cose_encrypt0_protected_header_t *protected_header); -bool fdo_cose_encrypt0_read_unprotected_header(fdor_t *fdor, - fdo_cose_encrypt0_unprotected_header_t *unprotected_header); +fdo_cose_encrypt0_t *fdo_cose_encrypt0_alloc(void); +bool fdo_cose_encrypt0_read_protected_header( + fdor_t *fdor, fdo_cose_encrypt0_protected_header_t *protected_header); +bool fdo_cose_encrypt0_read_unprotected_header( + fdor_t *fdor, fdo_cose_encrypt0_unprotected_header_t *unprotected_header); bool fdo_cose_encrypt0_read(fdor_t *fdor, fdo_cose_encrypt0_t *cose_encrypt0); -bool fdo_cose_encrypt0_write_protected_header(fdow_t *fdow, - fdo_cose_encrypt0_protected_header_t *protected_header); -bool fdo_cose_encrypt0_write_unprotected_header(fdow_t *fdow, - fdo_cose_encrypt0_unprotected_header_t *unprotected_header); +bool fdo_cose_encrypt0_write_protected_header( + fdow_t *fdow, fdo_cose_encrypt0_protected_header_t *protected_header); +bool fdo_cose_encrypt0_write_unprotected_header( + fdow_t *fdow, fdo_cose_encrypt0_unprotected_header_t *unprotected_header); bool fdo_cose_encrypt0_write(fdow_t *fdow, fdo_cose_encrypt0_t *cose_encrypt0); typedef struct { @@ -290,23 +293,28 @@ typedef struct { } fdo_eat_t; // methods to handle Entity Attestation Token (EAT). -fdo_eat_t* fdo_eat_alloc(void); +fdo_eat_t *fdo_eat_alloc(void); void fdo_eat_free(fdo_eat_t *eat); -bool fdo_eat_write_protected_header(fdow_t *fdow, fdo_eat_protected_header_t *eat_ph); -bool fdo_eat_write_unprotected_header(fdow_t *fdow, fdo_eat_unprotected_header_t *eat_uph); +bool fdo_eat_write_protected_header(fdow_t *fdow, + fdo_eat_protected_header_t *eat_ph); +bool fdo_eat_write_unprotected_header(fdow_t *fdow, + fdo_eat_unprotected_header_t *eat_uph); bool fdo_eat_write(fdow_t *fdow, fdo_eat_t *eat); bool fdo_eat_write_sigstructure(fdo_eat_protected_header_t *eat_ph, - fdo_byte_array_t *eat_payload, fdo_byte_array_t *external_aad, - fdo_byte_array_t **sig_structure); + fdo_byte_array_t *eat_payload, + fdo_byte_array_t *external_aad, + fdo_byte_array_t **sig_structure); typedef struct { fdo_byte_array_t *eatpayloads; fdo_nonce_t eatnonce; fdo_ueid_t eatueid; - // EATOtherClaims: Unused in implementation. Should be added depending on the requirement. + // EATOtherClaims: Unused in implementation. Should be added depending + // on the requirement. } fdo_eat_payload_base_map_t; -bool fdo_eat_write_payloadbasemap(fdow_t *fdow, fdo_eat_payload_base_map_t *eat_payload); +bool fdo_eat_write_payloadbasemap(fdow_t *fdow, + fdo_eat_payload_base_map_t *eat_payload); typedef struct { int ph_sig_alg; @@ -325,15 +333,19 @@ typedef struct { } fdo_cose_t; void fdo_cose_free(fdo_cose_t *cose); -bool fdo_cose_read_protected_header(fdor_t *fdor, fdo_cose_protected_header_t *cose_ph); -bool fdo_cose_read_unprotected_header(fdor_t *fdor, fdo_cose_unprotected_header_t *cose_uph); +bool fdo_cose_read_protected_header(fdor_t *fdor, + fdo_cose_protected_header_t *cose_ph); +bool fdo_cose_read_unprotected_header(fdor_t *fdor, + fdo_cose_unprotected_header_t *cose_uph); bool fdo_cose_read(fdor_t *fdor, fdo_cose_t *cose, bool empty_uph); -bool fdo_cose_write_protected_header(fdow_t *fdow, fdo_cose_protected_header_t *cose_ph); +bool fdo_cose_write_protected_header(fdow_t *fdow, + fdo_cose_protected_header_t *cose_ph); bool fdo_cose_write_unprotected_header(fdow_t *fdow); bool fdo_cose_write(fdow_t *fdow, fdo_cose_t *cose); bool fdo_cose_write_sigstructure(fdo_cose_protected_header_t *cose_ph, - fdo_byte_array_t *cose_payload, fdo_byte_array_t *external_aad, - fdo_byte_array_t **sig_structure); + fdo_byte_array_t *cose_payload, + fdo_byte_array_t *external_aad, + fdo_byte_array_t **sig_structure); /* * This is a lookup on all possible TransportProtocol values (Section 3.3.12) @@ -360,7 +372,8 @@ typedef struct { void fdo_rvto2addr_entry_free(fdo_rvto2addr_entry_t *rvto2addr_entry); void fdo_rvto2addr_free(fdo_rvto2addr_t *rvto2addr); -bool fdo_rvto2addr_entry_read(fdor_t *fdor, fdo_rvto2addr_entry_t *rvto2addr_entry); +bool fdo_rvto2addr_entry_read(fdor_t *fdor, + fdo_rvto2addr_entry_t *rvto2addr_entry); bool fdo_rvto2addr_read(fdor_t *fdor, fdo_rvto2addr_t *rvto2addr); typedef struct fdo_key_value_s { @@ -449,13 +462,15 @@ typedef struct fdo_rendezvous_list_s { } fdo_rendezvous_list_t; int fdo_rendezvous_directive_add(fdo_rendezvous_list_t *list, - fdo_rendezvous_directive_t *directive); -fdo_rendezvous_directive_t *fdo_rendezvous_directive_get( - fdo_rendezvous_list_t *list, int num); + fdo_rendezvous_directive_t *directive); +fdo_rendezvous_directive_t * +fdo_rendezvous_directive_get(fdo_rendezvous_list_t *list, int num); fdo_rendezvous_list_t *fdo_rendezvous_list_alloc(void); void fdo_rendezvous_list_free(fdo_rendezvous_list_t *list); -int fdo_rendezvous_list_add(fdo_rendezvous_directive_t *list, fdo_rendezvous_t *rv); -fdo_rendezvous_t *fdo_rendezvous_list_get(fdo_rendezvous_directive_t *list, int num); +int fdo_rendezvous_list_add(fdo_rendezvous_directive_t *list, + fdo_rendezvous_t *rv); +fdo_rendezvous_t *fdo_rendezvous_list_get(fdo_rendezvous_directive_t *list, + int num); int fdo_rendezvous_list_read(fdor_t *fdor, fdo_rendezvous_list_t *list); bool fdo_rendezvous_list_write(fdow_t *fdow, fdo_rendezvous_list_t *list); @@ -483,7 +498,7 @@ bool fdo_service_info_add_kv_str(fdo_service_info_t *si, const char *key, bool fdo_service_info_add_kv_bin(fdo_service_info_t *si, const char *key, const fdo_byte_array_t *val); bool fdo_service_info_add_kv_bool(fdo_service_info_t *si, const char *key, - bool val); + bool val); bool fdo_service_info_add_kv_int(fdo_service_info_t *si, const char *key, int val); bool fdo_service_info_add_kv(fdo_service_info_t *si, fdo_key_value_t *kv); @@ -516,16 +531,18 @@ void fdo_sdk_service_info_deregister_module(void); void print_service_info_module_list(void); bool fdo_serviceinfo_write(fdow_t *fdow, fdo_service_info_t *si, size_t mtu); -bool fdo_serviceinfo_kv_write(fdow_t *fdow, fdo_service_info_t *si, size_t num, size_t mtu); +bool fdo_serviceinfo_kv_write(fdow_t *fdow, fdo_service_info_t *si, size_t num, + size_t mtu); bool fdo_serviceinfo_modules_list_write(fdow_t *fdow); -bool fdo_serviceinfo_external_mod_is_more(fdow_t *fdow, - fdo_sdk_service_info_module_list_t *module_list, size_t mtu, bool *is_more); -fdo_sdk_service_info_module* fdo_serviceinfo_get_external_mod_to_write(fdow_t *fdow, - fdo_sdk_service_info_module_list_t *module_list, - size_t mtu); -bool fdo_serviceinfo_external_mod_write(fdow_t *fdow, fdo_byte_array_t *ext_serviceinfo, - fdo_sdk_service_info_module *module, - size_t mtu); +bool fdo_serviceinfo_external_mod_is_more( + fdow_t *fdow, fdo_sdk_service_info_module_list_t *module_list, size_t mtu, + bool *is_more); +fdo_sdk_service_info_module *fdo_serviceinfo_get_external_mod_to_write( + fdow_t *fdow, fdo_sdk_service_info_module_list_t *module_list, size_t mtu); +bool fdo_serviceinfo_external_mod_write(fdow_t *fdow, + fdo_byte_array_t *ext_serviceinfo, + fdo_sdk_service_info_module *module, + size_t mtu); bool fdo_serviceinfo_fit_mtu(fdow_t *fdow, fdo_service_info_t *si, size_t mtu); bool fdo_mod_exec_sv_infotype(fdo_sdk_service_info_module_list_t *module_list, @@ -534,23 +551,28 @@ bool fdo_mod_exec_sv_infotype(fdo_sdk_service_info_module_list_t *module_list, void fdo_sv_info_clear_module_psi_osi_index( fdo_sdk_service_info_module_list_t *module_list); -bool fdo_serviceinfo_read(fdor_t *fdor, fdo_sdk_service_info_module_list_t *module_list, - int *cb_return_val, fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames); +bool fdo_serviceinfo_read( + fdor_t *fdor, fdo_sdk_service_info_module_list_t *module_list, + int *cb_return_val, + fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames); bool fdo_supply_serviceinfoval(char *module_name, char *module_message, - fdo_byte_array_t *module_val, - fdo_sdk_service_info_module_list_t *module_list, int *cb_return_val); -bool fdo_serviceinfo_invalid_modname_add(char *module_name, - fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames); + fdo_byte_array_t *module_val, + fdo_sdk_service_info_module_list_t *module_list, + int *cb_return_val); +bool fdo_serviceinfo_invalid_modname_add( + char *module_name, + fdo_sv_invalid_modnames_t **serviceinfo_invalid_modnames); void fdo_serviceinfo_invalid_modname_free( - fdo_sv_invalid_modnames_t *serviceinfo_invalid_modnames); -bool fdo_serviceinfo_deactivate_modules(fdo_sdk_service_info_module_list_t *module_list); + fdo_sv_invalid_modnames_t *serviceinfo_invalid_modnames); +bool fdo_serviceinfo_deactivate_modules( + fdo_sdk_service_info_module_list_t *module_list); bool fdo_compare_hashes(fdo_hash_t *hash1, fdo_hash_t *hash2); bool fdo_compare_byte_arrays(fdo_byte_array_t *ba1, fdo_byte_array_t *ba2); bool fdo_compare_rv_lists(fdo_rendezvous_list_t *rv_list1, fdo_rendezvous_list_t *rv_list2); bool fdo_rendezvous_instr_compare(fdo_rendezvous_t *entry1, - fdo_rendezvous_t *entry2); + fdo_rendezvous_t *entry2); void fdo_log_block(fdo_block_t *fdob); diff --git a/lib/include/load_credentials.h b/lib/include/load_credentials.h index 8e3ecd95..2b21d2aa 100644 --- a/lib/include/load_credentials.h +++ b/lib/include/load_credentials.h @@ -32,4 +32,10 @@ int store_credential(fdo_dev_cred_t *ocred); bool load_device_status(fdo_sdk_device_status *state); bool store_device_status(fdo_sdk_device_status *state); +#if defined(DEVICE_TPM20_ENABLED) +bool read_tpm_device_credentials(uint32_t nv, fdo_dev_cred_t *our_dev_cred); +bool write_tpm_device_credentials(uint32_t nv, fdo_dev_cred_t *our_dev_cred); +int store_tpm_credential(fdo_dev_cred_t *ocred); +#endif + #endif /* __LOAD_CREDENTIALS_H__ */ diff --git a/lib/include/util.h b/lib/include/util.h index c5c48a73..2d2efc63 100644 --- a/lib/include/util.h +++ b/lib/include/util.h @@ -58,7 +58,8 @@ typedef enum log_level { { \ if (level <= LOG_LEVEL) { \ if (level == LOG_ERROR) { \ - printf("ERROR:[%s():%d] ", __func__, __LINE__);\ + printf("ERROR:[%s():%d] ", __func__, \ + __LINE__); \ } \ if (level == LOG_DEBUG) { \ if (print_timestamp() != 0) \ @@ -69,7 +70,7 @@ typedef enum log_level { } #endif -//Removed(commented) the below MBEDOS part to enable compilation with ubuntu 22 +// Removed(commented) the below MBEDOS part to enable compilation with ubuntu 22 //#ifndef TARGET_OS_MBEDOS //#define ATTRIBUTE_FALLTHROUGH __attribute__((fallthrough)) //#else @@ -130,7 +131,8 @@ void hexdump(const char *message, const void *buffer, size_t size); /* Print a non null-terminated buffer. */ void print_buffer(int log_level, const uint8_t *buffer, size_t length); -/// Read a buffer from content of a file. The buffer returned is non NULL-terminated. +/// Read a buffer from content of a file. The buffer returned is non +/// NULL-terminated. /*! \param[in] filename The file path. @@ -156,6 +158,11 @@ char *strdup_s(const char *str); /* Print timestamp */ int print_timestamp(void); +#if defined(GET_DEV_SERIAL) +/* Get device serial number */ +int get_device_serial(char *str); +#endif + #ifdef __cplusplus } #endif diff --git a/lib/m-string.c b/lib/m-string.c index 63f872ca..ccd49250 100644 --- a/lib/m-string.c +++ b/lib/m-string.c @@ -12,16 +12,22 @@ #include "fdoprot.h" #include "util.h" #include "safe_lib.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include "snprintf_s.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "storage_al.h" #if defined(DEVICE_CSE_ENABLED) #include "cse_utils.h" #include "cse_tools.h" #endif +#if defined(DEVICE_TPM20_ENABLED) +#include "tpm20_Utils.h" +#include "fdo_crypto.h" +#include "tpm2_nv_storage.h" +#endif #include +#include /* * Generate the "m" string value. @@ -45,9 +51,9 @@ /* All below sizes are excluding NULL termination */ #if defined(DEVICE_CSE_ENABLED) -#define DEVICE_MFG_STRING_ARRAY_SZ 8 +#define DEVICE_MFG_STRING_ARRAY_SZ 9 #else -#define DEVICE_MFG_STRING_ARRAY_SZ 5 +#define DEVICE_MFG_STRING_ARRAY_SZ 6 #endif #define MAX_DEV_SERIAL_SZ 255 @@ -69,26 +75,95 @@ static int read_fill_modelserial(void) uint8_t def_model_sz = 0; size_t fsize = 0; +#if defined(GET_DEV_SERIAL) + int flag = 0; + int curr = 0; + char ch; + char temp_device_serial[MAX_DEV_SERIAL_SZ]; + uint8_t temp_serial_sz = 0; + + if (memset_s(temp_device_serial, sizeof(temp_device_serial), 0) != 0) { + LOG(LOG_ERROR, "Memset() failed!\n"); + goto err; + } + + ret = get_device_serial(temp_device_serial); + if (ret) { + LOG(LOG_ERROR, "Failed to get serial no.\n"); + } + + ch = temp_device_serial[0]; + if (ch == '\0') { + flag = 1; + } else { + while (ch != '\0') { + if (!isalnum(ch)) { + flag = 1; + } + ch = temp_device_serial[++curr]; + if (ch == '\n') { + ch = temp_device_serial[++curr]; + } + } + } + + if (ret || flag) { + LOG(LOG_DEBUG, "Defaulting serial num to 'abcdef'\n"); + def_serial_sz = strnlen_s(DEF_SERIAL_NO, MAX_DEV_SERIAL_SZ); + if (!def_serial_sz || def_serial_sz == MAX_DEV_SERIAL_SZ) { + LOG(LOG_ERROR, "Default serial number string isn't " + "NULL terminated\n"); + goto err; + } + + ret = strncpy_s(device_serial, MAX_DEV_SERIAL_SZ, DEF_SERIAL_NO, + def_serial_sz); + if (ret) { + LOG(LOG_ERROR, "Failed to copy serial no!\n"); + goto err; + } + } else { + temp_serial_sz = + strnlen_s(temp_device_serial, MAX_DEV_SERIAL_SZ); + if (!temp_serial_sz || temp_serial_sz == MAX_DEV_SERIAL_SZ) { + LOG(LOG_ERROR, "Default serial number string isn't " + "NULL terminated\n"); + goto err; + } + + if (*temp_device_serial && + temp_device_serial[temp_serial_sz - 1] == '\n') { + temp_device_serial[temp_serial_sz - 1] = '\0'; + } + + ret = strncpy_s(device_serial, MAX_DEV_SERIAL_SZ, + temp_device_serial, temp_serial_sz); + if (ret) { + LOG(LOG_ERROR, "Failed to copy serial no!\n"); + goto err; + } + } +#else fsize = fdo_blob_size((const char *)SERIAL_FILE, FDO_SDK_RAW_DATA); if ((fsize > 0) && (fsize <= MAX_DEV_SERIAL_SZ)) { if (fdo_blob_read((const char *)SERIAL_FILE, FDO_SDK_RAW_DATA, - (uint8_t *)device_serial, fsize) <= 0) { - + (uint8_t *)device_serial, fsize) <= 0) { LOG(LOG_ERROR, "Failed to get serial no\n"); goto err; } } else { if (fsize > MAX_DEV_SERIAL_SZ) { - LOG(LOG_INFO, "Serialno exceeds 255 characters. Defaulting it to 'abcdef'\n"); - } else { + LOG(LOG_INFO, "Serialno exceeds 255 characters. " + "Defaulting it to 'abcdef'\n"); + } else if (!fsize) { LOG(LOG_INFO, "No serialno file present!\n"); } def_serial_sz = strnlen_s(DEF_SERIAL_NO, MAX_DEV_SERIAL_SZ); if (!def_serial_sz || def_serial_sz == MAX_DEV_SERIAL_SZ) { LOG(LOG_ERROR, "Default serial number string isn't " - "NULL terminated\n"); + "NULL terminated\n"); goto err; } @@ -99,17 +174,20 @@ static int read_fill_modelserial(void) goto err; } } +#endif + LOG(LOG_DEBUG, "Device serial = %s\n", device_serial); fsize = fdo_blob_size((const char *)MODEL_FILE, FDO_SDK_RAW_DATA); if ((fsize > 0) && (fsize <= MAX_MODEL_NO_SZ)) { if (fdo_blob_read((const char *)MODEL_FILE, FDO_SDK_RAW_DATA, - (uint8_t *)model_number, fsize) <= 0) { + (uint8_t *)model_number, fsize) <= 0) { LOG(LOG_ERROR, "Failed to get serial no\n"); goto err; } } else { if (fsize > MAX_MODEL_NO_SZ) { - LOG(LOG_INFO, "Model number exceeds 32 characters. Defaulting it to '12345'\n"); + LOG(LOG_INFO, "Model number exceeds 32 characters. " + "Defaulting it to '12345'\n"); } else { LOG(LOG_INFO, "No model number file present!\n"); } @@ -117,7 +195,7 @@ static int read_fill_modelserial(void) def_model_sz = strnlen_s(DEF_MODEL_NO, MAX_MODEL_NO_SZ); if (!def_model_sz || def_model_sz == MAX_MODEL_NO_SZ) { LOG(LOG_ERROR, "Default model number string isn't " - "NULL terminated\n"); + "NULL terminated\n"); goto err; } @@ -154,6 +232,8 @@ int ps_get_m_string(fdo_prot_t *ps) fdo_byte_array_t *csr = NULL; fdow_t temp_fdow = {0}; size_t enc_device_mfginfo = 0; + fdo_byte_array_t *mac_addresses = NULL; + size_t mac_addresses_sz = 0; #if defined(DEVICE_CSE_ENABLED) fdo_byte_array_t *cse_cert = NULL; @@ -190,21 +270,27 @@ int ps_get_m_string(fdo_prot_t *ps) /* Get the CSR data */ #if defined(DEVICE_TPM20_ENABLED) - size_t m_string_sz = get_file_size(TPM_DEVICE_CSR); + size_t m_string_sz = fdo_tpm_nvread_size(TPM_DEVICE_CSR_NV_IDX); csr = fdo_byte_array_alloc(m_string_sz); if (!csr) { LOG(LOG_ERROR, - "Failed to allocate memory for device mstring.\n"); + "Failed to allocate memory for device mstring.\n"); goto err; } - ret = read_buffer_from_file(TPM_DEVICE_CSR, csr->bytes, - csr->byte_sz); - if (0 != ret) { - LOG(LOG_ERROR, "Failed to read %s file!\n", TPM_DEVICE_CSR); + if (fdo_tpm_read_nv(TPM_DEVICE_CSR_NV_IDX, csr->bytes, csr->byte_sz) == + -1) { + LOG(LOG_ERROR, "Failed to load TPM DEVICE CSR into buffer.\n"); goto err; } +#if defined(LOCK_TPM) + if (fdo_tpm_nvread_lock(TPM_DEVICE_CSR_NV_IDX)) { + LOG(LOG_ERROR, "Failed to lock file!\n"); + goto err; + } +#endif + ret = 0; #elif defined(DEVICE_CSE_ENABLED) // CSR will be NULL for CSE csr = fdo_byte_array_alloc(0); @@ -216,37 +302,45 @@ int ps_get_m_string(fdo_prot_t *ps) // Read OnDie ECDSA cert chain from CSE cse_cert = fdo_byte_array_alloc(FDO_MAX_CERT_CHAIN_SIZE); if (!cse_cert) { - LOG(LOG_ERROR,"DeviceMfgInfo: Failed to allocate data for storing cert data\n"); + LOG(LOG_ERROR, "DeviceMfgInfo: Failed to allocate data for " + "storing cert data\n"); goto err; } ret = cse_get_cert_chain(&cse_cert); if (0 != ret) { - LOG(LOG_ERROR, "DeviceMfgInfo: Unable to get Cert chain from CSE\n"); + LOG(LOG_ERROR, + "DeviceMfgInfo: Unable to get Cert chain from CSE\n"); goto err; } // Get the Sig structure - ret = cse_get_cose_sig_structure(&cose_sig_structure, (uint8_t *)device_serial, device_serial_len); + ret = cse_get_cose_sig_structure( + &cose_sig_structure, (uint8_t *)device_serial, device_serial_len); if (0 != ret) { - LOG(LOG_ERROR, "DeviceMfgInfo: Unable to get Cose Sig structure\n"); + LOG(LOG_ERROR, + "DeviceMfgInfo: Unable to get Cose Sig structure\n"); goto err; } // Read test signature and MAROE prefix fromm CSE cse_maroeprefix = fdo_byte_array_alloc(FDO_MAX_MAROE_PREFIX_SIZE); if (!cse_maroeprefix) { - LOG(LOG_ERROR,"DeviceMfgInfo: Failed to allocate data for storing CSE maroeprefix\n"); + LOG(LOG_ERROR, "DeviceMfgInfo: Failed to allocate data for " + "storing CSE maroeprefix\n"); goto err; } cse_signature = fdo_byte_array_alloc(FDO_SIGNATURE_LENGTH); if (!cse_signature) { - LOG(LOG_ERROR,"DeviceMfgInfo: Failed to allocate data for storing cse sig data\n"); + LOG(LOG_ERROR, "DeviceMfgInfo: Failed to allocate data for " + "storing cse sig data\n"); goto err; } - ret = cse_get_test_sig(&cse_signature, &cse_maroeprefix, cose_sig_structure, (uint8_t *)device_serial, device_serial_len); + ret = cse_get_test_sig(&cse_signature, &cse_maroeprefix, + cose_sig_structure, (uint8_t *)device_serial, + device_serial_len); if (0 != ret) { LOG(LOG_ERROR, "DeviceMfgInfo: Unable to get test Signature\n"); goto err; @@ -257,13 +351,38 @@ int ps_get_m_string(fdo_prot_t *ps) LOG(LOG_ERROR, "Unable to get device CSR\n"); goto err; } +#endif +#if defined(BUILD_MFG_TOOLKIT) + mac_addresses_sz = get_file_size(MAC_ADDRESSES); + + mac_addresses = fdo_byte_array_alloc(mac_addresses_sz); + if (!mac_addresses) { + LOG(LOG_ERROR, + "Failed to allocate memory for MAC ADDRESSES.\n"); + goto err; + } + + ret = read_buffer_from_file(MAC_ADDRESSES, mac_addresses->bytes, + mac_addresses->byte_sz); + if (0 != ret) { + LOG(LOG_ERROR, "Failed to read %s file!\n", MAC_ADDRESSES); + goto err; + } +#else + mac_addresses = fdo_byte_array_alloc(mac_addresses_sz); + if (!mac_addresses) { + LOG(LOG_ERROR, + "Failed to allocate memory for MAC ADDRESSES.\n"); + goto err; + } #endif // use this temporary FDOW to write DeviceMfgInfo array // 4K bytes is probably sufficient, extend if required if (!fdow_init(&temp_fdow) || - !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_4K_BYTES) || - !fdow_encoder_init(&temp_fdow)) { - LOG(LOG_ERROR, "DeviceMfgInfo: FDOW Initialization/Allocation failed!\n"); + !fdo_block_alloc_with_size(&temp_fdow.b, BUFF_SIZE_4K_BYTES) || + !fdow_encoder_init(&temp_fdow)) { + LOG(LOG_ERROR, + "DeviceMfgInfo: FDOW Initialization/Allocation failed!\n"); goto err; } if (!fdow_start_array(&temp_fdow, DEVICE_MFG_STRING_ARRAY_SZ)) { @@ -278,57 +397,66 @@ int ps_get_m_string(fdo_prot_t *ps) LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write keyEnc\n"); goto err; } - if (!fdow_text_string(&temp_fdow, (char *) device_serial, device_serial_len)) { + if (!fdow_text_string(&temp_fdow, (char *)device_serial, + device_serial_len)) { LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write serialNumber\n"); goto err; } - if (!fdow_text_string(&temp_fdow, (char *) model_number, model_number_len)) { + if (!fdow_text_string(&temp_fdow, (char *)model_number, + model_number_len)) { LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write deviceInfo\n"); goto err; } -#if defined(DEVICE_CSE_ENABLED) - if (!fdow_byte_string(&temp_fdow, csr->bytes, csr->byte_sz)) { LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write CSR\n"); goto err; } + if (!fdow_byte_string(&temp_fdow, mac_addresses->bytes, + mac_addresses->byte_sz)) { + LOG(LOG_ERROR, + "DeviceMfgInfo: Failed to write mac_addresses\n"); + goto err; + } +#if defined(DEVICE_CSE_ENABLED) if (!fdow_byte_string(&temp_fdow, cse_cert->bytes, cse_cert->byte_sz)) { - LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write CSE cert data\n"); + LOG(LOG_ERROR, + "DeviceMfgInfo: Failed to write CSE cert data\n"); goto err; } if (!fdow_byte_string(&temp_fdow, cse_signature->bytes, - cse_signature->byte_sz)) { - LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write CSE signature\n"); + cse_signature->byte_sz)) { + LOG(LOG_ERROR, + "DeviceMfgInfo: Failed to write CSE signature\n"); goto err; } if (!fdow_byte_string(&temp_fdow, cse_maroeprefix->bytes, - cse_maroeprefix->byte_sz)) { - LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write CSE maroeprefix\n"); + cse_maroeprefix->byte_sz)) { + LOG(LOG_ERROR, + "DeviceMfgInfo: Failed to write CSE maroeprefix\n"); goto err; } ret = 0; -#else - if (!fdow_byte_string(&temp_fdow, csr->bytes, csr->byte_sz)) { - LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write CSR\n"); - goto err; - } #endif if (!fdow_end_array(&temp_fdow)) { LOG(LOG_ERROR, "DeviceMfgInfo: Failed to end array\n"); goto err; } - if (!fdow_encoded_length(&temp_fdow, &enc_device_mfginfo) || enc_device_mfginfo == 0) { - LOG(LOG_ERROR, "DeviceMfgInfo: Failed to find encoded length\n"); + if (!fdow_encoded_length(&temp_fdow, &enc_device_mfginfo) || + enc_device_mfginfo == 0) { + LOG(LOG_ERROR, + "DeviceMfgInfo: Failed to find encoded length\n"); goto err; } // now write the CBOR-encoded DeviceMfgInfo as bstr - if (!fdow_byte_string(&ps->fdow, temp_fdow.b.block, enc_device_mfginfo)) { - LOG(LOG_ERROR, "DeviceMfgInfo: Failed to write DeviceMfgInfo as bstr\n"); + if (!fdow_byte_string(&ps->fdow, temp_fdow.b.block, + enc_device_mfginfo)) { + LOG(LOG_ERROR, + "DeviceMfgInfo: Failed to write DeviceMfgInfo as bstr\n"); goto err; } LOG(LOG_DEBUG, "Generated DeviceMfgInfo successfully\n"); @@ -336,6 +464,12 @@ int ps_get_m_string(fdo_prot_t *ps) if (csr) { fdo_byte_array_free(csr); } + + if (mac_addresses) { + fdo_byte_array_free(mac_addresses); + mac_addresses_sz = 0; + } + #if defined(DEVICE_CSE_ENABLED) if (cose_sig_structure) { fdo_byte_array_free(cose_sig_structure); diff --git a/lib/prot/di/msg11.c b/lib/prot/di/msg11.c index ed9d103c..de237cc4 100644 --- a/lib/prot/di/msg11.c +++ b/lib/prot/di/msg11.c @@ -9,7 +9,7 @@ */ #include "load_credentials.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include "fdoprot.h" #include "util.h" @@ -86,18 +86,20 @@ int32_t msg11(fdo_prot_t *ps) } if (!fdor_string_length(&ps->fdor, &ovheader_sz) || ovheader_sz == 0) { - LOG(LOG_ERROR, - "DISetCredentials: Failed to read OVeader as bstr length\n"); + LOG(LOG_ERROR, "DISetCredentials: Failed to read OVeader as " + "bstr length\n"); goto err; } ovheader = fdo_byte_array_alloc(ovheader_sz); if (!ovheader) { - LOG(LOG_ERROR, "DISetCredentials: Failed to alloc for OVHeader as bstr\n"); + LOG(LOG_ERROR, + "DISetCredentials: Failed to alloc for OVHeader as bstr\n"); goto err; } if (!fdor_byte_string(&ps->fdor, ovheader->bytes, ovheader->byte_sz)) { - LOG(LOG_ERROR, "DISetCredentials: Failed to read OVHeader as bstr\n"); + LOG(LOG_ERROR, + "DISetCredentials: Failed to read OVHeader as bstr\n"); goto err; } diff --git a/lib/prot/di/msg13.c b/lib/prot/di/msg13.c old mode 100755 new mode 100644 index ad63a39c..e3f9c80f --- a/lib/prot/di/msg13.c +++ b/lib/prot/di/msg13.c @@ -49,7 +49,8 @@ int32_t msg13(fdo_prot_t *ps) } size_t num_array_entries; - if (!fdor_array_length(&ps->fdor, &num_array_entries) || num_array_entries != 0) { + if (!fdor_array_length(&ps->fdor, &num_array_entries) || + num_array_entries != 0) { goto err; } if (!fdor_start_array(&ps->fdor)) { @@ -77,11 +78,19 @@ int32_t msg13(fdo_prot_t *ps) FDO_STATUS fdo_status; if (TEE_SUCCESS != fdo_heci_commit_file(&fdo_cse_handle, OVH_FILE_ID, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "FDO OVH COMMIT failed!!\n"); return -1; } LOG(LOG_DEBUG, "FDO OVH COMMIT succeeded %u\n", fdo_status); +#elif defined(DEVICE_TPM20_ENABLED) + ps->dev_cred->dc_active = true; + + if (store_tpm_credential(ps->dev_cred) != 0) { + LOG(LOG_ERROR, "TO2.Done: Failed to store new device creds\n"); + goto err; + } #else if (store_credential(ps->dev_cred) != 0) { LOG(LOG_ERROR, "Failed to store updated device credentials\n"); @@ -95,7 +104,8 @@ int32_t msg13(fdo_prot_t *ps) ps->fdor.have_block = false; LOG(LOG_INFO, "(Current) GUID after DI: %s\n", - fdo_guid_to_string(ps->dev_cred->owner_blk->guid, guid_buf, sizeof(guid_buf))); + fdo_guid_to_string(ps->dev_cred->owner_blk->guid, guid_buf, + sizeof(guid_buf))); LOG(LOG_DEBUG, "DIDone completed\n"); ret = 0; diff --git a/lib/prot/to1/msg30.c b/lib/prot/to1/msg30.c index fca385ae..578a3b07 100644 --- a/lib/prot/to1/msg30.c +++ b/lib/prot/to1/msg30.c @@ -40,7 +40,7 @@ int32_t msg30(fdo_prot_t *ps) /* Write GUID received during DI */ if (!fdow_byte_string(&ps->fdow, ps->dev_cred->owner_blk->guid->bytes, - ps->dev_cred->owner_blk->guid->byte_sz)) { + ps->dev_cred->owner_blk->guid->byte_sz)) { LOG(LOG_ERROR, "TO1.HelloRV: Failed to write Guid\n"); return false; } diff --git a/lib/prot/to1/msg31.c b/lib/prot/to1/msg31.c index 4c727b03..b34fbf60 100644 --- a/lib/prot/to1/msg31.c +++ b/lib/prot/to1/msg31.c @@ -46,9 +46,11 @@ int32_t msg31(fdo_prot_t *ps) } ps->nonce_to1proof = fdo_byte_array_alloc(FDO_NONCE_BYTES); - if (!ps->nonce_to1proof || !fdor_byte_string(&ps->fdor, - ps->nonce_to1proof->bytes, ps->nonce_to1proof->byte_sz)) { - LOG(LOG_ERROR, "TO1.HelloRVAck: Failed to read NonceTO1Proof\n"); + if (!ps->nonce_to1proof || + !fdor_byte_string(&ps->fdor, ps->nonce_to1proof->bytes, + ps->nonce_to1proof->byte_sz)) { + LOG(LOG_ERROR, + "TO1.HelloRVAck: Failed to read NonceTO1Proof\n"); goto err; } diff --git a/lib/prot/to1/msg32.c b/lib/prot/to1/msg32.c index afd7e788..3c23c39c 100644 --- a/lib/prot/to1/msg32.c +++ b/lib/prot/to1/msg32.c @@ -10,7 +10,7 @@ #include "util.h" #include "fdoprot.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" /** * msg32() - TO1.ProveToRV, Type 32 @@ -36,8 +36,8 @@ int32_t msg32(fdo_prot_t *ps) LOG(LOG_DEBUG, "TO1.ProveToRV started\n"); - // Allocate EAT object now. Initialize and fill the contents when needed to finally - // CBOR encode. Free once used in this method later. + // Allocate EAT object now. Initialize and fill the contents when needed + // to finally CBOR encode. Free once used in this method later. fdo_eat_t *eat = fdo_eat_alloc(); if (!eat) { LOG(LOG_ERROR, "TO1.ProveToRV: Failed to allocate for EAT\n"); @@ -57,35 +57,41 @@ int32_t msg32(fdo_prot_t *ps) // copy nonce4 and GUID into the struct if (0 != memcpy_s(&payloadbasemap.eatnonce, FDO_NONCE_BYTES, - ps->nonce_to1proof->bytes, ps->nonce_to1proof->byte_sz)) { + ps->nonce_to1proof->bytes, + ps->nonce_to1proof->byte_sz)) { LOG(LOG_ERROR, "TO1.ProveToRV: Failed to copy NonceTO1Proof\n"); goto err; } payloadbasemap.eatueid[0] = 1; if (0 != memcpy_s(&payloadbasemap.eatueid[1], FDO_GUID_BYTES, - ps->dev_cred->owner_blk->guid->bytes, ps->dev_cred->owner_blk->guid->byte_sz)) { - LOG(LOG_ERROR, "TO1.ProveToRV: Failed to copy GUID\n"); - goto err; + ps->dev_cred->owner_blk->guid->bytes, + ps->dev_cred->owner_blk->guid->byte_sz)) { + LOG(LOG_ERROR, "TO1.ProveToRV: Failed to copy GUID\n"); + goto err; } payloadbasemap.eatpayloads = NULL; // Create the payload as CBOR map. Sign the encoded payload. // Then, wrap the encoded payload a a bstr. if (!fdo_eat_write_payloadbasemap(&ps->fdow, &payloadbasemap)) { - LOG(LOG_ERROR, "TO1.ProveToRV: Failed to write EATPayloadBaseMap\n"); + LOG(LOG_ERROR, + "TO1.ProveToRV: Failed to write EATPayloadBaseMap\n"); goto err; } size_t payload_length = 0; - if (!fdow_encoded_length(&ps->fdow, &payload_length) || payload_length == 0) { - LOG(LOG_ERROR, "TO1.ProveToRV: Failed to read EATPayload length\n"); + if (!fdow_encoded_length(&ps->fdow, &payload_length) || + payload_length == 0) { + LOG(LOG_ERROR, + "TO1.ProveToRV: Failed to read EATPayload length\n"); goto err; } ps->fdow.b.block_size = payload_length; // Set the encoded payload into buffer - encoded_payloadbasemap = - fdo_byte_array_alloc_with_byte_array(ps->fdow.b.block, ps->fdow.b.block_size); + encoded_payloadbasemap = fdo_byte_array_alloc_with_byte_array( + ps->fdow.b.block, ps->fdow.b.block_size); if (!encoded_payloadbasemap) { - LOG(LOG_ERROR, "TO1.ProveToRV: Failed to alloc for encoded EATPayload\n"); + LOG(LOG_ERROR, + "TO1.ProveToRV: Failed to alloc for encoded EATPayload\n"); goto err; } eat->eat_payload = encoded_payloadbasemap; @@ -94,21 +100,24 @@ int32_t msg32(fdo_prot_t *ps) fdo_block_reset(&ps->fdow.b); ps->fdow.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "TO1.ProveToRV: Failed to initilize FDOW encoder\n"); + LOG(LOG_ERROR, + "TO1.ProveToRV: Failed to initilize FDOW encoder\n"); goto err; } if (!fdo_eat_write_sigstructure(eat->eat_ph, eat->eat_payload, NULL, - &eat_sig_structure) || !eat_sig_structure) { - LOG(LOG_ERROR, "TO1.ProveToRV: Failed to write COSE Sig_structure\n"); + &eat_sig_structure) || + !eat_sig_structure) { + LOG(LOG_ERROR, + "TO1.ProveToRV: Failed to write COSE Sig_structure\n"); goto err; } fdo_byte_array_t *eat_maroe = NULL; // generate the signature on Sig_structure - if (0 != - fdo_device_sign(eat_sig_structure->bytes, eat_sig_structure->byte_sz, - &eat->eat_signature, &eat_maroe)) { + if (0 != fdo_device_sign(eat_sig_structure->bytes, + eat_sig_structure->byte_sz, + &eat->eat_signature, &eat_maroe)) { LOG(LOG_ERROR, "TO1.ProveToRV: Failed to generate signature\n"); goto err; } @@ -116,7 +125,6 @@ int32_t msg32(fdo_prot_t *ps) eat->eat_uph->eatmaroeprefix = eat_maroe; #endif - /* Start writing the block for msg31 */ fdow_next_block(&ps->fdow, FDO_TO1_TYPE_PROVE_TO_FDO); diff --git a/lib/prot/to1/msg33.c b/lib/prot/to1/msg33.c index 6f756ec3..4846284e 100644 --- a/lib/prot/to1/msg33.c +++ b/lib/prot/to1/msg33.c @@ -26,8 +26,8 @@ * ] * where, * to1dBlobPayload = [ - * [+[RVIP, RVDNS, RVPort, RVProtocol]], // one or more array of inner entries (inner array) - * [hashtype, hash] + * [+[RVIP, RVDNS, RVPort, RVProtocol]], // one or more array of inner + *entries (inner array) [hashtype, hash] * ] * */ @@ -65,24 +65,28 @@ int32_t msg33(fdo_prot_t *ps) goto err; } - // clear the FDOR buffer and push COSE payload into it, essentially reusing the FDOR object. + // clear the FDOR buffer and push COSE payload into it, essentially + // reusing the FDOR object. fdo_block_reset(&ps->fdor.b); ps->fdor.b.block_size = ps->to1d_cose->cose_payload->byte_sz; if (0 != memcpy_s(ps->fdor.b.block, ps->fdor.b.block_size, - ps->to1d_cose->cose_payload->bytes, ps->to1d_cose->cose_payload->byte_sz)) { + ps->to1d_cose->cose_payload->bytes, + ps->to1d_cose->cose_payload->byte_sz)) { LOG(LOG_ERROR, "TO1.RVRedirect: Failed to copy Nonce4\n"); goto err; } - // initialize the parser once the buffer contains COSE payload to be decoded. + // initialize the parser once the buffer contains COSE payload to be + // decoded. if (!fdor_parser_init(&ps->fdor)) { - LOG(LOG_ERROR, "TO1.RVRedirect: Failed to initialize FDOR parser\n"); + LOG(LOG_ERROR, + "TO1.RVRedirect: Failed to initialize FDOR parser\n"); goto err; } size_t num_payloadbasemap_items = 0; if (!fdor_array_length(&ps->fdor, &num_payloadbasemap_items) || - num_payloadbasemap_items != 2) { + num_payloadbasemap_items != 2) { LOG(LOG_ERROR, "TO1.RVRedirect: Failed to read array length\n"); goto err; } diff --git a/lib/prot/to2/msg60.c b/lib/prot/to2/msg60.c index df614b47..123f2d20 100644 --- a/lib/prot/to2/msg60.c +++ b/lib/prot/to2/msg60.c @@ -10,7 +10,7 @@ #include "fdoprot.h" #include "util.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" /** * msg60() - TO2.HelloDevice @@ -49,12 +49,14 @@ int32_t msg60(fdo_prot_t *ps) /* Fill in the maxDeviceMessageSize */ if (!fdow_unsigned_int(&ps->fdow, ps->max_device_message_size)) { - LOG(LOG_ERROR, "TO2.HelloDevice: Failed to write maxDeviceMessageSize\n"); + LOG(LOG_ERROR, + "TO2.HelloDevice: Failed to write maxDeviceMessageSize\n"); return false; } if (ps->max_device_message_size > MAX_NEGO_MSG_SIZE) { - LOG(LOG_ERROR, "TO2.HelloDevice: maxDeviceMessageSize can not be greater than 65535\n"); + LOG(LOG_ERROR, "TO2.HelloDevice: maxDeviceMessageSize can not " + "be greater than 65535\n"); goto err; } @@ -67,24 +69,29 @@ int32_t msg60(fdo_prot_t *ps) /* Fill in the Nonce */ ps->nonce_to2proveov = fdo_byte_array_alloc(FDO_NONCE_BYTES); if (!ps->nonce_to2proveov) { - LOG(LOG_ERROR, "TO2.HelloDevice: Failed to allocate memory for NonceTO2ProveOV\n"); + LOG(LOG_ERROR, "TO2.HelloDevice: Failed to allocate memory for " + "NonceTO2ProveOV\n"); goto err; } fdo_nonce_init_rand(ps->nonce_to2proveov); - if (!fdow_byte_string(&ps->fdow, ps->nonce_to2proveov->bytes, ps->nonce_to2proveov->byte_sz)) { - LOG(LOG_ERROR, "TO2.HelloDevice: Failed to write NonceTO2ProveOV\n"); + if (!fdow_byte_string(&ps->fdow, ps->nonce_to2proveov->bytes, + ps->nonce_to2proveov->byte_sz)) { + LOG(LOG_ERROR, + "TO2.HelloDevice: Failed to write NonceTO2ProveOV\n"); return false; } /* Fill in the key exchange */ if (!fdow_text_string(&ps->fdow, kx->bytes, kx->byte_sz)) { - LOG(LOG_ERROR, "TO2.HelloDevice: Failed to write kexSuiteName\n"); + LOG(LOG_ERROR, + "TO2.HelloDevice: Failed to write kexSuiteName\n"); return false; } /* Fill in the ciphersuite info */ if (!fdow_signed_int(&ps->fdow, cs)) { - LOG(LOG_ERROR, "TO2.HelloDevice: Failed to write cipherSuiteName\n"); + LOG(LOG_ERROR, + "TO2.HelloDevice: Failed to write cipherSuiteName\n"); return false; } @@ -100,14 +107,16 @@ int32_t msg60(fdo_prot_t *ps) } if (!fdow_encoded_length(&ps->fdow, &ps->fdow.b.block_size)) { - LOG(LOG_ERROR, "TO2.HelloDevice: Failed to get encoded length for helloDeviceHash\n"); + LOG(LOG_ERROR, "TO2.HelloDevice: Failed to get encoded length " + "for helloDeviceHash\n"); return false; } if (0 != fdo_crypto_hash(ps->fdow.b.block, ps->fdow.b.block_size, - ps->hello_device_hash->hash->bytes, - ps->hello_device_hash->hash->byte_sz)) { - LOG(LOG_ERROR, "TO2.HelloDevice: Failed to generate helloDeviceHash\n"); + ps->hello_device_hash->hash->bytes, + ps->hello_device_hash->hash->byte_sz)) { + LOG(LOG_ERROR, + "TO2.HelloDevice: Failed to generate helloDeviceHash\n"); return false; } /* Mark to move to next message */ diff --git a/lib/prot/to2/msg61.c b/lib/prot/to2/msg61.c index 5640e08c..f393becf 100644 --- a/lib/prot/to2/msg61.c +++ b/lib/prot/to2/msg61.c @@ -12,18 +12,19 @@ #include "safe_lib.h" #include "fdokeyexchange.h" #include "util.h" -#include "fdoCryptoCommons.h" +#include "fdo_crypto_commons.h" /** * msg61 - TO2.ProveOVHdr - * The owner responds to the device with the OVHeader. The COSESignature.signature - * is signed with owner Private key to start establishing that it is the - * rightful owner of the Ownership Voucher and thus the device. + * The owner responds to the device with the OVHeader. The + * COSESignature.signature is signed with owner Private key to start + * establishing that it is the rightful owner of the Ownership Voucher and thus + * the device. * * TO2.ProveOVHdr = CoseSignature, where * TO2ProveOVHdrUnprotectedHeaders = ( - * CUPHNonce: NonceTO2ProveDv, ;; NonceTO2ProveDv is used below in TO2.ProveDevice and TO2.Done - * CUPHOwnerPubKey: PublicKey ;; Owner key, as hint + * CUPHNonce: NonceTO2ProveDv, ;; NonceTO2ProveDv is used below in + * TO2.ProveDevice and TO2.Done CUPHOwnerPubKey: PublicKey ;; Owner key, as hint * ) * $COSEPayloads /= ( * TO2ProveOVHdrPayload @@ -75,8 +76,8 @@ int32_t msg61(fdo_prot_t *ps) LOG(LOG_DEBUG, "TO2.ProveOVHdr started\n"); - // Allocate for cose object now. Allocate for its members when needed later. - // Free immediately once its of no use. + // Allocate for cose object now. Allocate for its members when needed + // later. Free immediately once its of no use. cose = fdo_alloc(sizeof(fdo_cose_t)); if (!cose) { LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to alloc COSE\n"); @@ -88,97 +89,120 @@ int32_t msg61(fdo_prot_t *ps) goto err; } - // get the Owner public key & NonceTO2ProveDv from the COSE's Unprotected header and save it - ps->owner_public_key = fdo_public_key_clone(cose->cose_uph->cuphowner_public_key); + // get the Owner public key & NonceTO2ProveDv from the COSE's + // Unprotected header and save it + ps->owner_public_key = + fdo_public_key_clone(cose->cose_uph->cuphowner_public_key); ps->nonce_to2provedv = fdo_byte_array_alloc(FDO_NONCE_BYTES); if (!ps->nonce_to2provedv) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to alloc NonceTO2ProveDv\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to alloc NonceTO2ProveDv\n"); goto err; } if (0 != memcpy_s(ps->nonce_to2provedv->bytes, FDO_NONCE_BYTES, - &cose->cose_uph->cuphnonce, sizeof(cose->cose_uph->cuphnonce))) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to copy NonceTO2ProveDv\n"); + &cose->cose_uph->cuphnonce, + sizeof(cose->cose_uph->cuphnonce))) { + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to copy NonceTO2ProveDv\n"); goto err; } - if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, NULL, - &cose_sig_structure) || !cose_sig_structure) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to write COSE Sig_structure\n"); + if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, + NULL, &cose_sig_structure) || + !cose_sig_structure) { + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to write COSE Sig_structure\n"); goto err; } - /* The signature verification over TO2.ProveOVHdr.TO2ProveOVHdrPayload must verify */ + /* The signature verification over TO2.ProveOVHdr.TO2ProveOVHdrPayload + * must verify */ if (!fdo_signature_verification(cose_sig_structure, cose->cose_signature, ps->owner_public_key)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: COSE signature verification failed\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: COSE signature verification failed\n"); goto err; } - LOG(LOG_DEBUG, "TO2.ProveOVHdr: COSE signature verification successful\n"); + LOG(LOG_DEBUG, + "TO2.ProveOVHdr: COSE signature verification successful\n"); fdo_byte_array_free(cose_sig_structure); cose_sig_structure = NULL; // verify the to1d that was received during TO1.RVRedirect, Type 33 // Happens only when TO2 was started without RVBypass flow. if (ps->to1d_cose) { - if (!fdo_cose_write_sigstructure(ps->to1d_cose->cose_ph, ps->to1d_cose->cose_payload, - NULL, &cose_sig_structure) || !cose_sig_structure) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to write COSE Sig_structure\n"); + if (!fdo_cose_write_sigstructure(ps->to1d_cose->cose_ph, + ps->to1d_cose->cose_payload, + NULL, &cose_sig_structure) || + !cose_sig_structure) { + LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to write COSE " + "Sig_structure\n"); goto err; } if (!fdo_signature_verification(cose_sig_structure, - ps->to1d_cose->cose_signature, - ps->owner_public_key)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: COSE signature verification failed\n"); + ps->to1d_cose->cose_signature, + ps->owner_public_key)) { + LOG(LOG_ERROR, "TO2.ProveOVHdr: COSE signature " + "verification failed\n"); goto err; } - LOG(LOG_DEBUG, "TO2.ProveOVHdr: to1d signature verification successful\n"); + LOG(LOG_DEBUG, + "TO2.ProveOVHdr: to1d signature verification successful\n"); } - // clear the FDOR buffer and push COSE payload into it, essentially reusing the FDOR object. + // clear the FDOR buffer and push COSE payload into it, essentially + // reusing the FDOR object. fdo_block_reset(&ps->fdor.b); ps->fdor.b.block_size = cose->cose_payload->byte_sz; if (0 != memcpy_s(ps->fdor.b.block, ps->fdor.b.block_size, - cose->cose_payload->bytes, cose->cose_payload->byte_sz)) { + cose->cose_payload->bytes, + cose->cose_payload->byte_sz)) { LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to copy Nonce4\n"); goto err; } fdo_cose_free(cose); cose = NULL; - // initialize the parser once the buffer contains COSE payload to be decoded. + // initialize the parser once the buffer contains COSE payload to be + // decoded. if (!fdor_parser_init(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to initilize FDOR parser\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to initilize FDOR parser\n"); goto err; } size_t num_payloadbasemap_items = 0; // check if TO2.ProveOVHdrPayload consist of all entries i.e. 8 entries if (!fdor_array_length(&ps->fdor, &num_payloadbasemap_items) || - num_payloadbasemap_items != 8) { + num_payloadbasemap_items != 8) { LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read array length\n"); goto err; } if (!fdor_start_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to start TO2ProveOVHdrPayload array\n"); + LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to start " + "TO2ProveOVHdrPayload array\n"); goto err; } // Read the bin character length if (!fdor_string_length(&ps->fdor, &ovheader_sz) || ovheader_sz == 0) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Unable to decode length of ProveOVHdr!\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Unable to decode length of ProveOVHdr!\n"); goto err; } // bstr-unwrap OVHeader ovheader = fdo_byte_array_alloc(ovheader_sz); if (!ovheader) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to alloc for OVHeader as bstr\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to alloc for OVHeader as bstr\n"); goto err; } if (!fdor_byte_string(&ps->fdor, ovheader->bytes, ovheader->byte_sz)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read OVHeader as bstr\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to read OVHeader as bstr\n"); goto err; } @@ -191,29 +215,35 @@ int32_t msg61(fdo_prot_t *ps) ovheader_pubkey_hash = fdo_pub_key_hash(ps->ovoucher->mfg_pub_key); if (!ovheader_pubkey_hash) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Hash creation of OVHeader.OVPubKey failed\n"); + LOG(LOG_ERROR, "TO2.ProveOVHdr: Hash creation of " + "OVHeader.OVPubKey failed\n"); goto err; } - if (!fdo_compare_hashes(ovheader_pubkey_hash, ps->dev_cred->owner_blk->pkh)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to verify OVHeader.OVPubKey hash\n"); + if (!fdo_compare_hashes(ovheader_pubkey_hash, + ps->dev_cred->owner_blk->pkh)) { + LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to verify " + "OVHeader.OVPubKey hash\n"); goto err; } - LOG(LOG_DEBUG, "TO2.ProveOVHdr: OVHeader.OVPubKey hash verification successful\n"); + LOG(LOG_DEBUG, + "TO2.ProveOVHdr: OVHeader.OVPubKey hash verification successful\n"); /* * Read the number of OVEntries present. */ ps->ovoucher->num_ov_entries = 0; if (!fdor_signed_int(&ps->fdor, &ps->ovoucher->num_ov_entries) || - ps->ovoucher->num_ov_entries == 0) { + ps->ovoucher->num_ov_entries == 0) { LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read NumOVEntries\n"); goto err; } - LOG(LOG_DEBUG, "TO2.ProveOVHdr: Total number of OwnershipVoucher.OVEntries: %d\n", - ps->ovoucher->num_ov_entries); + LOG(LOG_DEBUG, + "TO2.ProveOVHdr: Total number of OwnershipVoucher.OVEntries: %d\n", + ps->ovoucher->num_ov_entries); if (ps->ovoucher->num_ov_entries > MAX_NO_OVENTRIES) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: NumOVEntries can not be greater than 255\n"); + LOG(LOG_ERROR, "TO2.ProveOVHdr: NumOVEntries can not be " + "greater than 255\n"); goto err; } @@ -228,19 +258,21 @@ int32_t msg61(fdo_prot_t *ps) } #if defined(DEVICE_CSE_ENABLED) -/** - * Note: In the case of CSE implementation, it compares the received ovheader - * with the existing ovheader stored during DI. - * If verification succeeds it loads the existing HMAC. - * - */ + /** + * Note: In the case of CSE implementation, it compares the received + * ovheader with the existing ovheader stored during DI. If verification + * succeeds it loads the existing HMAC. + * + */ if (!fdo_ov_hdr_cse_load_hmac(ovheader, &ps->new_ov_hdr_hmac)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to calculate OVHeader HMac\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to calculate OVHeader HMac\n"); goto err; } #else if (!fdo_ov_hdr_hmac(ovheader, &ps->new_ov_hdr_hmac)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to calculate OVHeader HMac\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to calculate OVHeader HMac\n"); goto err; } #endif @@ -257,7 +289,8 @@ int32_t msg61(fdo_prot_t *ps) ps->new_ov_hdr_hmac->hash->bytes, ps->new_ov_hdr_hmac->hash->byte_sz, &result_memcmp); if (ret || result_memcmp != 0) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Invalid HMac received over OVHeader\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Invalid HMac received over OVHeader\n"); ret = -1; goto err; } @@ -269,20 +302,24 @@ int32_t msg61(fdo_prot_t *ps) goto err; } size_t nonce5_length = 0; - if (!fdor_string_length(&ps->fdor, &nonce5_length) || nonce5_length != FDO_NONCE_BYTES) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Invalid/Failed to read NonceTO2ProveOV length\n"); + if (!fdor_string_length(&ps->fdor, &nonce5_length) || + nonce5_length != FDO_NONCE_BYTES) { + LOG(LOG_ERROR, "TO2.ProveOVHdr: Invalid/Failed to read " + "NonceTO2ProveOV length\n"); goto err; } if (!fdor_byte_string(&ps->fdor, ps->nonce_to2proveov_rcv->bytes, - ps->nonce_to2proveov_rcv->byte_sz)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read NonceTO2ProveOV\n"); + ps->nonce_to2proveov_rcv->byte_sz)) { + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to read NonceTO2ProveOV\n"); goto err; } /* The nonces "NonceTO2ProveOV" from Type 60 and 61 must match */ if (!fdo_nonce_equal(ps->nonce_to2proveov_rcv, ps->nonce_to2proveov)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Received NonceTO2ProveOV does not match with" - "existing NonceTO2ProveOV \n"); + LOG(LOG_ERROR, "TO2.ProveOVHdr: Received NonceTO2ProveOV does " + "not match with" + "existing NonceTO2ProveOV \n"); goto err; } @@ -303,16 +340,19 @@ int32_t msg61(fdo_prot_t *ps) */ size_t xA_length = 8; if (!fdor_string_length(&ps->fdor, &xA_length)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read xAKeyExchange length\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to read xAKeyExchange length\n"); goto err; } xA = fdo_byte_array_alloc(xA_length); if (!xA) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to allocate memory for xAKeyExchange\n"); + LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to allocate memory for " + "xAKeyExchange\n"); goto err; } - if(!fdor_byte_string(&ps->fdor, xA->bytes, xA->byte_sz)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read xAKeyExchange\n"); + if (!fdor_byte_string(&ps->fdor, xA->bytes, xA->byte_sz)) { + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to read xAKeyExchange\n"); goto err; } @@ -323,33 +363,39 @@ int32_t msg61(fdo_prot_t *ps) hello_device_hash_rcv = fdo_hash_alloc_empty(); if (!hello_device_hash_rcv) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to alloc for helloDeviceHash\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to alloc for helloDeviceHash\n"); goto err; } if (!fdo_hash_read(&ps->fdor, hello_device_hash_rcv)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read helloDeviceHash\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to read helloDeviceHash\n"); goto err; } if (!fdo_compare_hashes(hello_device_hash_rcv, ps->hello_device_hash)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to verify helloDeviceHash\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to verify helloDeviceHash\n"); goto err; } - // maxOwnerMessageSize is read, but not really used since it may require changing - // previously allocated buffer sizes for protocol messages + // maxOwnerMessageSize is read, but not really used since it may require + // changing previously allocated buffer sizes for protocol messages if (!fdor_unsigned_int(&ps->fdor, &ps->max_owner_message_size)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to read maxOwnerMessageSize\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to read maxOwnerMessageSize\n"); goto err; } if (ps->max_owner_message_size > MAX_NEGO_MSG_SIZE) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: maxOwnerMessageSize can not be greater than 65535\n"); + LOG(LOG_ERROR, "TO2.ProveOVHdr: maxOwnerMessageSize can not be " + "greater than 65535\n"); goto err; } if (!fdor_end_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to end TO2ProveOVHdrPayload array\n"); + LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to end " + "TO2ProveOVHdrPayload array\n"); goto err; } @@ -360,22 +406,27 @@ int32_t msg61(fdo_prot_t *ps) goto err; } if (!fdo_ove_hash_hdr_info_save(ps->ovoucher)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to save OVEHashHdrInfo\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to save OVEHashHdrInfo\n"); goto err; } // reset the FDOW block to prepare for OVEHashPrevEntry fdo_block_reset(&ps->fdow.b); ps->fdow.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to initilize FDOW encoder\n"); + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to initilize FDOW encoder\n"); goto err; } - if (!fdo_ove_hash_prev_entry_save(&ps->fdow, ps->ovoucher, ps->ovoucher->ovoucher_hdr_hash)) { - LOG(LOG_ERROR, "TO2.ProveOVHdr: Failed to save OVEHashPrevEntry\n"); + if (!fdo_ove_hash_prev_entry_save(&ps->fdow, ps->ovoucher, + ps->ovoucher->ovoucher_hdr_hash)) { + LOG(LOG_ERROR, + "TO2.ProveOVHdr: Failed to save OVEHashPrevEntry\n"); goto err; } // To verify the next entry in the ownership voucher - ps->ovoucher->ov_entries->pk = fdo_public_key_clone(ps->ovoucher->mfg_pub_key); + ps->ovoucher->ov_entries->pk = + fdo_public_key_clone(ps->ovoucher->mfg_pub_key); /* * If the TO2.ProveOVHdr.TO2ProveOVHdrPayload.NumOVEntries > 0, diff --git a/lib/prot/to2/msg62.c b/lib/prot/to2/msg62.c index 37a42fb8..7aa2ecf9 100644 --- a/lib/prot/to2/msg62.c +++ b/lib/prot/to2/msg62.c @@ -31,18 +31,21 @@ int32_t msg62(fdo_prot_t *ps) fdow_next_block(&ps->fdow, FDO_TO2_GET_OP_NEXT_ENTRY); if (!fdow_start_array(&ps->fdow, 1)) { - LOG(LOG_ERROR, "TO2.GetOVNextEntry: Failed to read start array\n"); + LOG(LOG_ERROR, + "TO2.GetOVNextEntry: Failed to read start array\n"); return -1; } /* Write OVEntryNum value in the block */ if (!fdow_signed_int(&ps->fdow, ps->ov_entry_num)) { - LOG(LOG_ERROR, "TO2.GetOVNextEntry: Failed to read OPEntryNum\n"); + LOG(LOG_ERROR, + "TO2.GetOVNextEntry: Failed to read OPEntryNum\n"); return -1; } if (!fdow_end_array(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.GetOVNextEntry: Failed to read end array\n"); + LOG(LOG_ERROR, + "TO2.GetOVNextEntry: Failed to read end array\n"); return -1; } /* Move to msg63 */ diff --git a/lib/prot/to2/msg63.c b/lib/prot/to2/msg63.c index 20435315..3ba3e95e 100644 --- a/lib/prot/to2/msg63.c +++ b/lib/prot/to2/msg63.c @@ -12,7 +12,7 @@ #include "fdotypes.h" #include "safe_lib.h" #include "util.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" /** * msg63() - TO2.OVNextEntry @@ -79,7 +79,8 @@ int32_t msg63(fdo_prot_t *ps) goto err; } - // OVEntryNum value must match with the requested Ownership Voucher index + // OVEntryNum value must match with the requested Ownership Voucher + // index if (entry_num != ps->ov_entry_num) { LOG(LOG_ERROR, "TO2.OVNextEntry: Invalid OVEntryNum, " @@ -88,8 +89,8 @@ int32_t msg63(fdo_prot_t *ps) goto err; } - // Allocate for cose object now. Allocate for its members when needed later. - // Free immediately once its of no use. + // Allocate for cose object now. Allocate for its members when needed + // later. Free immediately once its of no use. cose = fdo_alloc(sizeof(fdo_cose_t)); if (!cose) { LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to alloc COSE\n"); @@ -106,41 +107,47 @@ int32_t msg63(fdo_prot_t *ps) goto err; } - if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, NULL, - &cose_sig_structure) || !cose_sig_structure) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to write COSE Sig_structure\n"); + if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, + NULL, &cose_sig_structure) || + !cose_sig_structure) { + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to write COSE Sig_structure\n"); goto err; } // verify the received COSE signature if (!fdo_signature_verification(cose_sig_structure, cose->cose_signature, ps->ovoucher->ov_entries->pk)) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to verify OVEntry signature\n"); + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to verify OVEntry signature\n"); goto err; } - LOG(LOG_DEBUG, "TO2.OVNextEntry: OVEntry Signature verification successful\n"); + LOG(LOG_DEBUG, + "TO2.OVNextEntry: OVEntry Signature verification successful\n"); - // Generate COSE as CBOR bytes again that is used to calculate OVEHashPrevEntry. + // Generate COSE as CBOR bytes again that is used to calculate + // OVEHashPrevEntry. if (!fdo_cose_write(&ps->fdow, cose)) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to write COSE for OVEHashPrevEntry\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to write COSE for " + "OVEHashPrevEntry\n"); goto err; } // Get encoded COSE and copy if (!fdow_encoded_length(&ps->fdow, &ps->fdow.b.block_size)) { - LOG(LOG_ERROR, - "TO2.OVNextEntry: Failed to get encoded COSE length for OVEHashPrevEntry\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to get encoded COSE " + "length for OVEHashPrevEntry\n"); goto err; } cose_encoded = fdo_byte_array_alloc(ps->fdow.b.block_size); if (!cose_encoded) { - LOG(LOG_ERROR, - "TO2.OVNextEntry: Failed to alloc encoded COSE for OVEHashPrevEntry\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to alloc encoded COSE " + "for OVEHashPrevEntry\n"); goto err; } if (0 != memcpy_s(cose_encoded->bytes, cose_encoded->byte_sz, - ps->fdow.b.block, ps->fdow.b.block_size)) { - LOG(LOG_ERROR, - "TO2.OVNextEntry: Failed to copy encoded COSE for OVEHashPrevEntry\n"); + ps->fdow.b.block, ps->fdow.b.block_size)) { + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to copy encoded COSE " + "for OVEHashPrevEntry\n"); goto err; } @@ -149,9 +156,10 @@ int32_t msg63(fdo_prot_t *ps) fdo_block_reset(&ps->fdor.b); ps->fdor.b.block_size = cose->cose_payload->byte_sz; if (0 != memcpy_s(ps->fdor.b.block, ps->fdor.b.block_size, - cose->cose_payload->bytes, cose->cose_payload->byte_sz)) { - LOG(LOG_ERROR, - "TO2.OVNextEntry: Failed to copy encoded COSEPayload for OVEHashPrevEntry\n"); + cose->cose_payload->bytes, + cose->cose_payload->byte_sz)) { + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to copy encoded " + "COSEPayload for OVEHashPrevEntry\n"); goto err; } @@ -159,35 +167,41 @@ int32_t msg63(fdo_prot_t *ps) fdo_cose_free(cose); cose = NULL; - // initialize the parser once the buffer contains COSE payload to be decoded. + // initialize the parser once the buffer contains COSE payload to be + // decoded. if (!fdor_parser_init(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to initilize FDOR parser\n"); + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to initilize FDOR parser\n"); goto err; } // start parsing OVEntryPayload size_t num_payloadbasemap_items = 0; if (!fdor_array_length(&ps->fdor, &num_payloadbasemap_items) || - num_payloadbasemap_items != 4) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read array length\n"); + num_payloadbasemap_items != 4) { + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to read array length\n"); goto err; } if (!fdor_start_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to start OVEntryPayload array\n"); + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to start OVEntryPayload array\n"); goto err; } // Read OVEntryPayload.OVEHashPrevEntry temp_hash_hp = fdo_hash_alloc_empty(); if (!temp_hash_hp || fdo_hash_read(&ps->fdor, temp_hash_hp) <= 0) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read OVEntryPayload.OVEHashPrevEntry\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read " + "OVEntryPayload.OVEHashPrevEntry\n"); fdo_hash_free(temp_hash_hp); goto err; } if (temp_hash_hp->hash_type != FDO_CRYPTO_HASH_TYPE_USED) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Invalid Hash Type at OVEntryPayload.OVEHashPrevEntry\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Invalid Hash Type at " + "OVEntryPayload.OVEHashPrevEntry\n"); fdo_hash_free(temp_hash_hp); goto err; } @@ -195,37 +209,44 @@ int32_t msg63(fdo_prot_t *ps) // Read OVEntryPayload.OVEHashHdrInfo temp_hash_hc = fdo_hash_alloc_empty(); if (!temp_hash_hc || fdo_hash_read(&ps->fdor, temp_hash_hc) <= 0) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read OVEntryPayload.OVEHashHdrInfo\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read " + "OVEntryPayload.OVEHashHdrInfo\n"); fdo_hash_free(temp_hash_hc); goto err; } if (temp_hash_hc->hash_type != FDO_CRYPTO_HASH_TYPE_USED) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Invalid Hash Type at OVEntryPayload.OVEHashHdrInfo\n"); - fdo_hash_free(temp_hash_hp); + LOG(LOG_ERROR, "TO2.OVNextEntry: Invalid Hash Type at " + "OVEntryPayload.OVEHashHdrInfo\n"); + fdo_hash_free(temp_hash_hc); goto err; } // Read OVEntryPayload.OVEExtra if (fdor_is_value_null(&ps->fdor)) { if (!fdor_next(&ps->fdor)) { - LOG(LOG_ERROR, - "TO2.OVNextEntry: Failed to read OVNextEntry as null\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read " + "OVNextEntry as null\n"); goto err; } } else { // Read the bin character length - if (!fdor_string_length(&ps->fdor, &ove_extra_len) || ove_extra_len == 0) { - LOG(LOG_DEBUG, "TO2.OVNextEntry: Unable to decode length of OVEExtra!\n"); + if (!fdor_string_length(&ps->fdor, &ove_extra_len) || + ove_extra_len == 0) { + LOG(LOG_DEBUG, "TO2.OVNextEntry: Unable to decode " + "length of OVEExtra!\n"); goto err; } temp_ove_extra = fdo_byte_array_alloc(ove_extra_len); if (!temp_ove_extra) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to alloc for OVEExtra as bstr\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to alloc for " + "OVEExtra as bstr\n"); goto err; } - if (!fdor_byte_string(&ps->fdor, temp_ove_extra->bytes, temp_ove_extra->byte_sz)) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read OVEExtra as bstr\n"); + if (!fdor_byte_string(&ps->fdor, temp_ove_extra->bytes, + temp_ove_extra->byte_sz)) { + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read " + "OVEExtra as bstr\n"); goto err; } } @@ -233,12 +254,14 @@ int32_t msg63(fdo_prot_t *ps) // Read OVEntryPayload.OVEPubKey temp_pk = fdo_public_key_read(&ps->fdor); if (!temp_pk) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read OVEntryPayload.OVEPubKey\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to read " + "OVEntryPayload.OVEPubKey\n"); goto err; } if (!fdor_end_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to end OVEntryPayload array\n"); + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to end OVEntryPayload array\n"); goto err; } @@ -254,26 +277,28 @@ int32_t msg63(fdo_prot_t *ps) temp_entry->ove_extra = temp_ove_extra; temp_entry->pk = temp_pk; - // Compare OVEHashPrevEntry (msg61 data) with the OVEHashPrevEntry from this message + // Compare OVEHashPrevEntry (msg61 data) with the OVEHashPrevEntry from + // this message if (memcmp_s(ps->ovoucher->ov_entries->hp_hash->hash->bytes, ps->ovoucher->ov_entries->hp_hash->hash->byte_sz, temp_entry->hp_hash->hash->bytes, - temp_entry->hp_hash->hash->byte_sz, - &result_memcmp) || + temp_entry->hp_hash->hash->byte_sz, &result_memcmp) || result_memcmp) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to match OVEHashPrevEntry %d\n", + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to match OVEHashPrevEntry %d\n", ps->ov_entry_num); goto err; } - // Compare OVEHashHdrInfo (msg61 data) with the OVEHashHdrInfo from this message + // Compare OVEHashHdrInfo (msg61 data) with the OVEHashHdrInfo from this + // message if (memcmp_s(ps->ovoucher->ov_entries->hc_hash->hash->bytes, ps->ovoucher->ov_entries->hc_hash->hash->byte_sz, temp_entry->hc_hash->hash->bytes, - temp_entry->hc_hash->hash->byte_sz, - &result_memcmp) || + temp_entry->hc_hash->hash->byte_sz, &result_memcmp) || result_memcmp) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to match OVEHashHdrInfo %d\n", + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to match OVEHashHdrInfo %d\n", ps->ov_entry_num); goto err; } @@ -282,7 +307,8 @@ int32_t msg63(fdo_prot_t *ps) current_hp_hash = fdo_hash_alloc(FDO_CRYPTO_HASH_TYPE_USED, FDO_SHA_DIGEST_SIZE_USED); if (!current_hp_hash) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to alloc current OVEntry hash!\n"); + LOG(LOG_ERROR, + "TO2.OVNextEntry: Failed to alloc current OVEntry hash!\n"); goto err; } @@ -290,7 +316,8 @@ int32_t msg63(fdo_prot_t *ps) current_hp_hash->hash->bytes, current_hp_hash->hash->byte_sz)) { fdo_hash_free(current_hp_hash); - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to generate current OVEntry hash!\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to generate current " + "OVEntry hash!\n"); goto err; } // free the previous hash and push the new one. @@ -301,7 +328,8 @@ int32_t msg63(fdo_prot_t *ps) fdo_public_key_free(ps->ovoucher->ov_entries->pk); ps->ovoucher->ov_entries->pk = temp_entry->pk; - LOG(LOG_DEBUG, "TO2.OVNextEntry: Verified OVEntry: %d\n", ps->ov_entry_num); + LOG(LOG_DEBUG, "TO2.OVNextEntry: Verified OVEntry: %d\n", + ps->ov_entry_num); /* * if (TO2.ProveOVHdr.NumOVEntries - 1 == OVEntryNum) @@ -316,7 +344,8 @@ int32_t msg63(fdo_prot_t *ps) fdo_block_reset(&ps->fdow.b); ps->fdor.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to initialize " + "FDOW encoder\n"); goto err; } } else { @@ -327,8 +356,8 @@ int32_t msg63(fdo_prot_t *ps) if (!fdo_compare_public_keys(ps->owner_public_key, temp_entry->pk)) { - LOG(LOG_ERROR, - "TO2.OVNextEntry: Failed to match Owner's pk to OVHdr pk!\n"); + LOG(LOG_ERROR, "TO2.OVNextEntry: Failed to match " + "Owner's pk to OVHdr pk!\n"); goto err; } ps->state = FDO_STATE_TO2_SND_PROVE_DEVICE; diff --git a/lib/prot/to2/msg64.c b/lib/prot/to2/msg64.c index 2efc4c01..ab2b36d3 100644 --- a/lib/prot/to2/msg64.c +++ b/lib/prot/to2/msg64.c @@ -11,7 +11,7 @@ #include "fdoprot.h" #include "fdokeyexchange.h" #include "util.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" /** * msg64() - TO2.ProveDevice @@ -24,7 +24,8 @@ * xBKeyExchange * ] * $EATUnprotectedHeaders /= ( - * EUPHNonce: NonceTO2SetupDv ;; NonceTO2SetupDv is used in TO2.SetupDevice and TO2.Done2 + * EUPHNonce: NonceTO2SetupDv ;; NonceTO2SetupDv is used in TO2.SetupDevice + * and TO2.Done2 * ) * $EATPayloads /= ( * TO2ProveDevicePayload @@ -45,8 +46,8 @@ int32_t msg64(fdo_prot_t *ps) LOG(LOG_DEBUG, "TO2.ProveDevice started\n"); - // Allocate EAT object now. Initialize and fill the contents when needed to finally - // CBOR encode. Free once used in this method later. + // Allocate EAT object now. Initialize and fill the contents when needed + // to finally CBOR encode. Free once used in this method later. fdo_eat_t *eat = fdo_eat_alloc(); if (!eat) { LOG(LOG_ERROR, "TO2.ProveDevice: Failed to allocate for EAT\n"); @@ -66,55 +67,66 @@ int32_t msg64(fdo_prot_t *ps) // copy NonceTO2ProveDv and GUID into the struct if (0 != memcpy_s(&payloadbasemap.eatnonce, FDO_NONCE_BYTES, - ps->nonce_to2provedv->bytes, ps->nonce_to2provedv->byte_sz)) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to copy NonceTO2ProveDv\n"); + ps->nonce_to2provedv->bytes, + ps->nonce_to2provedv->byte_sz)) { + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to copy NonceTO2ProveDv\n"); goto err; } payloadbasemap.eatueid[0] = 1; if (0 != memcpy_s(&payloadbasemap.eatueid[1], FDO_GUID_BYTES, - ps->dev_cred->owner_blk->guid->bytes, ps->dev_cred->owner_blk->guid->byte_sz)) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to copy GUID\n"); - goto err; + ps->dev_cred->owner_blk->guid->bytes, + ps->dev_cred->owner_blk->guid->byte_sz)) { + LOG(LOG_ERROR, "TO2.ProveDevice: Failed to copy GUID\n"); + goto err; } /* Get the second part of Key Exchange */ payloadbasemap.eatpayloads = NULL; ret = fdo_get_kex_paramB(&payloadbasemap.eatpayloads); if (0 != ret || !payloadbasemap.eatpayloads) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to generate xBKeyExchange\n"); + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to generate xBKeyExchange\n"); goto err; } ret = -1; // reset the given FDOW for the next encoding - // This is done out of cycle here because FDOW object was used in Type 63 + // This is done out of cycle here because FDOW object was used in Type + // 63 fdo_block_reset(&ps->fdow.b); ps->fdow.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, + "OVEHashPrevEntry: Failed to initialize FDOW encoder\n"); goto err; } // Create the payload as CBOR map. Sign the encoded payload. // Then, wrap the encoded payload as a bstr later. if (!fdo_eat_write_payloadbasemap(&ps->fdow, &payloadbasemap)) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to write EATPayloadBaseMap\n"); + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to write EATPayloadBaseMap\n"); goto err; } size_t payload_length = 0; - if (!fdow_encoded_length(&ps->fdow, &payload_length) || payload_length == 0) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to read EATPayload length\n"); + if (!fdow_encoded_length(&ps->fdow, &payload_length) || + payload_length == 0) { + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to read EATPayload length\n"); goto err; } ps->fdow.b.block_size = payload_length; - LOG(LOG_DEBUG, "TO2.ProveDevice: EATPayloadBaseMap created successfuly\n"); + LOG(LOG_DEBUG, + "TO2.ProveDevice: EATPayloadBaseMap created successfuly\n"); // Set the encoded payload into buffer - encoded_payloadbasemap = - fdo_byte_array_alloc_with_byte_array(ps->fdow.b.block, ps->fdow.b.block_size); + encoded_payloadbasemap = fdo_byte_array_alloc_with_byte_array( + ps->fdow.b.block, ps->fdow.b.block_size); if (!encoded_payloadbasemap) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to copy encoded EATPayload\n"); + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to copy encoded EATPayload\n"); goto err; } eat->eat_payload = encoded_payloadbasemap; @@ -123,22 +135,26 @@ int32_t msg64(fdo_prot_t *ps) fdo_block_reset(&ps->fdow.b); ps->fdow.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to initilize FDOW encoder\n"); + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to initilize FDOW encoder\n"); goto err; } if (!fdo_eat_write_sigstructure(eat->eat_ph, eat->eat_payload, NULL, - &eat_sig_structure) || !eat_sig_structure) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to write COSE Sig_structure\n"); + &eat_sig_structure) || + !eat_sig_structure) { + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to write COSE Sig_structure\n"); goto err; } // generate the signature on encoded Sig_structure fdo_byte_array_t *eat_maroe = NULL; - if (0 != - fdo_device_sign(eat_sig_structure->bytes, eat_sig_structure->byte_sz, - &eat->eat_signature, &eat_maroe)) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to generate signature\n"); + if (0 != fdo_device_sign(eat_sig_structure->bytes, + eat_sig_structure->byte_sz, + &eat->eat_signature, &eat_maroe)) { + LOG(LOG_ERROR, + "TO2.ProveDevice: Failed to generate signature\n"); goto err; } #if defined(DEVICE_CSE_ENABLED) @@ -155,9 +171,10 @@ int32_t msg64(fdo_prot_t *ps) // copy NonceTO2SetupDv into the struct eat->eat_uph->euphnonce = fdo_byte_array_alloc_with_byte_array( - ps->nonce_to2setupdv->bytes, ps->nonce_to2setupdv->byte_sz); + ps->nonce_to2setupdv->bytes, ps->nonce_to2setupdv->byte_sz); if (!eat->eat_uph->euphnonce) { - LOG(LOG_ERROR, "TO2.ProveDevice: Failed to copy NonceTO2SetupDv into EUPHNonce\n"); + LOG(LOG_ERROR, "TO2.ProveDevice: Failed to copy " + "NonceTO2SetupDv into EUPHNonce\n"); goto err; } diff --git a/lib/prot/to2/msg65.c b/lib/prot/to2/msg65.c index d3a93a01..60adf1cc 100644 --- a/lib/prot/to2/msg65.c +++ b/lib/prot/to2/msg65.c @@ -17,7 +17,7 @@ * msg65() - TO2.SetupDevice * So, the owner has verified that it is talking to right device and * is receiving the next Owner's credentials. - * + * * TO2.SetupDevice = CoseSignature * TO2SetupDevicePayload = [ * RendezvousInfo, ;; RendezvousInfo replacement @@ -57,7 +57,8 @@ int32_t msg65(fdo_prot_t *ps) /* If the packet is encrypted, decrypt it */ pkt = fdo_encrypted_packet_read(&ps->fdor); if (pkt == NULL) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to parse encrypted packet\n"); + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to parse encrypted packet\n"); goto err; } @@ -66,8 +67,8 @@ int32_t msg65(fdo_prot_t *ps) goto err; } - // Allocate for cose object now. Allocate for its members when needed later. - // Free immediately once its of no use. + // Allocate for cose object now. Allocate for its members when needed + // later. Free immediately once its of no use. cose = fdo_alloc(sizeof(fdo_cose_t)); if (!cose) { LOG(LOG_ERROR, "TO2.SetupDevice: Failed to alloc COSE\n"); @@ -79,18 +80,23 @@ int32_t msg65(fdo_prot_t *ps) goto err; } - // clear the FDOR buffer and push COSE payload into it, essentially reusing the FDOR object. + // clear the FDOR buffer and push COSE payload into it, essentially + // reusing the FDOR object. fdo_block_reset(&ps->fdor.b); ps->fdor.b.block_size = cose->cose_payload->byte_sz; if (0 != memcpy_s(ps->fdor.b.block, ps->fdor.b.block_size, - cose->cose_payload->bytes, cose->cose_payload->byte_sz)) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to copy COSE payload\n"); + cose->cose_payload->bytes, + cose->cose_payload->byte_sz)) { + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to copy COSE payload\n"); goto err; } - // initialize the parser once the buffer contains COSE payload to be decoded. + // initialize the parser once the buffer contains COSE payload to be + // decoded. if (!fdor_parser_init(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to initilize FDOR parser\n"); + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to initilize FDOR parser\n"); goto err; } @@ -101,67 +107,78 @@ int32_t msg65(fdo_prot_t *ps) /* Create the destination of this final data */ ps->osc = fdo_owner_supplied_credentials_alloc(); if (ps->osc == NULL) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to alloc for new set of credentials\n"); + LOG(LOG_ERROR, "TO2.SetupDevice: Failed to alloc for new set " + "of credentials\n"); goto err; } - // update the replacement RendezvousInfo + // update the replacement RendezvousInfo ps->osc->rvlst = fdo_rendezvous_list_alloc(); if (!ps->osc->rvlst) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to alloc for replacement RendezvousInfo\n"); + LOG(LOG_ERROR, "TO2.SetupDevice: Failed to alloc for " + "replacement RendezvousInfo\n"); goto err; } if (!fdo_rendezvous_list_read(&ps->fdor, ps->osc->rvlst)) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read replacement RendezvousInfo\n"); + LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read replacement " + "RendezvousInfo\n"); goto err; } // update the replacement Guid size_t guid_length = 0; if (!fdor_string_length(&ps->fdor, &guid_length) || - guid_length != FDO_GUID_BYTES) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read replacement GUID length\n"); + guid_length != FDO_GUID_BYTES) { + LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read replacement " + "GUID length\n"); goto err; } ps->osc->guid = fdo_byte_array_alloc(guid_length); if (!ps->osc->guid) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to alloc for replacement GUID\n"); + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to alloc for replacement GUID\n"); goto err; } - if (!fdor_byte_string(&ps->fdor, ps->osc->guid->bytes, ps->osc->guid->byte_sz)) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read replacement GUID\n"); + if (!fdor_byte_string(&ps->fdor, ps->osc->guid->bytes, + ps->osc->guid->byte_sz)) { + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to read replacement GUID\n"); goto err; } size_t nonce7_length = 0; if (!fdor_string_length(&ps->fdor, &nonce7_length) || - nonce7_length != FDO_NONCE_BYTES) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read NonceTO2SetupDv length\n"); + nonce7_length != FDO_NONCE_BYTES) { + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to read NonceTO2SetupDv length\n"); goto err; } ps->nonce_to2setupdv_rcv = fdo_byte_array_alloc(FDO_NONCE_BYTES); if (!ps->nonce_to2setupdv_rcv) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to alloc NonceTO2SetupDv\n"); + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to alloc NonceTO2SetupDv\n"); goto err; } - if (!fdor_byte_string(&ps->fdor, ps->nonce_to2setupdv_rcv->bytes, FDO_NONCE_BYTES)) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read NonceTO2SetupDv\n"); + if (!fdor_byte_string(&ps->fdor, ps->nonce_to2setupdv_rcv->bytes, + FDO_NONCE_BYTES)) { + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to read NonceTO2SetupDv\n"); goto err; } if (!fdo_nonce_equal(ps->nonce_to2setupdv_rcv, ps->nonce_to2setupdv)) { - LOG(LOG_ERROR, - "TO2.SetupDevice: Received NonceTO2SetupDv does not match with existing NonceTO2SetupDv\n"); + LOG(LOG_ERROR, "TO2.SetupDevice: Received NonceTO2SetupDv does " + "not match with existing NonceTO2SetupDv\n"); goto err; } // update the replacement Owner key (Owner2Key) ps->osc->pubkey = fdo_public_key_read(&ps->fdor); if (!ps->osc->pubkey) { - LOG(LOG_ERROR, - "TO2.SetupDevice: Failed to read replacement Owner key (Owner2Key)\n"); + LOG(LOG_ERROR, "TO2.SetupDevice: Failed to read replacement " + "Owner key (Owner2Key)\n"); goto err; } @@ -170,20 +187,23 @@ int32_t msg65(fdo_prot_t *ps) goto err; } - if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, NULL, - &cose_sig_structure) || !cose_sig_structure) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to write COSE Sig_structure\n"); + if (!fdo_cose_write_sigstructure(cose->cose_ph, cose->cose_payload, + NULL, &cose_sig_structure) || + !cose_sig_structure) { + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to write COSE Sig_structure\n"); goto err; } // verify the received COSE signature - if (!fdo_signature_verification(cose_sig_structure, - cose->cose_signature, - ps->osc->pubkey)) { - LOG(LOG_ERROR, "TO2.SetupDevice: Failed to verify OVEntry signature\n"); + if (!fdo_signature_verification( + cose_sig_structure, cose->cose_signature, ps->osc->pubkey)) { + LOG(LOG_ERROR, + "TO2.SetupDevice: Failed to verify OVEntry signature\n"); goto err; } - LOG(LOG_DEBUG, "TO2.SetupDevice: OVEntry Signature verification successful\n"); + LOG(LOG_DEBUG, + "TO2.SetupDevice: OVEntry Signature verification successful\n"); ps->state = FDO_STATE_TO2_SND_NEXT_DEVICE_SERVICE_INFO; LOG(LOG_DEBUG, "TO2.SetupDevice completed successfully\n"); diff --git a/lib/prot/to2/msg66.c b/lib/prot/to2/msg66.c index d3ea02a3..262d57f5 100644 --- a/lib/prot/to2/msg66.c +++ b/lib/prot/to2/msg66.c @@ -11,7 +11,7 @@ #include "fdoprot.h" #include "fdokeyexchange.h" #include "util.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" /** * msg66() - TO2.DeviceServiceInfoReady @@ -20,7 +20,8 @@ * * TO2.DeviceServiceInfoReady = [ * ReplacementHMac, ;; Replacement for DI.SetHMac.HMac or equivalent - * maxOwnerServiceInfoSz ;; maximum size service info that Device can receive + * maxOwnerServiceInfoSz ;; maximum size service info that Device can + * receive * ] */ int32_t msg66(fdo_prot_t *ps) @@ -39,59 +40,74 @@ int32_t msg66(fdo_prot_t *ps) fdow_next_block(&ps->fdow, FDO_TO2_NEXT_DEVICE_SERVICE_INFO); if (!fdow_start_array(&ps->fdow, 2)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to start array\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfoReady: Failed to start array\n"); goto err; } /* Check if REUSE is ON */ if (fdo_compare_public_keys(ps->owner_public_key, ps->osc->pubkey) && - fdo_compare_byte_arrays(ps->dev_cred->owner_blk->guid, ps->osc->guid) && - fdo_compare_rv_lists(ps->dev_cred->owner_blk->rvlst, ps->osc->rvlst)) { + fdo_compare_byte_arrays(ps->dev_cred->owner_blk->guid, + ps->osc->guid) && + fdo_compare_rv_lists(ps->dev_cred->owner_blk->rvlst, + ps->osc->rvlst)) { LOG(LOG_DEBUG, "\n***** REUSE feature enabled *****\n"); ps->reuse_enabled = true; } if (ps->reuse_enabled && reuse_supported) { - LOG(LOG_DEBUG, "TO2.DeviceServiceInfoReady: *****Reuse triggered.*****\n"); + LOG(LOG_DEBUG, + "TO2.DeviceServiceInfoReady: *****Reuse triggered.*****\n"); // write CBOR NULL if (!fdow_null(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to write ReplacementHMac\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to " + "write ReplacementHMac\n"); goto err; } } else { /* Resale Case or Reuse not supported case*/ if (ps->reuse_enabled) { - LOG(LOG_DEBUG, - "TO2.DeviceServiceInfoReady: *****Reuse triggered but not supported.*****\n"); + LOG(LOG_DEBUG, "TO2.DeviceServiceInfoReady: *****Reuse " + "triggered but not supported.*****\n"); // throw error now as per FDO sec goto err; } if (resale_supported) { - LOG(LOG_DEBUG, "TO2.DeviceServiceInfoReady: *****Resale triggered.*****\n"); + LOG(LOG_DEBUG, "TO2.DeviceServiceInfoReady: " + "*****Resale triggered.*****\n"); /* Generate new HMAC secret for OV header validation */ if (0 != fdo_generate_ov_replacement_hmac_key()) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to refresh OV HMAC Key\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfoReady: Failed to " + "refresh OV HMAC Key\n"); goto err; } hmac = fdo_new_ov_hdr_sign(ps->dev_cred, ps->osc, ps->ovoucher->hdc); if (!hmac) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to generate ReplacementHMac\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfoReady: Failed to " + "generate ReplacementHMac\n"); goto err; } if (!fdo_hash_write(&ps->fdow, hmac)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to write ReplacementHMac\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfoReady: Failed to " + "write ReplacementHMac\n"); goto err; } } else { LOG(LOG_DEBUG, - "TO2.DeviceServiceInfoReady: *****Resale triggered but not supported.*****\n"); + "TO2.DeviceServiceInfoReady: *****Resale triggered " + "but not supported.*****\n"); // write CBOR NULL if (!fdow_null(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to write ReplacementHMac\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfoReady: Failed to " + "write ReplacementHMac\n"); goto err; } goto err; @@ -99,26 +115,33 @@ int32_t msg66(fdo_prot_t *ps) } if (!fdow_unsigned_int(&ps->fdow, ps->maxOwnerServiceInfoSz)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to write maxOwnerServiceInfoSz\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to write " + "maxOwnerServiceInfoSz\n"); goto err; } if (ps->maxOwnerServiceInfoSz > MAX_NEGO_MSG_SIZE) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: maxOwnerServiceInfoSz can not be greater than 65535\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfoReady: maxOwnerServiceInfoSz can not " + "be greater than 65535\n"); goto err; } - LOG(LOG_DEBUG, "TO2.DeviceServiceInfoReady: Sent maxOwnerServiceInfoSz = %"PRIu64"\n", - ps->maxOwnerServiceInfoSz); + LOG(LOG_DEBUG, + "TO2.DeviceServiceInfoReady: Sent maxOwnerServiceInfoSz = %" PRIu64 + "\n", + ps->maxOwnerServiceInfoSz); if (!fdow_end_array(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to end array\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfoReady: Failed to end array\n"); goto err; } /* Encrypt the packet */ - if (!fdo_encrypted_packet_windup( - &ps->fdow, FDO_TO2_NEXT_DEVICE_SERVICE_INFO)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to create Encrypted Message\n"); + if (!fdo_encrypted_packet_windup(&ps->fdow, + FDO_TO2_NEXT_DEVICE_SERVICE_INFO)) { + LOG(LOG_ERROR, "TO2.DeviceServiceInfoReady: Failed to create " + "Encrypted Message\n"); goto err; } diff --git a/lib/prot/to2/msg67.c b/lib/prot/to2/msg67.c index e50b350a..3509c7ff 100644 --- a/lib/prot/to2/msg67.c +++ b/lib/prot/to2/msg67.c @@ -11,13 +11,14 @@ #include "fdoprot.h" #include "fdokeyexchange.h" #include "util.h" -#include "fdoCrypto.h" +#include "fdo_crypto.h" /** * msg67() - TO2.OwnerServiceInfoReady * * TO2.OwnerServiceInfoReady = [ - * maxDeviceServiceInfoSz ;; maximum size service info that Owner can receive, uint/NULL + * maxDeviceServiceInfoSz ;; maximum size service info that Owner can + * receive, uint/NULL * ] */ int32_t msg67(fdo_prot_t *ps) @@ -45,69 +46,82 @@ int32_t msg67(fdo_prot_t *ps) pkt = fdo_encrypted_packet_read(&ps->fdor); if (pkt == NULL) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfoReady: Failed to parse encrypted packet\n"); + LOG(LOG_ERROR, "TO2.OwnerServiceInfoReady: Failed to parse " + "encrypted packet\n"); goto err; } if (!fdo_encrypted_packet_unwind(&ps->fdor, pkt)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfoReady: Failed to decrypt packet!\n"); + LOG(LOG_ERROR, + "TO2.OwnerServiceInfoReady: Failed to decrypt packet!\n"); goto err; } if (!fdor_start_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfoReady: Failed to start array\n"); + LOG(LOG_ERROR, + "TO2.OwnerServiceInfoReady: Failed to start array\n"); goto err; } - // maxDeviceServiceInfoSz = CBOR NULL implies that MIN_SERVICEINFO_SZ should be accepted - // maxDeviceServiceInfoSz = Unsigned Integer implies that the given value should be processed + // maxDeviceServiceInfoSz = CBOR NULL implies that MIN_SERVICEINFO_SZ + // should be accepted maxDeviceServiceInfoSz = Unsigned Integer implies + // that the given value should be processed if (fdor_is_value_signed_int(&ps->fdor)) { - if (!fdor_unsigned_int(&ps->fdor, &rec_maxDeviceServiceInfoSz)) { + if (!fdor_unsigned_int(&ps->fdor, + &rec_maxDeviceServiceInfoSz)) { LOG(LOG_ERROR, - "TO2.OwnerServiceInfoReady: Failed to read maxDeviceServiceInfoSz as number\n"); + "TO2.OwnerServiceInfoReady: Failed to read " + "maxDeviceServiceInfoSz as number\n"); goto err; } } else if (fdor_is_value_null(&ps->fdor)) { if (!fdor_next(&ps->fdor)) { - LOG(LOG_ERROR, - "TO2.OwnerServiceInfoReady: Failed to read maxDeviceServiceInfoSz as null\n"); + LOG(LOG_ERROR, "TO2.OwnerServiceInfoReady: Failed to " + "read maxDeviceServiceInfoSz as null\n"); goto err; } } else { // Throw an error if not int/NULL. - LOG(LOG_ERROR, - "TO2.OwnerServiceInfoReady: Invalid value type for maxDeviceServiceInfoSz\n"); + LOG(LOG_ERROR, "TO2.OwnerServiceInfoReady: Invalid value type " + "for maxDeviceServiceInfoSz\n"); goto err; } - LOG(LOG_DEBUG, "TO2.OwnerServiceInfoReady: Received maxDeviceServiceInfoSz = %"PRIu64"\n", - rec_maxDeviceServiceInfoSz); + LOG(LOG_DEBUG, + "TO2.OwnerServiceInfoReady: Received maxDeviceServiceInfoSz = " + "%" PRIu64 "\n", + rec_maxDeviceServiceInfoSz); if (rec_maxDeviceServiceInfoSz < MIN_SERVICEINFO_SZ) { // default to minimum and log it ps->maxDeviceServiceInfoSz = MIN_SERVICEINFO_SZ; LOG(LOG_DEBUG, - "TO2.OwnerServiceInfoReady: Received maxDeviceServiceInfoSz is less than " - "the minimum size supported. Defaulting to %"PRIu64"\n", - ps->maxDeviceServiceInfoSz); + "TO2.OwnerServiceInfoReady: Received " + "maxDeviceServiceInfoSz is less than " + "the minimum size supported. Defaulting to %" PRIu64 "\n", + ps->maxDeviceServiceInfoSz); } else if (rec_maxDeviceServiceInfoSz > ps->maxDeviceServiceInfoSz) { // nothing to do, just log it LOG(LOG_DEBUG, - "TO2.OwnerServiceInfoReady: Received maxDeviceServiceInfoSz is more than " - "the maximum size supported. Defaulting to %"PRIu64"\n", - ps->maxDeviceServiceInfoSz); + "TO2.OwnerServiceInfoReady: Received " + "maxDeviceServiceInfoSz is more than " + "the maximum size supported. Defaulting to %" PRIu64 "\n", + ps->maxDeviceServiceInfoSz); } else { // set the received value ps->maxDeviceServiceInfoSz = rec_maxDeviceServiceInfoSz; - LOG(LOG_DEBUG, - "TO2.OwnerServiceInfoReady: Received maxDeviceServiceInfoSz is valid\n"); + LOG(LOG_DEBUG, "TO2.OwnerServiceInfoReady: Received " + "maxDeviceServiceInfoSz is valid\n"); } if (!fdor_end_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfoReady: Failed to end array\n"); + LOG(LOG_ERROR, + "TO2.OwnerServiceInfoReady: Failed to end array\n"); goto err; } - LOG(LOG_DEBUG, "TO2.OwnerServiceInfoReady: Expected Maximum Device ServiceInfo size is %"PRIu64"\n", + LOG(LOG_DEBUG, + "TO2.OwnerServiceInfoReady: Expected Maximum Device ServiceInfo " + "size is %" PRIu64 "\n", ps->maxDeviceServiceInfoSz); ps->state = FDO_STATE_T02_SND_GET_NEXT_OWNER_SERVICE_INFO; LOG(LOG_DEBUG, "TO2.OwnerServiceInfoReady completed successfully\n"); diff --git a/lib/prot/to2/msg68.c b/lib/prot/to2/msg68.c index 506fc817..29161d00 100644 --- a/lib/prot/to2/msg68.c +++ b/lib/prot/to2/msg68.c @@ -16,7 +16,7 @@ /** * msg68() - TO2.DeviceServiceInfo * Device sends the Device ServiceInfo to the owner. - * + * * TO2.DeviceServiceInfo = [ * IsMoreServiceInfo, ;; more ServiceInfo to come, bool * ServiceInfo ;; service info entries @@ -40,7 +40,8 @@ int32_t msg68(fdo_prot_t *ps) fdo_sv_invalid_modnames_t *serviceinfo_invalid_modnames_it = NULL; char sv_modname_key[FDO_MODULE_NAME_LEN + FDO_MODULE_MSG_LEN + 1] = ""; size_t serviceinfo_invalid_modnames_count = 0; - // Pointer to hold the external module reference. No memory is allocated, thus never freed. + // Pointer to hold the external module reference. No memory is + // allocated, thus never freed. fdo_sdk_service_info_module *ext_module = NULL; bool module_write_done = false; @@ -55,10 +56,12 @@ int32_t msg68(fdo_prot_t *ps) fdow_next_block(&ps->fdow, FDO_TO2_GET_NEXT_OWNER_SERVICE_INFO); // DeviceServiceInfo's that need to be sent, sequentially: - // 1. 'devmod' module contained within 'ps->service_info' will be sent by default initially. - // Once sent completely, 'ps->service_info' is cleared for further usage to send (2). - // 2. Response [modname:active, false] when an unsupported module is being accessed. - // Stored in 'ps->service_info', and once sent completely, is cleared for further usage. + // 1. 'devmod' module contained within 'ps->service_info' will be sent + // by default initially. Once sent completely, 'ps->service_info' is + // cleared for further usage to send (2). + // 2. Response [modname:active, false] when an unsupported module is + // being accessed. Stored in 'ps->service_info', and once sent + // completely, is cleared for further usage. // 3. External module(s) (remaining iterations, as per module responses) // Process ServiceInfo to send for Options (1), (2) and (3), @@ -66,130 +69,177 @@ int32_t msg68(fdo_prot_t *ps) if (!ps->owner_serviceinfo_ismore) { // Preparing to send (2), because (1) is sent - // (which is why 'ps->service_info' is now NULL, as mentioned above) - // There is a list of unsupported module names that need to be sent, AND, - // it has not been added to the serviceinfo list, that is currently NULL. + // (which is why 'ps->service_info' is now NULL, as mentioned + // above) There is a list of unsupported module names that need + // to be sent, AND, it has not been added to the serviceinfo + // list, that is currently NULL. if (!ps->service_info && ps->serviceinfo_invalid_modnames) { ps->service_info = fdo_service_info_alloc(); - if(!ps->service_info) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to alloc ServiceInfo\n"); + if (!ps->service_info) { + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to alloc ServiceInfo\n"); goto err; } - serviceinfo_invalid_modnames_it = ps->serviceinfo_invalid_modnames; + serviceinfo_invalid_modnames_it = + ps->serviceinfo_invalid_modnames; while (serviceinfo_invalid_modnames_it) { - // The message to be sent contains a list of unsupported module names - // with key/message 'active' and value 'false', something of the form - // [[modname1:active, false], [modname2:active, false]]... + // The message to be sent contains a list of + // unsupported module names with key/message + // 'active' and value 'false', something of the + // form + // [[modname1:active, false], [modname2:active, + // false]]... // create 'modname:active' - if (0 != strncpy_s(sv_modname_key, FDO_MODULE_NAME_LEN, - serviceinfo_invalid_modnames_it->bytes, FDO_MODULE_NAME_LEN)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to concatenate module name\n"); + if (0 != + strncpy_s( + sv_modname_key, FDO_MODULE_NAME_LEN, + serviceinfo_invalid_modnames_it->bytes, + FDO_MODULE_NAME_LEN)) { + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to " + "concatenate module name\n"); goto err; } - if (0 != strcat_s(sv_modname_key, FDO_MODULE_MSG_LEN, - FDO_MODULE_SEPARATOR)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to concatenate module name\n"); + if (0 != strcat_s(sv_modname_key, + FDO_MODULE_MSG_LEN, + FDO_MODULE_SEPARATOR)) { + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to " + "concatenate module name\n"); goto err; } - if (0 != strcat_s(sv_modname_key, FDO_MODULE_MSG_LEN, - FDO_MODULE_MESSAGE_ACTIVE)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to concatenate module name\n"); + if (0 != strcat_s(sv_modname_key, + FDO_MODULE_MSG_LEN, + FDO_MODULE_MESSAGE_ACTIVE)) { + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to " + "concatenate module name\n"); goto err; } - // add 'modname:active=false' into the serviceinfo list - if (!fdo_service_info_add_kv_bool(ps->service_info, - sv_modname_key, false)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to create ServiceInfo\n"); + // add 'modname:active=false' into the + // serviceinfo list + if (!fdo_service_info_add_kv_bool( + ps->service_info, sv_modname_key, + false)) { + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to " + "create ServiceInfo\n"); goto err; } - serviceinfo_invalid_modnames_it = serviceinfo_invalid_modnames_it->next; + serviceinfo_invalid_modnames_it = + serviceinfo_invalid_modnames_it->next; serviceinfo_invalid_modnames_count++; } - ps->service_info->numKV = serviceinfo_invalid_modnames_count; + ps->service_info->numKV = + serviceinfo_invalid_modnames_count; // clear it here immediately, so we don't use it back - fdo_serviceinfo_invalid_modname_free(ps->serviceinfo_invalid_modnames); + fdo_serviceinfo_invalid_modname_free( + ps->serviceinfo_invalid_modnames); ps->serviceinfo_invalid_modnames = NULL; - } - // As per the spec, Only send Device ServiceInfo modules IF Owner is not done if (!ps->owner_serviceinfo_isdone) { - // get any external module that has some ServiceInfo to send 'NOW', - ext_module = fdo_serviceinfo_get_external_mod_to_write(&ps->fdow, - ps->sv_info_mod_list_head, - ps->maxDeviceServiceInfoSz - SERVICEINFO_MTU_FIT_MARGIN); - // reset FDOW because it may have been used by the above method + // get any external module that has some ServiceInfo to + // send 'NOW', + ext_module = fdo_serviceinfo_get_external_mod_to_write( + &ps->fdow, ps->sv_info_mod_list_head, + ps->maxDeviceServiceInfoSz - + SERVICEINFO_MTU_FIT_MARGIN); + // reset FDOW because it may have been used by the above + // method fdo_block_reset(&ps->fdow.b); ps->fdor.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to initialize FDOW encoder\n"); goto err; } } // Finally, Send ServiceInfo in priority: - // 1. Send 'devmod' 1st , and then received unsupported modules-names as a part of 1st 'if' - // i.e, (1) then (2). Fit within MTU as needed. - // 2. Send external module's Device ServiceInfo (if present) in the 'else if', i.e (3) + // 1. Send 'devmod' 1st , and then received unsupported + // modules-names as a part of 1st 'if' i.e, (1) then (2). Fit + // within MTU as needed. + // 2. Send external module's Device ServiceInfo (if present) in + // the 'else if', i.e (3) if (ps->service_info) { - // Try to fit in MTU for either (1) or (2), at any given time. - // The splitting is done by considering an additional margin for CBOR encoding. - // The data is CBOR encoded twice. First time to find the what can be fit, and - // and second time to actually transmit the ServiceInfo. - // This is done in this way, since the underlying - // TinyCBOR library doesn't allow us to change the total number of entries - // in an array (ServiceInfoKeyVal, in this case), once it's set. - if (!fdo_serviceinfo_fit_mtu(&ps->fdow, ps->service_info, - ps->maxDeviceServiceInfoSz - SERVICEINFO_MTU_FIT_MARGIN)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to fit within MTU\n"); + // Try to fit in MTU for either (1) or (2), at any given + // time. The splitting is done by considering an + // additional margin for CBOR encoding. The data is CBOR + // encoded twice. First time to find the what can be + // fit, and and second time to actually transmit the + // ServiceInfo. This is done in this way, since the + // underlying TinyCBOR library doesn't allow us to + // change the total number of entries in an array + // (ServiceInfoKeyVal, in this case), once it's set. + if (!fdo_serviceinfo_fit_mtu( + &ps->fdow, ps->service_info, + ps->maxDeviceServiceInfoSz - + SERVICEINFO_MTU_FIT_MARGIN)) { + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to fit within MTU\n"); goto err; } - if (ps->service_info->sv_index_end == ps->service_info->numKV && - ps->service_info->sv_val_index == 0) { + if (ps->service_info->sv_index_end == + ps->service_info->numKV && + ps->service_info->sv_val_index == 0) { ps->device_serviceinfo_ismore = false; - } else if (ps->service_info->sv_index_end < ps->service_info->numKV) { + } else if (ps->service_info->sv_index_end < + ps->service_info->numKV) { ps->device_serviceinfo_ismore = true; } else { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Invalid state reached while processing " - "Device ServiceInfo\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Invalid " + "state reached while processing " + "Device ServiceInfo\n"); goto err; } - // reset FDOW because it was used in this method, out of place + // reset FDOW because it was used in this method, out of + // place fdo_block_reset(&ps->fdow.b); ps->fdor.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to initialize FDOW encoder\n"); goto err; } if (!fdow_start_array(&ps->fdow, 2)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to start array\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to start array\n"); goto err; } - ps->device_serviceinfo_ismore = ps->device_serviceinfo_ismore || (ext_module != NULL); - if (!fdow_boolean(&ps->fdow, ps->device_serviceinfo_ismore)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to write IsMoreServiceInfo\n"); + ps->device_serviceinfo_ismore = + ps->device_serviceinfo_ismore || + (ext_module != NULL); + if (!fdow_boolean(&ps->fdow, + ps->device_serviceinfo_ismore)) { + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to write IsMoreServiceInfo\n"); goto err; } serviceinfo_itr = ps->service_info; // Construct and write Device ServiceInfo - if (!fdo_serviceinfo_write(&ps->fdow, serviceinfo_itr, - ps->maxDeviceServiceInfoSz - SERVICEINFO_MTU_FIT_MARGIN)) { - LOG(LOG_ERROR, "Error in combining platform DSI's!\n"); + if (!fdo_serviceinfo_write( + &ps->fdow, serviceinfo_itr, + ps->maxDeviceServiceInfoSz - + SERVICEINFO_MTU_FIT_MARGIN)) { + LOG(LOG_ERROR, + "Error in combining platform DSI's!\n"); goto err; } if (!fdow_end_array(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to end array\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to end array\n"); goto err; } @@ -206,44 +256,57 @@ int32_t msg68(fdo_prot_t *ps) } else if (ext_module != NULL) { // write External module ServiceInfo - if (!fdo_serviceinfo_external_mod_is_more(&ps->fdow, - ps->sv_info_mod_list_head, - ps->maxDeviceServiceInfoSz - SERVICEINFO_MTU_FIT_MARGIN, &ps->device_serviceinfo_ismore)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to calculate IsMoreServiceInfo\n"); + if (!fdo_serviceinfo_external_mod_is_more( + &ps->fdow, ps->sv_info_mod_list_head, + ps->maxDeviceServiceInfoSz - + SERVICEINFO_MTU_FIT_MARGIN, + &ps->device_serviceinfo_ismore)) { + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to " + "calculate IsMoreServiceInfo\n"); goto err; } - // reset FDOW because it may have been used by the above method + // reset FDOW because it may have been used by the above + // method fdo_block_reset(&ps->fdow.b); ps->fdor.b.block_size = ps->prot_buff_sz; if (!fdow_encoder_init(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to initialize FDOW encoder\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to initialize FDOW encoder\n"); goto err; } if (!fdow_start_array(&ps->fdow, 2)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to start array\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to start array\n"); goto err; } - if (!fdow_boolean(&ps->fdow, ps->device_serviceinfo_ismore)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to write IsMoreServiceInfo\n"); + if (!fdow_boolean(&ps->fdow, + ps->device_serviceinfo_ismore)) { + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to write IsMoreServiceInfo\n"); goto err; } - if (!fdo_serviceinfo_external_mod_write(&ps->fdow, ps->ext_service_info, - ext_module, ps->maxDeviceServiceInfoSz - SERVICEINFO_MTU_FIT_MARGIN)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to write External module ServiceInfo\n"); + if (!fdo_serviceinfo_external_mod_write( + &ps->fdow, ps->ext_service_info, ext_module, + ps->maxDeviceServiceInfoSz - + SERVICEINFO_MTU_FIT_MARGIN)) { + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to write " + "External module ServiceInfo\n"); goto err; } if (!fdow_end_array(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to end array\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed " + "to end array\n"); goto err; } // if we reach here, ServiceInfo write has been done module_write_done = true; } - } // write Empty ServiceInfo message if no write has been performed yet, @@ -251,33 +314,39 @@ int32_t msg68(fdo_prot_t *ps) if (ps->owner_serviceinfo_ismore || !module_write_done) { // Empty ServiceInfo. send [false, []] if (!fdow_start_array(&ps->fdow, 2)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to start array\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to start array\n"); goto err; } if (!fdow_boolean(&ps->fdow, false)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to write IsMoreServiceInfo\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to write " + "IsMoreServiceInfo\n"); goto err; } if (!fdow_start_array(&ps->fdow, 0)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to start empty ServiceInfo array\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to start " + "empty ServiceInfo array\n"); goto err; } if (!fdow_end_array(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to end empty ServiceInfo array\n"); + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to end " + "empty ServiceInfo array\n"); goto err; } if (!fdow_end_array(&ps->fdow)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to end array\n"); + LOG(LOG_ERROR, + "TO2.DeviceServiceInfo: Failed to end array\n"); goto err; } } - if (!fdo_encrypted_packet_windup( - &ps->fdow, FDO_TO2_GET_NEXT_OWNER_SERVICE_INFO)) { - LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to create Encrypted Message\n"); + if (!fdo_encrypted_packet_windup(&ps->fdow, + FDO_TO2_GET_NEXT_OWNER_SERVICE_INFO)) { + LOG(LOG_ERROR, "TO2.DeviceServiceInfo: Failed to create " + "Encrypted Message\n"); goto err; } diff --git a/lib/prot/to2/msg69.c b/lib/prot/to2/msg69.c index 26be080d..caef30e8 100644 --- a/lib/prot/to2/msg69.c +++ b/lib/prot/to2/msg69.c @@ -60,11 +60,13 @@ int32_t msg69(fdo_prot_t *ps) /* If the packet is encrypted, decrypt it */ pkt = fdo_encrypted_packet_read(&ps->fdor); if (pkt == NULL) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to parse encrypted packet\n"); + LOG(LOG_ERROR, + "TO2.OwnerServiceInfo: Failed to parse encrypted packet\n"); goto err; } if (!fdo_encrypted_packet_unwind(&ps->fdor, pkt)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to decrypt packet!\n"); + LOG(LOG_ERROR, + "TO2.OwnerServiceInfo: Failed to decrypt packet!\n"); goto err; } @@ -74,7 +76,8 @@ int32_t msg69(fdo_prot_t *ps) } if (!fdor_boolean(&ps->fdor, &ps->owner_serviceinfo_ismore)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to read IsMoreServiceInfo\n"); + LOG(LOG_ERROR, + "TO2.OwnerServiceInfo: Failed to read IsMoreServiceInfo\n"); goto err; } @@ -87,32 +90,42 @@ int32_t msg69(fdo_prot_t *ps) // TO2.DeviceServiceInfo.IsMoreServiceInfo is true // Expecting received Owner ServiceInfo to be an empty array []. if (!fdor_start_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to start empty ServiceInfo array\n"); + LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to start " + "empty ServiceInfo array\n"); goto err; } if (!fdor_end_array(&ps->fdor)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to end empty ServiceInfo array\n"); + LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to end " + "empty ServiceInfo array\n"); goto err; } } else { - // the message [bool,bool, [],[]..], when CBOR encoded, will always take up 3 bytes: - // 1 byte for main array, 1 byte each for bool values. - // the remaining data is the ServiceInfo, and hence we can deduce the size of received - // ServiceInfo by subtracting 3 from the total message length. - if ((uint64_t)(ps->fdor.b.block_size - 3) <= ps->maxOwnerServiceInfoSz) { + // the message [bool,bool, [],[]..], when CBOR encoded, will + // always take up 3 bytes: 1 byte for main array, 1 byte each + // for bool values. the remaining data is the ServiceInfo, and + // hence we can deduce the size of received ServiceInfo by + // subtracting 3 from the total message length. + if ((uint64_t)(ps->fdor.b.block_size - 3) <= + ps->maxOwnerServiceInfoSz) { // process the received ServiceInfo module_list_itr = ps->sv_info_mod_list_head; - if (!fdo_serviceinfo_read(&ps->fdor, module_list_itr, &module_ret_val, + if (!fdo_serviceinfo_read( + &ps->fdor, module_list_itr, &module_ret_val, &ps->serviceinfo_invalid_modnames)) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed to read ServiceInfo\n"); + LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Failed " + "to read ServiceInfo\n"); goto err; } + } else { - // do not process ServiceInfo since the ServiceInfo size received is more than the - // agreed maxOwnerServiceInfoSz from TO2.OwnerServiceInfoReady, Type 67 + // do not process ServiceInfo since the ServiceInfo size + // received is more than the agreed + // maxOwnerServiceInfoSz from TO2.OwnerServiceInfoReady, + // Type 67 LOG(LOG_ERROR, - "TO2.OwnerServiceInfo: Received ServiceInfo size is greater than maxOwnerServiceInfoSz\n"); + "TO2.OwnerServiceInfo: Received ServiceInfo size " + "is greater than maxOwnerServiceInfoSz\n"); goto err; } } @@ -124,15 +137,20 @@ int32_t msg69(fdo_prot_t *ps) if (ps->owner_serviceinfo_isdone) { if (ps->owner_serviceinfo_ismore) { - LOG(LOG_ERROR, "TO2.OwnerServiceInfo: Both isMoreServiceInfo and isDone are true\n"); + LOG(LOG_ERROR, + "TO2.OwnerServiceInfo: Both isMoreServiceInfo and " + "isDone are true\n"); goto err; } // Device does not have anything else to send - if (!ps->serviceinfo_invalid_modnames && !ps->device_serviceinfo_ismore) { + if (!ps->serviceinfo_invalid_modnames && + !ps->device_serviceinfo_ismore) { ps->state = FDO_STATE_TO2_SND_DONE; } else { - // Device has more ServiceInfo to send (ONLY Unsupported module names can be sent) - ps->state = FDO_STATE_T02_SND_GET_NEXT_OWNER_SERVICE_INFO; + // Device has more ServiceInfo to send (ONLY Unsupported + // module names can be sent) + ps->state = + FDO_STATE_T02_SND_GET_NEXT_OWNER_SERVICE_INFO; } } else { ps->state = FDO_STATE_T02_SND_GET_NEXT_OWNER_SERVICE_INFO; diff --git a/lib/prot/to2/msg70.c b/lib/prot/to2/msg70.c index 45db678a..ed4dd9b5 100644 --- a/lib/prot/to2/msg70.c +++ b/lib/prot/to2/msg70.c @@ -8,7 +8,7 @@ * \brief This file implements msg70 of TO2 state machine. */ -#include "fdoCrypto.h" +#include "fdo_crypto.h" #include "load_credentials.h" #include "fdoprot.h" #include "util.h" @@ -39,15 +39,16 @@ int32_t msg70(fdo_prot_t *ps) LOG(LOG_DEBUG, "TO2.Done started\n"); LOG(LOG_DEBUG, "(Old) GUID before TO2: %s\n", - fdo_guid_to_string(ps->dev_cred->owner_blk->guid, guid_buf, sizeof(guid_buf))); + fdo_guid_to_string(ps->dev_cred->owner_blk->guid, guid_buf, + sizeof(guid_buf))); /* * TODO: Writing credentials to TEE! - * This GUID came as TO2SetupDevicePayload.Guid - "the new transaction GUID" - * which will overwrite GUID in initial credential data. - * A new transaction will start fresh, taking the latest - * credential (among them this, new GUID). That's why - * simple memorizing GUID in RAM is not needed. + * This GUID came as TO2SetupDevicePayload.Guid - "the new transaction + * GUID" which will overwrite GUID in initial credential data. A new + * transaction will start fresh, taking the latest credential (among + * them this, new GUID). That's why simple memorizing GUID in RAM is not + * needed. */ fdo_byte_array_free(ps->dev_cred->owner_blk->guid); ps->dev_cred->owner_blk->guid = ps->osc->guid; @@ -57,19 +58,24 @@ int32_t msg70(fdo_prot_t *ps) fdo_public_key_free(ps->dev_cred->owner_blk->pk); ps->dev_cred->owner_blk->pk = ps->osc->pubkey; + ps->dev_cred->dc_active = false; if (ps->reuse_enabled && reuse_supported) { // Reuse scenario, moving to post DI state ps->dev_cred->ST = FDO_DEVICE_STATE_READY1; + ps->dev_cred->dc_active = true; } else if (resale_supported) { // Done with FIDO Device Onboard. // As of now moving to done state for resale ps->dev_cred->ST = FDO_DEVICE_STATE_IDLE; + ps->dev_cred->dc_active = true; // create new Owner's public key hash fdo_hash_free(ps->dev_cred->owner_blk->pkh); - ps->dev_cred->owner_blk->pkh = fdo_pub_key_hash(ps->dev_cred->owner_blk->pk); + ps->dev_cred->owner_blk->pkh = + fdo_pub_key_hash(ps->dev_cred->owner_blk->pk); if (!ps->dev_cred->owner_blk->pkh) { - LOG(LOG_ERROR, "TO2.Done: Hash creation of TO2.SetupDevice.Owner2Key failed\n"); + LOG(LOG_ERROR, "TO2.Done: Hash creation of " + "TO2.SetupDevice.Owner2Key failed\n"); goto err; } } @@ -80,39 +86,52 @@ int32_t msg70(fdo_prot_t *ps) goto err; } LOG(LOG_DEBUG, "(New) GUID after TO2: %s\n", - fdo_guid_to_string(ps->dev_cred->owner_blk->guid, guid_buf, sizeof(guid_buf))); + fdo_guid_to_string(ps->dev_cred->owner_blk->guid, guid_buf, + sizeof(guid_buf))); /* Rotate Data Protection Key */ if (0 != fdo_generate_storage_hmac_key()) { - LOG(LOG_ERROR, "TO2.Done: Failed to rotate data protection key.\n"); + LOG(LOG_ERROR, + "TO2.Done: Failed to rotate data protection key.\n"); } - LOG(LOG_DEBUG, "TO2.Done: Data protection key rotated successfully!!\n"); + LOG(LOG_DEBUG, + "TO2.Done: Data protection key rotated successfully!!\n"); if (!ps->reuse_enabled) { - /* Commit the replacement hmac key only if reuse was not triggered*/ + /* Commit the replacement hmac key only if reuse was not + * triggered*/ if (fdo_commit_ov_replacement_hmac_key() != 0) { - LOG(LOG_ERROR, "TO2.Done: Failed to store new device hmac key.\n"); + LOG(LOG_ERROR, + "TO2.Done: Failed to store new device hmac key.\n"); goto err; } LOG(LOG_DEBUG, "TO2.Done: Updated device's new hmac key\n"); } else { - LOG(LOG_DEBUG, "TO2.Done: Device hmac key is unchanged as reuse was triggered.\n"); + LOG(LOG_DEBUG, "TO2.Done: Device hmac key is unchanged as " + "reuse was triggered.\n"); } /* Write new device credentials and state*/ if (!store_device_status(&ps->dev_cred->ST)) { - LOG(LOG_ERROR, "TO2.Done: Failed to store updated device status\n"); + LOG(LOG_ERROR, + "TO2.Done: Failed to store updated device status\n"); goto err; } #if defined(DEVICE_CSE_ENABLED) FDO_STATUS fdo_status; if (TEE_SUCCESS != fdo_heci_commit_file(&fdo_cse_handle, OVH_FILE_ID, - &fdo_status) || FDO_STATUS_SUCCESS != fdo_status) { + &fdo_status) || + FDO_STATUS_SUCCESS != fdo_status) { LOG(LOG_ERROR, "TO2.Done: FDO OVH COMMIT failed!!\n"); goto err; } LOG(LOG_DEBUG, "TO2.Done: FDO OVH COMMIT succeeded %u\n", fdo_status); +#elif defined(DEVICE_TPM20_ENABLED) + if (store_tpm_credential(ps->dev_cred) != 0) { + LOG(LOG_ERROR, "TO2.Done: Failed to store new device creds\n"); + goto err; + } #else if (store_credential(ps->dev_cred) != 0) { LOG(LOG_ERROR, "TO2.Done: Failed to store new device creds\n"); @@ -134,13 +153,13 @@ int32_t msg70(fdo_prot_t *ps) return false; } - if(!ps->nonce_to2provedv) { + if (!ps->nonce_to2provedv) { LOG(LOG_ERROR, "TO2.Done: NonceTO2ProveDv not found\n"); return false; } if (!fdow_byte_string(&ps->fdow, ps->nonce_to2provedv->bytes, - ps->nonce_to2provedv->byte_sz)) { + ps->nonce_to2provedv->byte_sz)) { LOG(LOG_ERROR, "TO2.Done: Failed to write NonceTO2ProveDv\n"); return false; } @@ -151,7 +170,8 @@ int32_t msg70(fdo_prot_t *ps) } if (!fdo_encrypted_packet_windup(&ps->fdow, FDO_TO2_DONE)) { - LOG(LOG_ERROR, "TO2.Done: Failed to create Encrypted Message\n"); + LOG(LOG_ERROR, + "TO2.Done: Failed to create Encrypted Message\n"); goto err; } diff --git a/lib/prot/to2/msg71.c b/lib/prot/to2/msg71.c index 272ee4b4..902fc75d 100644 --- a/lib/prot/to2/msg71.c +++ b/lib/prot/to2/msg71.c @@ -61,9 +61,10 @@ int32_t msg71(fdo_prot_t *ps) /* already allocated nonce_to2setupdv_rcv*/ if (!ps->nonce_to2setupdv_rcv || - !fdor_byte_string(&ps->fdor, ps->nonce_to2setupdv_rcv->bytes, - ps->nonce_to2setupdv_rcv->byte_sz)) { - LOG(LOG_ERROR, "TO2.Done2: Failed to alloc/read NonceTO2SetupDv array\n"); + !fdor_byte_string(&ps->fdor, ps->nonce_to2setupdv_rcv->bytes, + ps->nonce_to2setupdv_rcv->byte_sz)) { + LOG(LOG_ERROR, + "TO2.Done2: Failed to alloc/read NonceTO2SetupDv array\n"); goto err; } @@ -74,8 +75,9 @@ int32_t msg71(fdo_prot_t *ps) /* verify the nonce received is correct. */ if (!fdo_nonce_equal(ps->nonce_to2setupdv_rcv, ps->nonce_to2setupdv)) { - LOG(LOG_ERROR, "TO2.Done2: Received NonceTO2SetupDv does not match with the" - "stored NonceTO2SetupDv\n"); + LOG(LOG_ERROR, "TO2.Done2: Received NonceTO2SetupDv does not " + "match with the" + "stored NonceTO2SetupDv\n"); goto err; } diff --git a/mbedos/components/sdo/sdo/main.cpp b/mbedos/components/sdo/sdo/main.cpp index 65bca3ed..7b259ca2 100644 --- a/mbedos/components/sdo/sdo/main.cpp +++ b/mbedos/components/sdo/sdo/main.cpp @@ -6,7 +6,7 @@ /*! * \file * \brief Main application. This file has implementation for entry point into - * the platform and necessary things to initialize fdo, run it and exit + * the platform and necessary things to initialize FDO, run it and exit * gracefully. */ diff --git a/network/include/network_al.h b/network/include/network_al.h index 18fa369b..b5b83be5 100644 --- a/network/include/network_al.h +++ b/network/include/network_al.h @@ -18,10 +18,9 @@ #include #include #define IPV4_ADDR_LEN 4 -#define MAX_TIME_OUT 60000L +#define MAX_TIME_OUT 60000L #ifndef TARGET_OS_MBEDOS -typedef void *fdo_con_handle; #define FDO_CON_INVALID_HANDLE NULL #endif @@ -54,89 +53,84 @@ int32_t fdo_con_dns_lookup(const char *url, fdo_ip_address_t **ip_list, * Open a connection specified by IP address and port. * * @param[in] addr: IP Address to connect to. + * @param dn: Domain name of the server * @param[in] port: port number to connect to. * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is * @retval -1 on failure, connection handle on success. */ -fdo_con_handle fdo_con_connect(fdo_ip_address_t *addr, uint16_t port, - bool tls); +int32_t fdo_con_connect(fdo_ip_address_t *addr, const char *dn, uint16_t port, + bool tls); /* * Disconnect the connection. * - * @param[in] handle: connection handler (for ex: socket-id) * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_disconnect(fdo_con_handle handle); +int32_t fdo_con_disconnect(void); /* * Check the REST header for given REST response buffer and offset. * * @param[in] curl_buf: Input buffer that contains the REST header - * @param[in] header_start_offset: offset in the buffer that points to the start of REST header + * @param[in] header_start_offset: offset in the buffer that points to the start + * of REST header * @retval true if header is valid and complete and false otherwise. */ -bool has_header(char *buf, - size_t header_start_offset); +bool has_header(char *buf, size_t header_start_offset); /* * Get the message length from the given REST response buffer. * * @param[in] curl_buf: Input buffer that contains the REST header - * @param[in/out] cur_offset: offset in the buffer that initially points to the start of REST header. - * This gets updated to point to start of message body after successful parsing + * @param[in/out] cur_offset: offset in the buffer that initially points to the + * start of REST header. This gets updated to point to start of message body + * after successful parsing * @param[out] msglen: Message length as specified in the REST header - * @retval bool returns true for success and false in case of invalid/incomplete content/parsing failure. + * @retval bool returns true for success and false in case of invalid/incomplete + * content/parsing failure. */ -bool get_msg_length(char *curl_buf, - size_t *cur_offset, uint32_t *msglen); +bool get_msg_length(char *curl_buf, size_t *cur_offset, uint32_t *msglen); /* - * Receive(read) length of incoming fdo packet. + * Receive(read) length of incoming FDO packet. * - * @param[in] handle: connection handler (for ex: socket-id) * @param[out] protocol_version: FDO protocol version * @param[out] message_type: message type of incoming FDO message. * @param[out] msglen: length of incoming message. - * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is - * @param[out] curl_buf: data buffer to read into msg received by curl. - * @param[out] curl_buf_offset: pointer to track curl_buf. + * @param[in] hdr_buf: data buffer to parse msg received by curl. * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_recv_msg_header(fdo_con_handle handle, - uint32_t *protocol_version, - uint32_t *message_type, uint32_t *msglen, - char *curl_buf, size_t *curl_buf_offset); +int32_t fdo_con_parse_msg_header(uint32_t *protocol_version, + uint32_t *message_type, uint32_t *msglen, + char *hdr_buf); /* - * Receive(read) incoming fdo packet. + * Receive(read) incoming FDO packet. * - * @param[in] handle: connection handler (for ex: socket-id) * @param[out] buf: data buffer to read into. * @param[in] length: Number of received bytes to be read. - * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is - * @param[in] curl_buf: data buffer to read into msg received by curl. - * @param[in] curl_buf_offset: pointer to track curl_buf. + * @param[in] body_buf: data buffer to parse msg received by curl. * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_recv_msg_body(uint8_t *buf, size_t length, char *curl_buf, - size_t curl_buf_offset); +int32_t fdo_con_parse_msg_body(uint8_t *buf, size_t length, char *body_buf); /* - * Send(write) data. + * Send(write) and receive(read) data. * - * @param[in] handle: connection handler (for ex: socket-id) * @param[in] protocol_version: FDO protocol version * @param[in] message_type: message type of outgoing FDO message. * @param[in] buf: data buffer to write from. * @param[in] length: Number of sent bytes. * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is + * @param[in] header_buf: header data buffer to read into msg received by curl. + * @param[in] body_buf: body data buffer to read into msg received by curl. * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_send_message(fdo_con_handle handle, uint32_t protocol_version, - uint32_t message_type, const uint8_t *buf, - size_t length, bool tls); +int32_t fdo_con_send_recv_message(uint32_t protocol_version, + uint32_t message_type, const uint8_t *buf, + size_t length, bool tls, char *header_buf, + char *body_buf); /* * Network Connection tear down. @@ -168,13 +162,15 @@ const char *get_device_serial_number(void); int fdo_random(void); /** - * fdo_curl_setup connects to the given ip_addr via curl API + * fdo_curl_connect connects to the given ip_addr via curl API * * @param ip_addr[in] - pointer to IP address info + * @param dn: Domain name of the server * @param port[in] - port number to connect - * @return connection handle on success. -ve value on failure + * @return 0 on success. -1 on failure */ -int fdo_curl_setup(fdo_ip_address_t *ip_addr, uint16_t port, bool tls); +int32_t fdo_curl_connect(fdo_ip_address_t *ip_addr, const char *dn, + uint16_t port, bool tls); /** * fdo_curl_proxy set up the proxy connection via curl API diff --git a/network/include/rest_interface.h b/network/include/rest_interface.h index 85d40937..bbaa00cb 100644 --- a/network/include/rest_interface.h +++ b/network/include/rest_interface.h @@ -25,7 +25,7 @@ // maximum supported length is 64000 + 700. #define REST_MAX_MSGBODY_SIZE MAX_SERVICEINFO_SZ + MSG_METADATA_SIZE #define HTTP_SUCCESS_OK 200 -#define IP_TAG_LEN 16 // e.g. 192.168.111.111 +#define IP_TAG_LEN 16 // e.g. 192.168.111.111 #define MAX_PORT_SIZE 6 // max port size is 65536 + 1null char #define ISASCII(ch) ((ch & ~0x7f) == 0) @@ -45,6 +45,11 @@ typedef struct Rest_ctx_s { bool is_dns; } rest_ctx_t; +struct MemoryStruct { + char *memory; + size_t size; +}; + extern CURL *curl; bool cache_host_dns(const char *dns); @@ -53,7 +58,7 @@ bool cache_host_port(uint16_t port); bool cache_tls_connection(void); bool init_rest_context(void); rest_ctx_t *get_rest_context(void); -bool construct_rest_header(rest_ctx_t *rest, char *header, size_t header_len); +bool construct_rest_header(rest_ctx_t *rest, struct curl_slist **msg_header); char get_rest_hdr_body_separator(void); bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len); void exit_rest_context(void); diff --git a/network/mbed_net_al.h b/network/mbed_net_al.h index 66334e75..a3231f75 100644 --- a/network/mbed_net_al.h +++ b/network/mbed_net_al.h @@ -21,7 +21,7 @@ class fdo_con_handle : public TCPSocket }; #else #include "mbedtls/ssl.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" typedef void *fdo_con_handle; #define FDO_CON_INVALID_HANDLE NULL #endif diff --git a/network/network_if_linux.c b/network/network_if_linux.c index dad70757..1d2f8583 100644 --- a/network/network_if_linux.c +++ b/network/network_if_linux.c @@ -21,49 +21,47 @@ #include "util.h" #include "network_al.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "fdoprotctx.h" #include "fdonet.h" #include "safe_lib.h" #include "snprintf_s.h" #include "rest_interface.h" -/** - * Auxiliary function that waits on the socket while receiving data from connected socket. - * - * @param sockfd - socket struct for read. - * @param for_recv - bit for receive (1 or 0) - * @param timeout_ms - timeout in milliseconds. - * @retval returns the number of signalled sockets or -1. - */ -static int wait_on_socket(curl_socket_t sockfd, int for_recv, long timeout_ms) +// Function used by libcurl to allocate memory to data received from the HTTP +// response +static void init_string(struct MemoryStruct *s) { - struct timeval tv; - fd_set infd, outfd, errfd; - int res; - - tv.tv_sec = timeout_ms / 1000; - tv.tv_usec = (timeout_ms % 1000) * 1000; - - FD_ZERO(&infd); - FD_ZERO(&outfd); - FD_ZERO(&errfd); + s->size = 0; + s->memory = malloc(s->size + 1); + if (s->memory == NULL) { + LOG(LOG_ERROR, "malloc() failed\n"); + exit(EXIT_FAILURE); + } + s->memory[0] = '\0'; +} - FD_SET(sockfd, &errfd); /* always check for error */ +// Callback for libcurl. data written to this buffer. +static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, + void *userp) +{ + size_t realsize = size * nmemb; + struct MemoryStruct *mem = (struct MemoryStruct *)userp; - if (for_recv) { - FD_SET(sockfd, &infd); - } else { - FD_SET(sockfd, &outfd); + char *ptr = (char *)realloc(mem->memory, mem->size + realsize + 1); + if (ptr == NULL) { + LOG(LOG_ERROR, "error: not enough memory\n"); + return 0; } - /* select() returns the number of signalled sockets or -1 */ - res = select((int)sockfd + 1, &infd, &outfd, &errfd, &tv); - return res; + mem->memory = ptr; + memcpy(&(mem->memory[mem->size]), contents, realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + + return realsize; } -struct fdo_sock_handle { - int sockfd; -}; + /** * Read from curl buffer until new-line is encountered. * @@ -74,7 +72,7 @@ struct fdo_sock_handle { * @retval true if line read was successful, false otherwise. */ static bool read_until_new_line(char *out, size_t size, char *curl_buf, - size_t *curl_buf_offset) + size_t *curl_buf_offset) { size_t sz; char c; @@ -94,7 +92,8 @@ static bool read_until_new_line(char *out, size_t size, char *curl_buf, } else { // error out even if no new-line is encountered // if the sz grows larger than size - LOG(LOG_ERROR, "Exceeded expected size while reading socket\n"); + LOG(LOG_ERROR, + "Exceeded expected size while reading buffer\n"); return false; } @@ -147,7 +146,7 @@ int32_t fdo_con_setup(char *medium, char **params, uint32_t count) * @retval -1 on failure, 0 on success. */ int32_t fdo_con_dns_lookup(const char *url, fdo_ip_address_t **ip_list, - uint32_t *ip_list_size) + uint32_t *ip_list_size) { int idx; struct addrinfo *result = NULL, *it = NULL; @@ -204,8 +203,8 @@ int32_t fdo_con_dns_lookup(const char *url, fdo_ip_address_t **ip_list, (ip_list_temp + idx)->length = IPV4_ADDR_LEN; if (memcpy_s((ip_list_temp + idx)->addr, ip_list_temp->length, - &(sa_in->sin_addr.s_addr), - ip_list_temp->length) != 0) { + &(sa_in->sin_addr.s_addr), + ip_list_temp->length) != 0) { LOG(LOG_ERROR, "Memcpy failed\n"); goto end; } @@ -246,7 +245,7 @@ bool fdo_curl_proxy(fdo_ip_address_t *ip_addr, uint16_t port) goto err; } - if (ip_addr->addr) { + if (ip_addr) { ip_ascii = fdo_alloc(IP_TAG_LEN); if (!ip_ascii) { goto err; @@ -257,25 +256,29 @@ bool fdo_curl_proxy(fdo_ip_address_t *ip_addr, uint16_t port) } } - if (snprintf_s_si(proxy_url, HTTP_MAX_URL_SIZE, "%s:%d", - ip_ascii, port) < 0) { + if (snprintf_s_si(proxy_url, HTTP_MAX_URL_SIZE, "%s:%d", ip_ascii, + port) < 0) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto err; } if (curl) { - if (curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1) != CURLE_OK) { - LOG(LOG_ERROR, "CURL_PROXY: Cannot set HTTP proxy tunnel.\n"); + if (curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1) != + CURLE_OK) { + LOG(LOG_ERROR, + "CURL_PROXY: Cannot set HTTP proxy tunnel.\n"); goto err; } - if (curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1) != CURLE_OK) { + if (curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1) != + CURLE_OK) { LOG(LOG_ERROR, "CURL_PROXY: Cannot redirect proxy.\n"); goto err; } - if (curl_easy_setopt(curl, CURLOPT_PROXY, proxy_url) != CURLE_OK) { + if (curl_easy_setopt(curl, CURLOPT_PROXY, proxy_url) != + CURLE_OK) { LOG(LOG_ERROR, "CURL_PROXY: Cannot set proxy.\n"); goto err; } @@ -298,22 +301,25 @@ bool fdo_curl_proxy(fdo_ip_address_t *ip_addr, uint16_t port) } /** - * fdo_curl_setup connects to the given ip_addr via curl API + * fdo_curl_connect connects to the given ip_addr via curl API * * @param ip_addr - pointer to IP address info + * @param dn: Domain name of the server * @param port - port number to connect * @param tls: flag describing whether HTTP (false) or HTTPS (true) is - * @return connection handle on success. -ve value on failure + * @return 0 on success. -1 on failure */ -int fdo_curl_setup(fdo_ip_address_t *ip_addr, uint16_t port, bool tls) +int32_t fdo_curl_connect(fdo_ip_address_t *ip_addr, const char *dn, + uint16_t port, bool tls) { CURLcode res; - curl_socket_t sockfd; CURLcode curlCode = CURLE_OK; int ret = -1; - char temp[HTTP_MAX_URL_SIZE] = {0}; + char temp[2 * HTTP_MAX_URL_SIZE] = {0}; char url[HTTP_MAX_URL_SIZE] = {0}; char *ip_ascii = NULL; + struct curl_slist *host = NULL; + bool enable_sni = false; if (!ip_addr) { goto err; @@ -331,7 +337,7 @@ int fdo_curl_setup(fdo_ip_address_t *ip_addr, uint16_t port, bool tls) } } - if (ip_addr->addr) { + if (ip_addr) { ip_ascii = fdo_alloc(IP_TAG_LEN); if (!ip_ascii) { goto err; @@ -342,39 +348,37 @@ int fdo_curl_setup(fdo_ip_address_t *ip_addr, uint16_t port, bool tls) } } - if (snprintf_s_si(temp, HTTP_MAX_URL_SIZE, "%s:%d", - ip_ascii, port) < 0) { - LOG(LOG_ERROR, "Snprintf() failed!\n"); - goto err; - } - - if (strcat_s(url, HTTP_MAX_URL_SIZE, temp) != 0) { - LOG(LOG_ERROR, "Strcat() failed!\n"); - goto err; - } - if (curl) { if (tls) { // we are directed to enforce TLS - char *ciphers_list = "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:" - "TLS_AES_128_CCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:" - "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" - "ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-GCM-SHA256"; - - curl_version_info_data * vinfo = curl_version_info(CURLVERSION_NOW); - if (CURL_VERSION_SSL == (vinfo->features & CURL_VERSION_SSL)) { + char *ciphers_list = + "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:" + "TLS_AES_128_CCM_SHA256:TLS_CHACHA20_POLY1305_" + "SHA256:" + "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-" + "GCM-SHA384:" + "ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-GCM-" + "SHA256"; + + curl_version_info_data *vinfo = + curl_version_info(CURLVERSION_NOW); + if (CURL_VERSION_SSL == + (vinfo->features & CURL_VERSION_SSL)) { // SSL support enabled - LOG(LOG_INFO, "SSL support verified.\n"); + LOG(LOG_DEBUG, "SSL support verified.\n"); } - // Add option to force the https TLS connection to TLS v1.2 - curlCode = curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); + // Add option to force the https TLS connection to TLS + // v1.2 + curlCode = curl_easy_setopt(curl, CURLOPT_SSLVERSION, + CURL_SSLVERSION_TLSv1_2); if (curlCode != CURLE_OK) { goto err; } // Add option to allow recommended ciphers list - curlCode = curl_easy_setopt(curl, CURLOPT_SSL_CIPHER_LIST, ciphers_list); + curlCode = curl_easy_setopt( + curl, CURLOPT_SSL_CIPHER_LIST, ciphers_list); if (curlCode != CURLE_OK) { goto err; } @@ -383,66 +387,120 @@ int fdo_curl_setup(fdo_ip_address_t *ip_addr, uint16_t port, bool tls) if (useSelfSignedCerts) { // Add options if using self-signed certificates curlCode = CURLE_OK; - curlCode = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curlCode = curl_easy_setopt( + curl, CURLOPT_SSL_VERIFYPEER, 0L); if (curlCode != CURLE_OK) { - LOG(LOG_ERROR, "CURL_ERROR: Could not disable verify peer.\n"); + LOG(LOG_ERROR, + "CURL_ERROR: Could not disable " + "verify peer.\n"); goto err; } - curlCode = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + curlCode = curl_easy_setopt( + curl, CURLOPT_SSL_VERIFYHOST, 0L); if (curlCode != CURLE_OK) { - LOG(LOG_ERROR, "CURL_ERROR: Could not disable verify host.\n"); + LOG(LOG_ERROR, + "CURL_ERROR: Could not disable " + "verify host.\n"); goto err; } - LOG(LOG_INFO, "Set connection for self signed certificate usage.\n"); } #endif - curlCode = curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL); + curlCode = curl_easy_setopt(curl, CURLOPT_USE_SSL, + CURLUSESSL_ALL); if (curlCode != CURLE_OK) { - LOG(LOG_ERROR, "CURL_ERROR: Could not enable ssl.\n"); + LOG(LOG_ERROR, + "CURL_ERROR: Could not enable ssl.\n"); goto err; } + } +#if defined(SNI_SUPPORTED) + if (dn && tls) { + enable_sni = true; + } +#endif + if (enable_sni) { + LOG(LOG_DEBUG, "Using DNS\n"); + if (snprintf_s_si(temp, HTTP_MAX_URL_SIZE, "%s:%d", + (char *)dn, port) < 0) { + LOG(LOG_ERROR, "Snprintf() failed!\n"); + goto err; + } + if (strcat_s(url, HTTP_MAX_URL_SIZE, temp) != 0) { + LOG(LOG_ERROR, "Strcat() failed!\n"); + goto err; + } + if (strcat_s(temp, 2 * HTTP_MAX_URL_SIZE, ":") != 0) { + LOG(LOG_ERROR, "Strcat() failed!\n"); + goto err; + } + if (strcat_s(temp, 2 * HTTP_MAX_URL_SIZE, ip_ascii) != + 0) { + LOG(LOG_ERROR, "Strcat() failed!\n"); + goto err; + } + host = curl_slist_append(NULL, temp); + if (host == NULL) { + LOG(LOG_ERROR, + "CURL_ERROR: failed to append list.\n"); + goto err; + } + curlCode = + curl_easy_setopt(curl, CURLOPT_RESOLVE, host); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: failure to set dns " + "resolve config.\n"); + goto err; + } + } else { + (void)dn; + LOG(LOG_DEBUG, "Using IP\n"); + if (snprintf_s_si(temp, HTTP_MAX_URL_SIZE, "%s:%d", + ip_ascii, port) < 0) { + LOG(LOG_ERROR, "Snprintf() failed!\n"); + goto err; + } + if (strcat_s(url, HTTP_MAX_URL_SIZE, temp) != 0) { + LOG(LOG_ERROR, "Strcat() failed!\n"); + goto err; + } } curlCode = curl_easy_setopt(curl, CURLOPT_URL, url); if (curlCode != CURLE_OK) { - LOG(LOG_ERROR, "CURL_ERROR: Could not able to pass url.\n"); + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass url.\n"); goto err; } - /* Do not do the transfer - only connect to host */ curlCode = curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L); if (curlCode != CURLE_OK) { - LOG(LOG_ERROR, "CURL_ERROR: Could not able connect to host.\n"); + LOG(LOG_ERROR, + "CURL_ERROR: Unable to connect to host.\n"); goto err; } - res = curl_easy_perform(curl); + res = curl_easy_perform(curl); if (res != CURLE_OK) { - LOG(LOG_ERROR,"Error: %s\n", curl_easy_strerror(res)); + LOG(LOG_ERROR, "Error: %s\n", curl_easy_strerror(res)); goto err; } - /* Extract the socket from the curl handle - we will need it for - waiting. */ - res = curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sockfd); - - if (res != CURLE_OK) { - LOG(LOG_ERROR, "Error: %s\n", curl_easy_strerror(res)); - goto err; + if (res == CURLE_OK) { + LOG(LOG_DEBUG, "Connect OK\n"); + ret = 0; } } else { goto err; } - ret = (int)sockfd; - err: if (ip_ascii) { fdo_free(ip_ascii); } - + if (host) { + curl_slist_free_all(host); + } if (ret < 0 && curl) { curl_easy_cleanup(curl); } @@ -451,37 +509,31 @@ int fdo_curl_setup(fdo_ip_address_t *ip_addr, uint16_t port, bool tls) } /** - * fdo_con_connect connects to the network socket + * fdo_con_connect connects to the network * * @param ip_addr - pointer to IP address info + * @param dn: Domain name of the server * @param port - port number to connect * @param tls: flag describing whether HTTP (false) or HTTPS (true) is * @return connection handle on success. -ve value on failure */ -fdo_con_handle fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, - bool tls) +int32_t fdo_con_connect(fdo_ip_address_t *ip_addr, const char *dn, + uint16_t port, bool tls) { - struct fdo_sock_handle *sock_hdl = FDO_CON_INVALID_HANDLE; + int connect_ok = -1; if (!ip_addr) { goto end; } - /* Allocate memory for sock handle */ - sock_hdl = (struct fdo_sock_handle *)fdo_alloc(sizeof(*sock_hdl)); - if (!sock_hdl) { - LOG(LOG_ERROR, "Out of memory for sock handle\n"); - goto end; - } - #ifdef USE_MBEDTLS if (ssl) { char ipv4[IP_TAG_LEN] = {0}; char port_s[MAX_PORT_SIZE] = {0}; uint8_t octlet_size = - 4; // e.g 192.168.0.100, max 3char + 1null/oct. + 4; // e.g 192.168.0.100, max 3char + 1null/oct. if (!ip_addr) { goto end; @@ -492,16 +544,16 @@ fdo_con_handle fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, * mbed connect */ if ((snprintf_s_i(ipv4, octlet_size, "%d", ip_addr->addr[0]) < - 0) || - (snprintf_s_i((ipv4 + strnlen_s(ipv4, IP_TAG_LEN)), - octlet_size + 1, ".%d", - ip_addr->addr[1]) < 0) || - (snprintf_s_i((ipv4 + strnlen_s(ipv4, IP_TAG_LEN)), - octlet_size + 1, ".%d", - ip_addr->addr[2]) < 0) || - (snprintf_s_i((ipv4 + strnlen_s(ipv4, IP_TAG_LEN)), - octlet_size + 1, ".%d", - ip_addr->addr[3]) < 0)) { + 0) || + (snprintf_s_i((ipv4 + strnlen_s(ipv4, IP_TAG_LEN)), + octlet_size + 1, ".%d", + ip_addr->addr[1]) < 0) || + (snprintf_s_i((ipv4 + strnlen_s(ipv4, IP_TAG_LEN)), + octlet_size + 1, ".%d", + ip_addr->addr[2]) < 0) || + (snprintf_s_i((ipv4 + strnlen_s(ipv4, IP_TAG_LEN)), + octlet_size + 1, ".%d", + ip_addr->addr[3]) < 0)) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto end; } @@ -514,8 +566,8 @@ fdo_con_handle fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, if (NULL == *ssl) { LOG(LOG_ERROR, "TLS connection " - "setup " - "failed\n"); + "setup " + "failed\n"); goto end; } return MBEDTLS_NET_DUMMY_SOCKET; @@ -523,50 +575,31 @@ fdo_con_handle fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, #endif #if defined(USE_OPENSSL) - sock_hdl->sockfd = fdo_curl_setup(ip_addr, port, tls); - if (sock_hdl->sockfd < 0) { + connect_ok = fdo_curl_connect(ip_addr, dn, port, tls); + if (connect_ok < 0) { goto end; } - #endif - - return sock_hdl; - end: - if (sock_hdl) { - fdo_free(sock_hdl); - } - return FDO_CON_INVALID_HANDLE; + return connect_ok; } /** * Disconnect the connection for a given connection handle. * - * @param handle - connection handler (for ex: socket-id) * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_disconnect(fdo_con_handle handle) +int32_t fdo_con_disconnect(void) { - int sockfd = 0, ret = -1; - struct fdo_sock_handle *sock_hdl = handle; - - if (!sock_hdl) { - return 0; - } - - sockfd = sock_hdl->sockfd; - + int ret = -1; #ifdef USE_MBEDTLS return 0; #endif // close() returns 0 on success - if (sock_hdl) { - if (sockfd && curl) { - curl_easy_cleanup(curl); - ret = 0; - } - fdo_free(sock_hdl); + if (curl) { + curl_easy_cleanup(curl); + ret = 0; } return ret; } @@ -575,11 +608,11 @@ int32_t fdo_con_disconnect(fdo_con_handle handle) * Check the REST header for given REST response buffer and offset. * * @param[in] curl_buf: Input buffer that contains the REST header - * @param[in] header_start_offset: offset in the buffer that points to the start of REST header + * @param[in] header_start_offset: offset in the buffer that points to the start + * of REST header * @retval true if header is valid and complete and false otherwise. */ -bool has_header(char *buf, - size_t header_start_offset) +bool has_header(char *buf, size_t header_start_offset) { char tmp[REST_MAX_MSGHDR_SIZE]; size_t cur_offset = header_start_offset; @@ -589,17 +622,19 @@ bool has_header(char *buf, LOG(LOG_ERROR, "Memset() failed!\n"); goto err; } - if (!read_until_new_line(tmp, REST_MAX_MSGHDR_SIZE, buf, &cur_offset)) { + if (!read_until_new_line(tmp, REST_MAX_MSGHDR_SIZE, buf, + &cur_offset)) { goto err; } // end of header - if ((header_start_offset < cur_offset) && (tmp[0] == get_rest_hdr_body_separator())) { + if ((header_start_offset < cur_offset) && + (tmp[0] == get_rest_hdr_body_separator())) { ret = true; break; } } - err: +err: return ret; } @@ -607,13 +642,14 @@ bool has_header(char *buf, * Get the message length from the given REST response buffer. * * @param[in] curl_buf: Input buffer that contains the REST header - * @param[in/out] cur_offset: offset in the buffer that initially points to the start of REST header. - * This gets updated to point to start of message body after successful parsing + * @param[in/out] cur_offset: offset in the buffer that initially points to the + * start of REST header. This gets updated to point to start of message body + * after successful parsing * @param[out] msglen: Message length as specified in the REST header - * @retval bool returns true for success and false in case of invalid/incomplete content/parsing failure. + * @retval bool returns true for success and false in case of invalid/incomplete + * content/parsing failure. */ -bool get_msg_length(char *curl_buf, - size_t *cur_offset, uint32_t *msglen) +bool get_msg_length(char *curl_buf, size_t *cur_offset, uint32_t *msglen) { char hdr[REST_MAX_MSGHDR_SIZE] = {0}; char tmp[REST_MAX_MSGHDR_SIZE]; @@ -626,7 +662,8 @@ bool get_msg_length(char *curl_buf, goto err; } - if (!read_until_new_line(tmp, REST_MAX_MSGHDR_SIZE, curl_buf, cur_offset)) { + if (!read_until_new_line(tmp, REST_MAX_MSGHDR_SIZE, curl_buf, + cur_offset)) { LOG(LOG_ERROR, "read_until_new_line() failed!\n"); goto err; } @@ -639,7 +676,7 @@ bool get_msg_length(char *curl_buf, tmplen = strnlen_s(tmp, REST_MAX_MSGHDR_SIZE); if (!tmplen || tmplen == REST_MAX_MSGHDR_SIZE) { LOG(LOG_ERROR, "Strlen() failed!\n") - goto err; + goto err; } // accumulate header content @@ -668,84 +705,83 @@ bool get_msg_length(char *curl_buf, goto err; } ret = true; - err: +err: return ret; } /** * Receive(read) protocol version, message type and length of rest body * - * @param handle - connection handler (for ex: socket-id) * @param protocol_version - out FDO protocol version * @param message_type - out message type of incoming FDO message. * @param msglen - out Number of received bytes. - * @param curl_buf: data buffer to read into msg received by curl. - * @param curl_buf_offset: pointer to track curl_buf. + * @param hdr_buf: header data buffer to parse msg received by curl. * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_recv_msg_header(fdo_con_handle handle, - uint32_t *protocol_version, - uint32_t *message_type, uint32_t *msglen, - char *curl_buf, size_t *curl_buf_offset) +int32_t fdo_con_parse_msg_header(uint32_t *protocol_version, + uint32_t *message_type, uint32_t *msglen, + char *hdr_buf) { int32_t ret = -1; - size_t curl_tmp_offset = *curl_buf_offset; + size_t hdr_offset = 0; rest_ctx_t *rest = NULL; - struct fdo_sock_handle *sock_hdl = handle; - int sockfd = sock_hdl->sockfd; - CURLcode res; - size_t nread; - int max_iteration = 100; - int itr = 0; - size_t nread_total = 0; - bool headerParsed = false; + char hdr[REST_MAX_MSGHDR_SIZE] = {0}; + char tmp[REST_MAX_MSGHDR_SIZE]; + size_t tmplen; + size_t hdrlen; - if (!protocol_version || !message_type || !msglen) { + if (!protocol_version || !message_type || !msglen || !hdr_buf) { goto err; } - LOG(LOG_DEBUG,"Reading response.\n"); + LOG(LOG_DEBUG, "Parsing received Header.\n"); - do { - nread = 0; - res = curl_easy_recv(curl, curl_buf + nread_total, - REST_MAX_MSGBODY_SIZE - nread_total, &nread); - nread_total += nread; - if (!headerParsed && nread_total && has_header(curl_buf, curl_tmp_offset)) { - // If we already received the header and not yet parsed the message length - if (!get_msg_length(curl_buf, &curl_tmp_offset, msglen)) { - LOG(LOG_ERROR, "Msg len parsing from REST Header failed!!\n"); - goto err; - } - headerParsed = true; + for (;;) { + if (memset_s(tmp, sizeof(tmp), 0) != 0) { + LOG(LOG_ERROR, "Memset() failed!\n"); + goto err; } - if (headerParsed && ((curl_tmp_offset+*msglen) <= (*curl_buf_offset+nread_total))) { - // expected total length is equal or included in already received buffer length - *curl_buf_offset = curl_tmp_offset; - // curl_buf_offset now points to the start of message body - break; + + if (!read_until_new_line(tmp, REST_MAX_MSGHDR_SIZE, hdr_buf, + &hdr_offset)) { + LOG(LOG_ERROR, "read_until_new_line() failed!\n"); + goto err; + } + + if (tmp[0] == get_rest_hdr_body_separator()) { + break; } - if (res == CURLE_AGAIN && !wait_on_socket(sockfd, 1, MAX_TIME_OUT)) { - LOG(LOG_ERROR,"Error: timeout.\n"); + tmplen = strnlen_s(tmp, REST_MAX_MSGHDR_SIZE); + if (!tmplen || tmplen == REST_MAX_MSGHDR_SIZE) { + LOG(LOG_ERROR, "Strlen() failed!\n") goto err; } - itr++; - } while ((res == CURLE_OK && nread ) || - (res == CURLE_AGAIN && itr < max_iteration)); - if (res != CURLE_OK) { - LOG(LOG_ERROR,"Error: %s\n", curl_easy_strerror(res)); - goto err; + // accumulate header content + if (strncat_s(hdr, REST_MAX_MSGHDR_SIZE, tmp, tmplen) != 0) { + LOG(LOG_ERROR, "Strcat() failed!\n"); + goto err; + } + + // append new line for convenient parsing in REST + if (strcat_s(hdr, REST_MAX_MSGHDR_SIZE, "\n") != 0) { + LOG(LOG_ERROR, "Strcat() failed!\n"); + goto err; + } } - if (nread_total == 0) { - LOG(LOG_ERROR,"No response recevied! \n"); + hdrlen = strnlen_s(hdr, REST_MAX_MSGHDR_SIZE); + if (!hdrlen || hdrlen == REST_MAX_MSGHDR_SIZE) { + LOG(LOG_ERROR, "hdr is not NULL terminated.\n"); goto err; } - LOG(LOG_DEBUG,"Received %" CURL_FORMAT_CURL_OFF_T " bytes.\n", - (curl_off_t)nread_total); + /* Process REST header and get content-length of body */ + if (!get_rest_content_length(hdr, hdrlen, msglen)) { + LOG(LOG_ERROR, "REST Header processing failed!!\n"); + goto err; + } rest = get_rest_context(); if (!rest) { @@ -768,60 +804,59 @@ int32_t fdo_con_recv_msg_header(fdo_con_handle handle, * * @param buf - data buffer to read into. * @param length - Number of received bytes. - * @param curl_buf: data buffer to read into msg received by curl. - * @param curl_buf_offset: pointer to track curl_buf. - * @retval -1 on failure, number of bytes read on success. + * @param body_buf: body data buffer to parse msg received by curl. + * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_recv_msg_body(uint8_t *buf, size_t length, char *curl_buf, - size_t curl_buf_offset) +int32_t fdo_con_parse_msg_body(uint8_t *buf, size_t length, char *body_buf) { int32_t ret = -1; - if (!buf || !length) { + if (!buf || !length || !body_buf) { goto err; } - if (memcpy_s(buf, length, curl_buf + curl_buf_offset, length)) { + if (memcpy_s(buf, length, body_buf, length)) { LOG(LOG_ERROR, "Failed to copy msg data in byte array\n"); goto err; } - ret = length; + ret = 0; err: return ret; } /** - * Send(write) data. - * - * @param handle - connection handler (for ex: socket-id) - * @param protocol_version - FDO protocol version - * @param message_type - message type of outgoing FDO message. - * @param buf - data buffer to write from. - * @param length - Number of sent bytes. - * @param tls: flag describing whether HTTP (false) or HTTPS (true) is - * @retval -1 on failure, number of bytes written. + * Send and Receive data. + * @param[in] protocol_version: FDO protocol version + * @param[in] message_type: message type of outgoing FDO message. + * @param[in] buf: data buffer to write from. + * @param[in] length: Number of sent bytes. + * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is + * @param[in] header_buf: header data buffer to read into msg received by curl. + * @param[in] body_buf: body data buffer to read into msg received by curl. + * @retval -1 on failure, 0 on success. */ -int32_t fdo_con_send_message(fdo_con_handle handle, uint32_t protocol_version, - uint32_t message_type, const uint8_t *buf, - size_t length, bool tls) +int32_t fdo_con_send_recv_message(uint32_t protocol_version, + uint32_t message_type, const uint8_t *buf, + size_t length, bool tls, char *header_buf, + char *body_buf) { int ret = -1; - int n; rest_ctx_t *rest = NULL; - char rest_hdr[REST_MAX_MSGHDR_SIZE] = {0}; - size_t header_len = 0; - int sockfd = 0; - struct fdo_sock_handle *sock_hdl = handle; + struct curl_slist *msg_header = NULL; + struct curl_slist *temp_msg_header = NULL; + CURLcode curlCode; + struct MemoryStruct temp_header_buf; + struct MemoryStruct temp_body_buf; + + init_string(&temp_header_buf); + init_string(&temp_body_buf); - if (!buf || !length || !sock_hdl) { + if (!buf || !length) { goto err; } - sockfd = sock_hdl->sockfd; - rest = get_rest_context(); - if (!rest) { LOG(LOG_ERROR, "REST context is NULL!\n"); goto err; @@ -835,141 +870,165 @@ int32_t fdo_con_send_message(fdo_con_handle handle, uint32_t protocol_version, rest->tls = true; } - if (!construct_rest_header(rest, rest_hdr, REST_MAX_MSGHDR_SIZE)) { + if (!construct_rest_header(rest, &msg_header) || msg_header == NULL) { LOG(LOG_ERROR, "Error during constrcution of REST hdr!\n"); goto err; } - header_len = strnlen_s(rest_hdr, REST_MAX_MSGHDR_SIZE); + if (length > REST_MAX_MSGHDR_SIZE) { + msg_header = curl_slist_append(msg_header, "Expect:"); + } - if (!header_len || header_len == REST_MAX_MSGHDR_SIZE) { - LOG(LOG_ERROR, "Strlen() failed!\n"); + curlCode = curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 0L); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Could not disable connect only.\n"); goto err; } - /* Send REST header */ - CURLcode res; - size_t nsent_total = 0; - LOG(LOG_DEBUG,"Sending REST header.\n"); - - do { - size_t nsent; - int max_iteration = 100; - int itr = 0; - do { - nsent = 0; - res = curl_easy_send(curl, rest_hdr + nsent_total, - header_len - nsent_total, &nsent); - nsent_total += nsent; - - if (res == CURLE_AGAIN && !wait_on_socket(sockfd, 0, MAX_TIME_OUT)) { - LOG(LOG_ERROR,"Error: timeout.\n"); - goto hdrerr; - } - itr++; - } while (res == CURLE_AGAIN && itr < max_iteration); +#if defined(MTLS) + curlCode = curl_easy_setopt(curl, CURLOPT_SSLCERT, (char *)SSL_CERT); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to select client " + "certificate.\n"); + goto err; + } - if (res != CURLE_OK) { - LOG(LOG_ERROR,"Error: %s\n", curl_easy_strerror(res)); - goto hdrerr; - } + curlCode = curl_easy_setopt(curl, CURLOPT_SSLKEY, (char *)SSL_KEY); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to select client key.\n"); + goto err; + } +#endif + + curlCode = curl_easy_setopt(curl, CURLOPT_URL, msg_header->data); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass url.\n"); + goto err; + } - LOG(LOG_DEBUG,"Sent %" CURL_FORMAT_CURL_OFF_T " bytes.\n", - (curl_off_t)nsent); + curlCode = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, msg_header); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass header.\n"); + goto err; + } - } while (nsent_total < header_len); - n = nsent_total; + curlCode = curl_easy_setopt(curl, CURLOPT_POST, 1L); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Could not set POST.\n"); + goto err; + } - if (n <= 0) { - LOG(LOG_ERROR, - "Curl send Failed, ret=%d, " - "errno=%d, %d\n", - n, errno, __LINE__); + curlCode = curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, length); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Could not set POST length.\n"); + goto err; + } - if (fdo_con_disconnect(handle)) { - LOG(LOG_ERROR, "Error during socket close()\n"); - goto hdrerr; - } - goto hdrerr; + curlCode = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass POST data.\n"); + goto err; + } - } else if ((size_t)n < header_len) { - LOG(LOG_ERROR, - "Rest Header write returns %d/%zu bytes\n", n, - header_len); - goto hdrerr; + curlCode = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Could not set follow location.\n"); + goto err; + } - } else { - LOG(LOG_DEBUG, - "Rest Header write returns %d/%zu bytes\n\n", n, - header_len); - } - - LOG(LOG_DEBUG, "REST:header(%zu):%s\n", header_len, rest_hdr); - - /* Send REST body */ - nsent_total = 0; - LOG(LOG_DEBUG,"Sending REST body.\n"); - - do { - size_t nsent; - int max_iteration = 100; - int itr = 0; - do { - nsent = 0; - res = curl_easy_send(curl, buf + nsent_total, - length - nsent_total, &nsent); - nsent_total += nsent; - - if (res == CURLE_AGAIN && !wait_on_socket(sockfd, 0, MAX_TIME_OUT)) { - LOG(LOG_ERROR,"Error: timeout.\n"); - goto bodyerr; - } - itr++; - } while (res == CURLE_AGAIN && itr < max_iteration); + curlCode = + curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass header " + "WriteMemoryCallback.\n"); + goto err; + } - if (res != CURLE_OK) { - LOG(LOG_ERROR,"Error: %s\n", curl_easy_strerror(res)); - goto bodyerr; - } + LOG(LOG_DEBUG, "\nSending REST header.\n\n"); + LOG(LOG_DEBUG, "REST:header\n"); - LOG(LOG_DEBUG,"Sent %" CURL_FORMAT_CURL_OFF_T " bytes.\n", - (curl_off_t)nsent); + temp_msg_header = msg_header; + while (temp_msg_header != NULL) { + LOG(LOG_DEBUG, "%s\n", temp_msg_header->data); + temp_msg_header = temp_msg_header->next; + } + LOG(LOG_DEBUG, "\n"); - } while (nsent_total < length); + curlCode = curl_easy_setopt(curl, CURLOPT_HEADERDATA, + (void *)&temp_header_buf); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass header buffer.\n"); + goto err; + } - n = nsent_total; + curlCode = + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass " + "WriteMemoryCallback.\n"); + goto err; + } - if (n <= 0) { - LOG(LOG_ERROR, - "Curl send Failed, ret=%d, " - "errno=%d, %d\n", - n, errno, __LINE__); + curlCode = + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&temp_body_buf); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to pass body buffer.\n"); + goto err; + } - if (fdo_con_disconnect(handle)) { - LOG(LOG_ERROR, "Error during socket close()\n"); - goto bodyerr; - } - goto bodyerr; + curlCode = curl_easy_setopt(curl, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Unable to suppress connect " + "headers.\n"); + goto err; + } - } else if ((size_t)n < length) { - LOG(LOG_ERROR, "Rest Body write returns %d/%zu bytes\n", - n, length); - goto bodyerr; +#ifdef DEBUG_LOGS + curlCode = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "CURL_ERROR: Could not enable curl logs.\n"); + goto err; + } +#endif - } else { - LOG(LOG_DEBUG, - "Rest Body write returns %d/%zu bytes\n\n", n, - length); + curlCode = curl_easy_perform(curl); + if (curlCode != CURLE_OK) { + LOG(LOG_ERROR, "Error: %s\n", curl_easy_strerror(curlCode)); + goto err; } - return n; + if (memcpy_s(header_buf, temp_header_buf.size, temp_header_buf.memory, + temp_header_buf.size)) { + LOG(LOG_ERROR, "Failed to copy msg data in byte array\n"); + goto err; + } -hdrerr: - LOG(LOG_ERROR, "REST Header write not successful!\n"); - goto err; -bodyerr: - LOG(LOG_ERROR, "REST Body write not successful!\n"); + if ((message_type >= FDO_DI_APP_START) && + (message_type < FDO_TYPE_ERROR)) { + if (memcpy_s(body_buf, temp_body_buf.size, temp_body_buf.memory, + temp_body_buf.size)) { + LOG(LOG_ERROR, + "Failed to copy msg data in byte array\n"); + goto err; + } + } + + ret = 0; err: + if (temp_header_buf.memory) { + free(temp_header_buf.memory); + temp_header_buf.size = 0; + } + + if (temp_body_buf.memory) { + free(temp_body_buf.memory); + temp_body_buf.size = 0; + } + + if (msg_header) { + curl_slist_free_all(msg_header); + } + return ret; } diff --git a/network/network_if_mbedos.c b/network/network_if_mbedos.c index 0ccf9717..4081180c 100644 --- a/network/network_if_mbedos.c +++ b/network/network_if_mbedos.c @@ -11,7 +11,7 @@ #include "util.h" #include "network_al.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "fdoprotctx.h" #include "fdonet.h" #include "safe_lib.h" @@ -283,7 +283,7 @@ int32_t fdo_con_recv_msg_header(fdo_con_handle handle, if (!hdrlen || hdrlen == REST_MAX_MSGHDR_SIZE) { LOG(LOG_ERROR, "hdr is not NULL terminated.\n"); goto err; - } + } /* Process REST header and get content-length of body */ if (!get_rest_content_length(hdr, hdrlen, msglen)) { diff --git a/network/rest_interface.c b/network/rest_interface.c index 15129bcb..6c71f9a5 100644 --- a/network/rest_interface.c +++ b/network/rest_interface.c @@ -11,7 +11,7 @@ #include "util.h" #include "network_al.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "fdoprotctx.h" #include #include "fdonet.h" @@ -202,21 +202,20 @@ bool ip_bin_to_ascii(fdo_ip_address_t *ip, char *ip_ascii) size_t temp_len = 0; for (int i = 0; i < 4; i++) { if (snprintf_s_i(temp + temp_len, octlet_size + 1, "%d.", - ip->addr[i]) < 0) { + ip->addr[i]) < 0) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto err; } temp_len = strnlen_s(temp, IP_TAG_LEN + 1); if (!temp_len || temp_len == IP_TAG_LEN + 1) { - LOG(LOG_ERROR, - "temp string is not NULL terminated.\n"); + LOG(LOG_ERROR, "temp string is not NULL terminated.\n"); goto err; } } // Remove the last '.' - temp[temp_len-1] = '\0'; + temp[temp_len - 1] = '\0'; if (strcpy_s(ip_ascii, temp_len, temp) != 0) { LOG(LOG_ERROR, "Strcpy() failed!\n"); @@ -232,20 +231,19 @@ bool ip_bin_to_ascii(fdo_ip_address_t *ip, char *ip_ascii) * REST header (POST URL) construction based on current REST context. * * @param rest_ctx - current REST context. - * @param g_URL - post URL output. + * @param hdr - REST header output. * @param post_url_len - post URL max length. * @retval true if header onstruction was successful, false otherwise. */ -bool construct_rest_header(rest_ctx_t *rest_ctx, char *g_URL, - size_t post_url_len) +bool construct_rest_header(rest_ctx_t *rest_ctx, struct curl_slist **msg_header) { char *ip_ascii = NULL; - char temp[HTTP_MAX_URL_SIZE] = {0}; - char temp1[256] = {0}; - char msgequals[] = ""; + char temp[REST_MAX_MSGHDR_SIZE] = {0}; + char g_URL[HTTP_MAX_URL_SIZE] = {0}; + char temp1[REST_MAX_MSGHDR_SIZE] = {0}; bool ret = false; - if (!rest_ctx || !g_URL || !post_url_len) { + if (!rest_ctx) { LOG(LOG_ERROR, "Invalid input!\n"); goto err; } @@ -262,12 +260,12 @@ bool construct_rest_header(rest_ctx_t *rest_ctx, char *g_URL, } if (rest_ctx->tls) { - if (strcpy_s(g_URL, post_url_len, "POST https://") != 0) { + if (strcpy_s(g_URL, HTTP_MAX_URL_SIZE, "https://") != 0) { LOG(LOG_ERROR, "Strcat() failed!\n"); goto err; } } else { - if (strcpy_s(g_URL, post_url_len, "POST http://") != 0) { + if (strcpy_s(g_URL, HTTP_MAX_URL_SIZE, "http://") != 0) { LOG(LOG_ERROR, "Strcat() failed!\n"); goto err; } @@ -275,14 +273,14 @@ bool construct_rest_header(rest_ctx_t *rest_ctx, char *g_URL, if (rest_ctx->host_dns) { /* DNS */ - if (snprintf_s_si(temp, sizeof(temp), "%s:%d", + if (snprintf_s_si(temp, REST_MAX_MSGHDR_SIZE, "%s:%d", rest_ctx->host_dns, rest_ctx->portno) < 0) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto err; } } else if (rest_ctx->host_ip && ip_ascii) { /* IP */ - if (snprintf_s_si(temp, sizeof(temp), "%s:%d", ip_ascii, + if (snprintf_s_si(temp, REST_MAX_MSGHDR_SIZE, "%s:%d", ip_ascii, rest_ctx->portno) < 0) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto err; @@ -292,103 +290,86 @@ bool construct_rest_header(rest_ctx_t *rest_ctx, char *g_URL, goto err; } - if (strcat_s(g_URL, post_url_len, temp) != 0) { + if (strcat_s(g_URL, HTTP_MAX_URL_SIZE, temp) != 0) { LOG(LOG_ERROR, "Strcat() failed!\n"); goto err; } - if (snprintf_s_i(temp, sizeof(temp), "/fdo/%d", rest_ctx->prot_ver) < - 0) { + if (snprintf_s_i(temp, REST_MAX_MSGHDR_SIZE, "/fdo/%d", + rest_ctx->prot_ver) < 0) { LOG(LOG_ERROR, "Snprintf failed!\n"); goto err; } - if (strcat_s(g_URL, post_url_len, temp) != 0) { + if (strcat_s(g_URL, HTTP_MAX_URL_SIZE, temp) != 0) { LOG(LOG_ERROR, "Strcat() failed!\n"); goto err; } - if (snprintf_s_i(temp, sizeof(temp), "/msg/%d", rest_ctx->msg_type) < - 0) { + if (snprintf_s_i(temp, REST_MAX_MSGHDR_SIZE, "/msg/%d", + rest_ctx->msg_type) < 0) { LOG(LOG_ERROR, "Snprintf failed!\n"); goto err; } - if (strcat_s(g_URL, post_url_len, temp) != 0) { + if (strcat_s(g_URL, HTTP_MAX_URL_SIZE, temp) != 0) { LOG(LOG_ERROR, "Strcat() failed!\n"); goto err; } - if (strcat_s(g_URL, post_url_len, " HTTP/1.1\r\n") != 0) { - LOG(LOG_ERROR, "Strcat() failed!\n"); - goto err; - } + *msg_header = curl_slist_append(*msg_header, g_URL); - if (memset_s(temp, sizeof(temp), 0) != 0) { + if (memset_s(temp, REST_MAX_MSGHDR_SIZE, 0) != 0) { ret = false; goto err; } if (rest_ctx->host_dns) { /* DNS */ - if (snprintf_s_si(temp, sizeof(temp), "HOST:%s:%d\r\n", + if (snprintf_s_si(temp, REST_MAX_MSGHDR_SIZE, "HOST:%s:%d", rest_ctx->host_dns, rest_ctx->portno) < 0) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto err; } } else if (rest_ctx->host_ip && ip_ascii) { /* IP */ - if (snprintf_s_si(temp, sizeof(temp), "HOST:%s:%d\r\n", + if (snprintf_s_si(temp, REST_MAX_MSGHDR_SIZE, "HOST:%s:%d", ip_ascii, rest_ctx->portno) < 0) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto err; } } - if (strcat_s(g_URL, post_url_len, temp) != 0) { - LOG(LOG_ERROR, "Strcat() failed!\n"); - goto err; - } + *msg_header = curl_slist_append(*msg_header, temp); + *msg_header = + curl_slist_append(*msg_header, "Content-type:application/cbor"); - if (snprintf_s_i(temp1, sizeof(temp1), - "Content-type:application/cbor\r\n" - "Content-length:%u\r\n_connection: keep-alive\r\n", + if (snprintf_s_i(temp1, REST_MAX_MSGHDR_SIZE, "Content-length:%u", rest_ctx->content_length) < 0) { LOG(LOG_ERROR, "Snprintf() failed!\n"); goto err; } + *msg_header = curl_slist_append(*msg_header, temp1); + *msg_header = curl_slist_append(*msg_header, "_connection: keep-alive"); - if (strcat_s(g_URL, post_url_len, temp1) != 0) { - LOG(LOG_ERROR, "Strcat() failed!\n"); + if (memset_s(temp, REST_MAX_MSGHDR_SIZE, 0) != 0) { + ret = false; goto err; } if (rest_ctx->authorization) { - if (strcat_s(g_URL, post_url_len, "Authorization:") != 0) { - LOG(LOG_ERROR, "Strcpy() failed!\n"); - goto err; - } - - if (strcat_s(g_URL, post_url_len, rest_ctx->authorization) != + if (strcat_s(temp, REST_MAX_MSGHDR_SIZE, "Authorization:") != 0) { - LOG(LOG_ERROR, "Strcat() failed!\n"); + LOG(LOG_ERROR, "Strcpy() failed!\n"); goto err; } - if (strcat_s(g_URL, post_url_len, "\r\n") != 0) { + if (strcat_s(temp, REST_MAX_MSGHDR_SIZE, + rest_ctx->authorization) != 0) { LOG(LOG_ERROR, "Strcat() failed!\n"); goto err; } - } - - if (strcat_s(g_URL, post_url_len, "\r\n") != 0) { - LOG(LOG_ERROR, "Strcat() failed!\n"); - goto err; - } - - if (strcat_s(g_URL, post_url_len, msgequals) != 0) { - LOG(LOG_ERROR, "Strcat() failed!\n"); - goto err; + *msg_header = curl_slist_append(*msg_header, temp); } ret = true; @@ -433,7 +414,7 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) goto err; } - for (counter = 0; counter < hdrlen; counter ++) { + for (counter = 0; counter < hdrlen; counter++) { if (!ISASCII(hdr[counter])) { LOG(LOG_ERROR, "Header contains non-ASCII values\n"); goto err; @@ -442,7 +423,7 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) rest->msg_type = 0; // GET HTTP reponse from header - if(strstr_s(hdr, hdrlen, "\n", 1, &rem)){ + if (strstr_s(hdr, hdrlen, "\n", 1, &rem)) { LOG(LOG_ERROR, "Error parsing resonse\n"); goto err; } @@ -466,7 +447,7 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) LOG(LOG_DEBUG, "REST: HTTP response line: %s\n", tmp); // validate HTTP response - if(strstr_s(tmp, tmplen, " ", 1, &p1)){ + if (strstr_s(tmp, tmplen, " ", 1, &p1)) { LOG(LOG_ERROR, "fdo_rest_run: Response line parse error\n"); goto err; @@ -477,7 +458,8 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) errno = 0; rcode = strtol(p1, &eptr, 10); if (!eptr || eptr == p1 || errno != 0) { - LOG(LOG_ERROR, "Invalid value read for Response Code\n"); + LOG(LOG_ERROR, + "Invalid value read for Response Code\n"); goto err; } @@ -487,7 +469,7 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) goto err; } - if(strstr_s(p1, p1_len, " ", 1, &p2)) { + if (strstr_s(p1, p1_len, " ", 1, &p2)) { LOG(LOG_DEBUG, "Response code %03ld\n", rcode); } else { *p2++ = 0; @@ -506,7 +488,7 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) // parse and process other header elements while (1) { - if(strstr_s(hdr, hdrlen, "\n", 1, &rem)) { + if (strstr_s(hdr, hdrlen, "\n", 1, &rem)) { break; } @@ -526,7 +508,7 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) hdr += tmplen; hdrlen -= tmplen; - if(strstr_s(tmp, tmplen, ":", 1, &p1)) { + if (strstr_s(tmp, tmplen, ":", 1, &p1)) { LOG(LOG_ERROR, "REST: HEADER parse error\n"); goto err; } @@ -543,7 +525,8 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) errno = 0; rest->content_length = strtol(p1, &eptr, 10); if (!eptr || eptr == p1 || errno != 0) { - LOG(LOG_ERROR, "Invalid value read for Content-length\n"); + LOG(LOG_ERROR, + "Invalid value read for Content-length\n"); goto err; } LOG(LOG_DEBUG, "Content-length: %zu\n", @@ -568,11 +551,13 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) &result_strcmpcase) == 0 && result_strcmpcase == 0) { if (rest->authorization) { - // currently received token can be compared against previously - // received token. - // however, do nothing for now since specification doesn't mandate us to - // the ONLY requirement is that the Client MUST cache the received token once - // and transmit the same in subsequent messages. + // currently received token can be compared + // against previously received token. however, + // do nothing for now since specification + // doesn't mandate us to the ONLY requirement is + // that the Client MUST cache the received token + // once and transmit the same in subsequent + // messages. } else { rest->authorization = strdup_s(p1); } @@ -596,11 +581,12 @@ bool get_rest_content_length(char *hdr, size_t hdrlen, uint32_t *cont_len) errno = 0; rest->msg_type = strtol(p1, &eptr, 10); if (!eptr || eptr == p1 || errno != 0) { - LOG(LOG_ERROR, "Invalid value read for Message-Type\n"); + LOG(LOG_ERROR, + "Invalid value read for Message-Type\n"); goto err; } - LOG(LOG_DEBUG, "Message-Type: %"PRIu32"\n", - rest->msg_type); + LOG(LOG_DEBUG, "Message-Type: %" PRIu32 "\n", + rest->msg_type); } else { /* TODO: This looks like dead code, remove this */ diff --git a/storage/CMakeLists.txt b/storage/CMakeLists.txt index 191ffdb6..94fab877 100644 --- a/storage/CMakeLists.txt +++ b/storage/CMakeLists.txt @@ -16,4 +16,10 @@ client_sdk_sources_with_lib( storage util.c ) +if (${DA} MATCHES tpm) + client_sdk_sources_with_lib( storage + linux/tpm2_nv_storage.c + ) +endif() + target_link_libraries(storage PUBLIC client_sdk_interface) diff --git a/storage/include/storage_al.h b/storage/include/storage_al.h index f2ffb1f0..f6c7e699 100644 --- a/storage/include/storage_al.h +++ b/storage/include/storage_al.h @@ -17,9 +17,16 @@ #include #include #include +#if defined(DEVICE_TPM20_ENABLED) +#include "tpm2_nv_storage.h" +#endif // platform HMAC and blob size +#if defined(DEVICE_TPM20_ENABLED) && defined(ECDSA384_DA) +#define PLATFORM_HMAC_SIZE BUFF_SIZE_48_BYTES +#else #define PLATFORM_HMAC_SIZE BUFF_SIZE_32_BYTES +#endif #define BLOB_CONTENT_SIZE BUFF_SIZE_4_BYTES typedef enum { @@ -42,6 +49,14 @@ size_t fdo_blob_size(const char *blob_name, fdo_sdk_blob_flags flags); int32_t create_hmac_normal_blob(void); +#if defined(DEVICE_TPM20_ENABLED) +int32_t fdo_tpm_read_nv(TPMI_RH_NV_INDEX nv, uint8_t *buffer, uint32_t length); + +int32_t fdo_tpm_write_nv(TPMI_RH_NV_INDEX nv, const uint8_t *buffer, + uint32_t length); + +size_t fdo_tpm_size_nv(TPMI_RH_NV_INDEX nv); +#endif #ifdef __cplusplus } // endof externc (CPP code) #endif diff --git a/storage/include/tpm2_nv_storage.h b/storage/include/tpm2_nv_storage.h new file mode 100644 index 00000000..2a833b24 --- /dev/null +++ b/storage/include/tpm2_nv_storage.h @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include +#include + +#define FDO_DCActive_NV_IDX 0x01D10000 +#define FDO_CRED_NV_IDX 0x01D10001 +#define TPM_DEVICE_KEY_PERSISTANT_HANDLE 0x81020002 +#define TPM_HMAC_KEY_PERSISTANT_HANDLE 0x81020003 +#define TPM_DEVICE_CSR_NV_IDX 0x01D10005 + +#if defined(ECDSA256_DA) +#define FDO_TPM2_ALG_SHA TPM2_ALG_SHA256 +#else +#define FDO_TPM2_ALG_SHA TPM2_ALG_SHA384 +#endif + +/** Define space at NV index. + * + * @param[in] nv NV index to delete. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvdefine(TPMI_RH_NV_INDEX nv, size_t data_size); + +/** Store a data in a NV index. + * + * @param[in] data Key to store to NVRAM. + * @param[in] data_size Size of the data. + * @param[in] nv NV index to store the data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvwrite(const uint8_t *data, size_t data_size, TPMI_RH_NV_INDEX nv); + +/** Lock the NV index for further writes. + * + * @param[in] nv NV index to store the data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvwrite_lock(TPMI_RH_NV_INDEX nv); + +/** Load data size from a NV index. + * + * @param[in] nv NV index of the data. + * @retval data size on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +size_t fdo_tpm_nvread_size(TPMI_RH_NV_INDEX nv); + +/** Load a data from a NV index. + * + * @param[in] nv NV index of the data. + * @param[out] data Loaded data. + * @param[out] data_size Size of the data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvread(TPMI_RH_NV_INDEX nv, size_t data_size, uint8_t **data); + +/** Lock the NV index for further reads. + * + * @param[in] nv NV index to store the data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvread_lock(TPMI_RH_NV_INDEX nv); + +/** Delete data from a NV index. + * + * @param[in] nv NV index to delete. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvdel(TPMI_RH_NV_INDEX nv); \ No newline at end of file diff --git a/storage/linux/platform_utils_if_linux.c b/storage/linux/platform_utils_if_linux.c index baa0e4c9..f6ca2a0f 100644 --- a/storage/linux/platform_utils_if_linux.c +++ b/storage/linux/platform_utils_if_linux.c @@ -11,7 +11,7 @@ #include #include "util.h" #include "safe_lib.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "platform_utils.h" /** * Generate platform IV (if not already generated) else provide already @@ -111,7 +111,9 @@ bool get_platform_iv(uint8_t *iv, size_t len, size_t datalen) end: if (fp) { - fclose(fp); + if (fclose(fp) == EOF) { + LOG(LOG_INFO, "Fclose Failed"); + } } if (p_iv) { fdo_free(p_iv); @@ -152,7 +154,7 @@ bool get_platform_aes_key(uint8_t *key, size_t len) len); if (crypto_hal_random_bytes(key, - PLATFORM_AES_KEY_DEFAULT_LEN)) { + PLATFORM_AES_KEY_DEFAULT_LEN)) { LOG(LOG_ERROR, "Generating random platform AES Key failed!\n"); goto end; @@ -185,7 +187,9 @@ bool get_platform_aes_key(uint8_t *key, size_t len) end: if (fp) { - fclose(fp); + if (fclose(fp) == EOF) { + LOG(LOG_INFO, "Fclose Failed"); + } } return retval; } @@ -222,7 +226,7 @@ bool get_platform_hmac_key(uint8_t *key, size_t len) len); if (crypto_hal_random_bytes(key, - PLATFORM_HMAC_KEY_DEFAULT_LEN)) { + PLATFORM_HMAC_KEY_DEFAULT_LEN)) { LOG(LOG_ERROR, "Generating random platform HMAC Key failed!\n"); goto end; @@ -255,7 +259,9 @@ bool get_platform_hmac_key(uint8_t *key, size_t len) end: if (fp) { - fclose(fp); + if (fclose(fp) == EOF) { + LOG(LOG_INFO, "Fclose Failed"); + } } return retval; } diff --git a/storage/linux/storage_if_linux.c b/storage/linux/storage_if_linux.c index 50aa843a..1aaa2990 100644 --- a/storage/linux/storage_if_linux.c +++ b/storage/linux/storage_if_linux.c @@ -16,10 +16,13 @@ #include #include "safe_lib.h" #include "util.h" -#include "fdoCryptoHal.h" -#include "fdoCrypto.h" +#include "fdo_crypto_hal.h" +#include "fdo_crypto.h" #include "crypto_utils.h" #include "platform_utils.h" +#if defined(DEVICE_TPM20_ENABLED) +#include "tpm20_Utils.h" +#endif /**************************************************** * @@ -52,15 +55,16 @@ * Note: FDO_SDK_OTP_DATA flag is not supported for this platform. * @param name - pointer to the blob/file name * @param flags - descriptor telling type of file -* @return file size on success, 0 if file does not exist or on other failure + * @return file size on success, 0 if file does not exist or on other failure */ size_t fdo_blob_size(const char *name, fdo_sdk_blob_flags flags) { size_t retval = 0; - const size_t NORMAL_BLOB_OVERHEAD = PLATFORM_HMAC_SIZE + BLOB_CONTENT_SIZE; - const size_t SECURE_BLOB_OVERHEAD = AES_TAG_LEN + - PLATFORM_IV_DEFAULT_LEN + BLOB_CONTENT_SIZE; + const size_t NORMAL_BLOB_OVERHEAD = + PLATFORM_HMAC_SIZE + BLOB_CONTENT_SIZE; + const size_t SECURE_BLOB_OVERHEAD = + AES_TAG_LEN + PLATFORM_IV_DEFAULT_LEN + BLOB_CONTENT_SIZE; if (!name) { LOG(LOG_ERROR, "Invalid parameters!\n"); @@ -93,7 +97,8 @@ size_t fdo_blob_size(const char *name, fdo_sdk_blob_flags flags) if (retval >= NORMAL_BLOB_OVERHEAD) { retval -= NORMAL_BLOB_OVERHEAD; } else { - /* File format is not correct, not enough data in the file */ + /* File format is not correct, not enough data in the + * file */ retval = 0; } break; @@ -106,7 +111,8 @@ size_t fdo_blob_size(const char *name, fdo_sdk_blob_flags flags) if (retval >= SECURE_BLOB_OVERHEAD) { retval -= SECURE_BLOB_OVERHEAD; } else { - /* File format is not correct, not enough data in the file */ + /* File format is not correct, not enough data in the + * file */ retval = 0; } break; @@ -235,8 +241,11 @@ int32_t fdo_blob_read(const char *name, fdo_sdk_blob_flags flags, uint8_t *buf, } // compare HMAC - memcmp_s(stored_hmac, PLATFORM_HMAC_SIZE, computed_hmac, - PLATFORM_HMAC_SIZE, &strcmp_result); + if (memcmp_s(stored_hmac, PLATFORM_HMAC_SIZE, computed_hmac, + PLATFORM_HMAC_SIZE, &strcmp_result) != 0) { + LOG(LOG_ERROR, "Failed to compare HMAC\n"); + goto exit; + } if (strcmp_result != 0) { LOG(LOG_ERROR, "%s: HMACs do not compare!\n", __func__); goto exit; @@ -260,9 +269,8 @@ int32_t fdo_blob_read(const char *name, fdo_sdk_blob_flags flags, uint8_t *buf, * Sizeof_ciphertext(8 * bytes)||Ciphertet(n_bytes bytes)] */ - encrypted_data_len = PLATFORM_IV_DEFAULT_LEN + - AES_TAG_LEN + BLOB_CONTENT_SIZE + - n_bytes; + encrypted_data_len = PLATFORM_IV_DEFAULT_LEN + AES_TAG_LEN + + BLOB_CONTENT_SIZE + n_bytes; encrypted_data = fdo_alloc(encrypted_data_len); if (NULL == encrypted_data) { @@ -311,8 +319,8 @@ int32_t fdo_blob_read(const char *name, fdo_sdk_blob_flags flags, uint8_t *buf, goto exit; } - data = encrypted_data + PLATFORM_IV_DEFAULT_LEN + - AES_TAG_LEN + BLOB_CONTENT_SIZE; + data = encrypted_data + PLATFORM_IV_DEFAULT_LEN + AES_TAG_LEN + + BLOB_CONTENT_SIZE; if (!get_platform_aes_key(aes_key, PLATFORM_AES_KEY_DEFAULT_LEN)) { @@ -323,9 +331,9 @@ int32_t fdo_blob_read(const char *name, fdo_sdk_blob_flags flags, uint8_t *buf, // decrypt and authenticate cipher-text content and fill the // given buffer with clear-text if (crypto_hal_aes_decrypt( - buf, &n_bytes, data, data_length, 16, iv, - aes_key, PLATFORM_AES_KEY_DEFAULT_LEN, - stored_tag, AES_TAG_LEN, NULL, 0) < 0) { + buf, &n_bytes, data, data_length, 16, iv, aes_key, + PLATFORM_AES_KEY_DEFAULT_LEN, stored_tag, AES_TAG_LEN, + NULL, 0) < 0) { LOG(LOG_ERROR, "Decryption failed during Secure " "Blob Read!\n"); goto exit; @@ -460,9 +468,8 @@ int32_t fdo_blob_write(const char *name, fdo_sdk_blob_flags flags, * Sizeof_ciphertext(8 * bytes)||Ciphertet(n_bytes bytes)] */ - write_context_len = PLATFORM_IV_DEFAULT_LEN + - AES_TAG_LEN + BLOB_CONTENT_SIZE + - n_bytes; + write_context_len = PLATFORM_IV_DEFAULT_LEN + AES_TAG_LEN + + BLOB_CONTENT_SIZE + n_bytes; write_context = fdo_alloc(write_context_len); if (NULL == write_context) { @@ -481,17 +488,17 @@ int32_t fdo_blob_write(const char *name, fdo_sdk_blob_flags flags, goto exit; } - write_context_len_temp = write_context_len - (PLATFORM_IV_DEFAULT_LEN + - AES_TAG_LEN + BLOB_CONTENT_SIZE); + write_context_len_temp = + write_context_len - + (PLATFORM_IV_DEFAULT_LEN + AES_TAG_LEN + BLOB_CONTENT_SIZE); // encrypt plain-text and copy cipher-text content if (crypto_hal_aes_encrypt( buf, n_bytes, - &write_context[PLATFORM_IV_DEFAULT_LEN + - AES_TAG_LEN + BLOB_CONTENT_SIZE], - &write_context_len_temp, - 16, iv, aes_key, - PLATFORM_AES_KEY_DEFAULT_LEN, tag, - AES_TAG_LEN, NULL, 0) < 0) { + &write_context[PLATFORM_IV_DEFAULT_LEN + AES_TAG_LEN + + BLOB_CONTENT_SIZE], + &write_context_len_temp, 16, iv, aes_key, + PLATFORM_AES_KEY_DEFAULT_LEN, tag, AES_TAG_LEN, NULL, + 0) < 0) { LOG(LOG_ERROR, "Encypting data failed during Secure " "Blob write!\n"); goto exit; @@ -558,3 +565,278 @@ int32_t fdo_blob_write(const char *name, fdo_sdk_blob_flags flags, } return retval; } + +#if defined(DEVICE_TPM20_ENABLED) +/** + * fdo_tpm_size_nv Get specified FDO nv size + * @param nv - ptpm nv index + * @return file size on success, 0 if file does not exist or on other failure + */ + +size_t fdo_tpm_size_nv(TPMI_RH_NV_INDEX nv) +{ + size_t retval = 0; + const size_t NORMAL_NV_OVERHEAD = + PLATFORM_HMAC_SIZE + BLOB_CONTENT_SIZE; + + if (!nv) { + LOG(LOG_ERROR, "Invalid parameters!\n"); + goto end; + } + + /* Normal cred is stored as: + * [HMAC(32bytes)||data-content-size(4bytes)||data-content(?)] + */ + retval = fdo_tpm_nvread_size(nv); + + // Return 0 if the file is empty. + if (retval == 0) { + LOG(LOG_DEBUG, "NV is empty!\n"); + retval = 0; + goto end; + } + + if (retval >= NORMAL_NV_OVERHEAD) { + retval -= NORMAL_NV_OVERHEAD; + } else { + /* File format is not correct, not enough data in the + * file */ + retval = 0; + } + +end: + if (retval > R_MAX_SIZE) { + LOG(LOG_ERROR, "File size is more than R_MAX_SIZE\n"); + retval = 0; + } + return retval; +} + +/** + * fdo_blob_read Read FDO blob(file) into specified buffer, + * fdo_blob_read ensures authenticity & integrity for non-secure + * data & additionally confidentiality for secure data. + * Note: FDO_SDK_OTP_DATA flag is not supported for this platform. + * @param nv - tpm nv index + * @param flags - descriptor telling type of file + * @param buf - pointer to buf where data is read into + * @param n_bytes - length of data(in bytes) to be read + * @return num of bytes read if success, -1 on error + */ +int32_t fdo_tpm_read_nv(TPMI_RH_NV_INDEX nv, uint8_t *buf, uint32_t n_bytes) +{ + int retval = -1; + uint8_t *data = NULL; + uint32_t data_length = 0; + uint8_t *sealed_data = NULL; + uint32_t sealed_data_len = 0; + uint8_t stored_hmac[PLATFORM_HMAC_SIZE] = {0}; + uint8_t computed_hmac[PLATFORM_HMAC_SIZE] = {0}; + int strcmp_result = -1; + + if (!nv || !buf || n_bytes == 0) { + LOG(LOG_ERROR, "Invalid parameters in %s!\n", __func__); + goto exit; + } + + if (n_bytes > R_MAX_SIZE) { + LOG(LOG_ERROR, + "file read buffer is more than R_MAX_SIZE in " + "%s!\n", + __func__); + goto exit; + } + + if (nv == FDO_CRED_NV_IDX) { + /* HMAC-256 is being used to store files under + * FDO_SDK_NORMAL_DATA flag. + * File content to be stored as: + * [HMAC(32 bytes)||Sizeof_plaintext(4 bytes)||Plaintext(n_bytes + * bytes)] + */ + + sealed_data_len = + PLATFORM_HMAC_SIZE + BLOB_CONTENT_SIZE + n_bytes; + + sealed_data = fdo_alloc(sealed_data_len); + if (NULL == sealed_data) { + LOG(LOG_ERROR, "Malloc Failed in %s!\n", __func__); + goto exit; + } + + if (fdo_tpm_nvread(nv, sealed_data_len, &sealed_data)) { + LOG(LOG_ERROR, "Failed to read file!\n"); + goto exit; + } + + // get actual data length + data_length |= sealed_data[PLATFORM_HMAC_SIZE] << 24; + data_length |= sealed_data[PLATFORM_HMAC_SIZE + 1] << 16; + data_length |= sealed_data[PLATFORM_HMAC_SIZE + 2] << 8; + data_length |= + (sealed_data[PLATFORM_HMAC_SIZE + 3] & 0x000000FF); + + // check if input buffer is sufficient ? + if (n_bytes < data_length) { + LOG(LOG_ERROR, + "Failed to read data, Buffer is not enough, " + "buf_len:%d,\t Lengthstoredinfilesystem:%d\n", + n_bytes, data_length); + goto exit; + } + + if (memcpy_s(stored_hmac, PLATFORM_HMAC_SIZE, sealed_data, + PLATFORM_HMAC_SIZE) != 0) { + LOG(LOG_ERROR, + "Copying stored HMAC failed during " + "%s!\n", + __func__); + goto exit; + } + + data = sealed_data + PLATFORM_HMAC_SIZE + BLOB_CONTENT_SIZE; + + if (0 != fdo_tpm_get_hmac(data, data_length, computed_hmac, + PLATFORM_HMAC_SIZE, + TPM_HMAC_KEY_PERSISTANT_HANDLE)) { + LOG(LOG_ERROR, + "HMAC computation dailed during" + " %s!\n", + __func__); + goto exit; + } + + // compare HMAC + if (memcmp_s(stored_hmac, PLATFORM_HMAC_SIZE, computed_hmac, + PLATFORM_HMAC_SIZE, &strcmp_result) != 0) { + LOG(LOG_ERROR, "Failed to compare HMAC\n"); + goto exit; + } + if (strcmp_result != 0) { + LOG(LOG_ERROR, "%s: HMACs do not compare!\n", __func__); + goto exit; + } + + // copy data into supplied buffer + if (memcpy_s(buf, n_bytes, data, data_length) != 0) { + LOG(LOG_ERROR, + "%s: Copying data into " + "buffer failed!\n", + __func__); + goto exit; + } + } else { + if (0 != fdo_tpm_nvread(nv, n_bytes, &buf)) { + LOG(LOG_ERROR, "Failed to read file!\n"); + goto exit; + } + } + + retval = (int32_t)n_bytes; + +exit: + return retval; +} + +/** + * fdo_blob_write Write FDO blob(file) from specified buffer + * fdo_blob_write ensures integrity & authenticity for non-secure + * data & additionally confidentiality for secure data. + * Note: FDO_SDK_OTP_DATA flag is not supported for this platform. + * @param nv - ptpm nv index + * @param flags - descriptor telling type of file + * @param buf - pointer to buf from where data is read and then written + * @param n_bytes - length of data(in bytes) to be written + * @return num of bytes write if success, -1 on error + */ + +int32_t fdo_tpm_write_nv(TPMI_RH_NV_INDEX nv, const uint8_t *buf, + uint32_t n_bytes) +{ + int retval = -1; + uint32_t write_context_len = 0; + uint8_t *write_context = NULL; + + if (!buf || !nv || n_bytes == 0) { + LOG(LOG_ERROR, "Invalid parameters in %s!\n", __func__); + goto exit; + } + + if (n_bytes > R_MAX_SIZE) { + LOG(LOG_ERROR, + "file write buffer is more than R_MAX_SIZE in " + "%s!\n", + __func__); + goto exit; + } + + if (nv == FDO_CRED_NV_IDX) { + /* HMAC-256 is being used to store files under + * FDO_SDK_NORMAL_DATA flag. + * File content to be stored as: + * [HMAC(32 bytes)||Sizeof_plaintext(4 bytes)||Plaintext(n_bytes + * bytes)] + */ + write_context_len = + PLATFORM_HMAC_SIZE + BLOB_CONTENT_SIZE + n_bytes; + + write_context = fdo_alloc(write_context_len); + if (NULL == write_context) { + LOG(LOG_ERROR, "Malloc Failed in %s!\n", __func__); + goto exit; + } + + if (0 != fdo_tpm_get_hmac(buf, n_bytes, write_context, + PLATFORM_HMAC_SIZE, + TPM_HMAC_KEY_PERSISTANT_HANDLE)) { + LOG(LOG_ERROR, "Computing HMAC failed!\n"); + goto exit; + } + + // copy plain-text size + write_context[PLATFORM_HMAC_SIZE + 3] = n_bytes >> 0; + write_context[PLATFORM_HMAC_SIZE + 2] = n_bytes >> 8; + write_context[PLATFORM_HMAC_SIZE + 1] = n_bytes >> 16; + write_context[PLATFORM_HMAC_SIZE + 0] = n_bytes >> 24; + + // copy plain-text content + if (memcpy_s(write_context + PLATFORM_HMAC_SIZE + + BLOB_CONTENT_SIZE, + (write_context_len - PLATFORM_HMAC_SIZE - + BLOB_CONTENT_SIZE), + buf, n_bytes) != 0) { + LOG(LOG_ERROR, + "Copying data failed during Normal Blob write!\n"); + goto exit; + } + } else { + write_context_len = n_bytes; + + write_context = fdo_alloc(write_context_len); + if (NULL == write_context) { + LOG(LOG_ERROR, "Malloc Failed in %s!\n", __func__); + goto exit; + } + + if (memcpy_s(write_context, write_context_len, buf, n_bytes) != + 0) { + LOG(LOG_ERROR, + "Copying data failed during RAW Blob write!\n"); + goto exit; + } + } + + if (fdo_tpm_nvwrite(write_context, write_context_len, nv)) { + LOG(LOG_ERROR, "Failed to write in TPM NV!\n"); + goto exit; + } + + retval = (int32_t)n_bytes; + +exit: + if (write_context) { + fdo_free(write_context); + } + return retval; +} +#endif \ No newline at end of file diff --git a/storage/linux/tpm2_nv_storage.c b/storage/linux/tpm2_nv_storage.c new file mode 100644 index 00000000..9e67dca4 --- /dev/null +++ b/storage/linux/tpm2_nv_storage.c @@ -0,0 +1,747 @@ +#include "util.h" +#include "tpm2_nv_storage.h" +#include "safe_lib.h" + +/** + * Initialize Esys context. + * + * @param esys_context : output Esys Context + * + * @return + * TPM2_RC_SUCCESS, on success + * -1, on failure + */ +static int32_t fdo_tpm_esys_context_init(ESYS_CONTEXT **esys_context) +{ + int ret = -1; + TSS2_TCTI_CONTEXT *tcti_context = NULL; + + if ((TSS2_RC_SUCCESS != + Tss2_TctiLdr_Initialize(TPM2_TCTI_TYPE, &tcti_context)) || + (!tcti_context)) { + LOG(LOG_ERROR, "TCTI Context initialization failed.\n"); + goto err; + } + + if (Esys_Initialize(esys_context, tcti_context, NULL) != + TPM2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + return TPM2_RC_SUCCESS; + +err: + if (tcti_context) { + Tss2_TctiLdr_Finalize(&tcti_context); + } + return ret; +} + +/** + * Create HMAC based auth session for Esys Context + * + * @param esys_context : input Esys Context + * @param session_handle : output authentication session Handle + * + * @return + * TPM2_RC_SUCCESS, on success + * -1, on failure + */ +static int32_t fdo_tpm_esys_auth_session_init(ESYS_CONTEXT *esys_context, + ESYS_TR *session_handle) +{ + int ret = -1; + TSS2_RC rval; + TPMT_SYM_DEF symmetric = {.algorithm = TPM2_ALG_AES, + .keyBits = {.aes = 128}, + .mode = {.aes = TPM2_ALG_CFB}}; + + rval = Esys_StartAuthSession(esys_context, ESYS_TR_NONE, ESYS_TR_NONE, + ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, + NULL, TPM2_SE_HMAC, &symmetric, + FDO_TPM2_ALG_SHA, session_handle); + + if (rval != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start the auth session.\n"); + return ret; + } + + rval = Esys_TRSess_SetAttributes(esys_context, *session_handle, + TPMA_SESSION_DECRYPT | + TPMA_SESSION_ENCRYPT | + TPMA_SESSION_CONTINUESESSION, + 0xff); + if (rval != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to Set session attributes.\n"); + return ret; + } + + return rval; +} + +/** + * Clear Esys, TCTI, contexts and Auth Session, Primary Key handles. + * + * @param esys_context : Esys Context to be cleared + * @param auth_session_handle : Auth session Handle to be flushed + * @param nv_handle : NV handle to be cleared + * @return + * 0, on success + * -1, on failure + */ +static int32_t fdo_tpm_context_clean_up(ESYS_CONTEXT **esys_context, + ESYS_TR *auth_session_handle, + ESYS_TR *nv_handle) +{ + int ret = -1, is_failed = 0; + TSS2_TCTI_CONTEXT *tcti_context = NULL; + TSS2_RC rc = TPM2_RC_FAILURE; + + if (!esys_context || !*esys_context) { + LOG(LOG_ERROR, "Invalid parameter received.\n"); + return ret; + } + + if (auth_session_handle && (*auth_session_handle != ESYS_TR_NONE)) { + if (Esys_FlushContext(*esys_context, *auth_session_handle) != + TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, + "Failed to flush auth session handle.\n"); + is_failed = 1; + } else { + LOG(LOG_DEBUG, + "Auth session handle flushed successfully.\n"); + *auth_session_handle = ESYS_TR_NONE; + } + } + + if (nv_handle && (*nv_handle != ESYS_TR_NONE)) { + if (Esys_TR_Close(*esys_context, nv_handle) != + TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to flush primary key handle.\n"); + is_failed = 1; + } else { + LOG(LOG_DEBUG, + "Primary key handle flushed successfully.\n"); + *nv_handle = ESYS_TR_NONE; + } + } + + rc = Esys_GetTcti(*esys_context, &tcti_context); + if (rc != TPM2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to cleanup TCTI.\n"); + is_failed = 1; + } + Esys_Finalize(esys_context); + + if (tcti_context) { + Tss2_TctiLdr_Finalize(&tcti_context); + if (tcti_context) { + LOG(LOG_ERROR, "Failed to finalize context.\n"); + is_failed = 1; + } + } + + if (is_failed) { + return ret; + } + + return 0; +} + +/** Define space at NV index. + * + * @param[in] nv NV index to delete. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvdefine(TPMI_RH_NV_INDEX nv, size_t data_size) +{ + + if (!nv) { + return -1; + } + + int ret = -1; + TSS2_RC rc; + ESYS_CONTEXT *ctx; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_AUTH emptyAuth = { + .size = 0, + }; + + TPM2B_NV_PUBLIC publicInfo = { + .size = 0, + .nvPublic = { + .nvIndex = nv, + .nameAlg = FDO_TPM2_ALG_SHA, + .attributes = + (TPMA_NV_OWNERWRITE | TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | + TPMA_NV_OWNERREAD | TPMA_NV_NO_DA | TPMA_NV_READ_STCLEAR | + TPMA_NV_WRITE_STCLEAR | TPMA_NV_WRITEDEFINE), + .authPolicy = + { + .size = 0, + .buffer = {0}, + }, + .dataSize = data_size, + }}; + + rc = fdo_tpm_esys_context_init(&ctx); + if (rc != TSS2_RC_SUCCESS || !ctx) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + rc = fdo_tpm_esys_auth_session_init(ctx, &auth_session_handle); + if (rc != TSS2_RC_SUCCESS || !auth_session_handle) { + LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); + goto err; + } + + rc = Esys_Startup(ctx, TPM2_SU_CLEAR); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start Esys context.\n"); + goto err; + } + + // Search the NV index + TPMS_CAPABILITY_DATA *capability_data = NULL; + rc = + Esys_GetCapability(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, + TPM2_CAP_HANDLES, nv, 1, NULL, &capability_data); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Esys_GetCapability failed!\n"); + goto err; + } + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); + if (exists == 1) { + LOG(LOG_DEBUG, "NV index already exist.\n"); + ret = 0; + goto err; + } + + rc = Esys_NV_DefineSpace(ctx, ESYS_TR_RH_OWNER, auth_session_handle, + ESYS_TR_NONE, ESYS_TR_NONE, &emptyAuth, + &publicInfo, &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to define Esys NV space.\n"); + goto err; + } + + ret = 0; + +err: + + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + ret = -1; + } + + return ret; +} + +/** Store a data in a NV index. + * + * @param[in] data Key to store to NVRAM. + * @param[in] data_size Size of the data. + * @param[in] nv NV index to store the data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvwrite(const uint8_t *data, size_t data_size, TPMI_RH_NV_INDEX nv) +{ + if (!data || !nv) { + return -1; + } + + int ret = -1; + TSS2_RC rc; + ESYS_CONTEXT *ctx; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_AUTH emptyAuth = { + .size = 0, + }; + + TPM2B_NV_PUBLIC publicInfo = { + .size = 0, + .nvPublic = { + .nvIndex = nv, + .nameAlg = FDO_TPM2_ALG_SHA, + .attributes = + (TPMA_NV_OWNERWRITE | TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | + TPMA_NV_OWNERREAD | TPMA_NV_NO_DA | TPMA_NV_READ_STCLEAR | + TPMA_NV_WRITEDEFINE), + .authPolicy = + { + .size = 0, + .buffer = {0}, + }, + .dataSize = data_size, + }}; + + TPM2B_MAX_NV_BUFFER blob = {.size = data_size}; + if (blob.size > sizeof(blob.buffer)) { + LOG(LOG_ERROR, "Data too large.\n"); + return -1; + } + + if (memcpy_s(&blob.buffer[0], blob.size, data, data_size) != 0) { + LOG(LOG_ERROR, "Failed to copy data to blob!\n"); + goto err; + } + + rc = fdo_tpm_esys_context_init(&ctx); + if (rc != TSS2_RC_SUCCESS || !ctx) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + rc = fdo_tpm_esys_auth_session_init(ctx, &auth_session_handle); + if (rc != TSS2_RC_SUCCESS || !auth_session_handle) { + LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); + goto err; + } + + rc = Esys_Startup(ctx, TPM2_SU_CLEAR); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start Esys context.\n"); + goto err; + } + + // Search the NV index + TPMS_CAPABILITY_DATA *capability_data = NULL; + rc = + Esys_GetCapability(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, + TPM2_CAP_HANDLES, nv, 1, NULL, &capability_data); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Esys_GetCapability failed!\n"); + goto err; + } + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); + if (exists == 1) { + LOG(LOG_DEBUG, "NV index already exist. Deleting it.\n"); + rc = Esys_TR_FromTPMPublic(ctx, nv, auth_session_handle, + ESYS_TR_NONE, ESYS_TR_NONE, + &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, + "Failed to constructs an ESYS_TR object.\n"); + goto err; + } + rc = Esys_NV_UndefineSpace(ctx, ESYS_TR_RH_OWNER, nvHandle, + auth_session_handle, ESYS_TR_NONE, + ESYS_TR_NONE); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to undefine Esys NV space.\n"); + goto err; + } + } + + rc = Esys_NV_DefineSpace(ctx, ESYS_TR_RH_OWNER, auth_session_handle, + ESYS_TR_NONE, ESYS_TR_NONE, &emptyAuth, + &publicInfo, &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to define Esys NV space.\n"); + goto err; + } + + rc = Esys_NV_Write(ctx, nvHandle, nvHandle, auth_session_handle, + ESYS_TR_NONE, ESYS_TR_NONE, &blob, 0 /*=offset*/); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to write in Esys NV space.\n"); + goto err; + } + + ret = 0; + +err: + + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + ret = -1; + } + return ret; +} + +/** Lock the NV index for further writes. + * + * @param[in] nv NV index to store the data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvwrite_lock(TPMI_RH_NV_INDEX nv) +{ + if (!nv) { + return -1; + } + + int ret = -1; + TSS2_RC rc; + ESYS_CONTEXT *ctx; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + + rc = fdo_tpm_esys_context_init(&ctx); + if (rc != TSS2_RC_SUCCESS || !ctx) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + rc = fdo_tpm_esys_auth_session_init(ctx, &auth_session_handle); + if (rc != TSS2_RC_SUCCESS || !auth_session_handle) { + LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); + goto err; + } + + rc = Esys_Startup(ctx, TPM2_SU_CLEAR); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start Esys context.\n"); + goto err; + } + + rc = Esys_TR_FromTPMPublic(ctx, nv, auth_session_handle, ESYS_TR_NONE, + ESYS_TR_NONE, &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to constructs an ESYS_TR object.\n"); + goto err; + } + + rc = Esys_NV_WriteLock(ctx, ESYS_TR_RH_OWNER, nvHandle, + auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to lock NV write.\n"); + goto err; + } + + ret = 0; + +err: + + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + ret = -1; + } + return ret; +} + +/** Load data size from a NV index. + * + * @param[in] nv NV index of the data. + * @retval data size on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +size_t fdo_tpm_nvread_size(TPMI_RH_NV_INDEX nv) +{ + int ret = -1; + TSS2_RC rc; + ESYS_CONTEXT *ctx; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_NV_PUBLIC *publicInfo = NULL; + size_t data_size; + + if (!nv) { + return -1; + } + + rc = fdo_tpm_esys_context_init(&ctx); + if (rc != TSS2_RC_SUCCESS || !ctx) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + rc = fdo_tpm_esys_auth_session_init(ctx, &auth_session_handle); + if (rc != TSS2_RC_SUCCESS || !auth_session_handle) { + LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); + goto err; + } + + rc = Esys_Startup(ctx, TPM2_SU_CLEAR); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start Esys API.\n"); + goto err; + } + + // Search the NV index + TPMS_CAPABILITY_DATA *capability_data = NULL; + rc = + Esys_GetCapability(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, + TPM2_CAP_HANDLES, nv, 1, NULL, &capability_data); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Esys_GetCapability failed!\n"); + goto err; + } + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); + if (exists != 1) { + LOG(LOG_DEBUG, "NV index doesn't exist.\n"); + ret = 0; + goto err; + } + + rc = Esys_TR_FromTPMPublic(ctx, nv, auth_session_handle, ESYS_TR_NONE, + ESYS_TR_NONE, &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to constructs an ESYS_TR object.\n"); + goto err; + } + + rc = Esys_NV_ReadPublic(ctx, nvHandle, auth_session_handle, + ESYS_TR_NONE, ESYS_TR_NONE, &publicInfo, NULL); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to read publicinfo from NV.\n"); + goto err; + } + + data_size = publicInfo->nvPublic.dataSize; + + ret = data_size; + +err: + + if (publicInfo) { + free(publicInfo); + } + + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + ret = -1; + } + return ret; +} + +/** Load data from a NV index. + * + * @param[in] nv NV index of the data. + * @param[in] data_size Size of the data. + * @param[out] data Loaded data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvread(TPMI_RH_NV_INDEX nv, size_t data_size, uint8_t **data) +{ + int ret = -1; + TSS2_RC rc; + ESYS_CONTEXT *ctx; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_MAX_NV_BUFFER *blob; + + if (!nv) { + return -1; + } + + rc = fdo_tpm_esys_context_init(&ctx); + if (rc != TSS2_RC_SUCCESS || !ctx) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + rc = fdo_tpm_esys_auth_session_init(ctx, &auth_session_handle); + if (rc != TSS2_RC_SUCCESS || !auth_session_handle) { + LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); + goto err; + } + + rc = Esys_Startup(ctx, TPM2_SU_CLEAR); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start Esys API.\n"); + goto err; + } + + rc = Esys_TR_FromTPMPublic(ctx, nv, auth_session_handle, ESYS_TR_NONE, + ESYS_TR_NONE, &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to constructs an ESYS_TR object.\n"); + goto err; + } + + rc = Esys_NV_Read(ctx, ESYS_TR_RH_OWNER, nvHandle, auth_session_handle, + ESYS_TR_NONE, ESYS_TR_NONE, data_size, 0 /*=offset*/, + &blob); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to read data from NV storage.\n"); + goto err; + } + + if (memcpy_s(*data, data_size, &blob->buffer[0], blob->size) != 0) { + LOG(LOG_ERROR, "Failed to copy data to blob!\n"); + goto err; + } + + ret = 0; + +err: + + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + ret = -1; + } + return ret; +} + +/** Lock the NV index for further reads. + * + * @param[in] nv NV index to store the data. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvread_lock(TPMI_RH_NV_INDEX nv) +{ + if (!nv) { + return -1; + } + + int ret = -1; + TSS2_RC rc; + ESYS_CONTEXT *ctx; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + + rc = fdo_tpm_esys_context_init(&ctx); + if (rc != TSS2_RC_SUCCESS || !ctx) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + rc = fdo_tpm_esys_auth_session_init(ctx, &auth_session_handle); + if (rc != TSS2_RC_SUCCESS || !auth_session_handle) { + LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); + goto err; + } + + rc = Esys_Startup(ctx, TPM2_SU_CLEAR); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start Esys context.\n"); + goto err; + } + + rc = Esys_TR_FromTPMPublic(ctx, nv, auth_session_handle, ESYS_TR_NONE, + ESYS_TR_NONE, &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to constructs an ESYS_TR object.\n"); + goto err; + } + + rc = Esys_NV_ReadLock(ctx, ESYS_TR_RH_OWNER, nvHandle, + auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to lock NV read.\n"); + goto err; + } + + ret = 0; + +err: + + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + ret = -1; + } + return ret; +} + +/** Delete data from a NV index. + * + * @param[in] nv NV index to delete. + * @retval 0 on success. + * @retval -1 on undefined/general failure. + * @retval TSS2_RC response code for failures relayed from the TSS library. + */ +int fdo_tpm_nvdel(TPMI_RH_NV_INDEX nv) +{ + int ret = -1; + TSS2_RC rc; + ESYS_CONTEXT *ctx; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + + if (!nv) { + return -1; + } + + rc = fdo_tpm_esys_context_init(&ctx); + if (rc != TSS2_RC_SUCCESS || !ctx) { + LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); + goto err; + } + + rc = fdo_tpm_esys_auth_session_init(ctx, &auth_session_handle); + if (rc != TSS2_RC_SUCCESS || !auth_session_handle) { + LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); + goto err; + } + + rc = Esys_Startup(ctx, TPM2_SU_CLEAR); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to start Esys API.\n"); + goto err; + } + + // Search the NV index + TPMS_CAPABILITY_DATA *capability_data = NULL; + rc = + Esys_GetCapability(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, + TPM2_CAP_HANDLES, nv, 1, NULL, &capability_data); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Esys_GetCapability failed!\n"); + goto err; + } + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); + if (exists != 1) { + LOG(LOG_DEBUG, "NV index doesn't exist.\n"); + ret = 0; + goto err; + } + + rc = Esys_TR_FromTPMPublic(ctx, nv, ESYS_TR_NONE, ESYS_TR_NONE, + ESYS_TR_NONE, &nvHandle); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to constructs an ESYS_TR object.\n"); + goto err; + } + + rc = Esys_NV_UndefineSpace(ctx, ESYS_TR_RH_OWNER, nvHandle, + auth_session_handle, ESYS_TR_NONE, + ESYS_TR_NONE); + if (rc != TSS2_RC_SUCCESS) { + LOG(LOG_ERROR, "Failed to undefine Esys NV space.\n"); + goto err; + } + nvHandle = ESYS_TR_NONE; + + ret = 0; + +err: + + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); + ret = -1; + } + + return ret; +} diff --git a/storage/mbedos/platform_utils_if_mbed.cpp b/storage/mbedos/platform_utils_if_mbed.cpp index 6874cb05..e0092040 100644 --- a/storage/mbedos/platform_utils_if_mbed.cpp +++ b/storage/mbedos/platform_utils_if_mbed.cpp @@ -11,7 +11,7 @@ #include #include "util.h" #include "storage_al.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "platform_utils.h" #include "safe_lib.h" diff --git a/storage/mbedos/storage_if_mbedSD.cpp b/storage/mbedos/storage_if_mbedSD.cpp index 633053c0..e364e814 100644 --- a/storage/mbedos/storage_if_mbedSD.cpp +++ b/storage/mbedos/storage_if_mbedSD.cpp @@ -15,7 +15,7 @@ #include #include #include "util.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "crypto_utils.h" #include "platform_utils.h" #include "safe_lib.h" @@ -146,7 +146,7 @@ size_t fdo_blob_size(const char *name, fdo_sdk_blob_flags flags) } else { /* File format is not correct, not enough data in the file */ retval = 0; - } + } break; default: LOG(LOG_ERROR, "Invalid storage flag:%d!\n", flags); diff --git a/storage/util.c b/storage/util.c old mode 100755 new mode 100644 index 6a5d80cd..a26c5260 --- a/storage/util.c +++ b/storage/util.c @@ -20,6 +20,10 @@ #include "freertos/task.h" #endif +#ifndef MAX_DEV_SERIAL_SZ +#define MAX_DEV_SERIAL_SZ 255 +#endif + bool file_exists(char const *filename) { FILE *fp = NULL; @@ -215,7 +219,7 @@ void *fdo_alloc(size_t size) if (size == 0 || size > R_MAX_SIZE) { LOG(LOG_ERROR, "Failed, size should be between 1 and %d\n", - R_MAX_SIZE); + R_MAX_SIZE); goto end; } @@ -238,7 +242,8 @@ void *fdo_alloc(size_t size) /** * Internal API to create string duplicate */ -char *strdup_s(const char *str) { +char *strdup_s(const char *str) +{ if (NULL == str) { return NULL; @@ -316,3 +321,47 @@ int print_timestamp(void) #endif return 0; } + +#if defined(GET_DEV_SERIAL) +/** + * Internal API + * Get device serial number from system BIOS table + * */ +int get_device_serial(char *serial_buff) +{ + if (!serial_buff) { + return -1; + } + + FILE *fp; + const char *cmd = "dmidecode -s system-serial-number"; + int out_sz; + char out[MAX_DEV_SERIAL_SZ]; + int ret = -1; + + if (cmd != NULL) { + /* Open the command for reading. */ + fp = popen(cmd, "r"); + if (fp != NULL) { + + /* Read the output a line at a time - output it. */ + while (fgets(out, out_sz = sizeof(out), fp) != NULL) { + if (strcat_s(serial_buff, MAX_DEV_SERIAL_SZ, out) != + 0) { + LOG(LOG_ERROR, "Strcat() failed!\n"); + goto end; + } + } + } else { + goto end; + } + ret = 0; + } +end: + /* close */ + if (fp) { + pclose(fp); + } + return ret; +} +#endif \ No newline at end of file diff --git a/tests/unit/test_AESRoutines.c b/tests/unit/test_AESRoutines.c index 3e556633..723ef50d 100644 --- a/tests/unit/test_AESRoutines.c +++ b/tests/unit/test_AESRoutines.c @@ -131,7 +131,7 @@ TEST_CASE("aes_encrypt", "[AESRoutines][fdo]") int result_memcmp = 0; uint8_t aad[16] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, - 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; #if defined(ECDSA384_DA) uint8_t key_1[32] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, @@ -161,21 +161,19 @@ TEST_CASE("aes_encrypt", "[AESRoutines][fdo]") TEST_ASSERT_NOT_NULL(tag); // check for any NULL parameter - ret = crypto_hal_aes_encrypt(clear_txt, clear_txt_size, NULL, - &cipher_length, FDO_AES_BLOCK_SIZE, iv1, - key1, key1Length, tag, AES_TAG_LEN, - aad, sizeof(aad)); + ret = crypto_hal_aes_encrypt( + clear_txt, clear_txt_size, NULL, &cipher_length, FDO_AES_BLOCK_SIZE, + iv1, key1, key1Length, tag, AES_TAG_LEN, aad, sizeof(aad)); TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(-1, ret, - "Invalid return value"); + "Invalid return value"); // check for encrypted data length less than clear data length cipher_length = 0; - ret = crypto_hal_aes_encrypt(clear_txt, clear_txt_size, NULL, - &cipher_length, FDO_AES_BLOCK_SIZE, iv1, - key1, key1Length, tag, AES_TAG_LEN, - aad, sizeof(aad)); + ret = crypto_hal_aes_encrypt( + clear_txt, clear_txt_size, NULL, &cipher_length, FDO_AES_BLOCK_SIZE, + iv1, key1, key1Length, tag, AES_TAG_LEN, aad, sizeof(aad)); TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(-1, ret, - "Invalid return value"); + "Invalid return value"); cipher_length = clear_txt_size; cipher_text = fdo_alloc(cipher_length); @@ -184,27 +182,27 @@ TEST_CASE("aes_encrypt", "[AESRoutines][fdo]") // encrypt ret = crypto_hal_aes_encrypt(clear_txt, clear_txt_size, cipher_text, &cipher_length, FDO_AES_BLOCK_SIZE, iv1, - key1, key1Length, tag, AES_TAG_LEN, - aad, sizeof(aad)); + key1, key1Length, tag, AES_TAG_LEN, aad, + sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(0, ret, "AES Encryption Failed"); // check for any NULL parameter ret = crypto_hal_aes_decrypt(NULL, &decrypted_length, cipher_text, cipher_length, FDO_AES_BLOCK_SIZE, iv1, - key1, key1Length, tag, AES_TAG_LEN, - aad, sizeof(aad)); + key1, key1Length, tag, AES_TAG_LEN, aad, + sizeof(aad)); TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(-1, ret, - "Invalid return value"); + "Invalid return value"); // check for clear data length less than encrypted data length ret = crypto_hal_aes_decrypt(NULL, &decrypted_length, cipher_text, cipher_length, FDO_AES_BLOCK_SIZE, iv1, - key1, key1Length, tag, AES_TAG_LEN, - aad, sizeof(aad)); + key1, key1Length, tag, AES_TAG_LEN, aad, + sizeof(aad)); TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(-1, ret, - "Invalid return value"); + "Invalid return value"); decrypted_length = cipher_length; decrypted_txt = fdo_alloc(decrypted_length); @@ -229,7 +227,6 @@ TEST_CASE("aes_encrypt", "[AESRoutines][fdo]") tag, AES_TAG_LEN, aad, sizeof(aad)); TEST_ASSERT_NOT_EQUAL_MESSAGE(0, ret, "AES Decryption Failed"); - // encrypt->decrypt->change iv->decrypt again memset_s(iv1, AES_IV_LEN, 1); memset_s(tag, AES_TAG_LEN, 0); @@ -237,15 +234,15 @@ TEST_CASE("aes_encrypt", "[AESRoutines][fdo]") ret = crypto_hal_aes_encrypt(clear_txt, clear_txt_size, cipher_text, &cipher_length, FDO_AES_BLOCK_SIZE, iv1, - key1, key1Length, tag, AES_TAG_LEN, - aad, sizeof(aad)); + key1, key1Length, tag, AES_TAG_LEN, aad, + sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(0, ret, "AES Encryption Failed"); decrypted_length = cipher_length; ret = crypto_hal_aes_decrypt(decrypted_txt, &decrypted_length, cipher_text, cipher_length, FDO_AES_BLOCK_SIZE, iv1, key1, key1Length, - tag, AES_TAG_LEN, aad, sizeof(aad)); + tag, AES_TAG_LEN, aad, sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(0, ret, "AES Decryption Failed"); ret = memcmp_s(clear_txt, clear_txt_size, decrypted_txt, @@ -258,7 +255,7 @@ TEST_CASE("aes_encrypt", "[AESRoutines][fdo]") ret = crypto_hal_aes_decrypt(decrypted_txt, &decrypted_length, cipher_text, cipher_length, FDO_AES_BLOCK_SIZE, iv1, key1, key1Length, - tag, AES_TAG_LEN, aad, sizeof(aad)); + tag, AES_TAG_LEN, aad, sizeof(aad)); TEST_ASSERT_NOT_EQUAL_MESSAGE(0, ret, "AES Decryption Failed"); ret = random_close(); diff --git a/tests/unit/test_AESRoutines.h b/tests/unit/test_AESRoutines.h index 61385715..e11f4518 100644 --- a/tests/unit/test_AESRoutines.h +++ b/tests/unit/test_AESRoutines.h @@ -12,7 +12,7 @@ #include #include "BN_support.h" -#include +#include #ifdef USE_OPENSSL #include diff --git a/tests/unit/test_ECDSASignRoutines.c b/tests/unit/test_ECDSASignRoutines.c index ff75a721..29b43af3 100644 --- a/tests/unit/test_ECDSASignRoutines.c +++ b/tests/unit/test_ECDSASignRoutines.c @@ -5,15 +5,24 @@ /*! * \file - * \brief Unit tests for ECDSA signature generation abstraction routines of FDO library. + * \brief Unit tests for ECDSA signature generation abstraction routines of FDO + * library. */ #include "safe_lib.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "storage_al.h" #include "unity.h" +#include "openssl/core_names.h" +#include +#include +#include +#include +#include +#include +#include -//#define HEXDEBUG 1 +// #define HEXDEBUG 1 #define CLR_TXT_LENGTH BUFF_SIZE_1K_BYTES #define ECDSA_SIG_MAX_LENGTH 150 @@ -72,7 +81,7 @@ static void dump_pubkey(const char *title, void *ctx) #if defined(USE_OPENSSL) uint8_t *pub_copy = buf; - EC_KEY *eckey = (EC_KEY *)ctx; + EVP_PKEY *eckey = (EVP_PKEY *)ctx; len = i2o_ECPublicKey(eckey, NULL); /* pub_copy is required, because i2o_ECPublicKey alters the input @@ -105,24 +114,24 @@ static fdo_byte_array_t *getcleartext(int length) //---------------------------------------------------- #ifdef USE_OPENSSL -static EC_KEY *generateECDSA_key(void) +static EVP_PKEY *generateECDSA_key(void) { - EC_KEY *eckey = NULL; + EVP_PKEY *evp_key = NULL; + uint32_t group_name_nid; #if defined(ECDSA256_DA) - eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); -#elif defined(ECDSA384_DA) - eckey = EC_KEY_new_by_curve_name(NID_secp384r1); + group_name_nid = NID_X9_62_prime256v1; +#else + group_name_nid = NID_secp384r1; #endif - /* For cert signing, we use the OPENSSL_EC_NAMED_CURVE flag */ - EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); - - if (eckey) - if (EC_KEY_generate_key(eckey) == 0) { - EC_KEY_free(eckey); - eckey = NULL; - } - return eckey; + + evp_key = EVP_EC_gen(OBJ_nid2sn(group_name_nid)); + if (!evp_key) { + LOG(LOG_ERROR, "EC key generation failed\n"); + return NULL; + } + + return evp_key; } #endif // USE_OPENSSL @@ -196,10 +205,12 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") size_t siglen = ECDSA_SIG_MAX_LENGTH; unsigned char *sigtestdata = fdo_alloc(ECDSA_SIG_MAX_LENGTH); TEST_ASSERT_NOT_NULL(sigtestdata); - unsigned char hash[SHA512_DIGEST_SIZE] = {0}; - size_t hash_length = 0; + EVP_MD_CTX *mdctx = NULL; unsigned char *sig_r = NULL; unsigned char *sig_s = NULL; + uint32_t der_sig_len = 0; + uint8_t *der_sig = NULL; + size_t hash_length = 0; #if defined(ECDSA256_DA) hash_length = SHA256_DIGEST_SIZE; @@ -209,7 +220,7 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") // Create the context & create the key #ifdef USE_OPENSSL - EC_KEY *avalidkey = generateECDSA_key(); + EVP_PKEY *avalidkey = generateECDSA_key(); TEST_ASSERT_NOT_NULL(avalidkey); int privatekey_buflen = hash_length; BIGNUM *r = NULL; @@ -234,16 +245,64 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") EVP_PKEY *privkey = EVP_PKEY_new(); TEST_ASSERT_NOT_NULL(privkey); - // if (!EVP_PKEY_assign_EC_KEY(privkey,avalidkey)) - if (!EVP_PKEY_set1_EC_KEY(privkey, avalidkey)) - printf(" assigning ECC key to EVP_PKEY fail.\n"); - const EC_GROUP *group = EC_KEY_get0_group(avalidkey); + BIGNUM *priv; + OSSL_PARAM_BLD *param_bld; + OSSL_PARAM *params = NULL; + EVP_PKEY_CTX *ctx; // Creating new EVP_PKEY context + + priv = BN_bin2bn(privatekey, privatekey_buflen, NULL); + param_bld = OSSL_PARAM_BLD_new(); + + if (priv != NULL && param_bld != NULL && + OSSL_PARAM_BLD_push_utf8_string(param_bld, "group", "prime256v1", + 0) && + OSSL_PARAM_BLD_push_BN(param_bld, "priv", priv) && + OSSL_PARAM_BLD_push_octet_string(param_bld, "pub", NULL, 0)) { + params = OSSL_PARAM_BLD_to_param(param_bld); + } + + ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); + + if (ctx == NULL || params == NULL || EVP_PKEY_fromdata_init(ctx) <= 0 || + EVP_PKEY_fromdata(ctx, &privkey, EVP_PKEY_KEYPAIR, params) <= 0) { + exit(1); + } + + size_t group_name_size; + char group_name[64]; + + EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, + NULL, 0, &group_name_size); + if (group_name_size >= sizeof(group_name)) { + LOG(LOG_ERROR, "Unexpected long group name : %zu for EC key\n", + group_name_size); + exit(1); + } + + if (!EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, + group_name, sizeof(group_name), + &group_name_size)) { + LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); + exit(1); + } + + int group_nid = OBJ_sn2nid(group_name); + const EC_GROUP *group = EC_GROUP_new_by_curve_name(group_nid); + + if (group == NULL) { + LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); + exit(1); + } + + if (!PEM_write_bio_Parameters(outbio, privkey)) { + BIO_printf(outbio, "Error writing parameters in PEM format"); + } - PEM_write_bio_ECPKParameters(outbio, group); - if (!PEM_write_bio_ECPrivateKey(outbio, avalidkey, NULL, NULL, 0, 0, - NULL)) + if (PEM_write_bio_PrivateKey(outbio, privkey, NULL, NULL, 0, 0, NULL) == + 0) { BIO_printf(outbio, "Error writing private key data in PEM format"); + } BUF_MEM *bptr = NULL; BIO_get_mem_ptr(outbio, &bptr); @@ -256,8 +315,13 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") #else // save in bin format #ifdef USE_OPENSSL - if (BN_bn2bin(EC_KEY_get0_private_key((const EC_KEY *)avalidkey), - privatekey)) + BIGNUM *privkey_bn = NULL; + if (!EVP_PKEY_get_bn_param((const EVP_PKEY *)avalidkey, + OSSL_PKEY_PARAM_PRIV_KEY, &privkey_bn)) { + LOG(LOG_ERROR, "Failed to get private key bn\n"); + result = -1; + } + if (BN_bn2bin(privkey_bn, privatekey)) result = 0; #endif #ifdef USE_MBEDTLS @@ -285,28 +349,40 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") TEST_ASSERT_EQUAL(0, result); #ifdef USE_OPENSSL - // create the hash of the plaintext -// if (hash_length == SHA256_DIGEST_SIZE) + if (!(mdctx = EVP_MD_CTX_create())) { + LOG(LOG_ERROR, "Msg Digest init failed \n"); + result = -1; + } #if defined(ECDSA256_DA) - if (SHA256((const unsigned char *)testdata->bytes, testdata->byte_sz, - hash) == NULL) + if (1 != + EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, avalidkey)) { + LOG(LOG_ERROR, "EVP verify init failed \n"); result = -1; + } #elif defined(ECDSA384_DA) - if (SHA384((const unsigned char *)testdata->bytes, testdata->byte_sz, - hash) == NULL) + if (1 != + EVP_DigestVerifyInit(mdctx, NULL, EVP_sha384(), NULL, avalidkey)) { + LOG(LOG_ERROR, "EVP verify init failed \n"); result = -1; + } #endif + + if (1 != + EVP_DigestVerifyUpdate(mdctx, testdata->bytes, testdata->byte_sz)) { + LOG(LOG_ERROR, "EVP verify update failed \n"); + result = -1; + } TEST_ASSERT_EQUAL(0, result); - sig_r = fdo_alloc(siglen/2); + sig_r = fdo_alloc(siglen / 2); TEST_ASSERT_NOT_NULL(sig_r); - memcpy_s(sig_r, siglen/2, sigtestdata, siglen/2); - sig_s = fdo_alloc(siglen/2); + memcpy_s(sig_r, siglen / 2, sigtestdata, siglen / 2); + sig_s = fdo_alloc(siglen / 2); TEST_ASSERT_NOT_NULL(sig_s); - memcpy_s(sig_s, siglen/2, sigtestdata + siglen/2, siglen/2); - r = BN_bin2bn((const unsigned char*) sig_r, siglen/2, NULL); + memcpy_s(sig_s, siglen / 2, sigtestdata + siglen / 2, siglen / 2); + r = BN_bin2bn((const unsigned char *)sig_r, siglen / 2, NULL); TEST_ASSERT_NOT_NULL(r); - s = BN_bin2bn((const unsigned char*) sig_s, siglen/2, NULL); + s = BN_bin2bn((const unsigned char *)sig_s, siglen / 2, NULL); TEST_ASSERT_NOT_NULL(s); sig = ECDSA_SIG_new(); @@ -319,8 +395,20 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") } TEST_ASSERT_EQUAL(0, result); + der_sig_len = i2d_ECDSA_SIG(sig, NULL); + if (!der_sig_len) { + LOG(LOG_ERROR, "Failure in format conversion of signature \n"); + result = -1; + } + + der_sig_len = i2d_ECDSA_SIG(sig, &der_sig); + if (!der_sig_len || !der_sig) { + LOG(LOG_ERROR, "Failure in format conversion of signature \n"); + result = -1; + } + // verify the signature. - if (1 != ECDSA_do_verify(hash, hash_length, sig, avalidkey)) { + if (1 != EVP_DigestVerifyFinal(mdctx, der_sig, der_sig_len)) { LOG(LOG_ERROR, "ECDSA Sig verification failed\n"); result = -1; } @@ -329,11 +417,11 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") // Negative test case sigtestdata[4] = 'a'; - memcpy_s(sig_r, siglen/2, sigtestdata, siglen/2); + memcpy_s(sig_r, siglen / 2, sigtestdata, siglen / 2); ECDSA_SIG_free(sig); - r = BN_bin2bn((const unsigned char*) sig_r, siglen/2, NULL); + r = BN_bin2bn((const unsigned char *)sig_r, siglen / 2, NULL); TEST_ASSERT_NOT_NULL(r); - s = BN_bin2bn((const unsigned char*) sig_s, siglen/2, NULL); + s = BN_bin2bn((const unsigned char *)sig_s, siglen / 2, NULL); TEST_ASSERT_NOT_NULL(s); sig = ECDSA_SIG_new(); TEST_ASSERT_NOT_NULL(sig); @@ -345,7 +433,20 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") } TEST_ASSERT_EQUAL(0, result); - if (1 != ECDSA_do_verify(hash, hash_length, sig, avalidkey)) { + der_sig_len = i2d_ECDSA_SIG(sig, NULL); + if (!der_sig_len) { + LOG(LOG_ERROR, "Failure in format conversion of signature \n"); + result = -1; + } + + der_sig_len = i2d_ECDSA_SIG(sig, &der_sig); + if (!der_sig_len || !der_sig) { + LOG(LOG_ERROR, "Failure in format conversion of signature \n"); + result = -1; + } + + // verify the signature. + if (1 != EVP_DigestVerifyFinal(mdctx, der_sig, der_sig_len)) { LOG(LOG_ERROR, "ECDSA Sig verification failed\n"); result = -1; } @@ -354,7 +455,7 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") #ifdef USE_MBEDTLS mbedtls_md_type_t hash_type = MBEDTLS_MD_NONE; - // create the hash of the plaintext +// create the hash of the plaintext #if defined(ECDSA256_DA) hash_type = MBEDTLS_MD_SHA256; #elif defined(ECDSA384_DA) @@ -395,7 +496,8 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") BIO_free_all(outbio); #endif if (avalidkey) { - EC_KEY_free(avalidkey); + EVP_PKEY_free(avalidkey); + avalidkey = NULL; } if (sig) { ECDSA_SIG_free(sig); diff --git a/tests/unit/test_ECDSAVerifyRoutines.c b/tests/unit/test_ECDSAVerifyRoutines.c index f8f042fb..73207b0a 100644 --- a/tests/unit/test_ECDSAVerifyRoutines.c +++ b/tests/unit/test_ECDSAVerifyRoutines.c @@ -5,14 +5,16 @@ /*! * \file - * \brief Unit tests for ECDSA signature verification abstraction routines of FDO library. + * \brief Unit tests for ECDSA signature verification abstraction routines of + * FDO library. */ #include "safe_lib.h" -#include "fdoCryptoHal.h" -#include "fdoCrypto.h" +#include "fdo_crypto_hal.h" +#include "fdo_crypto.h" #include "storage_al.h" #include "unity.h" +#include "openssl/core_names.h" //#define HEXDEBUG 1 @@ -38,7 +40,6 @@ void tear_down(void) } #endif - #if defined(HEXDEBUG) // Helper function to convert binary to hex static char *bytes_to_hex(const uint8_t bin[], size_t len) @@ -73,7 +74,7 @@ static void dump_pubkey(const char *title, void *ctx) #if defined(USE_OPENSSL) uint8_t *pub_copy = buf; - EC_KEY *eckey = (EC_KEY *)ctx; + EVP_PKEY *eckey = (EVP_PKEY *)ctx; len = i2o_ECPublicKey(eckey, NULL); /* pub_copy is required, because i2o_ECPublicKey alters the input @@ -112,36 +113,35 @@ static void showPK(fdo_public_key_t *pk) #endif //---------------------------------------------------- #ifdef USE_OPENSSL -static EC_KEY *generateECDSA_key(int curve) +static EVP_PKEY *generateECDSA_key(int curve) { - EC_KEY *eckey = NULL; + EVP_PKEY *evp_key = NULL; + uint32_t group_name_nid; if (curve == 256) - eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + group_name_nid = NID_X9_62_prime256v1; else if (curve == 384) - eckey = EC_KEY_new_by_curve_name(NID_secp384r1); + group_name_nid = NID_secp384r1; else return NULL; - /* For cert signing, we use the OPENSSL_EC_NAMED_CURVE flag */ - EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); + evp_key = EVP_EC_gen(OBJ_nid2sn(group_name_nid)); + if (!evp_key) { + LOG(LOG_ERROR, "EC key generation failed\n"); + return NULL; + } - if (eckey) - if (EC_KEY_generate_key(eckey) == 0) { - EC_KEY_free(eckey); - eckey = NULL; - } - return eckey; + return evp_key; } // return 1 on success; 0/-1 for failure static int sha_ECCsign(int curve, unsigned char *msg, unsigned int mlen, - unsigned char *out, unsigned int *outlen, EC_KEY *eckey) + unsigned char *out, unsigned int *outlen, + EVP_PKEY *evpKey) { - unsigned char hash[SHA512_DIGEST_SIZE] = {0}; - size_t hashlength = 0; - unsigned char *signature = NULL; - unsigned int siglen = 0; + unsigned char *der_sig = NULL; + size_t der_sig_len = 0; + EVP_MD_CTX *mdctx = NULL; // ECDSA_sign return 1 on success, 0 on failure int result = 0; ECDSA_SIG *sig = NULL; @@ -150,29 +150,63 @@ static int sha_ECCsign(int curve, unsigned char *msg, unsigned int mlen, unsigned char *sig_s = NULL; int sig_s_len = 0; - siglen = ECDSA_size(eckey); - signature = OPENSSL_malloc(siglen); + // Create the Message Digest Context + mdctx = EVP_MD_CTX_create(); + if (!mdctx) { + LOG(LOG_ERROR, "Failed to create message digest context\n"); + goto done; + } if (curve == 256) { - if (SHA256(msg, mlen, hash) == NULL) + if (1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, + evpKey)) { + LOG(LOG_ERROR, "EVP sign init failed \n"); goto done; - hashlength = SHA256_DIGEST_SIZE; + } } else if (curve == 384) { - if (SHA384(msg, mlen, hash) == NULL) + if (1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha384(), NULL, + evpKey)) { + LOG(LOG_ERROR, "EVP sign init failed \n"); goto done; - hashlength = SHA384_DIGEST_SIZE; - // ECDSA_sign return 1 on success, 0 on failure + } } else { goto done; } -#ifdef HEXDEBUG - hexdump("sha_sign:MESSAGE", msg, mlen); - hexdump("sha_sign:SHAHASH", hash, hashlength); -#endif + if (1 != EVP_DigestSignUpdate(mdctx, msg, mlen)) { + LOG(LOG_ERROR, "EVP sign update failed \n"); + goto done; + } + // First call with NULL param to obtain the DER encoded signature length + if (1 != EVP_DigestSignFinal(mdctx, NULL, &der_sig_len)) { + LOG(LOG_ERROR, "EVP sign final for size failed \n"); + goto done; + } + if (der_sig_len <= 0) { + LOG(LOG_ERROR, + "EVP_DigestSignFinal returned invalid signature length.\n"); + goto done; + } + + der_sig = fdo_alloc(der_sig_len); + if (!der_sig) { + LOG(LOG_ERROR, "Signature alloc Failed\n"); + goto done; + } + // second call with actual param to obtain the DEr encoded signature + if (1 != EVP_DigestSignFinal(mdctx, der_sig, &der_sig_len)) { + LOG(LOG_ERROR, "EVP sign final failed \n"); + goto done; + } - sig = ECDSA_do_sign(hash, hashlength, eckey); + // Decode DER encoded signature to convert to raw format + sig = ECDSA_SIG_new(); + const unsigned char *sig_input = der_sig; + if (!sig || d2i_ECDSA_SIG(&sig, &sig_input, der_sig_len) == NULL) { + LOG(LOG_ERROR, "DER to EVP_PKEY struct decoding failed!\n"); + goto done; + } TEST_ASSERT_NOT_NULL(sig); // both r and s are maintained by sig, no need to free explicitly @@ -191,13 +225,13 @@ static int sha_ECCsign(int curve, unsigned char *msg, unsigned int mlen, TEST_ASSERT_NOT_NULL(sig_s); BN_bn2bin(s, sig_s); - *outlen = sig_r_len + sig_s_len;; - if (0 != memcpy_s(out, *outlen, (char *)sig_r, - (size_t)sig_r_len)) { + *outlen = sig_r_len + sig_s_len; + ; + if (0 != memcpy_s(out, *outlen, (char *)sig_r, (size_t)sig_r_len)) { goto done; } if (0 != memcpy_s(out + sig_r_len, *outlen, (char *)sig_s, - (size_t)sig_s_len)) { + (size_t)sig_s_len)) { goto done; } result = 1; @@ -205,7 +239,6 @@ static int sha_ECCsign(int curve, unsigned char *msg, unsigned int mlen, hexdump("sha256_sign:SIGNEDMESSAGE", out, *outlen); #endif done: - OPENSSL_free(signature); if (sig) { ECDSA_SIG_free(sig); } @@ -215,10 +248,22 @@ static int sha_ECCsign(int curve, unsigned char *msg, unsigned int mlen, if (sig_s) { fdo_free(sig_s); } + if (der_sig) { + fdo_free(der_sig); + sig_input = NULL; + } + if (mdctx) { + EVP_MD_CTX_free(mdctx); + mdctx = NULL; + } + if (evpKey) { + EVP_PKEY_free(evpKey); + evpKey = NULL; + } return result; } -static fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey) +static fdo_public_key_t *getFDOpk(int curve, EVP_PKEY *evpKey) { (void)curve; unsigned char *key_buf = NULL; @@ -237,27 +282,28 @@ static fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey) #endif TEST_ASSERT_NOT_NULL_MESSAGE(ecgroup, "Failed to get ECGROUP\n"); - const EC_POINT *pub = EC_KEY_get0_public_key(eckey); + const EC_POINT *pub = EC_POINT_new(ecgroup); TEST_ASSERT_NOT_NULL_MESSAGE(pub, "Failed to get ECPOINT\n"); - if (EC_POINT_get_affine_coordinates_GFp(ecgroup, pub, x, y, NULL)) { + if (EVP_PKEY_get_bn_param(evpKey, OSSL_PKEY_PARAM_EC_PUB_X, &x) && + EVP_PKEY_get_bn_param(evpKey, OSSL_PKEY_PARAM_EC_PUB_Y, &y)) { x_len = BN_num_bytes(x); y_len = BN_num_bytes(y); key_buf_len = x_len + y_len; key_buf = fdo_alloc(key_buf_len); TEST_ASSERT_NOT_NULL(key_buf); - BN_bn2bin(x, key_buf); + BN_bn2bin(x, key_buf); BN_bn2bin(y, key_buf + x_len); #if defined(ECDSA256_DA) pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256, - FDO_CRYPTO_PUB_KEY_ENCODING_X509, key_buf_len, - key_buf); + FDO_CRYPTO_PUB_KEY_ENCODING_X509, + key_buf_len, key_buf); #else pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384, - FDO_CRYPTO_PUB_KEY_ENCODING_X509, key_buf_len, - key_buf); + FDO_CRYPTO_PUB_KEY_ENCODING_X509, + key_buf_len, key_buf); #endif - } + } if (!pk || !pk->key1) { return NULL; @@ -277,11 +323,15 @@ static fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey) } #ifdef HEXDEBUG - dump_pubkey(" + Public key: ", eckey); + dump_pubkey(" + Public key: ", evpKey); hexdump("key1", (unsigned char *)pk->key1, pub_len); if (pk->key2) showPK(pk); #endif + if (evpKey) { + EVP_PKEY_free(evpKey); + evpKey = NULL; + } return pk; } @@ -444,14 +494,14 @@ static void ec_sig_verification(int curve) // int curve = 256; #ifdef USE_OPENSSL unsigned char *pubkey = key_buf; - EC_KEY *avalidkey = generateECDSA_key(curve); + EVP_PKEY *avalidkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(avalidkey); if (1 == (result = sha_ECCsign(curve, testdata->bytes, testdata->byte_sz, sigtestdata, &siglen, avalidkey))) { TEST_ASSERT_EQUAL(1, result); - key_buf_len = i2d_EC_PUBKEY(avalidkey, &pubkey); + key_buf_len = i2d_PUBKEY(avalidkey, &pubkey); TEST_ASSERT_NOT_EQUAL_MESSAGE(0, key_buf_len, "DER encoding failed!"); pk = getFDOpk(curve, avalidkey); @@ -525,7 +575,7 @@ static void ec_sig_verification(int curve) fdo_public_key_t *anotherpk = NULL; #ifdef USE_OPENSSL /* force a failure by using another/different key */ - EC_KEY *anotherkey = generateECDSA_key(curve); + EVP_PKEY *anotherkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(anotherkey); anotherpk = getFDOpk(curve, anotherkey); #endif @@ -558,8 +608,10 @@ static void ec_sig_verification(int curve) /* clean up */ fdo_public_key_free(anotherpk); #ifdef USE_OPENSSL - if (anotherkey) - EC_KEY_free(anotherkey); + if (anotherkey) { + EVP_PKEY_free(anotherkey); + anotherkey = NULL; + } #endif #ifdef USE_MBEDTLS mbedtls_ecdsa_free(&anotherkey); @@ -569,7 +621,8 @@ static void ec_sig_verification(int curve) #ifdef USE_OPENSSL if (avalidkey) { - EC_KEY_free(avalidkey); + EVP_PKEY_free(avalidkey); + avalidkey = NULL; } #endif #ifdef USE_MBEDTLS @@ -581,29 +634,28 @@ static void ec_sig_verification(int curve) /*** Test functions. ***/ #ifndef TARGET_OS_FREERTOS -void test_ecdsa256sigverification(void) + void test_ecdsa256sigverification(void) #else TEST_CASE("ecdsa256sigverification", "[ECDSARoutines][fdo]") #endif -{ - //TO-DO: Update test case for X509-encoded public key types - TEST_IGNORE(); + { + // TO-DO: Update test case for X509-encoded public key types + TEST_IGNORE(); #ifndef ECDSA256_DA - TEST_IGNORE(); + TEST_IGNORE(); #endif - ec_sig_verification(256); -} + ec_sig_verification(256); + } #ifndef TARGET_OS_FREERTOS -void test_ecdsa384sigverification(void) + void test_ecdsa384sigverification(void) #else TEST_CASE("ecdsa384sigverification", "[ECDSARoutines][fdo]") #endif -{ - TEST_IGNORE(); + { + TEST_IGNORE(); #ifdef ECDSA256_DA - TEST_IGNORE(); + TEST_IGNORE(); #endif - ec_sig_verification(384); -} - + ec_sig_verification(384); + } diff --git a/tests/unit/test_SSLRoutines.c b/tests/unit/test_SSLRoutines.c index ed2ca383..53b4eb1c 100644 --- a/tests/unit/test_SSLRoutines.c +++ b/tests/unit/test_SSLRoutines.c @@ -19,7 +19,7 @@ #include #include #include "util.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "unity.h" #ifdef TARGET_OS_LINUX diff --git a/tests/unit/test_bn_support.c b/tests/unit/test_bn_support.c index 05bf9003..c0dbe62b 100644 --- a/tests/unit/test_bn_support.c +++ b/tests/unit/test_bn_support.c @@ -10,7 +10,7 @@ */ #include "unity.h" -#include +#include #include #include #include "BN_support.h" diff --git a/tests/unit/test_credentials.c b/tests/unit/test_credentials.c index dff2942a..80501431 100644 --- a/tests/unit/test_credentials.c +++ b/tests/unit/test_credentials.c @@ -13,8 +13,8 @@ #include "unity.h" #include "load_credentials.h" #include "safe_lib.h" -#include "fdoCryptoHal.h" -#include "fdoCrypto.h" +#include "fdo_crypto_hal.h" +#include "fdo_crypto.h" #include "platform_utils.h" #ifdef TARGET_OS_FREERTOS @@ -63,55 +63,53 @@ static int32_t configure_blobs(void) // contents are hard-coded for AES-GCM-256 crypto unsigned char hmac_key[] = { - 0xa3, 0x97, 0xa2, 0x55, 0x53, 0xbe, 0xf1, 0xfc, 0xf9, 0x79, 0x6b, - 0x52, 0x14, 0x13, 0xe9, 0xe2, 0x2d, 0x51, 0x8e, 0x1f, 0x56, 0x08, - 0x57, 0x27, 0xa7, 0x05, 0xd4, 0xd0, 0x52, 0x82, 0x77, 0x75 - }; + 0xa3, 0x97, 0xa2, 0x55, 0x53, 0xbe, 0xf1, 0xfc, 0xf9, 0x79, 0x6b, + 0x52, 0x14, 0x13, 0xe9, 0xe2, 0x2d, 0x51, 0x8e, 0x1f, 0x56, 0x08, + 0x57, 0x27, 0xa7, 0x05, 0xd4, 0xd0, 0x52, 0x82, 0x77, 0x75}; unsigned char data_platform_iv_bin[] = { - 0x42, 0x42, 0x4e, 0x41, 0xaf, 0x32, 0x34, 0x49, 0xe8, 0xa6, 0xdb, - 0xcf, 0x42, 0x42, 0x4e, 0x41, 0xaf, 0x32, 0x34, 0x49, 0xe8, 0xa6, - 0xdb, 0xcf - }; + 0x42, 0x42, 0x4e, 0x41, 0xaf, 0x32, 0x34, 0x49, + 0xe8, 0xa6, 0xdb, 0xcf, 0x42, 0x42, 0x4e, 0x41, + 0xaf, 0x32, 0x34, 0x49, 0xe8, 0xa6, 0xdb, 0xcf}; unsigned int data_platform_iv_bin_len = 24; unsigned char data_platform_aes_key_bin[] = { - 0xc9, 0xbb, 0x49, 0xf6, 0x52, 0x1a, 0x6c, 0x7d, 0xcf, 0xfe, 0x1a, - 0x9c, 0x79, 0x32, 0x55, 0x29, 0x5b, 0xe0, 0x0b, 0xd3, 0xe2, 0xf9, - 0xd5, 0x31, 0xd9, 0xdf, 0xf2, 0x11, 0x73, 0x8a, 0x55, 0xb1 - }; + 0xc9, 0xbb, 0x49, 0xf6, 0x52, 0x1a, 0x6c, 0x7d, 0xcf, 0xfe, 0x1a, + 0x9c, 0x79, 0x32, 0x55, 0x29, 0x5b, 0xe0, 0x0b, 0xd3, 0xe2, 0xf9, + 0xd5, 0x31, 0xd9, 0xdf, 0xf2, 0x11, 0x73, 0x8a, 0x55, 0xb1}; unsigned int data_platform_aes_key_bin_len = 32; /* [3, true, 100, "12345", h'C6F29F84DAD6456488CFEF0ED1AA889A', - [[[5, "host.docker.internal"], [3, 8040], [12, 1], [2, h'7F000001'], [4, 8443]]], + [[[5, "host.docker.internal"], [3, 8040], [12, 1], [2, h'7F000001'], [4, + 8443]]], [-43, h'E2DE3109F7F73264C530C8694FD0F0FD9534F255C329ED1A9A23AF8C7B0884 48E85C9B919C7A2C74F23804389006678F']] */ unsigned char data_Normal_blob[] = { - 0x30, 0x4c, 0x4e, 0x61, 0x5c, 0xa6, 0xb4, 0xd6, 0xba, 0x39, 0x40, 0x0f, 0xb0, - 0xba, 0x9f, 0x2e, 0x92, 0xa6, 0x89, 0xda, 0xb0, 0x93, 0xcb, 0xd5, 0xd5, 0xc8, - 0xe9, 0x97, 0xa5, 0x2b, 0x88, 0xdc, 0x00, 0x00, 0x00, 0x73, 0x87, 0x03, 0xf5, - 0x18, 0x64, 0x65, 0x31, 0x32, 0x33, 0x34, 0x35, 0x50, 0xc6, 0xf2, 0x9f, 0x84, - 0xda, 0xd6, 0x45, 0x64, 0x88, 0xcf, 0xef, 0x0e, 0xd1, 0xaa, 0x88, 0x9a, 0x81, - 0x85, 0x82, 0x05, 0x69, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, - 0x82, 0x03, 0x19, 0x1f, 0x68, 0x82, 0x0c, 0x01, 0x82, 0x02, 0x44, 0x7f, 0x00, - 0x00, 0x01, 0x82, 0x04, 0x19, 0x20, 0xfb, 0x82, 0x38, 0x2a, 0x58, 0x30, 0xe2, - 0xde, 0x31, 0x09, 0xf7, 0xf7, 0x32, 0x64, 0xc5, 0x30, 0xc8, 0x69, 0x4f, 0xd0, - 0xf0, 0xfd, 0x95, 0x34, 0xf2, 0x55, 0xc3, 0x29, 0xed, 0x1a, 0x9a, 0x23, 0xaf, - 0x8c, 0x7b, 0x08, 0x84, 0x48, 0xe8, 0x5c, 0x9b, 0x91, 0x9c, 0x7a, 0x2c, 0x74, - 0xf2, 0x38, 0x04, 0x38, 0x90, 0x06, 0x67, 0x8f - }; + 0x30, 0x4c, 0x4e, 0x61, 0x5c, 0xa6, 0xb4, 0xd6, 0xba, 0x39, 0x40, + 0x0f, 0xb0, 0xba, 0x9f, 0x2e, 0x92, 0xa6, 0x89, 0xda, 0xb0, 0x93, + 0xcb, 0xd5, 0xd5, 0xc8, 0xe9, 0x97, 0xa5, 0x2b, 0x88, 0xdc, 0x00, + 0x00, 0x00, 0x73, 0x87, 0x03, 0xf5, 0x18, 0x64, 0x65, 0x31, 0x32, + 0x33, 0x34, 0x35, 0x50, 0xc6, 0xf2, 0x9f, 0x84, 0xda, 0xd6, 0x45, + 0x64, 0x88, 0xcf, 0xef, 0x0e, 0xd1, 0xaa, 0x88, 0x9a, 0x81, 0x85, + 0x82, 0x05, 0x69, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, + 0x74, 0x82, 0x03, 0x19, 0x1f, 0x68, 0x82, 0x0c, 0x01, 0x82, 0x02, + 0x44, 0x7f, 0x00, 0x00, 0x01, 0x82, 0x04, 0x19, 0x20, 0xfb, 0x82, + 0x38, 0x2a, 0x58, 0x30, 0xe2, 0xde, 0x31, 0x09, 0xf7, 0xf7, 0x32, + 0x64, 0xc5, 0x30, 0xc8, 0x69, 0x4f, 0xd0, 0xf0, 0xfd, 0x95, 0x34, + 0xf2, 0x55, 0xc3, 0x29, 0xed, 0x1a, 0x9a, 0x23, 0xaf, 0x8c, 0x7b, + 0x08, 0x84, 0x48, 0xe8, 0x5c, 0x9b, 0x91, 0x9c, 0x7a, 0x2c, 0x74, + 0xf2, 0x38, 0x04, 0x38, 0x90, 0x06, 0x67, 0x8f}; unsigned int data_Normal_blob_len = sizeof(data_Normal_blob); unsigned char data_Secure_blob[] = { - 0x42, 0x42, 0x4e, 0x41, 0xaf, 0x32, 0x34, 0x49, 0xe8, 0xa6, 0xdb, 0xcf, 0xd7, - 0xa4, 0xe7, 0x43, 0x23, 0x4f, 0x63, 0xc8, 0x5c, 0xbe, 0x65, 0xff, 0xe1, 0x64, - 0x66, 0x36, 0x00, 0x00, 0x00, 0x22, 0x88, 0xe5, 0x86, 0x32, 0xc9, 0xc8, 0x4c, - 0x9e, 0x44, 0xc6, 0x9b, 0x01, 0x50, 0xe1, 0x02, 0x3d, 0x53, 0x87, 0x54, 0x1a, - 0x75, 0xbf, 0x2e, 0xb2, 0x66, 0x22, 0xfe, 0x8c, 0x09, 0x80, 0x53, 0x69, 0xb5, - 0x5c - }; + 0x42, 0x42, 0x4e, 0x41, 0xaf, 0x32, 0x34, 0x49, 0xe8, 0xa6, 0xdb, + 0xcf, 0xd7, 0xa4, 0xe7, 0x43, 0x23, 0x4f, 0x63, 0xc8, 0x5c, 0xbe, + 0x65, 0xff, 0xe1, 0x64, 0x66, 0x36, 0x00, 0x00, 0x00, 0x22, 0x88, + 0xe5, 0x86, 0x32, 0xc9, 0xc8, 0x4c, 0x9e, 0x44, 0xc6, 0x9b, 0x01, + 0x50, 0xe1, 0x02, 0x3d, 0x53, 0x87, 0x54, 0x1a, 0x75, 0xbf, 0x2e, + 0xb2, 0x66, 0x22, 0xfe, 0x8c, 0x09, 0x80, 0x53, 0x69, 0xb5, 0x5c}; unsigned int data_Secure_blob_len = sizeof(data_Secure_blob); /* Write Platform HMAC */ @@ -223,7 +221,8 @@ static int32_t configure_blobs(void) static fdo_sdk_service_info_module *fdo_sv_info_modules_init(void) { fdo_sdk_service_info_module *module_info = NULL; - module_info = fdo_alloc(FDO_MAX_MODULES * (sizeof(fdo_sdk_service_info_module))); + module_info = + fdo_alloc(FDO_MAX_MODULES * (sizeof(fdo_sdk_service_info_module))); if (!module_info) { LOG(LOG_ERROR, "Malloc failed!\n"); return NULL; @@ -245,7 +244,7 @@ void test_read_normal_device_credentials(void) #endif { TEST_IGNORE(); -#if !defined (AES_MODE_GCM_ENABLED) || AES_BITS != 256 +#if !defined(AES_MODE_GCM_ENABLED) || AES_BITS != 256 TEST_IGNORE(); #endif int ret = -1; @@ -291,7 +290,7 @@ void test_read_secure_device_credentials(void) #endif { TEST_IGNORE(); -#if !defined (AES_MODE_GCM_ENABLED) || AES_BITS != 256 +#if !defined(AES_MODE_GCM_ENABLED) || AES_BITS != 256 TEST_IGNORE(); #endif int ret = -1; @@ -373,7 +372,7 @@ void test_read_write_Device_credentials(void) #endif { TEST_IGNORE(); -#if !defined (AES_MODE_GCM_ENABLED) || AES_BITS != 256 +#if !defined(AES_MODE_GCM_ENABLED) || AES_BITS != 256 TEST_IGNORE(); #endif int ret = -1; @@ -405,16 +404,14 @@ void test_read_write_Device_credentials(void) FDO_SDK_NORMAL_DATA, ocred); TEST_ASSERT_TRUE(ret); - ret = write_normal_device_credentials(NULL, - FDO_SDK_NORMAL_DATA, ocred); + ret = write_normal_device_credentials(NULL, FDO_SDK_NORMAL_DATA, ocred); TEST_ASSERT_FALSE(ret); ret = write_secure_device_credentials((char *)FDO_CRED_SECURE, FDO_SDK_SECURE_DATA, ocred); TEST_ASSERT_TRUE(ret); - ret = write_secure_device_credentials(NULL, - FDO_SDK_SECURE_DATA, ocred); + ret = write_secure_device_credentials(NULL, FDO_SDK_SECURE_DATA, ocred); TEST_ASSERT_FALSE(ret); fdo_sdk_deinit(); @@ -428,7 +425,7 @@ void test_store_credential(void) #endif { TEST_IGNORE(); -#if !defined (AES_MODE_GCM_ENABLED) || AES_BITS != 256 +#if !defined(AES_MODE_GCM_ENABLED) || AES_BITS != 256 TEST_IGNORE(); #endif int ret = -1; @@ -458,4 +455,3 @@ void test_store_credential(void) fdo_sdk_deinit(); fdo_free(module_info); } - diff --git a/tests/unit/test_cryptoSupport.c b/tests/unit/test_cryptoSupport.c index e4e16b8e..a4dbf5d8 100644 --- a/tests/unit/test_cryptoSupport.c +++ b/tests/unit/test_cryptoSupport.c @@ -9,8 +9,8 @@ */ #include "crypto_utils.h" -#include "fdoCrypto.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto.h" +#include "fdo_crypto_hal.h" #include "unity.h" #include "storage_al.h" #include "safe_lib.h" @@ -18,6 +18,14 @@ #include "ecdsa_privkey.h" #include "safe_lib.h" #include "fdotypes.h" +#include "openssl/core_names.h" +#include +#include +#include +#include +#include +#include +#include #define PLAIN_TEXT_SIZE BUFF_SIZE_1K_BYTES #define DER_PUBKEY_LEN_MAX 512 @@ -52,10 +60,10 @@ uint8_t pub_key[] = { 0x83, 0x7d, 0x3e, 0x31, 0xee, 0x11, 0x40, 0xa9}; /*** Function Declarations ***/ -EC_KEY *generateECDSA_key(int curve); +EVP_PKEY *generateECDSA_key(int curve); int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, - uint32_t *outlen, EC_KEY *eckey); -fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey); + uint32_t *outlen, EVP_PKEY *eckey); +fdo_public_key_t *getFDOpk(int curve, EVP_PKEY *eckey); void set_up(void); void tear_down(void); int32_t __wrap_crypto_hal_set_peer_random(void *context, @@ -75,7 +83,7 @@ int __wrap_crypto_hal_sig_verify( uint32_t signature_length, const uint8_t *key_param1, uint32_t key_param1Length, const uint8_t *key_param2, uint32_t key_param2Length); -int __wrap_get_ec_key(void); +// int __wrap_get_ec_key(void); int __wrap_ECDSA_size(const EC_KEY *eckey); int __wrap_memcpy_s(void *dest, size_t dmax, const void *src, size_t smax); void test_crypto_support_random(void); @@ -145,7 +153,6 @@ fdo_string_t *__wrap_fdo_string_alloc_with_str(char *data); errno_t __wrap_strcmp_s(const char *dest, rsize_t dmax, const char *src, int *indicator); static uint8_t *get_randomiv(void); -static EC_KEY *Private_key(void); /*** Function Definitions ***/ @@ -162,27 +169,24 @@ static uint8_t *get_randomiv(void) } #ifdef USE_OPENSSL -static EC_KEY *Private_key(void) +static EVP_PKEY *Private_key(void) { - EC_KEY *eckey = NULL; + EVP_PKEY *evp_key = NULL; + uint32_t group_name_nid; #if defined(ECDSA256_DA) - eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + group_name_nid = NID_X9_62_prime256v1; #else - eckey = EC_KEY_new_by_curve_name(NID_secp384r1); + group_name_nid = NID_secp384r1; #endif - if (eckey == NULL) + evp_key = EVP_EC_gen(OBJ_nid2sn(group_name_nid)); + if (!evp_key) { + LOG(LOG_ERROR, "EC key generation failed\n"); return NULL; - /* For cert signing, we use the OPENSSL_EC_NAMED_CURVE flag */ - EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); + } - if (eckey) - if (EC_KEY_generate_key(eckey) == 0) { - EC_KEY_free(eckey); - eckey = NULL; - } - return eckey; + return evp_key; } #endif @@ -226,37 +230,35 @@ static int Private_key(mbedtls_ecdsa_context *ctx_sign) #endif #ifdef USE_OPENSSL -EC_KEY *generateECDSA_key(int curve) +EVP_PKEY *generateECDSA_key(int curve) { (void)curve; - EC_KEY *eckey = NULL; + EVP_PKEY *evp_key = NULL; + uint32_t group_name_nid; #if defined(ECDSA256_DA) - eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + group_name_nid = NID_X9_62_prime256v1; #else - eckey = EC_KEY_new_by_curve_name(NID_secp384r1); + group_name_nid = NID_secp384r1; #endif - if (eckey == NULL) - return NULL; - /* For cert signing, we use the OPENSSL_EC_NAMED_CURVE flag */ - EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); + evp_key = EVP_EC_gen(OBJ_nid2sn(group_name_nid)); + if (!evp_key) { + LOG(LOG_ERROR, "EC key generation failed\n"); + return NULL; + } - if (eckey) - if (EC_KEY_generate_key(eckey) == 0) { - EC_KEY_free(eckey); - eckey = NULL; - } - return eckey; + return evp_key; } // return 0 on success; -1 for failure int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, - uint32_t *outlen, EC_KEY *eckey) + uint32_t *outlen, EVP_PKEY *evpKey) { (void)curve; - uint8_t hash[SHA512_DIGEST_SIZE] = {0}; - size_t hashlength = 0; + unsigned char *der_sig = NULL; + size_t der_sig_len = 0; + EVP_MD_CTX *mdctx = NULL; int result = -1; ECDSA_SIG *sig = NULL; unsigned char *sig_r = NULL; @@ -264,17 +266,56 @@ int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, unsigned char *sig_s = NULL; int sig_s_len = 0; + // Create the Message Digest Context + mdctx = EVP_MD_CTX_create(); + if (!mdctx) { + LOG(LOG_ERROR, "Failed to create message digest context\n"); + goto done; + } #if defined(ECDSA256_DA) - if (SHA256(msg, mlen, hash) == NULL) + if (1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, evpKey)) { + LOG(LOG_ERROR, "EVP sign init failed \n"); goto done; - hashlength = SHA256_DIGEST_SIZE; -#else - if (SHA384(msg, mlen, hash) == NULL) + } +#elif defined(ECDSA384_DA) + if (1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha384(), NULL, evpKey)) { + LOG(LOG_ERROR, "EVP sign init failed \n"); goto done; - hashlength = SHA384_DIGEST_SIZE; + } #endif + if (1 != EVP_DigestSignUpdate(mdctx, msg, mlen)) { + LOG(LOG_ERROR, "EVP sign update failed \n"); + goto done; + } + // First call with NULL param to obtain the DER encoded signature length + if (1 != EVP_DigestSignFinal(mdctx, NULL, &der_sig_len)) { + LOG(LOG_ERROR, "EVP sign final for size failed \n"); + goto done; + } + if (der_sig_len <= 0) { + LOG(LOG_ERROR, + "EVP_DigestSignFinal returned invalid signature length.\n"); + goto done; + } - sig = ECDSA_do_sign(hash, hashlength, eckey); + der_sig = fdo_alloc(der_sig_len); + if (!der_sig) { + LOG(LOG_ERROR, "Signature alloc Failed\n"); + goto done; + } + // second call with actual param to obtain the DEr encoded signature + if (1 != EVP_DigestSignFinal(mdctx, der_sig, &der_sig_len)) { + LOG(LOG_ERROR, "EVP sign final failed \n"); + goto done; + } + + // Decode DER encoded signature to convert to raw format + sig = ECDSA_SIG_new(); + const unsigned char *sig_input = der_sig; + if (!sig || d2i_ECDSA_SIG(&sig, &sig_input, der_sig_len) == NULL) { + LOG(LOG_ERROR, "DER to EC_KEY struct decoding failed!\n"); + goto done; + } TEST_ASSERT_NOT_NULL(sig); // both r and s are maintained by sig, no need to free explicitly @@ -293,13 +334,13 @@ int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, TEST_ASSERT_NOT_NULL(sig_s); BN_bn2bin(s, sig_s); - *outlen = sig_r_len + sig_s_len;; - if (0 != memcpy_s(out, *outlen, (char *)sig_r, - (size_t)sig_r_len)) { + *outlen = sig_r_len + sig_s_len; + ; + if (0 != memcpy_s(out, *outlen, (char *)sig_r, (size_t)sig_r_len)) { goto done; } if (0 != memcpy_s(out + sig_r_len, *outlen, (char *)sig_s, - (size_t)sig_s_len)) { + (size_t)sig_s_len)) { goto done; } result = 1; @@ -314,17 +355,29 @@ int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, if (sig_s) { fdo_free(sig_s); } + if (der_sig) { + fdo_free(der_sig); + sig_input = NULL; + } + if (mdctx) { + EVP_MD_CTX_free(mdctx); + mdctx = NULL; + } + if (evpKey) { + EVP_PKEY_free(evpKey); + evpKey = NULL; + } return result; } -fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey) +fdo_public_key_t *getFDOpk(int curve, EVP_PKEY *evpKey) { (void)curve; unsigned char *key_buf = NULL; int key_buf_len = 0; EC_GROUP *ecgroup = NULL; BIGNUM *x = BN_new(); - BIGNUM *y = BN_new(); + BIGNUM *y = BN_new(); int x_len = 0; int y_len = 0; fdo_public_key_t *pk = NULL; @@ -336,9 +389,11 @@ fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey) #endif TEST_ASSERT_NOT_NULL_MESSAGE(ecgroup, "Failed to get ECGROUP\n"); - const EC_POINT *pub = EC_KEY_get0_public_key(eckey); + const EC_POINT *pub = EC_POINT_new(ecgroup); TEST_ASSERT_NOT_NULL_MESSAGE(pub, "Failed to get ECPOINT\n"); - if (EC_POINT_get_affine_coordinates_GFp(ecgroup, pub, x, y, NULL)) { + /* Get the public key co-ordinates in x and y*/ + if (EVP_PKEY_get_bn_param(evpKey, OSSL_PKEY_PARAM_EC_PUB_X, &x) && + EVP_PKEY_get_bn_param(evpKey, OSSL_PKEY_PARAM_EC_PUB_Y, &y)) { x_len = BN_num_bytes(x); y_len = BN_num_bytes(y); key_buf_len = x_len + y_len; @@ -349,14 +404,14 @@ fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey) #if defined(ECDSA256_DA) pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256, - FDO_CRYPTO_PUB_KEY_ENCODING_X509, key_buf_len, - key_buf); + FDO_CRYPTO_PUB_KEY_ENCODING_X509, + key_buf_len, key_buf); #else pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384, - FDO_CRYPTO_PUB_KEY_ENCODING_X509, key_buf_len, - key_buf); + FDO_CRYPTO_PUB_KEY_ENCODING_X509, + key_buf_len, key_buf); #endif - } + } if (!pk || !pk->key1) { return NULL; @@ -374,6 +429,10 @@ fdo_public_key_t *getFDOpk(int curve, EC_KEY *eckey) if (y) { BN_free(y); } + if (evpKey) { + EVP_PKEY_free(evpKey); + evpKey = NULL; + } return pk; } #endif // USE_OPENSSL @@ -683,15 +742,15 @@ int __wrap_crypto_hal_sig_verify( } #ifdef USE_OPENSSL -int __real_get_ec_key(void); -int __wrap_get_ec_key(void) -{ - if (get_ec_key_fail_flag) { - return 0; - } else { - return __real_get_ec_key(); - } -} +// int __real_get_ec_key(void); +// int __wrap_get_ec_key(void) +// { +// if (get_ec_key_fail_flag) { +// return 0; +// } else { +// return __real_get_ec_key(); +// } +// } int __real_ECDSA_size(const EC_KEY *eckey); int __wrap_ECDSA_size(const EC_KEY *eckey) @@ -764,6 +823,7 @@ void test_crypto_support_Private_key(void) TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") #endif { + // TEST_IGNORE(); int ret = -1; int privatekey_buflen = 0; #ifdef USE_OPENSSL @@ -773,10 +833,11 @@ TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") size_t hash_length = SHA384_DIGEST_SIZE; #endif - EC_KEY *validkey = Private_key(); + EVP_PKEY *validkey = Private_key(); TEST_ASSERT_NOT_NULL(validkey); privatekey_buflen = hash_length; #endif + #ifdef USE_MBEDTLS mbedtls_ecdsa_context ctx_sign = {0}; ret = Private_key(&ctx_sign); @@ -794,16 +855,62 @@ TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") EVP_PKEY *privkey = EVP_PKEY_new(); TEST_ASSERT_NOT_NULL(privkey); - // if (!EVP_PKEY_assign_EC_KEY(privkey,avalidkey)) - if (!EVP_PKEY_set1_EC_KEY(privkey, validkey)) - printf(" assigning ECC key to EVP_PKEY fail.\n"); - const EC_GROUP *group = EC_KEY_get0_group(validkey); + BIGNUM *priv; + OSSL_PARAM_BLD *param_bld; + OSSL_PARAM *params = NULL; + EVP_PKEY_CTX *ctx; + + priv = BN_bin2bn(privatekey, privatekey_buflen, NULL); + param_bld = OSSL_PARAM_BLD_new(); + + if (priv != NULL && param_bld != NULL && + OSSL_PARAM_BLD_push_utf8_string(param_bld, "group", "prime256v1", + 0) && + OSSL_PARAM_BLD_push_BN(param_bld, "priv", priv) && + OSSL_PARAM_BLD_push_octet_string(param_bld, "pub", NULL, 0)) { + params = OSSL_PARAM_BLD_to_param(param_bld); + } + + ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); + + if (ctx == NULL || params == NULL || EVP_PKEY_fromdata_init(ctx) <= 0 || + EVP_PKEY_fromdata(ctx, &privkey, EVP_PKEY_KEYPAIR, params) <= 0) { + exit(1); + } + + size_t group_name_size; + char group_name[64]; + + EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, + NULL, 0, &group_name_size); + if (group_name_size >= sizeof(group_name)) { + LOG(LOG_ERROR, "Unexpected long group name : %zu for EC key\n", + group_name_size); + exit(1); + } + + if (!EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, + group_name, sizeof(group_name), + &group_name_size)) { + LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); + exit(1); + } + + int group_nid = OBJ_sn2nid(group_name); + const EC_GROUP *group = EC_GROUP_new_by_curve_name(group_nid); - PEM_write_bio_ECPKParameters(outbio, group); - if (!PEM_write_bio_ECPrivateKey(outbio, validkey, NULL, NULL, 0, 0, - NULL)) - BIO_printf(outbio, - "Error writing private key data in PEM format"); + if (group == NULL) { + LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); + exit(1); + } + + if (!PEM_write_bio_Parameters(outbio, privkey)) { + BIO_printf(outbio, "Error writing parameters in PEM format"); + } + + if(PEM_write_bio_PrivateKey(outbio, privkey, NULL, NULL, 0, 0, NULL) == 0) { + BIO_printf(outbio, "Error writing private key data in PEM format"); + } BUF_MEM *bptr = NULL; BIO_get_mem_ptr(outbio, &bptr); @@ -815,8 +922,14 @@ TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") #else #ifdef USE_OPENSSL - if (BN_bn2bin(EC_KEY_get0_private_key((const EC_KEY *)validkey), - privatekey)) + BIGNUM *privkey_bn = NULL; + if (!EVP_PKEY_get_bn_param((const EVP_PKEY *)validkey, + OSSL_PKEY_PARAM_PRIV_KEY, &privkey_bn)) { + LOG(LOG_ERROR, "Failed to get private key bn\n"); + ret = -1; + } + + if (BN_bn2bin(privkey_bn, privatekey)) ret = 0; #endif #ifdef USE_MBEDTLS @@ -834,10 +947,14 @@ TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") #ifdef USE_OPENSSL #if defined(ECDSA_PEM) EVP_PKEY_free(privkey); + EVP_PKEY_CTX_free(ctx); BIO_free_all(outbio); + OSSL_PARAM_free(params); + OSSL_PARAM_BLD_free(param_bld); + BN_free(priv); #endif if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS mbedtls_ecdsa_free(&ctx_sign); @@ -904,6 +1021,9 @@ TEST_CASE("crypto_support_fdo_msg_encrypt_valid", "[crypto_support][fdo]") iv1, tag, AES_TAG_LEN, aad, 16); TEST_ASSERT_EQUAL_INT(0, ret); + ret = fdo_kex_close(); + TEST_ASSERT_EQUAL_INT(0, ret); + if (cipher) { fdo_free(cipher); } @@ -946,7 +1066,7 @@ TEST_CASE("crypto_support_fdo_msg_encrypt_invalid_clear_text", TEST_ASSERT_NOT_NULL(aad); ret = fdo_msg_encrypt(NULL, clear_length, cipher, &cipher_length, iv1, - tag, AES_TAG_LEN, aad, 16); + tag, AES_TAG_LEN, aad, 16); TEST_ASSERT_EQUAL_INT(-1, ret); if (cipher) { @@ -990,8 +1110,8 @@ TEST_CASE("crypto_support_fdo_msg_encrypt_invalid_clear_text_length", aad = fdo_alloc(16); TEST_ASSERT_NOT_NULL(aad); - ret = fdo_msg_encrypt(test_buff1, 0, cipher, &cipher_length, iv1, - tag, AES_TAG_LEN, aad, 16); + ret = fdo_msg_encrypt(test_buff1, 0, cipher, &cipher_length, iv1, tag, + AES_TAG_LEN, aad, 16); TEST_ASSERT_EQUAL_INT(-1, ret); if (cipher) { @@ -1035,8 +1155,8 @@ TEST_CASE("crypto_support_fdo_msg_encrypt_invalid_cipher_text_length", aad = fdo_alloc(16); TEST_ASSERT_NOT_NULL(aad); - ret = fdo_msg_encrypt(test_buff1, clear_length, cipher, NULL, iv1, - tag, AES_TAG_LEN, aad, 16); + ret = fdo_msg_encrypt(test_buff1, clear_length, cipher, NULL, iv1, tag, + AES_TAG_LEN, aad, 16); TEST_ASSERT_EQUAL_INT(-1, ret); if (cipher) { @@ -1079,8 +1199,8 @@ TEST_CASE("crypto_support_fdo_msg_encrypt_invalid_iv", "[crypto_support][fdo]") aad = fdo_alloc(16); TEST_ASSERT_NOT_NULL(aad); - ret = fdo_msg_encrypt(test_buff1, clear_length, cipher, &cipher_length, iv1, - tag, AES_TAG_LEN, aad, 16); + ret = fdo_msg_encrypt(test_buff1, clear_length, cipher, &cipher_length, + iv1, tag, AES_TAG_LEN, aad, 16); TEST_ASSERT_EQUAL_INT(-1, ret); if (cipher) { @@ -1117,8 +1237,8 @@ TEST_CASE("crypto_support_fdo_msg_encrypt_invalid_tag", "[crypto_support][fdo]") aad = fdo_alloc(16); TEST_ASSERT_NOT_NULL(aad); - ret = fdo_msg_encrypt(test_buff1, clear_length, cipher, &cipher_length, iv1, - tag, AES_TAG_LEN, aad, 16); + ret = fdo_msg_encrypt(test_buff1, clear_length, cipher, &cipher_length, + iv1, tag, AES_TAG_LEN, aad, 16); TEST_ASSERT_EQUAL_INT(-1, ret); if (cipher) { @@ -1653,6 +1773,7 @@ TEST_CASE("crypto_support_fdo_kex_init_fdo_string_alloc_with_str_fail", ret = fdo_kex_init(); fdo_string_alloc_with_str_fail_case = false; TEST_ASSERT_EQUAL_INT(-1, ret); + fdo_kex_close(); } #ifndef TARGET_OS_FREERTOS @@ -1667,6 +1788,7 @@ TEST_CASE("crypto_support_fdo_kex_init_fdo_byte_array_alloc_fail", ret = fdo_kex_init(); fdo_byte_array_alloc_fail_case = false; TEST_ASSERT_EQUAL_INT(-1, ret); + fdo_kex_close(); } #ifndef TARGET_OS_FREERTOS @@ -1829,7 +1951,7 @@ void test_fdo_ov_verify(void) TEST_CASE("fdo_ov_verify", "[crypto_support][fdo]") #endif { - //TO-DO: Update test case for X509-encoded public key types. + // TO-DO: Update test case for X509-encoded public key types. TEST_IGNORE(); int ret; uint8_t test_buff[] = {1, 2, 3, 4, 5}; @@ -1850,7 +1972,7 @@ TEST_CASE("fdo_ov_verify", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -1923,7 +2045,7 @@ TEST_CASE("fdo_ov_verify", "[crypto_support][fdo]") if (pubkey) fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -1969,7 +2091,7 @@ TEST_CASE("fdo_ov_verify_invalid_message", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -2036,7 +2158,7 @@ TEST_CASE("fdo_ov_verify_invalid_message", "[crypto_support][fdo]") if (pubkey) fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -2080,7 +2202,7 @@ TEST_CASE("fdo_ov_verify_invalid_message_length", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -2147,7 +2269,7 @@ TEST_CASE("fdo_ov_verify_invalid_message_length", "[crypto_support][fdo]") if (pubkey) fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -2191,7 +2313,7 @@ TEST_CASE("fdo_ov_verify_invalid_message_signature", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -2258,7 +2380,7 @@ TEST_CASE("fdo_ov_verify_invalid_message_signature", "[crypto_support][fdo]") if (pubkey) fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -2302,7 +2424,7 @@ TEST_CASE("fdo_ov_verify_invalid_signature_len", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -2369,7 +2491,7 @@ TEST_CASE("fdo_ov_verify_invalid_signature_len", "[crypto_support][fdo]") if (pubkey) fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -2413,7 +2535,7 @@ TEST_CASE("fdo_ov_verify_invalid_pubkey", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -2479,7 +2601,7 @@ TEST_CASE("fdo_ov_verify_invalid_pubkey", "[crypto_support][fdo]") fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -2521,7 +2643,7 @@ TEST_CASE("fdo_ov_verify_invalid_result", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -2590,7 +2712,7 @@ TEST_CASE("fdo_ov_verify_invalid_result", "[crypto_support][fdo]") if (pubkey) fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -2616,7 +2738,7 @@ TEST_CASE("fdo_device_sign", "[crypto_support][fdo]") fdo_byte_array_t *signature = NULL; // Positive test case - ret = fdo_device_sign(message, message_len, &signature); + ret = fdo_device_sign(message, message_len, &signature, NULL); TEST_ASSERT_EQUAL(0, ret); if (signature) { fdo_byte_array_free(signature); @@ -2635,7 +2757,7 @@ TEST_CASE("fdo_device_sign_invalid_message", "[crypto_support][fdo]") fdo_byte_array_t *signature = NULL; /* Negative test case */ - ret = fdo_device_sign(NULL, message_len, &signature); + ret = fdo_device_sign(NULL, message_len, &signature, NULL); TEST_ASSERT_EQUAL(-1, ret); if (signature) { fdo_byte_array_free(signature); @@ -2654,7 +2776,7 @@ TEST_CASE("fdo_device_sign_invalid_message_len", "[crypto_support][fdo]") fdo_byte_array_t *signature = NULL; /* Negative test case */ - ret = fdo_device_sign(message, 0, &signature); + ret = fdo_device_sign(message, 0, &signature, NULL); TEST_ASSERT_EQUAL(-1, ret); if (signature) { fdo_byte_array_free(signature); @@ -3001,7 +3123,7 @@ TEST_CASE("crypto_hal_sig_verify_fail_case", "[crypto_support][fdo]") #else curve = 384; #endif - EC_KEY *validkey = generateECDSA_key(curve); + EVP_PKEY *validkey = generateECDSA_key(curve); TEST_ASSERT_NOT_NULL(validkey); ret = sha_ECCsign(curve, message, message_length, message_signature, &signature_len, validkey); @@ -3069,7 +3191,7 @@ TEST_CASE("crypto_hal_sig_verify_fail_case", "[crypto_support][fdo]") if (pubkey) fdo_public_key_free(pubkey); if (validkey) - EC_KEY_free(validkey); + EVP_PKEY_free(validkey); #endif #ifdef USE_MBEDTLS @@ -3099,7 +3221,7 @@ TEST_CASE("get_ec_key_fail_case", "[crypto_support][fdo]") fdo_byte_array_t *signature = NULL; get_ec_key_fail_flag = true; - ret = fdo_device_sign(message, message_len, &signature); + ret = fdo_device_sign(message, message_len, &signature, NULL); TEST_ASSERT_EQUAL(-1, ret); get_ec_key_fail_flag = false; @@ -3121,7 +3243,7 @@ TEST_CASE("ECDSA_size_fail_case", "[crypto_support][fdo]") fdo_byte_array_t *signature = NULL; ECDSA_size_fail_flag = true; - ret = fdo_device_sign(message, message_len, &signature); + ret = fdo_device_sign(message, message_len, &signature, NULL); TEST_ASSERT_EQUAL(-1, ret); ECDSA_size_fail_flag = false; @@ -3143,7 +3265,7 @@ TEST_CASE("memcpy_s_fail_case", "[crypto_support][fdo]") fdo_byte_array_t *signature = NULL; memcpy_s_fail_flag = true; - ret = fdo_device_sign(message, message_len, &signature); + ret = fdo_device_sign(message, message_len, &signature, NULL); memcpy_s_fail_flag = false; TEST_ASSERT_EQUAL(-1, ret); #else diff --git a/tests/unit/test_cryptoUtils.c b/tests/unit/test_cryptoUtils.c index a54e5c71..c21c34f9 100644 --- a/tests/unit/test_cryptoUtils.c +++ b/tests/unit/test_cryptoUtils.c @@ -16,8 +16,8 @@ #include "unity.h" #include "safe_mem_lib.h" #include "crypto_utils.h" -#include "fdoCryptoHal.h" -#include "fdoCrypto.h" +#include "fdo_crypto_hal.h" +#include "fdo_crypto.h" #ifdef TARGET_OS_LINUX /* @@ -212,7 +212,8 @@ void test_aes_encrypt_packet(void) ret = fdo_kex_init(); TEST_ASSERT_EQUAL_INT(0, ret); - ret = aes_encrypt_packet(cipher_txt, clear_txt->bytes, PLAIN_TEXT_SIZE, aad, sizeof(aad)); + ret = aes_encrypt_packet(cipher_txt, clear_txt->bytes, PLAIN_TEXT_SIZE, + aad, sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(0, ret, "AES Encryption Failed"); TEST_ASSERT_NOT_NULL(cipher_txt->em_body); @@ -222,18 +223,21 @@ void test_aes_encrypt_packet(void) } /* Negative Test Case */ - ret = aes_encrypt_packet(NULL, clear_txt->bytes, PLAIN_TEXT_SIZE, NULL, sizeof(aad)); + ret = aes_encrypt_packet(NULL, clear_txt->bytes, PLAIN_TEXT_SIZE, NULL, + sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "AES Encryption Failed"); /* Negative Test Case */ g_malloc_fail = true; - ret = aes_encrypt_packet(cipher_txt, clear_txt->bytes, PLAIN_TEXT_SIZE, aad, sizeof(aad)); + ret = aes_encrypt_packet(cipher_txt, clear_txt->bytes, PLAIN_TEXT_SIZE, + aad, sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "AES Encryption Failed"); g_malloc_fail = false; /* Negative Test Case */ g_memset_fail = true; - ret = aes_encrypt_packet(cipher_txt, clear_txt->bytes, PLAIN_TEXT_SIZE, aad, sizeof(aad)); + ret = aes_encrypt_packet(cipher_txt, clear_txt->bytes, PLAIN_TEXT_SIZE, + aad, sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "AES Encryption Failed"); g_memset_fail = false; @@ -245,6 +249,7 @@ void test_aes_encrypt_packet(void) fdo_bits_free(keyset->sek); fdo_byte_array_free(keyset->svk); fdo_free(keyset); + fdo_free(aad); } #ifdef TARGET_OS_FREERTOS @@ -258,7 +263,8 @@ void test_aes_decrypt_packet(void) fdo_alloc(sizeof(fdo_encrypted_packet_t)); fdo_aes_keyset_t *keyset = fdo_alloc(sizeof(fdo_aes_keyset_t)); fdo_byte_array_t *cleartext = getcleartext(PLAIN_TEXT_SIZE); - fdo_byte_array_t *cleartext_decrypted = fdo_byte_array_alloc(PLAIN_TEXT_SIZE); + fdo_byte_array_t *cleartext_decrypted = + fdo_byte_array_alloc(PLAIN_TEXT_SIZE); uint8_t *aad = NULL; TEST_ASSERT_NOT_NULL(cipher_txt); @@ -283,9 +289,11 @@ void test_aes_decrypt_packet(void) ret = fdo_kex_init(); TEST_ASSERT_EQUAL_INT(0, ret); - ret = aes_encrypt_packet(cipher_txt, cleartext->bytes, PLAIN_TEXT_SIZE, aad, sizeof(aad)); + ret = aes_encrypt_packet(cipher_txt, cleartext->bytes, PLAIN_TEXT_SIZE, + aad, sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(0, ret, "AES Encryption Failed"); - ret = aes_decrypt_packet(cipher_txt, cleartext_decrypted, aad, sizeof(aad)); + ret = aes_decrypt_packet(cipher_txt, cleartext_decrypted, aad, + sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(0, ret, "AES Decryption Failed"); if (cipher_txt->em_body) { @@ -299,7 +307,8 @@ void test_aes_decrypt_packet(void) /* Negative Test Case */ g_malloc_fail = true; - ret = aes_decrypt_packet(cipher_txt, cleartext_decrypted, aad, sizeof(aad)); + ret = aes_decrypt_packet(cipher_txt, cleartext_decrypted, aad, + sizeof(aad)); TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "AES Decryption Failed"); g_malloc_fail = false; diff --git a/tests/unit/test_fdoblockio.c b/tests/unit/test_fdoblockio.c index 2a705b37..39863b55 100644 --- a/tests/unit/test_fdoblockio.c +++ b/tests/unit/test_fdoblockio.c @@ -19,33 +19,36 @@ /*** Unity Declarations ***/ void test_encode_decode(void); -void test_encode_decode(void) { +void test_encode_decode(void) +{ fdow_t *fdow = fdo_alloc(sizeof(fdow_t)); fdor_t *fdor = fdo_alloc(sizeof(fdor_t)); - if (!fdow_init(fdow)) - LOG(LOG_ERROR, "Failed to initialize fdow\n"); + if (!fdow_init(fdow)) + LOG(LOG_ERROR, "Failed to initialize fdow\n"); if (!fdor_init(fdor)) - LOG(LOG_ERROR, "Failed to initialize fdor\n"); + LOG(LOG_ERROR, "Failed to initialize fdor\n"); TEST_ASSERT_NOT_NULL(fdow); TEST_ASSERT_NOT_NULL(fdor); - + uint64_t key1 = 1, key2 = 2; int val1 = 50, val3 = 100; - + TEST_ASSERT_TRUE(fdo_block_alloc(&fdow->b)); TEST_ASSERT_TRUE(fdow_encoder_init(fdow)); TEST_ASSERT_TRUE(fdo_block_alloc(&fdor->b)); - TEST_ASSERT_TRUE(fdow_start_array(fdow, 1)); + TEST_ASSERT_TRUE(fdow_start_array(fdow, 1)); TEST_ASSERT_TRUE(fdow_start_array(fdow, 2)); TEST_ASSERT_TRUE(fdow_start_map(fdow, 2)); TEST_ASSERT_TRUE(fdow_unsigned_int(fdow, key1)); TEST_ASSERT_TRUE(fdow_signed_int(fdow, val1)); TEST_ASSERT_TRUE(fdow_unsigned_int(fdow, key2)); - fdo_byte_array_t *mstring = fdo_byte_array_alloc(sizeof(fdo_byte_array_t)); + fdo_byte_array_t *mstring = + fdo_byte_array_alloc(sizeof(fdo_byte_array_t)); TEST_ASSERT_NOT_NULL(mstring); - if (memset_s(mstring->bytes, mstring->byte_sz * sizeof(uint8_t), 0) != 0) { + if (memset_s(mstring->bytes, mstring->byte_sz * sizeof(uint8_t), 0) != + 0) { LOG(LOG_ERROR, "memset() failed!\n"); } fdow_byte_string(fdow, mstring->bytes, mstring->byte_sz); @@ -54,18 +57,19 @@ void test_encode_decode(void) { TEST_ASSERT_TRUE(fdow_end_array(fdow)); TEST_ASSERT_TRUE(fdow_end_array(fdow)); - long unsigned i; - size_t finalLength; - TEST_ASSERT_TRUE(fdow_encoded_length(fdow, &finalLength)); + long unsigned i; + size_t finalLength; + TEST_ASSERT_TRUE(fdow_encoded_length(fdow, &finalLength)); LOG(LOG_INFO, "\nEncoded Length : %zu\n", finalLength); - for(i=0; ib.block[i]); } LOG(LOG_INFO, "\nEncoding finished successfully\n"); fdow->b.block_size = finalLength; fdor->b.block_size = finalLength; - memcpy_s(fdor->b.block, CBOR_BUFFER_LENGTH, fdow->b.block, fdow->b.block_size); + memcpy_s(fdor->b.block, CBOR_BUFFER_LENGTH, fdow->b.block, + fdow->b.block_size); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); TEST_ASSERT_TRUE(fdor_start_array(fdor)); TEST_ASSERT_TRUE(fdor_start_array(fdor)); @@ -73,7 +77,7 @@ void test_encode_decode(void) { uint64_t item1; TEST_ASSERT_TRUE(fdor_unsigned_int(fdor, &item1)); TEST_ASSERT_EQUAL_UINT64(item1, key1); - int item2; + int item2; TEST_ASSERT_TRUE(fdor_signed_int(fdor, &item2)); TEST_ASSERT_EQUAL_INT(item2, val1); uint64_t item3; @@ -94,5 +98,14 @@ void test_encode_decode(void) { TEST_ASSERT_TRUE(fdor_end_array(fdor)); LOG(LOG_INFO, "\nDecoding finished successfully\n"); fdow_flush(fdow); + fdo_free(fdow); fdor_flush(fdor); -} \ No newline at end of file + fdo_free(fdor); + if (mstring) { + fdo_byte_array_free(mstring); + mstring = NULL; + } + if (item4) { + fdo_free(item4); + } +} diff --git a/tests/unit/test_fdonet.c b/tests/unit/test_fdonet.c index a0e16e84..05105d9b 100644 --- a/tests/unit/test_fdonet.c +++ b/tests/unit/test_fdonet.c @@ -24,8 +24,8 @@ bool __wrap_cache_host_ip(fdo_ip_address_t *ip); bool __wrap_cache_host_port(uint16_t port); int32_t __wrap_fdo_con_dns_lookup(char *dns, fdo_ip_address_t **ip_list, uint32_t *ip_list_size); -fdo_con_handle __wrap_fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, - void **ssl); +int32_t __wrap_fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, + void **ssl); fdo_byte_array_t *__wrap_fdo_byte_array_alloc(int byte_sz); bool __wrap_fdor_init(fdor_t *fdor, FDOReceive_fcn_ptr_t rcv, void *rcv_data); void test_setup_http_proxy(void); @@ -98,13 +98,13 @@ int32_t __wrap_fdo_con_dns_lookup(char *dns, fdo_ip_address_t **ip_list, } static bool connect_fail = false; -fdo_con_handle __real_fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, - void **ssl); -fdo_con_handle __wrap_fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, - void **ssl) +int32_t __real_fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, + void **ssl); +int32_t __wrap_fdo_con_connect(fdo_ip_address_t *ip_addr, uint16_t port, + void **ssl) { if (connect_fail) - return FDO_CON_INVALID_HANDLE; + return -1; else return __real_fdo_con_connect(ip_addr, port, ssl); } @@ -205,25 +205,23 @@ void test_Connect_toManufacturer(void) uint16_t port = 8039; bool ret = false; - fdo_con_handle sock = FDO_CON_INVALID_HANDLE; - ip.length = 4; - ret = connect_to_manufacturer(NULL, 0, NULL, NULL); + ret = connect_to_manufacturer(NULL, NULL, 0, NULL); TEST_ASSERT_FALSE(ret); cache_ip_fail = true; - ret = connect_to_manufacturer(&ip, port, &sock, NULL); + ret = connect_to_manufacturer(&ip, NULL, port, NULL); TEST_ASSERT_FALSE(ret); cache_ip_fail = false; cache_port_fail = true; - ret = connect_to_manufacturer(&ip, port, &sock, NULL); + ret = connect_to_manufacturer(&ip, NULL, port, NULL); TEST_ASSERT_FALSE(ret); cache_port_fail = false; connect_fail = true; - ret = connect_to_manufacturer(NULL, port, &sock, NULL); + ret = connect_to_manufacturer(NULL, NULL, port, NULL); TEST_ASSERT_FALSE(ret); connect_fail = false; } @@ -240,25 +238,23 @@ void test_Connect_toRendezvous(void) uint16_t port = 8041; bool ret = false; - fdo_con_handle sock = FDO_CON_INVALID_HANDLE; - ip.length = 4; - ret = connect_to_rendezvous(NULL, 0, NULL, NULL); + ret = connect_to_rendezvous(NULL, NULL, 0, NULL); TEST_ASSERT_FALSE(ret); cache_ip_fail = true; - ret = connect_to_rendezvous(&ip, port, &sock, NULL); + ret = connect_to_rendezvous(&ip, NULL, port, NULL); TEST_ASSERT_FALSE(ret); cache_ip_fail = false; cache_port_fail = true; - ret = connect_to_rendezvous(&ip, port, &sock, NULL); + ret = connect_to_rendezvous(&ip, NULL, port, NULL); TEST_ASSERT_FALSE(ret); cache_port_fail = false; connect_fail = true; - ret = connect_to_rendezvous(NULL, port, &sock, NULL); + ret = connect_to_rendezvous(NULL, NULL, port, NULL); TEST_ASSERT_FALSE(ret); connect_fail = false; } @@ -275,25 +271,23 @@ void test_Connect_toOwner(void) uint16_t port = 8042; bool ret = false; - fdo_con_handle sock = FDO_CON_INVALID_HANDLE; - ip.length = 4; - ret = connect_to_owner(NULL, 0, NULL, NULL); + ret = connect_to_owner(NULL, NULL, 0, NULL); TEST_ASSERT_FALSE(ret); cache_ip_fail = true; - ret = connect_to_owner(&ip, port, &sock, NULL); + ret = connect_to_owner(&ip, NULL, port, NULL); TEST_ASSERT_FALSE(ret); cache_ip_fail = false; cache_port_fail = true; - ret = connect_to_owner(&ip, port, &sock, NULL); + ret = connect_to_owner(&ip, NULL, port, NULL); TEST_ASSERT_FALSE(ret); cache_port_fail = false; connect_fail = true; - ret = connect_to_owner(NULL, port, &sock, NULL); + ret = connect_to_owner(NULL, NULL, port, NULL); TEST_ASSERT_FALSE(ret); connect_fail = false; } diff --git a/tests/unit/test_fdotypes.c b/tests/unit/test_fdotypes.c index fa617781..c5e7a94d 100644 --- a/tests/unit/test_fdotypes.c +++ b/tests/unit/test_fdotypes.c @@ -7,8 +7,8 @@ #include "crypto_utils.h" #include "fdoprot.h" #include "fdotypes.h" -#include "fdoCrypto.h" -#include "fdoCryptoHal.h" +#include "fdo_crypto.h" +#include "fdo_crypto_hal.h" #include "util.h" #include "fdo.h" #include @@ -19,7 +19,7 @@ /***! * \file * \brief Unit tests for FDO defined data structure parsing/packing routines. -**/ + **/ /*** Unity Declarations. ***/ void set_up(void); @@ -69,14 +69,13 @@ void test_fdo_compare_hashes(void); void test_fdo_compare_byte_arrays(void); void test_fdo_compare_rvLists(void); - /*** Unity functions. ***/ /* * set_up function is called at the beginning of each test-case in unity * framework. Declare, Initialize all mandatory variables needed at the start * to execute the test-case. * @return none. -*/ + */ void set_up(void) { } @@ -364,11 +363,11 @@ void test_fdo_hash_read(void) int ret; // sample CBOR encoded HMAC with HMAC-SHA384 data uint8_t hmac_cbor[] = { - 0x82, 0x06, 0x58, 0x30, 0x89, 0x5B, 0xD7, 0x23, 0x65, 0xFE, 0xE9, 0x3F, 0x89, - 0x65, 0xBB, 0x5E, 0xB7, 0xDF, 0x6E, 0x74, 0xF6, 0xA8, 0x64, 0x21, 0xA7, 0x22, - 0x74, 0xC5, 0xAC, 0xC5, 0x48, 0x81, 0x3E, 0x8F, 0x60, 0x1A, 0x05, 0xE4, 0xA6, - 0x28, 0xDC, 0x79, 0x1E, 0x30, 0xCB, 0x49, 0x6E, 0x69, 0xB9, 0x9B, 0x0F, 0x1C - }; + 0x82, 0x06, 0x58, 0x30, 0x89, 0x5B, 0xD7, 0x23, 0x65, 0xFE, 0xE9, + 0x3F, 0x89, 0x65, 0xBB, 0x5E, 0xB7, 0xDF, 0x6E, 0x74, 0xF6, 0xA8, + 0x64, 0x21, 0xA7, 0x22, 0x74, 0xC5, 0xAC, 0xC5, 0x48, 0x81, 0x3E, + 0x8F, 0x60, 0x1A, 0x05, 0xE4, 0xA6, 0x28, 0xDC, 0x79, 0x1E, 0x30, + 0xCB, 0x49, 0x6E, 0x69, 0xB9, 0x9B, 0x0F, 0x1C}; ret = fdo_hash_read(NULL, NULL); TEST_ASSERT_EQUAL_INT(0, ret); @@ -377,7 +376,8 @@ void test_fdo_hash_read(void) TEST_ASSERT_NOT_NULL(fdor); TEST_ASSERT_TRUE(fdor_init(fdor)); TEST_ASSERT_TRUE(fdo_block_alloc(&fdor->b)); - memcpy_s(fdor->b.block, sizeof(hmac_cbor), hmac_cbor, sizeof(hmac_cbor)); + memcpy_s(fdor->b.block, sizeof(hmac_cbor), hmac_cbor, + sizeof(hmac_cbor)); fdor->b.block_size = sizeof(hmac_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); @@ -449,15 +449,14 @@ void test_fdo_read_ipaddress(void) fdo_ip_address_t fdoip = {0}; bool ret; // sample CBOR encoded IPV4 address - uint8_t ipv4_cbor[] = { - 0x44, 0x7F, 0x00, 0x00, 0x01 - }; + uint8_t ipv4_cbor[] = {0x44, 0x7F, 0x00, 0x00, 0x01}; fdor = fdo_alloc(sizeof(fdor_t)); TEST_ASSERT_NOT_NULL(fdor); TEST_ASSERT_TRUE(fdor_init(fdor)); TEST_ASSERT_TRUE(fdo_block_alloc(&fdor->b)); - memcpy_s(fdor->b.block, sizeof(ipv4_cbor), ipv4_cbor, sizeof(ipv4_cbor)); + memcpy_s(fdor->b.block, sizeof(ipv4_cbor), ipv4_cbor, + sizeof(ipv4_cbor)); fdor->b.block_size = sizeof(ipv4_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); @@ -599,7 +598,8 @@ void test_fdo_public_key_write(void) TEST_ASSERT_TRUE(fdow_encoder_init(fdow)); fdopubkey = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384, - FDO_CRYPTO_PUB_KEY_ENCODING_X509, sizeof(pkey), pkey); + FDO_CRYPTO_PUB_KEY_ENCODING_X509, + sizeof(pkey), pkey); TEST_ASSERT_NOT_NULL(fdopubkey); ret = fdo_public_key_write(NULL, fdopubkey); @@ -625,28 +625,30 @@ TEST_CASE("fdo_public_key_read", "[fdo_types][fdo]") void test_fdo_public_key_read(void) #endif { -#if !defined (AES_MODE_GCM_ENABLED) || AES_BITS == 256 +#if !defined(AES_MODE_GCM_ENABLED) || AES_BITS == 256 TEST_IGNORE(); #endif fdor_t *fdor = NULL; fdo_public_key_t *fdopubkey = NULL; // sample CBOR encoded public key uint8_t pubkey_cbor[] = { - 0x83, 0x0A, 0x01, 0x58, 0x60, 0x92, 0x11, 0x12, 0xFD, 0x17, 0xEC, 0x7F, 0x33,0x05, - 0x24, 0xFD, 0x4D, 0xE3, 0x18, 0xE5, 0x0A, 0x85, 0x93, 0x3A, 0xDA, 0xFF, 0x6B, 0x2F, - 0x1B, 0x7C, 0x51, 0xE5, 0x5D, 0xFB, 0x52, 0x71, 0x02, 0x33, 0x94, 0xAE, 0x3F, 0x7D, - 0x1F, 0xDE, 0x29, 0x82, 0x27, 0x30, 0x4A, 0x01, 0xE5, 0x4B, 0x08, 0x90, 0xFE, 0x98, - 0xA3, 0xEA, 0x09, 0xD4, 0x01, 0x1C, 0xE0, 0xCC, 0xC5, 0x37, 0xCD, 0xCD, 0xFF, 0x55, - 0x3B, 0x21, 0x83, 0x24, 0x93, 0x3C, 0x72, 0x55, 0xE2, 0x49, 0xB4, 0xA3, 0xF5, 0x38, - 0x0E, 0x0D, 0x16, 0x58, 0x97, 0x15, 0xCE, 0x9F, 0x0B, 0xC7, 0xB2, 0xE8, 0x0F, 0xAF, - 0xB6, 0x15, 0x89 - }; + 0x83, 0x0A, 0x01, 0x58, 0x60, 0x92, 0x11, 0x12, 0xFD, 0x17, 0xEC, + 0x7F, 0x33, 0x05, 0x24, 0xFD, 0x4D, 0xE3, 0x18, 0xE5, 0x0A, 0x85, + 0x93, 0x3A, 0xDA, 0xFF, 0x6B, 0x2F, 0x1B, 0x7C, 0x51, 0xE5, 0x5D, + 0xFB, 0x52, 0x71, 0x02, 0x33, 0x94, 0xAE, 0x3F, 0x7D, 0x1F, 0xDE, + 0x29, 0x82, 0x27, 0x30, 0x4A, 0x01, 0xE5, 0x4B, 0x08, 0x90, 0xFE, + 0x98, 0xA3, 0xEA, 0x09, 0xD4, 0x01, 0x1C, 0xE0, 0xCC, 0xC5, 0x37, + 0xCD, 0xCD, 0xFF, 0x55, 0x3B, 0x21, 0x83, 0x24, 0x93, 0x3C, 0x72, + 0x55, 0xE2, 0x49, 0xB4, 0xA3, 0xF5, 0x38, 0x0E, 0x0D, 0x16, 0x58, + 0x97, 0x15, 0xCE, 0x9F, 0x0B, 0xC7, 0xB2, 0xE8, 0x0F, 0xAF, 0xB6, + 0x15, 0x89}; fdor = fdo_alloc(sizeof(fdor_t)); TEST_ASSERT_NOT_NULL(fdor); TEST_ASSERT_TRUE(fdor_init(fdor)); TEST_ASSERT_TRUE(fdo_block_alloc(&fdor->b)); - memcpy_s(fdor->b.block, sizeof(pubkey_cbor), pubkey_cbor, sizeof(pubkey_cbor)); + memcpy_s(fdor->b.block, sizeof(pubkey_cbor), pubkey_cbor, + sizeof(pubkey_cbor)); fdor->b.block_size = sizeof(pubkey_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); @@ -663,7 +665,6 @@ void test_fdo_public_key_read(void) if (fdopubkey) { fdo_public_key_free(fdopubkey); } - } #ifdef TARGET_OS_FREERTOS @@ -710,7 +711,7 @@ TEST_CASE("fdo_rendezvous_list_write", "[fdo_types][fdo]") void test_fdo_rendezvous_list_write(void) #endif { - + TEST_IGNORE(); fdow_t *fdow = NULL; fdo_rendezvous_t *rv = NULL; fdo_rendezvous_list_t *rvlist = NULL; @@ -780,17 +781,17 @@ TEST_CASE("fdo_rendezvous_list_read", "[fdo_types][fdo]") void test_fdo_rendezvous_list_read(void) #endif { - //TO-DO: Encapsulate sample CBOR encoded RV blob with byte strings + // TO-DO: Encapsulate sample CBOR encoded RV blob with byte strings TEST_IGNORE(); fdor_t *fdor = NULL; fdo_rendezvous_list_t *rvlist = NULL; bool ret; // sample CBOR encoded RV blob - uint8_t rv_cbor[] = { - 0x81, 0x85, 0x82, 0x05, 0x69, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x68, 0x6F, 0x73, 0x74, - 0x82, 0x03, 0x19, 0x1F, 0x68, 0x82, 0x0C, 0x01, 0x82, 0x02, 0x44, 0x7F, 0x00, 0x00, - 0x01, 0x82, 0x04, 0x19, 0x20, 0xFB - }; + uint8_t rv_cbor[] = {0x81, 0x85, 0x82, 0x05, 0x69, 0x6C, 0x6F, + 0x63, 0x61, 0x6C, 0x68, 0x6F, 0x73, 0x74, + 0x82, 0x03, 0x19, 0x1F, 0x68, 0x82, 0x0C, + 0x01, 0x82, 0x02, 0x44, 0x7F, 0x00, 0x00, + 0x01, 0x82, 0x04, 0x19, 0x20, 0xFB}; fdor = fdo_alloc(sizeof(fdor_t)); TEST_ASSERT_NOT_NULL(fdor); @@ -852,8 +853,6 @@ void test_fdo_rendezvous_list_get(void) ret = fdo_rendezvous_list_get(NULL, 0); TEST_ASSERT_NULL(ret); - - } #ifdef TARGET_OS_FREERTOS @@ -862,7 +861,8 @@ TEST_CASE("fdo_encrypted_packet_read", "[fdo_types][fdo]") void test_fdo_encrypted_packet_read(void) #endif { - //TO-DO: Update sample CBOR encoded Encrypted Message body with COSE Tag + // TO-DO: Update sample CBOR encoded Encrypted Message body with COSE + // Tag TEST_IGNORE(); fdor_t *fdor = NULL; fdo_encrypted_packet_t *pkt = NULL; @@ -872,39 +872,36 @@ void test_fdo_encrypted_packet_read(void) // IV 12/7 bytes #if COSE_ENC_TYPE == 1 uint8_t enc_msg_cbor[] = { - 0x83, 0x43, 0xa1, 0x01, 0x01, 0xa1, 0x05, 0x4c, 0xfe, 0x6b, 0x0d, - 0x51, 0x5a, 0x74, 0xe6, 0xe8, 0xb5, 0xa0, 0x07, 0x89, 0x54, 0x48, - 0x66, 0x0b, 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, 0x2f, - 0xfa, 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e - }; + 0x83, 0x43, 0xa1, 0x01, 0x01, 0xa1, 0x05, 0x4c, 0xfe, 0x6b, 0x0d, + 0x51, 0x5a, 0x74, 0xe6, 0xe8, 0xb5, 0xa0, 0x07, 0x89, 0x54, 0x48, + 0x66, 0x0b, 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, 0x2f, + 0xfa, 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e}; #elif COSE_ENC_TYPE == 3 uint8_t enc_msg_cbor[] = { - 0x83, 0x43, 0xa1, 0x01, 0x03, 0xa1, 0x05, 0x4c, 0xfe, 0x6b, 0x0d, - 0x51, 0x5a, 0x74, 0xe6, 0xe8, 0xb5, 0xa0, 0x07, 0x89, 0x54, 0x48, - 0x66, 0x0b, 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, 0x2f, - 0xfa, 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e - }; + 0x83, 0x43, 0xa1, 0x01, 0x03, 0xa1, 0x05, 0x4c, 0xfe, 0x6b, 0x0d, + 0x51, 0x5a, 0x74, 0xe6, 0xe8, 0xb5, 0xa0, 0x07, 0x89, 0x54, 0x48, + 0x66, 0x0b, 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, 0x2f, + 0xfa, 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e}; #elif COSE_ENC_TYPE == 32 uint8_t enc_msg_cbor[] = { - 0x83, 0x44, 0xa1, 0x01, 0x18, 0x20, 0xa1, 0x05, 0x47, 0xfe, 0x6b, - 0x0d, 0x51, 0x5a, 0x74, 0xe6, 0x54, - 0x48, 0x66, 0x0b, 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, - 0x2f, 0xfa, 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e - }; + 0x83, 0x44, 0xa1, 0x01, 0x18, 0x20, 0xa1, 0x05, 0x47, 0xfe, + 0x6b, 0x0d, 0x51, 0x5a, 0x74, 0xe6, 0x54, 0x48, 0x66, 0x0b, + 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, 0x2f, 0xfa, + 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e}; #else uint8_t enc_msg_cbor[] = { - 0x83, 0x44, 0xa1, 0x01, 0x18, 0x21, 0xa1, 0x05, 0x47, 0xfe, 0x6b, - 0x0d, 0x51, 0x5a, 0x74, 0xe6, 0x54, - 0x48, 0x66, 0x0b, 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, - 0x2f, 0xfa, 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e - }; + 0x83, 0x44, 0xa1, 0x01, 0x18, 0x21, 0xa1, 0x05, 0x47, 0xfe, + 0x6b, 0x0d, 0x51, 0x5a, 0x74, 0xe6, 0x54, 0x48, 0x66, 0x0b, + 0x35, 0xbc, 0x04, 0xd1, 0x05, 0x07, 0x9a, 0x0a, 0x2f, 0xfa, + 0x25, 0x28, 0xd3, 0x53, 0x5e, 0xb5, 0x1e}; #endif fdor = fdo_alloc(sizeof(fdor_t)); TEST_ASSERT_NOT_NULL(fdor); TEST_ASSERT_TRUE(fdor_init(fdor)); TEST_ASSERT_TRUE(fdo_block_alloc(&fdor->b)); - memcpy_s(fdor->b.block, sizeof(enc_msg_cbor), enc_msg_cbor, sizeof(enc_msg_cbor)); + memcpy_s(fdor->b.block, sizeof(enc_msg_cbor), enc_msg_cbor, + sizeof(enc_msg_cbor)); fdor->b.block_size = sizeof(enc_msg_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); @@ -934,8 +931,8 @@ TEST_CASE("fdo_encrypted_packet_windup", "[fdo_types][fdo]") void test_fdo_encrypted_packet_windup(void) #endif { - // test this when encryption is mocked, add 'fdo_encrypted_packet_unwind()' as well - // ignore the test for now + // test this when encryption is mocked, add + // 'fdo_encrypted_packet_unwind()' as well ignore the test for now TEST_IGNORE(); fdow_t *fdow = NULL; @@ -1114,20 +1111,20 @@ TEST_CASE("fdo_cose_read", "[fdo_types][fdo]") void test_fdo_cose_read(void) #endif { - //TO-DO: Update sample COSE CBOR with COSE Tag + // TO-DO: Update sample COSE CBOR with COSE Tag TEST_IGNORE(); fdor_t *fdor = NULL; fdo_cose_t *cose = NULL; bool ret; - uint8_t cose_cbor[] = { - 0x84, 0x44, 0xA1, 0x01, 0x38, 0x22, 0xA0, 0x41, 0x02, 0x41, 0x02 - }; + uint8_t cose_cbor[] = {0x84, 0x44, 0xA1, 0x01, 0x38, 0x22, + 0xA0, 0x41, 0x02, 0x41, 0x02}; fdor = fdo_alloc(sizeof(fdor_t)); TEST_ASSERT_NOT_NULL(fdor); TEST_ASSERT_TRUE(fdor_init(fdor)); TEST_ASSERT_TRUE(fdo_block_alloc(&fdor->b)); - memcpy_s(fdor->b.block, sizeof(cose_cbor), cose_cbor, sizeof(cose_cbor)); + memcpy_s(fdor->b.block, sizeof(cose_cbor), cose_cbor, + sizeof(cose_cbor)); fdor->b.block_size = sizeof(cose_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); @@ -1138,14 +1135,16 @@ void test_fdo_cose_read(void) ret = fdo_cose_read(fdor, cose, true); TEST_ASSERT_TRUE(ret); - memcpy_s(fdor->b.block, sizeof(cose_cbor), cose_cbor, sizeof(cose_cbor)); + memcpy_s(fdor->b.block, sizeof(cose_cbor), cose_cbor, + sizeof(cose_cbor)); fdor->b.block_size = sizeof(cose_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); ret = fdo_cose_read(fdor, cose, false); TEST_ASSERT_FALSE(ret); cose_cbor[0] = 0x83; - memcpy_s(fdor->b.block, sizeof(cose_cbor), cose_cbor, sizeof(cose_cbor)); + memcpy_s(fdor->b.block, sizeof(cose_cbor), cose_cbor, + sizeof(cose_cbor)); fdor->b.block_size = sizeof(cose_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); ret = fdo_cose_read(fdor, cose, true); @@ -1216,20 +1215,17 @@ void test_fdo_siginfo_read(void) fdor_t *fdor = NULL; bool ret; #if defined(ECDSA384_DA) - uint8_t siginfo_cbor[] = { - 0x82, 0x38, 0x22, 0x40 - }; + uint8_t siginfo_cbor[] = {0x82, 0x38, 0x22, 0x40}; #else - uint8_t siginfo_cbor[] = { - 0x82, 0x26, 0x40 - }; + uint8_t siginfo_cbor[] = {0x82, 0x26, 0x40}; #endif fdor = fdo_alloc(sizeof(fdor_t)); TEST_ASSERT_NOT_NULL(fdor); TEST_ASSERT_TRUE(fdor_init(fdor)); TEST_ASSERT_TRUE(fdo_block_alloc(&fdor->b)); - memcpy_s(fdor->b.block, sizeof(siginfo_cbor), siginfo_cbor, sizeof(siginfo_cbor)); + memcpy_s(fdor->b.block, sizeof(siginfo_cbor), siginfo_cbor, + sizeof(siginfo_cbor)); fdor->b.block_size = sizeof(siginfo_cbor); TEST_ASSERT_TRUE(fdor_parser_init(fdor)); @@ -1380,8 +1376,7 @@ void test_fdo_service_info_add_kv_bool(void) TEST_ASSERT_FALSE(ret); // update existing key with updated value is a positive case - ret = - fdo_service_info_add_kv_bool(si, "dummy_key", false); + ret = fdo_service_info_add_kv_bool(si, "dummy_key", false); TEST_ASSERT_TRUE(ret); if (si) { @@ -1414,8 +1409,7 @@ void test_fdo_service_info_add_kv_int(void) TEST_ASSERT_FALSE(ret); // update existing key with updated value is a positive case - ret = - fdo_service_info_add_kv_int(si, "dummy_key", 7); + ret = fdo_service_info_add_kv_int(si, "dummy_key", 7); TEST_ASSERT_TRUE(ret); if (si) { @@ -1452,14 +1446,13 @@ void test_fdo_service_info_add_kv_bin(void) // update existing key with updated value is a positive case memset_s(bytes->bytes, 10, 1); - ret = - fdo_service_info_add_kv_bin(si, "dummy_key", bytes); + ret = fdo_service_info_add_kv_bin(si, "dummy_key", bytes); TEST_ASSERT_TRUE(ret); if (si) { fdo_service_info_free(si); } - if (bytes){ + if (bytes) { fdo_byte_array_free(bytes); } } @@ -1494,15 +1487,18 @@ void test_fdo_serviceinfo_invalid_modname_add(void) bool ret = false; fdo_sv_invalid_modnames_t *serviceinfo_invalid_modnames = NULL; - ret = fdo_serviceinfo_invalid_modname_add("testmod1", &serviceinfo_invalid_modnames); + ret = fdo_serviceinfo_invalid_modname_add( + "testmod1", &serviceinfo_invalid_modnames); TEST_ASSERT_TRUE(ret); TEST_ASSERT_NOT_NULL(serviceinfo_invalid_modnames); - ret = fdo_serviceinfo_invalid_modname_add("testmod1", &serviceinfo_invalid_modnames); + ret = fdo_serviceinfo_invalid_modname_add( + "testmod1", &serviceinfo_invalid_modnames); TEST_ASSERT_TRUE(ret); TEST_ASSERT_NOT_NULL(serviceinfo_invalid_modnames); - ret = fdo_serviceinfo_invalid_modname_add("testmod2", &serviceinfo_invalid_modnames); + ret = fdo_serviceinfo_invalid_modname_add( + "testmod2", &serviceinfo_invalid_modnames); TEST_ASSERT_TRUE(ret); TEST_ASSERT_NOT_NULL(serviceinfo_invalid_modnames->next); diff --git a/tests/unit/test_hal_os.c b/tests/unit/test_hal_os.c index 5ea357e7..14dc6717 100644 --- a/tests/unit/test_hal_os.c +++ b/tests/unit/test_hal_os.c @@ -11,7 +11,7 @@ #include #include "network_al.h" #include -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "fdoprotctx.h" #include "rest_interface.h" #include @@ -133,17 +133,24 @@ int __wrap_connect(int socket, const struct sockaddr *address, * Note: This function is copied from NW HAL just for testing purpose. * The same function is a static function in NW HAL. * - * @param sock - socket-id. * @param out - out pointer to REST header line. * @param size - REST header size. * @retval true if line read was successful, false otherwise. */ -static bool read_until_new_line(fdo_con_handle handle, char *out, size_t size) +static bool read_until_new_line(char *out, size_t size) { - int sz, n; + int sz; char c; - struct fdo_sock_handle *sock_hdl = handle; - int sockfd = sock_hdl->sockfd; + char curl_buf_offset = 0; + static int curl_buf[50]; + char alphabet[27] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\n'}; + + // create random int and store in randomArray + for (int i = 0; i < 50; i++) { + curl_buf[i] = alphabet[rand() % 27]; + } if (!out || !size) return false; @@ -151,16 +158,15 @@ static bool read_until_new_line(fdo_con_handle handle, char *out, size_t size) --size; // leave room for NULL sz = 0; for (;;) { - n = recv(sockfd, (uint8_t *)&c, 1, MSG_WAITALL); - - if (n <= 0) - return false; + c = curl_buf[curl_buf_offset + sz]; if ((uint8_t)sz < size) out[sz++] = c; - if (c == '\n') + if (c == '\n') { + curl_buf_offset += sz; break; + } } out[sz] = 0; /* remove \n and \r and don't process invalid string */ @@ -195,20 +201,19 @@ void test_fdo_con_connect(void) /* False tests */ return_socket = -1; - TEST_ASSERT_EQUAL_INT( - FDO_CON_INVALID_HANDLE, - fdo_con_connect(&fdoip, port, NULL)); /* socket() returns -1 */ + TEST_ASSERT_EQUAL_INT(-1, + fdo_con_connect(&fdoip, NULL, port, + NULL)); /* socket() returns -1 */ return_socket = 0; - TEST_ASSERT_EQUAL_INT( - FDO_CON_INVALID_HANDLE, - fdo_con_connect(&fdoip, port, NULL)); /* connect() returns -1 */ + TEST_ASSERT_EQUAL_INT(-1, + fdo_con_connect(&fdoip, NULL, port, + NULL)); /* connect() returns -1 */ /* Pass tests */ return_socket = 123; - uint16_t *ret_val; - ret_val = fdo_con_connect(&fdoip, port, NULL); - TEST_ASSERT_NOT_EQUAL(FDO_CON_INVALID_HANDLE, ret_val); - fdo_free(ret_val); + int ret_val; + ret_val = fdo_con_connect(&fdoip, NULL, port, NULL); + TEST_ASSERT_NOT_EQUAL(-1, ret_val); // undo setup rest protocol fdo_con_teardown(); @@ -220,8 +225,8 @@ TEST_CASE("fdo_con_disconnect", "[OS][HAL][fdo]") void test_fdo_con_disconnect(void) #endif { - fdo_con_handle handle = FDO_CON_INVALID_HANDLE; - TEST_ASSERT_EQUAL_INT(0, fdo_con_disconnect(handle)); + curl = curl_easy_init(); + TEST_ASSERT_EQUAL_INT(0, fdo_con_disconnect()); } #ifdef TARGET_OS_FREERTOS TEST_CASE("fdo_con_recv_message", "[OS][HAL][fdo]") @@ -232,9 +237,13 @@ void test_fdo_con_recv_message(void) uint8_t buf[5]; char curl_buf[5]; ssize_t nbytes = 5; + + for (int i = 0; i < 5; i++) { + curl_buf[i] = rand() % 100 + 1; + } + curl = curl_easy_init(); - TEST_ASSERT_EQUAL_INT(5, - fdo_con_recv_msg_body(buf, nbytes, curl_buf, 0)); + TEST_ASSERT_EQUAL_INT(0, fdo_con_parse_msg_body(buf, nbytes, curl_buf)); } #ifdef TARGET_OS_FREERTOS @@ -243,17 +252,15 @@ TEST_CASE("fdo_con_send_message", "[OS][HAL][fdo]") void test_fdo_con_send_message(void) #endif { - fdo_con_handle sock = FDO_CON_INVALID_HANDLE; uint8_t buf[42]; ssize_t nbytes = 42; curl = curl_easy_init(); - // setup rest protocol TEST_ASSERT_EQUAL_INT(0, fdo_con_setup(NULL, NULL, 0)); TEST_ASSERT_EQUAL_INT( - -1, fdo_con_send_message(sock, 0, 0, buf, nbytes, NULL)); + -1, fdo_con_send_recv_message(0, 0, buf, nbytes, NULL, NULL, NULL)); // undo setup rest protocol fdo_con_teardown(); @@ -268,19 +275,16 @@ TEST_CASE("read_until_new_line", "[OS][HAL][fdo]") char buff[50]; int bufsize = 22, ret; bool retval; - struct fdo_sock_handle handle = {0}; fdo_prot_ctx_t *prot_ctx = fdo_alloc(sizeof(fdo_prot_ctx_t)); TEST_ASSERT_NOT_NULL(prot_ctx); ret = memset_s(prot_ctx, sizeof(fdo_prot_ctx_t), 0); TEST_ASSERT_EQUAL_INT(0, ret); - handle.sockfd = 100; - prot_ctx->sock_hdl = (fdo_con_handle)&handle; // prot_ctx->ssl = NULL; recv_configured = 0; - retval = read_until_new_line(prot_ctx->sock_hdl, buff, bufsize); - TEST_ASSERT_FALSE(retval); + retval = read_until_new_line(buff, bufsize); + TEST_ASSERT_TRUE(retval); recv_configured = 1; free(prot_ctx); } diff --git a/tests/unit/test_protctx.c b/tests/unit/test_protctx.c index 77cd9f5b..7c325e7d 100644 --- a/tests/unit/test_protctx.c +++ b/tests/unit/test_protctx.c @@ -12,7 +12,7 @@ #include "unity.h" #include "test_crypto.h" #include -#include "fdoCryptoHal.h" +#include "fdo_crypto_hal.h" #include "fdoprotctx.h" #include "fdoprot.h" #include "fdoblockio.h" @@ -224,7 +224,6 @@ TEST_CASE("fdo_prot_ctx_run", "[protctx][fdo]") prot_ctx->protdata = fdo_alloc(sizeof(fdo_prot_t)); TEST_ASSERT_NOT_NULL(prot_ctx->protdata); - prot_ctx->sock_hdl = FDO_CON_INVALID_HANDLE; return_socket = -1; prot_ctx->protrun = &fdo_prot_dummy; prot_ctx->host_port = host_port; diff --git a/tests/unit/unity/include/unity.h b/tests/unit/unity/include/unity.h index 8caa7852..bcbd0f81 100644 --- a/tests/unit/unity/include/unity.h +++ b/tests/unit/unity/include/unity.h @@ -8,14 +8,15 @@ #define UNITY_FRAMEWORK_H #define UNITY -#define UNITY_VERSION_MAJOR 2 -#define UNITY_VERSION_MINOR 5 -#define UNITY_VERSION_BUILD 1 -#define UNITY_VERSION ((UNITY_VERSION_MAJOR << 16) | (UNITY_VERSION_MINOR << 8) | UNITY_VERSION_BUILD) +#define UNITY_VERSION_MAJOR 2 +#define UNITY_VERSION_MINOR 5 +#define UNITY_VERSION_BUILD 1 +#define UNITY_VERSION \ + ((UNITY_VERSION_MAJOR << 16) | (UNITY_VERSION_MINOR << 8) | \ + UNITY_VERSION_BUILD) #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif #include "unity_internals.h" @@ -55,13 +56,17 @@ void verifyTest(void); /*------------------------------------------------------- * Configuration Options *------------------------------------------------------- - * All options described below should be passed as a compiler flag to all files using Unity. If you must add #defines, place them BEFORE the #include above. + * All options described below should be passed as a compiler flag to all files + using Unity. If you must add #defines, place them BEFORE the #include above. * Integers/longs/pointers * - Unity attempts to automatically discover your integer sizes - * - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in - * - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in - * - If you cannot use the automatic methods above, you can force Unity by using these options: + * - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in + + * - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in + + * - If you cannot use the automatic methods above, you can force Unity by + using these options: * - define UNITY_SUPPORT_64 * - set UNITY_INT_WIDTH * - set UNITY_LONG_WIDTH @@ -69,52 +74,72 @@ void verifyTest(void); * Floats * - define UNITY_EXCLUDE_FLOAT to disallow floating point comparisons - * - define UNITY_FLOAT_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_FLOAT - * - define UNITY_FLOAT_TYPE to specify doubles instead of single precision floats + * - define UNITY_FLOAT_PRECISION to specify the precision to use when doing + TEST_ASSERT_EQUAL_FLOAT + * - define UNITY_FLOAT_TYPE to specify doubles instead of single precision + floats * - define UNITY_INCLUDE_DOUBLE to allow double floating point comparisons - * - define UNITY_EXCLUDE_DOUBLE to disallow double floating point comparisons (default) - * - define UNITY_DOUBLE_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_DOUBLE + * - define UNITY_EXCLUDE_DOUBLE to disallow double floating point + comparisons (default) + * - define UNITY_DOUBLE_PRECISION to specify the precision to use when + doing TEST_ASSERT_EQUAL_DOUBLE * - define UNITY_DOUBLE_TYPE to specify something other than double - * - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print floating point values in errors + * - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print + floating point values in errors * Output - * - by default, Unity prints to standard out with putchar. define UNITY_OUTPUT_CHAR(a) with a different function if desired - * - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at test end summary - for automated search for failure + * - by default, Unity prints to standard out with putchar. define + UNITY_OUTPUT_CHAR(a) with a different function if desired + * - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at + test end summary - for automated search for failure * Optimization - * - by default, line numbers are stored in unsigned shorts. Define UNITY_LINE_TYPE with a different type if your files are huge - * - by default, test and failure counters are unsigned shorts. Define UNITY_COUNTER_TYPE with a different type if you want to save space or have more than 65535 Tests. + * - by default, line numbers are stored in unsigned shorts. Define + UNITY_LINE_TYPE with a different type if your files are huge + * - by default, test and failure counters are unsigned shorts. Define + UNITY_COUNTER_TYPE with a different type if you want to save space or have more + than 65535 Tests. * Test Cases - * - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though really it's mostly about the runner generator script + * - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though + really it's mostly about the runner generator script * Parameterized Tests - * - you'll want to create a define of TEST_CASE(...) which basically evaluates to nothing + * - you'll want to create a define of TEST_CASE(...) which basically + evaluates to nothing * Tests with Arguments - * - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test runner passing arguments to Unity + * - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test + runner passing arguments to Unity *------------------------------------------------------- * Basic Fail and Ignore *-------------------------------------------------------*/ -#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message)) -#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL) -#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message)) -#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL) -#define TEST_MESSAGE(message) UnityMessage((message), __LINE__) +#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message)) +#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL) +#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message)) +#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL) +#define TEST_MESSAGE(message) UnityMessage((message), __LINE__) #define TEST_ONLY() #ifdef UNITY_INCLUDE_PRINT_FORMATTED -#define TEST_PRINTF(message, ...) UnityPrintF(__LINE__, (message), __VA_ARGS__) +#define TEST_PRINTF(message, ...) UnityPrintF(__LINE__, (message), __VA_ARGS__) #endif -/* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails. - * This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */ -#define TEST_PASS() TEST_ABORT() -#define TEST_PASS_MESSAGE(message) do { UnityMessage((message), __LINE__); TEST_ABORT(); } while(0) +/* It is not necessary for you to call PASS. A PASS condition is assumed if + * nothing fails. + * This method allows you to abort a test immediately with a PASS state, + * ignoring the remainder of the test. */ +#define TEST_PASS() TEST_ABORT() +#define TEST_PASS_MESSAGE(message) \ + do { \ + UnityMessage((message), __LINE__); \ + TEST_ABORT(); \ + } while (0) -/* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out - * which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */ +/* This macro does nothing, but it is useful for build tools (like Ceedling) to + * make use of this to figure out which files should be linked to in order to + * perform a test. Use it like TEST_FILE("sandwiches.c") */ #define TEST_FILE(a) /*------------------------------------------------------- @@ -122,267 +147,654 @@ void verifyTest(void); *-------------------------------------------------------*/ /* Boolean */ -#define TEST_ASSERT(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expression Evaluated To FALSE") -#define TEST_ASSERT_TRUE(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expected TRUE Was FALSE") -#define TEST_ASSERT_UNLESS(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expression Evaluated To TRUE") -#define TEST_ASSERT_FALSE(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expected FALSE Was TRUE") -#define TEST_ASSERT_NULL(pointer) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, " Expected NULL") -#define TEST_ASSERT_NOT_NULL(pointer) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL") -#define TEST_ASSERT_EMPTY(pointer) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, " Expected Empty") -#define TEST_ASSERT_NOT_EMPTY(pointer) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, " Expected Non-Empty") +#define TEST_ASSERT(condition) \ + UNITY_TEST_ASSERT((condition), __LINE__, \ + " Expression Evaluated To FALSE") +#define TEST_ASSERT_TRUE(condition) \ + UNITY_TEST_ASSERT((condition), __LINE__, " Expected TRUE Was FALSE") +#define TEST_ASSERT_UNLESS(condition) \ + UNITY_TEST_ASSERT(!(condition), __LINE__, \ + " Expression Evaluated To TRUE") +#define TEST_ASSERT_FALSE(condition) \ + UNITY_TEST_ASSERT(!(condition), __LINE__, " Expected FALSE Was TRUE") +#define TEST_ASSERT_NULL(pointer) \ + UNITY_TEST_ASSERT_NULL((pointer), __LINE__, " Expected NULL") +#define TEST_ASSERT_NOT_NULL(pointer) \ + UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL") +#define TEST_ASSERT_EMPTY(pointer) \ + UNITY_TEST_ASSERT_EMPTY((pointer), __LINE__, " Expected Empty") +#define TEST_ASSERT_NOT_EMPTY(pointer) \ + UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, " Expected Non-Empty") /* Integers (of all sizes) */ -#define TEST_ASSERT_EQUAL_INT(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_size_t(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_CHAR(expected, actual) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, NULL) -#define TEST_ASSERT_BIT_HIGH(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, NULL) -#define TEST_ASSERT_BIT_LOW(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT8(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT16(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT32(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT64(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT8(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_UINT8((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT16(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_UINT16((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT32(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_UINT32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT64(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_UINT64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_size_t(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX8(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_HEX8((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX16(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX32(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX64(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_CHAR(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS(mask, expected, actual) \ + UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS_HIGH(mask, actual) \ + UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_BITS_LOW(mask, actual) \ + UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_BIT_HIGH(bit, actual) \ + UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), \ + (actual), __LINE__, NULL) +#define TEST_ASSERT_BIT_LOW(bit, actual) \ + UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), \ + (actual), __LINE__, NULL) /* Integer Not Equal To (of all sizes) */ -#define TEST_ASSERT_NOT_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_INT(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_NOT_EQUAL_size_t(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual) \ + UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) /* Integer Greater Than/ Less Than (of all sizes) */ -#define TEST_ASSERT_GREATER_THAN(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_size_t(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, \ + NULL) + +#define TEST_ASSERT_LESS_THAN(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_size_t(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_LESS_THAN_CHAR(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, \ + NULL) + +#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_size_t(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), \ + __LINE__, NULL) + +#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_size_t(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_CHAR(threshold, actual) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), \ + __LINE__, NULL) /* Integer Ranges (of all sizes) */ -#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_size_t_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_CHAR_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_size_t_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, \ + NULL) +#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_CHAR_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, \ + NULL) /* Integer Array Ranges (of all sizes) */ -#define TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_size_t_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) - +#define TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_size_t_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) +#define TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements) \ + UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, NULL) /* Structs and Strings */ -#define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING(expected, actual) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_PTR(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) \ + UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), \ + __LINE__, NULL) +#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) \ + UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, \ + NULL) /* Arrays */ -#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_size_t_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_size_t_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) /* Arrays Compared To Single Value */ -#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_size_t(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), \ + __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_size_t(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), \ + __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), \ + (num_elements), __LINE__, NULL) /* Floating Point (If Enabled) */ -#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_INF(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NAN(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL) /* Double (If Enabled) */ -#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) \ + UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), \ + __LINE__, NULL) +#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) \ + UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), \ + (num_elements), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_INF(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NAN(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL) /* Shorthand */ #ifdef UNITY_SHORTHAND_AS_OLD -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") +#define TEST_ASSERT_EQUAL(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) \ + UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, \ + " Expected Not-Equal") #endif #ifdef UNITY_SHORTHAND_AS_INT -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_EQUAL(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) #endif #ifdef UNITY_SHORTHAND_AS_MEM -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_EQUAL(expected, actual) \ + UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), \ + sizeof(expected), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) #endif #ifdef UNITY_SHORTHAND_AS_RAW -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, " Expected Equal") -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") +#define TEST_ASSERT_EQUAL(expected, actual) \ + UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, " Expected Equal") +#define TEST_ASSERT_NOT_EQUAL(expected, actual) \ + UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, \ + " Expected Not-Equal") #endif #ifdef UNITY_SHORTHAND_AS_NONE -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_EQUAL(expected, actual) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) #endif /*------------------------------------------------------- @@ -390,268 +802,736 @@ void verifyTest(void); *-------------------------------------------------------*/ /* Boolean */ -#define TEST_ASSERT_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) -#define TEST_ASSERT_TRUE_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) -#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) -#define TEST_ASSERT_FALSE_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) -#define TEST_ASSERT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, (message)) -#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message)) -#define TEST_ASSERT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, (message)) -#define TEST_ASSERT_NOT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, (message)) +#define TEST_ASSERT_MESSAGE(condition, message) \ + UNITY_TEST_ASSERT((condition), __LINE__, (message)) +#define TEST_ASSERT_TRUE_MESSAGE(condition, message) \ + UNITY_TEST_ASSERT((condition), __LINE__, (message)) +#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) \ + UNITY_TEST_ASSERT(!(condition), __LINE__, (message)) +#define TEST_ASSERT_FALSE_MESSAGE(condition, message) \ + UNITY_TEST_ASSERT(!(condition), __LINE__, (message)) +#define TEST_ASSERT_NULL_MESSAGE(pointer, message) \ + UNITY_TEST_ASSERT_NULL((pointer), __LINE__, (message)) +#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) \ + UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message)) +#define TEST_ASSERT_EMPTY_MESSAGE(pointer, message) \ + UNITY_TEST_ASSERT_EMPTY((pointer), __LINE__, (message)) +#define TEST_ASSERT_NOT_EMPTY_MESSAGE(pointer, message) \ + UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, (message)) /* Integers (of all sizes) */ -#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_size_t_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message)) -#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) -#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_CHAR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_UINT8((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_UINT16((expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_UINT32((expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_UINT64((expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_EQUAL_size_t_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_HEX8((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) \ + UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) \ + UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) \ + UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) \ + UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), \ + (actual), __LINE__, (message)) +#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) \ + UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), \ + (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_CHAR_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, (message)) /* Integer Not Equal To (of all sizes) */ -#define TEST_ASSERT_NOT_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - +#define TEST_ASSERT_NOT_EQUAL_INT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_INT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_INT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_INT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_INT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_UINT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_UINT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_UINT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_UINT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_UINT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_size_t_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_HEX8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_HEX16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_HEX32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_HEX64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_NOT_EQUAL_CHAR_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, \ + (message)) /* Integer Greater Than/ Less Than (of all sizes) */ -#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_size_t_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_GREATER_THAN_CHAR_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, \ + (message)) + +#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_size_t_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_LESS_THAN_CHAR_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, \ + (message)) + +#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, \ + message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, \ + message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, \ + message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_size_t_MESSAGE(threshold, actual, \ + message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), \ + __LINE__, (message)) + +#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) \ + UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), \ + __LINE__, (message)) /* Integer Ranges (of all sizes) */ -#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_size_t_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_CHAR_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_size_t_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_CHAR_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, \ + (message)) /* Integer Array Ranges (of all sizes) */ -#define TEST_ASSERT_INT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_size_t_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_CHAR_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) - +#define TEST_ASSERT_INT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_size_t_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN( \ + (delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_CHAR_ARRAY_WITHIN_MESSAGE(delta, expected, actual, \ + num_elements, message) \ + UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), \ + num_elements, __LINE__, (message)) /* Structs and Strings */ -#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) \ + UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), \ + __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) \ + UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, \ + (message)) /* Arrays */ -#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_size_t_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_CHAR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), \ + (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_size_t_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), \ + (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, \ + num_elements, message) \ + UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY( \ + (expected), (actual), (len), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_CHAR_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) /* Arrays Compared To Single Value*/ -#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_size_t_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_CHAR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), \ + __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), \ + (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT16( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT32( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_INT64( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), \ + (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT8( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT16( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT32( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT64( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_size_t_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), \ + (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX32( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), \ + (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX16( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX32( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_HEX64( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), \ + __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_STRING( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, \ + num_elements, message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY( \ + (expected), (actual), (len), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_CHAR_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), \ + (num_elements), __LINE__, (message)) /* Floating Point (If Enabled) */ -#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, \ + (message)) /* Double (If Enabled) */ -#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), \ + __LINE__, (message)) +#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, \ + (message)) +#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, \ + message) \ + UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE( \ + (expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) \ + UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, \ + (message)) /* Shorthand */ #ifdef UNITY_SHORTHAND_AS_OLD -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) #endif #ifdef UNITY_SHORTHAND_AS_INT -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, message) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) #endif -#ifdef UNITY_SHORTHAND_AS_MEM -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#ifdef UNITY_SHORTHAND_AS_MEM +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), \ + sizeof(expected), __LINE__, message) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) #endif -#ifdef UNITY_SHORTHAND_AS_RAW -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, message) +#ifdef UNITY_SHORTHAND_AS_RAW +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, message) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, message) #endif #ifdef UNITY_SHORTHAND_AS_NONE -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) \ + UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) #endif /* end of UNITY_FRAMEWORK_H */ diff --git a/tests/unit/unity/include/unity_internals.h b/tests/unit/unity/include/unity_internals.h index d7c2116c..1c434b50 100644 --- a/tests/unit/unity/include/unity_internals.h +++ b/tests/unit/unity/include/unity_internals.h @@ -51,47 +51,47 @@ * which may not necessarily be the size in bytes. * Therefore, infer it from UINT_MAX if possible. */ #ifndef UNITY_INT_WIDTH - #ifdef UINT_MAX - #if (UINT_MAX == 0xFFFF) - #define UNITY_INT_WIDTH (16) - #elif (UINT_MAX == 0xFFFFFFFF) - #define UNITY_INT_WIDTH (32) - #elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF) - #define UNITY_INT_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_INT_WIDTH (32) - #endif /* UINT_MAX */ +#ifdef UINT_MAX +#if (UINT_MAX == 0xFFFF) +#define UNITY_INT_WIDTH (16) +#elif (UINT_MAX == 0xFFFFFFFF) +#define UNITY_INT_WIDTH (32) +#elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF) +#define UNITY_INT_WIDTH (64) +#endif +#else /* Set to default */ +#define UNITY_INT_WIDTH (32) +#endif /* UINT_MAX */ #endif /* Determine the size of a long, if not already specified. */ #ifndef UNITY_LONG_WIDTH - #ifdef ULONG_MAX - #if (ULONG_MAX == 0xFFFF) - #define UNITY_LONG_WIDTH (16) - #elif (ULONG_MAX == 0xFFFFFFFF) - #define UNITY_LONG_WIDTH (32) - #elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF) - #define UNITY_LONG_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_LONG_WIDTH (32) - #endif /* ULONG_MAX */ +#ifdef ULONG_MAX +#if (ULONG_MAX == 0xFFFF) +#define UNITY_LONG_WIDTH (16) +#elif (ULONG_MAX == 0xFFFFFFFF) +#define UNITY_LONG_WIDTH (32) +#elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF) +#define UNITY_LONG_WIDTH (64) +#endif +#else /* Set to default */ +#define UNITY_LONG_WIDTH (32) +#endif /* ULONG_MAX */ #endif /* Determine the size of a pointer, if not already specified. */ #ifndef UNITY_POINTER_WIDTH - #ifdef UINTPTR_MAX - #if (UINTPTR_MAX <= 0xFFFF) - #define UNITY_POINTER_WIDTH (16) - #elif (UINTPTR_MAX <= 0xFFFFFFFF) - #define UNITY_POINTER_WIDTH (32) - #elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF) - #define UNITY_POINTER_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH - #endif /* UINTPTR_MAX */ +#ifdef UINTPTR_MAX +#if (UINTPTR_MAX <= 0xFFFF) +#define UNITY_POINTER_WIDTH (16) +#elif (UINTPTR_MAX <= 0xFFFFFFFF) +#define UNITY_POINTER_WIDTH (32) +#elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF) +#define UNITY_POINTER_WIDTH (64) +#endif +#else /* Set to default */ +#define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH +#endif /* UINTPTR_MAX */ #endif /*------------------------------------------------------- @@ -99,21 +99,21 @@ *-------------------------------------------------------*/ #if (UNITY_INT_WIDTH == 32) - typedef unsigned char UNITY_UINT8; - typedef unsigned short UNITY_UINT16; - typedef unsigned int UNITY_UINT32; - typedef signed char UNITY_INT8; - typedef signed short UNITY_INT16; - typedef signed int UNITY_INT32; +typedef unsigned char UNITY_UINT8; +typedef unsigned short UNITY_UINT16; +typedef unsigned int UNITY_UINT32; +typedef signed char UNITY_INT8; +typedef signed short UNITY_INT16; +typedef signed int UNITY_INT32; #elif (UNITY_INT_WIDTH == 16) - typedef unsigned char UNITY_UINT8; - typedef unsigned int UNITY_UINT16; - typedef unsigned long UNITY_UINT32; - typedef signed char UNITY_INT8; - typedef signed int UNITY_INT16; - typedef signed long UNITY_INT32; +typedef unsigned char UNITY_UINT8; +typedef unsigned int UNITY_UINT16; +typedef unsigned long UNITY_UINT32; +typedef signed char UNITY_INT8; +typedef signed int UNITY_INT16; +typedef signed long UNITY_INT32; #else - #error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported) +#error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported) #endif /*------------------------------------------------------- @@ -122,31 +122,35 @@ /* Auto-detect 64 Bit Support */ #ifndef UNITY_SUPPORT_64 - #if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 - #define UNITY_SUPPORT_64 - #endif +#if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 +#define UNITY_SUPPORT_64 +#endif #endif /* 64-Bit Support Dependent Configuration */ #ifndef UNITY_SUPPORT_64 - /* No 64-bit Support */ - typedef UNITY_UINT32 UNITY_UINT; - typedef UNITY_INT32 UNITY_INT; - #define UNITY_MAX_NIBBLES (8) /* Maximum number of nibbles in a UNITY_(U)INT */ +/* No 64-bit Support */ +typedef UNITY_UINT32 UNITY_UINT; +typedef UNITY_INT32 UNITY_INT; +#define UNITY_MAX_NIBBLES \ + (8) /* Maximum number of nibbles in a UNITY_(U)INT \ + */ +#else +/* 64-bit Support */ +#if (UNITY_LONG_WIDTH == 32) +typedef unsigned long long UNITY_UINT64; +typedef signed long long UNITY_INT64; +#elif (UNITY_LONG_WIDTH == 64) +typedef unsigned long UNITY_UINT64; +typedef signed long UNITY_INT64; #else - /* 64-bit Support */ - #if (UNITY_LONG_WIDTH == 32) - typedef unsigned long long UNITY_UINT64; - typedef signed long long UNITY_INT64; - #elif (UNITY_LONG_WIDTH == 64) - typedef unsigned long UNITY_UINT64; - typedef signed long UNITY_INT64; - #else - #error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) - #endif - typedef UNITY_UINT64 UNITY_UINT; - typedef UNITY_INT64 UNITY_INT; - #define UNITY_MAX_NIBBLES (16) /* Maximum number of nibbles in a UNITY_(U)INT */ +#error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) +#endif +typedef UNITY_UINT64 UNITY_UINT; +typedef UNITY_INT64 UNITY_INT; +#define UNITY_MAX_NIBBLES \ + (16) /* Maximum number of nibbles in a UNITY_(U)INT \ + */ #endif /*------------------------------------------------------- @@ -154,24 +158,24 @@ *-------------------------------------------------------*/ #if (UNITY_POINTER_WIDTH == 32) - #define UNITY_PTR_TO_INT UNITY_INT32 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 +#define UNITY_PTR_TO_INT UNITY_INT32 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 #elif (UNITY_POINTER_WIDTH == 64) - #define UNITY_PTR_TO_INT UNITY_INT64 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 +#define UNITY_PTR_TO_INT UNITY_INT64 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 #elif (UNITY_POINTER_WIDTH == 16) - #define UNITY_PTR_TO_INT UNITY_INT16 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 +#define UNITY_PTR_TO_INT UNITY_INT16 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 #else - #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) +#error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) #endif #ifndef UNITY_PTR_ATTRIBUTE - #define UNITY_PTR_ATTRIBUTE +#define UNITY_PTR_ATTRIBUTE #endif #ifndef UNITY_INTERNAL_PTR - #define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* +#define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void * #endif /*------------------------------------------------------- @@ -220,32 +224,33 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; /* unlike float, we DON'T include by default */ #if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE) - /* No Floating Point Support */ - #ifndef UNITY_EXCLUDE_DOUBLE - #define UNITY_EXCLUDE_DOUBLE - #else - #undef UNITY_INCLUDE_DOUBLE - #endif - - #ifndef UNITY_EXCLUDE_FLOAT - #ifndef UNITY_DOUBLE_TYPE - #define UNITY_DOUBLE_TYPE double - #endif - typedef UNITY_FLOAT UNITY_DOUBLE; - /* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */ - #endif +/* No Floating Point Support */ +#ifndef UNITY_EXCLUDE_DOUBLE +#define UNITY_EXCLUDE_DOUBLE +#else +#undef UNITY_INCLUDE_DOUBLE +#endif + +#ifndef UNITY_EXCLUDE_FLOAT +#ifndef UNITY_DOUBLE_TYPE +#define UNITY_DOUBLE_TYPE double +#endif +typedef UNITY_FLOAT UNITY_DOUBLE; +/* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or + * float */ +#endif #else - /* Double Floating Point Support */ - #ifndef UNITY_DOUBLE_PRECISION - #define UNITY_DOUBLE_PRECISION (1e-12) - #endif +/* Double Floating Point Support */ +#ifndef UNITY_DOUBLE_PRECISION +#define UNITY_DOUBLE_PRECISION (1e-12) +#endif - #ifndef UNITY_DOUBLE_TYPE - #define UNITY_DOUBLE_TYPE double - #endif - typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE; +#ifndef UNITY_DOUBLE_TYPE +#define UNITY_DOUBLE_TYPE double +#endif +typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE; #endif @@ -253,30 +258,32 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; * Output Method: stdout (DEFAULT) *-------------------------------------------------------*/ #ifndef UNITY_OUTPUT_CHAR - /* Default to using putchar, which is defined in stdio.h */ - #include - #define UNITY_OUTPUT_CHAR(a) (void)putchar(a) +/* Default to using putchar, which is defined in stdio.h */ +#include +#define UNITY_OUTPUT_CHAR(a) (void)putchar(a) #else - /* If defined as something else, make sure we declare it here so it's ready for use */ - #ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION - extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION; - #endif +/* If defined as something else, make sure we declare it here so it's ready for + * use */ +#ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION +extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION; +#endif #endif #ifndef UNITY_OUTPUT_FLUSH - #ifdef UNITY_USE_FLUSH_STDOUT - /* We want to use the stdout flush utility */ - #include - #define UNITY_OUTPUT_FLUSH() (void)fflush(stdout) - #else - /* We've specified nothing, therefore flush should just be ignored */ - #define UNITY_OUTPUT_FLUSH() - #endif +#ifdef UNITY_USE_FLUSH_STDOUT +/* We want to use the stdout flush utility */ +#include +#define UNITY_OUTPUT_FLUSH() (void)fflush(stdout) #else - /* If defined as something else, make sure we declare it here so it's ready for use */ - #ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION - extern void UNITY_OUTPUT_FLUSH_HEADER_DECLARATION; - #endif +/* We've specified nothing, therefore flush should just be ignored */ +#define UNITY_OUTPUT_FLUSH() +#endif +#else +/* If defined as something else, make sure we declare it here so it's ready for + * use */ +#ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION +extern void UNITY_OUTPUT_FLUSH_HEADER_DECLARATION; +#endif #endif #ifndef UNITY_OUTPUT_FLUSH @@ -286,7 +293,7 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; #endif #ifndef UNITY_PRINT_EOL -#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n') +#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n') #endif #ifndef UNITY_OUTPUT_START @@ -298,58 +305,71 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; #endif #ifdef UNITY_INCLUDE_EXEC_TIME - #if !defined(UNITY_EXEC_TIME_START) && \ - !defined(UNITY_EXEC_TIME_STOP) && \ - !defined(UNITY_PRINT_EXEC_TIME) && \ - !defined(UNITY_TIME_TYPE) - /* If none any of these macros are defined then try to provide a default implementation */ - - #if defined(UNITY_CLOCK_MS) - /* This is a simple way to get a default implementation on platforms that support getting a millisecond counter */ - #define UNITY_TIME_TYPE UNITY_UINT - #define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS() - #define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS() - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #elif defined(_WIN32) - #include - #define UNITY_TIME_TYPE clock_t - #define UNITY_GET_TIME(t) t = (clock_t)((clock() * 1000) / CLOCKS_PER_SEC) - #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) - #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #elif defined(__unix__) - #include - #define UNITY_TIME_TYPE struct timespec - #define UNITY_GET_TIME(t) clock_gettime(CLOCK_MONOTONIC, &t) - #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) - #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = ((Unity.CurrentTestStopTime.tv_sec - Unity.CurrentTestStartTime.tv_sec) * 1000L); \ - execTimeMs += ((Unity.CurrentTestStopTime.tv_nsec - Unity.CurrentTestStartTime.tv_nsec) / 1000000L); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #endif - #endif +#if !defined(UNITY_EXEC_TIME_START) && !defined(UNITY_EXEC_TIME_STOP) && \ + !defined(UNITY_PRINT_EXEC_TIME) && !defined(UNITY_TIME_TYPE) +/* If none any of these macros are defined then try to provide a default + * implementation */ + +#if defined(UNITY_CLOCK_MS) +/* This is a simple way to get a default implementation on platforms that + * support getting a millisecond counter */ +#define UNITY_TIME_TYPE UNITY_UINT +#define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS() +#define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS() +#define UNITY_PRINT_EXEC_TIME() \ + { \ + UNITY_UINT execTimeMs = \ + (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ + UnityPrint(" ("); \ + UnityPrintNumberUnsigned(execTimeMs); \ + UnityPrint(" ms)"); \ + } +#elif defined(_WIN32) +#include +#define UNITY_TIME_TYPE clock_t +#define UNITY_GET_TIME(t) t = (clock_t)((clock() * 1000) / CLOCKS_PER_SEC) +#define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) +#define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) +#define UNITY_PRINT_EXEC_TIME() \ + { \ + UNITY_UINT execTimeMs = \ + (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ + UnityPrint(" ("); \ + UnityPrintNumberUnsigned(execTimeMs); \ + UnityPrint(" ms)"); \ + } +#elif defined(__unix__) +#include +#define UNITY_TIME_TYPE struct timespec +#define UNITY_GET_TIME(t) clock_gettime(CLOCK_MONOTONIC, &t) +#define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) +#define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) +#define UNITY_PRINT_EXEC_TIME() \ + { \ + UNITY_UINT execTimeMs = ((Unity.CurrentTestStopTime.tv_sec - \ + Unity.CurrentTestStartTime.tv_sec) * \ + 1000L); \ + execTimeMs += ((Unity.CurrentTestStopTime.tv_nsec - \ + Unity.CurrentTestStartTime.tv_nsec) / \ + 1000000L); \ + UnityPrint(" ("); \ + UnityPrintNumberUnsigned(execTimeMs); \ + UnityPrint(" ms)"); \ + } +#endif +#endif #endif #ifndef UNITY_EXEC_TIME_START -#define UNITY_EXEC_TIME_START() do{}while(0) +#define UNITY_EXEC_TIME_START() \ + do { \ + } while (0) #endif #ifndef UNITY_EXEC_TIME_STOP -#define UNITY_EXEC_TIME_STOP() do{}while(0) +#define UNITY_EXEC_TIME_STOP() \ + do { \ + } while (0) #endif #ifndef UNITY_TIME_TYPE @@ -357,7 +377,9 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; #endif #ifndef UNITY_PRINT_EXEC_TIME -#define UNITY_PRINT_EXEC_TIME() do{}while(0) +#define UNITY_PRINT_EXEC_TIME() \ + do { \ + } while (0) #endif /*------------------------------------------------------- @@ -378,95 +400,93 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; typedef void (*UnityTestFunction)(void); -#define UNITY_DISPLAY_RANGE_INT (0x10) +#define UNITY_DISPLAY_RANGE_INT (0x10) #define UNITY_DISPLAY_RANGE_UINT (0x20) -#define UNITY_DISPLAY_RANGE_HEX (0x40) +#define UNITY_DISPLAY_RANGE_HEX (0x40) #define UNITY_DISPLAY_RANGE_CHAR (0x80) -typedef enum -{ - UNITY_DISPLAY_STYLE_INT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, +typedef enum { + UNITY_DISPLAY_STYLE_INT = + (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, #ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, #endif - UNITY_DISPLAY_STYLE_UINT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT = + (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, #ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT, #endif - UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX, - UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX, - UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX, #ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, #endif - UNITY_DISPLAY_STYLE_CHAR = 1 + UNITY_DISPLAY_RANGE_CHAR + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_CHAR = + 1 + UNITY_DISPLAY_RANGE_CHAR + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_UNKNOWN + UNITY_DISPLAY_STYLE_UNKNOWN } UNITY_DISPLAY_STYLE_T; -typedef enum -{ - UNITY_WITHIN = 0x0, - UNITY_EQUAL_TO = 0x1, - UNITY_GREATER_THAN = 0x2, - UNITY_GREATER_OR_EQUAL = 0x2 + UNITY_EQUAL_TO, - UNITY_SMALLER_THAN = 0x4, - UNITY_SMALLER_OR_EQUAL = 0x4 + UNITY_EQUAL_TO, - UNITY_NOT_EQUAL = 0x0, - UNITY_UNKNOWN +typedef enum { + UNITY_WITHIN = 0x0, + UNITY_EQUAL_TO = 0x1, + UNITY_GREATER_THAN = 0x2, + UNITY_GREATER_OR_EQUAL = 0x2 + UNITY_EQUAL_TO, + UNITY_SMALLER_THAN = 0x4, + UNITY_SMALLER_OR_EQUAL = 0x4 + UNITY_EQUAL_TO, + UNITY_NOT_EQUAL = 0x0, + UNITY_UNKNOWN } UNITY_COMPARISON_T; #ifndef UNITY_EXCLUDE_FLOAT -typedef enum UNITY_FLOAT_TRAIT -{ - UNITY_FLOAT_IS_NOT_INF = 0, - UNITY_FLOAT_IS_INF, - UNITY_FLOAT_IS_NOT_NEG_INF, - UNITY_FLOAT_IS_NEG_INF, - UNITY_FLOAT_IS_NOT_NAN, - UNITY_FLOAT_IS_NAN, - UNITY_FLOAT_IS_NOT_DET, - UNITY_FLOAT_IS_DET, - UNITY_FLOAT_INVALID_TRAIT +typedef enum UNITY_FLOAT_TRAIT { + UNITY_FLOAT_IS_NOT_INF = 0, + UNITY_FLOAT_IS_INF, + UNITY_FLOAT_IS_NOT_NEG_INF, + UNITY_FLOAT_IS_NEG_INF, + UNITY_FLOAT_IS_NOT_NAN, + UNITY_FLOAT_IS_NAN, + UNITY_FLOAT_IS_NOT_DET, + UNITY_FLOAT_IS_DET, + UNITY_FLOAT_INVALID_TRAIT } UNITY_FLOAT_TRAIT_T; #endif -typedef enum -{ - UNITY_ARRAY_TO_VAL = 0, - UNITY_ARRAY_TO_ARRAY, - UNITY_ARRAY_UNKNOWN +typedef enum { + UNITY_ARRAY_TO_VAL = 0, + UNITY_ARRAY_TO_ARRAY, + UNITY_ARRAY_UNKNOWN } UNITY_FLAGS_T; -struct UNITY_STORAGE_T -{ - const char* TestFile; - const char* CurrentTestName; +struct UNITY_STORAGE_T { + const char *TestFile; + const char *CurrentTestName; #ifndef UNITY_EXCLUDE_DETAILS - const char* CurrentDetail1; - const char* CurrentDetail2; -#endif - UNITY_LINE_TYPE CurrentTestLineNumber; - UNITY_COUNTER_TYPE NumberOfTests; - UNITY_COUNTER_TYPE TestFailures; - UNITY_COUNTER_TYPE TestIgnores; - UNITY_COUNTER_TYPE CurrentTestFailed; - UNITY_COUNTER_TYPE CurrentTestIgnored; + const char *CurrentDetail1; + const char *CurrentDetail2; +#endif + UNITY_LINE_TYPE CurrentTestLineNumber; + UNITY_COUNTER_TYPE NumberOfTests; + UNITY_COUNTER_TYPE TestFailures; + UNITY_COUNTER_TYPE TestIgnores; + UNITY_COUNTER_TYPE CurrentTestFailed; + UNITY_COUNTER_TYPE CurrentTestIgnored; #ifdef UNITY_INCLUDE_EXEC_TIME - UNITY_TIME_TYPE CurrentTestStartTime; - UNITY_TIME_TYPE CurrentTestStopTime; + UNITY_TIME_TYPE CurrentTestStartTime; + UNITY_TIME_TYPE CurrentTestStopTime; #endif #ifndef UNITY_EXCLUDE_SETJMP_H - jmp_buf AbortFrame; + jmp_buf AbortFrame; #endif }; @@ -476,13 +496,14 @@ extern struct UNITY_STORAGE_T Unity; * Test Suite Management *-------------------------------------------------------*/ -void UnityBegin(const char* filename); -int UnityEnd(void); -void UnitySetTestFile(const char* filename); +void UnityBegin(const char *filename); +int UnityEnd(void); +void UnitySetTestFile(const char *filename); void UnityConcludeTest(void); #ifndef RUN_TEST -void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum); +void UnityDefaultTestRun(UnityTestFunction Func, const char *FuncName, + const int FuncLineNum); #else #define UNITY_SKIP_DEFAULT_RUNNER #endif @@ -494,11 +515,23 @@ void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int #ifdef UNITY_EXCLUDE_DETAILS #define UNITY_CLR_DETAILS() #define UNITY_SET_DETAIL(d1) -#define UNITY_SET_DETAILS(d1,d2) +#define UNITY_SET_DETAILS(d1, d2) #else -#define UNITY_CLR_DETAILS() { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; } -#define UNITY_SET_DETAIL(d1) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = 0; } -#define UNITY_SET_DETAILS(d1,d2) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = (d2); } +#define UNITY_CLR_DETAILS() \ + { \ + Unity.CurrentDetail1 = 0; \ + Unity.CurrentDetail2 = 0; \ + } +#define UNITY_SET_DETAIL(d1) \ + { \ + Unity.CurrentDetail1 = (d1); \ + Unity.CurrentDetail2 = 0; \ + } +#define UNITY_SET_DETAILS(d1, d2) \ + { \ + Unity.CurrentDetail1 = (d1); \ + Unity.CurrentDetail2 = (d2); \ + } #ifndef UNITY_DETAIL1_NAME #define UNITY_DETAIL1_NAME "Function" @@ -517,15 +550,16 @@ void UNITY_PRINT_TEST_CONTEXT(void); * Test Output *-------------------------------------------------------*/ -void UnityPrint(const char* string); +void UnityPrint(const char *string); #ifdef UNITY_INCLUDE_PRINT_FORMATTED -void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...); +void UnityPrintF(const UNITY_LINE_TYPE line, const char *format, ...); #endif -void UnityPrintLen(const char* string, const UNITY_UINT32 length); +void UnityPrintLen(const char *string, const UNITY_UINT32 length); void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number); -void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style); +void UnityPrintNumberByStyle(const UNITY_INT number, + const UNITY_DISPLAY_STYLE_T style); void UnityPrintNumber(const UNITY_INT number_to_print); void UnityPrintNumberUnsigned(const UNITY_UINT number); void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print); @@ -542,117 +576,97 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number); * convention and will pull in file and line information * for you. */ -void UnityAssertEqualNumber(const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); +void UnityAssertEqualNumber(const UNITY_INT expected, const UNITY_INT actual, + const char *msg, const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, - const UNITY_INT actual, - const UNITY_COMPARISON_T compare, - const char *msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); + const UNITY_INT actual, + const UNITY_COMPARISON_T compare, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags); - -void UnityAssertBits(const UNITY_INT mask, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualString(const char* expected, - const char* actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualStringLen(const char* expected, - const char* actual, - const UNITY_UINT32 length, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected, - const char** actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 length, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertNumbersWithin(const UNITY_UINT delta, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); - -void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, - UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags); - -void UnityFail(const char* message, const UNITY_LINE_TYPE line); -void UnityIgnore(const char* message, const UNITY_LINE_TYPE line); -void UnityMessage(const char* message, const UNITY_LINE_TYPE line); + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags); + +void UnityAssertBits(const UNITY_INT mask, const UNITY_INT expected, + const UNITY_INT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualString(const char *expected, const char *actual, + const char *msg, const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualStringLen(const char *expected, const char *actual, + const UNITY_UINT32 length, const char *msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualStringArray(UNITY_INTERNAL_PTR expected, + const char **actual, + const UNITY_UINT32 num_elements, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertEqualMemory(UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 length, + const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertNumbersWithin(const UNITY_UINT delta, const UNITY_INT expected, + const UNITY_INT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); + +void UnityAssertNumbersArrayWithin( + const UNITY_UINT delta, UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags); + +void UnityFail(const char *message, const UNITY_LINE_TYPE line); +void UnityIgnore(const char *message, const UNITY_LINE_TYPE line); +void UnityMessage(const char *message, const UNITY_LINE_TYPE line); #ifndef UNITY_EXCLUDE_FLOAT void UnityAssertFloatsWithin(const UNITY_FLOAT delta, - const UNITY_FLOAT expected, - const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); + const UNITY_FLOAT expected, + const UNITY_FLOAT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber); -void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); +void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT *expected, + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT *actual, + const UNITY_UINT32 num_elements, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); -void UnityAssertFloatSpecial(const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style); +void UnityAssertFloatSpecial(const UNITY_FLOAT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style); #endif #ifndef UNITY_EXCLUDE_DOUBLE void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, - const UNITY_DOUBLE expected, - const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); + const UNITY_DOUBLE expected, + const UNITY_DOUBLE actual, const char *msg, + const UNITY_LINE_TYPE lineNumber); -void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); +void UnityAssertEqualDoubleArray( + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE *expected, + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE *actual, + const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, const UNITY_FLAGS_T flags); -void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style); +void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style); #endif /*------------------------------------------------------- @@ -693,7 +707,8 @@ extern const char UnityStrErrShorthand[]; #define TEST_ABORT() return #endif -/* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */ +/* This tricky series of macros gives us an optional line argument to treat it + * as RUN_TEST(func, num=__LINE__) */ #ifndef RUN_TEST #ifdef __STDC_VERSION__ #if __STDC_VERSION__ >= 199901L @@ -701,15 +716,19 @@ extern const char UnityStrErrShorthand[]; #endif #endif #ifdef UNITY_SUPPORT_VARIADIC_MACROS -#define RUN_TEST(...) UnityDefaultTestRun(RUN_TEST_FIRST(__VA_ARGS__), RUN_TEST_SECOND(__VA_ARGS__)) +#define RUN_TEST(...) \ + UnityDefaultTestRun(RUN_TEST_FIRST(__VA_ARGS__), \ + RUN_TEST_SECOND(__VA_ARGS__)) #define RUN_TEST_FIRST(...) RUN_TEST_FIRST_HELPER(__VA_ARGS__, throwaway) #define RUN_TEST_FIRST_HELPER(first, ...) (first), #first -#define RUN_TEST_SECOND(...) RUN_TEST_SECOND_HELPER(__VA_ARGS__, __LINE__, throwaway) +#define RUN_TEST_SECOND(...) \ + RUN_TEST_SECOND_HELPER(__VA_ARGS__, __LINE__, throwaway) #define RUN_TEST_SECOND_HELPER(first, second, ...) (second) #endif #endif -/* If we can't do the tricky version, we'll just have to require them to always include the line number */ +/* If we can't do the tricky version, we'll just have to require them to always + * include the line number */ #ifndef RUN_TEST #ifdef CMOCK #define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num) @@ -720,10 +739,10 @@ extern const char UnityStrErrShorthand[]; #define TEST_LINE_NUM (Unity.CurrentTestLineNumber) #define TEST_IS_IGNORED (Unity.CurrentTestIgnored) -#define UNITY_NEW_TEST(a) \ - Unity.CurrentTestName = (a); \ - Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \ - Unity.NumberOfTests++; +#define UNITY_NEW_TEST(a) \ + Unity.CurrentTestName = (a); \ + Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \ + Unity.NumberOfTests++; #ifndef UNITY_BEGIN #define UNITY_BEGIN() UnityBegin(__FILE__) @@ -748,7 +767,7 @@ extern const char UnityStrErrShorthand[]; *-----------------------------------------------*/ #ifdef UNITY_USE_COMMAND_LINE_ARGS -int UnityParseOptions(int argc, char** argv); +int UnityParseOptions(int argc, char **argv); int UnityTestMatches(void); #endif @@ -756,274 +775,1178 @@ int UnityTestMatches(void); * Basic Fail and Ignore *-------------------------------------------------------*/ -#define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_FAIL(line, message) \ + UnityFail((message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_IGNORE(line, message) \ + UnityIgnore((message), (UNITY_LINE_TYPE)(line)) /*------------------------------------------------------- * Test Asserts *-------------------------------------------------------*/ -#define UNITY_TEST_ASSERT(condition, line, message) do {if (condition) {} else {UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message));}} while(0) -#define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) == 0), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_NOT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) != 0), (UNITY_LINE_TYPE)(line), (message)) - -#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_EQUAL_CHAR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) -#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line)) - -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16) (threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32) (threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16) (expected), (UNITY_INT)(UNITY_INT16) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32) (expected), (UNITY_INT)(UNITY_INT32) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_CHAR_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) - - -#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) -#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) - -#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) - -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) (expected), (UNITY_POINTER_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT(condition, line, message) \ + do { \ + if (condition) { \ + } else { \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message)); \ + } \ + } while (0) +#define UNITY_TEST_ASSERT_NULL(pointer, line, message) \ + UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), \ + (message)) +#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) \ + UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), \ + (message)) +#define UNITY_TEST_ASSERT_EMPTY(pointer, line, message) \ + UNITY_TEST_ASSERT(((pointer[0]) == 0), (UNITY_LINE_TYPE)(line), \ + (message)) +#define UNITY_TEST_ASSERT_NOT_EMPTY(pointer, line, message) \ + UNITY_TEST_ASSERT(((pointer[0]) != 0), (UNITY_LINE_TYPE)(line), \ + (message)) + +#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), \ + (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8)(expected), \ + (UNITY_INT)(UNITY_INT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), \ + (UNITY_INT)(UNITY_INT16)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), \ + (UNITY_INT)(UNITY_INT32)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), \ + (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8)(expected), \ + (UNITY_INT)(UNITY_UINT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), \ + (UNITY_INT)(UNITY_UINT16)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), \ + (UNITY_INT)(UNITY_UINT32)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8)(expected), \ + (UNITY_INT)(UNITY_INT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), \ + (UNITY_INT)(UNITY_INT16)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), \ + (UNITY_INT)(UNITY_INT32)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_EQUAL_CHAR(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8)(expected), \ + (UNITY_INT)(UNITY_INT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_CHAR) +#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) \ + UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), \ + (UNITY_INT)(actual), (message), \ + (UNITY_LINE_TYPE)(line)) + +#define UNITY_TEST_ASSERT_NOT_EQUAL_INT(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT16)(threshold), \ + (UNITY_INT)(UNITY_INT16)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT32)(threshold), \ + (UNITY_INT)(UNITY_INT32)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_NOT_EQUAL, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) + +#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT16)(threshold), \ + (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT32)(threshold), \ + (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_GREATER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) + +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT16)(threshold), \ + (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT32)(threshold), \ + (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_CHAR(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_SMALLER_THAN, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) + +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT16)(threshold), \ + (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT32)(threshold), \ + (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_GREATER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) + +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT16)(threshold), \ + (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT32)(threshold), \ + (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT8)(threshold), \ + (UNITY_INT)(UNITY_UINT8)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT16)(threshold), \ + (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_UINT32)(threshold), \ + (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(UNITY_INT8)(threshold), \ + (UNITY_INT)(UNITY_INT8)(actual), UNITY_SMALLER_OR_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) + +#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT8)(delta), (UNITY_INT)(UNITY_INT8)(expected), \ + (UNITY_INT)(UNITY_INT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16)(expected), \ + (UNITY_INT)(UNITY_INT16)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32)(expected), \ + (UNITY_INT)(UNITY_INT32)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT8)(delta), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT8)(expected), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, \ + message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT16)(delta), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, \ + message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT32)(delta), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT8)(delta), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT8)(expected), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT16)(delta), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT32)(delta), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), \ + (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_CHAR_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (UNITY_UINT8)(delta), (UNITY_INT)(UNITY_INT8)(expected), \ + (UNITY_INT)(UNITY_INT8)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) + +#define UNITY_TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT8)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT8)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT8)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, \ + UNITY_ARRAY_TO_ARRAY) + +#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) \ + UnityAssertEqualNumber( \ + (UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) +#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) \ + UnityAssertEqualString((const char *)(expected), \ + (const char *)(actual), (message), \ + (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, \ + message) \ + UnityAssertEqualStringLen((const char *)(expected), \ + (const char *)(actual), (UNITY_UINT32)(len), \ + (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) \ + UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(len), 1, (message), \ + (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) + +#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualStringArray( \ + (UNITY_INTERNAL_PTR)(expected), (const char **)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, \ + num_elements, line, message) \ + UnityAssertEqualMemory( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) + +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, \ + message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(expected), (UNITY_INT_WIDTH / 8)), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT8)(expected), 1), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT16)(expected), 2), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT32)(expected), 4), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(expected), (UNITY_INT_WIDTH / 8)), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_UINT8)(expected), 1), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT8)(expected), 1), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT16)(expected), 2), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT32)(expected), 4), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, \ + message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_PTR_TO_INT)(expected), \ + (UNITY_POINTER_WIDTH / 8)), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualStringArray( \ + (UNITY_INTERNAL_PTR)(expected), (const char **)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, \ + num_elements, line, message) \ + UnityAssertEqualMemory( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT8)(expected), 1), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, \ + UNITY_ARRAY_TO_VAL) #ifdef UNITY_SUPPORT_64 -#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), \ + (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), \ + (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) \ + UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), \ + (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_UINT64)(expected), 8), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualIntArray( \ + UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, \ + message) \ + UnityAssertNumbersWithin( \ + (delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) \ + UnityAssertNumbersWithin( \ + (delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, \ + message) \ + UnityAssertGreaterOrLessOrEqualNumber( \ + (UNITY_INT)(threshold), (UNITY_INT)(actual), \ + UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), \ + UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UnityAssertNumbersArrayWithin( \ + (UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), \ + (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), \ + (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, \ + UNITY_ARRAY_TO_ARRAY) #else -#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, \ + line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, \ + line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, \ + line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, \ + num_elements, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #endif #ifdef UNITY_EXCLUDE_FLOAT -#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, \ + line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, \ + line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #else -#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) -#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) +#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) \ + UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), \ + (UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) \ + UNITY_TEST_ASSERT_FLOAT_WITHIN( \ + (UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, \ + (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), \ + (UNITY_LINE_TYPE)(line), (message)) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualFloatArray( \ + (UNITY_FLOAT *)(expected), (UNITY_FLOAT *)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualFloatArray( \ + UnityFloatToPtr(expected), (UNITY_FLOAT *)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NEG_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) +#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_NEG_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_NAN) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) \ + UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_DET) #endif #ifdef UNITY_EXCLUDE_DOUBLE -#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, \ + message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, \ + line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, \ + line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) \ + UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #else -#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) -#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) +#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, \ + message) \ + UnityAssertDoublesWithin( \ + (UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), \ + (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) \ + UNITY_TEST_ASSERT_DOUBLE_WITHIN( \ + (UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, \ + (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), \ + (UNITY_LINE_TYPE)(line), (message)) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualDoubleArray( \ + (UNITY_DOUBLE *)(expected), (UNITY_DOUBLE *)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, \ + line, message) \ + UnityAssertEqualDoubleArray( \ + UnityDoubleToPtr(expected), (UNITY_DOUBLE *)(actual), \ + (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), \ + UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NEG_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) +#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_NEG_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_NAN) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) \ + UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), \ + (UNITY_LINE_TYPE)(line), \ + UNITY_FLOAT_IS_NOT_DET) #endif /* End of UNITY_INTERNALS_H */ diff --git a/tests/unit/unity/src/unity.c b/tests/unit/unity/src/unity.c index ffa5cf0d..3e323183 100644 --- a/tests/unit/unity/src/unity.c +++ b/tests/unit/unity/src/unity.c @@ -13,62 +13,78 @@ #define PROGMEM #endif -/* If omitted from header, declare overrideable prototypes here so they're ready for use */ +/* If omitted from header, declare overrideable prototypes here so they're ready + * for use */ #ifdef UNITY_OMIT_OUTPUT_CHAR_HEADER_DECLARATION void UNITY_OUTPUT_CHAR(int); #endif /* Helpful macros for us to use here in Assert functions */ -#define UNITY_FAIL_AND_BAIL { Unity.CurrentTestFailed = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); } -#define UNITY_IGNORE_AND_BAIL { Unity.CurrentTestIgnored = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); } -#define RETURN_IF_FAIL_OR_IGNORE if (Unity.CurrentTestFailed || Unity.CurrentTestIgnored) TEST_ABORT() +#define UNITY_FAIL_AND_BAIL \ + { \ + Unity.CurrentTestFailed = 1; \ + UNITY_OUTPUT_FLUSH(); \ + TEST_ABORT(); \ + } +#define UNITY_IGNORE_AND_BAIL \ + { \ + Unity.CurrentTestIgnored = 1; \ + UNITY_OUTPUT_FLUSH(); \ + TEST_ABORT(); \ + } +#define RETURN_IF_FAIL_OR_IGNORE \ + if (Unity.CurrentTestFailed || Unity.CurrentTestIgnored) \ + TEST_ABORT() struct UNITY_STORAGE_T Unity; #ifdef UNITY_OUTPUT_COLOR -const char PROGMEM UnityStrOk[] = "\033[42mOK\033[00m"; -const char PROGMEM UnityStrPass[] = "\033[42mPASS\033[00m"; -const char PROGMEM UnityStrFail[] = "\033[41mFAIL\033[00m"; -const char PROGMEM UnityStrIgnore[] = "\033[43mIGNORE\033[00m"; +const char PROGMEM UnityStrOk[] = "\033[42mOK\033[00m"; +const char PROGMEM UnityStrPass[] = "\033[42mPASS\033[00m"; +const char PROGMEM UnityStrFail[] = "\033[41mFAIL\033[00m"; +const char PROGMEM UnityStrIgnore[] = "\033[43mIGNORE\033[00m"; #else -const char PROGMEM UnityStrOk[] = "OK"; -const char PROGMEM UnityStrPass[] = "PASS"; -const char PROGMEM UnityStrFail[] = "FAIL"; -const char PROGMEM UnityStrIgnore[] = "IGNORE"; +const char PROGMEM UnityStrOk[] = "OK"; +const char PROGMEM UnityStrPass[] = "PASS"; +const char PROGMEM UnityStrFail[] = "FAIL"; +const char PROGMEM UnityStrIgnore[] = "IGNORE"; #endif -static const char PROGMEM UnityStrNull[] = "NULL"; -static const char PROGMEM UnityStrSpacer[] = ". "; -static const char PROGMEM UnityStrExpected[] = " Expected "; -static const char PROGMEM UnityStrWas[] = " Was "; -static const char PROGMEM UnityStrGt[] = " to be greater than "; -static const char PROGMEM UnityStrLt[] = " to be less than "; -static const char PROGMEM UnityStrOrEqual[] = "or equal to "; -static const char PROGMEM UnityStrNotEqual[] = " to be not equal to "; -static const char PROGMEM UnityStrElement[] = " Element "; -static const char PROGMEM UnityStrByte[] = " Byte "; -static const char PROGMEM UnityStrMemory[] = " Memory Mismatch."; -static const char PROGMEM UnityStrDelta[] = " Values Not Within Delta "; -static const char PROGMEM UnityStrPointless[] = " You Asked Me To Compare Nothing, Which Was Pointless."; -static const char PROGMEM UnityStrNullPointerForExpected[] = " Expected pointer to be NULL"; -static const char PROGMEM UnityStrNullPointerForActual[] = " Actual pointer was NULL"; +static const char PROGMEM UnityStrNull[] = "NULL"; +static const char PROGMEM UnityStrSpacer[] = ". "; +static const char PROGMEM UnityStrExpected[] = " Expected "; +static const char PROGMEM UnityStrWas[] = " Was "; +static const char PROGMEM UnityStrGt[] = " to be greater than "; +static const char PROGMEM UnityStrLt[] = " to be less than "; +static const char PROGMEM UnityStrOrEqual[] = "or equal to "; +static const char PROGMEM UnityStrNotEqual[] = " to be not equal to "; +static const char PROGMEM UnityStrElement[] = " Element "; +static const char PROGMEM UnityStrByte[] = " Byte "; +static const char PROGMEM UnityStrMemory[] = " Memory Mismatch."; +static const char PROGMEM UnityStrDelta[] = " Values Not Within Delta "; +static const char PROGMEM UnityStrPointless[] = + " You Asked Me To Compare Nothing, Which Was Pointless."; +static const char PROGMEM UnityStrNullPointerForExpected[] = + " Expected pointer to be NULL"; +static const char PROGMEM UnityStrNullPointerForActual[] = + " Actual pointer was NULL"; #ifndef UNITY_EXCLUDE_FLOAT -static const char PROGMEM UnityStrNot[] = "Not "; -static const char PROGMEM UnityStrInf[] = "Infinity"; -static const char PROGMEM UnityStrNegInf[] = "Negative Infinity"; -static const char PROGMEM UnityStrNaN[] = "NaN"; -static const char PROGMEM UnityStrDet[] = "Determinate"; -static const char PROGMEM UnityStrInvalidFloatTrait[] = "Invalid Float Trait"; +static const char PROGMEM UnityStrNot[] = "Not "; +static const char PROGMEM UnityStrInf[] = "Infinity"; +static const char PROGMEM UnityStrNegInf[] = "Negative Infinity"; +static const char PROGMEM UnityStrNaN[] = "NaN"; +static const char PROGMEM UnityStrDet[] = "Determinate"; +static const char PROGMEM UnityStrInvalidFloatTrait[] = "Invalid Float Trait"; #endif -const char PROGMEM UnityStrErrShorthand[] = "Unity Shorthand Support Disabled"; -const char PROGMEM UnityStrErrFloat[] = "Unity Floating Point Disabled"; -const char PROGMEM UnityStrErrDouble[] = "Unity Double Precision Disabled"; -const char PROGMEM UnityStrErr64[] = "Unity 64-bit Support Disabled"; -static const char PROGMEM UnityStrBreaker[] = "-----------------------"; -static const char PROGMEM UnityStrResultsTests[] = " Tests "; -static const char PROGMEM UnityStrResultsFailures[] = " Failures "; -static const char PROGMEM UnityStrResultsIgnored[] = " Ignored "; -static const char PROGMEM UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " "; -static const char PROGMEM UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " "; +const char PROGMEM UnityStrErrShorthand[] = "Unity Shorthand Support Disabled"; +const char PROGMEM UnityStrErrFloat[] = "Unity Floating Point Disabled"; +const char PROGMEM UnityStrErrDouble[] = "Unity Double Precision Disabled"; +const char PROGMEM UnityStrErr64[] = "Unity 64-bit Support Disabled"; +static const char PROGMEM UnityStrBreaker[] = "-----------------------"; +static const char PROGMEM UnityStrResultsTests[] = " Tests "; +static const char PROGMEM UnityStrResultsFailures[] = " Failures "; +static const char PROGMEM UnityStrResultsIgnored[] = " Ignored "; +static const char PROGMEM UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " "; +static const char PROGMEM UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " "; /*----------------------------------------------- * Pretty Printers & Test Result Output Handlers @@ -76,251 +92,213 @@ static const char PROGMEM UnityStrDetail2Name[] = " " UNITY_DETAIL2_N /*-----------------------------------------------*/ /* Local helper function to print characters. */ -static void UnityPrintChar(const char* pch) +static void UnityPrintChar(const char *pch) { - /* printable characters plus CR & LF are printed */ - if ((*pch <= 126) && (*pch >= 32)) - { - UNITY_OUTPUT_CHAR(*pch); - } - /* write escaped carriage returns */ - else if (*pch == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (*pch == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)*pch, 2); - } + /* printable characters plus CR & LF are printed */ + if ((*pch <= 126) && (*pch >= 32)) { + UNITY_OUTPUT_CHAR(*pch); + } + /* write escaped carriage returns */ + else if (*pch == 13) { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('r'); + } + /* write escaped line feeds */ + else if (*pch == 10) { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('n'); + } + /* unprintable characters are shown as codes */ + else { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)*pch, 2); + } } /*-----------------------------------------------*/ /* Local helper function to print ANSI escape strings e.g. "\033[42m". */ #ifdef UNITY_OUTPUT_COLOR -static UNITY_UINT UnityPrintAnsiEscapeString(const char* string) +static UNITY_UINT UnityPrintAnsiEscapeString(const char *string) { - const char* pch = string; - UNITY_UINT count = 0; - - while (*pch && (*pch != 'm')) - { - UNITY_OUTPUT_CHAR(*pch); - pch++; - count++; - } - UNITY_OUTPUT_CHAR('m'); - count++; - - return count; + const char *pch = string; + UNITY_UINT count = 0; + + while (*pch && (*pch != 'm')) { + UNITY_OUTPUT_CHAR(*pch); + pch++; + count++; + } + UNITY_OUTPUT_CHAR('m'); + count++; + + return count; } #endif /*-----------------------------------------------*/ -void UnityPrint(const char* string) +void UnityPrint(const char *string) { - const char* pch = string; + const char *pch = string; - if (pch != NULL) - { - while (*pch) - { + if (pch != NULL) { + while (*pch) { #ifdef UNITY_OUTPUT_COLOR - /* print ANSI escape code */ - if ((*pch == 27) && (*(pch + 1) == '[')) - { - pch += UnityPrintAnsiEscapeString(pch); - continue; - } + /* print ANSI escape code */ + if ((*pch == 27) && (*(pch + 1) == '[')) { + pch += UnityPrintAnsiEscapeString(pch); + continue; + } #endif - UnityPrintChar(pch); - pch++; - } - } + UnityPrintChar(pch); + pch++; + } + } } /*-----------------------------------------------*/ -void UnityPrintLen(const char* string, const UNITY_UINT32 length) +void UnityPrintLen(const char *string, const UNITY_UINT32 length) { - const char* pch = string; - - if (pch != NULL) - { - while (*pch && ((UNITY_UINT32)(pch - string) < length)) - { - /* printable characters plus CR & LF are printed */ - if ((*pch <= 126) && (*pch >= 32)) - { - UNITY_OUTPUT_CHAR(*pch); - } - /* write escaped carriage returns */ - else if (*pch == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (*pch == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)*pch, 2); - } - pch++; - } - } + const char *pch = string; + + if (pch != NULL) { + while (*pch && ((UNITY_UINT32)(pch - string) < length)) { + /* printable characters plus CR & LF are printed */ + if ((*pch <= 126) && (*pch >= 32)) { + UNITY_OUTPUT_CHAR(*pch); + } + /* write escaped carriage returns */ + else if (*pch == 13) { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('r'); + } + /* write escaped line feeds */ + else if (*pch == 10) { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('n'); + } + /* unprintable characters are shown as codes */ + else { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)*pch, 2); + } + pch++; + } + } } /*-----------------------------------------------*/ -void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style) +void UnityPrintNumberByStyle(const UNITY_INT number, + const UNITY_DISPLAY_STYLE_T style) { - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (style == UNITY_DISPLAY_STYLE_CHAR) - { - /* printable characters plus CR & LF are printed */ - UNITY_OUTPUT_CHAR('\''); - if ((number <= 126) && (number >= 32)) - { - UNITY_OUTPUT_CHAR((int)number); - } - /* write escaped carriage returns */ - else if (number == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (number == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, 2); - } - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrintNumber(number); - } - } - else if ((style & UNITY_DISPLAY_RANGE_UINT) == UNITY_DISPLAY_RANGE_UINT) - { - UnityPrintNumberUnsigned((UNITY_UINT)number); - } - else - { - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, (char)((style & 0xF) * 2)); - } + if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) { + if (style == UNITY_DISPLAY_STYLE_CHAR) { + /* printable characters plus CR & LF are printed */ + UNITY_OUTPUT_CHAR('\''); + if ((number <= 126) && (number >= 32)) { + UNITY_OUTPUT_CHAR((int)number); + } + /* write escaped carriage returns */ + else if (number == 13) { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('r'); + } + /* write escaped line feeds */ + else if (number == 10) { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('n'); + } + /* unprintable characters are shown as codes */ + else { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)number, 2); + } + UNITY_OUTPUT_CHAR('\''); + } else { + UnityPrintNumber(number); + } + } else if ((style & UNITY_DISPLAY_RANGE_UINT) == + UNITY_DISPLAY_RANGE_UINT) { + UnityPrintNumberUnsigned((UNITY_UINT)number); + } else { + UNITY_OUTPUT_CHAR('0'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)number, + (char)((style & 0xF) * 2)); + } } /*-----------------------------------------------*/ void UnityPrintNumber(const UNITY_INT number_to_print) { - UNITY_UINT number = (UNITY_UINT)number_to_print; - - if (number_to_print < 0) - { - /* A negative number, including MIN negative */ - UNITY_OUTPUT_CHAR('-'); - number = (~number) + 1; - } - UnityPrintNumberUnsigned(number); + UNITY_UINT number = (UNITY_UINT)number_to_print; + + if (number_to_print < 0) { + /* A negative number, including MIN negative */ + UNITY_OUTPUT_CHAR('-'); + number = (~number) + 1; + } + UnityPrintNumberUnsigned(number); } /*----------------------------------------------- * basically do an itoa using as little ram as possible */ void UnityPrintNumberUnsigned(const UNITY_UINT number) { - UNITY_UINT divisor = 1; - - /* figure out initial divisor */ - while (number / divisor > 9) - { - divisor *= 10; - } - - /* now mod and print, then divide divisor */ - do - { - UNITY_OUTPUT_CHAR((char)('0' + (number / divisor % 10))); - divisor /= 10; - } while (divisor > 0); + UNITY_UINT divisor = 1; + + /* figure out initial divisor */ + while (number / divisor > 9) { + divisor *= 10; + } + + /* now mod and print, then divide divisor */ + do { + UNITY_OUTPUT_CHAR((char)('0' + (number / divisor % 10))); + divisor /= 10; + } while (divisor > 0); } /*-----------------------------------------------*/ void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print) { - int nibble; - char nibbles = nibbles_to_print; - - if ((unsigned)nibbles > UNITY_MAX_NIBBLES) - { - nibbles = UNITY_MAX_NIBBLES; - } - - while (nibbles > 0) - { - nibbles--; - nibble = (int)(number >> (nibbles * 4)) & 0x0F; - if (nibble <= 9) - { - UNITY_OUTPUT_CHAR((char)('0' + nibble)); - } - else - { - UNITY_OUTPUT_CHAR((char)('A' - 10 + nibble)); - } - } + int nibble; + char nibbles = nibbles_to_print; + + if ((unsigned)nibbles > UNITY_MAX_NIBBLES) { + nibbles = UNITY_MAX_NIBBLES; + } + + while (nibbles > 0) { + nibbles--; + nibble = (int)(number >> (nibbles * 4)) & 0x0F; + if (nibble <= 9) { + UNITY_OUTPUT_CHAR((char)('0' + nibble)); + } else { + UNITY_OUTPUT_CHAR((char)('A' - 10 + nibble)); + } + } } /*-----------------------------------------------*/ void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number) { - UNITY_UINT current_bit = (UNITY_UINT)1 << (UNITY_INT_WIDTH - 1); - UNITY_INT32 i; - - for (i = 0; i < UNITY_INT_WIDTH; i++) - { - if (current_bit & mask) - { - if (current_bit & number) - { - UNITY_OUTPUT_CHAR('1'); - } - else - { - UNITY_OUTPUT_CHAR('0'); - } - } - else - { - UNITY_OUTPUT_CHAR('X'); - } - current_bit = current_bit >> 1; - } + UNITY_UINT current_bit = (UNITY_UINT)1 << (UNITY_INT_WIDTH - 1); + UNITY_INT32 i; + + for (i = 0; i < UNITY_INT_WIDTH; i++) { + if (current_bit & mask) { + if (current_bit & number) { + UNITY_OUTPUT_CHAR('1'); + } else { + UNITY_OUTPUT_CHAR('0'); + } + } else { + UNITY_OUTPUT_CHAR('X'); + } + current_bit = current_bit >> 1; + } } /*-----------------------------------------------*/ @@ -335,194 +313,192 @@ void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number) void UnityPrintFloat(const UNITY_DOUBLE input_number) { #ifdef UNITY_INCLUDE_DOUBLE - static const int sig_digits = 9; - static const UNITY_INT32 min_scaled = 100000000; - static const UNITY_INT32 max_scaled = 1000000000; + static const int sig_digits = 9; + static const UNITY_INT32 min_scaled = 100000000; + static const UNITY_INT32 max_scaled = 1000000000; #else - static const int sig_digits = 7; - static const UNITY_INT32 min_scaled = 1000000; - static const UNITY_INT32 max_scaled = 10000000; + static const int sig_digits = 7; + static const UNITY_INT32 min_scaled = 1000000; + static const UNITY_INT32 max_scaled = 10000000; #endif - UNITY_DOUBLE number = input_number; - - /* print minus sign (does not handle negative zero) */ - if (number < 0.0f) - { - UNITY_OUTPUT_CHAR('-'); - number = -number; - } - - /* handle zero, NaN, and +/- infinity */ - if (number == 0.0f) - { - UnityPrint("0"); - } - else if (isnan(number)) - { - UnityPrint("nan"); - } - else if (isinf(number)) - { - UnityPrint("inf"); - } - else - { - UNITY_INT32 n_int = 0, n; - int exponent = 0; - int decimals, digits; - char buf[16] = {0}; - - /* - * Scale up or down by powers of 10. To minimize rounding error, - * start with a factor/divisor of 10^10, which is the largest - * power of 10 that can be represented exactly. Finally, compute - * (exactly) the remaining power of 10 and perform one more - * multiplication or division. - */ - if (number < 1.0f) - { - UNITY_DOUBLE factor = 1.0f; - - while (number < (UNITY_DOUBLE)max_scaled / 1e10f) { number *= 1e10f; exponent -= 10; } - while (number * factor < (UNITY_DOUBLE)min_scaled) { factor *= 10.0f; exponent--; } - - number *= factor; - } - else if (number > (UNITY_DOUBLE)max_scaled) - { - UNITY_DOUBLE divisor = 1.0f; - - while (number > (UNITY_DOUBLE)min_scaled * 1e10f) { number /= 1e10f; exponent += 10; } - while (number / divisor > (UNITY_DOUBLE)max_scaled) { divisor *= 10.0f; exponent++; } - - number /= divisor; - } - else - { - /* - * In this range, we can split off the integer part before - * doing any multiplications. This reduces rounding error by - * freeing up significant bits in the fractional part. - */ - UNITY_DOUBLE factor = 1.0f; - n_int = (UNITY_INT32)number; - number -= (UNITY_DOUBLE)n_int; - - while (n_int < min_scaled) { n_int *= 10; factor *= 10.0f; exponent--; } - - number *= factor; - } - - /* round to nearest integer */ - n = ((UNITY_INT32)(number + number) + 1) / 2; + UNITY_DOUBLE number = input_number; + + /* print minus sign (does not handle negative zero) */ + if (number < 0.0f) { + UNITY_OUTPUT_CHAR('-'); + number = -number; + } + + /* handle zero, NaN, and +/- infinity */ + if (number == 0.0f) { + UnityPrint("0"); + } else if (isnan(number)) { + UnityPrint("nan"); + } else if (isinf(number)) { + UnityPrint("inf"); + } else { + UNITY_INT32 n_int = 0, n; + int exponent = 0; + int decimals, digits; + char buf[16] = {0}; + + /* + * Scale up or down by powers of 10. To minimize rounding + * error, start with a factor/divisor of 10^10, which is the + * largest power of 10 that can be represented exactly. Finally, + * compute (exactly) the remaining power of 10 and perform one + * more multiplication or division. + */ + if (number < 1.0f) { + UNITY_DOUBLE factor = 1.0f; + + while (number < (UNITY_DOUBLE)max_scaled / 1e10f) { + number *= 1e10f; + exponent -= 10; + } + while (number * factor < (UNITY_DOUBLE)min_scaled) { + factor *= 10.0f; + exponent--; + } + + number *= factor; + } else if (number > (UNITY_DOUBLE)max_scaled) { + UNITY_DOUBLE divisor = 1.0f; + + while (number > (UNITY_DOUBLE)min_scaled * 1e10f) { + number /= 1e10f; + exponent += 10; + } + while (number / divisor > (UNITY_DOUBLE)max_scaled) { + divisor *= 10.0f; + exponent++; + } + + number /= divisor; + } else { + /* + * In this range, we can split off the integer part + * before doing any multiplications. This reduces + * rounding error by freeing up significant bits in the + * fractional part. + */ + UNITY_DOUBLE factor = 1.0f; + n_int = (UNITY_INT32)number; + number -= (UNITY_DOUBLE)n_int; + + while (n_int < min_scaled) { + n_int *= 10; + factor *= 10.0f; + exponent--; + } + + number *= factor; + } + + /* round to nearest integer */ + n = ((UNITY_INT32)(number + number) + 1) / 2; #ifndef UNITY_ROUND_TIES_AWAY_FROM_ZERO - /* round to even if exactly between two integers */ - if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f)) - n--; + /* round to even if exactly between two integers */ + if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f)) + n--; #endif - n += n_int; - - if (n >= max_scaled) - { - n = min_scaled; - exponent++; - } - - /* determine where to place decimal point */ - decimals = ((exponent <= 0) && (exponent >= -(sig_digits + 3))) ? (-exponent) : (sig_digits - 1); - exponent += decimals; - - /* truncate trailing zeroes after decimal point */ - while ((decimals > 0) && ((n % 10) == 0)) - { - n /= 10; - decimals--; - } - - /* build up buffer in reverse order */ - digits = 0; - while ((n != 0) || (digits < (decimals + 1))) - { - buf[digits++] = (char)('0' + n % 10); - n /= 10; - } - while (digits > 0) - { - if (digits == decimals) { UNITY_OUTPUT_CHAR('.'); } - UNITY_OUTPUT_CHAR(buf[--digits]); - } - - /* print exponent if needed */ - if (exponent != 0) - { - UNITY_OUTPUT_CHAR('e'); - - if (exponent < 0) - { - UNITY_OUTPUT_CHAR('-'); - exponent = -exponent; - } - else - { - UNITY_OUTPUT_CHAR('+'); - } - - digits = 0; - while ((exponent != 0) || (digits < 2)) - { - buf[digits++] = (char)('0' + exponent % 10); - exponent /= 10; - } - while (digits > 0) - { - UNITY_OUTPUT_CHAR(buf[--digits]); - } - } - } + n += n_int; + + if (n >= max_scaled) { + n = min_scaled; + exponent++; + } + + /* determine where to place decimal point */ + decimals = ((exponent <= 0) && (exponent >= -(sig_digits + 3))) + ? (-exponent) + : (sig_digits - 1); + exponent += decimals; + + /* truncate trailing zeroes after decimal point */ + while ((decimals > 0) && ((n % 10) == 0)) { + n /= 10; + decimals--; + } + + /* build up buffer in reverse order */ + digits = 0; + while ((n != 0) || (digits < (decimals + 1))) { + buf[digits++] = (char)('0' + n % 10); + n /= 10; + } + while (digits > 0) { + if (digits == decimals) { + UNITY_OUTPUT_CHAR('.'); + } + UNITY_OUTPUT_CHAR(buf[--digits]); + } + + /* print exponent if needed */ + if (exponent != 0) { + UNITY_OUTPUT_CHAR('e'); + + if (exponent < 0) { + UNITY_OUTPUT_CHAR('-'); + exponent = -exponent; + } else { + UNITY_OUTPUT_CHAR('+'); + } + + digits = 0; + while ((exponent != 0) || (digits < 2)) { + buf[digits++] = (char)('0' + exponent % 10); + exponent /= 10; + } + while (digits > 0) { + UNITY_OUTPUT_CHAR(buf[--digits]); + } + } + } } #endif /* ! UNITY_EXCLUDE_FLOAT_PRINT */ /*-----------------------------------------------*/ -static void UnityTestResultsBegin(const char* file, const UNITY_LINE_TYPE line) +static void UnityTestResultsBegin(const char *file, const UNITY_LINE_TYPE line) { #ifdef UNITY_OUTPUT_FOR_ECLIPSE - UNITY_OUTPUT_CHAR('('); - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(')'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); + UNITY_OUTPUT_CHAR('('); + UnityPrint(file); + UNITY_OUTPUT_CHAR(':'); + UnityPrintNumber((UNITY_INT)line); + UNITY_OUTPUT_CHAR(')'); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(Unity.CurrentTestName); + UNITY_OUTPUT_CHAR(':'); #else #ifdef UNITY_OUTPUT_FOR_IAR_WORKBENCH - UnityPrint("'); - UnityPrint(Unity.CurrentTestName); - UnityPrint(" "); + UnityPrint("'); + UnityPrint(Unity.CurrentTestName); + UnityPrint(" "); #else #ifdef UNITY_OUTPUT_FOR_QT_CREATOR - UnityPrint("file://"); - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); + UnityPrint("file://"); + UnityPrint(file); + UNITY_OUTPUT_CHAR(':'); + UnityPrintNumber((UNITY_INT)line); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(Unity.CurrentTestName); + UNITY_OUTPUT_CHAR(':'); #else - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(':'); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); + UnityPrint(file); + UNITY_OUTPUT_CHAR(':'); + UnityPrintNumber((UNITY_INT)line); + UNITY_OUTPUT_CHAR(':'); + UnityPrint(Unity.CurrentTestName); + UNITY_OUTPUT_CHAR(':'); #endif #endif #endif @@ -531,116 +507,98 @@ static void UnityTestResultsBegin(const char* file, const UNITY_LINE_TYPE line) /*-----------------------------------------------*/ static void UnityTestResultsFailBegin(const UNITY_LINE_TYPE line) { - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrFail); - UNITY_OUTPUT_CHAR(':'); + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint(UnityStrFail); + UNITY_OUTPUT_CHAR(':'); } /*-----------------------------------------------*/ void UnityConcludeTest(void) { - if (Unity.CurrentTestIgnored) - { - Unity.TestIgnores++; - } - else if (!Unity.CurrentTestFailed) - { - UnityTestResultsBegin(Unity.TestFile, Unity.CurrentTestLineNumber); - UnityPrint(UnityStrPass); - } - else - { - Unity.TestFailures++; - } - - Unity.CurrentTestFailed = 0; - Unity.CurrentTestIgnored = 0; - UNITY_PRINT_EXEC_TIME(); - UNITY_PRINT_EOL(); - UNITY_FLUSH_CALL(); + if (Unity.CurrentTestIgnored) { + Unity.TestIgnores++; + } else if (!Unity.CurrentTestFailed) { + UnityTestResultsBegin(Unity.TestFile, + Unity.CurrentTestLineNumber); + UnityPrint(UnityStrPass); + } else { + Unity.TestFailures++; + } + + Unity.CurrentTestFailed = 0; + Unity.CurrentTestIgnored = 0; + UNITY_PRINT_EXEC_TIME(); + UNITY_PRINT_EOL(); + UNITY_FLUSH_CALL(); } /*-----------------------------------------------*/ -static void UnityAddMsgIfSpecified(const char* msg) +static void UnityAddMsgIfSpecified(const char *msg) { - if (msg) - { - UnityPrint(UnityStrSpacer); + if (msg) { + UnityPrint(UnityStrSpacer); #ifdef UNITY_PRINT_TEST_CONTEXT - UNITY_PRINT_TEST_CONTEXT(); + UNITY_PRINT_TEST_CONTEXT(); #endif #ifndef UNITY_EXCLUDE_DETAILS - if (Unity.CurrentDetail1) - { - UnityPrint(UnityStrDetail1Name); - UnityPrint(Unity.CurrentDetail1); - if (Unity.CurrentDetail2) - { - UnityPrint(UnityStrDetail2Name); - UnityPrint(Unity.CurrentDetail2); - } - UnityPrint(UnityStrSpacer); - } + if (Unity.CurrentDetail1) { + UnityPrint(UnityStrDetail1Name); + UnityPrint(Unity.CurrentDetail1); + if (Unity.CurrentDetail2) { + UnityPrint(UnityStrDetail2Name); + UnityPrint(Unity.CurrentDetail2); + } + UnityPrint(UnityStrSpacer); + } #endif - UnityPrint(msg); - } + UnityPrint(msg); + } } /*-----------------------------------------------*/ -static void UnityPrintExpectedAndActualStrings(const char* expected, const char* actual) +static void UnityPrintExpectedAndActualStrings(const char *expected, + const char *actual) { - UnityPrint(UnityStrExpected); - if (expected != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrint(expected); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } - UnityPrint(UnityStrWas); - if (actual != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrint(actual); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } + UnityPrint(UnityStrExpected); + if (expected != NULL) { + UNITY_OUTPUT_CHAR('\''); + UnityPrint(expected); + UNITY_OUTPUT_CHAR('\''); + } else { + UnityPrint(UnityStrNull); + } + UnityPrint(UnityStrWas); + if (actual != NULL) { + UNITY_OUTPUT_CHAR('\''); + UnityPrint(actual); + UNITY_OUTPUT_CHAR('\''); + } else { + UnityPrint(UnityStrNull); + } } /*-----------------------------------------------*/ -static void UnityPrintExpectedAndActualStringsLen(const char* expected, - const char* actual, - const UNITY_UINT32 length) +static void UnityPrintExpectedAndActualStringsLen(const char *expected, + const char *actual, + const UNITY_UINT32 length) { - UnityPrint(UnityStrExpected); - if (expected != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrintLen(expected, length); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } - UnityPrint(UnityStrWas); - if (actual != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrintLen(actual, length); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } + UnityPrint(UnityStrExpected); + if (expected != NULL) { + UNITY_OUTPUT_CHAR('\''); + UnityPrintLen(expected, length); + UNITY_OUTPUT_CHAR('\''); + } else { + UnityPrint(UnityStrNull); + } + UnityPrint(UnityStrWas); + if (actual != NULL) { + UNITY_OUTPUT_CHAR('\''); + UnityPrintLen(actual, length); + UNITY_OUTPUT_CHAR('\''); + } else { + UnityPrint(UnityStrNull); + } } /*----------------------------------------------- @@ -649,32 +607,32 @@ static void UnityPrintExpectedAndActualStringsLen(const char* expected, /*-----------------------------------------------*/ static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_LINE_TYPE lineNumber, - const char* msg) + UNITY_INTERNAL_PTR actual, + const UNITY_LINE_TYPE lineNumber, + const char *msg) { - /* Both are NULL or same pointer */ - if (expected == actual) { return 0; } - - /* print and return true if just expected is NULL */ - if (expected == NULL) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrNullPointerForExpected); - UnityAddMsgIfSpecified(msg); - return 1; - } - - /* print and return true if just actual is NULL */ - if (actual == NULL) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrNullPointerForActual); - UnityAddMsgIfSpecified(msg); - return 1; - } - - return 0; /* return false if neither is NULL */ + /* Both are NULL or same pointer */ + if (expected == actual) { + return 0; + } + + /* print and return true if just expected is NULL */ + if (expected == NULL) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrNullPointerForExpected); + UnityAddMsgIfSpecified(msg); + return 1; + } + + /* print and return true if just actual is NULL */ + if (actual == NULL) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrNullPointerForActual); + UnityAddMsgIfSpecified(msg); + return 1; + } + + return 0; /* return false if neither is NULL */ } /*----------------------------------------------- @@ -682,934 +640,909 @@ static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected, *-----------------------------------------------*/ /*-----------------------------------------------*/ -void UnityAssertBits(const UNITY_INT mask, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) +void UnityAssertBits(const UNITY_INT mask, const UNITY_INT expected, + const UNITY_INT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber) { - RETURN_IF_FAIL_OR_IGNORE; - - if ((mask & expected) != (mask & actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)expected); - UnityPrint(UnityStrWas); - UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + RETURN_IF_FAIL_OR_IGNORE; + + if ((mask & expected) != (mask & actual)) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)expected); + UnityPrint(UnityStrWas); + UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } /*-----------------------------------------------*/ -void UnityAssertEqualNumber(const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) +void UnityAssertEqualNumber(const UNITY_INT expected, const UNITY_INT actual, + const char *msg, const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style) { - RETURN_IF_FAIL_OR_IGNORE; - - if (expected != actual) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expected, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + RETURN_IF_FAIL_OR_IGNORE; + + if (expected != actual) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expected, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } /*-----------------------------------------------*/ void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, - const UNITY_INT actual, - const UNITY_COMPARISON_T compare, - const char *msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) + const UNITY_INT actual, + const UNITY_COMPARISON_T compare, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style) { - int failed = 0; - RETURN_IF_FAIL_OR_IGNORE; - - if ((threshold == actual) && (compare & UNITY_EQUAL_TO)) { return; } - if ((threshold == actual)) { failed = 1; } - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if ((actual > threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } - if ((actual < threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } - } - else /* UINT or HEX */ - { - if (((UNITY_UINT)actual > (UNITY_UINT)threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } - if (((UNITY_UINT)actual < (UNITY_UINT)threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } - } - - if (failed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(actual, style); - if (compare & UNITY_GREATER_THAN) { UnityPrint(UnityStrGt); } - if (compare & UNITY_SMALLER_THAN) { UnityPrint(UnityStrLt); } - if (compare & UNITY_EQUAL_TO) { UnityPrint(UnityStrOrEqual); } - if (compare == UNITY_NOT_EQUAL) { UnityPrint(UnityStrNotEqual); } - UnityPrintNumberByStyle(threshold, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + int failed = 0; + RETURN_IF_FAIL_OR_IGNORE; + + if ((threshold == actual) && (compare & UNITY_EQUAL_TO)) { + return; + } + if ((threshold == actual)) { + failed = 1; + } + + if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) { + if ((actual > threshold) && (compare & UNITY_SMALLER_THAN)) { + failed = 1; + } + if ((actual < threshold) && (compare & UNITY_GREATER_THAN)) { + failed = 1; + } + } else /* UINT or HEX */ + { + if (((UNITY_UINT)actual > (UNITY_UINT)threshold) && + (compare & UNITY_SMALLER_THAN)) { + failed = 1; + } + if (((UNITY_UINT)actual < (UNITY_UINT)threshold) && + (compare & UNITY_GREATER_THAN)) { + failed = 1; + } + } + + if (failed) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(actual, style); + if (compare & UNITY_GREATER_THAN) { + UnityPrint(UnityStrGt); + } + if (compare & UNITY_SMALLER_THAN) { + UnityPrint(UnityStrLt); + } + if (compare & UNITY_EQUAL_TO) { + UnityPrint(UnityStrOrEqual); + } + if (compare == UNITY_NOT_EQUAL) { + UnityPrint(UnityStrNotEqual); + } + UnityPrintNumberByStyle(threshold, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } -#define UnityPrintPointlessAndBail() \ -{ \ - UnityTestResultsFailBegin(lineNumber); \ - UnityPrint(UnityStrPointless); \ - UnityAddMsgIfSpecified(msg); \ - UNITY_FAIL_AND_BAIL; } +#define UnityPrintPointlessAndBail() \ + { \ + UnityTestResultsFailBegin(lineNumber); \ + UnityPrint(UnityStrPointless); \ + UnityAddMsgIfSpecified(msg); \ + UNITY_FAIL_AND_BAIL; \ + } /*-----------------------------------------------*/ void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags) + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags) { - UNITY_UINT32 elements = num_elements; - unsigned int length = style & 0xF; - unsigned int increment = 0; - - RETURN_IF_FAIL_OR_IGNORE; - - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while ((elements > 0) && (elements--)) - { - UNITY_INT expect_val; - UNITY_INT actual_val; - - switch (length) - { - case 1: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; - increment = sizeof(UNITY_INT8); - break; - - case 2: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; - increment = sizeof(UNITY_INT16); - break; + UNITY_UINT32 elements = num_elements; + unsigned int length = style & 0xF; + unsigned int increment = 0; + + RETURN_IF_FAIL_OR_IGNORE; + + if (num_elements == 0) { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) { + UNITY_FAIL_AND_BAIL; + } + + while ((elements > 0) && (elements--)) { + UNITY_INT expect_val; + UNITY_INT actual_val; + + switch (length) { + case 1: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT8 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT8 *)actual; + increment = sizeof(UNITY_INT8); + break; + + case 2: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT16 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT16 *)actual; + increment = sizeof(UNITY_INT16); + break; #ifdef UNITY_SUPPORT_64 - case 8: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; - increment = sizeof(UNITY_INT64); - break; + case 8: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT64 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT64 *)actual; + increment = sizeof(UNITY_INT64); + break; #endif - default: /* default is length 4 bytes */ - case 4: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; - increment = sizeof(UNITY_INT32); - length = 4; - break; - } - - if (expect_val != actual_val) - { - if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) - { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ - UNITY_INT mask = 1; - mask = (mask << 8 * length) - 1; - expect_val &= mask; - actual_val &= mask; - } - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expect_val, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual_val, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - /* Walk through array by incrementing the pointers */ - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); - } - actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); - } + default: /* default is length 4 bytes */ + case 4: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT32 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT32 *)actual; + increment = sizeof(UNITY_INT32); + length = 4; + break; + } + + if (expect_val != actual_val) { + if ((style & UNITY_DISPLAY_RANGE_UINT) && + (length < + (UNITY_INT_WIDTH / + 8))) { /* For UINT, remove sign extension (padding + 1's) from signed type casts above */ + UNITY_INT mask = 1; + mask = (mask << 8 * length) - 1; + expect_val &= mask; + actual_val &= mask; + } + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expect_val, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual_val, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + /* Walk through array by incrementing the pointers */ + if (flags == UNITY_ARRAY_TO_ARRAY) { + expected = (UNITY_INTERNAL_PTR)((const char *)expected + + increment); + } + actual = (UNITY_INTERNAL_PTR)((const char *)actual + increment); + } } /*-----------------------------------------------*/ #ifndef UNITY_EXCLUDE_FLOAT /* Wrap this define in a function with variable types as float or double */ -#define UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff) \ - if (isinf(expected) && isinf(actual) && (((expected) < 0) == ((actual) < 0))) return 1; \ - if (UNITY_NAN_CHECK) return 1; \ - (diff) = (actual) - (expected); \ - if ((diff) < 0) (diff) = -(diff); \ - if ((delta) < 0) (delta) = -(delta); \ - return !(isnan(diff) || isinf(diff) || ((diff) > (delta))) - /* This first part of this condition will catch any NaN or Infinite values */ +#define UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff) \ + if (isinf(expected) && isinf(actual) && \ + (((expected) < 0) == ((actual) < 0))) \ + return 1; \ + if (UNITY_NAN_CHECK) \ + return 1; \ + (diff) = (actual) - (expected); \ + if ((diff) < 0) \ + (diff) = -(diff); \ + if ((delta) < 0) \ + (delta) = -(delta); \ + return !(isnan(diff) || isinf(diff) || ((diff) > (delta))) +/* This first part of this condition will catch any NaN or Infinite values */ #ifndef UNITY_NAN_NOT_EQUAL_NAN - #define UNITY_NAN_CHECK isnan(expected) && isnan(actual) +#define UNITY_NAN_CHECK isnan(expected) && isnan(actual) #else - #define UNITY_NAN_CHECK 0 +#define UNITY_NAN_CHECK 0 #endif #ifndef UNITY_EXCLUDE_FLOAT_PRINT - #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ - { \ - UnityPrint(UnityStrExpected); \ - UnityPrintFloat(expected); \ - UnityPrint(UnityStrWas); \ - UnityPrintFloat(actual); } +#define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ + { \ + UnityPrint(UnityStrExpected); \ + UnityPrintFloat(expected); \ + UnityPrint(UnityStrWas); \ + UnityPrintFloat(actual); \ + } #else - #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ - UnityPrint(UnityStrDelta) +#define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ + UnityPrint(UnityStrDelta) #endif /* UNITY_EXCLUDE_FLOAT_PRINT */ /*-----------------------------------------------*/ -static int UnityFloatsWithin(UNITY_FLOAT delta, UNITY_FLOAT expected, UNITY_FLOAT actual) +static int UnityFloatsWithin(UNITY_FLOAT delta, UNITY_FLOAT expected, + UNITY_FLOAT actual) { - UNITY_FLOAT diff; - UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); + UNITY_FLOAT diff; + UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); } /*-----------------------------------------------*/ -void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) +void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT *expected, + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT *actual, + const UNITY_UINT32 num_elements, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags) { - UNITY_UINT32 elements = num_elements; - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_expected = expected; - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_actual = actual; - - RETURN_IF_FAIL_OR_IGNORE; - - if (elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - if (!UnityFloatsWithin(*ptr_expected * UNITY_FLOAT_PRECISION, *ptr_expected, *ptr_actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)*ptr_expected, (UNITY_DOUBLE)*ptr_actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - if (flags == UNITY_ARRAY_TO_ARRAY) - { - ptr_expected++; - } - ptr_actual++; - } + UNITY_UINT32 elements = num_elements; + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT *ptr_expected = expected; + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT *ptr_actual = actual; + + RETURN_IF_FAIL_OR_IGNORE; + + if (elements == 0) { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, + (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) { + UNITY_FAIL_AND_BAIL; + } + + while (elements--) { + if (!UnityFloatsWithin(*ptr_expected * UNITY_FLOAT_PRECISION, + *ptr_expected, *ptr_actual)) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT( + (UNITY_DOUBLE)*ptr_expected, + (UNITY_DOUBLE)*ptr_actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + if (flags == UNITY_ARRAY_TO_ARRAY) { + ptr_expected++; + } + ptr_actual++; + } } /*-----------------------------------------------*/ void UnityAssertFloatsWithin(const UNITY_FLOAT delta, - const UNITY_FLOAT expected, - const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) + const UNITY_FLOAT expected, + const UNITY_FLOAT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber) { - RETURN_IF_FAIL_OR_IGNORE; - - - if (!UnityFloatsWithin(delta, expected, actual)) - { - UnityTestResultsFailBegin(lineNumber); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + RETURN_IF_FAIL_OR_IGNORE; + + if (!UnityFloatsWithin(delta, expected, actual)) { + UnityTestResultsFailBegin(lineNumber); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)expected, + (UNITY_DOUBLE)actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } /*-----------------------------------------------*/ -void UnityAssertFloatSpecial(const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style) +void UnityAssertFloatSpecial(const UNITY_FLOAT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style) { - const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; - UNITY_INT should_be_trait = ((UNITY_INT)style & 1); - UNITY_INT is_trait = !should_be_trait; - UNITY_INT trait_index = (UNITY_INT)(style >> 1); - - RETURN_IF_FAIL_OR_IGNORE; - - switch (style) - { - case UNITY_FLOAT_IS_INF: - case UNITY_FLOAT_IS_NOT_INF: - is_trait = isinf(actual) && (actual > 0); - break; - case UNITY_FLOAT_IS_NEG_INF: - case UNITY_FLOAT_IS_NOT_NEG_INF: - is_trait = isinf(actual) && (actual < 0); - break; - - case UNITY_FLOAT_IS_NAN: - case UNITY_FLOAT_IS_NOT_NAN: - is_trait = isnan(actual) ? 1 : 0; - break; - - case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ - case UNITY_FLOAT_IS_NOT_DET: - is_trait = !isinf(actual) && !isnan(actual); - break; - - default: - trait_index = 0; - trait_names[0] = UnityStrInvalidFloatTrait; - break; - } - - if (is_trait != should_be_trait) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - if (!should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); - UnityPrint(UnityStrWas); + const char *trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, + UnityStrDet}; + UNITY_INT should_be_trait = ((UNITY_INT)style & 1); + UNITY_INT is_trait = !should_be_trait; + UNITY_INT trait_index = (UNITY_INT)(style >> 1); + + RETURN_IF_FAIL_OR_IGNORE; + + switch (style) { + case UNITY_FLOAT_IS_INF: + case UNITY_FLOAT_IS_NOT_INF: + is_trait = isinf(actual) && (actual > 0); + break; + case UNITY_FLOAT_IS_NEG_INF: + case UNITY_FLOAT_IS_NOT_NEG_INF: + is_trait = isinf(actual) && (actual < 0); + break; + + case UNITY_FLOAT_IS_NAN: + case UNITY_FLOAT_IS_NOT_NAN: + is_trait = isnan(actual) ? 1 : 0; + break; + + case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not + NaN. */ + case UNITY_FLOAT_IS_NOT_DET: + is_trait = !isinf(actual) && !isnan(actual); + break; + + default: + trait_index = 0; + trait_names[0] = UnityStrInvalidFloatTrait; + break; + } + + if (is_trait != should_be_trait) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + if (!should_be_trait) { + UnityPrint(UnityStrNot); + } + UnityPrint(trait_names[trait_index]); + UnityPrint(UnityStrWas); #ifndef UNITY_EXCLUDE_FLOAT_PRINT - UnityPrintFloat((UNITY_DOUBLE)actual); + UnityPrintFloat((UNITY_DOUBLE)actual); #else - if (should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); + if (should_be_trait) { + UnityPrint(UnityStrNot); + } + UnityPrint(trait_names[trait_index]); #endif - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } #endif /* not UNITY_EXCLUDE_FLOAT */ /*-----------------------------------------------*/ #ifndef UNITY_EXCLUDE_DOUBLE -static int UnityDoublesWithin(UNITY_DOUBLE delta, UNITY_DOUBLE expected, UNITY_DOUBLE actual) +static int UnityDoublesWithin(UNITY_DOUBLE delta, UNITY_DOUBLE expected, + UNITY_DOUBLE actual) { - UNITY_DOUBLE diff; - UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); + UNITY_DOUBLE diff; + UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); } /*-----------------------------------------------*/ -void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) +void UnityAssertEqualDoubleArray( + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE *expected, + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE *actual, + const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, const UNITY_FLAGS_T flags) { - UNITY_UINT32 elements = num_elements; - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_expected = expected; - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_actual = actual; - - RETURN_IF_FAIL_OR_IGNORE; - - if (elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - if (!UnityDoublesWithin(*ptr_expected * UNITY_DOUBLE_PRECISION, *ptr_expected, *ptr_actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(*ptr_expected, *ptr_actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - if (flags == UNITY_ARRAY_TO_ARRAY) - { - ptr_expected++; - } - ptr_actual++; - } + UNITY_UINT32 elements = num_elements; + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE *ptr_expected = expected; + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE *ptr_actual = actual; + + RETURN_IF_FAIL_OR_IGNORE; + + if (elements == 0) { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, + (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) { + UNITY_FAIL_AND_BAIL; + } + + while (elements--) { + if (!UnityDoublesWithin(*ptr_expected * UNITY_DOUBLE_PRECISION, + *ptr_expected, *ptr_actual)) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(*ptr_expected, + *ptr_actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + if (flags == UNITY_ARRAY_TO_ARRAY) { + ptr_expected++; + } + ptr_actual++; + } } /*-----------------------------------------------*/ void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, - const UNITY_DOUBLE expected, - const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) + const UNITY_DOUBLE expected, + const UNITY_DOUBLE actual, const char *msg, + const UNITY_LINE_TYPE lineNumber) { - RETURN_IF_FAIL_OR_IGNORE; - - if (!UnityDoublesWithin(delta, expected, actual)) - { - UnityTestResultsFailBegin(lineNumber); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + RETURN_IF_FAIL_OR_IGNORE; + + if (!UnityDoublesWithin(delta, expected, actual)) { + UnityTestResultsFailBegin(lineNumber); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } /*-----------------------------------------------*/ -void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style) +void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style) { - const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; - UNITY_INT should_be_trait = ((UNITY_INT)style & 1); - UNITY_INT is_trait = !should_be_trait; - UNITY_INT trait_index = (UNITY_INT)(style >> 1); - - RETURN_IF_FAIL_OR_IGNORE; - - switch (style) - { - case UNITY_FLOAT_IS_INF: - case UNITY_FLOAT_IS_NOT_INF: - is_trait = isinf(actual) && (actual > 0); - break; - case UNITY_FLOAT_IS_NEG_INF: - case UNITY_FLOAT_IS_NOT_NEG_INF: - is_trait = isinf(actual) && (actual < 0); - break; - - case UNITY_FLOAT_IS_NAN: - case UNITY_FLOAT_IS_NOT_NAN: - is_trait = isnan(actual) ? 1 : 0; - break; - - case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ - case UNITY_FLOAT_IS_NOT_DET: - is_trait = !isinf(actual) && !isnan(actual); - break; - - default: - trait_index = 0; - trait_names[0] = UnityStrInvalidFloatTrait; - break; - } - - if (is_trait != should_be_trait) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - if (!should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); - UnityPrint(UnityStrWas); + const char *trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, + UnityStrDet}; + UNITY_INT should_be_trait = ((UNITY_INT)style & 1); + UNITY_INT is_trait = !should_be_trait; + UNITY_INT trait_index = (UNITY_INT)(style >> 1); + + RETURN_IF_FAIL_OR_IGNORE; + + switch (style) { + case UNITY_FLOAT_IS_INF: + case UNITY_FLOAT_IS_NOT_INF: + is_trait = isinf(actual) && (actual > 0); + break; + case UNITY_FLOAT_IS_NEG_INF: + case UNITY_FLOAT_IS_NOT_NEG_INF: + is_trait = isinf(actual) && (actual < 0); + break; + + case UNITY_FLOAT_IS_NAN: + case UNITY_FLOAT_IS_NOT_NAN: + is_trait = isnan(actual) ? 1 : 0; + break; + + case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not + NaN. */ + case UNITY_FLOAT_IS_NOT_DET: + is_trait = !isinf(actual) && !isnan(actual); + break; + + default: + trait_index = 0; + trait_names[0] = UnityStrInvalidFloatTrait; + break; + } + + if (is_trait != should_be_trait) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + if (!should_be_trait) { + UnityPrint(UnityStrNot); + } + UnityPrint(trait_names[trait_index]); + UnityPrint(UnityStrWas); #ifndef UNITY_EXCLUDE_FLOAT_PRINT - UnityPrintFloat(actual); + UnityPrintFloat(actual); #else - if (should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); + if (should_be_trait) { + UnityPrint(UnityStrNot); + } + UnityPrint(trait_names[trait_index]); #endif - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } #endif /* not UNITY_EXCLUDE_DOUBLE */ /*-----------------------------------------------*/ -void UnityAssertNumbersWithin(const UNITY_UINT delta, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) +void UnityAssertNumbersWithin(const UNITY_UINT delta, const UNITY_INT expected, + const UNITY_INT actual, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style) { - RETURN_IF_FAIL_OR_IGNORE; - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (actual > expected) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); - } - } - else - { - if ((UNITY_UINT)actual > (UNITY_UINT)expected) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrDelta); - UnityPrintNumberByStyle((UNITY_INT)delta, style); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expected, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + RETURN_IF_FAIL_OR_IGNORE; + + if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) { + if (actual > expected) { + Unity.CurrentTestFailed = + (((UNITY_UINT)actual - (UNITY_UINT)expected) > + delta); + } else { + Unity.CurrentTestFailed = + (((UNITY_UINT)expected - (UNITY_UINT)actual) > + delta); + } + } else { + if ((UNITY_UINT)actual > (UNITY_UINT)expected) { + Unity.CurrentTestFailed = + (((UNITY_UINT)actual - (UNITY_UINT)expected) > + delta); + } else { + Unity.CurrentTestFailed = + (((UNITY_UINT)expected - (UNITY_UINT)actual) > + delta); + } + } + + if (Unity.CurrentTestFailed) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrDelta); + UnityPrintNumberByStyle((UNITY_INT)delta, style); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expected, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } /*-----------------------------------------------*/ -void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, - UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags) +void UnityAssertNumbersArrayWithin( + const UNITY_UINT delta, UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags) { - UNITY_UINT32 elements = num_elements; - unsigned int length = style & 0xF; - unsigned int increment = 0; - - RETURN_IF_FAIL_OR_IGNORE; - - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while ((elements > 0) && (elements--)) - { - UNITY_INT expect_val; - UNITY_INT actual_val; - - switch (length) - { - case 1: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; - increment = sizeof(UNITY_INT8); - break; - - case 2: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; - increment = sizeof(UNITY_INT16); - break; + UNITY_UINT32 elements = num_elements; + unsigned int length = style & 0xF; + unsigned int increment = 0; + + RETURN_IF_FAIL_OR_IGNORE; + + if (num_elements == 0) { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) { + UNITY_FAIL_AND_BAIL; + } + + while ((elements > 0) && (elements--)) { + UNITY_INT expect_val; + UNITY_INT actual_val; + + switch (length) { + case 1: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT8 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT8 *)actual; + increment = sizeof(UNITY_INT8); + break; + + case 2: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT16 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT16 *)actual; + increment = sizeof(UNITY_INT16); + break; #ifdef UNITY_SUPPORT_64 - case 8: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; - increment = sizeof(UNITY_INT64); - break; + case 8: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT64 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT64 *)actual; + increment = sizeof(UNITY_INT64); + break; #endif - default: /* default is length 4 bytes */ - case 4: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; - increment = sizeof(UNITY_INT32); - length = 4; - break; - } - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (actual_val > expect_val) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); - } - } - else - { - if ((UNITY_UINT)actual_val > (UNITY_UINT)expect_val) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); - } - } - - if (Unity.CurrentTestFailed) - { - if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) - { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ - UNITY_INT mask = 1; - mask = (mask << 8 * length) - 1; - expect_val &= mask; - actual_val &= mask; - } - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrDelta); - UnityPrintNumberByStyle((UNITY_INT)delta, style); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expect_val, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual_val, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - /* Walk through array by incrementing the pointers */ - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); - } - actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); - } + default: /* default is length 4 bytes */ + case 4: + expect_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT32 *)expected; + actual_val = + *(UNITY_PTR_ATTRIBUTE const UNITY_INT32 *)actual; + increment = sizeof(UNITY_INT32); + length = 4; + break; + } + + if ((style & UNITY_DISPLAY_RANGE_INT) == + UNITY_DISPLAY_RANGE_INT) { + if (actual_val > expect_val) { + Unity.CurrentTestFailed = + (((UNITY_UINT)actual_val - + (UNITY_UINT)expect_val) > delta); + } else { + Unity.CurrentTestFailed = + (((UNITY_UINT)expect_val - + (UNITY_UINT)actual_val) > delta); + } + } else { + if ((UNITY_UINT)actual_val > (UNITY_UINT)expect_val) { + Unity.CurrentTestFailed = + (((UNITY_UINT)actual_val - + (UNITY_UINT)expect_val) > delta); + } else { + Unity.CurrentTestFailed = + (((UNITY_UINT)expect_val - + (UNITY_UINT)actual_val) > delta); + } + } + + if (Unity.CurrentTestFailed) { + if ((style & UNITY_DISPLAY_RANGE_UINT) && + (length < + (UNITY_INT_WIDTH / + 8))) { /* For UINT, remove sign extension (padding + 1's) from signed type casts above */ + UNITY_INT mask = 1; + mask = (mask << 8 * length) - 1; + expect_val &= mask; + actual_val &= mask; + } + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrDelta); + UnityPrintNumberByStyle((UNITY_INT)delta, style); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expect_val, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual_val, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + /* Walk through array by incrementing the pointers */ + if (flags == UNITY_ARRAY_TO_ARRAY) { + expected = (UNITY_INTERNAL_PTR)((const char *)expected + + increment); + } + actual = (UNITY_INTERNAL_PTR)((const char *)actual + increment); + } } /*-----------------------------------------------*/ -void UnityAssertEqualString(const char* expected, - const char* actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) +void UnityAssertEqualString(const char *expected, const char *actual, + const char *msg, const UNITY_LINE_TYPE lineNumber) { - UNITY_UINT32 i; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if both pointers not null compare the strings */ - if (expected && actual) - { - for (i = 0; expected[i] || actual[i]; i++) - { - if (expected[i] != actual[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expected != actual) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrintExpectedAndActualStrings(expected, actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + UNITY_UINT32 i; + + RETURN_IF_FAIL_OR_IGNORE; + + /* if both pointers not null compare the strings */ + if (expected && actual) { + for (i = 0; expected[i] || actual[i]; i++) { + if (expected[i] != actual[i]) { + Unity.CurrentTestFailed = 1; + break; + } + } + } else { /* handle case of one pointers being null (if both null, test + should pass) */ + if (expected != actual) { + Unity.CurrentTestFailed = 1; + } + } + + if (Unity.CurrentTestFailed) { + UnityTestResultsFailBegin(lineNumber); + UnityPrintExpectedAndActualStrings(expected, actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } /*-----------------------------------------------*/ -void UnityAssertEqualStringLen(const char* expected, - const char* actual, - const UNITY_UINT32 length, - const char* msg, - const UNITY_LINE_TYPE lineNumber) +void UnityAssertEqualStringLen(const char *expected, const char *actual, + const UNITY_UINT32 length, const char *msg, + const UNITY_LINE_TYPE lineNumber) { - UNITY_UINT32 i; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if both pointers not null compare the strings */ - if (expected && actual) - { - for (i = 0; (i < length) && (expected[i] || actual[i]); i++) - { - if (expected[i] != actual[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expected != actual) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrintExpectedAndActualStringsLen(expected, actual, length); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } + UNITY_UINT32 i; + + RETURN_IF_FAIL_OR_IGNORE; + + /* if both pointers not null compare the strings */ + if (expected && actual) { + for (i = 0; (i < length) && (expected[i] || actual[i]); i++) { + if (expected[i] != actual[i]) { + Unity.CurrentTestFailed = 1; + break; + } + } + } else { /* handle case of one pointers being null (if both null, test + should pass) */ + if (expected != actual) { + Unity.CurrentTestFailed = 1; + } + } + + if (Unity.CurrentTestFailed) { + UnityTestResultsFailBegin(lineNumber); + UnityPrintExpectedAndActualStringsLen(expected, actual, length); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } } /*-----------------------------------------------*/ void UnityAssertEqualStringArray(UNITY_INTERNAL_PTR expected, - const char** actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) + const char **actual, + const UNITY_UINT32 num_elements, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags) { - UNITY_UINT32 i = 0; - UNITY_UINT32 j = 0; - const char* expd = NULL; - const char* act = NULL; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if no elements, it's an error */ - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if ((const void*)expected == (const void*)actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - if (flags != UNITY_ARRAY_TO_ARRAY) - { - expd = (const char*)expected; - } - - do - { - act = actual[j]; - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expd = ((const char* const*)expected)[j]; - } - - /* if both pointers not null compare the strings */ - if (expd && act) - { - for (i = 0; expd[i] || act[i]; i++) - { - if (expd[i] != act[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expd != act) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - if (num_elements > 1) - { - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(j); - } - UnityPrintExpectedAndActualStrings(expd, act); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - } while (++j < num_elements); + UNITY_UINT32 i = 0; + UNITY_UINT32 j = 0; + const char *expd = NULL; + const char *act = NULL; + + RETURN_IF_FAIL_OR_IGNORE; + + /* if no elements, it's an error */ + if (num_elements == 0) { + UnityPrintPointlessAndBail(); + } + + if ((const void *)expected == (const void *)actual) { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, + (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) { + UNITY_FAIL_AND_BAIL; + } + + if (flags != UNITY_ARRAY_TO_ARRAY) { + expd = (const char *)expected; + } + + do { + act = actual[j]; + if (flags == UNITY_ARRAY_TO_ARRAY) { + expd = ((const char *const *)expected)[j]; + } + + /* if both pointers not null compare the strings */ + if (expd && act) { + for (i = 0; expd[i] || act[i]; i++) { + if (expd[i] != act[i]) { + Unity.CurrentTestFailed = 1; + break; + } + } + } else { /* handle case of one pointers being null (if both + null, test should pass) */ + if (expd != act) { + Unity.CurrentTestFailed = 1; + } + } + + if (Unity.CurrentTestFailed) { + UnityTestResultsFailBegin(lineNumber); + if (num_elements > 1) { + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(j); + } + UnityPrintExpectedAndActualStrings(expd, act); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + } while (++j < num_elements); } /*-----------------------------------------------*/ void UnityAssertEqualMemory(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 length, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 length, + const UNITY_UINT32 num_elements, const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags) { - UNITY_PTR_ATTRIBUTE const unsigned char* ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; - UNITY_PTR_ATTRIBUTE const unsigned char* ptr_act = (UNITY_PTR_ATTRIBUTE const unsigned char*)actual; - UNITY_UINT32 elements = num_elements; - UNITY_UINT32 bytes; - - RETURN_IF_FAIL_OR_IGNORE; - - if ((elements == 0) || (length == 0)) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - bytes = length; - while (bytes--) - { - if (*ptr_exp != *ptr_act) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrMemory); - if (num_elements > 1) - { - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - } - UnityPrint(UnityStrByte); - UnityPrintNumberUnsigned(length - bytes - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(*ptr_exp, UNITY_DISPLAY_STYLE_HEX8); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(*ptr_act, UNITY_DISPLAY_STYLE_HEX8); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - ptr_exp++; - ptr_act++; - } - if (flags == UNITY_ARRAY_TO_VAL) - { - ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; - } - } + UNITY_PTR_ATTRIBUTE const unsigned char *ptr_exp = + (UNITY_PTR_ATTRIBUTE const unsigned char *)expected; + UNITY_PTR_ATTRIBUTE const unsigned char *ptr_act = + (UNITY_PTR_ATTRIBUTE const unsigned char *)actual; + UNITY_UINT32 elements = num_elements; + UNITY_UINT32 bytes; + + RETURN_IF_FAIL_OR_IGNORE; + + if ((elements == 0) || (length == 0)) { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) { + UNITY_FAIL_AND_BAIL; + } + + while (elements--) { + bytes = length; + while (bytes--) { + if (*ptr_exp != *ptr_act) { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrMemory); + if (num_elements > 1) { + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - + elements - 1); + } + UnityPrint(UnityStrByte); + UnityPrintNumberUnsigned(length - bytes - 1); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle( + *ptr_exp, UNITY_DISPLAY_STYLE_HEX8); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle( + *ptr_act, UNITY_DISPLAY_STYLE_HEX8); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + ptr_exp++; + ptr_act++; + } + if (flags == UNITY_ARRAY_TO_VAL) { + ptr_exp = + (UNITY_PTR_ATTRIBUTE const unsigned char *)expected; + } + } } /*-----------------------------------------------*/ -static union -{ - UNITY_INT8 i8; - UNITY_INT16 i16; - UNITY_INT32 i32; +static union { + UNITY_INT8 i8; + UNITY_INT16 i16; + UNITY_INT32 i32; #ifdef UNITY_SUPPORT_64 - UNITY_INT64 i64; + UNITY_INT64 i64; #endif #ifndef UNITY_EXCLUDE_FLOAT - float f; + float f; #endif #ifndef UNITY_EXCLUDE_DOUBLE - double d; + double d; #endif } UnityQuickCompare; UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size) { - switch(size) - { - case 1: - UnityQuickCompare.i8 = (UNITY_INT8)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8); + switch (size) { + case 1: + UnityQuickCompare.i8 = (UNITY_INT8)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8); - case 2: - UnityQuickCompare.i16 = (UNITY_INT16)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16); + case 2: + UnityQuickCompare.i16 = (UNITY_INT16)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16); #ifdef UNITY_SUPPORT_64 - case 8: - UnityQuickCompare.i64 = (UNITY_INT64)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64); + case 8: + UnityQuickCompare.i64 = (UNITY_INT64)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64); #endif - default: /* 4 bytes */ - UnityQuickCompare.i32 = (UNITY_INT32)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32); - } + default: /* 4 bytes */ + UnityQuickCompare.i32 = (UNITY_INT32)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32); + } } #ifndef UNITY_EXCLUDE_FLOAT /*-----------------------------------------------*/ UNITY_INTERNAL_PTR UnityFloatToPtr(const float num) { - UnityQuickCompare.f = num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.f); + UnityQuickCompare.f = num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.f); } #endif @@ -1617,8 +1550,8 @@ UNITY_INTERNAL_PTR UnityFloatToPtr(const float num) /*-----------------------------------------------*/ UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num) { - UnityQuickCompare.d = num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.d); + UnityQuickCompare.d = num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.d); } #endif @@ -1626,274 +1559,261 @@ UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num) * printf helper function *-----------------------------------------------*/ #ifdef UNITY_INCLUDE_PRINT_FORMATTED -static void UnityPrintFVA(const char* format, va_list va) +static void UnityPrintFVA(const char *format, va_list va) { - const char* pch = format; - if (pch != NULL) - { - while (*pch) - { - /* format identification character */ - if (*pch == '%') - { - pch++; - - if (pch != NULL) - { - switch (*pch) - { - case 'd': - case 'i': - { - const int number = va_arg(va, int); - UnityPrintNumber((UNITY_INT)number); - break; - } + const char *pch = format; + if (pch != NULL) { + while (*pch) { + /* format identification character */ + if (*pch == '%') { + pch++; + + if (pch != NULL) { + switch (*pch) { + case 'd': + case 'i': { + const int number = + va_arg(va, int); + UnityPrintNumber( + (UNITY_INT)number); + break; + } #ifndef UNITY_EXCLUDE_FLOAT_PRINT - case 'f': - case 'g': - { - const double number = va_arg(va, double); - UnityPrintFloat((UNITY_DOUBLE)number); - break; - } + case 'f': + case 'g': { + const double number = + va_arg(va, double); + UnityPrintFloat( + (UNITY_DOUBLE)number); + break; + } #endif - case 'u': - { - const unsigned int number = va_arg(va, unsigned int); - UnityPrintNumberUnsigned((UNITY_UINT)number); - break; - } - case 'b': - { - const unsigned int number = va_arg(va, unsigned int); - const UNITY_UINT mask = (UNITY_UINT)0 - (UNITY_UINT)1; - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('b'); - UnityPrintMask(mask, (UNITY_UINT)number); - break; - } - case 'x': - case 'X': - case 'p': - { - const unsigned int number = va_arg(va, unsigned int); - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, 8); - break; - } - case 'c': - { - const int ch = va_arg(va, int); - UnityPrintChar((const char *)&ch); - break; - } - case 's': - { - const char * string = va_arg(va, const char *); - UnityPrint(string); - break; - } - case '%': - { - UnityPrintChar(pch); - break; - } - default: - { - /* print the unknown format character */ - UNITY_OUTPUT_CHAR('%'); - UnityPrintChar(pch); - break; - } - } - } - } + case 'u': { + const unsigned int number = + va_arg(va, unsigned int); + UnityPrintNumberUnsigned( + (UNITY_UINT)number); + break; + } + case 'b': { + const unsigned int number = + va_arg(va, unsigned int); + const UNITY_UINT mask = + (UNITY_UINT)0 - + (UNITY_UINT)1; + UNITY_OUTPUT_CHAR('0'); + UNITY_OUTPUT_CHAR('b'); + UnityPrintMask( + mask, (UNITY_UINT)number); + break; + } + case 'x': + case 'X': + case 'p': { + const unsigned int number = + va_arg(va, unsigned int); + UNITY_OUTPUT_CHAR('0'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex( + (UNITY_UINT)number, 8); + break; + } + case 'c': { + const int ch = va_arg(va, int); + UnityPrintChar( + (const char *)&ch); + break; + } + case 's': { + const char *string = + va_arg(va, const char *); + UnityPrint(string); + break; + } + case '%': { + UnityPrintChar(pch); + break; + } + default: { + /* print the unknown format + * character */ + UNITY_OUTPUT_CHAR('%'); + UnityPrintChar(pch); + break; + } + } + } + } #ifdef UNITY_OUTPUT_COLOR - /* print ANSI escape code */ - else if ((*pch == 27) && (*(pch + 1) == '[')) - { - pch += UnityPrintAnsiEscapeString(pch); - continue; - } + /* print ANSI escape code */ + else if ((*pch == 27) && (*(pch + 1) == '[')) { + pch += UnityPrintAnsiEscapeString(pch); + continue; + } #endif - else if (*pch == '\n') - { - UNITY_PRINT_EOL(); - } - else - { - UnityPrintChar(pch); - } - - pch++; - } - } + else if (*pch == '\n') { + UNITY_PRINT_EOL(); + } else { + UnityPrintChar(pch); + } + + pch++; + } + } } -void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...) +void UnityPrintF(const UNITY_LINE_TYPE line, const char *format, ...) { - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint("INFO"); - if(format != NULL) - { - UnityPrint(": "); - va_list va; - va_start(va, format); - UnityPrintFVA(format, va); - va_end(va); - } - UNITY_PRINT_EOL(); + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint("INFO"); + if (format != NULL) { + UnityPrint(": "); + va_list va; + va_start(va, format); + UnityPrintFVA(format, va); + va_end(va); + } + UNITY_PRINT_EOL(); } #endif /* ! UNITY_INCLUDE_PRINT_FORMATTED */ - /*----------------------------------------------- * Control Functions *-----------------------------------------------*/ /*-----------------------------------------------*/ -void UnityFail(const char* msg, const UNITY_LINE_TYPE line) +void UnityFail(const char *msg, const UNITY_LINE_TYPE line) { - RETURN_IF_FAIL_OR_IGNORE; + RETURN_IF_FAIL_OR_IGNORE; - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrFail); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint(UnityStrFail); + if (msg != NULL) { + UNITY_OUTPUT_CHAR(':'); #ifdef UNITY_PRINT_TEST_CONTEXT - UNITY_PRINT_TEST_CONTEXT(); + UNITY_PRINT_TEST_CONTEXT(); #endif #ifndef UNITY_EXCLUDE_DETAILS - if (Unity.CurrentDetail1) - { - UnityPrint(UnityStrDetail1Name); - UnityPrint(Unity.CurrentDetail1); - if (Unity.CurrentDetail2) - { - UnityPrint(UnityStrDetail2Name); - UnityPrint(Unity.CurrentDetail2); - } - UnityPrint(UnityStrSpacer); - } + if (Unity.CurrentDetail1) { + UnityPrint(UnityStrDetail1Name); + UnityPrint(Unity.CurrentDetail1); + if (Unity.CurrentDetail2) { + UnityPrint(UnityStrDetail2Name); + UnityPrint(Unity.CurrentDetail2); + } + UnityPrint(UnityStrSpacer); + } #endif - if (msg[0] != ' ') - { - UNITY_OUTPUT_CHAR(' '); - } - UnityPrint(msg); - } - - UNITY_FAIL_AND_BAIL; + if (msg[0] != ' ') { + UNITY_OUTPUT_CHAR(' '); + } + UnityPrint(msg); + } + + UNITY_FAIL_AND_BAIL; } /*-----------------------------------------------*/ -void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line) +void UnityIgnore(const char *msg, const UNITY_LINE_TYPE line) { - RETURN_IF_FAIL_OR_IGNORE; - - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrIgnore); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(msg); - } - UNITY_IGNORE_AND_BAIL; + RETURN_IF_FAIL_OR_IGNORE; + + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint(UnityStrIgnore); + if (msg != NULL) { + UNITY_OUTPUT_CHAR(':'); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(msg); + } + UNITY_IGNORE_AND_BAIL; } /*-----------------------------------------------*/ -void UnityMessage(const char* msg, const UNITY_LINE_TYPE line) +void UnityMessage(const char *msg, const UNITY_LINE_TYPE line) { - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint("INFO"); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(msg); - } - UNITY_PRINT_EOL(); + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint("INFO"); + if (msg != NULL) { + UNITY_OUTPUT_CHAR(':'); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(msg); + } + UNITY_PRINT_EOL(); } /*-----------------------------------------------*/ -/* If we have not defined our own test runner, then include our default test runner to make life easier */ +/* If we have not defined our own test runner, then include our default test + * runner to make life easier */ #ifndef UNITY_SKIP_DEFAULT_RUNNER -void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum) +void UnityDefaultTestRun(UnityTestFunction Func, const char *FuncName, + const int FuncLineNum) { - Unity.CurrentTestName = FuncName; - Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)FuncLineNum; - Unity.NumberOfTests++; - UNITY_CLR_DETAILS(); - UNITY_EXEC_TIME_START(); - if (TEST_PROTECT()) - { - setUp(); - Func(); - } - if (TEST_PROTECT()) - { - tearDown(); - } - UNITY_EXEC_TIME_STOP(); - UnityConcludeTest(); + Unity.CurrentTestName = FuncName; + Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)FuncLineNum; + Unity.NumberOfTests++; + UNITY_CLR_DETAILS(); + UNITY_EXEC_TIME_START(); + if (TEST_PROTECT()) { + setUp(); + Func(); + } + if (TEST_PROTECT()) { + tearDown(); + } + UNITY_EXEC_TIME_STOP(); + UnityConcludeTest(); } #endif /*-----------------------------------------------*/ -void UnitySetTestFile(const char* filename) +void UnitySetTestFile(const char *filename) { Unity.TestFile = filename; } /*-----------------------------------------------*/ -void UnityBegin(const char* filename) +void UnityBegin(const char *filename) { - Unity.TestFile = filename; - Unity.CurrentTestName = NULL; - Unity.CurrentTestLineNumber = 0; - Unity.NumberOfTests = 0; - Unity.TestFailures = 0; - Unity.TestIgnores = 0; - Unity.CurrentTestFailed = 0; - Unity.CurrentTestIgnored = 0; - - UNITY_CLR_DETAILS(); - UNITY_OUTPUT_START(); + Unity.TestFile = filename; + Unity.CurrentTestName = NULL; + Unity.CurrentTestLineNumber = 0; + Unity.NumberOfTests = 0; + Unity.TestFailures = 0; + Unity.TestIgnores = 0; + Unity.CurrentTestFailed = 0; + Unity.CurrentTestIgnored = 0; + + UNITY_CLR_DETAILS(); + UNITY_OUTPUT_START(); } /*-----------------------------------------------*/ int UnityEnd(void) { - UNITY_PRINT_EOL(); - UnityPrint(UnityStrBreaker); - UNITY_PRINT_EOL(); - UnityPrintNumber((UNITY_INT)(Unity.NumberOfTests)); - UnityPrint(UnityStrResultsTests); - UnityPrintNumber((UNITY_INT)(Unity.TestFailures)); - UnityPrint(UnityStrResultsFailures); - UnityPrintNumber((UNITY_INT)(Unity.TestIgnores)); - UnityPrint(UnityStrResultsIgnored); - UNITY_PRINT_EOL(); - if (Unity.TestFailures == 0U) - { - UnityPrint(UnityStrOk); - } - else - { - UnityPrint(UnityStrFail); + UNITY_PRINT_EOL(); + UnityPrint(UnityStrBreaker); + UNITY_PRINT_EOL(); + UnityPrintNumber((UNITY_INT)(Unity.NumberOfTests)); + UnityPrint(UnityStrResultsTests); + UnityPrintNumber((UNITY_INT)(Unity.TestFailures)); + UnityPrint(UnityStrResultsFailures); + UnityPrintNumber((UNITY_INT)(Unity.TestIgnores)); + UnityPrint(UnityStrResultsIgnored); + UNITY_PRINT_EOL(); + if (Unity.TestFailures == 0U) { + UnityPrint(UnityStrOk); + } else { + UnityPrint(UnityStrFail); #ifdef UNITY_DIFFERENTIATE_FINAL_FAIL - UNITY_OUTPUT_CHAR('E'); UNITY_OUTPUT_CHAR('D'); + UNITY_OUTPUT_CHAR('E'); + UNITY_OUTPUT_CHAR('D'); #endif - } - UNITY_PRINT_EOL(); - UNITY_FLUSH_CALL(); - UNITY_OUTPUT_COMPLETE(); - return (int)(Unity.TestFailures); + } + UNITY_PRINT_EOL(); + UNITY_FLUSH_CALL(); + UNITY_OUTPUT_COMPLETE(); + return (int)(Unity.TestFailures); } /*----------------------------------------------- @@ -1901,208 +1821,191 @@ int UnityEnd(void) *-----------------------------------------------*/ #ifdef UNITY_USE_COMMAND_LINE_ARGS -char* UnityOptionIncludeNamed = NULL; -char* UnityOptionExcludeNamed = NULL; -int UnityVerbosity = 1; +char *UnityOptionIncludeNamed = NULL; +char *UnityOptionExcludeNamed = NULL; +int UnityVerbosity = 1; /*-----------------------------------------------*/ -int UnityParseOptions(int argc, char** argv) +int UnityParseOptions(int argc, char **argv) { - int i; - UnityOptionIncludeNamed = NULL; - UnityOptionExcludeNamed = NULL; - - for (i = 1; i < argc; i++) - { - if (argv[i][0] == '-') - { - switch (argv[i][1]) - { - case 'l': /* list tests */ - return -1; - case 'n': /* include tests with name including this string */ - case 'f': /* an alias for -n */ - if (argv[i][2] == '=') - { - UnityOptionIncludeNamed = &argv[i][3]; - } - else if (++i < argc) - { - UnityOptionIncludeNamed = argv[i]; - } - else - { - UnityPrint("ERROR: No Test String to Include Matches For"); - UNITY_PRINT_EOL(); - return 1; - } - break; - case 'q': /* quiet */ - UnityVerbosity = 0; - break; - case 'v': /* verbose */ - UnityVerbosity = 2; - break; - case 'x': /* exclude tests with name including this string */ - if (argv[i][2] == '=') - { - UnityOptionExcludeNamed = &argv[i][3]; - } - else if (++i < argc) - { - UnityOptionExcludeNamed = argv[i]; - } - else - { - UnityPrint("ERROR: No Test String to Exclude Matches For"); - UNITY_PRINT_EOL(); - return 1; - } - break; - default: - UnityPrint("ERROR: Unknown Option "); - UNITY_OUTPUT_CHAR(argv[i][1]); - UNITY_PRINT_EOL(); - return 1; - } - } - } - - return 0; + int i; + UnityOptionIncludeNamed = NULL; + UnityOptionExcludeNamed = NULL; + + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + switch (argv[i][1]) { + case 'l': /* list tests */ + return -1; + case 'n': /* include tests with name including this + string */ + case 'f': /* an alias for -n */ + if (argv[i][2] == '=') { + UnityOptionIncludeNamed = &argv[i][3]; + } else if (++i < argc) { + UnityOptionIncludeNamed = argv[i]; + } else { + UnityPrint("ERROR: No Test String to " + "Include Matches For"); + UNITY_PRINT_EOL(); + return 1; + } + break; + case 'q': /* quiet */ + UnityVerbosity = 0; + break; + case 'v': /* verbose */ + UnityVerbosity = 2; + break; + case 'x': /* exclude tests with name including this + string */ + if (argv[i][2] == '=') { + UnityOptionExcludeNamed = &argv[i][3]; + } else if (++i < argc) { + UnityOptionExcludeNamed = argv[i]; + } else { + UnityPrint("ERROR: No Test String to " + "Exclude Matches For"); + UNITY_PRINT_EOL(); + return 1; + } + break; + default: + UnityPrint("ERROR: Unknown Option "); + UNITY_OUTPUT_CHAR(argv[i][1]); + UNITY_PRINT_EOL(); + return 1; + } + } + } + + return 0; } /*-----------------------------------------------*/ -int IsStringInBiggerString(const char* longstring, const char* shortstring) +int IsStringInBiggerString(const char *longstring, const char *shortstring) { - const char* lptr = longstring; - const char* sptr = shortstring; - const char* lnext = lptr; - - if (*sptr == '*') - { - return 1; - } - - while (*lptr) - { - lnext = lptr + 1; - - /* If they current bytes match, go on to the next bytes */ - while (*lptr && *sptr && (*lptr == *sptr)) - { - lptr++; - sptr++; - - /* We're done if we match the entire string or up to a wildcard */ - if (*sptr == '*') - return 1; - if (*sptr == ',') - return 1; - if (*sptr == '"') - return 1; - if (*sptr == '\'') - return 1; - if (*sptr == ':') - return 2; - if (*sptr == 0) - return 1; - } - - /* Otherwise we start in the long pointer 1 character further and try again */ - lptr = lnext; - sptr = shortstring; - } - - return 0; + const char *lptr = longstring; + const char *sptr = shortstring; + const char *lnext = lptr; + + if (*sptr == '*') { + return 1; + } + + while (*lptr) { + lnext = lptr + 1; + + /* If they current bytes match, go on to the next bytes */ + while (*lptr && *sptr && (*lptr == *sptr)) { + lptr++; + sptr++; + + /* We're done if we match the entire string or up to a + * wildcard */ + if (*sptr == '*') + return 1; + if (*sptr == ',') + return 1; + if (*sptr == '"') + return 1; + if (*sptr == '\'') + return 1; + if (*sptr == ':') + return 2; + if (*sptr == 0) + return 1; + } + + /* Otherwise we start in the long pointer 1 character further + * and try again */ + lptr = lnext; + sptr = shortstring; + } + + return 0; } /*-----------------------------------------------*/ -int UnityStringArgumentMatches(const char* str) +int UnityStringArgumentMatches(const char *str) { - int retval; - const char* ptr1; - const char* ptr2; - const char* ptrf; - - /* Go through the options and get the substrings for matching one at a time */ - ptr1 = str; - while (ptr1[0] != 0) - { - if ((ptr1[0] == '"') || (ptr1[0] == '\'')) - { - ptr1++; - } - - /* look for the start of the next partial */ - ptr2 = ptr1; - ptrf = 0; - do - { - ptr2++; - if ((ptr2[0] == ':') && (ptr2[1] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')) - { - ptrf = &ptr2[1]; - } - } while ((ptr2[0] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')); - - while ((ptr2[0] != 0) && ((ptr2[0] == ':') || (ptr2[0] == '\'') || (ptr2[0] == '"') || (ptr2[0] == ','))) - { - ptr2++; - } - - /* done if complete filename match */ - retval = IsStringInBiggerString(Unity.TestFile, ptr1); - if (retval == 1) - { - return retval; - } - - /* done if testname match after filename partial match */ - if ((retval == 2) && (ptrf != 0)) - { - if (IsStringInBiggerString(Unity.CurrentTestName, ptrf)) - { - return 1; - } - } - - /* done if complete testname match */ - if (IsStringInBiggerString(Unity.CurrentTestName, ptr1) == 1) - { - return 1; - } - - ptr1 = ptr2; - } - - /* we couldn't find a match for any substrings */ - return 0; + int retval; + const char *ptr1; + const char *ptr2; + const char *ptrf; + + /* Go through the options and get the substrings for matching one at a + * time */ + ptr1 = str; + while (ptr1[0] != 0) { + if ((ptr1[0] == '"') || (ptr1[0] == '\'')) { + ptr1++; + } + + /* look for the start of the next partial */ + ptr2 = ptr1; + ptrf = 0; + do { + ptr2++; + if ((ptr2[0] == ':') && (ptr2[1] != 0) && + (ptr2[0] != '\'') && (ptr2[0] != '"') && + (ptr2[0] != ',')) { + ptrf = &ptr2[1]; + } + } while ((ptr2[0] != 0) && (ptr2[0] != '\'') && + (ptr2[0] != '"') && (ptr2[0] != ',')); + + while ((ptr2[0] != 0) && + ((ptr2[0] == ':') || (ptr2[0] == '\'') || + (ptr2[0] == '"') || (ptr2[0] == ','))) { + ptr2++; + } + + /* done if complete filename match */ + retval = IsStringInBiggerString(Unity.TestFile, ptr1); + if (retval == 1) { + return retval; + } + + /* done if testname match after filename partial match */ + if ((retval == 2) && (ptrf != 0)) { + if (IsStringInBiggerString(Unity.CurrentTestName, + ptrf)) { + return 1; + } + } + + /* done if complete testname match */ + if (IsStringInBiggerString(Unity.CurrentTestName, ptr1) == 1) { + return 1; + } + + ptr1 = ptr2; + } + + /* we couldn't find a match for any substrings */ + return 0; } /*-----------------------------------------------*/ int UnityTestMatches(void) { - /* Check if this test name matches the included test pattern */ - int retval; - if (UnityOptionIncludeNamed) - { - retval = UnityStringArgumentMatches(UnityOptionIncludeNamed); - } - else - { - retval = 1; - } - - /* Check if this test name matches the excluded test pattern */ - if (UnityOptionExcludeNamed) - { - if (UnityStringArgumentMatches(UnityOptionExcludeNamed)) - { - retval = 0; - } - } - - return retval; + /* Check if this test name matches the included test pattern */ + int retval; + if (UnityOptionIncludeNamed) { + retval = UnityStringArgumentMatches(UnityOptionIncludeNamed); + } else { + retval = 1; + } + + /* Check if this test name matches the excluded test pattern */ + if (UnityOptionExcludeNamed) { + if (UnityStringArgumentMatches(UnityOptionExcludeNamed)) { + retval = 0; + } + } + + return retval; } #endif /* UNITY_USE_COMMAND_LINE_ARGS */ diff --git a/utils/clear_tpm_nv.sh b/utils/clear_tpm_nv.sh new file mode 100755 index 00000000..92faf761 --- /dev/null +++ b/utils/clear_tpm_nv.sh @@ -0,0 +1,35 @@ +#!/bin/bash +TPM_DEVICE_KEY_PERSISTANT_HANDLE=0x81020002 + +execute_cmd_on_failure_exit() +{ + eval exec_cmd="$1" + eval success_msg="$2" + eval failure_msg="$3" + + echo -e "\e[2;33mExecuting :\e[0m ${exec_cmd}" + out=$(eval ${exec_cmd}" 2>&1") + if [ `echo $?` != 0 ]; then + echo -e "\e[2;31m${failure_msg}\e[0m" + else + echo -e "\e[2;32m${success_msg}\e[0m" + fi + + return 0 +} + +task="Delete keys if exists from persistance memory" +cmd="tpm2_evictcontrol -C o -c $TPM_DEVICE_KEY_PERSISTANT_HANDLE -V" +success_string="$task completed successfully at $TPM_DEVICE_KEY_PERSISTANT_HANDLE !!" +failure_string="$task failed [probably ignore it]" +execute_cmd_on_failure_exit "\$cmd" "\$success_string" "\$failure_string" + +for n in {0,1,5}; +do + task="Deleting a Non-Volatile (NV) index at 0x01D1000$n" + cmd="tpm2_nvundefine 0x01D1000$n" + success_string="$task completed successfully!!" + failure_string="Non-Volatile (NV) index at 0x01D1000$n is not defined!!" + execute_cmd_on_failure_exit "\$cmd" "\$success_string" "\$failure_string" +done +echo "TPM NV storage cleared!" diff --git a/utils/install_openssl_curl.sh b/utils/install_openssl_curl.sh old mode 100644 new mode 100755 index 0e2bafcb..8e67f519 --- a/utils/install_openssl_curl.sh +++ b/utils/install_openssl_curl.sh @@ -1,13 +1,15 @@ -CURL_VER="7.88.0" -CURL_LINK="https://github.com/curl/curl/releases/download/curl-7_88_0/curl-7.88.0.tar.gz --no-check-certificate" +OPENSSL_ROOT=/opt/openssl +CURL_ROOT=/opt/curl +CURL_VER="8.8.0" +CURL_LINK="https://curl.se/download/curl-8.8.0.tar.gz --no-check-certificate" PARENT_DIR=`pwd` cd $PARENT_DIR -install() -{ +install() +{ OPENSSL_LINK="https://www.openssl.org/source/openssl-$OPENSSL_VER.tar.gz --no-check-certificate" echo "Build & Install OpenSSL version : $OPENSSL_VER" cd $PARENT_DIR @@ -16,31 +18,25 @@ install() tar -xvzf openssl-$OPENSSL_VER.tar.gz cd openssl-$OPENSSL_VER - ./config --libdir=/usr/local/lib + ./config --prefix=$OPENSSL_ROOT --openssldir=/usr/local/ssl make -j$(nproc) - mv /usr/bin/openssl ~/tmp make install - - ln -s /usr/local/bin/openssl /usr/bin/openssl - grep -qxF '/usr/local/lib/' /etc/ld.so.conf.d/libc.conf || echo /usr/local/lib/ | sudo tee -a /etc/ld.so.conf.d/libc.conf + + grep -qxF '$OPENSSL_ROOT/lib64/' /etc/ld.so.conf.d/libc.conf || echo $OPENSSL_ROOT/lib64/ | sudo tee -a /etc/ld.so.conf.d/libc.conf ldconfig - openssl version - + echo "Build & Install Curl version : $CURL_VER" cd $PARENT_DIR wget $CURL_LINK tar -xvzf curl-$CURL_VER.tar.gz cd curl-$CURL_VER - ./configure --with-openssl=$PARENT_DIR/openssl-$OPENSSL_VER --enable-versioned-symbols + ./configure --prefix=$CURL_ROOT --with-openssl=$OPENSSL_ROOT --with-nghttp2 --enable-versioned-symbols --without-libpsl make -j$(nproc) make install - - ldconfig - openssl version - curl --version - - + + $OPENSSL_ROOT/bin/openssl version + $CURL_ROOT/bin/curl -V } @@ -48,7 +44,7 @@ uninstall() { OPENSSL_LINK="https://www.openssl.org/source/openssl-$OPENSSL_VER.tar.gz --no-check-certificate" echo "Uninstall OpenSSL version : $OPENSSL_VER" - + cd $PARENT_DIR rm -f openssl-$OPENSSL_VER.tar.gz wget $OPENSSL_LINK @@ -70,8 +66,8 @@ usage() ./$0