Просмотр исходного кода

Merge branch 'feature/c3_ds' into 'master'

ESP32-C3 Digital Signature, HAL layer for DS.

Closes IDF-2111

See merge request espressif/esp-idf!10813
Angus Gratton 5 лет назад
Родитель
Сommit
5b68cf9de4

+ 1 - 0
components/esp32c3/CMakeLists.txt

@@ -16,6 +16,7 @@ else()
              "crosscore_int.c"
              "dport_access.c"
              "esp_hmac.c"
+             "esp_ds.c"
              "esp_crypto_lock.c"
              "hw_random.c"
              "system_api_esp32c3.c")

+ 229 - 0
components/esp32c3/esp_ds.c

@@ -0,0 +1,229 @@
+// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "freertos/FreeRTOS.h"
+#include "freertos/task.h"
+#include "driver/periph_ctrl.h"
+#include "esp_crypto_lock.h"
+#include "hal/ds_hal.h"
+#include "hal/hmac_hal.h"
+#include "esp32c3/rom/digital_signature.h"
+
+#include "esp_ds.h"
+
+struct esp_ds_context {
+    const esp_ds_data_t *data;
+};
+
+/**
+ * The vtask delay \c esp_ds_sign() is using while waiting for completion of the signing operation.
+ */
+#define ESP_DS_SIGN_TASK_DELAY_MS 10
+
+#define RSA_LEN_MAX 127
+
+/*
+ * esp_digital_signature_length_t is used in esp_ds_data_t in contrast to ets_ds_data_t, where unsigned is used.
+ * Check esp_digital_signature_length_t's width here because it's converted to unsigned using raw casts.
+ */
+_Static_assert(sizeof(esp_digital_signature_length_t) == sizeof(unsigned),
+        "The size of esp_digital_signature_length_t and unsigned has to be the same");
+
+/*
+ * esp_ds_data_t is used in the encryption function but casted to ets_ds_data_t.
+ * Check esp_ds_data_t's width here because it's converted using raw casts.
+ */
+_Static_assert(sizeof(esp_ds_data_t) == sizeof(ets_ds_data_t),
+        "The size of esp_ds_data_t and ets_ds_data_t has to be the same");
+
+static void ds_acquire_enable(void)
+{
+    esp_crypto_ds_lock_acquire();
+
+    // We also enable SHA and HMAC here. SHA is used by HMAC, HMAC is used by DS.
+    periph_module_enable(PERIPH_HMAC_MODULE);
+    periph_module_enable(PERIPH_SHA_MODULE);
+    periph_module_enable(PERIPH_DS_MODULE);
+
+    hmac_hal_start();
+}
+
+static void ds_disable_release(void)
+{
+    ds_hal_finish();
+
+    periph_module_disable(PERIPH_DS_MODULE);
+    periph_module_disable(PERIPH_SHA_MODULE);
+    periph_module_disable(PERIPH_HMAC_MODULE);
+
+    esp_crypto_ds_lock_release();
+}
+
+esp_err_t esp_ds_sign(const void *message,
+        const esp_ds_data_t *data,
+        hmac_key_id_t key_id,
+        void *signature)
+{
+    // Need to check signature here, otherwise the signature is only checked when the signing has finished and fails
+    // but the signing isn't uninitialized and the mutex is still locked.
+    if (!signature) {
+        return ESP_ERR_INVALID_ARG;
+    }
+
+    esp_ds_context_t *context;
+    esp_err_t result = esp_ds_start_sign(message, data, key_id, &context);
+    if (result != ESP_OK) {
+        return result;
+    }
+
+    while (esp_ds_is_busy())
+        vTaskDelay(ESP_DS_SIGN_TASK_DELAY_MS / portTICK_PERIOD_MS);
+
+    return esp_ds_finish_sign(signature, context);
+}
+
+esp_err_t esp_ds_start_sign(const void *message,
+        const esp_ds_data_t *data,
+        hmac_key_id_t key_id,
+        esp_ds_context_t **esp_ds_ctx)
+{
+    if (!message || !data || !esp_ds_ctx) {
+        return ESP_ERR_INVALID_ARG;
+    }
+
+    if (key_id >= HMAC_KEY_MAX) {
+        return ESP_ERR_INVALID_ARG;
+    }
+
+    if (!(data->rsa_length == ESP_DS_RSA_1024
+            || data->rsa_length == ESP_DS_RSA_2048
+            || data->rsa_length == ESP_DS_RSA_3072)) {
+        return ESP_ERR_INVALID_ARG;
+    }
+
+    ds_acquire_enable();
+
+    // initiate hmac
+    uint32_t conf_error = hmac_hal_configure(HMAC_OUTPUT_DS, key_id);
+    if (conf_error) {
+        ds_disable_release();
+        return ESP32C3_ERR_HW_CRYPTO_DS_HMAC_FAIL;
+    }
+
+    ds_hal_start();
+
+    // check encryption key from HMAC
+    ds_key_check_t key_check_result = ds_hal_check_decryption_key();
+    if (key_check_result != DS_KEY_INPUT_OK) {
+        ds_disable_release();
+        return ESP32C3_ERR_HW_CRYPTO_DS_INVALID_KEY;
+    }
+
+    esp_ds_context_t *context = malloc(sizeof(esp_ds_context_t));
+    if (!context) {
+        ds_disable_release();
+        return ESP_ERR_NO_MEM;
+    }
+
+    size_t rsa_len = (data->rsa_length + 1) * 4;
+    ds_hal_write_private_key_params(data->c);
+    ds_hal_configure_iv(data->iv);
+    ds_hal_write_message(message, rsa_len);
+
+    // initiate signing
+    ds_hal_start_sign();
+
+    context->data = data;
+    *esp_ds_ctx = context;
+
+    return ESP_OK;
+}
+
+bool esp_ds_is_busy(void)
+{
+    return ds_hal_busy();
+}
+
+esp_err_t esp_ds_finish_sign(void *signature, esp_ds_context_t *esp_ds_ctx)
+{
+    if (!signature || !esp_ds_ctx) {
+        return ESP_ERR_INVALID_ARG;
+    }
+
+    const esp_ds_data_t *data = esp_ds_ctx->data;
+    unsigned rsa_len = (data->rsa_length + 1) * 4;
+
+    while (ds_hal_busy()) { }
+
+    ds_signature_check_t sig_check_result = ds_hal_read_result((uint8_t*) signature, (size_t) rsa_len);
+
+    esp_err_t return_value = ESP_OK;
+
+    if (sig_check_result == DS_SIGNATURE_MD_FAIL || sig_check_result == DS_SIGNATURE_PADDING_AND_MD_FAIL) {
+        return_value = ESP32C3_ERR_HW_CRYPTO_DS_INVALID_DIGEST;
+    }
+
+    if (sig_check_result == DS_SIGNATURE_PADDING_FAIL) {
+        return_value = ESP32C3_ERR_HW_CRYPTO_DS_INVALID_PADDING;
+    }
+
+    free(esp_ds_ctx);
+
+    hmac_hal_clean();
+
+    ds_disable_release();
+
+    return return_value;
+}
+
+esp_err_t esp_ds_encrypt_params(esp_ds_data_t *data,
+        const void *iv,
+        const esp_ds_p_data_t *p_data,
+        const void *key)
+{
+    if (!p_data) {
+        return ESP_ERR_INVALID_ARG;
+    }
+
+    esp_err_t result = ESP_OK;
+
+    esp_crypto_ds_lock_acquire();
+    periph_module_enable(PERIPH_AES_MODULE);
+    periph_module_enable(PERIPH_DS_MODULE);
+    periph_module_enable(PERIPH_SHA_MODULE);
+    periph_module_enable(PERIPH_HMAC_MODULE);
+    periph_module_enable(PERIPH_RSA_MODULE);
+
+    ets_ds_data_t *ds_data = (ets_ds_data_t*) data;
+    const ets_ds_p_data_t *ds_plain_data = (const ets_ds_p_data_t*) p_data;
+
+    ets_ds_result_t ets_result = ets_ds_encrypt_params(ds_data, iv, ds_plain_data, key, ETS_DS_KEY_HMAC);
+
+    if (ets_result == ETS_DS_INVALID_PARAM) {
+        result = ESP_ERR_INVALID_ARG;
+    }
+
+    periph_module_disable(PERIPH_RSA_MODULE);
+    periph_module_disable(PERIPH_HMAC_MODULE);
+    periph_module_disable(PERIPH_SHA_MODULE);
+    periph_module_disable(PERIPH_DS_MODULE);
+    periph_module_disable(PERIPH_AES_MODULE);
+    esp_crypto_ds_lock_release();
+
+    return result;
+}

