diff --git a/app/inc/aat_def.h b/app/inc/aat_def.h deleted file mode 100644 index 54d51d6..0000000 --- a/app/inc/aat_def.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef AAT_DEF_H -#define AAT_DEF_H - -#define APP_ADDRESS_TABLE_TYPE (0x0AA7) -#define BOOTLOADER_ADDRESS_TABLE_TYPE (0x0BA7) -#define RAMEXE_ADDRESS_TABLE_TYPE (0x0EA7) - - -#define AAT_VERSION (0x0109) -#define AAT_MAJOR_VERSION (0x0100) -#define AAT_MAJOR_VERSION_MASK (0xFF00) - -//Magic numbers are used to check if preinstalled software is present to skip crc check -//EBL DFU files contain real crc values which will be checked that image is valid -#define IMAGE_CRC_MAGIC (0xB1736D20) -#define IMAGE_TIMESTAMP_MAGIC (0xACE135C3) - - -typedef struct aat_s -{ - uint32_t *topOfStack; // Stack initialization pointer - void (*resetVector)(void); // Reset vector - void (*nmiHandler)(void); // NMI Handler - void (*hardFaultHandler)(void); // Hardfault handler - uint16_t type; // 0x0AA7 for Application Address Table, 0x0BA7 for Bootloader Address Table, 0x0EA7 for RAMEXE - uint16_t version; // Current version = 0x0109 (first byte is majorversion, last byte is minorversion) - uint32_t *vectorTable; // Pointer to the real Cortex-M vector table - uint8_t platInfo; // Platform type - defined in micro.h - uint8_t microInfo; // Micro type - defined in micro.h - uint8_t phyInfo; // Phy type - defined in micro.h - uint8_t aatSize; // Size of the AAT in bytes. - uint16_t softwareVersion; // SOFTWARE_VERSION (Defined by the stack) - uint16_t softwareBuild; // EMBER_BUILD_NUMBER (Defined by the stack) - uint32_t timeStamp; // Unix epoch time for EBL generation - uint8_t imageInfo[32]; // User defined string. Usually just NULL (our tools don't fill this out). - uint32_t imageCrc; // CRC of the pageRanges defined below. - uint16_t pageRanges[6]; // Each pageRange is two bytes. The first defines the first page used, and the second byte is the last page in the range. - void *simeeBottom; // Pointer to the bottom of SimEE - uint32_t customerApplicationVersion; // Customer defined version number. - void *internalStorageBottom; // Location of internal storage. - uint8_t imageStamp[8]; // AES-MMO of image. Not used for security, but for checking if on-chip image is the same as the EBL version. - uint8_t familyInfo; // family type - defined in micro.h - uint8_t reserved0[3]; // Reserved for bootloader expansion - uint32_t reserved1[5]; // Reserved for bootloader expansion -} aat_t; - -// this is our copy of the AAT. - -extern const aat_t AppAddressTable; -extern const aat_t __stack_AAT; - -#endif diff --git a/app/inc/blat.h b/app/inc/blat.h new file mode 100644 index 0000000..a3fa418 --- /dev/null +++ b/app/inc/blat.h @@ -0,0 +1,27 @@ +// +// Created by Clyde Stubbs on 4/4/17. +// + +#ifndef BGBOOTLOAD_BLAT_H +#define BGBOOTLOAD_BLAT_H + +// this structure is included at the beginning of each user application. It is similar in intent, but different +// in format, to the Silabs AAT. + +#define APP_BOOT_ADDRESS_TYPE (0xFFFFFFA7) // this value set in the file +#define APP_APP_ADDRESS_TYPE (0xF765FFA7) // this value written after successful download + +typedef struct { + uint32_t *topOfStack; // Stack initialization pointer + void (*resetVector)(void); // Reset vector + void (*nmiHandler)(void); // NMI Handler + void (*hardFaultHandler)(void); // Hardfault handler + uint32_t type; // 0x0AA7 for Application Address Table, 0x0BA7 for Bootloader Address Table, 0x0EA7 for RAMEXE + uint32_t *vectorTable; // Pointer to the real Cortex-M vector table + uint32_t timeStamp; // Unix epoch time for EBL generation + uint32_t appVersion; // Customer defined version number. + uint8_t aatSize; // Size of the AAT in bytes. + uint8_t unused[3]; // Reserved for bootloader expansion + +} blat_t; +#endif //BGBOOTLOAD_BLAT_H diff --git a/app/src/aat.c b/app/src/aat.c index c1a12eb..c368512 100644 --- a/app/src/aat.c +++ b/app/src/aat.c @@ -1,27 +1,25 @@ #include -#include "aat_def.h" +#include //AAT extern void NMI_Handler(void); + extern void HardFault_Handler(void); + extern void Reset_Handler(void); extern uint32_t __StackTop; extern uint32_t __Vectors; -const aat_t app_ATT -__attribute__ ((section (".AAT"))) -= -{ - .topOfStack=&__StackTop, //.topOfStack=(uint32_t*)&CSTACK$$Limit, - .resetVector=Reset_Handler, // main program for the app - .nmiHandler=NMI_Handler, /* 2 - NMI */ - .hardFaultHandler=HardFault_Handler, /* 3 - HardFault */ - .type=APP_ADDRESS_TABLE_TYPE, //uint16_t type; - .version=AAT_MAJOR_VERSION, //uint16_t version; - .vectorTable=(void*)&__Vectors, //const HalVectorTableType *vectorTable; - .aatSize=sizeof(AppAddressTable), - .simeeBottom=(void*)0xFFFFFFFF, - .imageCrc=IMAGE_CRC_MAGIC, - .timeStamp=IMAGE_TIMESTAMP_MAGIC -}; +const blat_t app_ATT + __attribute__ ((section (".AAT"))) + = + { + .topOfStack=&__StackTop, //.topOfStack=(uint32_t*)&CSTACK$$Limit, + .resetVector=Reset_Handler, // main program for the app + .nmiHandler=NMI_Handler, /* 2 - NMI */ + .hardFaultHandler=HardFault_Handler, /* 3 - HardFault */ + .type=APP_BOOT_ADDRESS_TYPE, // type; The bootloader will overwrite this once it's happy + .vectorTable=(void *) &__Vectors, //const HalVectorTableType *vectorTable; + .aatSize=sizeof(blat_t), + }; diff --git a/app/src/main.c b/app/src/main.c index c770120..0185189 100644 --- a/app/src/main.c +++ b/app/src/main.c @@ -3,17 +3,18 @@ #include #include #include -#include "io.h" +#include #include #include -#include #include -#include #include "gecko_configuration.h" #include "native_gecko.h" #define MAX_CONNECTIONS 1 #define RESET_REQUEST 0x05FA0004 // value to request system reset +typedef void( Func )(void); +#define enterDfu ((Func **)28) + uint8_t bluetooth_stack_heap[DEFAULT_BLUETOOTH_HEAP(MAX_CONNECTIONS)]; bool doReboot; @@ -50,6 +51,7 @@ static void user_write(struct gecko_cmd_packet *evt) { if(writeStatus->value.len == 4 && memcmp(writeStatus->value.data, DFU_TRIGGER, 4) == 0) { response = 1; doReboot = true; + (*enterDfu)(); } gecko_cmd_gatt_server_send_user_write_response(writeStatus->connection, writeStatus->characteristic, response); break; diff --git a/bootload/CMakeLists.txt b/bootload/CMakeLists.txt index 25cdf67..b19f9cd 100644 --- a/bootload/CMakeLists.txt +++ b/bootload/CMakeLists.txt @@ -15,12 +15,16 @@ include_directories(platform/CMSIS/Include) # find the bgbuild command used to translate xml into C find_program(BGBUILD_CMD bin/bgbuild - $ENV{HOME}/dev/tools/ble/v2.1.1.0/protocol/bluetooth_2.1) + /Applications/Simplicity Studio.app/Contents/Eclipse/developer/stacks/ble/v2.1.1.0 + $ENV{HOME}/dev/tools/ble/v2.1.1.0/protocol/bluetooth_2.1 + ) set(GATT_DB gatt_db) set(GATT_DIR ${CMAKE_SOURCE_DIR}/gatt) set(LOCALDIR ${CMAKE_SOURCE_DIR}/localdefs) set(OTA_SERVICE_UUID_FILE ${LOCALDIR}/ota_service.txt) +set(OTA_KEY_FILE ${LOCALDIR}/ota_key.txt) +set(OTA_KEY_C ota_key.c) set(BLE_STACK_DIR ${CMAKE_SOURCE_DIR}/libs/ble.v2.1.1.0) set(GATT_SRC ${GATT_DIR}/gatt.bgproj) set(GATT_XML ${GATT_DIR}/gatt.xml) @@ -31,6 +35,7 @@ set(BIN_FILE ${CMAKE_BINARY_DIR}/${PROJECT_NAME}.bin) file(GLOB_RECURSE USER_SOURCES "src/*.c") file(GLOB_RECURSE USER_HEADERS "inc/*.h") file(STRINGS ${OTA_SERVICE_UUID_FILE} OTA_SERVICE) +file(STRINGS ${OTA_KEY_FILE} OTA_KEY LIMIT_INPUT 64) IF (CMAKE_BUILD_TYPE MATCHES Debug) file(GLOB_RECURSE RTT_LIBS "libs/SEGGER_RTT_V612j/RTT/*.c") @@ -56,7 +61,16 @@ add_custom_command( COMMAND ${BGBUILD_CMD} -gn ${GATT_SRC}) set_source_files_properties(${GATT_OUTPUTS} PROPERTIES GENERATED TRUE) -add_executable(${PROJECT_NAME}.elf ${USER_SOURCES} ${USER_HEADERS} ${LINKER_SCRIPT} gatt/${GATT_DB}.c ${RTT_LIBS}) +add_custom_command( + OUTPUT ${OTA_KEY_C} + DEPENDS ${OTA_KEY_FILE} + COMMAND echo 'const unsigned char ota_key[] = {' >${OTA_KEY_C} + COMMAND head -1 ${OTA_KEY_FILE} | sed 's/[a-z0-9A-Z][A-Za-z0-9]/0x&,/g' >> ${OTA_KEY_C} + COMMAND echo "'};'" >>${OTA_KEY_C} + +) + +add_executable(${PROJECT_NAME}.elf ${USER_SOURCES} ${USER_HEADERS} ${LINKER_SCRIPT} gatt/${GATT_DB}.c ${RTT_LIBS} ${OTA_KEY_C}) target_link_libraries(${PROJECT_NAME}.elf ${LIBRARIES}) set_target_properties(${PROJECT_NAME}.elf PROPERTIES LINK_DEPENDS ${LINKER_SCRIPT}) diff --git a/bootload/bgbootload.ld b/bootload/bgbootload.ld index e215254..d05046e 100644 --- a/bootload/bgbootload.ld +++ b/bootload/bgbootload.ld @@ -12,6 +12,7 @@ MEMORY { FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x40000 RAM (rwx) : ORIGIN = 0x20003000, LENGTH = 0x4C00-4 + BLERAM (rwx) : ORIGIN = 0x20002FF0, LENGTH = 0x10 } /* This is the linker script for the bootloader. @@ -127,6 +128,12 @@ SECTIONS __UserStart = .; }> FLASH +/* This is where the enter-dfu key gets written */ + .dfu_key : + { + KEEP(*(.dfu_key)) + } > BLERAM + .text_app_data : AT (__etext) { diff --git a/bootload/inc/aat_def.h b/bootload/inc/aat_def.h index 54d51d6..f41774c 100644 --- a/bootload/inc/aat_def.h +++ b/bootload/inc/aat_def.h @@ -44,9 +44,8 @@ typedef struct aat_s uint32_t reserved1[5]; // Reserved for bootloader expansion } aat_t; -// this is our copy of the AAT. +// this is our copy of the stack's AAT. -extern const aat_t AppAddressTable; extern const aat_t __stack_AAT; #endif diff --git a/bootload/inc/blat.h b/bootload/inc/blat.h new file mode 100644 index 0000000..a3fa418 --- /dev/null +++ b/bootload/inc/blat.h @@ -0,0 +1,27 @@ +// +// Created by Clyde Stubbs on 4/4/17. +// + +#ifndef BGBOOTLOAD_BLAT_H +#define BGBOOTLOAD_BLAT_H + +// this structure is included at the beginning of each user application. It is similar in intent, but different +// in format, to the Silabs AAT. + +#define APP_BOOT_ADDRESS_TYPE (0xFFFFFFA7) // this value set in the file +#define APP_APP_ADDRESS_TYPE (0xF765FFA7) // this value written after successful download + +typedef struct { + uint32_t *topOfStack; // Stack initialization pointer + void (*resetVector)(void); // Reset vector + void (*nmiHandler)(void); // NMI Handler + void (*hardFaultHandler)(void); // Hardfault handler + uint32_t type; // 0x0AA7 for Application Address Table, 0x0BA7 for Bootloader Address Table, 0x0EA7 for RAMEXE + uint32_t *vectorTable; // Pointer to the real Cortex-M vector table + uint32_t timeStamp; // Unix epoch time for EBL generation + uint32_t appVersion; // Customer defined version number. + uint8_t aatSize; // Size of the AAT in bytes. + uint8_t unused[3]; // Reserved for bootloader expansion + +} blat_t; +#endif //BGBOOTLOAD_BLAT_H diff --git a/bootload/inc/dfu.h b/bootload/inc/dfu.h index 139cadc..53b44e9 100644 --- a/bootload/inc/dfu.h +++ b/bootload/inc/dfu.h @@ -6,7 +6,9 @@ #define BGBOOTLOAD_DFU_H #include -#include "bg_types.h" +#include +#include +#include // definitions for the DFU protocol // Control packets @@ -20,11 +22,25 @@ #define DFU_CMD_RESTART 0x1 // reset DFU system - resets data counts etc. #define DFU_CMD_DATA 0x2 // data coming on the data channel -#define DFU_CMD_CRC 0x3 // total count and CRC of data sent -#define DFU_CMD_RESET 0x4 // reset device - +#define DFU_CMD_IV 0x3 // Initialization vector coming on data channel +#define DFU_CMD_DONE 0x4 // Download done, send status +#define DFU_CMD_RESET 0x5 // reset device +#define DFU_CMD_DIGEST 0x6 // Digest coming +#define DFU_CMD_PING 0x7 // Check progress + +#define IV_LEN 16 // length of initialization vector +#define KEY_LEN (256/8) // length of key +#define DIGEST_LEN (256/8) // length of SHA256 digest + +extern blat_t __UserStart; +#define USER_BLAT (&__UserStart) extern bool processCtrlPacket(uint8 * packet); // process a control packet. Return true if accepted extern bool processDataPacket(uint8 * packet, uint8 len); // process a data packet. extern bool enterDfu; +extern bool doReset; +extern const unsigned char ota_key[KEY_LEN]; +extern unsigned char deKey[KEY_LEN]; + +#define DFU_ENTRY_VECTOR 7 // index into vector table for EnterDFU_Handler #endif //BGBOOTLOAD_DFU_H diff --git a/bootload/inc/em_crypto.h b/bootload/inc/em_crypto.h new file mode 100644 index 0000000..3b44aa1 --- /dev/null +++ b/bootload/inc/em_crypto.h @@ -0,0 +1,1559 @@ +/***************************************************************************//** + * @file em_crypto.h + * @brief Cryptography accelerator peripheral API + * @version 5.0.0 + ******************************************************************************* + * @section License + * Copyright 2016 Silicon Laboratories, Inc. http://www.silabs.com + ******************************************************************************* + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Labs has no + * obligation to support this Software. Silicon Labs is providing the + * Software "AS IS", with no express or implied warranties of any kind, + * including, but not limited to, any implied warranties of merchantability + * or fitness for any particular purpose or warranties against infringement + * of any proprietary rights of a third party. + * + * Silicon Labs will not be liable for any consequential, incidental, or + * special damages, or any other relief, or for any claim by any third party, + * arising from your use of this Software. + * + ******************************************************************************/ +#ifndef EM_CRYPTO_H +#define EM_CRYPTO_H + +#include "em_device.h" + +#if defined(CRYPTO_COUNT) && (CRYPTO_COUNT > 0) + +#include "em_bus.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * @addtogroup emlib + * @{ + ******************************************************************************/ + +/***************************************************************************//** + * @addtogroup CRYPTO + * + * @brief Cryptography accelerator peripheral API + * + * @details + * In order for cryptographic support, users are recommended to consider the + * crypto APIs of the mbedTLS library provided by Silicon Labs instead of the + * interface provided in em_crypto.h. The mbedTLS library provides a much + * richer crypto API, including hardware acceleration of several functions. + * + * The main purpose of em_crypto.h is to implement a thin software interface + * for the CRYPTO hardware functions especially for the accelerated APIs of + * the mbedTLS library. Additionally em_crypto.h implement the AES API of the + * em_aes.h (supported by classic EFM32) for backwards compatibility. The + * following list summarizes the em_crypto.h inteface: + * @li AES (Advanced Encryption Standard) @ref crypto_aes + * @li SHA (Secure Hash Algorithm) @ref crypto_sha + * @li Big Integer multiplier @ref crypto_mul + * @li Functions for loading data and executing instruction sequences @ref crypto_exec + * + * @n @section crypto_aes AES + * The AES APIs include support for AES-128 and AES-256 with block cipher + * modes: + * @li CBC - Cipher Block Chaining mode + * @li CFB - Cipher Feedback mode + * @li CTR - Counter mode + * @li ECB - Electronic Code Book mode + * @li OFB - Output Feedback mode + * + * For the AES APIs Input/output data (plaintext, ciphertext, key etc) are + * treated as byte arrays, starting with most significant byte. Ie, 32 bytes + * of plaintext (B0...B31) is located in memory in the same order, with B0 at + * the lower address and B31 at the higher address. + * + * Byte arrays must always be a multiple of AES block size, ie. a multiple + * of 16. Padding, if required, is done at the end of the byte array. + * + * Byte arrays should be word (32 bit) aligned for performance + * considerations, since the array is accessed with 32 bit access type. + * The core MCUs supports unaligned accesses, but with a performance penalty. + * + * It is possible to specify the same output buffer as input buffer as long + * as they point to the same address. In that case the provided input buffer + * is replaced with the encrypted/decrypted output. Notice that the buffers + * must be exactly overlapping. If partly overlapping, the behavior is + * undefined. + * + * It is up to the user to use a cipher mode according to its requirements + * in order to not break security. Please refer to specific cipher mode + * theory for details. + * + * References: + * @li Wikipedia - Cipher modes, http://en.wikipedia.org/wiki/Cipher_modes + * + * @li Recommendation for Block Cipher Modes of Operation, + * NIST Special Publication 800-38A, 2001 Edition, + * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf + * + * @li Recommendation for Block Cipher Modes of Operation, + * http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf + * + * @n @section crypto_sha SHA + * The SHA APIs include support for + * @li SHA-1 @ref CRYPTO_SHA_1 + * @li SHA-256 @ref CRYPTO_SHA_256 + * + * The SHA-1 implementation is FIPS-180-1 compliant, ref: + * @li Wikipedia - SHA-1, https://en.wikipedia.org/wiki/SHA-1 + * @li SHA-1 spec - http://www.itl.nist.gov/fipspubs/fip180-1.htm + * + * The SHA-256 implementation is FIPS-180-2 compliant, ref: + * @li Wikipedia - SHA-2, https://en.wikipedia.org/wiki/SHA-2 + * @li SHA-2 spec - http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf + * + * @n @section crypto_mul CRYPTO_Mul + * @ref CRYPTO_Mul is a function for multiplying big integers that are + * bigger than the operand size of the MUL instruction which is 128 bits. + * CRYPTO_Mul multiplies all partial operands of the input operands using + * MUL to form a resulting number which may be twice the size of + * the operands. + * + * CRPYTO_Mul is typically used by RSA implementations which perform a + * huge amount of multiplication and square operations in order to + * implement modular exponentiation. + * Some RSA implementations use a number representation including arrays + * of 32bit words of variable size. The user should compile with + * -D USE_VARIABLE_SIZED_DATA_LOADS in order to load these numbers + * directly into CRYPTO without converting the number representation. + * + * @n @section crypto_exec Load and Execute Instruction Sequences + * The functions for loading data and executing instruction sequences can + * be used to implement complex algorithms like elliptic curve cryptography + * (ECC)) and authenticated encryption algorithms. There are two typical + * modes of operation: + * @li Multi sequence operation + * @li Single static instruction sequence operation + * + * In multi sequence mode the software starts by loading input data, then + * an instruction sequence, execute, and finally read the result. This + * process is repeated until the full crypto operation is complete. + * + * When using a single static instruction sequence, there is just one + * instruction sequence which is loaded initially. The sequence can be setup + * to run multiple times. The data can be loaded during the execution of the + * sequence by using DMA, BUFC and/or programmed I/O directly from the MCU + * core. For details on how to program the instruction sequences please refer + * to the reference manual of the particular Silicon Labs device. + * + * In order to load input data to the CRYPTO module use any of the following + * functions: + * @li @ref CRYPTO_DataWrite - Write 128 bits to a DATA register. + * @li @ref CRYPTO_DDataWrite - Write 256 bits to a DDATA register. + * @li @ref CRYPTO_QDataWrite - Write 512 bits to a QDATA register. + * + * In order to read output data from the CRYPTO module use any of the + * following functions: + * @li @ref CRYPTO_DataRead - Read 128 bits from a DATA register. + * @li @ref CRYPTO_DDataRead - Read 256 bits from a DDATA register. + * @li @ref CRYPTO_QDataRead - Read 512 bits from a QDATA register. + * + * In order to load an instruction sequence to the CRYPTO module use + * @ref CRYPTO_InstructionSequenceLoad. + * + * In order to execute the current instruction sequence in the CRYPTO module + * use @ref CRYPTO_InstructionSequenceExecute. + * + * In order to check whether an instruction sequence has completed + * use @ref CRYPTO_InstructionSequenceDone. + * + * In order to wait for an instruction sequence to complete + * use @ref CRYPTO_InstructionSequenceWait. + * + * In order to optimally load (with regards to speed) and execute an + * instruction sequence use any of the CRYPTO_EXECUTE_X macros (where X is + * in the range 1-20) defined in @ref em_crypto.h. E.g. CRYPTO_EXECUTE_19. + * @{ + ******************************************************************************/ + + /******************************************************************************* + ****************************** DEFINES *********************************** + ******************************************************************************/ + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ +/** Data sizes used by CRYPTO operations. */ +#define CRYPTO_DATA_SIZE_IN_BITS (128) +#define CRYPTO_DATA_SIZE_IN_BYTES (CRYPTO_DATA_SIZE_IN_BITS/8) +#define CRYPTO_DATA_SIZE_IN_32BIT_WORDS (CRYPTO_DATA_SIZE_IN_BYTES/sizeof(uint32_t)) + +#define CRYPTO_KEYBUF_SIZE_IN_BITS (256) +#define CRYPTO_KEYBUF_SIZE_IN_BYTES (CRYPTO_DDATA_SIZE_IN_BITS/8) +#define CRYPTO_KEYBUF_SIZE_IN_32BIT_WORDS (CRYPTO_DDATA_SIZE_IN_BYTES/sizeof(uint32_t)) + +#define CRYPTO_DDATA_SIZE_IN_BITS (256) +#define CRYPTO_DDATA_SIZE_IN_BYTES (CRYPTO_DDATA_SIZE_IN_BITS/8) +#define CRYPTO_DDATA_SIZE_IN_32BIT_WORDS (CRYPTO_DDATA_SIZE_IN_BYTES/sizeof(uint32_t)) + +#define CRYPTO_QDATA_SIZE_IN_BITS (512) +#define CRYPTO_QDATA_SIZE_IN_BYTES (CRYPTO_QDATA_SIZE_IN_BITS/8) +#define CRYPTO_QDATA_SIZE_IN_32BIT_WORDS (CRYPTO_QDATA_SIZE_IN_BYTES/sizeof(uint32_t)) + +#define CRYPTO_DATA260_SIZE_IN_32BIT_WORDS (9) + +/** SHA-1 digest sizes */ +#define CRYPTO_SHA1_DIGEST_SIZE_IN_BITS (160) +#define CRYPTO_SHA1_DIGEST_SIZE_IN_BYTES (CRYPTO_SHA1_DIGEST_SIZE_IN_BITS/8) + +/** SHA-256 digest sizes */ +#define CRYPTO_SHA256_DIGEST_SIZE_IN_BITS (256) +#define CRYPTO_SHA256_DIGEST_SIZE_IN_BYTES (CRYPTO_SHA256_DIGEST_SIZE_IN_BITS/8) + +/** + * Read and write all 260 bits of DDATA0 when in 260 bit mode. + */ +#define CRYPTO_DDATA0_260_BITS_READ(crypto, bigint260) CRYPTO_DData0Read260(crypto, bigint260) +#define CRYPTO_DDATA0_260_BITS_WRITE(crypto, bigint260) CRYPTO_DData0Write260(crypto, bigint260) +/** @endcond */ + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ +/** + * Instruction sequence load macros CRYPTO_SEQ_LOAD_X (where X is in the range + * 1-20). E.g. @ref CRYPTO_SEQ_LOAD_20. + * Use these macros in order for faster execution than the function API. + */ +#define CRYPTO_SEQ_LOAD_1(crypto, a1) { \ + crypto->SEQ0 = a1 | (CRYPTO_CMD_INSTR_END<<8);} +#define CRYPTO_SEQ_LOAD_2(crypto, a1, a2) { \ + crypto->SEQ0 = a1 | (a2<<8) | (CRYPTO_CMD_INSTR_END<<16);} +#define CRYPTO_SEQ_LOAD_3(crypto, a1, a2, a3) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (CRYPTO_CMD_INSTR_END<<24);} +#define CRYPTO_SEQ_LOAD_4(crypto, a1, a2, a3, a4) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = CRYPTO_CMD_INSTR_END;} +#define CRYPTO_SEQ_LOAD_5(crypto, a1, a2, a3, a4, a5) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (CRYPTO_CMD_INSTR_END<<8);} +#define CRYPTO_SEQ_LOAD_6(crypto, a1, a2, a3, a4, a5, a6) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (CRYPTO_CMD_INSTR_END<<16);} +#define CRYPTO_SEQ_LOAD_7(crypto, a1, a2, a3, a4, a5, a6, a7) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (CRYPTO_CMD_INSTR_END<<24);} +#define CRYPTO_SEQ_LOAD_8(crypto, a1, a2, a3, a4, a5, a6, a7, a8) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = CRYPTO_CMD_INSTR_END;} +#define CRYPTO_SEQ_LOAD_9(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (CRYPTO_CMD_INSTR_END<<8);} +#define CRYPTO_SEQ_LOAD_10(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (CRYPTO_CMD_INSTR_END<<16);} +#define CRYPTO_SEQ_LOAD_11(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (CRYPTO_CMD_INSTR_END<<24);} +#define CRYPTO_SEQ_LOAD_12(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = CRYPTO_CMD_INSTR_END;} +#define CRYPTO_SEQ_LOAD_13(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (CRYPTO_CMD_INSTR_END<<8);} +#define CRYPTO_SEQ_LOAD_14(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (CRYPTO_CMD_INSTR_END<<16);} +#define CRYPTO_SEQ_LOAD_15(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (CRYPTO_CMD_INSTR_END<<24);} +#define CRYPTO_SEQ_LOAD_16(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = CRYPTO_CMD_INSTR_END;} +#define CRYPTO_SEQ_LOAD_17(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (CRYPTO_CMD_INSTR_END<<8);} +#define CRYPTO_SEQ_LOAD_18(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (a18<<8) | (CRYPTO_CMD_INSTR_END<<16);} +#define CRYPTO_SEQ_LOAD_19(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (a18<<8) | (a19<<16) | (CRYPTO_CMD_INSTR_END<<24);} +#define CRYPTO_SEQ_LOAD_20(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (a18<<8) | (a19<<16) | (a20<<24);} +/** @endcond */ + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ +/** + * Instruction sequence execution macros CRYPTO_EXECUTE_X (where X is in the range + * 1-20). E.g. @ref CRYPTO_EXECUTE_19. + * Use these macros in order for faster execution than the function API. + */ +#define CRYPTO_EXECUTE_1(crypto, a1) { \ + crypto->SEQ0 = a1 | (CRYPTO_CMD_INSTR_EXEC<<8); } +#define CRYPTO_EXECUTE_2(crypto, a1, a2) { \ + crypto->SEQ0 = a1 | (a2<<8) | (CRYPTO_CMD_INSTR_EXEC<<16); } +#define CRYPTO_EXECUTE_3(crypto, a1, a2, a3) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (CRYPTO_CMD_INSTR_EXEC<<24); } +#define CRYPTO_EXECUTE_4(crypto, a1, a2, a3, a4) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = CRYPTO_CMD_INSTR_EXEC; } +#define CRYPTO_EXECUTE_5(crypto, a1, a2, a3, a4, a5) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (CRYPTO_CMD_INSTR_EXEC<<8); } +#define CRYPTO_EXECUTE_6(crypto, a1, a2, a3, a4, a5, a6) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (CRYPTO_CMD_INSTR_EXEC<<16); } +#define CRYPTO_EXECUTE_7(crypto, a1, a2, a3, a4, a5, a6, a7) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (CRYPTO_CMD_INSTR_EXEC<<24); } +#define CRYPTO_EXECUTE_8(crypto, a1, a2, a3, a4, a5, a6, a7, a8) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = CRYPTO_CMD_INSTR_EXEC; } +#define CRYPTO_EXECUTE_9(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (CRYPTO_CMD_INSTR_EXEC<<8); } +#define CRYPTO_EXECUTE_10(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (CRYPTO_CMD_INSTR_EXEC<<16); } +#define CRYPTO_EXECUTE_11(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (CRYPTO_CMD_INSTR_EXEC<<24); } +#define CRYPTO_EXECUTE_12(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = CRYPTO_CMD_INSTR_EXEC; } +#define CRYPTO_EXECUTE_13(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (CRYPTO_CMD_INSTR_EXEC<<8); } +#define CRYPTO_EXECUTE_14(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (CRYPTO_CMD_INSTR_EXEC<<16); } +#define CRYPTO_EXECUTE_15(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (CRYPTO_CMD_INSTR_EXEC<<24); } +#define CRYPTO_EXECUTE_16(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = CRYPTO_CMD_INSTR_EXEC; } +#define CRYPTO_EXECUTE_17(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (CRYPTO_CMD_INSTR_EXEC<<8); } +#define CRYPTO_EXECUTE_18(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (a18<<8) | (CRYPTO_CMD_INSTR_EXEC<<16); } +#define CRYPTO_EXECUTE_19(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (a18<<8) | (a19<<16) | (CRYPTO_CMD_INSTR_EXEC<<24); } +#define CRYPTO_EXECUTE_20(crypto, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) { \ + crypto->SEQ0 = a1 | (a2<<8) | (a3<<16) | (a4<<24); \ + crypto->SEQ1 = a5 | (a6<<8) | (a7<<16) | (a8<<24); \ + crypto->SEQ2 = a9 | (a10<<8) | (a11<<16) | (a12<<24); \ + crypto->SEQ3 = a13 | (a14<<8) | (a15<<16) | (a16<<24); \ + crypto->SEQ4 = a17 | (a18<<8) | (a19<<16) | (a20<<24); \ + CRYPTO_InstructionSequenceExecute();} +/** @endcond */ + +/******************************************************************************* + ****************************** TYPEDEFS *********************************** + ******************************************************************************/ + +/** + * CRYPTO data types used for data load functions. This data type is + * capable of storing a 128 bits value as used in the crypto DATA + * registers + */ +typedef uint32_t CRYPTO_Data_TypeDef[CRYPTO_DATA_SIZE_IN_32BIT_WORDS]; + +/** + * CRYPTO data type used for data load functions. This data type + * is capable of storing a 256 bits value as used in the crypto DDATA + * registers + */ +typedef uint32_t CRYPTO_DData_TypeDef[CRYPTO_DDATA_SIZE_IN_32BIT_WORDS]; + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ +typedef uint32_t* CRYPTO_DDataPtr_TypeDef; +/** @endcond */ + +/** + * CRYPTO data type used for data load functions. This data type is + * capable of storing a 512 bits value as used in the crypto QDATA + * registers + */ +typedef uint32_t CRYPTO_QData_TypeDef[CRYPTO_QDATA_SIZE_IN_32BIT_WORDS]; + +/** + * CRYPTO data type used for data load functions. This data type is + * capable of storing a 260 bits value as used by the @ref CRYPTO_DData0Write260 + * function. + * + * Note that this data type is multiple of 32 bit words, so the + * actual storage used by this type is 32x9=288 bits. + */ +typedef uint32_t CRYPTO_Data260_TypeDef[CRYPTO_DATA260_SIZE_IN_32BIT_WORDS]; + +/** + * CRYPTO data type used for data load functions. This data type is + * capable of storing 256 bits as used in the crypto KEYBUF register. + */ +typedef uint32_t CRYPTO_KeyBuf_TypeDef[CRYPTO_KEYBUF_SIZE_IN_32BIT_WORDS]; + +/** + * CRYPTO 128 bit Data register pointer type. The 128 bit registers are used to + * load 128 bit values as input and output data for cryptographic and big + * integer arithmetic functions of the CRYPTO module. + */ +typedef volatile uint32_t* CRYPTO_DataReg_TypeDef; + +/** + * CRYPTO 256 bit DData (Double Data) register pointer type. The 256 bit + * registers are used to load 256 bit values as input and output data for + * cryptographic and big integer arithmetic functions of the CRYPTO module. + */ +typedef volatile uint32_t* CRYPTO_DDataReg_TypeDef; + +/** + * CRYPTO 512 bit QData (Quad data) register pointer type. The 512 bit + * registers are used to load 512 bit values as input and output data for + * cryptographic and big integer arithmetic functions of the CRYPTO module. + */ +typedef volatile uint32_t* CRYPTO_QDataReg_TypeDef; + +/** CRYPTO modulus identifiers. */ +typedef enum +{ + cryptoModulusBin256 = CRYPTO_WAC_MODULUS_BIN256, /**< Generic 256 bit modulus 2^256 */ + cryptoModulusBin128 = CRYPTO_WAC_MODULUS_BIN128, /**< Generic 128 bit modulus 2^128 */ + cryptoModulusGcmBin128 = CRYPTO_WAC_MODULUS_GCMBIN128, /**< GCM 128 bit modulus = 2^128 + 2^7 + 2^2 + 2 + 1 */ + cryptoModulusEccB233 = CRYPTO_WAC_MODULUS_ECCBIN233P, /**< ECC B233 prime modulus = 2^233 + 2^74 + 1 */ + cryptoModulusEccB163 = CRYPTO_WAC_MODULUS_ECCBIN163P, /**< ECC B163 prime modulus = 2^163 + 2^7 + 2^6 + 2^3 + 1 */ + cryptoModulusEccP256 = CRYPTO_WAC_MODULUS_ECCPRIME256P, /**< ECC P256 prime modulus = 2^256 - 2^224 + 2^192 + 2^96 - 1 */ + cryptoModulusEccP224 = CRYPTO_WAC_MODULUS_ECCPRIME224P, /**< ECC P224 prime modulus = 2^224 - 2^96 - 1 */ + cryptoModulusEccP192 = CRYPTO_WAC_MODULUS_ECCPRIME192P, /**< ECC P192 prime modulus = 2^192 - 2^64 - 1 */ + cryptoModulusEccB233Order = CRYPTO_WAC_MODULUS_ECCBIN233N, /**< ECC B233 order modulus */ + cryptoModulusEccB233KOrder = CRYPTO_WAC_MODULUS_ECCBIN233KN, /**< ECC B233K order modulus */ + cryptoModulusEccB163Order = CRYPTO_WAC_MODULUS_ECCBIN163N, /**< ECC B163 order modulus */ + cryptoModulusEccB163KOrder = CRYPTO_WAC_MODULUS_ECCBIN163KN, /**< ECC B163K order modulus */ + cryptoModulusEccP256Order = CRYPTO_WAC_MODULUS_ECCPRIME256N, /**< ECC P256 order modulus */ + cryptoModulusEccP224Order = CRYPTO_WAC_MODULUS_ECCPRIME224N, /**< ECC P224 order modulus */ + cryptoModulusEccP192Order = CRYPTO_WAC_MODULUS_ECCPRIME192N /**< ECC P192 order modulus */ +} CRYPTO_ModulusId_TypeDef; + +/** CRYPTO multiplication widths for wide arithmetic operations. */ +typedef enum +{ + cryptoMulOperand256Bits = CRYPTO_WAC_MULWIDTH_MUL256, /**< 256 bits operands */ + cryptoMulOperand128Bits = CRYPTO_WAC_MULWIDTH_MUL128, /**< 128 bits operands */ + cryptoMulOperandModulusBits = CRYPTO_WAC_MULWIDTH_MULMOD /**< MUL operand width + is specified by the + modulus type.*/ +} CRYPTO_MulOperandWidth_TypeDef; + +/** CRYPTO result widths for MUL operations. */ +typedef enum +{ + cryptoResult128Bits = CRYPTO_WAC_RESULTWIDTH_128BIT, /**< Multiplication result width is 128 bits*/ + cryptoResult256Bits = CRYPTO_WAC_RESULTWIDTH_256BIT, /**< Multiplication result width is 256 bits*/ + cryptoResult260Bits = CRYPTO_WAC_RESULTWIDTH_260BIT /**< Multiplication result width is 260 bits*/ +} CRYPTO_ResultWidth_TypeDef; + +/** CRYPTO result widths for MUL operations. */ +typedef enum +{ + cryptoInc1byte = CRYPTO_CTRL_INCWIDTH_INCWIDTH1, /**< inc width is 1 byte*/ + cryptoInc2byte = CRYPTO_CTRL_INCWIDTH_INCWIDTH2, /**< inc width is 2 byte*/ + cryptoInc3byte = CRYPTO_CTRL_INCWIDTH_INCWIDTH3, /**< inc width is 3 byte*/ + cryptoInc4byte = CRYPTO_CTRL_INCWIDTH_INCWIDTH4 /**< inc width is 4 byte*/ +} CRYPTO_IncWidth_TypeDef; + +/** CRYPTO key width. */ +typedef enum +{ + cryptoKey128Bits = 8, /**< Key width is 128 bits*/ + cryptoKey256Bits = 16, /**< Key width is 256 bits*/ +} CRYPTO_KeyWidth_TypeDef; + +/** + * The max number of crypto instructions in an instruction sequence + */ +#define CRYPTO_MAX_SEQUENCE_INSTRUCTIONS (20) + +/** + * Instruction sequence type. + * The user should fill in the desired operations from step1, then step2 etc. + * The CRYPTO_CMD_INSTR_END marks the end of the sequence. + * Bit fields are used to format the memory layout of the struct equal to the + * sequence registers in the CRYPTO module. + */ +typedef uint8_t CRYPTO_InstructionSequence_TypeDef[CRYPTO_MAX_SEQUENCE_INSTRUCTIONS]; + +/** Default instruction sequence consisting of all ENDs. The user can + initialize the instruction sequence with this default value set, and fill + in the desired operations from step 1. The first END instruction marks + the end of the sequence. */ +#define CRYPTO_INSTRUCTIONSEQUENSE_DEFAULT \ + {CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, \ + CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, \ + CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, \ + CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, \ + CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, \ + CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END, \ + CRYPTO_CMD_INSTR_END, CRYPTO_CMD_INSTR_END} + +/** SHA-1 Digest type. */ +typedef uint8_t CRYPTO_SHA1_Digest_TypeDef[CRYPTO_SHA1_DIGEST_SIZE_IN_BYTES]; + +/** SHA-256 Digest type. */ +typedef uint8_t CRYPTO_SHA256_Digest_TypeDef[CRYPTO_SHA256_DIGEST_SIZE_IN_BYTES]; + +/** + * @brief + * AES counter modification function pointer. + * + * @note + * This is defined in order for backwards compatibility with EFM32 em_aes.h. + * The CRYPTO implementation of Counter mode does not support counter update + * callbacks. + * + * @param[in] ctr Counter value to be modified. + */ +typedef void (*CRYPTO_AES_CtrFuncPtr_TypeDef)(uint8_t * ctr); + +/******************************************************************************* + ***************************** PROTOTYPES ********************************** + ******************************************************************************/ + +/***************************************************************************//** + * @brief + * Set the modulus type used for wide arithmetic operations. + * + * @details + * This function sets the modulus type to be used by the Modulus instructions + * of the CRYPTO module. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] modType + * Modulus type. + ******************************************************************************/ +void CRYPTO_ModulusSet(CRYPTO_TypeDef * crypto, + CRYPTO_ModulusId_TypeDef modType); + +/***************************************************************************//** + * @brief + * Set the number of bits in the operands of the MUL instruction. + * + * @details + * This function sets the number of bits to be used in the operands of + * the MUL instruction. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] mulOperandWidth + * Multiplication width in bits. + ******************************************************************************/ +__STATIC_INLINE +void CRYPTO_MulOperandWidthSet(CRYPTO_TypeDef *crypto, + CRYPTO_MulOperandWidth_TypeDef mulOperandWidth) +{ + uint32_t temp = crypto->WAC & (~_CRYPTO_WAC_MULWIDTH_MASK); + crypto->WAC = temp | mulOperandWidth; +} + +/***************************************************************************//** + * @brief + * Set the width of the results of the non-modulus instructions. + * + * @details + * This function sets the result width of the non-modulus instructions. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] resultWidth + * Result width of non-modulus instructions. + ******************************************************************************/ +__STATIC_INLINE +void CRYPTO_ResultWidthSet(CRYPTO_TypeDef *crypto, + CRYPTO_ResultWidth_TypeDef resultWidth) +{ + uint32_t temp = crypto->WAC & (~_CRYPTO_WAC_RESULTWIDTH_MASK); + crypto->WAC = temp | resultWidth; +} + +/***************************************************************************//** + * @brief + * Set the width of the DATA1 increment instruction DATA1INC. + * + * @details + * This function sets the width of the DATA1 increment instruction + * @ref CRYPTO_CMD_INSTR_DATA1INC. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] incWidth + * incrementation width. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_IncWidthSet(CRYPTO_TypeDef *crypto, + CRYPTO_IncWidth_TypeDef incWidth) +{ + uint32_t temp = crypto->CTRL & (~_CRYPTO_CTRL_INCWIDTH_MASK); + crypto->CTRL = temp | incWidth; +} + +/***************************************************************************//** + * @brief + * Write a 128 bit value into a crypto register. + * + * @note + * This function provide a low-level api for writing to the multi-word + * registers in the crypto peripheral. Applications should prefer to use + * @ref CRYPTO_DataWrite, @ref CRYPTO_DDataWrite or @ref CRYPTO_QDataWrite + * for writing to the DATA, DDATA and QDATA registers. + * + * @param[in] reg + * Pointer to the crypto register. + * + * @param[in] val + * This is a pointer to 4 32 bit integers that contains the 128 bit value + * which will be written to the crypto register. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_BurstToCrypto(volatile uint32_t * reg, + const uint32_t * val) +{ + /* Load data from memory into local registers. */ + register uint32_t v0 = val[0]; + register uint32_t v1 = val[1]; + register uint32_t v2 = val[2]; + register uint32_t v3 = val[3]; + /* Store data to CRYPTO */ + *reg = v0; + *reg = v1; + *reg = v2; + *reg = v3; +} + +/***************************************************************************//** + * @brief + * Read a 128 bit value from a crypto register. + * + * @note + * This function provide a low-level api for reading one of the multi-word + * registers in the crypto peripheral. Applications should prefer to use + * @ref CRYPTO_DataRead, @ref CRYPTO_DDataRead or @ref CRYPTO_QDataRead + * for reading the value of the DATA, DDATA and QDATA registers. + * + * @param[in] reg + * Pointer to the crypto register. + * + * @param[out] val + * This is a pointer to an array that is capable of holding 4 32 bit integers + * that will be filled with the 128 bit value from the crypto register. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_BurstFromCrypto(volatile uint32_t * reg, uint32_t * val) +{ + /* Load data from CRYPTO into local registers. */ + register uint32_t v0 = *reg; + register uint32_t v1 = *reg; + register uint32_t v2 = *reg; + register uint32_t v3 = *reg; + /* Store data to memory */ + val[0] = v0; + val[1] = v1; + val[2] = v2; + val[3] = v3; +} + +/***************************************************************************//** + * @brief + * Write 128 bits of data to a DATAX register in the CRYPTO module. + * + * @details + * Write 128 bits of data to a DATAX register in the crypto module. The data + * value is typically input to a big integer operation (see crypto + * instructions). + * + * @param[in] dataReg The 128 bit DATA register. + * @param[in] val Value of the data to write to the DATA register. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_DataWrite(CRYPTO_DataReg_TypeDef dataReg, + const CRYPTO_Data_TypeDef val) +{ + CRYPTO_BurstToCrypto((volatile uint32_t *)dataReg, val); +} + +/***************************************************************************//** + * @brief + * Read 128 bits of data from a DATAX register in the CRYPTO module. + * + * @details + * Read 128 bits of data from a DATAX register in the crypto module. The data + * value is typically output from a big integer operation (see crypto + * instructions) + * + * @param[in] dataReg The 128 bit DATA register. + * @param[out] val Location where to store the value in memory. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_DataRead(CRYPTO_DataReg_TypeDef dataReg, + CRYPTO_Data_TypeDef val) +{ + CRYPTO_BurstFromCrypto((volatile uint32_t *)dataReg, val); +} + +/***************************************************************************//** + * @brief + * Write 256 bits of data to a DDATAX register in the CRYPTO module. + * + * @details + * Write 256 bits of data into a DDATAX (Double Data) register in the crypto + * module. The data value is typically input to a big integer operation (see + * crypto instructions). + * + * @param[in] ddataReg The 256 bit DDATA register. + * @param[in] val Value of the data to write to the DDATA register. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_DDataWrite(CRYPTO_DDataReg_TypeDef ddataReg, + const CRYPTO_DData_TypeDef val) +{ + CRYPTO_BurstToCrypto((volatile uint32_t *)ddataReg, &val[0]); + CRYPTO_BurstToCrypto((volatile uint32_t *)ddataReg, &val[4]); +} + +/***************************************************************************//** + * @brief + * Read 256 bits of data from a DDATAX register in the CRYPTO module. + * + * @details + * Read 256 bits of data from a DDATAX (Double Data) register in the crypto + * module. The data value is typically output from a big integer operation + * (see crypto instructions). + * + * @param[in] ddataReg The 256 bit DDATA register. + * @param[out] val Location where to store the value in memory. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_DDataRead(CRYPTO_DDataReg_TypeDef ddataReg, + CRYPTO_DData_TypeDef val) +{ + CRYPTO_BurstFromCrypto((volatile uint32_t *)ddataReg, &val[0]); + CRYPTO_BurstFromCrypto((volatile uint32_t *)ddataReg, &val[4]); +} + +/***************************************************************************//** + * @brief + * Write 512 bits of data to a QDATAX register in the CRYPTO module. + * + * @details + * Write 512 bits of data into a QDATAX (Quad Data) register in the crypto module + * The data value is typically input to a big integer operation (see crypto + * instructions). + * + * @param[in] qdataReg The 512 bits QDATA register. + * @param[in] val Value of the data to write to the QDATA register. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_QDataWrite(CRYPTO_QDataReg_TypeDef qdataReg, + CRYPTO_QData_TypeDef val) +{ + CRYPTO_BurstToCrypto((volatile uint32_t *)qdataReg, &val[0]); + CRYPTO_BurstToCrypto((volatile uint32_t *)qdataReg, &val[4]); + CRYPTO_BurstToCrypto((volatile uint32_t *)qdataReg, &val[8]); + CRYPTO_BurstToCrypto((volatile uint32_t *)qdataReg, &val[12]); +} + +/***************************************************************************//** + * @brief + * Read 512 bits of data from a QDATAX register in the CRYPTO module. + * + * @details + * Read 512 bits of data from a QDATAX register in the crypto module. The data + * value is typically input to a big integer operation (see crypto + * instructions). + * + * @param[in] qdataReg The 512 bits QDATA register. + * @param[in] val Value of the data to write to the QDATA register. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_QDataRead(CRYPTO_QDataReg_TypeDef qdataReg, + CRYPTO_QData_TypeDef val) +{ + CRYPTO_BurstFromCrypto((volatile uint32_t *)qdataReg, &val[0]); + CRYPTO_BurstFromCrypto((volatile uint32_t *)qdataReg, &val[4]); + CRYPTO_BurstFromCrypto((volatile uint32_t *)qdataReg, &val[8]); + CRYPTO_BurstFromCrypto((volatile uint32_t *)qdataReg, &val[12]); +} + +/***************************************************************************//** + * @brief + * Set the key value to be used by the CRYPTO module. + * + * @details + * Write 128 or 256 bit key to the KEYBUF register in the crypto module. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] val + * Value of the data to write to the KEYBUF register. + * + * @param[in] keyWidth + * Key width - 128 or 256 bits + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_KeyBufWrite(CRYPTO_TypeDef *crypto, + CRYPTO_KeyBuf_TypeDef val, + CRYPTO_KeyWidth_TypeDef keyWidth) +{ + if (keyWidth == cryptoKey256Bits) + { + /* Set AES-256 mode */ + BUS_RegBitWrite(&crypto->CTRL, _CRYPTO_CTRL_AES_SHIFT, _CRYPTO_CTRL_AES_AES256); + /* Load key in KEYBUF register (= DDATA4) */ + CRYPTO_DDataWrite(&crypto->DDATA4, (uint32_t *)val); + } + else + { + /* Set AES-128 mode */ + BUS_RegBitWrite(&crypto->CTRL, _CRYPTO_CTRL_AES_SHIFT, _CRYPTO_CTRL_AES_AES128); + CRYPTO_BurstToCrypto(&crypto->KEYBUF, &val[0]); + } +} + +void CRYPTO_KeyRead(CRYPTO_TypeDef *crypto, + CRYPTO_KeyBuf_TypeDef val, + CRYPTO_KeyWidth_TypeDef keyWidth); + +/***************************************************************************//** + * @brief + * Quick write 128 bit key to the CRYPTO module. + * + * @details + * Quick write 128 bit key to the KEYBUF register in the CRYPTO module. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] val + * Value of the data to write to the KEYBUF register. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_KeyBuf128Write(CRYPTO_TypeDef *crypto, + const uint32_t * val) +{ + CRYPTO_BurstToCrypto(&crypto->KEYBUF, val); +} + +/***************************************************************************//** + * @brief + * Quick read access of the Carry bit from arithmetic operations. + * + * @details + * This function reads the carry bit of the CRYPTO ALU. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @return + * Returns 'true' if carry is 1, and 'false' if carry is 0. + ******************************************************************************/ +__STATIC_INLINE bool CRYPTO_CarryIsSet(CRYPTO_TypeDef *crypto) +{ + return (crypto->DSTATUS & _CRYPTO_DSTATUS_CARRY_MASK) + >> _CRYPTO_DSTATUS_CARRY_SHIFT; +} + +/***************************************************************************//** + * @brief + * Quick read access of the 4 LSbits of the DDATA0 register. + * + * @details + * This function quickly retrieves the 4 least significant bits of the + * DDATA0 register via the DDATA0LSBS bit field in the DSTATUS register. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @return + * Returns the 4 LSbits of DDATA0. + ******************************************************************************/ +__STATIC_INLINE uint8_t CRYPTO_DData0_4LSBitsRead(CRYPTO_TypeDef *crypto) +{ + return (crypto->DSTATUS & _CRYPTO_DSTATUS_DDATA0LSBS_MASK) + >> _CRYPTO_DSTATUS_DDATA0LSBS_SHIFT; +} + +/***************************************************************************//** + * @brief + * Read 260 bits from the DDATA0 register. + * + * @details + * This functions reads 260 bits from the DDATA0 register in the CRYPTO + * module. The data value is typically output from a big integer operation + * (see crypto instructions) when the result width is set to 260 bits by + * calling @ref CRYPTO_ResultWidthSet(cryptoResult260Bits); + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] val + * Location where to store the value in memory. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_DData0Read260(CRYPTO_TypeDef *crypto, + CRYPTO_Data260_TypeDef val) +{ + CRYPTO_DDataRead(&crypto->DDATA0, val); + val[8] = (crypto->DSTATUS & _CRYPTO_DSTATUS_DDATA0MSBS_MASK) + >> _CRYPTO_DSTATUS_DDATA0MSBS_SHIFT; +} + +/***************************************************************************//** + * @brief + * Write 260 bits to the DDATA0 register. + * + * @details + * This functions writes 260 bits to the DDATA0 register in the CRYPTO + * module. The data value is typically input to a big integer operation + * (see crypto instructions) when the result width is set to 260 bits by + * calling @ref CRYPTO_ResultWidthSet(cryptoResult260Bits); + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] val + * Location where of the value in memory. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_DData0Write260(CRYPTO_TypeDef *crypto, + const CRYPTO_Data260_TypeDef val) +{ + CRYPTO_DDataWrite(&crypto->DDATA0, val); + crypto->DDATA0BYTE32 = val[8] & _CRYPTO_DDATA0BYTE32_DDATA0BYTE32_MASK; +} + +/***************************************************************************//** + * @brief + * Quick read the MSbit of the DDATA1 register. + * + * @details + * This function reads the most significant bit (bit 255) of the DDATA1 + * register via the DDATA1MSB bit field in the DSTATUS register. This can + * be used to quickly check the signedness of a big integer resident in the + * CRYPTO module. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @return + * Returns 'true' if MSbit is 1, and 'false' if MSbit is 0. + ******************************************************************************/ +__STATIC_INLINE bool CRYPTO_DData1_MSBitRead(CRYPTO_TypeDef *crypto) +{ + return (crypto->DSTATUS & _CRYPTO_DSTATUS_DDATA1MSB_MASK) + >> _CRYPTO_DSTATUS_DDATA1MSB_SHIFT; +} + +/***************************************************************************//** + * @brief + * Load a sequence of instructions to be executed on the current values in + * the data registers. + * + * @details + * This function loads a sequence of instructions to the crypto module. The + * instructions will be executed when the CRYPTO_InstructionSequenceExecute + * function is called. The first END marks the end of the sequence. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] instructionSequence + * Instruction sequence to load. + ******************************************************************************/ +__STATIC_INLINE +void CRYPTO_InstructionSequenceLoad(CRYPTO_TypeDef *crypto, + const CRYPTO_InstructionSequence_TypeDef instructionSequence) +{ + const uint32_t * pas = (const uint32_t *) instructionSequence; + + crypto->SEQ0 = pas[0]; + crypto->SEQ1 = pas[1]; + crypto->SEQ2 = pas[2]; + crypto->SEQ3 = pas[3]; + crypto->SEQ4 = pas[4]; +} + +/***************************************************************************//** + * @brief + * Execute the current programmed instruction sequence. + * + * @details + * This function starts the execution of the current instruction sequence + * in the CRYPTO module. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_InstructionSequenceExecute(CRYPTO_TypeDef *crypto) +{ + /* Start the command sequence. */ + crypto->CMD = CRYPTO_CMD_SEQSTART; +} + +/***************************************************************************//** + * @brief + * Check whether the execution of an instruction sequence has completed. + * + * @details + * This function checks whether an instruction sequence has completed. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @return + * Returns 'true' if the instruction sequence is done, and 'false' if not. + ******************************************************************************/ +__STATIC_INLINE bool CRYPTO_InstructionSequenceDone(CRYPTO_TypeDef *crypto) +{ + /* Return true if operation has completed. */ + return !(crypto->STATUS + & (CRYPTO_STATUS_INSTRRUNNING | CRYPTO_STATUS_SEQRUNNING)); +} + +/***************************************************************************//** + * @brief + * Wait for completion of the current sequence of instructions. + * + * @details + * This function "busy"-waits until the execution of the ongoing instruction + * sequence has completed. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_InstructionSequenceWait(CRYPTO_TypeDef *crypto) +{ + while (!CRYPTO_InstructionSequenceDone(crypto)) + ; +} + +/***************************************************************************//** + * @brief + * Wait for completion of the current command. + * + * @details + * This function "busy"-waits until the execution of the ongoing instruction + * has completed. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_InstructionWait(CRYPTO_TypeDef *crypto) +{ + /* Wait for completion */ + while (!(crypto->IF & CRYPTO_IF_INSTRDONE)) + ; + crypto->IFC = CRYPTO_IF_INSTRDONE; +} + +void CRYPTO_SHA_1(CRYPTO_TypeDef *crypto, + const uint8_t *msg, + uint64_t msgLen, + CRYPTO_SHA1_Digest_TypeDef digest); + +void CRYPTO_SHA_256(CRYPTO_TypeDef *crypto, + const uint8_t *msg, + uint64_t msgLen, + CRYPTO_SHA256_Digest_TypeDef digest); + +void CRYPTO_Mul(CRYPTO_TypeDef *crypto, + uint32_t * A, int aSize, + uint32_t * B, int bSize, + uint32_t * R, int rSize); + +void CRYPTO_AES_CBC128(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt); + +void CRYPTO_AES_CBC256(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt); + +void CRYPTO_AES_CFB128(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt); + +void CRYPTO_AES_CFB256(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt); + +void CRYPTO_AES_CTR128(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + uint8_t * ctr, + CRYPTO_AES_CtrFuncPtr_TypeDef ctrFunc); + +void CRYPTO_AES_CTR256(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + uint8_t * ctr, + CRYPTO_AES_CtrFuncPtr_TypeDef ctrFunc); + +void CRYPTO_AES_CTRUpdate32Bit(uint8_t * ctr); +void CRYPTO_AES_DecryptKey128(CRYPTO_TypeDef *crypto, uint8_t * out, const uint8_t * in); +void CRYPTO_AES_DecryptKey256(CRYPTO_TypeDef *crypto, uint8_t * out, const uint8_t * in); + +void CRYPTO_AES_ECB128(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + bool encrypt); + +void CRYPTO_AES_ECB256(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + bool encrypt); + +void CRYPTO_AES_OFB128(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv); + +void CRYPTO_AES_OFB256(CRYPTO_TypeDef *crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv); + +/***************************************************************************//** + * @brief + * Clear one or more pending CRYPTO interrupts. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] flags + * Pending CRYPTO interrupt source to clear. Use a bitwise logic OR combination of + * valid interrupt flags for the CRYPTO module (CRYPTO_IF_nnn). + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_IntClear(CRYPTO_TypeDef *crypto, uint32_t flags) +{ + crypto->IFC = flags; +} + +/***************************************************************************//** + * @brief + * Disable one or more CRYPTO interrupts. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] flags + * CRYPTO interrupt sources to disable. Use a bitwise logic OR combination of + * valid interrupt flags for the CRYPTO module (CRYPTO_IF_nnn). + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_IntDisable(CRYPTO_TypeDef *crypto, uint32_t flags) +{ + crypto->IEN &= ~(flags); +} + +/***************************************************************************//** + * @brief + * Enable one or more CRYPTO interrupts. + * + * @note + * Depending on the use, a pending interrupt may already be set prior to + * enabling the interrupt. Consider using CRYPTO_IntClear() prior to enabling + * if such a pending interrupt should be ignored. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] flags + * CRYPTO interrupt sources to enable. Use a bitwise logic OR combination of + * valid interrupt flags for the CRYPTO module (CRYPTO_IF_nnn). + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_IntEnable(CRYPTO_TypeDef *crypto, uint32_t flags) +{ + crypto->IEN |= flags; +} + +/***************************************************************************//** + * @brief + * Get pending CRYPTO interrupt flags. + * + * @note + * The event bits are not cleared by the use of this function. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @return + * CRYPTO interrupt sources pending. A bitwise logic OR combination of valid + * interrupt flags for the CRYPTO module (CRYPTO_IF_nnn). + ******************************************************************************/ +__STATIC_INLINE uint32_t CRYPTO_IntGet(CRYPTO_TypeDef *crypto) +{ + return crypto->IF; +} + +/***************************************************************************//** + * @brief + * Get enabled and pending CRYPTO interrupt flags. + * Useful for handling more interrupt sources in the same interrupt handler. + * + * @note + * Interrupt flags are not cleared by the use of this function. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @return + * Pending and enabled CRYPTO interrupt sources + * The return value is the bitwise AND of + * - the enabled interrupt sources in CRYPTO_IEN and + * - the pending interrupt flags CRYPTO_IF + ******************************************************************************/ +__STATIC_INLINE uint32_t CRYPTO_IntGetEnabled(CRYPTO_TypeDef *crypto) +{ + uint32_t tmp; + + /* Store IEN in temporary variable in order to define explicit order + * of volatile accesses. */ + tmp = crypto->IEN; + + /* Bitwise AND of pending and enabled interrupts */ + return crypto->IF & tmp; +} + +/***************************************************************************//** + * @brief + * Set one or more pending CRYPTO interrupts from SW. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] flags + * CRYPTO interrupt sources to set to pending. Use a bitwise logic OR combination + * of valid interrupt flags for the CRYPTO module (CRYPTO_IF_nnn). + ******************************************************************************/ +__STATIC_INLINE void CRYPTO_IntSet(CRYPTO_TypeDef *crypto, uint32_t flags) +{ + crypto->IFS = flags; +} + +/******************************************************************************* + ***** Static inline wrappers for CRYPTO AES functions in order to ***** + ***** preserve backwards compatibility with AES module API functions. ***** + ******************************************************************************/ + +/***************************************************************************//** + * @brief + * AES Cipher-block chaining (CBC) cipher mode encryption/decryption, + * 128 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_CBC128 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_CBC128(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + CRYPTO_AES_CBC128(CRYPTO, out, in, len, key, iv, encrypt); +} + +/***************************************************************************//** + * @brief + * AES Cipher-block chaining (CBC) cipher mode encryption/decryption, 256 bit + * key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_CBC256 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_CBC256(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + CRYPTO_AES_CBC256(CRYPTO, out, in, len, key, iv, encrypt); +} + +/***************************************************************************//** + * @brief + * AES Cipher feedback (CFB) cipher mode encryption/decryption, 128 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_CFB128 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_CFB128(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + CRYPTO_AES_CFB128(CRYPTO, out, in, len, key, iv, encrypt); +} + +/***************************************************************************//** + * @brief + * AES Cipher feedback (CFB) cipher mode encryption/decryption, 256 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_CFB256 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_CFB256(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + CRYPTO_AES_CFB256(CRYPTO, out, in, len, key, iv, encrypt); +} + +/***************************************************************************//** + * @brief + * AES Counter (CTR) cipher mode encryption/decryption, 128 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_CTR128 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_CTR128(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + uint8_t * ctr, + CRYPTO_AES_CtrFuncPtr_TypeDef ctrFunc) +{ + CRYPTO_AES_CTR128(CRYPTO, out, in, len, key, ctr, ctrFunc); +} + +/***************************************************************************//** + * @brief + * AES Counter (CTR) cipher mode encryption/decryption, 256 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_CTR256 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_CTR256(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + uint8_t * ctr, + CRYPTO_AES_CtrFuncPtr_TypeDef ctrFunc) +{ + CRYPTO_AES_CTR256(CRYPTO, out, in, len, key, ctr, ctrFunc); +} + +/***************************************************************************//** + * @brief + * Update last 32 bits of 128 bit counter, by incrementing with 1. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_CTRUpdate32Bit instead. + ******************************************************************************/ +__STATIC_INLINE void AES_CTRUpdate32Bit(uint8_t * ctr) +{ + CRYPTO_AES_CTRUpdate32Bit(ctr); +} + +/***************************************************************************//** + * @brief + * Generate 128 bit AES decryption key from 128 bit encryption key. The + * decryption key is used for some cipher modes when decrypting. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_DecryptKey128 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_DecryptKey128(uint8_t * out, const uint8_t * in) +{ + CRYPTO_AES_DecryptKey128(CRYPTO, out, in); +} + +/***************************************************************************//** + * @brief + * Generate 256 bit AES decryption key from 256 bit encryption key. The + * decryption key is used for some cipher modes when decrypting. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_DecryptKey256 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_DecryptKey256(uint8_t * out, const uint8_t * in) +{ + CRYPTO_AES_DecryptKey256(CRYPTO, out, in); +} + +/***************************************************************************//** + * @brief + * AES Electronic Codebook (ECB) cipher mode encryption/decryption, + * 128 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_ECB128 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_ECB128(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + bool encrypt) +{ + CRYPTO_AES_ECB128(CRYPTO, out, in, len, key, encrypt); +} + +/***************************************************************************//** + * @brief + * AES Electronic Codebook (ECB) cipher mode encryption/decryption, + * 256 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_ECB256 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_ECB256(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + bool encrypt) +{ + CRYPTO_AES_ECB256(CRYPTO, out, in, len, key, encrypt); +} + +/***************************************************************************//** + * @brief + * AES Output feedback (OFB) cipher mode encryption/decryption, 128 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_OFB128 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_OFB128(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv) +{ + CRYPTO_AES_OFB128(CRYPTO, out, in, len, key, iv); +} + +/***************************************************************************//** + * @brief + * AES Output feedback (OFB) cipher mode encryption/decryption, 256 bit key. + * + * @deprecated + * This function is present to preserve backwards compatibility. Use + * @ref CRYPTO_AES_OFB256 instead. + ******************************************************************************/ +__STATIC_INLINE void AES_OFB256(uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv) +{ + CRYPTO_AES_OFB256(CRYPTO, out, in, len, key, iv); +} + +#ifdef __cplusplus +} +#endif + +/** @} (end addtogroup CRYPTO) */ +/** @} (end addtogroup emlib) */ + +#endif /* defined(CRYPTO_COUNT) && (CRYPTO_COUNT > 0) */ + +#endif /* EM_CRYPTO_H */ diff --git a/bootload/inc/flash.h b/bootload/inc/flash.h index d1b8999..937c1a8 100644 --- a/bootload/inc/flash.h +++ b/bootload/inc/flash.h @@ -53,5 +53,7 @@ RAMFUNC void FLASH_eraseOneBlock(uint32_t blockStart); void FLASH_init(void); void FLASH_CalcPageSize(void); +//#define FLASH_PAGE_SIZE 0x800 // flash page size on EFR32BG + extern uint32_t flashPageSize; #endif diff --git a/bootload/src/aat.c b/bootload/src/aat.c index 1e4d96d..71621c6 100644 --- a/bootload/src/aat.c +++ b/bootload/src/aat.c @@ -22,7 +22,7 @@ __attribute__ ((section (".AAT"))) .type=APP_ADDRESS_TABLE_TYPE, //uint16_t type; .version=AAT_MAJOR_VERSION, //uint16_t version; .vectorTable=(void*)&__dfu_Vectors, //const HalVectorTableType *vectorTable; - .aatSize=sizeof(AppAddressTable), + .aatSize=sizeof(aat_t), .simeeBottom=(void*)0xFFFFFFFF, .imageCrc=IMAGE_CRC_MAGIC, .timeStamp=IMAGE_TIMESTAMP_MAGIC diff --git a/bootload/src/main.c b/bootload/src/boot_main.c similarity index 60% rename from bootload/src/main.c rename to bootload/src/boot_main.c index 6efb5d5..5977775 100644 --- a/bootload/src/main.c +++ b/bootload/src/boot_main.c @@ -11,11 +11,10 @@ #include #include -#include #include -#include #include #include +#include #define lockBits ((uint32_t *)LOCKBITS_BASE) @@ -27,8 +26,15 @@ static const uint32_t stack_aat[] = {0x20007BF8, 0x00020A4B, 0x0000CE87, 0x0000F393}; +// random bytes + +static const uint8_t dfu_key[] = {0xCE, 0x8D, 0xC1, 0x1F, 0x37, 0x7B, 0xB1, 0x9A, + 0x79, 0xF5, 0xE1, 0x44, 0x8C, 0xC9, 0xAD, 0x57}; +// copy of random bytes +static uint8_t dfu_key_copy[sizeof(dfu_key)] __attribute__ ((section (".dfu_key"))); bool enterDfu; // set if we should enter dfu mode + static void hang() { for (;;); } @@ -37,13 +43,13 @@ void main(void) { EMU_init(); CMU_init(); - /* Unlock the MSC */ - MSC->LOCK = MSC_UNLOCK_CODE; /* Enable writing to the flash */ -#if DEBUG == 0 +#if !defined(DEBUG) // check debug lock if(DLW != 0) { + /* Unlock the MSC */ + MSC->LOCK = MSC_UNLOCK_CODE; MSC->WRITECTRL |= MSC_WRITECTRL_WREN; FLASH_writeWord((uint32_t) &DLW, 0); MSC->WRITECTRL &= ~MSC_WRITECTRL_WREN; @@ -51,11 +57,19 @@ void main(void) { } #endif + // ************ + // for debug purposes, never run the user program +#if defined(DEBUG) + enterDfu = true; +#endif uint32_t cause = RMU_ResetCauseGet(); RMU_ResetCauseClear(); - if ((cause & (RMU_RSTCAUSE_PORST | RMU_RSTCAUSE_SYSREQRST)) == RMU_RSTCAUSE_SYSREQRST) + // enter DFU if we got here from anything other than a power on reset, and our key + // has been copied to RAM + if (!(cause & RMU_RSTCAUSE_PORST) && memcmp(dfu_key, dfu_key_copy, sizeof(dfu_key)) == 0) enterDfu = true; + memset(dfu_key_copy, 1, sizeof(dfu_key_copy)); /* check for valid BT stack loaded */ if (memcmp(stack_aat, &__stack_AAT, sizeof stack_aat) != 0) hang(); @@ -67,3 +81,12 @@ void main(void) { asm("mov sp,%0"::"r" (__stack_AAT.topOfStack)); __stack_AAT.resetVector(); } + +/** + * This function is called from the application program to flag that we should enter DFU mode + * after the next non-power on reset. It is accessed through + * an entry in the vector table, indexed at ENTER_DFU_VECTOR. + */ +void EnterDFU_Handler(void) { + memcpy(dfu_key_copy, dfu_key, sizeof(dfu_key_copy)); +} diff --git a/bootload/src/clkinit.c b/bootload/src/clkinit.c index 6645eab..933ec0c 100644 --- a/bootload/src/clkinit.c +++ b/bootload/src/clkinit.c @@ -80,6 +80,8 @@ void CMU_init(void) { /* Enable clock for GPIO by default */ CMU_ClockEnable(cmuClock_GPIO, true); + /* Enable clock for Crypto by default */ + CMU_ClockEnable(cmuClock_CRYPTO, true); // [Peripheral Clock enables]$ } diff --git a/bootload/src/dfu.c b/bootload/src/dfu.c index 370b131..7fd27db 100644 --- a/bootload/src/dfu.c +++ b/bootload/src/dfu.c @@ -4,10 +4,22 @@ #include #include +#include +#include + +static uint32 dataAddress, dataCount, digestSize, digestAddress; +static uint32 ivLen, digestLen; +static uint8_t iv[IV_LEN]; +static uint8_t digest[DIGEST_LEN]; +static uint8_t calcDigest[DIGEST_LEN]; + +bool doReset; + +static uint8_t dataBuffer[FLASH_PAGE_SIZE]; // holds data for decryption +static uint32_t bufferBase; // address corresponding to base of buffer +static uint32_t bufferStart; // start of encrypted data in buffer +static uint32_t bufferEnd; // length of encrypted data in buffer -static uint32 address; -static uint32 count; -static uint32 total; // get a 16 bit word static uint32 getWord16(uint8 *ptr) { @@ -19,46 +31,175 @@ static uint32 getWord16(uint8 *ptr) { static uint32 getWord32(uint8 *ptr) { return *ptr + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24); } +static void decode() { + if (bufferEnd != bufferStart) { + uint8_t newIv[IV_LEN]; + // save the last block of ciphertext as the new IV + memcpy(newIv, dataBuffer + bufferEnd - IV_LEN, IV_LEN); + uint8_t * bp = dataBuffer+bufferStart; + CRYPTO_AES_CBC256(CRYPTO, bp, bp, bufferEnd-bufferStart, deKey, iv, false); + memcpy(iv, newIv, IV_LEN); + printf("Flashing block at %X\n", bufferBase); + FLASH_eraseOneBlock(bufferBase); + FLASH_writeBlock((void *) bufferBase, FLASH_PAGE_SIZE, dataBuffer); + } +} + +/** + * Set the address of the buffer base. Copy existing data if required. + * @param address The next address to write to + */ +static void setAddress(uint32_t address) { + dataAddress = address; + uint32_t base = address & ~(FLASH_PAGE_SIZE - 1); // get start of block + if (bufferBase != base) { + decode(); + bufferBase = base; + // prefill the buffer with whatever data is already there, in case we want to write a partial block + memcpy(dataBuffer, (const void *) bufferBase, FLASH_PAGE_SIZE); + bufferStart = address-base; + bufferEnd = bufferStart; + } +} + +void dumphex(const uint8_t * buf, unsigned len) { + while(len-- != 0) + printf("%02X ", *buf++); +} + +bool checkDigest() { + CRYPTO_SHA_256(CRYPTO, (const uint8_t *) digestAddress, digestSize, calcDigest); + if(memcmp(digest, calcDigest, DIGEST_LEN) != 0) { +#if defined(DEBUG) + printf("Digest failed: expected:\n"); + dumphex(digest, DIGEST_LEN); + printf("\nActually got:\n"); + dumphex(calcDigest, DIGEST_LEN); +#endif + return false; + } + return true; +} +// process a data packet. +bool processDataPacket(uint8 *packet, uint8 len) { + //printf("Data packet len %d\n", len); + if (ivLen != 0) { + if (len == ivLen) { + memcpy(iv, packet, len); + ivLen = 0; + return true; + } + printf("Bad IV len %d\n", len); + ivLen = 0; + return false; + } + + if(digestLen != 0) { + if (len == digestLen) { + memcpy(digest, packet, len); + digestLen = 0; + if(checkDigest()) + return true; + return false; + } + printf("Bad digest len %d\n", len); + digestLen = 0; + return false; + } + + if (dataCount >= len) { + uint32_t offs = dataAddress-bufferBase; + memcpy(dataBuffer+offs, packet, len); + dataAddress += len; + bufferEnd = offs+len; + dataCount -= len; + //printf("Length remaining %d\n", count); + if(dataCount == 0) + decode(); + else + setAddress(dataAddress); + return true; + } + return false; +} // process a control packet. Return true if accepted bool processCtrlPacket(uint8 *packet) { uint32 cmd = getWord16(packet + DFU_CTRL_PKT_CMD); uint32 len = getWord16(packet + DFU_CTRL_PKT_LEN); - address = getWord32(packet + DFU_CTRL_PKT_ADR); + uint32 address = getWord32(packet + DFU_CTRL_PKT_ADR); printf("Cmd %X, len %d @ %X\n", cmd, len, address); switch (cmd) { case DFU_CMD_RESTART: - count = 0; - total = 0; + dataCount = 0; + bufferBase = 0; + bufferEnd = 0; + bufferStart = 0; printf("Restarted DFU\n"); return true; case DFU_CMD_DATA: - - if (count != 0) { + if (ivLen != 0 || dataCount != 0) { printf("DATA command before previous complete\n"); return false; } - count = len; - printf("DATA command: %d bytes at %X\n", count, address); + if(address < (uint32) USER_BLAT) { + printf("Invalid address - %X should be less than %X", address, USER_BLAT); + return false; + } + dataCount = len; + setAddress(address); + printf("DATA command: %d bytes at %X\n", len, address); + return true; + + case DFU_CMD_IV: + if (ivLen != 0 || dataCount != 0) { + printf("IV command before previous complete\n"); + return false; + } + ivLen = len; + printf("IV command: %d bytes\n", ivLen); return true; case DFU_CMD_RESET: - return false; + doReset = true; + return true; - default: - return false; - } + case DFU_CMD_DIGEST: + if (digestLen != 0 || ivLen != 0 || dataCount != 0) { + printf("DIGEST command before previous complete\n"); + return false; + } + if (address == 0 || len == 0) { + printf("DIGEST command without data block\n"); + return false; + } + digestAddress = address; + digestLen = DIGEST_LEN; + digestSize = len; + printf("Digest command: %d bytes\n", len); + return true; -} + case DFU_CMD_DONE: + if (digestLen != 0 || ivLen != 0 || dataCount != 0) + return false; + if(USER_BLAT->type == APP_BOOT_ADDRESS_TYPE) { + printf("Updating BLAT:"); + MSC->WRITECTRL |= MSC_WRITECTRL_WREN; + FLASH_writeWord((uint32_t) &USER_BLAT->type, APP_APP_ADDRESS_TYPE); + MSC->WRITECTRL &= ~MSC_WRITECTRL_WREN; + printf(" Blat now %X\n", USER_BLAT->type); + } + return true; -// process a data packet. -bool processDataPacket(uint8 *packet, uint8 len) { - printf("Data packet len %d\n", len); - if (count > len) { - count -= len; - return true; + case DFU_CMD_PING: + // checking if we are up to the same point as the master thinks we should be + printf("Pinged at %d/%d\n", len, dataCount); + return len == dataCount; + + default: + break; } return false; } diff --git a/bootload/src/dfu_main.c b/bootload/src/dfu_main.c index 8b996b2..550edf7 100644 --- a/bootload/src/dfu_main.c +++ b/bootload/src/dfu_main.c @@ -3,21 +3,28 @@ #include #include #include -#include "io.h" -#include "dfu.h" +#include +#include #include #include #include +#include #include "gecko_configuration.h" #include "native_gecko.h" -#define MAX_CONNECTIONS 1 +#define MAX_CONNECTIONS 1 // we only talk to one device at a time +#define MIN_CONN_INTERVAL 6 // 7.5ms +#define MAX_CONN_INTERVAL 20 // 25ms +#define LATENCY 40 // max number of connection attempts we can skip. This is set high +// to allow for AES decryption and flash programming +#define SUPERV_TIMEOUT 300 // 30s + #define AAT_VALUE ((uint32_t)&__dfu_AAT) // word value of AAT address -extern aat_t __UserStart; -#define USER_AAT (&__UserStart) +#define RESET_REQUEST 0x05FA0004 // value to request system reset uint8_t bluetooth_stack_heap[DEFAULT_BLUETOOTH_HEAP(MAX_CONNECTIONS)]; extern uint32_t __dfu_AAT; // our AAT address +unsigned char deKey[KEY_LEN]; /* Gecko configuration parameters (see gecko_configuration.h) */ @@ -35,16 +42,18 @@ static const gecko_configuration_t config = { static void user_write(struct gecko_cmd_packet *evt) { struct gecko_msg_gatt_server_user_write_request_evt_t *writeStatus; - unsigned i; + uint8 response; writeStatus = &evt->data.evt_gatt_server_user_write_request; + /* + unsigned i; printf("Write value: attr=%d, opcode=%d, offset=%d, value:\n", writeStatus->characteristic, writeStatus->att_opcode, writeStatus->offset); for (i = 0; i != writeStatus->value.len; i++) printf("%02X ", writeStatus->value.data[i]); printf("\n"); + */ switch (writeStatus->characteristic) { - uint8 response; case GATTDB_ota_control: response = (uint8) (processCtrlPacket(writeStatus->value.data) ? 0 : 1); gecko_cmd_gatt_server_send_user_write_response(writeStatus->connection, writeStatus->characteristic, @@ -70,17 +79,20 @@ static void user_write(struct gecko_cmd_packet *evt) { void dfu_main(void) { //EMU_init(); //CMU_init(); + printf("Started V2\n"); - if(USER_AAT->type != APP_ADDRESS_TABLE_TYPE) + if (USER_BLAT->type != APP_APP_ADDRESS_TYPE) enterDfu = true; - if(!enterDfu) { - SCB->VTOR=(uint32_t)USER_AAT->vectorTable; + if (!enterDfu) { + SCB->VTOR = (uint32_t) USER_BLAT->vectorTable; //Use stack from aat - asm("mov sp,%0" :: "r" (USER_AAT->topOfStack)); - USER_AAT->resetVector(); + asm("mov sp,%0"::"r" (USER_BLAT->topOfStack)); + USER_BLAT->resetVector(); } + CRYPTO_AES_DecryptKey256(CRYPTO, deKey, ota_key); gecko_init(&config); + gecko_cmd_le_gap_set_conn_parameters(MIN_CONN_INTERVAL, MAX_CONN_INTERVAL, LATENCY, SUPERV_TIMEOUT); printf("Stack initialised\n"); @@ -92,7 +104,7 @@ void dfu_main(void) { evt = gecko_wait_event(); /* Handle events */ -#if DEBUG +#if defined(DEBUG) && false unsigned id = BGLIB_MSG_ID(evt->header) & ~gecko_dev_type_gecko; if (id != (gecko_evt_hardware_soft_timer_id & ~gecko_dev_type_gecko)) { if (id & gecko_msg_type_evt) { @@ -120,7 +132,6 @@ void dfu_main(void) { /* Start general advertising and enable connections. */ gecko_cmd_le_gap_set_mode(le_gap_general_discoverable, le_gap_undirected_connectable); - break; case gecko_evt_le_connection_opened_id: @@ -129,8 +140,12 @@ void dfu_main(void) { case gecko_evt_le_connection_closed_id: printf("Connection closed\n"); - /* Restart advertising after client has disconnected */ - gecko_cmd_le_gap_set_mode(le_gap_general_discoverable, le_gap_undirected_connectable); + if (doReset) { + printf("Resetting....\n"); + SCB->AIRCR = RESET_REQUEST; + } else + /* Restart advertising after client has disconnected */ + gecko_cmd_le_gap_set_mode(le_gap_general_discoverable, le_gap_undirected_connectable); break; case gecko_evt_gatt_server_characteristic_status_id: diff --git a/bootload/src/em_crypto.c b/bootload/src/em_crypto.c new file mode 100644 index 0000000..0a83687 --- /dev/null +++ b/bootload/src/em_crypto.c @@ -0,0 +1,1840 @@ +/***************************************************************************//** + * @file em_crypto.c + * @brief Cryptography accelerator peripheral API + * @version 5.0.0 + ******************************************************************************* + * @section License + * Copyright 2016 Silicon Laboratories, Inc. http://www.silabs.com + ******************************************************************************* + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software.@n + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software.@n + * 3. This notice may not be removed or altered from any source distribution. + * + * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Labs has no + * obligation to support this Software. Silicon Labs is providing the + * Software "AS IS", with no express or implied warranties of any kind, + * including, but not limited to, any implied warranties of merchantability + * or fitness for any particular purpose or warranties against infringement + * of any proprietary rights of a third party. + * + * Silicon Labs will not be liable for any consequential, incidental, or + * special damages, or any other relief, or for any claim by any third party, + * arising from your use of this Software. + * + ******************************************************************************/ +#include "em_device.h" + +#if defined(CRYPTO_COUNT) && (CRYPTO_COUNT > 0) + +#include "em_crypto.h" +#include "em_assert.h" + +/***************************************************************************//** + * @addtogroup emlib + * @{ + ******************************************************************************/ + +/***************************************************************************//** + * @addtogroup CRYPTO + * @{ + ******************************************************************************/ + +/******************************************************************************* + ******************************* DEFINES *********************************** + ******************************************************************************/ + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ + +#define CRYPTO_INSTRUCTIONS_PER_REG (4) +#define CRYPTO_INSTRUCTIONS_MAX (12) +#define CRYPTO_INSTRUCTION_REGS (CRYPTO_INSTRUCTIONS_MAX/CRYPTO_INSTRUCTIONS_PER_REG) + +#define CRYPTO_SHA1_BLOCK_SIZE_IN_BITS (512) +#define CRYPTO_SHA1_BLOCK_SIZE_IN_BYTES (CRYPTO_SHA1_BLOCK_SIZE_IN_BITS/8) +#define CRYPTO_SHA1_BLOCK_SIZE_IN_32BIT_WORDS (CRYPTO_SHA1_BLOCK_SIZE_IN_BYTES/sizeof(uint32_t)) +#define CRYPTO_SHA1_DIGEST_SIZE_IN_32BIT_WORDS (CRYPTO_SHA1_DIGEST_SIZE_IN_BYTES/sizeof(uint32_t)) + +#define CRYPTO_SHA256_BLOCK_SIZE_IN_BITS (512) +#define CRYPTO_SHA256_BLOCK_SIZE_IN_BYTES (CRYPTO_SHA256_BLOCK_SIZE_IN_BITS/8) +#define CRYPTO_SHA256_BLOCK_SIZE_IN_32BIT_WORDS (CRYPTO_SHA256_BLOCK_SIZE_IN_BYTES/sizeof(uint32_t)) + +#define CRYPTO_SHA256_DIGEST_SIZE_IN_32BIT_WORDS (CRYPTO_SHA256_DIGEST_SIZE_IN_BYTES/sizeof(uint32_t)) + +#define PARTIAL_OPERAND_WIDTH_LOG2 (7) /* 2^7 = 128 */ +#define PARTIAL_OPERAND_WIDTH (1<WAC & (~(_CRYPTO_WAC_MODULUS_MASK | _CRYPTO_WAC_MODOP_MASK)); + + switch (modulusId) + { + case cryptoModulusBin256: + case cryptoModulusBin128: + case cryptoModulusGcmBin128: + case cryptoModulusEccB233: + case cryptoModulusEccB163: +#ifdef _CRYPTO_WAC_MODULUS_ECCBIN233N + case cryptoModulusEccB233Order: + case cryptoModulusEccB233KOrder: + case cryptoModulusEccB163Order: + case cryptoModulusEccB163KOrder: +#endif + crypto->WAC = temp | modulusId | CRYPTO_WAC_MODOP_BINARY; + break; + + case cryptoModulusEccP256: + case cryptoModulusEccP224: + case cryptoModulusEccP192: +#ifdef _CRYPTO_WAC_MODULUS_ECCPRIME256P + case cryptoModulusEccP256Order: + case cryptoModulusEccP224Order: + case cryptoModulusEccP192Order: +#endif + crypto->WAC = temp | modulusId | CRYPTO_WAC_MODOP_REGULAR; + break; + + default: + /* Unknown modulus identifier. */ + EFM_ASSERT(0); + } +} + +/***************************************************************************//** + * @brief + * Read the key value currently used by the CRYPTO module. + * + * @details + * Read 128 bits or 256 bits from KEY register in the CRYPTO module. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] val + * Value of the data to write to the KEYBUF register. + * + * @param[in] keyWidth + * Key width - 128 or 256 bits + ******************************************************************************/ +void CRYPTO_KeyRead(CRYPTO_TypeDef * crypto, + CRYPTO_KeyBuf_TypeDef val, + CRYPTO_KeyWidth_TypeDef keyWidth) +{ + EFM_ASSERT(val); + + CRYPTO_BurstFromCrypto(&crypto->KEY, &val[0]); + if (keyWidth == cryptoKey256Bits) + { + CRYPTO_BurstFromCrypto(&crypto->KEY, &val[4]); + } +} + +/***************************************************************************//** + * @brief + * Perform a SHA-1 hash operation on a message. + * + * @details + * This function performs a SHA-1 hash operation on the message specified by + * msg with length msgLen, and returns the message digest in msgDigest. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] msg + * Message to hash. + * + * @param[in] msgLen + * Length of message in bytes. + * + * @param[out] msgDigest + * Message digest. + ******************************************************************************/ +void CRYPTO_SHA_1(CRYPTO_TypeDef * crypto, + const uint8_t * msg, + uint64_t msgLen, + CRYPTO_SHA1_Digest_TypeDef msgDigest) +{ + uint32_t temp; + uint32_t len; + int blockLen; + uint32_t shaBlock[CRYPTO_SHA1_BLOCK_SIZE_IN_32BIT_WORDS]= + { + /* Initial value */ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 + }; + uint8_t * p8ShaBlock = (uint8_t *) shaBlock; + + /* Initialize crypto module to do SHA-1. */ + crypto->CTRL = CRYPTO_CTRL_SHA_SHA1; + crypto->SEQCTRL = 0; + crypto->SEQCTRLB = 0; + + /* Set result width of MADD32 operation. */ + CRYPTO_ResultWidthSet(crypto, cryptoResult256Bits); + + /* Write init value to DDATA1. */ + CRYPTO_DDataWrite(&crypto->DDATA1, shaBlock); + + /* Copy data to DDATA0 and select DDATA0 and DDATA1 for SHA operation. */ + CRYPTO_EXECUTE_2(crypto, + CRYPTO_CMD_INSTR_DDATA1TODDATA0, + CRYPTO_CMD_INSTR_SELDDATA0DDATA1); + + len = msgLen; + + while (len >= CRYPTO_SHA1_BLOCK_SIZE_IN_BYTES) + { + /* Write block to QDATA1. */ + CRYPTO_QDataWrite(&crypto->QDATA1BIG, (uint32_t *) msg); + + /* Execute SHA */ + CRYPTO_EXECUTE_3(crypto, + CRYPTO_CMD_INSTR_SHA, + CRYPTO_CMD_INSTR_MADD32, + CRYPTO_CMD_INSTR_DDATA0TODDATA1); + + len -= CRYPTO_SHA1_BLOCK_SIZE_IN_BYTES; + msg += CRYPTO_SHA1_BLOCK_SIZE_IN_BYTES; + } + + blockLen = 0; + + /* Build the last (or second to last) block */ + for (; len; len--) + p8ShaBlock[blockLen++] = *msg++; + + /* append the '1' bit */ + p8ShaBlock[blockLen++] = 0x80; + + /* if the length is currently above 56 bytes we append zeros + * then compress. Then we can fall back to padding zeros and length + * encoding like normal. + */ + if (blockLen > 56) + { + while (blockLen < 64) + p8ShaBlock[blockLen++] = 0; + + /* Write block to QDATA1BIG. */ + CRYPTO_QDataWrite(&crypto->QDATA1BIG, shaBlock); + + /* Execute SHA */ + CRYPTO_EXECUTE_3(crypto, + CRYPTO_CMD_INSTR_SHA, + CRYPTO_CMD_INSTR_MADD32, + CRYPTO_CMD_INSTR_DDATA0TODDATA1); + blockLen = 0; + } + + /* pad upto 56 bytes of zeroes */ + while (blockLen < 56) + p8ShaBlock[blockLen++] = 0; + + /* And finally, encode the message length. */ + { + uint64_t msgLenInBits = msgLen << 3; + temp = msgLenInBits >> 32; + *(uint32_t*)&p8ShaBlock[56] = SWAP32(temp); + temp = msgLenInBits & 0xFFFFFFFF; + *(uint32_t*)&p8ShaBlock[60] = SWAP32(temp); + } + + /* Write block to QDATA1BIG. */ + CRYPTO_QDataWrite(&crypto->QDATA1BIG, shaBlock); + + /* Execute SHA */ + CRYPTO_EXECUTE_3(crypto, + CRYPTO_CMD_INSTR_SHA, + CRYPTO_CMD_INSTR_MADD32, + CRYPTO_CMD_INSTR_DDATA0TODDATA1); + + /* Read resulting message digest from DDATA0BIG. */ + ((uint32_t*)msgDigest)[0] = crypto->DDATA0BIG; + ((uint32_t*)msgDigest)[1] = crypto->DDATA0BIG; + ((uint32_t*)msgDigest)[2] = crypto->DDATA0BIG; + ((uint32_t*)msgDigest)[3] = crypto->DDATA0BIG; + ((uint32_t*)msgDigest)[4] = crypto->DDATA0BIG; + temp = crypto->DDATA0BIG; + temp = crypto->DDATA0BIG; + temp = crypto->DDATA0BIG; +} + +/***************************************************************************//** + * @brief + * Perform a SHA-256 hash operation on a message. + * + * @details + * This function performs a SHA-256 hash operation on the message specified + * by msg with length msgLen, and returns the message digest in msgDigest. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] msg + * Message to hash. + * + * @param[in] msgLen + * Length of message in bytes. + * + * @param[out] msgDigest + * Message digest. + ******************************************************************************/ +void CRYPTO_SHA_256(CRYPTO_TypeDef * crypto, + const uint8_t * msg, + uint64_t msgLen, + CRYPTO_SHA256_Digest_TypeDef msgDigest) +{ + uint32_t temp; + uint32_t len; + int blockLen; + uint32_t shaBlock[CRYPTO_SHA256_BLOCK_SIZE_IN_32BIT_WORDS]= + { + /* Initial value */ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + }; + uint8_t * p8ShaBlock = (uint8_t *) shaBlock; + + /* Initialize crypyo module to do SHA-256 (SHA-2). */ + crypto->CTRL = CRYPTO_CTRL_SHA_SHA2; + crypto->SEQCTRL = 0; + crypto->SEQCTRLB = 0; + + /* Set result width of MADD32 operation. */ + CRYPTO_ResultWidthSet(crypto, cryptoResult256Bits); + + /* Write init value to DDATA1. */ + CRYPTO_DDataWrite(&crypto->DDATA1, shaBlock); + + /* Copy data ot DDATA0 and select DDATA0 and DDATA1 for SHA operation. */ + CRYPTO_EXECUTE_2(crypto, + CRYPTO_CMD_INSTR_DDATA1TODDATA0, + CRYPTO_CMD_INSTR_SELDDATA0DDATA1); + len = msgLen; + + while (len >= CRYPTO_SHA256_BLOCK_SIZE_IN_BYTES) + { + /* Write block to QDATA1BIG. */ + CRYPTO_QDataWrite(&crypto->QDATA1BIG, (uint32_t *) msg); + + /* Execute SHA */ + CRYPTO_EXECUTE_3(crypto, + CRYPTO_CMD_INSTR_SHA, + CRYPTO_CMD_INSTR_MADD32, + CRYPTO_CMD_INSTR_DDATA0TODDATA1); + + len -= CRYPTO_SHA256_BLOCK_SIZE_IN_BYTES; + msg += CRYPTO_SHA256_BLOCK_SIZE_IN_BYTES; + } + + blockLen = 0; + + /* Build the last (or second to last) block */ + for (; len; len--) + p8ShaBlock[blockLen++] = *msg++; + + /* append the '1' bit */ + p8ShaBlock[blockLen++] = 0x80; + + /* if the length is currently above 56 bytes we append zeros + * then compress. Then we can fall back to padding zeros and length + * encoding like normal. + */ + if (blockLen > 56) + { + while (blockLen < 64) + p8ShaBlock[blockLen++] = 0; + + /* Write block to QDATA1BIG. */ + CRYPTO_QDataWrite(&crypto->QDATA1BIG, shaBlock); + + /* Execute SHA */ + CRYPTO_EXECUTE_3(crypto, + CRYPTO_CMD_INSTR_SHA, + CRYPTO_CMD_INSTR_MADD32, + CRYPTO_CMD_INSTR_DDATA0TODDATA1); + blockLen = 0; + } + + /* Pad upto 56 bytes of zeroes */ + while (blockLen < 56) + p8ShaBlock[blockLen++] = 0; + + /* And finally, encode the message length. */ + { + uint64_t msgLenInBits = msgLen << 3; + temp = msgLenInBits >> 32; + *(uint32_t *)&p8ShaBlock[56] = SWAP32(temp); + temp = msgLenInBits & 0xFFFFFFFF; + *(uint32_t *)&p8ShaBlock[60] = SWAP32(temp); + } + + /* Write the final block to QDATA1BIG. */ + CRYPTO_QDataWrite(&crypto->QDATA1BIG, shaBlock); + + /* Execute SHA */ + CRYPTO_EXECUTE_3(crypto, + CRYPTO_CMD_INSTR_SHA, + CRYPTO_CMD_INSTR_MADD32, + CRYPTO_CMD_INSTR_DDATA0TODDATA1); + + /* Read resulting message digest from DDATA0BIG. */ + CRYPTO_DDataRead(&crypto->DDATA0BIG, (uint32_t *)msgDigest); +} + +/***************************************************************************//** + * @brief + * Set 32bit word array to zero. + * + * @param[in] words32bits Pointer to 32bit word array + * @param[in] num32bitWords Number of 32bit words in array + ******************************************************************************/ +__STATIC_INLINE void cryptoBigintZeroize(uint32_t * words32bits, + int num32bitWords) +{ + while (num32bitWords--) + *words32bits++ = 0; +} + +/***************************************************************************//** + * @brief + * Increment value of 32bit word array by one. + * + * @param[in] words32bits Pointer to 32bit word array + * @param[in] num32bitWords Number of 32bit words in array + ******************************************************************************/ +__STATIC_INLINE void cryptoBigintIncrement(uint32_t * words32bits, + int num32bitWords) +{ + int i; + for (i=0; i>5; + int numPartialOperandsA = numWordsLastOperandA ? + (aSize >> PARTIAL_OPERAND_WIDTH_LOG2) + 1 : + aSize >> PARTIAL_OPERAND_WIDTH_LOG2; + int numWordsLastOperandB = (bSize&PARTIAL_OPERAND_WIDTH_MASK)>>5; + int numPartialOperandsB = numWordsLastOperandB ? + (bSize >> PARTIAL_OPERAND_WIDTH_LOG2) + 1 : + bSize >> PARTIAL_OPERAND_WIDTH_LOG2; + int numWordsLastOperandR = (rSize&PARTIAL_OPERAND_WIDTH_MASK)>>5; + int numPartialOperandsR = numWordsLastOperandR ? + (rSize >> PARTIAL_OPERAND_WIDTH_LOG2) + 1 : + rSize >> PARTIAL_OPERAND_WIDTH_LOG2; + EFM_ASSERT(numPartialOperandsA + numPartialOperandsB <= numPartialOperandsR); +#else + int numPartialOperandsA = aSize >> PARTIAL_OPERAND_WIDTH_LOG2; + int numPartialOperandsB = bSize >> PARTIAL_OPERAND_WIDTH_LOG2; + EFM_ASSERT((aSize & PARTIAL_OPERAND_WIDTH_MASK) == 0); + EFM_ASSERT((bSize & PARTIAL_OPERAND_WIDTH_MASK) == 0); +#endif + EFM_ASSERT(aSize + bSize <= rSize); + + /* Set R to zero. */ + cryptoBigintZeroize(R, rSize >> 5); + + /* Set multiplication width. */ + crypto->WAC = CRYPTO_WAC_MULWIDTH_MUL128 | CRYPTO_WAC_RESULTWIDTH_256BIT; + + /* Setup DMA request signalling in order for MCU to run in parallel with + CRYPTO instruction sequence execution, and prepare data loading which + can take place immediately when CRYPTO is ready inside the instruction + sequence. */ + crypto->CTRL = + CRYPTO_CTRL_DMA0RSEL_DATA0 | CRYPTO_CTRL_DMA0MODE_FULL | + CRYPTO_CTRL_DMA1RSEL_DATA1 | CRYPTO_CTRL_DMA1MODE_FULL; + + CRYPTO_EXECUTE_4(crypto, + CRYPTO_CMD_INSTR_CCLR, /* Carry = 0 */ + CRYPTO_CMD_INSTR_CLR, /* DDATA0 = 0 */ + /* clear result accumulation register */ + CRYPTO_CMD_INSTR_DDATA0TODDATA2, + CRYPTO_CMD_INSTR_SELDDATA1DDATA3); + /* + register map: + DDATA0: working register + DDATA1: B(j) + DDATA2: R(i+j+1) and R(i+j), combined with DMA entry for B(j) + DDATA3: A(i) + */ + + CRYPTO_SEQ_LOAD_10(crypto, + /* Temporarily load partial operand B(j) to DATA0. */ + /* R(i+j+1) is still in DATA1 */ + CRYPTO_CMD_INSTR_DMA0TODATA, + /* Move B(j) to DDATA1 */ + CRYPTO_CMD_INSTR_DDATA2TODDATA1, + + /* Restore previous partial result (now R(i+j)) */ + CRYPTO_CMD_INSTR_DATA1TODATA0, + + /* Load next partial result R(i+j+1) */ + CRYPTO_CMD_INSTR_DMA1TODATA, + + /* Execute partial multiplication A(i)inDDATA1 * B(j)inDDATA3*/ + CRYPTO_CMD_INSTR_MULO, + + /* Add the result to the previous partial result */ + /* AND take the previous carry value into account */ + /* at the right place (bit 128, ADDIC instruction */ + CRYPTO_CMD_INSTR_SELDDATA0DDATA2, + CRYPTO_CMD_INSTR_ADDIC, + + /* Save the new partial result (lower half) */ + CRYPTO_CMD_INSTR_DDATA0TODDATA2, + CRYPTO_CMD_INSTR_DATATODMA0, + /* Reset the operand selector for next*/ + CRYPTO_CMD_INSTR_SELDDATA2DDATA3 + ); + + /**************** End Initializations ******************/ + + for(i=0; i>(i*PARTIAL_OPERAND_WIDTH) to DDATA1. */ +#ifdef USE_VARIABLE_SIZED_DATA_LOADS + if ( (numWordsLastOperandA != 0) && ( i == numPartialOperandsA-1 ) ) + CRYPTO_DataWriteVariableSize(&crypto->DATA2, + &A[i*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS], + numWordsLastOperandA); + else + CRYPTO_DataWrite(&crypto->DATA2, &A[i*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#else + CRYPTO_DataWrite(&crypto->DATA2, &A[i*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#endif + + /* Load partial result in R>>(i*PARTIAL_OPERAND_WIDTH) to DATA1. */ +#ifdef USE_VARIABLE_SIZED_DATA_LOADS + if ( (numWordsLastOperandR != 0) && ( i == numPartialOperandsR-1 ) ) + CRYPTO_DataWriteVariableSize(&crypto->DATA1, + &R[i*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS], + numWordsLastOperandR); + else + CRYPTO_DataWrite(&crypto->DATA1, &R[i*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#else + CRYPTO_DataWrite(&crypto->DATA1, &R[i*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#endif + + /* Clear carry */ + crypto->CMD = CRYPTO_CMD_INSTR_CCLR; + + /* Setup number of sequence iterations and block size. */ + crypto->SEQCTRL = CRYPTO_SEQCTRL_BLOCKSIZE_16BYTES + | (PARTIAL_OPERAND_WIDTH_IN_BYTES * numPartialOperandsB); + + /* Execute the MULtiply instruction sequence. */ + CRYPTO_InstructionSequenceExecute(crypto); + + for (j=0; j>(j*`PARTIAL_OPERAND_WIDTH) to DDATA2 + (via DATA0). */ +#ifdef USE_VARIABLE_SIZED_DATA_LOADS + if ( (numWordsLastOperandB != 0) && ( j == numPartialOperandsB-1 ) ) + CRYPTO_DataWriteVariableSize(&crypto->DATA0, + &B[j*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS], + numWordsLastOperandB); + else + CRYPTO_DataWrite(&crypto->DATA0, + &B[j*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#else + CRYPTO_DataWrite(&crypto->DATA0, + &B[j*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#endif + + /* Load most significant partial result + R>>((i+j+1)*`PARTIAL_OPERAND_WIDTH) into DATA1. */ +#ifdef USE_VARIABLE_SIZED_DATA_LOADS + if ( (numWordsLastOperandR != 0) && ( (i+j+1) == numPartialOperandsR-1 ) ) + CRYPTO_DataWriteVariableSize(&crypto->DATA1, + &R[(i+j+1)*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS], + numWordsLastOperandR); + else + CRYPTO_DataWrite(&crypto->DATA1, + &R[(i+j+1)*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#else + CRYPTO_DataWrite(&crypto->DATA1, + &R[(i+j+1)*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); +#endif + /* Store least significant partial result */ + CRYPTO_DataRead(&crypto->DATA0, + &R[(i+j)*PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); + + } /* for (j=0; jDATA1, + &R[(i+numPartialOperandsB) + * PARTIAL_OPERAND_WIDTH_IN_32BIT_WORDS]); + + } /* for (i=0; iXOR +-------------->XOR + * | | | + * V | V + * +--------------+ | +--------------+ + * Key ->| Block cipher | | Key ->| Block cipher | + * | encryption | | | encryption | + * +--------------+ | +--------------+ + * |---------+ | + * V V + * Ciphertext Ciphertext + * @endverbatim + * Decryption: + * @verbatim + * Ciphertext Ciphertext + * |----------+ | + * V | V + * +--------------+ | +--------------+ + * Key ->| Block cipher | | Key ->| Block cipher | + * | decryption | | | decryption | + * +--------------+ | +--------------+ + * | | | + * V | V + * InitVector ->XOR +-------------->XOR + * | | + * V V + * Plaintext Plaintext + * @endverbatim + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * When doing encryption, this is the 128 bit encryption key. When doing + * decryption, this is the 128 bit decryption key. The decryption key may + * be generated from the encryption key with CRYPTO_AES_DecryptKey128(). + * If this argument is null, the key will not be loaded, as it is assumed + * the key has been loaded into KEYHA previously. + * + * @param[in] iv + * 128 bit initialization vector to use. + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + ******************************************************************************/ +void CRYPTO_AES_CBC128(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES128; + CRYPTO_AES_CBCx(crypto, out, in, len, key, iv, encrypt, cryptoKey128Bits); +} + +/***************************************************************************//** + * @brief + * AES Cipher-block chaining (CBC) cipher mode encryption/decryption, 256 bit + * key. + * + * @details + * Please see CRYPTO_AES_CBC128() for CBC figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * When doing encryption, this is the 256 bit encryption key. When doing + * decryption, this is the 256 bit decryption key. The decryption key may + * be generated from the encryption key with CRYPTO_AES_DecryptKey256(). + * + * @param[in] iv + * 128 bit initialization vector to use. + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + ******************************************************************************/ +void CRYPTO_AES_CBC256(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES256; + CRYPTO_AES_CBCx(crypto, out, in, len, key, iv, encrypt, cryptoKey256Bits); +} + +/***************************************************************************//** + * @brief + * AES Cipher feedback (CFB) cipher mode encryption/decryption, 128 bit key. + * + * @details + * Encryption: + * @verbatim + * InitVector +----------------+ + * | | | + * V | V + * +--------------+ | +--------------+ + * Key ->| Block cipher | | Key ->| Block cipher | + * | encryption | | | encryption | + * +--------------+ | +--------------+ + * | | | + * V | V + * Plaintext ->XOR | Plaintext ->XOR + * |---------+ | + * V V + * Ciphertext Ciphertext + * @endverbatim + * Decryption: + * @verbatim + * InitVector +----------------+ + * | | | + * V | V + * +--------------+ | +--------------+ + * Key ->| Block cipher | | Key ->| Block cipher | + * | encryption | | | encryption | + * +--------------+ | +--------------+ + * | | | + * V | V + * XOR<- Ciphertext XOR<- Ciphertext + * | | + * V V + * Plaintext Plaintext + * @endverbatim + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 128 bit encryption key is used for both encryption and decryption modes. + * + * @param[in] iv + * 128 bit initialization vector to use. + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + ******************************************************************************/ +void CRYPTO_AES_CFB128(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES128; + CRYPTO_AES_CFBx(crypto, out, in, len, key, iv, encrypt, cryptoKey128Bits); +} + +/***************************************************************************//** + * @brief + * AES Cipher feedback (CFB) cipher mode encryption/decryption, 256 bit key. + * + * @details + * Please see CRYPTO_AES_CFB128() for CFB figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 256 bit encryption key is used for both encryption and decryption modes. + * + * @param[in] iv + * 128 bit initialization vector to use. + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + ******************************************************************************/ +void CRYPTO_AES_CFB256(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES256; + CRYPTO_AES_CFBx(crypto, out, in, len, key, iv, encrypt, cryptoKey256Bits); +} + +/***************************************************************************//** + * @brief + * AES Counter (CTR) cipher mode encryption/decryption, 128 bit key. + * + * @details + * Encryption: + * @verbatim + * Counter Counter + * | | + * V V + * +--------------+ +--------------+ + * Key ->| Block cipher | Key ->| Block cipher | + * | encryption | | encryption | + * +--------------+ +--------------+ + * | | + * Plaintext ->XOR Plaintext ->XOR + * | | + * V V + * Ciphertext Ciphertext + * @endverbatim + * Decryption: + * @verbatim + * Counter Counter + * | | + * V V + * +--------------+ +--------------+ + * Key ->| Block cipher | Key ->| Block cipher | + * | encryption | | encryption | + * +--------------+ +--------------+ + * | | + * Ciphertext ->XOR Ciphertext ->XOR + * | | + * V V + * Plaintext Plaintext + * @endverbatim + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 128 bit encryption key. + * If this argument is null, the key will not be loaded, as it is assumed + * the key has been loaded into KEYHA previously. + * + * @param[in,out] ctr + * 128 bit initial counter value. The counter is updated after each AES + * block encoding through use of @p ctrFunc. + * + * @param[in] ctrFunc + * Function used to update counter value. Not supported by CRYPTO. + * This parameter is included in order for backwards compatibility with + * the EFM32 em_aes.h API. + ******************************************************************************/ +void CRYPTO_AES_CTR128(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + uint8_t * ctr, + CRYPTO_AES_CtrFuncPtr_TypeDef ctrFunc) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES128; + CRYPTO_AES_CTRx(crypto, out, in, len, key, ctr, ctrFunc, cryptoKey128Bits); +} + +/***************************************************************************//** + * @brief + * AES Counter (CTR) cipher mode encryption/decryption, 256 bit key. + * + * @details + * Please see CRYPTO_AES_CTR128() for CTR figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 256 bit encryption key. + * + * @param[in,out] ctr + * 128 bit initial counter value. The counter is updated after each AES + * block encoding through use of @p ctrFunc. + * + * @param[in] ctrFunc + * Function used to update counter value. Not supported by CRYPTO. + * This parameter is included in order for backwards compatibility with + * the EFM32 em_aes.h API. + ******************************************************************************/ +void CRYPTO_AES_CTR256(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + uint8_t * ctr, + CRYPTO_AES_CtrFuncPtr_TypeDef ctrFunc) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES256; + CRYPTO_AES_CTRx(crypto, out, in, len, key, ctr, ctrFunc, cryptoKey256Bits); +} + +/***************************************************************************//** + * @brief + * Update last 32 bits of 128 bit counter, by incrementing with 1. + * + * @details + * Notice that no special consideration is given to possible wrap around. If + * 32 least significant bits are 0xFFFFFFFF, they will be updated to 0x00000000, + * ignoring overflow. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in,out] ctr + * Buffer holding 128 bit counter to be updated. + ******************************************************************************/ +void CRYPTO_AES_CTRUpdate32Bit(uint8_t * ctr) +{ + uint32_t * _ctr = (uint32_t *) ctr; + + _ctr[3] = __REV(__REV(_ctr[3]) + 1); +} + +/***************************************************************************//** + * @brief + * Generate 128 bit AES decryption key from 128 bit encryption key. The + * decryption key is used for some cipher modes when decrypting. + * + * @details + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place 128 bit decryption key. Must be at least 16 bytes long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding 128 bit encryption key. Must be at least 16 bytes long. + ******************************************************************************/ +void CRYPTO_AES_DecryptKey128(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in) +{ + uint32_t * _out = (uint32_t *) out; + const uint32_t * _in = (const uint32_t *) in; + + /* Load key */ + CRYPTO_BurstToCrypto(&crypto->KEYBUF, &_in[0]); + + /* Do dummy encryption to generate decrypt key */ + crypto->CTRL = CRYPTO_CTRL_AES_AES128; + CRYPTO_IntClear(crypto, CRYPTO_IF_INSTRDONE); + crypto->CMD = CRYPTO_CMD_INSTR_AESENC; + + /* Save decryption key */ + CRYPTO_BurstFromCrypto(&crypto->KEY, &_out[0]); +} + +/***************************************************************************//** + * @brief + * Generate 256 bit AES decryption key from 256 bit encryption key. The + * decryption key is used for some cipher modes when decrypting. + * + * @details + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place 256 bit decryption key. Must be at least 32 bytes long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding 256 bit encryption key. Must be at least 32 bytes long. + ******************************************************************************/ +void CRYPTO_AES_DecryptKey256(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in) +{ + uint32_t * _out = (uint32_t *) out; + const uint32_t * _in = (const uint32_t *) in; + + crypto->CTRL = CRYPTO_CTRL_AES_AES256; + CRYPTO_IntClear(crypto, CRYPTO_IF_INSTRDONE); + /* Load key */ + CRYPTO_BurstToCrypto(&crypto->KEYBUF, &_in[0]); + CRYPTO_BurstToCrypto(&crypto->KEYBUF, &_in[4]); + + /* Do dummy encryption to generate decrypt key */ + crypto->CMD = CRYPTO_CMD_INSTR_AESENC; + + /* Save decryption key */ + CRYPTO_BurstFromCrypto(&crypto->KEY, &_out[0]); + CRYPTO_BurstFromCrypto(&crypto->KEY, &_out[4]); +} + +/***************************************************************************//** + * @brief + * AES Electronic Codebook (ECB) cipher mode encryption/decryption, + * 128 bit key. + * + * @details + * Encryption: + * @verbatim + * Plaintext Plaintext + * | | + * V V + * +--------------+ +--------------+ + * Key ->| Block cipher | Key ->| Block cipher | + * | encryption | | encryption | + * +--------------+ +--------------+ + * | | + * V V + * Ciphertext Ciphertext + * @endverbatim + * Decryption: + * @verbatim + * Ciphertext Ciphertext + * | | + * V V + * +--------------+ +--------------+ + * Key ->| Block cipher | Key ->| Block cipher | + * | decryption | | decryption | + * +--------------+ +--------------+ + * | | + * V V + * Plaintext Plaintext + * @endverbatim + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * When doing encryption, this is the 128 bit encryption key. When doing + * decryption, this is the 128 bit decryption key. The decryption key may + * be generated from the encryption key with CRYPTO_AES_DecryptKey128(). + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + ******************************************************************************/ +void CRYPTO_AES_ECB128(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + bool encrypt) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES128; + CRYPTO_AES_ECBx(crypto, out, in, len, key, encrypt, cryptoKey128Bits); +} + +/***************************************************************************//** + * @brief + * AES Electronic Codebook (ECB) cipher mode encryption/decryption, + * 256 bit key. + * + * @details + * Please see CRYPTO_AES_ECB128() for ECB figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * When doing encryption, this is the 256 bit encryption key. When doing + * decryption, this is the 256 bit decryption key. The decryption key may + * be generated from the encryption key with CRYPTO_AES_DecryptKey256(). + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + ******************************************************************************/ +void CRYPTO_AES_ECB256(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + bool encrypt) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES256; + CRYPTO_AES_ECBx(crypto, out, in, len, key, encrypt, cryptoKey256Bits); +} + +/***************************************************************************//** + * @brief + * AES Output feedback (OFB) cipher mode encryption/decryption, 128 bit key. + * + * @details + * Encryption: + * @verbatim + * InitVector +----------------+ + * | | | + * V | V + * +--------------+ | +--------------+ + * Key ->| Block cipher | | Key ->| Block cipher | + * | encryption | | | encryption | + * +--------------+ | +--------------+ + * | | | + * |---------+ | + * V V + * Plaintext ->XOR Plaintext ->XOR + * | | + * V V + * Ciphertext Ciphertext + * @endverbatim + * Decryption: + * @verbatim + * InitVector +----------------+ + * | | | + * V | V + * +--------------+ | +--------------+ + * Key ->| Block cipher | | Key ->| Block cipher | + * | encryption | | | encryption | + * +--------------+ | +--------------+ + * | | | + * |---------+ | + * V V + * Ciphertext ->XOR Ciphertext ->XOR + * | | + * V V + * Plaintext Plaintext + * @endverbatim + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 128 bit encryption key. + * + * @param[in] iv + * 128 bit initialization vector to use. + ******************************************************************************/ +void CRYPTO_AES_OFB128(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES128; + CRYPTO_AES_OFBx(crypto, out, in, len, key, iv, cryptoKey128Bits); +} + +/***************************************************************************//** + * @brief + * AES Output feedback (OFB) cipher mode encryption/decryption, 256 bit key. + * + * @details + * Please see CRYPTO_AES_OFB128() for OFB figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 256 bit encryption key. + * + * @param[in] iv + * 128 bit initialization vector to use. + ******************************************************************************/ +void CRYPTO_AES_OFB256(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv) +{ + crypto->CTRL = CRYPTO_CTRL_AES_AES256; + CRYPTO_AES_OFBx(crypto, out, in, len, key, iv, cryptoKey256Bits); +} + +/******************************************************************************* + ************************** LOCAL FUNCTIONS ******************************* + ******************************************************************************/ + +/***************************************************************************//** + * @brief + * Cipher-block chaining (CBC) cipher mode encryption/decryption, 128/256 bit key. + * + * @details + * Please see CRYPTO_AES_CBC128() for CBC figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * When doing encryption, this is the 256 bit encryption key. When doing + * decryption, this is the 256 bit decryption key. The decryption key may + * be generated from the encryption key with CRYPTO_AES_DecryptKey256(). + * + * @param[in] iv + * 128 bit initialization vector to use. + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + * + * @param[in] keyWidth + * Set to cryptoKey128Bits or cryptoKey256Bits. + ******************************************************************************/ +static void CRYPTO_AES_CBCx(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt, + CRYPTO_KeyWidth_TypeDef keyWidth) +{ + EFM_ASSERT(!(len % CRYPTO_AES_BLOCKSIZE)); + + /* Initialize control registers. */ + crypto->WAC = 0; + + CRYPTO_KeyBufWrite(crypto, (uint32_t *)key, keyWidth); + + if (encrypt) + { + CRYPTO_DataWrite(&crypto->DATA0, (uint32_t *)iv); + + crypto->SEQ0 = + CRYPTO_CMD_INSTR_DATA1TODATA0XOR << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_AESENC << _CRYPTO_SEQ0_INSTR1_SHIFT; + + CRYPTO_AES_ProcessLoop(crypto, len, + &crypto->DATA1, (uint32_t *) in, + &crypto->DATA0, (uint32_t *) out); + } + else + { + CRYPTO_DataWrite(&crypto->DATA2, (uint32_t *) iv); + + crypto->SEQ0 = + CRYPTO_CMD_INSTR_DATA1TODATA0 << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_AESDEC << _CRYPTO_SEQ0_INSTR1_SHIFT | + CRYPTO_CMD_INSTR_DATA2TODATA0XOR << _CRYPTO_SEQ0_INSTR2_SHIFT | + CRYPTO_CMD_INSTR_DATA1TODATA2 << _CRYPTO_SEQ0_INSTR3_SHIFT; + + crypto->SEQ1 = 0; + + /* The following call is equivalent to the last call in the + 'if( encrypt )' branch. However moving this + call outside the conditional scope results in slightly poorer + performance for some compiler optimizations. */ + CRYPTO_AES_ProcessLoop(crypto, len, + &crypto->DATA1, (uint32_t *) in, + &crypto->DATA0, (uint32_t *) out); + } +} + +/***************************************************************************//** + * @brief + * Cipher feedback (CFB) cipher mode encryption/decryption, 128/256 bit key. + * + * @details + * Please see CRYPTO_AES_CFB128() for CFB figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 256 bit encryption key is used for both encryption and decryption modes. + * + * @param[in] iv + * 128 bit initialization vector to use. + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + * + * @param[in] keyWidth + * Set to cryptoKey128Bits or cryptoKey256Bits. + ******************************************************************************/ +static void CRYPTO_AES_CFBx(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + bool encrypt, + CRYPTO_KeyWidth_TypeDef keyWidth) +{ + EFM_ASSERT(!(len % CRYPTO_AES_BLOCKSIZE)); + + /* Initialize control registers. */ + crypto->WAC = 0; + + /* Load Key */ + CRYPTO_KeyBufWrite(crypto, (uint32_t *)key, keyWidth); + + /* Load instructions to CRYPTO sequencer. */ + if (encrypt) + { + /* Load IV */ + CRYPTO_DataWrite(&crypto->DATA0, (uint32_t *)iv); + + crypto->SEQ0 = + CRYPTO_CMD_INSTR_AESENC << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_DATA1TODATA0XOR << _CRYPTO_SEQ0_INSTR1_SHIFT; + + CRYPTO_AES_ProcessLoop(crypto, len, + &crypto->DATA1, (uint32_t *)in, + &crypto->DATA0, (uint32_t *)out + ); + } + else + { + /* Load IV */ + CRYPTO_DataWrite(&crypto->DATA2, (uint32_t *)iv); + + crypto->SEQ0 = + CRYPTO_CMD_INSTR_DATA2TODATA0 << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_AESENC << _CRYPTO_SEQ0_INSTR1_SHIFT | + CRYPTO_CMD_INSTR_DATA1TODATA0XOR << _CRYPTO_SEQ0_INSTR2_SHIFT | + CRYPTO_CMD_INSTR_DATA1TODATA2 << _CRYPTO_SEQ0_INSTR3_SHIFT; + crypto->SEQ1 = 0; + + CRYPTO_AES_ProcessLoop(crypto, len, + &crypto->DATA1, (uint32_t *)in, + &crypto->DATA0, (uint32_t *)out + ); + } +} + +/***************************************************************************//** + * @brief + * Counter (CTR) cipher mode encryption/decryption, 128/256 bit key. + * + * @details + * Please see CRYPTO_AES_CTR128() for CTR figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 256 bit encryption key. + * + * @param[in,out] ctr + * 128 bit initial counter value. The counter is updated after each AES + * block encoding through use of @p ctrFunc. + * + * @param[in] ctrFunc + * Function used to update counter value. Not supported by CRYPTO. + * This parameter is included in order for backwards compatibility with + * the EFM32 em_aes.h API. + * + * @param[in] keyWidth + * Set to cryptoKey128Bits or cryptoKey256Bits. + ******************************************************************************/ +static void CRYPTO_AES_CTRx(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + uint8_t * ctr, + CRYPTO_AES_CtrFuncPtr_TypeDef ctrFunc, + CRYPTO_KeyWidth_TypeDef keyWidth) +{ + (void) ctrFunc; + + EFM_ASSERT(!(len % CRYPTO_AES_BLOCKSIZE)); + + /* Initialize control registers. */ + crypto->CTRL |= CRYPTO_CTRL_INCWIDTH_INCWIDTH4; + crypto->WAC = 0; + + CRYPTO_KeyBufWrite(crypto, (uint32_t *)key, keyWidth); + + CRYPTO_DataWrite(&crypto->DATA1, (uint32_t *) ctr); + + crypto->SEQ0 = CRYPTO_CMD_INSTR_DATA1TODATA0 << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_AESENC << _CRYPTO_SEQ0_INSTR1_SHIFT | + CRYPTO_CMD_INSTR_DATA0TODATA3 << _CRYPTO_SEQ0_INSTR2_SHIFT | + CRYPTO_CMD_INSTR_DATA1INC << _CRYPTO_SEQ0_INSTR3_SHIFT; + + crypto->SEQ1 = CRYPTO_CMD_INSTR_DATA2TODATA0XOR << _CRYPTO_SEQ1_INSTR4_SHIFT; + + CRYPTO_AES_ProcessLoop(crypto, len, + &crypto->DATA2, (uint32_t *) in, + &crypto->DATA0, (uint32_t *) out); + + CRYPTO_DataRead(&crypto->DATA1, (uint32_t *) ctr); +} + +/***************************************************************************//** + * @brief + * Electronic Codebook (ECB) cipher mode encryption/decryption, 128/256 bit key. + * + * @details + * Please see CRYPTO_AES_ECB128() for ECB figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * When doing encryption, this is the 256 bit encryption key. When doing + * decryption, this is the 256 bit decryption key. The decryption key may + * be generated from the encryption key with CRYPTO_AES_DecryptKey256(). + * + * @param[in] encrypt + * Set to true to encrypt, false to decrypt. + * + * @param[in] keyWidth + * Set to cryptoKey128Bits or cryptoKey256Bits. + ******************************************************************************/ +static void CRYPTO_AES_ECBx(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + bool encrypt, + CRYPTO_KeyWidth_TypeDef keyWidth) +{ + EFM_ASSERT(!(len % CRYPTO_AES_BLOCKSIZE)); + + crypto->WAC = 0; + + CRYPTO_KeyBufWrite(crypto, (uint32_t *)key, keyWidth); + + if (encrypt) + { + crypto->SEQ0 = + (CRYPTO_CMD_INSTR_AESENC << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_DATA0TODATA1 << _CRYPTO_SEQ0_INSTR1_SHIFT); + } + else + { + crypto->SEQ0 = + (CRYPTO_CMD_INSTR_AESDEC << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_DATA0TODATA1 << _CRYPTO_SEQ0_INSTR1_SHIFT); + } + + CRYPTO_AES_ProcessLoop(crypto, len, + &crypto->DATA0, (uint32_t *) in, + &crypto->DATA1, (uint32_t *) out); +} + +/***************************************************************************//** + * @brief + * Output feedback (OFB) cipher mode encryption/decryption, 128/256 bit key. + * + * @details + * Please see CRYPTO_AES_OFB128() for OFB figure. + * + * Please refer to general comments on layout and byte ordering of parameters. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] key + * 256 bit encryption key. + * + * @param[in] iv + * 128 bit initialization vector to use. + * + * @param[in] keyWidth + * Set to cryptoKey128Bits or cryptoKey256Bits. + ******************************************************************************/ +static void CRYPTO_AES_OFBx(CRYPTO_TypeDef * crypto, + uint8_t * out, + const uint8_t * in, + unsigned int len, + const uint8_t * key, + const uint8_t * iv, + CRYPTO_KeyWidth_TypeDef keyWidth) +{ + EFM_ASSERT(!(len % CRYPTO_AES_BLOCKSIZE)); + + crypto->WAC = 0; + + CRYPTO_KeyBufWrite(crypto, (uint32_t *)key, keyWidth); + + CRYPTO_DataWrite(&crypto->DATA2, (uint32_t *)iv); + + crypto->SEQ0 = + CRYPTO_CMD_INSTR_DATA0TODATA1 << _CRYPTO_SEQ0_INSTR0_SHIFT | + CRYPTO_CMD_INSTR_DATA2TODATA0 << _CRYPTO_SEQ0_INSTR1_SHIFT | + CRYPTO_CMD_INSTR_AESENC << _CRYPTO_SEQ0_INSTR2_SHIFT | + CRYPTO_CMD_INSTR_DATA0TODATA2 << _CRYPTO_SEQ0_INSTR3_SHIFT; + crypto->SEQ1 = + CRYPTO_CMD_INSTR_DATA1TODATA0XOR << _CRYPTO_SEQ1_INSTR4_SHIFT | + CRYPTO_CMD_INSTR_DATA0TODATA1 << _CRYPTO_SEQ1_INSTR5_SHIFT; + + CRYPTO_AES_ProcessLoop(crypto, len, + &crypto->DATA0, (uint32_t *) in, + &crypto->DATA1, (uint32_t *) out); +} + +/***************************************************************************//** + * @brief + * Function performs generic AES loop. + * + * @details + * Function loads given register with provided input data. Triggers CRYPTO to + * perform sequence of instructions and read specified output register to + * output buffer. + * + * @param[in] crypto + * Pointer to CRYPTO peripheral register block. + * + * @param[in] len + * Number of bytes to encrypt/decrypt. Must be a multiple of 16. + * + * @param[in] inReg + * Input register - one of DATA0,DATA1,DATA2,DATA3 + * + * @param[in] in + * Buffer holding data to encrypt/decrypt. Must be at least @p len long. + * + * @param[in] outReg + * Output register - one of DATA0,DATA1,DATA2,DATA3 + * + * @param[out] out + * Buffer to place encrypted/decrypted data. Must be at least @p len long. It + * may be set equal to @p in, in which case the input buffer is overwritten. + ******************************************************************************/ +static inline void CRYPTO_AES_ProcessLoop(CRYPTO_TypeDef * crypto, + uint32_t len, + CRYPTO_DataReg_TypeDef inReg, + uint32_t * in, + CRYPTO_DataReg_TypeDef outReg, + uint32_t * out) +{ + len /= CRYPTO_AES_BLOCKSIZE; + crypto->SEQCTRL = 16 << _CRYPTO_SEQCTRL_LENGTHA_SHIFT; + + while (len--) + { + /* Load data and trigger encryption */ + CRYPTO_DataWrite(inReg, (uint32_t *)in); + + crypto->CMD = CRYPTO_CMD_SEQSTART; + + /* Save encrypted/decrypted data */ + CRYPTO_DataRead(outReg, (uint32_t *)out); + + out += 4; + in += 4; + } +} + +/** @} (end addtogroup CRYPTO) */ +/** @} (end addtogroup emlib) */ + +#endif /* defined(CRYPTO_COUNT) && (CRYPTO_COUNT > 0) */ diff --git a/bootload/src/startup.c b/bootload/src/startup.c index 3bbb46d..8d5ca3d 100644 --- a/bootload/src/startup.c +++ b/bootload/src/startup.c @@ -193,6 +193,10 @@ void RFSENSE_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); void FPUEH_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +/* special hook for the routine that enters DFU mode */ + +void EnterDFU_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); + /*---------------------------------------------------------------------------- Exception / Interrupt Vector table @@ -206,7 +210,7 @@ const pFunc __Vectors[] __attribute__ ((section(".vectors"))) = { MemManage_Handler, /* MPU Fault Handler */ BusFault_Handler, /* Bus Fault Handler */ UsageFault_Handler, /* Usage Fault Handler */ - Default_Handler, /* Reserved */ + EnterDFU_Handler, /* Enters DFU mode */ Default_Handler, /* Reserved */ Default_Handler, /* Reserved */ Default_Handler, /* Reserved */ diff --git a/utils/CMakeLists.txt b/utils/CMakeLists.txt index 3bcae80..bc98acf 100644 --- a/utils/CMakeLists.txt +++ b/utils/CMakeLists.txt @@ -8,13 +8,25 @@ set(SOURCE_FILES vector.c vector.h) +find_package(PkgConfig REQUIRED) +pkg_search_module(OPENSSL REQUIRED openssl) + +if( OPENSSL_FOUND ) + include_directories(${OPENSSL_INCLUDE_DIRS}) + message(STATUS "Using OpenSSL ${OPENSSL_VERSION}") +else() + # Error; with REQUIRED, pkg_search_module() will throw an error by it's own +endif() + + find_library(uuid /usr/local/lib) find_path(UUID_INCLUDE_DIR uuid/uuid.h /usr/local/include /opt/local/include /usr/include ) -include_directories(${UUID_INCLUDE_DIR}) +include_directories(${UUID_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR}) -add_executable(bgfirmware ${SOURCE_FILES}) \ No newline at end of file +add_executable(bgfirmware ${SOURCE_FILES}) +target_link_libraries(bgfirmware ${OPENSSL_LIBRARIES}) diff --git a/utils/firmware.c b/utils/firmware.c index 97dfdd9..265cf5a 100644 --- a/utils/firmware.c +++ b/utils/firmware.c @@ -5,7 +5,11 @@ #include #include #include +#include +#include +#include #include +#include #include "vector.h" /** @@ -28,7 +32,6 @@ typedef struct { unsigned char numblocks[2]; // the number of blocks in the file, unsigned char unused[6]; unsigned char service_uuid[UUID_LEN]; // the service uuid of the bootloader - unsigned char init_vector[IV_LEN]; // the block 0 initialization vector } firmware; /** A block header. @@ -41,6 +44,8 @@ typedef struct { unsigned char offset[4]; // offset in the file of the data unsigned char padding[1]; // length of padding at end unsigned char unused[3]; + unsigned char init_vector[IV_LEN]; // the block 0 initialization vector + unsigned char sha256[32]; // SHA256 hash of the data } block_header; typedef struct { @@ -53,10 +58,10 @@ typedef struct { unsigned long base, last; int lineno, major, minor; char *filename; -char * outfile; +char *outfile; char verbose; char lbuf[1024]; -char keybuf[KEY_LEN]; +unsigned char keybuf[KEY_LEN]; unsigned long offset; vector_t memblocks; vector_t assembledBlocks; @@ -83,7 +88,7 @@ put4(unsigned char *addr, unsigned long val) { } void -error(char *f, ...) { +hexerror(char *f, ...) { va_list ap; va_start(ap, f); @@ -91,6 +96,18 @@ error(char *f, ...) { vfprintf(stderr, f, ap); putc('\n', stderr); fprintf(stderr, "line: \"%s", lbuf); + exit(1); +} + +void +error(char *f, ...) { + va_list ap; + + va_start(ap, f); + fprintf(stderr, "%s: %d: ", filename, lineno); + vfprintf(stderr, f, ap); + putc('\n', stderr); + exit(1); } @@ -101,8 +118,7 @@ getx(char **p) { hi = (unsigned char) *(*p)++; lo = (unsigned char) *(*p)++; if (!isxdigit(hi) || !isxdigit(lo)) { - error("Saw 0%o and 0%o:- hex digit expected", hi, lo); - exit(1); + hexerror("Saw 0%o and 0%o:- hex digit expected", hi, lo); } if (islower(hi)) hi = (unsigned char) toupper(hi); @@ -147,8 +163,7 @@ readHexLine() { } cksum += getx(&p); if ((cksum & 0xFF) != 0) { - error("Checksum error"); - exit(1); + hexerror("Checksum error"); } switch (type) { case 1: /* EOF */ @@ -175,8 +190,8 @@ readHexLine() { break; default: - error("Unknown record type %2.2X - length %d", type, cnt); - return 0; + hexerror("Unknown record type %2.2X - length %d", type, cnt); + break; } return 1; @@ -202,25 +217,24 @@ int cmpBlock(const void *a1, const void *a2) { return 0; } -void combine(unsigned i, unsigned j, unsigned int length) { +void combine(unsigned i, unsigned j) { memblock *m1 = vec_elementAt(memblocks, i); - length += BLOCK_SIZE; - length &= ~(BLOCK_SIZE - 1); - unsigned char *buf = malloc(length); - memcpy(buf, m1->data, m1->length); - unsigned int offset = m1->length; - m1->fileLength = length; - free(m1->data); - m1->data = buf; - for (unsigned k = i + 1; k != j; k++) { + memblock *ml = vec_elementAt(memblocks, j - 1); + unsigned totLength = (unsigned int) (ml->addr + ml->length - m1->addr); + totLength += BLOCK_SIZE; + totLength &= ~(BLOCK_SIZE - 1); + m1->fileLength = totLength; + unsigned char *buf = calloc(totLength, 1); + for (unsigned k = i; k != j; k++) { memblock *m2 = vec_elementAt(memblocks, k); - memcpy(buf + offset, m2->data, m2->length); - offset += m2->length; + memcpy(buf + m2->addr - m1->addr, m2->data, m2->length); free(m2->data); - free(m2); + if (k != i) + free(m2); } - m1->length = offset; - memset(buf + offset, (unsigned char) (length - offset), (length - offset)); + m1->data = buf; + m1->length = (unsigned int) (ml->addr + ml->length - m1->addr); + memset(buf + m1->length, (unsigned char) (totLength - m1->length), (totLength - m1->length)); vec_add(assembledBlocks, m1); } @@ -229,8 +243,7 @@ void assembleBlocks() { memblock *m1, *m2; if (memblocks->count == 0) { - fprintf(stderr, "No data read\n"); - exit(1); + error("No data read"); } vec_sort(memblocks, cmpBlock); unsigned int i = 0; @@ -238,24 +251,28 @@ void assembleBlocks() { unsigned int length = m1->length; for (unsigned int j = 1; j != vec_size(memblocks); j++) { m2 = vec_elementAt(memblocks, j); - if (m1->addr + length == m2->addr) { + if (m1->addr + length >= m2->addr - BLOCK_SIZE - 1) { length += m2->length; continue; } - combine(i, j, length); + combine(i, j); i = j + 1; } if (i != vec_size(memblocks)) - combine(i, vec_size(memblocks), length); + combine(i, vec_size(memblocks)); } void writeData() { memblock *m1; + int outlen; + EVP_CIPHER_CTX *ctx; + ctx = EVP_CIPHER_CTX_new(); + EVP_MD_CTX * shaCtx = EVP_MD_CTX_create(); + if (ctx == NULL) { + error("Failed to initialise cipher context"); + } block_header header; - memset(&header, 0, sizeof(header)); - srand((unsigned int) time(NULL)); - for (int i = 0; i != IV_LEN; i++) - fw.init_vector[i] = (unsigned char) rand(); + memset(&fw, 0, sizeof(fw)); for (int i = 0; i != UUID_LEN; i++) fw.service_uuid[i] = uuid[i]; put4(fw.tag, FW_TAG); @@ -266,29 +283,81 @@ void writeData() { fseek(stdout, 0L, SEEK_SET); fwrite(&fw, sizeof fw, 1, stdout); VEC_ITERATE(assembledBlocks, m1, memblock *) { + memset(&header, 0, sizeof(header)); + arc4random_buf(header.init_vector, sizeof header.init_vector); + if(EVP_DigestInit_ex(shaCtx, EVP_sha256(), NULL) != 1) + error("Sha digest init failed"); + if(EVP_DigestUpdate(shaCtx, m1->data, m1->fileLength) != 1) + error("Sha digest update failed"); + unsigned int digest_len; + if(EVP_MD_size(EVP_sha256()) != sizeof(header.sha256)) + error("Sha digest length wrong"); + if(EVP_DigestFinal(shaCtx, header.sha256, &digest_len) != 1|| digest_len != sizeof(header.sha256)) + error("SHA digest final failed"); + if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, keybuf, header.init_vector) != 1) { + error("EncryptInit_ex failed"); + } + unsigned char *outbuf = malloc(m1->fileLength); + if (EVP_EncryptUpdate(ctx, outbuf, &outlen, m1->data, m1->fileLength) != 1) { + error("EncryptUpdate failed"); + } + if (outlen != m1->fileLength) { + error("Mismatched length after encryption - %d should be %d", outlen, m1->fileLength); + } + free(m1->data); + m1->data = outbuf; put4(header.addr, m1->addr); put4(header.size, m1->length); put4(header.offset, offset); + header.padding[0] = (unsigned char) (m1->fileLength - m1->length); offset += m1->fileLength; fwrite(&header, sizeof header, 1, stdout); } + EVP_CIPHER_CTX_free(ctx); + EVP_MD_CTX_destroy(shaCtx); VEC_ITERATE(assembledBlocks, m1, memblock *) { fwrite(m1->data, 1, m1->fileLength, stdout); } fclose(stdout); } +bool file_exists(char *fileName) { + struct stat buf; + return stat(fileName, &buf) == 0; +} + +char *readKey(char *fileName) { + FILE *fp = fopen(fileName, "rb"); + size_t len; + char *buf = calloc((KEY_LEN*2)+1, 1); + if (!fp) { + error("Failed to open key file %s", fileName); + } + len = fread(buf, 1, KEY_LEN*2, fp); + if(len != KEY_LEN*2) { + error("Short read on key file %s", fileName); + } + fclose(fp); + return buf; + +} + + int main(int argc, char **argv) { memblock *m1; char *arg; - bool error = false; + bool sawError = false; if (argc < 2) { fprintf(stderr, "Usage: firmware -o -b -n -k -s .hex ...\n"); exit(1); } + ERR_load_crypto_strings(); + OpenSSL_add_all_algorithms(); + OPENSSL_config(NULL); + assembledBlocks = vec_new(); memblocks = vec_new(); offset = 0x1000; @@ -301,7 +370,7 @@ main(int argc, char **argv) { if (*arg == 0) { if (argc < 1) { fprintf(stderr, "missing arg to -O\n"); - error = true; + sawError = true; continue; } argv++; @@ -317,7 +386,7 @@ main(int argc, char **argv) { if (*arg == 0) { if (argc < 1) { fprintf(stderr, "missing address arg to -B\n"); - error = true; + sawError = true; continue; } argv++; @@ -327,7 +396,7 @@ main(int argc, char **argv) { baseAddress = strtol(arg, NULL, 0); if (baseAddress == 0) { fprintf(stderr, "Base address evaluates to zero\n"); - error = true; + sawError = true; } break; @@ -337,17 +406,18 @@ main(int argc, char **argv) { if (*arg == 0) { if (argc < 1) { fprintf(stderr, "missing arg to -K\n"); - error = true; + sawError = true; continue; } argv++; argc--; arg = argv[1]; } - if (strlen(arg) != 64) { - fprintf(stderr, - "The key should be 64 bytes in hex\n"); - error = true; + if (strlen(arg) != KEY_LEN*2 && file_exists(arg)) + arg = readKey(arg); + if (strlen(arg) != KEY_LEN*2) { + fprintf(stderr, "The key should be %d bytes in hex\n", KEY_LEN); + sawError = true; } else for (int i = 0; i != 32; i++) keybuf[i] = getx(&arg); @@ -359,7 +429,7 @@ main(int argc, char **argv) { if (*arg == 0) { if (argc < 1) { fprintf(stderr, "missing uuid arg to -S\n"); - error = true; + sawError = true; continue; } argv++; @@ -375,7 +445,7 @@ main(int argc, char **argv) { if (*arg == 0) { if (argc < 1) { fprintf(stderr, "missing version number arg to -N\n"); - error = true; + sawError = true; continue; } argv++; @@ -391,7 +461,7 @@ main(int argc, char **argv) { break; default: fprintf(stderr, "Unknown arg %s\n", argv[1]); - error = true; + sawError = true; break; } @@ -400,7 +470,7 @@ main(int argc, char **argv) { } argc--; argv++; - if (error) + if (sawError) exit(1); while (*argv) { if (!freopen(argv[0], "r", stdin)) { @@ -416,14 +486,13 @@ main(int argc, char **argv) { } assembleBlocks(); if (verbose != 0) - VEC_ITERATE(assembledBlocks, m1, memblock *) - fprintf(stderr, "Block: %lX len %X\n", m1->addr, m1->length); - memblock * mp = vec_first(assembledBlocks); - if(baseAddress != 0 && mp->addr != baseAddress) { + VEC_ITERATE(assembledBlocks, m1, memblock *)fprintf(stderr, "Block: %lX len %X\n", m1->addr, m1->length); + memblock *mp = vec_first(assembledBlocks); + if (baseAddress != 0 && mp->addr != baseAddress) { fprintf(stderr, "Lowest address %lX does not match specified base address of %lX\n", mp->addr, baseAddress); exit(1); } - if(outfile == NULL) { + if (outfile == NULL) { fprintf(stderr, "No output file specified, skipping write\n"); exit(0); }