+ 1 - 1
components/esp32c3/esp_hmac.c

@@ -27,7 +27,7 @@
 /**
  * @brief Apply the HMAC padding without the embedded length.
  *
- * @note This function does not check the data length, it is the responsability of the other functions in this
+ * @note This function does not check the data length, it is the responsibility of the other functions in this
  * module to make sure that \c data_len is at most SHA256_BLOCK_SZ - 1 so the padding fits in.
  * Otherwise, this function has undefined behavior.
  * Note however, that for the actual HMAC implementation on ESP32C3, the length also needs to be applied at the end

+ 217 - 0
components/esp32c3/include/esp_ds.h

@@ -0,0 +1,217 @@
+// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+
+#include "esp_hmac.h"
+#include "esp_err.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ESP32C3_ERR_HW_CRYPTO_DS_HMAC_FAIL           ESP_ERR_HW_CRYPTO_BASE + 0x1 /*!< HMAC peripheral problem */
+#define ESP32C3_ERR_HW_CRYPTO_DS_INVALID_KEY         ESP_ERR_HW_CRYPTO_BASE + 0x2 /*!< given HMAC key isn't correct,
+                                                                                HMAC peripheral problem */
+#define ESP32C3_ERR_HW_CRYPTO_DS_INVALID_DIGEST      ESP_ERR_HW_CRYPTO_BASE + 0x4 /*!< message digest check failed,
+                                                                                result is invalid */
+#define ESP32C3_ERR_HW_CRYPTO_DS_INVALID_PADDING     ESP_ERR_HW_CRYPTO_BASE + 0x5 /*!< padding check failed, but result
+                                                                                   is produced anyway and can be read*/
+
+#define ESP_DS_IV_BIT_LEN 128
+#define ESP_DS_SIGNATURE_MAX_BIT_LEN 3072
+#define ESP_DS_SIGNATURE_MD_BIT_LEN 256
+#define ESP_DS_SIGNATURE_M_PRIME_BIT_LEN 32
+#define ESP_DS_SIGNATURE_L_BIT_LEN 32
+#define ESP_DS_SIGNATURE_PADDING_BIT_LEN 64
+
+/* Length of parameter 'C' stored in flash, in bytes
+   - Operands Y, M and r_bar; each 3072 bits
+   - Operand MD (message digest); 256 bits
+   - Operands M' and L; each 32 bits
+   - Operand beta (padding value; 64 bits
+*/
+#define ESP_DS_C_LEN (((ESP_DS_SIGNATURE_MAX_BIT_LEN * 3 \
+        + ESP_DS_SIGNATURE_MD_BIT_LEN   \
+        + ESP_DS_SIGNATURE_M_PRIME_BIT_LEN   \
+        + ESP_DS_SIGNATURE_L_BIT_LEN   \
+        + ESP_DS_SIGNATURE_PADDING_BIT_LEN) / 8))
+
+typedef struct esp_ds_context esp_ds_context_t;
+
+typedef enum {
+    ESP_DS_RSA_1024 = (1024 / 32) - 1,
+    ESP_DS_RSA_2048 = (2048 / 32) - 1,
+    ESP_DS_RSA_3072 = (3072 / 32) - 1
+} esp_digital_signature_length_t;
+
+/**
+ * Encrypted private key data. Recommended to store in flash in this format.
+ *
+ * @note This struct has to match to one from the ROM code! This documentation is mostly taken from there.
+ */
+typedef struct esp_digital_signature_data {
+    /**
+     * RSA LENGTH register parameters
+     * (number of words in RSA key & operands, minus one).
+     *
+     * Max value 127 (for RSA 3072).
+     *
+     * This value must match the length field encrypted and stored in 'c',
+     * or invalid results will be returned. (The DS peripheral will
+     * always use the value in 'c', not this value, so an attacker can't
+     * alter the DS peripheral results this way, it will just truncate or
+     * extend the message and the resulting signature in software.)
+     *
+     * @note In IDF, the enum type length is the same as of type unsigned, so they can be used interchangably.
+     *       See the ROM code for the original declaration of struct \c ets_ds_data_t.
+     */
+    esp_digital_signature_length_t rsa_length;
+
+    /**
+     * IV value used to encrypt 'c'
+     */
+    uint32_t iv[ESP_DS_IV_BIT_LEN / 32];
+
+    /**
+     * Encrypted Digital Signature parameters. Result of AES-CBC encryption
+     * of plaintext values. Includes an encrypted message digest.
+     */
+    uint8_t c[ESP_DS_C_LEN];
+} esp_ds_data_t;
+
+/**
+ * Plaintext parameters used by Digital Signature.
+ *
+ * This is only used for encrypting the RSA parameters by calling esp_ds_encrypt_params().
+ * Afterwards, the result can be stored in flash or in other persistent memory.
+ * The encryption is a prerequisite step before any signature operation can be done.
+ */
+typedef struct {
+    uint32_t  Y[ESP_DS_SIGNATURE_MAX_BIT_LEN / 32]; //!< RSA exponent
+    uint32_t  M[ESP_DS_SIGNATURE_MAX_BIT_LEN / 32]; //!< RSA modulus
+    uint32_t Rb[ESP_DS_SIGNATURE_MAX_BIT_LEN / 32]; //!< RSA r inverse operand
+    uint32_t M_prime;                               //!< RSA M prime operand
+    uint32_t length;                                //!< RSA length in words (32 bit)
+} esp_ds_p_data_t;
+
+/**
+ * @brief Sign the message with a hardware key from specific key slot.
+ *
+ * This function is a wrapper around \c esp_ds_finish_sign() and \c esp_ds_start_sign(), so do not use them
+ * in parallel.
+ * It blocks until the signing is finished and then returns the signature.
+ *
+ * @note This function locks the HMAC, SHA, AES and RSA components during its entire execution time.
+ *
+ * @param message the message to be signed; its length is determined by data->rsa_length
+ * @param data the encrypted signing key data (AES encrypted RSA key + IV)
+ * @param key_id the HMAC key ID determining the HMAC key of the HMAC which will be used to decrypt the
+ *        signing key data
+ * @param signature the destination of the signature, should be (data->rsa_length + 1)*4 bytes long
+ *
+ * @return
+ *      - ESP_OK if successful, the signature was written to the parameter \c signature.
+ *      - ESP_ERR_INVALID_ARG if one of the parameters is NULL or data->rsa_length is too long or 0
+ *      - ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL if there was an HMAC failure during retrieval of the decryption key
+ *      - ESP_ERR_NO_MEM if there hasn't been enough memory to allocate the context object
+ *      - ESP_ERR_HW_CRYPTO_DS_INVALID_KEY if there's a problem with passing the HMAC key to the DS component
+ *      - ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST if the message digest didn't match; the signature is invalid.
+ *      - ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING if the message padding is incorrect, the signature can be read though
+ *        since the message digest matches.
+ */
+esp_err_t esp_ds_sign(const void *message,
+        const esp_ds_data_t *data,
+        hmac_key_id_t key_id,
+        void *signature);
+
+/**
+ * @brief Start the signing process.
+ *
+ * This function yields a context object which needs to be passed to \c esp_ds_finish_sign() to finish the signing
+ * process.
+ *
+ * @note This function locks the HMAC, SHA, AES and RSA components, so the user has to ensure to call
+ *       \c esp_ds_finish_sign() in a timely manner.
+ *
+ * @param message the message to be signed; its length is determined by data->rsa_length
+ * @param data the encrypted signing key data (AES encrypted RSA key + IV)
+ * @param key_id the HMAC key ID determining the HMAC key of the HMAC which will be used to decrypt the
+ *        signing key data
+ * @param esp_ds_ctx the context object which is needed for finishing the signing process later
+ *
+ * @return
+ *      - ESP_OK if successful, the ds operation was started now and has to be finished with \c esp_ds_finish_sign()
+ *      - ESP_ERR_INVALID_ARG if one of the parameters is NULL or data->rsa_length is too long or 0
+ *      - ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL if there was an HMAC failure during retrieval of the decryption key
+ *      - ESP_ERR_NO_MEM if there hasn't been enough memory to allocate the context object
+ *      - ESP_ERR_HW_CRYPTO_DS_INVALID_KEY if there's a problem with passing the HMAC key to the DS component
+ */
+esp_err_t esp_ds_start_sign(const void *message,
+        const esp_ds_data_t *data,
+        hmac_key_id_t key_id,
+        esp_ds_context_t **esp_ds_ctx);
+
+/**
+ * Return true if the DS peripheral is busy, otherwise false.
+ *
+ * @note Only valid if \c esp_ds_start_sign() was called before.
+ */
+bool esp_ds_is_busy(void);
+
+/**
+ * @brief Finish the signing process.
+ *
+ * @param signature the destination of the signature, should be (data->rsa_length + 1)*4 bytes long
+ * @param esp_ds_ctx the context object retreived by \c esp_ds_start_sign()
+ *
+ * @return
+ *      - ESP_OK if successful, the ds operation has been finished and the result is written to signature.
+ *      - ESP_ERR_INVALID_ARG if one of the parameters is NULL
+ *      - ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST if the message digest didn't match; the signature is invalid.
+ *        This means that the encrypted RSA key parameters are invalid, indicating that they may have been tampered
+ *        with or indicating a flash error, etc.
+ *      - ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING if the message padding is incorrect, the signature can be read though
+ *        since the message digest matches (see TRM for more details).
+ */
+esp_err_t esp_ds_finish_sign(void *signature, esp_ds_context_t *esp_ds_ctx);
+
+/**
+ * @brief Encrypt the private key parameters.
+ *
+ * The encryption is a prerequisite step before any signature operation can be done.
+ * It is not strictly necessary to use this encryption function, the encryption could also happen on an external
+ * device.
+ *
+ * @param data Output buffer to store encrypted data, suitable for later use generating signatures.
+ *        The allocated memory must be in internal memory and word aligned since it's filled by DMA. Both is asserted
+ *        at run time.
+ * @param iv Pointer to 16 byte IV buffer, will be copied into 'data'. Should be randomly generated bytes each time.
+ * @param p_data Pointer to input plaintext key data. The expectation is this data will be deleted after this process
+ *        is done and 'data' is stored.
+ * @param key Pointer to 32 bytes of key data. Type determined by key_type parameter. The expectation is the
+ *        corresponding HMAC key will be stored to efuse and then permanently erased.
+ *
+ * @return
+ *      - ESP_OK if successful, the ds operation has been finished and the result is written to signature.
+ *      - ESP_ERR_INVALID_ARG if one of the parameters is NULL or p_data->rsa_length is too long
+ */
+esp_err_t esp_ds_encrypt_params(esp_ds_data_t *data,
+        const void *iv,
+        const esp_ds_p_data_t *p_data,
+        const void *key);
+
+#ifdef __cplusplus
+}
+#endif

+ 1 - 1
components/esp32c3/test/CMakeLists.txt

@@ -1,7 +1,7 @@
 if(IDF_TARGET STREQUAL "esp32c3")
     idf_component_register(SRC_DIRS .
                         INCLUDE_DIRS . ${CMAKE_CURRENT_BINARY_DIR}
-                        REQUIRES unity test_utils esp_common
+                        REQUIRES unity test_utils esp_common mbedtls
                         )
 
     idf_build_set_property(COMPILE_DEFINITIONS "-DESP_TIMER_DYNAMIC_OVERFLOW_VAL" APPEND)

Разница между файлами не показана из-за своего большого размера
+ 49 - 0
components/esp32c3/test/digital_signature_test_cases.h


+ 382 - 0
components/esp32c3/test/test_ds.c

@@ -0,0 +1,382 @@
+// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "unity.h"
+#include "esp32c3/rom/efuse.h"
+#include "esp32c3/rom/digital_signature.h"
+#include "esp32c3/rom/hmac.h"
+#include <string.h>
+
+#include "esp_ds.h"
+
+#define NUM_RESULTS 10
+#define DS_MAX_BITS (ETS_DS_MAX_BITS)
+
+typedef struct {
+    uint8_t iv[ETS_DS_IV_LEN];
+    ets_ds_p_data_t p_data;
+    uint8_t expected_c[ETS_DS_C_LEN];
+    uint8_t hmac_key_idx;
+    uint32_t expected_results[NUM_RESULTS][DS_MAX_BITS/32];
+} encrypt_testcase_t;
+
+// Generated header (components/esp32s2/test/gen_digital_signature_tests.py) defines
+// NUM_HMAC_KEYS, test_hmac_keys, NUM_MESSAGES, NUM_CASES, test_messages[], test_cases[]
+#include "digital_signature_test_cases.h"
+
+_Static_assert(NUM_RESULTS == NUM_MESSAGES, "expected_results size should be the same as NUM_MESSAGES in generated header");
+
+TEST_CASE("Digital Signature Parameter Encryption data NULL", "[hw_crypto] [ds]")
+{
+    const char iv [32];
+    esp_ds_p_data_t p_data;
+    const char key [32];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_encrypt_params(NULL, iv, &p_data, key));
+}
+
+TEST_CASE("Digital Signature Parameter Encryption iv NULL", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t data;
+    esp_ds_p_data_t p_data;
+    const char key [32];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_encrypt_params(&data, NULL, &p_data, key));
+}
+
+TEST_CASE("Digital Signature Parameter Encryption p_data NULL", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t data;
+    const char iv [32];
+    const char key [32];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_encrypt_params(&data, iv, NULL, key));
+}
+
+TEST_CASE("Digital Signature Parameter Encryption key NULL", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t data;
+    const char iv [32];
+    esp_ds_p_data_t p_data;
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_encrypt_params(&data, iv, &p_data, NULL));
+}
+
+TEST_CASE("Digital Signature Parameter Encryption", "[hw_crypto] [ds]")
+{
+    for (int i = 0; i < NUM_CASES; i++) {
+        printf("Encrypting test case %d...\n", i);
+        const encrypt_testcase_t *t = &test_cases[i];
+        esp_ds_data_t result = { };
+        esp_ds_p_data_t p_data;
+
+        memcpy(p_data.Y,   t->p_data.Y, ESP_DS_SIGNATURE_MAX_BIT_LEN/8);
+        memcpy(p_data.M,   t->p_data.M, ESP_DS_SIGNATURE_MAX_BIT_LEN/8);
+        memcpy(p_data.Rb, t->p_data.Rb, ESP_DS_SIGNATURE_MAX_BIT_LEN/8);
+        p_data.M_prime = t->p_data.M_prime;
+        p_data.length = t->p_data.length;
+
+        esp_err_t r = esp_ds_encrypt_params(&result, t->iv, &p_data,
+                                                  test_hmac_keys[t->hmac_key_idx]);
+        printf("Encrypting test case %d done\n", i);
+
+        TEST_ASSERT_EQUAL(ESP_OK, r);
+        TEST_ASSERT_EQUAL(t->p_data.length, result.rsa_length);
+        TEST_ASSERT_EQUAL_HEX8_ARRAY(t->iv, result.iv, ETS_DS_IV_LEN);
+        TEST_ASSERT_EQUAL_HEX8_ARRAY(t->expected_c, result.c, ETS_DS_C_LEN);
+    }
+}
+
+TEST_CASE("Digital Signature start Invalid message", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = { };
+    ds_data.rsa_length = ESP_DS_RSA_3072;
+    esp_ds_context_t *ctx;
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_start_sign(NULL, &ds_data, HMAC_KEY1, &ctx));
+}
+
+TEST_CASE("Digital Signature start Invalid data", "[hw_crypto] [ds]")
+{
+    const char *message = "test";
+    esp_ds_context_t *ctx;
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_start_sign(message, NULL, HMAC_KEY1, &ctx));
+}
+
+TEST_CASE("Digital Signature start Invalid context", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = ESP_DS_RSA_3072;
+    const char *message = "test";
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_start_sign(message, &ds_data, HMAC_KEY1, NULL));
+}
+
+TEST_CASE("Digital Signature RSA length 0", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = 0;
+    const char *message = "test";
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_start_sign(message, &ds_data, HMAC_KEY1, NULL));
+}
+
+TEST_CASE("Digital Signature RSA length too long", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = 128;
+    const char *message = "test";
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_start_sign(message, &ds_data, HMAC_KEY1, NULL));
+}
+
+TEST_CASE("Digital Signature start HMAC key out of range", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = ESP_DS_RSA_3072;
+    esp_ds_context_t *ctx;
+    const char *message = "test";
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_start_sign(message, &ds_data, HMAC_KEY5 + 1, &ctx));
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_start_sign(message, &ds_data, HMAC_KEY0 - 1, &ctx));
+}
+
+TEST_CASE("Digital Signature finish Invalid signature ptr", "[hw_crypto] [ds]")
+{
+    esp_ds_context_t *ctx = NULL;
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_finish_sign(NULL, ctx));
+}
+
+TEST_CASE("Digital Signature finish Invalid context", "[hw_crypto] [ds]")
+{
+    uint8_t signature_data [128 * 4];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_finish_sign(signature_data, NULL));
+}
+
+TEST_CASE("Digital Signature Blocking Invalid message", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = { };
+    ds_data.rsa_length = ESP_DS_RSA_3072;
+    uint8_t signature_data [128 * 4];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_sign(NULL, &ds_data, HMAC_KEY1, signature_data));
+}
+
+TEST_CASE("Digital Signature Blocking Invalid data", "[hw_crypto] [ds]")
+{
+    const char *message = "test";
+    uint8_t signature_data [128 * 4];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_sign(message, NULL, HMAC_KEY1, signature_data));
+}
+
+TEST_CASE("Digital Signature Blocking Invalid signature ptr", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = ESP_DS_RSA_3072;
+    const char *message = "test";
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_sign(message, &ds_data, HMAC_KEY1, NULL));
+}
+
+TEST_CASE("Digital Signature Blocking RSA length 0", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = 0;
+    const char *message = "test";
+    uint8_t signature_data [128 * 4];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_sign(message, &ds_data, HMAC_KEY1, signature_data));
+}
+
+TEST_CASE("Digital Signature Blocking RSA length too long", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = 128;
+    const char *message = "test";
+    uint8_t signature_data [128 * 4];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_sign(message, &ds_data, HMAC_KEY1, signature_data));
+}
+
+TEST_CASE("Digital Signature Blocking HMAC key out of range", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = 127;
+    const char *message = "test";
+    uint8_t signature_data [128 * 4];
+
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_sign(message, &ds_data, HMAC_KEY5 + 1, signature_data));
+    TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, esp_ds_sign(message, &ds_data, HMAC_KEY0 - 1, signature_data));
+}
+
+#if CONFIG_IDF_ENV_FPGA
+
+// Burn eFuse blocks 1, 2 and 3. Block 0 is used for HMAC tests already.
+static void burn_hmac_keys(void)
+{
+    printf("Burning %d HMAC keys to efuse...\n", NUM_HMAC_KEYS);
+    for (int i = 0; i < NUM_HMAC_KEYS; i++) {
+        // TODO: vary the purpose across the keys
+        ets_efuse_purpose_t purpose = ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE;
+        ets_efuse_write_key(ETS_EFUSE_BLOCK_KEY1 + i,
+                            purpose,
+                            test_hmac_keys[i], 32);
+    }
+    /* verify the keys are what we expect (possibly they're already burned, doesn't matter but they have to match) */
+    uint8_t block_compare[32];
+    for (int i = 0; i < NUM_HMAC_KEYS; i++) {
+        printf("Checking key %d...\n", i);
+        memcpy(block_compare, (void *)ets_efuse_get_read_register_address(ETS_EFUSE_BLOCK_KEY1 + i), 32);
+        TEST_ASSERT_EQUAL_HEX8_ARRAY(test_hmac_keys[i], block_compare, 32);
+    }
+}
+
+// This test uses the HMAC_KEY0 eFuse key which hasn't been burned by burn_hmac_keys().
+// HMAC_KEY0 is usually used for HMAC upstream (user access) tests.
+TEST_CASE("Digital Signature wrong HMAC key purpose (FPGA only)", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = ESP_DS_RSA_3072;
+    esp_ds_context_t *ctx;
+    const char *message = "test";
+
+    // HMAC fails in that case because it checks for the correct purpose
+    TEST_ASSERT_EQUAL(ESP32C3_ERR_HW_CRYPTO_DS_HMAC_FAIL, esp_ds_start_sign(message, &ds_data, HMAC_KEY0, &ctx));
+}
+
+// This test uses the HMAC_KEY0 eFuse key which hasn't been burned by burn_hmac_keys().
+// HMAC_KEY0 is usually used for HMAC upstream (user access) tests.
+TEST_CASE("Digital Signature Blocking wrong HMAC key purpose (FPGA only)", "[hw_crypto] [ds]")
+{
+    esp_ds_data_t ds_data = {};
+    ds_data.rsa_length = ESP_DS_RSA_3072;
+    const char *message = "test";
+    uint8_t signature_data [128 * 4];
+
+    // HMAC fails in that case because it checks for the correct purpose
+    TEST_ASSERT_EQUAL(ESP32C3_ERR_HW_CRYPTO_DS_HMAC_FAIL, esp_ds_sign(message, &ds_data, HMAC_KEY0, signature_data));
+}
+
+TEST_CASE("Digital Signature Operation (FPGA only)", "[hw_crypto] [ds]")
+{
+    burn_hmac_keys();
+
+    for (int i = 0; i < NUM_CASES; i++) {
+        printf("Running test case %d...\n", i);
+        const encrypt_testcase_t *t = &test_cases[i];
+
+        // copy encrypt parameter test case into ds_data structure
+        esp_ds_data_t ds_data = { };
+        memcpy(ds_data.iv, t->iv, ETS_DS_IV_LEN);
+        memcpy(ds_data.c, t->expected_c, ETS_DS_C_LEN);
+        ds_data.rsa_length = t->p_data.length;
+
+        for (int j = 0; j < NUM_MESSAGES; j++) {
+            uint8_t signature[DS_MAX_BITS/8] = { 0 };
+            printf(" ... message %d\n", j);
+
+            esp_ds_context_t *esp_ds_ctx;
+            esp_err_t ds_r = esp_ds_start_sign(test_messages[j],
+                    &ds_data,
+                    t->hmac_key_idx + 1,
+                    &esp_ds_ctx);
+            TEST_ASSERT_EQUAL(ESP_OK, ds_r);
+
+            ds_r = esp_ds_finish_sign(signature, esp_ds_ctx);
+            TEST_ASSERT_EQUAL(ESP_OK, ds_r);
+
+            TEST_ASSERT_EQUAL_HEX8_ARRAY(t->expected_results[j], signature, sizeof(signature));
+        }
+
+        ets_hmac_invalidate_downstream(ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE);
+    }
+}
+
+TEST_CASE("Digital Signature Blocking Operation (FPGA only)", "[hw_crypto] [ds]")
+{
+    burn_hmac_keys();
+
+    for (int i = 0; i < NUM_CASES; i++) {
+        printf("Running test case %d...\n", i);
+        const encrypt_testcase_t *t = &test_cases[i];
+
+        // copy encrypt parameter test case into ds_data structure
+        esp_ds_data_t ds_data = { };
+        memcpy(ds_data.iv, t->iv, ETS_DS_IV_LEN);
+        memcpy(ds_data.c, t->expected_c, ETS_DS_C_LEN);
+        ds_data.rsa_length = t->p_data.length;
+
+        uint8_t signature[DS_MAX_BITS/8] = { 0 };
+
+        esp_err_t ds_r = esp_ds_sign(test_messages[0],
+                &ds_data,
+                t->hmac_key_idx + 1,
+                signature);
+        TEST_ASSERT_EQUAL(ESP_OK, ds_r);
+
+        TEST_ASSERT_EQUAL_HEX8_ARRAY(t->expected_results[0], signature, sizeof(signature));
+    }
+}
+
+TEST_CASE("Digital Signature Invalid Data (FPGA only)", "[hw_crypto] [ds]")
+{
+    burn_hmac_keys();
+
+    // Set up a valid test case
+    const encrypt_testcase_t *t = &test_cases[0];
+    esp_ds_data_t ds_data = { };
+    memcpy(ds_data.iv, t->iv, ETS_DS_IV_LEN);
+    memcpy(ds_data.c, t->expected_c, ETS_DS_C_LEN);
+    ds_data.rsa_length = t->p_data.length;
+
+    uint8_t signature[DS_MAX_BITS/8] = { 0 };
+    const uint8_t zero[DS_MAX_BITS/8] = { 0 };
+
+    // Corrupt the IV one bit at a time, rerun and expect failure
+    for (int bit = 0; bit < 128; bit++) {
+        printf("Corrupting IV bit %d...\n", bit);
+        ds_data.iv[bit / 8] ^= 1 << (bit % 8);
+        esp_ds_context_t *esp_ds_ctx;
+
+        esp_err_t ds_r = esp_ds_start_sign(test_messages[0], &ds_data, t->hmac_key_idx + 1, &esp_ds_ctx);
+        TEST_ASSERT_EQUAL(ESP_OK, ds_r);
+        ds_r = esp_ds_finish_sign(signature, esp_ds_ctx);
+        TEST_ASSERT_EQUAL(ESP32C3_ERR_HW_CRYPTO_DS_INVALID_DIGEST, ds_r);
+        TEST_ASSERT_EQUAL_HEX8_ARRAY(zero, signature, DS_MAX_BITS/8);
+
+        ds_data.iv[bit / 8] ^= 1 << (bit % 8);
+    }
+
+    // Corrupt encrypted key data one bit at a time, rerun and expect failure
+    printf("Corrupting C...\n");
+    for (int bit = 0; bit < ETS_DS_C_LEN * 8; bit++) {
+        printf("Corrupting C bit %d...\n", bit);
+        ds_data.c[bit / 8] ^= 1 << (bit % 8);
+        esp_ds_context_t *esp_ds_ctx;
+
+        esp_err_t ds_r = esp_ds_start_sign(test_messages[0], &ds_data, t->hmac_key_idx + 1, &esp_ds_ctx);
+        TEST_ASSERT_EQUAL(ESP_OK, ds_r);
+        ds_r = esp_ds_finish_sign(signature, esp_ds_ctx);
+        TEST_ASSERT_EQUAL(ESP32C3_ERR_HW_CRYPTO_DS_INVALID_DIGEST, ds_r);
+        TEST_ASSERT_EQUAL_HEX8_ARRAY(zero, signature, DS_MAX_BITS/8);
+
+        ds_data.c[bit / 8] ^= 1 << (bit % 8);
+    }
+}
+
+#endif // CONFIG_IDF_ENV_FPGA

+ 6 - 7
components/esp32s2/include/esp_ds.h

@@ -21,13 +21,12 @@
 extern "C" {
 #endif
 
-#define ESP_ERR_HW_CRYPTO_DS_BASE 0xc000 /*!< Starting number of HW cryptography module error codes */
-#define ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL           ESP_ERR_HW_CRYPTO_DS_BASE + 0x1 /*!< HMAC peripheral problem */
-#define ESP_ERR_HW_CRYPTO_DS_INVALID_KEY         ESP_ERR_HW_CRYPTO_DS_BASE + 0x2 /*!< given HMAC key isn't correct,
-                                                                                   HMAC peripheral problem */
-#define ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST      ESP_ERR_HW_CRYPTO_DS_BASE + 0x4 /*!< message digest check failed,
-                                                                                   result is invalid */
-#define ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING     ESP_ERR_HW_CRYPTO_DS_BASE + 0x5 /*!< padding check failed, but result
+#define ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL           ESP_ERR_HW_CRYPTO_BASE + 0x1 /*!< HMAC peripheral problem */
+#define ESP_ERR_HW_CRYPTO_DS_INVALID_KEY         ESP_ERR_HW_CRYPTO_BASE + 0x2 /*!< given HMAC key isn't correct,
+                                                                                HMAC peripheral problem */
+#define ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST      ESP_ERR_HW_CRYPTO_BASE + 0x4 /*!< message digest check failed,
+                                                                                result is invalid */
+#define ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING     ESP_ERR_HW_CRYPTO_BASE + 0x5 /*!< padding check failed, but result
                                                                                    is produced anyway and can be read*/
 
 #define ESP_DS_IV_LEN 16

+ 1 - 0
components/esp_common/include/esp_err.h

@@ -42,6 +42,7 @@ typedef int esp_err_t;
 #define ESP_ERR_WIFI_BASE           0x3000  /*!< Starting number of WiFi error codes */
 #define ESP_ERR_MESH_BASE           0x4000  /*!< Starting number of MESH error codes */
 #define ESP_ERR_FLASH_BASE          0x6000  /*!< Starting number of flash error codes */
+#define ESP_ERR_HW_CRYPTO_BASE      0xc000  /*!< Starting number of HW cryptography module error codes */
 
 /**
   * @brief Returns string for esp_err_t error codes

+ 4 - 3
components/esp_common/src/esp_err_to_name.c

@@ -710,11 +710,12 @@ static const esp_err_msg_t esp_err_msg_table[] = {
 #   ifdef      ESP_ERR_HTTPD_TASK
     ERR_TBL_IT(ESP_ERR_HTTPD_TASK),                             /* 45064 0xb008 Failed to launch server task/thread */
 #   endif
-    // components/esp32s2/include/esp_ds.h
-#   ifdef      ESP_ERR_HW_CRYPTO_DS_BASE
-    ERR_TBL_IT(ESP_ERR_HW_CRYPTO_DS_BASE),                      /* 49152 0xc000 Starting number of HW cryptography
+    // components/esp_common/include/esp_err.h
+#   ifdef      ESP_ERR_HW_CRYPTO_BASE
+    ERR_TBL_IT(ESP_ERR_HW_CRYPTO_BASE),                         /* 49152 0xc000 Starting number of HW cryptography
                                                                                 module error codes */
 #   endif
+    // components/esp32s2/include/esp_ds.h
 #   ifdef      ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL
     ERR_TBL_IT(ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL),                 /* 49153 0xc001 HMAC peripheral problem */
 #   endif

+ 1 - 0
components/hal/CMakeLists.txt

@@ -87,6 +87,7 @@ if(NOT BOOTLOADER_BUILD)
 
     if(${target} STREQUAL "esp32c3")
         list(APPEND srcs
+              "ds_hal.c"
               "esp32c3/adc_hal.c"
               "esp32c3/brownout_hal.c"
               "esp32c3/systimer_hal.c"

+ 1 - 1
components/hal/component.mk

@@ -2,7 +2,7 @@ COMPONENT_SRCDIRS := . esp32
 COMPONENT_ADD_INCLUDEDIRS := esp32/include include
 COMPONENT_ADD_LDFRAGMENTS += linker.lf
 
-COMPONENT_OBJEXCLUDE += ./spi_slave_hd_hal.o ./spi_flash_hal_gpspi.o ./spi_slave_hd_hal.o
+COMPONENT_OBJEXCLUDE += ./spi_slave_hd_hal.o ./spi_flash_hal_gpspi.o ./spi_slave_hd_hal.o ./ds_hal.o
 
 ifndef CONFIG_ETH_USE_ESP32_EMAC
     COMPONENT_OBJEXCLUDE += esp32/emac_hal.o

+ 75 - 0
components/hal/ds_hal.c

@@ -0,0 +1,75 @@
+// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "hal/systimer_hal.h"
+#include "hal/ds_hal.h"
+#include "hal/ds_ll.h"
+
+void ds_hal_start(void)
+{
+    ds_ll_start();
+}
+
+void ds_hal_finish(void)
+{
+    ds_ll_finish();
+}
+
+ds_key_check_t ds_hal_check_decryption_key(void)
+{
+    uint64_t start_time = systimer_hal_get_time(SYSTIMER_COUNTER_0);
+    while (ds_ll_busy() != 0) {
+        if ((systimer_hal_get_time(SYSTIMER_COUNTER_0) - start_time) > DS_KEY_CHECK_MAX_WAIT_US) {
+            return ds_ll_key_error_source();
+        }
+    }
+
+    return DS_KEY_INPUT_OK;
+}
+
+void ds_hal_configure_iv(const uint32_t *iv)
+{
+    ds_ll_configure_iv(iv);
+}
+
+void ds_hal_write_message(const uint8_t *msg, size_t size)
+{
+    ds_ll_write_message(msg, size);
+}
+
+void ds_hal_write_private_key_params(const uint8_t *key_params)
+{
+    ds_ll_write_private_key_params(key_params);
+}
+
+void ds_hal_start_sign(void)
+{
+    ds_ll_start_sign();
+}
+
+bool ds_hal_busy(void)
+{
+    return ds_ll_busy();
+}
+
+ds_signature_check_t ds_hal_read_result(uint8_t *result, size_t size)
+{
+    ds_signature_check_t check_result = ds_ll_check_signature();
+
+    if (check_result == DS_SIGNATURE_OK || check_result == DS_SIGNATURE_PADDING_FAIL) {
+        ds_ll_read_result(result, size);
+    }
+
+    return check_result;
+}

+ 175 - 0
components/hal/esp32c3/include/hal/ds_ll.h

@@ -0,0 +1,175 @@
+// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/*******************************************************************************
+ * NOTICE
+ * The hal is not public api, don't use it in application code.
+ ******************************************************************************/
+
+#pragma once
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+
+#include "soc/hwcrypto_reg.h"
+#include "soc/ds_caps.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+static inline void ds_ll_start(void)
+{
+    REG_WRITE(DS_SET_START_REG, 1);
+}
+
+/**
+ * @brief Wait until DS peripheral has finished any outstanding operation.
+ */
+static inline bool ds_ll_busy(void)
+{
+    return (REG_READ(DS_QUERY_BUSY_REG) > 0) ? true : false;
+}
+
+/**
+ * @brief Busy wait until the hardware is ready.
+ */
+static inline void ds_ll_wait_busy(void)
+{
+    while (ds_ll_busy());
+}
+
+/**
+ * @brief In case of a key error, check what caused it.
+ */
+static inline ds_key_check_t ds_ll_key_error_source(void)
+{
+    uint32_t key_error = REG_READ(DS_QUERY_KEY_WRONG_REG);
+    if (key_error == 0) {
+        return DS_NO_KEY_INPUT;
+    } else {
+        return DS_OTHER_WRONG;
+    }
+}
+
+/**
+ * @brief Write the initialization vector to the corresponding register field.
+ */
+static inline void ds_ll_configure_iv(const uint32_t *iv)
+{
+    for (size_t i = 0; i < (DS_KEY_PARAM_MD_IV_LENGTH / sizeof(uint32_t)); i++) {
+        REG_WRITE(DS_IV_BASE + (i * 4) , iv[i]);
+    }
+}
+
+/**
+ * @brief Write the message which should be signed.
+ *
+ * @param msg Pointer to the message.
+ * @param size Length of msg in bytes. It is the RSA signature length in bytes.
+ */
+static inline void ds_ll_write_message(const uint8_t *msg, size_t size)
+{
+    memcpy((uint8_t*) DS_X_BASE, msg, size);
+    asm volatile ("fence");
+}
+
+/**
+ * @brief Write the encrypted private key parameters.
+ */
+static inline void ds_ll_write_private_key_params(const uint8_t *encrypted_key_params)
+{
+    /* Note: as the internal peripheral still has RSA 4096 structure,
+       but C is encrypted based on the actual max RSA length (ETS_DS_MAX_BITS), need to fragment it
+       when copying to hardware...
+
+       (note if ETS_DS_MAX_BITS == 4096, this should be the same as copying data->c to hardware in one fragment)
+    */
+    typedef struct { uint32_t addr; size_t len; } frag_t;
+    const frag_t frags[] = {
+                            {DS_C_Y_BASE,  DS_SIGNATURE_MAX_BIT_LEN / 8},
+                            {DS_C_M_BASE,  DS_SIGNATURE_MAX_BIT_LEN / 8},
+                            {DS_C_RB_BASE, DS_SIGNATURE_MAX_BIT_LEN / 8},
+                            {DS_C_BOX_BASE, DS_IV_BASE - DS_C_BOX_BASE},
+    };
+    const size_t NUM_FRAGS = sizeof(frags)/sizeof(frag_t);
+    const uint8_t *from = encrypted_key_params;
+
+    for (int i = 0; i < NUM_FRAGS; i++) {
+        memcpy((uint8_t *)frags[i].addr, from, frags[i].len);
+        asm volatile ("fence");
+        from += frags[i].len;
+    }
+}
+
+/**
+ * @brief Begin signing procedure.
+ */
+static inline void ds_ll_start_sign(void)
+{
+    REG_WRITE(DS_SET_ME_REG, 1);
+}
+
+/**
+ * @brief check the calculated signature.
+ *
+ * @return
+ * - DS_SIGNATURE_OK if no issue is detected with the signature.
+ * - DS_SIGNATURE_PADDING_FAIL if the padding of the private key parameters is wrong.
+ * - DS_SIGNATURE_MD_FAIL if the message digest check failed. This means that the message digest calculated using
+ *      the private key parameters fails, i.e., the integrity of the private key parameters is not protected.
+ * - DS_SIGNATURE_PADDING_AND_MD_FAIL if both padding and message digest check fail.
+ */
+static inline ds_signature_check_t ds_ll_check_signature(void)
+{
+    uint32_t result = REG_READ(DS_QUERY_CHECK_REG);
+    switch(result) {
+    case 0:
+        return DS_SIGNATURE_OK;
+    case 1:
+        return DS_SIGNATURE_MD_FAIL;
+    case 2:
+        return DS_SIGNATURE_PADDING_FAIL;
+    default:
+        return DS_SIGNATURE_PADDING_AND_MD_FAIL;
+    }
+}
+
+/**
+ * @brief Read the signature from the hardware.
+ *
+ * @param result The signature result.
+ * @param size Length of signature result in bytes. It is the RSA signature length in bytes.
+ */
+static inline void ds_ll_read_result(uint8_t *result, size_t size)
+{
+    memcpy(result, (uint8_t*) DS_Z_BASE, size);
+    asm volatile ("fence");
+}
+
+/**
+ * @brief Exit the signature operation.
+ *
+ * @note This does not deactivate the module. Corresponding clock/reset bits have to be triggered for deactivation.
+ */
+static inline void ds_ll_finish(void)
+{
+    REG_WRITE(DS_SET_FINISH_REG, 1);
+    ds_ll_wait_busy();
+}
+
+#ifdef __cplusplus
+}
+#endif

+ 1 - 1
components/hal/esp32c3/include/hal/hmac_hal.h

@@ -100,7 +100,7 @@ void hmac_hal_next_block_padding(void);
 void hmac_hal_read_result_256(void *result);
 
 /**
- * @brief Clean the HMAC result provided to other hardware.
+ * @brief Clear (invalidate) the HMAC result provided to other hardware.
  */
 void hmac_hal_clean(void);
 

+ 112 - 0
components/hal/include/hal/ds_hal.h

@@ -0,0 +1,112 @@
+// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/*******************************************************************************
+ * NOTICE
+ * The hal is not public api, don't use it in application code.
+ * See readme.md in soc/include/hal/readme.md
+ ******************************************************************************/
+
+#pragma once
+
+#if CONFIG_IDF_TARGET_ESP32
+    #error "ESP32 doesn't have a DS peripheral"
+#endif
+
+#include <stdint.h>
+#include <stddef.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * The result when checking whether the key to decrypt the RSA parameters is ready.
+ */
+typedef enum {
+    DS_KEY_INPUT_OK = 0, /**< The decryption key is ready. */
+    DS_NO_KEY_INPUT,     /**< Dependent peripheral providing key hasn't been activated. */
+    DS_OTHER_WRONG,      /**< Dependent peripheral running but problem receiving the key. */
+} ds_key_check_t;
+
+typedef enum {
+    DS_SIGNATURE_OK = 0,                    /**< Signature is valid and can be read. */
+    DS_SIGNATURE_PADDING_FAIL = 1,          /**< Padding invalid, signature can be read if user wants it. */
+    DS_SIGNATURE_MD_FAIL = 2,               /**< Message digest check failed, signature invalid. */
+    DS_SIGNATURE_PADDING_AND_MD_FAIL = 3,   /**< Both padding and MD check failed. */
+} ds_signature_check_t;
+
+/**
+ * @brief Start the whole signing process after the input key is ready.
+ *
+ * Call this before using any of the functions below. The input key is ready must be ready at this point.
+ */
+void ds_hal_start(void);
+
+/**
+ * @brief Finish the whole signing process. Call this after the signature is read or in case of an error.
+ */
+void ds_hal_finish(void);
+
+/**
+ * @brief Check whether the key input (HMAC on ESP32-C3) is correct.
+ */
+ds_key_check_t ds_hal_check_decryption_key(void);
+
+/**
+ * @brief Write the initialization vector.
+ */
+void ds_hal_configure_iv(const uint32_t *iv);
+
+/**
+ * @brief Write the message which should be signed.
+ *
+ * @param msg Pointer to the message.
+ * @param size Length of signature result in bytes. It is the RSA signature length in bytes.
+ */
+void ds_hal_write_message(const uint8_t *msg, size_t size);
+
+/**
+ * @brief Write the encrypted private key parameters.
+ */
+void ds_hal_write_private_key_params(const uint8_t *block);
+
+/**
+ * @brief Begin signing procedure.
+ */
+void ds_hal_start_sign(void);
+
+/**
+ * @brief Check whether the hardware is busy with an operation.
+ *
+ * @return True if the hardware has finished the signing procedure, otherwise false.
+ */
+bool ds_hal_busy(void);
+
+/**
+ * @brief Check and read the signature from the hardware.
+ *
+ * @return
+ * - DS_SIGNATURE_OK if no issue is detected with the signature.
+ * - DS_SIGNATURE_PADDING_FAIL if the padding of the private key parameters is wrong.
+ * - DS_SIGNATURE_MD_FAIL if the message digest check failed. This means that the message digest calculated using
+ *      the private key parameters fails, i.e., the integrity of the private key parameters is not protected.
+ * - DS_SIGNATURE_PADDING_AND_MD_FAIL if both padding and message digest check fail.
+ */
+ds_signature_check_t ds_hal_read_result(uint8_t *result, size_t size);
+
+#ifdef __cplusplus
+}
+#endif

+ 25 - 0
components/soc/esp32c3/include/soc/ds_caps.h

@@ -0,0 +1,25 @@
+// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+
+/** The maximum length of a Digital Signature in bits. */
+#define DS_SIGNATURE_MAX_BIT_LEN (3072)
+
+/** Initialization vector (IV) length for the RSA key parameter message digest (MD) in bytes. */
+#define DS_KEY_PARAM_MD_IV_LENGTH (16)
+
+/** Maximum wait time for DS parameter decryption key. If overdue, then key error.
+    See TRM DS chapter for more details */
+#define DS_KEY_CHECK_MAX_WAIT_US (1100)

+ 5 - 1
components/soc/esp32c3/include/soc/hwcrypto_reg.h

@@ -160,8 +160,12 @@
 #define AES_XTS_STATE_REG         ((DR_REG_AES_XTS_BASE) + 0x58)
 #define AES_XTS_DATE_REG          ((DR_REG_AES_XTS_BASE) + 0x5C)
 
-/* Digital Signature registers*/
+/* Digital Signature registers and memory blocks */
 #define DS_C_BASE                 ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0x000 )
+#define DS_C_Y_BASE               ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0x000 )
+#define DS_C_M_BASE               ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0x200 )
+#define DS_C_RB_BASE              ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0x400 )
+#define DS_C_BOX_BASE             ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0x600 )
 #define DS_IV_BASE                ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0x630 )
 #define DS_X_BASE                 ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0x800 )
 #define DS_Z_BASE                 ((DR_REG_DIGITAL_SIGNATURE_BASE) + 0xA00 )

Некоторые файлы не были показаны из-за большого количества измененных файлов