├── artifacts └── .gitkeep ├── upgrade ├── .gitignore └── make_update_package.py ├── before-build.bat ├── requirements.txt ├── verify.sh ├── source ├── driver │ ├── hrng_v2.lib │ ├── pki_v1.lib │ ├── rsa_v1.lib │ ├── ecdsa_v2.lib │ ├── ed25519-donna │ │ ├── ed25519.h │ │ ├── ed25519-donna-portable.h │ │ ├── ed25519_util.h │ │ ├── ed25519-donna.h │ │ ├── curve25519-donna-helpers.h │ │ └── ed25519.c │ ├── sr25519 │ │ ├── ristretto-donna.h │ │ ├── sr25519_util.h │ │ ├── sr25519.h │ │ └── merlin.h │ ├── blake2_common.h │ ├── blake2b.h │ ├── eflash.h │ ├── wdt.h │ ├── wdt.c │ ├── gpio.c │ ├── uart.h │ ├── gpio.h │ ├── eflash.c │ ├── hrng.h │ ├── sha2.h │ └── timer.h ├── COMMON │ ├── config.h │ ├── types.h │ ├── common.h │ ├── typedef.h │ ├── TLV.h │ ├── common.c │ ├── TLV.c │ ├── stack.h │ ├── queue.h │ ├── macro.h │ ├── util.h │ ├── circular_buffer.h │ ├── queue.c │ ├── stack.c │ └── circular_buffer.c ├── crypto │ ├── base58.h │ ├── bip39.h │ ├── secp256.h │ ├── bip44.h │ ├── slip39_encrypt.h │ ├── hmac.h │ ├── bip44.c │ ├── pbkdf2.h │ ├── crypto_api.h │ ├── slip39_encrypt.c │ ├── rmd128mc.h │ ├── RipeMD160.h │ ├── rmd160mc.h │ └── bip39.c ├── substrate │ └── substrate_sign.h ├── mason │ ├── mason_comm.h │ ├── mason_comm.c │ ├── mason_flash_partition.h │ ├── mason_iap.c │ ├── mason_iap.h │ ├── mason_hdw.h │ ├── mason_key.h │ ├── mason_setting.h │ ├── mason_errno.h │ ├── mason_commands.h │ ├── mason_storage.c │ ├── mason_wallet.h │ └── mason_tags.h ├── system │ ├── system_se.c │ └── system_se.h ├── version_def.h ├── version_def.c └── CMSIS │ └── Include │ ├── core_cmFunc.h │ └── core_cmInstr.h ├── Dockerfile ├── .gitignore ├── after-build.bat ├── README.md └── scripts └── verify_package.py /artifacts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /upgrade/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.bin 3 | -------------------------------------------------------------------------------- /before-build.bat: -------------------------------------------------------------------------------- 1 | REM del /Q .\Objects\*.* 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeystoneHQ/keystone-se-firmware/HEAD/requirements.txt -------------------------------------------------------------------------------- /verify.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | docker build -t firmware . 3 | docker run -it -v ./artifacts:/app/artifacts firmware -------------------------------------------------------------------------------- /source/driver/hrng_v2.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeystoneHQ/keystone-se-firmware/HEAD/source/driver/hrng_v2.lib -------------------------------------------------------------------------------- /source/driver/pki_v1.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeystoneHQ/keystone-se-firmware/HEAD/source/driver/pki_v1.lib -------------------------------------------------------------------------------- /source/driver/rsa_v1.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeystoneHQ/keystone-se-firmware/HEAD/source/driver/rsa_v1.lib -------------------------------------------------------------------------------- /source/driver/ecdsa_v2.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeystoneHQ/keystone-se-firmware/HEAD/source/driver/ecdsa_v2.lib -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | From python:3.8.3-alpine 2 | COPY . /app 3 | WORKDIR /app 4 | RUN pip install -r requirements.txt 5 | RUN cp mason_app.hex ./scripts/ 6 | CMD python scripts/verify_package.py -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # build directory 2 | Objects/* 3 | binHistory/ 4 | hexHistory/ 5 | !Objects/*.fed 6 | artifacts/* 7 | !artifacts/.gitkeep 8 | 9 | # build files 10 | *.hex 11 | *.bin 12 | *.map 13 | *.lst 14 | 15 | # compile project 16 | .vscode/ 17 | *uvopt* 18 | *.bak 19 | *uvgui* 20 | *.dep 21 | .idea/ 22 | .DS_Store -------------------------------------------------------------------------------- /source/COMMON/config.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __CONFIG_H__ 3 | #define __CONFIG_H__ 4 | 5 | #define DEBUG 6 | 7 | #ifdef DEBUG 8 | #define printfS printf 9 | #define printfB8 printf_buff_byte 10 | #define printfB32 printf_buff_word 11 | #else 12 | #define printfS(format, ...) ((void)0) 13 | #define printfB8(buff, byte_len) ((void)0) 14 | #define printfB32(buff, word_len) ((void)0) 15 | #endif 16 | 17 | /*--------------- clock----------------------- */ 18 | #define FCLK 48 19 | 20 | /*--------------- uart----------------------- */ 21 | #define UART_BAUD_RATE 115200 22 | //#define UART_Tx_INT_MODE 23 | //#define UART_ENABLE_FIFO_MODE 24 | 25 | //#define UARTA_USE_RTSMODE 26 | //#define UARTA_USE_CTSMODE 27 | 28 | #define UART_RX_BUF_MAX 1536 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /source/driver/ed25519-donna/ed25519.h: -------------------------------------------------------------------------------- 1 | #ifndef ED25519_H 2 | #define ED25519_H 3 | 4 | #include 5 | 6 | #if defined(__cplusplus) 7 | extern "C" { 8 | #endif 9 | 10 | typedef unsigned char ed25519_signature[64]; 11 | typedef unsigned char ed25519_public_key[32]; 12 | typedef unsigned char ed25519_secret_key[32]; 13 | 14 | typedef unsigned char curve25519_key[32]; 15 | 16 | void ed25519_publickey(ed25519_secret_key sk, ed25519_public_key pk); 17 | int ed25519_sign_open(unsigned char *m, size_t mlen, ed25519_public_key pk, ed25519_signature RS); 18 | void ed25519_sign(unsigned char *m, size_t mlen, ed25519_secret_key sk, ed25519_public_key pk, ed25519_signature RS); 19 | 20 | #if defined(__cplusplus) 21 | } 22 | #endif 23 | 24 | #endif // ED25519_H 25 | -------------------------------------------------------------------------------- /source/crypto/base58.h: -------------------------------------------------------------------------------- 1 | #ifndef LIBBASE58_H 2 | #define LIBBASE58_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #ifdef __cplusplus 9 | extern "C" { 10 | #endif 11 | 12 | extern bool (*b58_sha256_impl)(void *, const void *, size_t); 13 | 14 | extern bool b58tobin(void *bin, size_t *binszp, const char *b58, size_t b58sz); 15 | extern int b58check(const void *bin, size_t binsz, const char *base58str, size_t b58sz); 16 | 17 | extern bool b58enc(char *b58, size_t *b58sz, const void *data, size_t binsz); 18 | extern bool b58check_enc(char *b58c, size_t *b58c_sz, uint8_t *verPrefix, size_t prefixsz, 19 | const void *data, size_t datasz, uint8_t *suffix, size_t suffixsz); 20 | 21 | #ifdef __cplusplus 22 | } 23 | #endif 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /source/driver/sr25519/ristretto-donna.h: -------------------------------------------------------------------------------- 1 | // 2 | // This file is based on ristretto-donna 3 | // https://github.com/isislovecruft/ristretto-donna 4 | // 5 | 6 | #ifndef RISTRETTO_DONNA_H 7 | #define RISTRETTO_DONNA_H 8 | 9 | #include "ed25519-donna.h" 10 | 11 | typedef uint8_t ristretto255_hash_output[64]; 12 | 13 | uint8_t uint8_32_ct_eq(const unsigned char a[32], const unsigned char b[32]); 14 | 15 | int ristretto_decode(ge25519 *element, const unsigned char bytes[32]); 16 | void ristretto_encode(unsigned char bytes[32], const ge25519 element); 17 | void ristretto_from_uniform_bytes(ge25519 *element, const unsigned char bytes[64]); 18 | int ristretto_ct_eq(const ge25519 *a, const ge25519 *b); 19 | void ge25519_scalarmult(ge25519 *r, const ge25519 *p1, const bignum256modm s1); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /source/driver/blake2_common.h: -------------------------------------------------------------------------------- 1 | static inline uint32_t load32(const void *src) { 2 | uint32_t w; 3 | memcpy(&w, src, sizeof w); 4 | return w; 5 | } 6 | 7 | static inline uint64_t load64(const void *src) { 8 | uint64_t w; 9 | memcpy(&w, src, sizeof w); 10 | return w; 11 | } 12 | 13 | static inline void store16(void *dst, uint16_t w) { memcpy(dst, &w, sizeof w); } 14 | 15 | static inline void store32(void *dst, uint32_t w) { memcpy(dst, &w, sizeof w); } 16 | 17 | static inline void store64(void *dst, uint64_t w) { memcpy(dst, &w, sizeof w); } 18 | 19 | static inline uint32_t rotr32(const uint32_t w, const unsigned c) { 20 | return (w >> c) | (w << (32 - c)); 21 | } 22 | 23 | static inline uint64_t rotr64(const uint64_t w, const unsigned c) { 24 | return (w >> c) | (w << (64 - c)); 25 | } 26 | -------------------------------------------------------------------------------- /source/driver/ed25519-donna/ed25519-donna-portable.h: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | 3 | #define mul32x32_64(a, b) (((uint64_t)(a)) * (b)) 4 | 5 | /* platform */ 6 | #define DONNA_INLINE inline __attribute__((always_inline)) 7 | #define DONNA_NOINLINE __attribute__((noinline)) 8 | #define ALIGN(x) __attribute__((aligned(x))) 9 | #define ROTL32(a, b) (((a) << (b)) | ((a) >> (32 - b))) 10 | #define ROTR32(a, b) (((a) >> (b)) | ((a) << (32 - b))) 11 | 12 | /* endian */ 13 | static inline void U32TO8_LE(unsigned char *p, const uint32_t v) 14 | { 15 | p[0] = (unsigned char)(v); 16 | p[1] = (unsigned char)(v >> 8); 17 | p[2] = (unsigned char)(v >> 16); 18 | p[3] = (unsigned char)(v >> 24); 19 | } 20 | 21 | static inline uint32_t U8TO32_LE(const unsigned char *p) 22 | { 23 | return (((uint32_t)(p[0])) | 24 | ((uint32_t)(p[1]) << 8) | 25 | ((uint32_t)(p[2]) << 16) | 26 | ((uint32_t)(p[3]) << 24)); 27 | } 28 | -------------------------------------------------------------------------------- /source/driver/ed25519-donna/ed25519_util.h: -------------------------------------------------------------------------------- 1 | #ifndef __ED25519_UTIL_H__ 2 | #define __ED25519_UTIL_H__ 3 | 4 | #include 5 | #include 6 | 7 | typedef SHA512_CTX ed25519_hash_context; 8 | 9 | static void 10 | ed25519_hash_init(ed25519_hash_context *ctx) 11 | { 12 | sha512_Init(ctx); 13 | } 14 | 15 | static void 16 | ed25519_hash_update(ed25519_hash_context *ctx, uint8_t *in, size_t inlen) 17 | { 18 | sha512_Update(ctx, in, inlen); 19 | } 20 | 21 | static void 22 | ed25519_hash_final(ed25519_hash_context *ctx, uint8_t *hash) 23 | { 24 | sha512_Final(ctx, hash); 25 | } 26 | 27 | static void 28 | ed25519_hash(uint8_t *hash, uint8_t *in, size_t inlen) 29 | { 30 | sha512_Raw(in, inlen, hash); 31 | } 32 | 33 | static void ed25519_randombytes_unsafe(void *p, size_t len) 34 | { 35 | size_t i = 0; 36 | uint8_t *out = (uint8_t *)p; 37 | hrng_initial(); 38 | for (i = 0; i < len; i++) 39 | { 40 | out[i] = get_hrng8(); 41 | } 42 | return; 43 | } 44 | #endif 45 | -------------------------------------------------------------------------------- /source/driver/sr25519/sr25519_util.h: -------------------------------------------------------------------------------- 1 | #ifndef __SR25519_UTIL_H__ 2 | #define __SR25519_UTIL_H__ 3 | 4 | #include 5 | #include 6 | 7 | //sr25519_hash 8 | typedef SHA512_CTX sr25519_hash_context; 9 | 10 | static void 11 | sr25519_hash_init(sr25519_hash_context *ctx) 12 | { 13 | sha512_Init(ctx); 14 | } 15 | 16 | static void 17 | sr25519_hash_update(sr25519_hash_context *ctx, uint8_t *in, size_t inlen) 18 | { 19 | sha512_Update(ctx, in, inlen); 20 | } 21 | 22 | static void 23 | sr25519_hash_final(sr25519_hash_context *ctx, uint8_t *hash) 24 | { 25 | sha512_Final(ctx, hash); 26 | } 27 | 28 | static void 29 | sr25519_hash(uint8_t *hash, uint8_t *in, size_t inlen) 30 | { 31 | sha512_Raw(in, inlen, hash); 32 | } 33 | 34 | //sr25519_randombytes 35 | static void sr25519_randombytes(void *p, size_t len) 36 | { 37 | size_t i = 0; 38 | uint8_t *out = (uint8_t *)p; 39 | hrng_initial(); 40 | for (i = 0; i < len; i++) 41 | { 42 | out[i] = get_hrng8(); 43 | } 44 | return; 45 | } 46 | #endif 47 | -------------------------------------------------------------------------------- /after-build.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | set dateTime=%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2% 4 | (echo %dateTime% | find "/") && set dateTime=%date:~6,4%%date:~0,2%%date:~3,2%_%time:~0,2%%time:~3,2% 5 | set "dateTime=%dateTime: =0%" 6 | echo dateTime=%dateTime% 7 | 8 | if "%1"=="" ( 9 | set "projectName=mason_app" 10 | ) else ( 11 | set "projectName=%~1") 12 | 13 | echo projectName=%projectName% 14 | 15 | if "%2"=="" ( 16 | set "PREFIX=FW_APP_" 17 | ) else ( 18 | set "PREFIX=%~2") 19 | 20 | echo PREFIX=%PREFIX% 21 | 22 | xcopy .\%projectName%.bin .\binHistory\ /Y 23 | if exist .\binHistory\%projectName%-%PREFIX%%dateTime%.bin ( del .\binHistory\%projectName%-%PREFIX%%dateTime%.bin ) 24 | ren .\binHistory\%projectName%.bin %projectName%-%PREFIX%%dateTime%.bin 25 | 26 | xcopy .\Objects\%projectName%.hex .\ /Y 27 | xcopy .\Objects\%projectName%.hex .\hexHistory\ /Y 28 | if exist .\hexHistory\%projectName%-%PREFIX%%dateTime%.hex ( del .\hexHistory\%projectName%-%PREFIX%%dateTime%.hex ) 29 | ren .\hexHistory\%projectName%.hex %projectName%-%PREFIX%%dateTime%.hex 30 | 31 | xcopy .\Objects\%projectName%.hex .\upgrade\ /Y -------------------------------------------------------------------------------- /source/driver/blake2b.h: -------------------------------------------------------------------------------- 1 | #ifndef __BLAKE2B_H__ 2 | #define __BLAKE2B_H__ 3 | 4 | #include 5 | #include 6 | 7 | enum blake2b_constant 8 | { 9 | BLAKE2B_BLOCKBYTES = 128, 10 | BLAKE2B_OUTBYTES = 64, 11 | BLAKE2B_KEYBYTES = 64, 12 | BLAKE2B_SALTBYTES = 16, 13 | BLAKE2B_PERSONALBYTES = 16 14 | }; 15 | 16 | typedef struct __blake2b_state 17 | { 18 | uint64_t h[8]; 19 | uint64_t t[2]; 20 | uint64_t f[2]; 21 | uint8_t buf[BLAKE2B_BLOCKBYTES]; 22 | size_t buflen; 23 | size_t outlen; 24 | uint8_t last_node; 25 | } blake2b_state; 26 | 27 | #define BLAKE2B_CTX blake2b_state 28 | #define BLAKE2B_BLOCK_LENGTH BLAKE2B_BLOCKBYTES 29 | #define BLAKE2B_DIGEST_LENGTH BLAKE2B_OUTBYTES 30 | #define BLAKE2B_KEY_LENGTH BLAKE2B_KEYBYTES 31 | 32 | int blake2b_Init(blake2b_state *S, size_t outlen); 33 | int blake2b_InitKey(blake2b_state *S, size_t outlen, const void *key, size_t keylen); 34 | int blake2b_InitPersonal(blake2b_state *S, size_t outlen, const void *personal, size_t personal_len); 35 | int blake2b_Update(blake2b_state *S, const void *pin, size_t inlen); 36 | int blake2b_Final(blake2b_state *S, void *out, size_t outlen); 37 | 38 | int blake2b(const uint8_t *msg, uint32_t msg_len, void *out, size_t outlen); 39 | int blake2b_Key(const uint8_t *msg, uint32_t msg_len, const void *key, size_t keylen, void *out, size_t outlen); 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /source/driver/sr25519/sr25519.h: -------------------------------------------------------------------------------- 1 | #ifndef __SR25519_H__ 2 | #define __SR25519_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | typedef uint8_t sr25519_mini_secret_key[32]; 10 | typedef uint8_t sr25519_secret_key[64]; 11 | typedef uint8_t sr25519_secret_key_key[32]; 12 | typedef uint8_t sr25519_secret_key_nonce[32]; 13 | typedef uint8_t sr25519_chain_code[32]; 14 | typedef uint8_t sr25519_public_key[32]; 15 | typedef uint8_t sr25519_keypair[96]; 16 | typedef uint8_t sr25519_signature[64]; 17 | 18 | void sr25519_derive_keypair_hard(sr25519_keypair derived, const sr25519_keypair keypair, const sr25519_chain_code chain_code); 19 | void sr25519_derive_keypair_soft(sr25519_keypair derived, const sr25519_keypair keypair, const sr25519_chain_code chain_code); 20 | void sr25519_derive_public_soft(sr25519_public_key derived_public, const sr25519_public_key public, const sr25519_chain_code chain_code); 21 | void sr25519_keypair_from_seed(sr25519_keypair keypair, sr25519_mini_secret_key seed); 22 | void sr25519_uniform_keypair_from_seed(sr25519_keypair keypair, sr25519_mini_secret_key seed); 23 | void sr25519_sign(sr25519_signature signature, const sr25519_public_key public, const sr25519_secret_key secret, const uint8_t *message, unsigned long message_length); 24 | bool sr25519_verify(const sr25519_signature signature, const uint8_t *message, unsigned long message_length, const sr25519_public_key public); 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /source/substrate/substrate_sign.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | #ifndef SUBSTRATE_SIGN_H 18 | #define SUBSTRATE_SIGN_H 19 | 20 | #include "sr25519.h" 21 | #include "mason_key.h" 22 | 23 | #define SURI_DEPTH 10 24 | #define MAX_SURI_PATH_LEN 120 25 | 26 | typedef struct 27 | { 28 | sr25519_chain_code cc; 29 | bool is_hard; 30 | } suri_path_item_t; 31 | 32 | typedef struct 33 | { 34 | suri_path_item_t item[SURI_DEPTH]; 35 | uint8_t depth; 36 | } suri_path_t; 37 | 38 | bool substrate_derive_extpubkey(uint8_t *suri, uint32_t suri_len, extended_key_t *extpublic); 39 | bool substrate_sign(uint8_t *suri, uint32_t suri_len, uint8_t *message, uint32_t message_len, 40 | sr25519_signature signature, uint16_t *sign_len, public_key_t *pubkey); 41 | #endif 42 | -------------------------------------------------------------------------------- /source/COMMON/types.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | #ifndef __types_h 18 | #define __types_h 19 | 20 | typedef signed char INT8; 21 | typedef signed short int INT16; 22 | typedef signed int INT32; 23 | 24 | /* exact-width unsigned integer types */ 25 | typedef unsigned char UINT8; 26 | typedef unsigned short int UINT16; 27 | typedef unsigned int UINT32; 28 | 29 | typedef unsigned char BYTE; 30 | typedef unsigned short int WORD; 31 | typedef unsigned int DWORD; 32 | typedef unsigned char * PBYTE; 33 | typedef unsigned short int * PWORD; 34 | typedef unsigned int * PDWORD; 35 | 36 | typedef unsigned char BOOL; 37 | 38 | #define TRUE 1 39 | #define FALSE 0 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /source/COMMON/common.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_H__ 2 | #define __COMMON_H__ 3 | 4 | #include "stdio.h" //printf ..... 5 | #include "string.h" //strlen ,memset,strcmp,memcmp,strcpy ..... 6 | #include "types.h" 7 | #include "config.h" 8 | #include "se.h" 9 | #include "uart.h" 10 | 11 | #define SWAP(x) ((((x) & 0xFF) << 8) | (((x) >> 8) & 0xFF)) 12 | #define max(a, b) (((a) > (b)) ? (a) : (b)) 13 | #define min(a, b) (((a) < (b)) ? (a) : (b)) 14 | 15 | #ifndef _delay_ms 16 | #define _delay_ms delay_ms 17 | #endif 18 | 19 | #ifndef _delay_us 20 | #define _delay_us delay_us 21 | #endif 22 | 23 | 24 | /************************************************************************ 25 | * function : printf_buff_byte 26 | * Description: printf data block by byte 27 | * input : 28 | * UINT8* buff: buff 29 | * UINT32 length: byte length 30 | * return: none 31 | ************************************************************************/ 32 | void printf_buff_byte(UINT8* buff, UINT32 length); 33 | 34 | /************************************************************************ 35 | * function : printf_buff_word 36 | * Description: printf data block by word 37 | * input : 38 | * UINT8* buff: buff 39 | * UINT32 length: word length 40 | * return: none 41 | ************************************************************************/ 42 | void printf_buff_word(UINT32* buff, UINT32 length); 43 | 44 | void delay(UINT32 count); 45 | void delay_us(UINT32 count); 46 | void delay_ms(UINT32 count); 47 | void reverse_DWORD(UINT32 *var); 48 | void reverse_memory(UINT8 *buff, UINT32 length); 49 | 50 | 51 | #endif 52 | 53 | -------------------------------------------------------------------------------- /source/mason/mason_comm.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_COMM_H 19 | #define MASON_COMM_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef MASON_COMM_GLOBAL 23 | #define MASON_COMM_EXT 24 | #else 25 | #define MASON_COMM_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include 35 | #include "mason_errno.h" 36 | 37 | /** Compatibility with the cplusplus*/ 38 | #ifdef __cplusplus 39 | extern "C" 40 | { 41 | #endif /* __cplusplus */ 42 | 43 | /** Function declarations */ 44 | void mason_comm_handler(void); 45 | 46 | /** Compatibility with the cplusplus*/ 47 | #ifdef __cplusplus 48 | } /* Extern C */ 49 | #endif 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /source/COMMON/typedef.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | #ifndef _TypeDef_H_ 18 | #define _TypeDef_H_ 19 | 20 | #include "stdint.h" 21 | 22 | typedef signed char int8; 23 | typedef signed char INT8; 24 | 25 | typedef unsigned char BOOL; 26 | typedef unsigned char byte; 27 | typedef unsigned char BYTE; 28 | typedef unsigned char uchar; 29 | typedef unsigned char uint8; 30 | typedef unsigned char UINT8; 31 | 32 | typedef int int16; 33 | typedef int INT16; 34 | 35 | typedef unsigned int uint; 36 | typedef unsigned int uint16; 37 | typedef unsigned int UINT; 38 | typedef unsigned int UINT16; 39 | typedef unsigned int word; 40 | typedef unsigned int WORD; 41 | 42 | typedef long int int32; 43 | typedef long int INT32; 44 | 45 | typedef unsigned long int uint32; 46 | typedef unsigned long int UINT32; 47 | typedef unsigned long int dword; 48 | typedef unsigned long int DWORD; 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /source/driver/ed25519-donna/ed25519-donna.h: -------------------------------------------------------------------------------- 1 | /* 2 | Public domain by Andrew M. 3 | Modified from the amd64-51-30k implementation by 4 | Daniel J. Bernstein 5 | Niels Duif 6 | Tanja Lange 7 | Peter Schwabe 8 | Bo-Yin Yang 9 | */ 10 | 11 | #ifndef ED25519_DONNA_H 12 | #define ED25519_DONNA_H 13 | 14 | #include "ed25519-donna-portable.h" 15 | 16 | #include "curve25519-donna-32bit.h" 17 | 18 | #include "curve25519-donna-helpers.h" 19 | 20 | #include "modm-donna-32bit.h" 21 | 22 | typedef unsigned char hash_512bits[64]; 23 | 24 | /* 25 | Timing safe memory compare 26 | */ 27 | static int 28 | ed25519_verify(const unsigned char *x, const unsigned char *y, size_t len) { 29 | size_t differentbits = 0; 30 | while (len--) 31 | differentbits |= (*x++ ^ *y++); 32 | return (int) (1 & ((differentbits - 1) >> 8)); 33 | } 34 | 35 | /* 36 | * Arithmetic on the twisted Edwards curve -x^2 + y^2 = 1 + dx^2y^2 37 | * with d = -(121665/121666) = 37095705934669439343138083508754565189542113879843219016388785533085940283555 38 | * Base point: (15112221349535400772501151409588531511454012693041857206046113283949847762202,46316835694926478169428394003475163141307993866256225615783033603165251855960); 39 | */ 40 | 41 | typedef struct ge25519_t { 42 | bignum25519 x, y, z, t; 43 | } ge25519; 44 | 45 | typedef struct ge25519_p1p1_t { 46 | bignum25519 x, y, z, t; 47 | } ge25519_p1p1; 48 | 49 | typedef struct ge25519_niels_t { 50 | bignum25519 ysubx, xaddy, t2d; 51 | } ge25519_niels; 52 | 53 | typedef struct ge25519_pniels_t { 54 | bignum25519 ysubx, xaddy, z, t2d; 55 | } ge25519_pniels; 56 | 57 | #include "ed25519-donna-basepoint-table.h" 58 | 59 | #include "ed25519-donna-32bit-tables.h" 60 | 61 | #include "ed25519-donna-impl-base.h" 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /source/driver/eflash.h: -------------------------------------------------------------------------------- 1 | #ifndef __EFLASH_H__ 2 | #define __EFLASH_H__ 3 | 4 | #include "common.h" 5 | 6 | #define ROM_DRIVER_FLASH 7 | 8 | #define EFLASH_VERIFY_EN 9 | 10 | #define EFLASH_BASE_ADDR 0x00000000 11 | 12 | #define EFlashMainBaseAddr (EFLASH_BASE_ADDR + 0x00000000) 13 | #define EFlashNVR2BaseAddr (EFLASH_BASE_ADDR + 0x00080200) 14 | 15 | #define SM_FLASH_FF_VALUE_ADDR (EFlashNVR2BaseAddr + 0x64) 16 | 17 | #define EFC_RD_TIME 50 18 | 19 | #define EFC_WRITE_MODE (1<<0) 20 | #define EFC_PAGE_ERASE_MODE (1<<1) 21 | #define EFC_CHIP_ERASE_MODE (1<<2) 22 | #define EFC_DOUBLE_READ_EN (1<<3) 23 | #define EFC_PROGRAM_VRI_EN (1<<4) 24 | #define EFC_ERASE_VRI_EN (1<<5) 25 | #define EFC_ARCT_EN (1<<6) 26 | #define EFC_TIME_OUT_EN (1<<7) 27 | //#define EFC_RD_WAIT (2<<8) 28 | #define EFC_SLEEP_EN (1<<13) 29 | #define EFC_ERA_WRI_EN (1<<14) 30 | 31 | 32 | #define PagePerChip 640 33 | #define PAGE_SIZE 512 34 | 35 | 36 | 37 | #define eflash_read_word(addr) (*(volatile UINT32 *)(addr)) //read by word 38 | #define eflash_read_halfword(addr) (*(volatile UINT16 *)(addr)) //read by half word 39 | #define eflash_read_byte(addr) (*(volatile UINT8 *)(addr)) //read by byte 40 | 41 | UINT8 eflash_write_word(UINT32 addr, UINT32 value); 42 | UINT8 eflash_erase_page(UINT32 page_addr); 43 | void eflash_read_page(UINT32 *buff, UINT32 pageBaseAddr); 44 | void eflash_write_page(UINT32 *buff, UINT32 pageBaseAddr); 45 | void eflash_erase_pages(UINT32 startPageAddr, UINT32 pageCnt); 46 | void eflash_rewrite_word(UINT32 addr, UINT32 value); 47 | 48 | 49 | 50 | #endif 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /source/driver/wdt.h: -------------------------------------------------------------------------------- 1 | #ifndef __WDT_H__ 2 | #define __WDT_H__ 3 | #include "common.h" 4 | 5 | #define WDT_ENABLE (1<<7) 6 | #define WDT_ACTION_INT (1<<6) 7 | #define WDT_INT_EN (1<<4) 8 | 9 | #define WDT_DIVIDER_1 0x00 10 | #define WDT_DIVIDER_2 0x01 11 | #define WDT_DIVIDER_4 0x02 12 | #define WDT_DIVIDER_8 0x03 13 | #define WDT_DIVIDER_16 0x04 14 | #define WDT_DIVIDER_32 0x05 15 | #define WDT_DIVIDER_64 0x06 16 | #define WDT_DIVIDER_128 0x07 17 | 18 | 19 | #define WDT_1S (FCLK/16*1000000) 20 | #if WDT_1S > 0xFFFFFFFF 21 | #error "wdt invalid!" 22 | #endif 23 | 24 | 25 | extern volatile UINT8 flag_wdt_int; 26 | 27 | /************************************************************************ 28 | * function : wdt_init 29 | * Description: wdt initial 30 | * input : none 31 | * return: none 32 | ************************************************************************/ 33 | void wdt_init(void); 34 | 35 | /************************************************************************ 36 | * function : wdt_start 37 | * Description: watch dog start 38 | * input : none 39 | * return: none 40 | ************************************************************************/ 41 | void wdt_start(void); 42 | 43 | /************************************************************************ 44 | * function : wdt_stop 45 | * Description: watch dog stop 46 | * input : none 47 | * return: none 48 | ************************************************************************/ 49 | void wdt_stop(void); 50 | 51 | /************************************************************************ 52 | * function : wdt_feed 53 | * Description: watch dog feed 54 | * input : none 55 | * return: none 56 | ************************************************************************/ 57 | void wdt_feed(void); 58 | #endif 59 | 60 | 61 | -------------------------------------------------------------------------------- /source/crypto/bip39.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef BIP39_H 19 | #define BIP39_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef BIP39_GLOBAL 23 | #define BIP39_EXT 24 | #else 25 | #define BIP39_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | 35 | /** Compatibility with the cplusplus*/ 36 | #ifdef __cplusplus 37 | extern "C" 38 | { 39 | #endif /* __cplusplus */ 40 | 41 | /** Macro definitions*/ 42 | #define PASSPHRASE_PREFIX ("mnemonic") //BIP39 43 | 44 | /** Function declarations */ 45 | void bip39_gen_seed_with_mnemonic(uint8_t *pMnemonic, uint32_t mnemonicLen, 46 | uint8_t *pPassphrase, uint32_t passphraseLen, 47 | uint8_t *pSeed, int32_t seedLen); 48 | void bip39_gen_seed_with_entropy(uint8_t *pEntropy, uint32_t entropyLen, 49 | uint8_t *pPassphrase, uint32_t passphraseLen, 50 | uint8_t *pSeed, int32_t seedLen); 51 | /** Compatibility with the cplusplus*/ 52 | #ifdef __cplusplus 53 | } /* Extern C */ 54 | #endif 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /source/crypto/secp256.h: -------------------------------------------------------------------------------- 1 | #ifndef SECP256K1_H_ 2 | #define SECP256K1_H_ 3 | 4 | #include 5 | extern const UINT32 SECP256K1_CURVE_LENGTH; 6 | extern UINT32 SECP256K1_P[8]; 7 | extern UINT32 SECP256K1_a[8]; 8 | extern UINT32 SECP256K1_b[8]; 9 | extern UINT32 SECP256K1_N[8]; 10 | extern UINT32 SECP256K1_G_BaseX[8]; 11 | extern UINT32 SECP256K1_G_BaseY[8]; 12 | 13 | extern const UINT32 SECP256R1_CURVE_LENGTH; 14 | extern UINT32 SECP256R1_P[8]; 15 | extern UINT32 SECP256R1_a[8]; 16 | extern UINT32 SECP256R1_b[8]; 17 | extern UINT32 SECP256R1_N[8]; 18 | extern UINT32 SECP256R1_G_BaseX[8]; 19 | extern UINT32 SECP256R1_G_BaseY[8]; 20 | 21 | void ecc_utils_buffer_to_ecc_array(uint8_t *buffer, uint32_t *ecc_array, uint32_t ecc_array_len); 22 | void ecc_utils_ecc_array_to_buffer(uint32_t *ecc_array, uint32_t ecc_array_len, uint8_t *buffer); 23 | 24 | void secp256k1_init(void); 25 | bool secp256k1_private_key_to_public_key(uint8_t *private_key, uint8_t *public_key_x, uint8_t *public_key_y); 26 | void secp256k1_add_mod(uint8_t *a, uint8_t *b, uint8_t *output); 27 | bool secp256k1_generate_valid_key( 28 | uint8_t *i_left, 29 | uint8_t *parent_private_key, 30 | uint8_t *result_key); 31 | 32 | bool secp256k1_ecdsa_sign( 33 | uint8_t *hash, 34 | uint16_t hash_len, 35 | uint8_t *key, 36 | uint8_t *signature); 37 | bool secp256k1_ecdsa_verify( 38 | uint8_t *hash, 39 | uint8_t *public_key, 40 | uint8_t *signature); 41 | 42 | void secp256r1_init(void); 43 | bool secp256r1_private_key_to_public_key(uint8_t *private_key, uint8_t *public_key_x, uint8_t *public_key_y); 44 | void secp256r1_add_mod(uint8_t *a, uint8_t *b, uint8_t *output); 45 | bool secp256r1_generate_valid_key( 46 | uint8_t *i_left, 47 | uint8_t *parent_private_key, 48 | uint8_t *result_key); 49 | 50 | bool secp256r1_ecdsa_sign( 51 | uint8_t *hash, 52 | uint16_t hash_len, 53 | uint8_t *key, 54 | uint8_t *signature); 55 | bool secp256r1_ecdsa_verify( 56 | uint8_t *hash, 57 | uint8_t *public_key, 58 | uint8_t *signature); 59 | #endif 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Keystone Secure Element Firmware 2 | 3 | **The Keystone hardware wallet is simply relaunched from the Cobo Vault branding so both the code base and infrastructure are the same. For more info please checkout [here](https://blog.keyst.one/leaving-cobo-to-continue-the-cobo-vault-legacy-29bb2f8f026e)** 4 | 5 | 6 | Keystone is an air-gapped, open source hardware wallet that uses completely transparent QR code data transmissions. Visit the [Keystone official website]( https://keyst.one) to learn more about Keystone. 7 | 8 | You can also follow [@Keystone](https://twitter.com/KeystoneWallet) on Twitter. 9 | 10 |
11 | 12 | ## Table of Contents 13 | 14 | - [Clone](#clone) 15 | - [Build](#build) 16 | - [Code Structure](#code-structure) 17 | - [Issues and PRs](#issues-and-prs) 18 | - [License](#license) 19 | 20 | ## Clone 21 | 22 | git clone git@github.com:KeystoneHQ/keystone-se-firmware.git 23 | 24 | ## Build 25 | Currently, the source can only be compiled on Windows. 26 | You can build with ARM IDEs like "Keil MDK V4.x". 27 | 1. Download Keil MDK4.x [here](https://www.keil.com/demo/eval/armv4.htm). 28 | 2. Install MDK and register license. 29 | 3. Run MDK, and add firmware project. Open the dialog `Project - Open Project`, select `mason.uvproj` [here](./mason.uvproj). 30 | 4. Build the firmware project. Select the dialog `Project - Rebuild all target files` to compile the source files. 31 | 5. Find the firmware image `mason_app.hex` and `mason_app.bin` in directory `./`. 32 | 33 | ## Code Structure 34 | Modules: 35 | 36 | `source` : Source files for Secure Element firmware 37 | 38 | `upgrade` : Python script for verifying update package 39 | 40 | `*.bat`: Script file for compiling 41 | 42 | `uvproj`: Project files for MDK IDE 43 | 44 | ## License 45 | [![GPLv3 License](https://img.shields.io/badge/License-GPL%20v3-green.svg)](https://opensource.org/licenses/) 46 | This project is licensed under the GPL License. See the [LICENSE](LICENSE) file for details. 47 | -------------------------------------------------------------------------------- /source/COMMON/TLV.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef TLV_H 19 | #define TLV_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef TLV_GLOBAL 23 | #define TLV_EXT 24 | #else 25 | #define TLV_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | 35 | /** Compatibility with the cplusplus*/ 36 | #ifdef __cplusplus 37 | extern "C" 38 | { 39 | #endif /* __cplusplus */ 40 | 41 | /** Macro definitions*/ 42 | #define TLV_MAX 10 43 | 44 | /** Variable declarations */ 45 | typedef struct 46 | { 47 | uint16_t T; 48 | uint16_t L; 49 | const char *pV; 50 | } stTLVType, *pstTLVType; 51 | TLV_EXT stTLVType stTLV[TLV_MAX]; 52 | TLV_EXT volatile uint16_t tlvLen; 53 | 54 | /** Function declarations */ 55 | uint32_t tlv_get_tag(pstTLVType pstTLV, const char *stream, uint32_t index); 56 | uint32_t tlv_get_len(pstTLVType pstTLV, const char *stream, uint32_t index); 57 | uint32_t tlv_get_value(pstTLVType pstTLV, const char *stream, uint32_t index); 58 | 59 | /** Compatibility with the cplusplus*/ 60 | #ifdef __cplusplus 61 | } /* Extern C */ 62 | #endif 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /source/driver/wdt.c: -------------------------------------------------------------------------------- 1 | #include "wdt.h" 2 | 3 | volatile UINT8 flag_wdt_int = 0; 4 | /************************************************************************ 5 | * function : WDT_IRQHandler 6 | * Description: 7 | * input : 8 | * return: 9 | ************************************************************************/ 10 | void WDT_IRQHandler(void) 11 | { 12 | REG_WDT_FEED = 0xAA55A55A; //feed wdt and clear int 13 | flag_wdt_int = 1; 14 | } 15 | /************************************************************************ 16 | * function : wdt_init 17 | * Description: wdt initial 18 | * input : none 19 | * return: none 20 | ************************************************************************/ 21 | void wdt_init(void) 22 | { 23 | enable_module(BIT_WDT); 24 | reset_module(RESET_WDT); 25 | 26 | NVIC_ClearPendingIRQ(WDT_IRQn); 27 | NVIC_EnableIRQ(WDT_IRQn); 28 | 29 | REG_WDT_LOAD = WDT_1S*20; 30 | REG_WDT_INT_CLR_TIME = 0x8000; 31 | 32 | REG_WDT_CTRL = WDT_DIVIDER_16 | WDT_ACTION_INT | WDT_INT_EN; 33 | // REG_WDT_CTRL |= WDT_ENABLE; //start wdt 34 | } 35 | /************************************************************************ 36 | * function : wdt_start 37 | * Description: watch dog start 38 | * input : none 39 | * return: none 40 | ************************************************************************/ 41 | void wdt_start(void) 42 | { 43 | REG_WDT_CTRL |= WDT_ENABLE; //start wdt 44 | } 45 | /************************************************************************ 46 | * function : wdt_stop 47 | * Description: watch dog stop 48 | * input : none 49 | * return: none 50 | ************************************************************************/ 51 | void wdt_stop(void) 52 | { 53 | REG_WDT_CTRL &= ~WDT_ENABLE; //stop wdt 54 | } 55 | /************************************************************************ 56 | * function : wdt_feed 57 | * Description: watch dog feed 58 | * input : none 59 | * return: none 60 | ************************************************************************/ 61 | void wdt_feed(void) 62 | { 63 | REG_WDT_FEED = 0xAA55A55A; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /source/COMMON/common.c: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | 3 | 4 | #ifdef DEBUG 5 | /************************************************************************ 6 | * function : printf_buff_byte 7 | * Description: printf data block by byte 8 | * input : 9 | * UINT8* buff: buff 10 | * UINT32 length: byte length 11 | * return: none 12 | ************************************************************************/ 13 | void printf_buff_byte(UINT8* buff, UINT32 length) 14 | { 15 | UINT32 i; 16 | 17 | for(i=0;i buff_start) 88 | { 89 | UINT8 temp; 90 | temp = *buff_start; 91 | *buff_start++ = *buff_end; 92 | *buff_end-- = temp; 93 | } 94 | } 95 | 96 | -------------------------------------------------------------------------------- /source/driver/sr25519/merlin.h: -------------------------------------------------------------------------------- 1 | // 2 | // This file is base on libmerlin 3 | // https://github.com/hdevalence/libmerlin.git 4 | // 5 | 6 | #ifndef MERLIN_H 7 | #define MERLIN_H 8 | #define __STDC_WANT_LIB_EXT1__ 1 9 | #include 10 | #include 11 | 12 | /* XXX can these be made opaque without malloc? */ 13 | 14 | typedef struct merlin_strobe128_ 15 | { 16 | /* XXX endianness */ 17 | union 18 | { 19 | uint64_t state[25]; 20 | uint8_t state_bytes[200]; 21 | } u; 22 | uint8_t pos; 23 | uint8_t pos_begin; 24 | uint8_t cur_flags; 25 | } merlin_strobe128; 26 | 27 | typedef struct merlin_transcript_ 28 | { 29 | merlin_strobe128 sctx; 30 | } merlin_transcript; 31 | 32 | typedef struct merlin_rng_ 33 | { 34 | merlin_strobe128 sctx; 35 | uint8_t finalized; 36 | } merlin_rng; 37 | 38 | void merlin_transcript_init(merlin_transcript *mctx, 39 | const uint8_t *label, 40 | size_t label_len); 41 | 42 | void merlin_transcript_commit_bytes(merlin_transcript *mctx, 43 | const uint8_t *label, 44 | size_t label_len, 45 | const uint8_t *data, 46 | size_t data_len); 47 | 48 | void merlin_transcript_challenge_bytes(merlin_transcript *mctx, 49 | const uint8_t *label, 50 | size_t label_len, 51 | uint8_t *buffer, 52 | size_t buffer_len); 53 | 54 | void merlin_rng_init(merlin_rng *mrng, const merlin_transcript *mctx); 55 | 56 | void merlin_rng_commit_witness_bytes(merlin_rng *mrng, 57 | const uint8_t *label, 58 | size_t label_len, 59 | const uint8_t *witness, 60 | size_t witness_len); 61 | 62 | void merlin_rng_finalize(merlin_rng *mrng, const uint8_t entropy[32]); 63 | 64 | void merlin_rng_random_bytes(merlin_rng *mrng, uint8_t *buffer, size_t buffer_len); 65 | 66 | void merlin_rng_wipe(merlin_rng *mrng); 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /source/mason/mason_comm.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define MASON_COMM_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "mason_comm.h" 22 | #include "mason_tags.h" 23 | #include "mason_commands.h" 24 | #include "util.h" 25 | #include "uart.h" 26 | #include "timer.h" 27 | #include "wdt.h" 28 | 29 | /** Function declarations */ 30 | extern void enter_sleep(void); 31 | 32 | /** Variable definitions */ 33 | bool bIsOnSleeping = false; 34 | bool defense_trig_flag = false; 35 | 36 | /** Function implementations */ 37 | /** 38 | * @functionname: mason_comm_handler 39 | * @description: 40 | * @para: 41 | * @return: 42 | */ 43 | void mason_comm_handler(void) 44 | { 45 | switch (gemCmdFSM) 46 | { 47 | case E_CMD_FSM_WAIT_CMD: 48 | { 49 | gemCmdFSM = mason_command_handler(); 50 | break; 51 | } 52 | case E_CMD_FSM_MANAGE_CMD: 53 | { 54 | gemCmdFSM = mason_command_manager(); 55 | break; 56 | } 57 | case E_CMD_FSM_MANAGE_ERR: 58 | { 59 | gemCmdFSM = mason_command_manage_error(); 60 | break; 61 | } 62 | case E_CMD_FSM_IDLE: 63 | { 64 | if (!bIsOnSleeping) 65 | { 66 | bIsOnSleeping = true; 67 | timer_stop(TIMER1); 68 | timer_set_ms(TIMER1, 100000, enter_sleep); 69 | timer_start(TIMER1); 70 | } 71 | gemCmdFSM = E_CMD_FSM_WAIT_CMD; 72 | break; 73 | } 74 | default: 75 | { 76 | break; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /source/driver/gpio.c: -------------------------------------------------------------------------------- 1 | #include "gpio.h" 2 | #include "wdt.h" 3 | 4 | volatile bool flag_active_defense_trigger = false; 5 | volatile bool flag_passtive_defense_trigger = false; 6 | 7 | extern bool bIsOnSleeping; 8 | 9 | /************************************************************************ 10 | * function : GPIO_IRQHandler 11 | * Description: 12 | * input : none 13 | * return: none 14 | ************************************************************************/ 15 | void GPIO_IRQHandler(void) 16 | { 17 | UINT32 status = 0UL; 18 | 19 | status = REG_GPIO_MIS; //read interrupt status register 20 | 21 | //status = REG_GPIO_RIS; 22 | 23 | bIsOnSleeping = false; 24 | 25 | if (status & BIT_DET0) 26 | { 27 | flag_active_defense_trigger = true; 28 | REG_GPIO_IEN &= ~BIT_DET0; 29 | } 30 | 31 | if (status & (BIT_DET1 | BIT_DET2 | BIT_DET3)) 32 | { 33 | flag_passtive_defense_trigger = true; 34 | REG_GPIO_IEN &= ~(BIT_DET1 | BIT_DET2 | BIT_DET3); 35 | } 36 | 37 | REG_GPIO_IC = status; //clear interrupt bit 38 | } 39 | 40 | /************************************************************************ 41 | * function : gpio_init 42 | * Description: gpio initial 43 | * input : none 44 | * return: none 45 | ************************************************************************/ 46 | void gpio_init(void) 47 | { 48 | reset_module(RESET_GPIO); 49 | 50 | NVIC_ClearPendingIRQ(GPIO_IRQn); 51 | NVIC_EnableIRQ(GPIO_IRQn); 52 | } 53 | 54 | bool gpio_high(uint32_t bit, uint32_t durationMS) 55 | { 56 | uint32_t countMs = 30; 57 | 58 | delay_ms(50); 59 | while (bit == (REG_GPIO_IDATA & bit)) 60 | { 61 | wdt_feed(); 62 | delay_ms(50); 63 | countMs += 50; 64 | if (countMs > durationMS) 65 | { 66 | return true; 67 | } 68 | } 69 | 70 | return false; 71 | } 72 | 73 | bool gpio_low(uint32_t bit, uint32_t durationMS) 74 | { 75 | uint32_t countMs = 30; 76 | 77 | while (~bit == (REG_GPIO_IDATA | ~bit)) 78 | { 79 | wdt_feed(); 80 | delay_ms(50); 81 | countMs += 50; 82 | if (countMs > durationMS) 83 | { 84 | return true; 85 | } 86 | } 87 | 88 | return false; 89 | } 90 | -------------------------------------------------------------------------------- /source/crypto/bip44.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef BIP44_H 19 | #define BIP44_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef BIP44_GLOBAL 23 | #define BIP44_EXT 24 | #else 25 | #define BIP44_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include 35 | 36 | /** Compatibility with the cplusplus*/ 37 | #ifdef __cplusplus 38 | extern "C" 39 | { 40 | #endif /* __cplusplus */ 41 | 42 | /** Macro definitions*/ 43 | #define SF_VB_INT_MNET_PUB 0x0488B21E 44 | #define SF_VB_INT_MNET_PRV 0x0488ADE4 45 | #define SF_VB_INT_TNET_PUB 0x043587CF 46 | #define SF_VB_INT_TNET_PRV 0x04358394 47 | #define SF_VB_BUF_MNET_PUB (0x04, 0x88, 0xB2, 0x1E) 48 | #define SF_VB_BUF_MNET_PRV (0x04, 0x88, 0xAD, 0xE4) 49 | #define SF_VB_BUF_TNET_PUB (0x04, 0x35, 0x87, 0xCF) 50 | #define SF_VB_BUF_TNET_PRV (0x04, 0x35, 0x83, 0x94) 51 | 52 | #define HDPATH_DEPTH 10 53 | 54 | /** Variable declarations */ 55 | typedef struct 56 | { 57 | uint32_t verBytes; 58 | uint32_t value[HDPATH_DEPTH]; 59 | uint8_t depth; 60 | } stHDPathType; 61 | 62 | /** Function declarations */ 63 | BIP44_EXT bool bip44_str_to_hdpath(uint8_t *pStr, uint32_t strLen, stHDPathType *pstHDPath); 64 | 65 | /** Compatibility with the cplusplus*/ 66 | #ifdef __cplusplus 67 | } /* Extern C */ 68 | #endif 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /source/COMMON/TLV.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define TLV_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "TLV.h" 22 | #include "stack.h" 23 | 24 | /** Variable definitions */ 25 | TLV_EXT stTLVType stTLV[TLV_MAX] = {NULL}; 26 | TLV_EXT volatile uint16_t tlvLen = 0; 27 | 28 | /** Function implementations */ 29 | /** 30 | * @functionname: tlv_get_tag 31 | * @description: 32 | * @para: 33 | * @return: 34 | */ 35 | uint32_t tlv_get_tag(pstTLVType pstTLV, const char *stream, uint32_t index) 36 | { 37 | pstTLVType pstTmpTLV = pstTLV; 38 | uint16_t tmpTag = 0; 39 | 40 | tmpTag = ((uint16_t)stream[index++] << 8) & 0xFF00; 41 | tmpTag |= ((uint16_t)stream[index++]) & 0x00FF; 42 | pstTmpTLV->T = tmpTag; 43 | 44 | return index; 45 | } 46 | /** 47 | * @functionname: tlv_get_len 48 | * @description: 49 | * @para: 50 | * @return: 51 | */ 52 | uint32_t tlv_get_len(pstTLVType pstTLV, const char *stream, uint32_t index) 53 | { 54 | pstTLVType pstTmpTLV = pstTLV; 55 | uint16_t tmpLen = 0; 56 | 57 | tmpLen = ((uint16_t)stream[index++] << 8) & 0xFF00; 58 | tmpLen |= ((uint16_t)stream[index++]) & 0x00FF; 59 | pstTmpTLV->L = tmpLen; 60 | 61 | return index; 62 | } 63 | /** 64 | * @functionname: tlv_get_value 65 | * @description: 66 | * @para: 67 | * @return: 68 | */ 69 | uint32_t tlv_get_value(pstTLVType pstTLV, const char *stream, uint32_t index) 70 | { 71 | pstTLVType pstTmpTLV = pstTLV; 72 | 73 | pstTmpTLV->pV = stream + index; 74 | 75 | return index + pstTmpTLV->L; 76 | } 77 | -------------------------------------------------------------------------------- /source/driver/uart.h: -------------------------------------------------------------------------------- 1 | #ifndef __UART_H__ 2 | #define __UART_H__ 3 | 4 | #include "common.h" 5 | #include "circular_buffer.h" 6 | 7 | extern UINT8 uart_rx_buf[]; 8 | extern cbuf_handle_t cbuf_handle; 9 | /************************************************************************ 10 | * function : uart_set_baud_rate 11 | * Description: uart set baud rate 12 | * input : 13 | * UINT32 uart_index: Serial port number 14 | * UINT32 clk_hz: cpu frequency 15 | * UINT32 baud_rate: Series rate 16 | * return: none 17 | ************************************************************************/ 18 | void uart_set_baud_rate(UINT32 uart_index, UINT32 clk_hz, UINT32 baud_rate); 19 | 20 | /************************************************************************ 21 | * function : uart_init 22 | * Description: uart initial for uart_index, cpu_mhz, baud_rate 23 | * input : 24 | * UINT32 uart_index: Serial port number 25 | * UINT32 baud_rate: Series rate 26 | * return: none 27 | ************************************************************************/ 28 | void uart_init(UINT32 uart_index, UINT32 baud_rate); 29 | 30 | /************************************************************************ 31 | * function : outbyte 32 | * Description: uart out byte 33 | * input : 34 | * UINT32 uart_index: Serial port number 35 | * char c: out byte 36 | * return: none 37 | ************************************************************************/ 38 | void outbyte(UINT32 uart_index, char c); 39 | 40 | /************************************************************************ 41 | * function : uart_send_bytes 42 | * Description: uart send bytes 43 | * input : 44 | * UINT32 uart_index: Serial port number 45 | * UINT8* buff: out buffer 46 | * UINT32 length: buffer length 47 | * return: none 48 | ************************************************************************/ 49 | void uart_send_bytes(UINT32 uart_index, UINT8 *buff, UINT32 length); 50 | 51 | /************************************************************************ 52 | * function :UART_ReceByte 53 | * Description: 54 | * input : 55 | * return: none 56 | ************************************************************************/ 57 | UINT8 UART_ReceByte(UINT8 UARTx, UINT8 *pData); 58 | 59 | /************************************************************************ 60 | * function :UART_reset 61 | * Description: 62 | * input : 63 | * return: none 64 | ************************************************************************/ 65 | void UART_reset(UINT8 UARTx); 66 | 67 | #endif 68 | -------------------------------------------------------------------------------- /source/system/system_se.c: -------------------------------------------------------------------------------- 1 | #include "system_se.h" 2 | #include "se.h" 3 | 4 | uint32_t SystemCoreClock = 0; //core CLK (uint:Hz) 5 | uint32_t SRCClock = 0; //source CLK (uint:Hz) 6 | uint32_t PClock = 0; //APB ClK (uint:Hz) 7 | 8 | /************************************************************************ 9 | * function : clock_init 10 | * Description: clock init, initil several clock variables 11 | * input : 12 | * uint32_t system_clk_mhz: expected system core clock 13 | * return: none 14 | ************************************************************************/ 15 | void clock_init(uint32_t system_clk_mhz) 16 | { 17 | uint32_t div, rc48m; 18 | uint8_t wait_value; 19 | 20 | switch (system_clk_mhz) 21 | { 22 | case 48: 23 | div = 1; break; 24 | case 24: 25 | div = 2; break; 26 | case 12: 27 | div = 4; break; 28 | case 6 : 29 | div = 8; break; 30 | default: 31 | SystemCoreClock = 0; SRCClock = 0; PClock = 0; return; 32 | } 33 | 34 | REG_EFC_CTRL = (REG_EFC_CTRL & (~(0x1f << 8))) | (5 << 8); //config init EFC RD wait >40ns 35 | REG_SCU_CCR = (REG_SCU_CCR & ~0x03) | CLK_SRC_RC48M; //RC48M 36 | 37 | //REG_SCU_DIVR = ((div -1 ) << 0) | CLK_DIV_ALG | CLK_DIV_SPI | CLK_DIV_HRNGS; 38 | REG_SCU_DIVR = ((div - 1) << 0) | CLK_DIV_ALG | CLK_DIV_SPI | ((system_clk_mhz - 1) << 17); 39 | while ((REG_SCU_DIVR & (1 << 16)) == 0x00); 40 | 41 | rc48m = (*(volatile UINT32 *)(0x0008022C)) * 16000; 42 | if ((rc48m <= 52000000) && (rc48m >= 44000000)) SRCClock = rc48m; 43 | else SRCClock = 48000000; 44 | 45 | SystemCoreClock = SRCClock / div; 46 | PClock = SystemCoreClock; 47 | //set EFC RD_WAIT (at least 50ns) 48 | if (SystemCoreClock >= 30000000) wait_value = 1; 49 | else wait_value = 0; 50 | 51 | REG_EFC_CTRL = (REG_EFC_CTRL & (~(0x1f << 8))) | (wait_value << 8); 52 | } 53 | 54 | /************************************************************************ 55 | * function : SystemInit 56 | * Description: SystemInit 57 | * input : none 58 | * return: none 59 | ************************************************************************/ 60 | void SystemInit(void) 61 | { 62 | clock_init(FCLK); 63 | 64 | while (!(REG_SCU_PHYCR & (1 << 19)));//wait USB PHY wait long to 20ms 65 | if (!(REG_SCU_PHYCR & (1 << 16))) //select inter rc 66 | { 67 | REG_SCU_RCCR &= ~(1 << 7); //disable X12M 68 | } 69 | } 70 | 71 | void SystemCoreClockUpdate(void) 72 | { 73 | //SystemCoreClock=FCLK; 74 | } 75 | -------------------------------------------------------------------------------- /source/COMMON/stack.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef STACK_H 19 | #define STACK_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef STACK_GLOBAL 23 | #define STACK_EXT 24 | #else 25 | #define STACK_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include "TLV.h" 35 | 36 | /** Compatibility with the cplusplus*/ 37 | #ifdef __cplusplus 38 | extern "C" 39 | { 40 | #endif /* __cplusplus */ 41 | 42 | /** Macro definitions*/ 43 | #define STACK_SIZE 10 44 | 45 | /** Variable declarations */ 46 | typedef pstTLVType stackElementType; 47 | 48 | typedef enum EM_STACK 49 | { 50 | EM_STACK_OK, 51 | EM_STACK_FULL, 52 | EM_STACK_EMPTY, 53 | EM_STACK_INVALID, 54 | } emStackStatusType; 55 | 56 | typedef struct ST_STACK 57 | { 58 | stackElementType stack[STACK_SIZE]; 59 | int top; 60 | } stStackType, *pstStackType; 61 | // STACK_EXT stStackType stStack; 62 | 63 | /** Function declarations */ 64 | STACK_EXT void stack_init(pstStackType pstStack); 65 | STACK_EXT bool stack_empty(pstStackType pstStack); 66 | STACK_EXT emStackStatusType stack_push(pstStackType pstStack, stackElementType element); 67 | STACK_EXT emStackStatusType stack_pop(pstStackType pstStack, stackElementType *pelement); 68 | STACK_EXT emStackStatusType stack_top(pstStackType pstStack, stackElementType *pelement); 69 | STACK_EXT emStackStatusType stack_get(pstStackType pstStack, stackElementType *pelement, int index); 70 | STACK_EXT void stack_destroy(pstStackType pstStack); 71 | 72 | /** Compatibility with the cplusplus*/ 73 | #ifdef __cplusplus 74 | } /* Extern C */ 75 | #endif 76 | 77 | #endif 78 | -------------------------------------------------------------------------------- /source/driver/ed25519-donna/curve25519-donna-helpers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Public domain by Andrew M. 3 | See: https://github.com/floodyberry/curve25519-donna 4 | 5 | Curve25519 implementation agnostic helpers 6 | */ 7 | 8 | /* 9 | * In: b = 2^5 - 2^0 10 | * Out: b = 2^250 - 2^0 11 | */ 12 | static void 13 | curve25519_pow_two5mtwo0_two250mtwo0(bignum25519 b) { 14 | bignum25519 ALIGN(8) t0,c; 15 | 16 | /* 2^5 - 2^0 */ /* b */ 17 | /* 2^10 - 2^5 */ curve25519_square_times(t0, b, 5); 18 | /* 2^10 - 2^0 */ curve25519_mul_noinline(b, t0, b); 19 | /* 2^20 - 2^10 */ curve25519_square_times(t0, b, 10); 20 | /* 2^20 - 2^0 */ curve25519_mul_noinline(c, t0, b); 21 | /* 2^40 - 2^20 */ curve25519_square_times(t0, c, 20); 22 | /* 2^40 - 2^0 */ curve25519_mul_noinline(t0, t0, c); 23 | /* 2^50 - 2^10 */ curve25519_square_times(t0, t0, 10); 24 | /* 2^50 - 2^0 */ curve25519_mul_noinline(b, t0, b); 25 | /* 2^100 - 2^50 */ curve25519_square_times(t0, b, 50); 26 | /* 2^100 - 2^0 */ curve25519_mul_noinline(c, t0, b); 27 | /* 2^200 - 2^100 */ curve25519_square_times(t0, c, 100); 28 | /* 2^200 - 2^0 */ curve25519_mul_noinline(t0, t0, c); 29 | /* 2^250 - 2^50 */ curve25519_square_times(t0, t0, 50); 30 | /* 2^250 - 2^0 */ curve25519_mul_noinline(b, t0, b); 31 | } 32 | 33 | /* 34 | * z^(p - 2) = z(2^255 - 21) 35 | */ 36 | static void 37 | curve25519_recip(bignum25519 out, const bignum25519 z) { 38 | bignum25519 ALIGN(8) a,t0,b; 39 | 40 | /* 2 */ curve25519_square_times(a, z, 1); /* a = 2 */ 41 | /* 8 */ curve25519_square_times(t0, a, 2); 42 | /* 9 */ curve25519_mul_noinline(b, t0, z); /* b = 9 */ 43 | /* 11 */ curve25519_mul_noinline(a, b, a); /* a = 11 */ 44 | /* 22 */ curve25519_square_times(t0, a, 1); 45 | /* 2^5 - 2^0 = 31 */ curve25519_mul_noinline(b, t0, b); 46 | /* 2^250 - 2^0 */ curve25519_pow_two5mtwo0_two250mtwo0(b); 47 | /* 2^255 - 2^5 */ curve25519_square_times(b, b, 5); 48 | /* 2^255 - 21 */ curve25519_mul_noinline(out, b, a); 49 | } 50 | 51 | /* 52 | * z^((p-5)/8) = z^(2^252 - 3) 53 | */ 54 | static void 55 | curve25519_pow_two252m3(bignum25519 two252m3, const bignum25519 z) { 56 | bignum25519 ALIGN(8) b,c,t0; 57 | 58 | /* 2 */ curve25519_square_times(c, z, 1); /* c = 2 */ 59 | /* 8 */ curve25519_square_times(t0, c, 2); /* t0 = 8 */ 60 | /* 9 */ curve25519_mul_noinline(b, t0, z); /* b = 9 */ 61 | /* 11 */ curve25519_mul_noinline(c, b, c); /* c = 11 */ 62 | /* 22 */ curve25519_square_times(t0, c, 1); 63 | /* 2^5 - 2^0 = 31 */ curve25519_mul_noinline(b, t0, b); 64 | /* 2^250 - 2^0 */ curve25519_pow_two5mtwo0_two250mtwo0(b); 65 | /* 2^252 - 2^2 */ curve25519_square_times(b, b, 2); 66 | /* 2^252 - 3 */ curve25519_mul_noinline(two252m3, b, z); 67 | } 68 | -------------------------------------------------------------------------------- /source/COMMON/queue.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef QUEUE_H 19 | #define QUEUE_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef QUEUE_GLOBAL 23 | #define QUEUE_EXT 24 | #else 25 | #define QUEUE_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include "mason_commands.h" 35 | 36 | /** Compatibility with the cplusplus*/ 37 | #ifdef __cplusplus 38 | extern "C" 39 | { 40 | #endif /* __cplusplus */ 41 | 42 | /** Macro definitions*/ 43 | #define QUEUE_SIZE 10 44 | 45 | // #define QUEUE_LOG_ENABLE 46 | 47 | #ifdef QUEUE_LOG_ENABLE 48 | #define QUEUE_LOG(...) \ 49 | printf(__VA_ARGS__) 50 | #else 51 | #define QUEUE_LOG(...) 52 | #endif 53 | 54 | /** Variable declarations */ 55 | typedef pstCMDType queueElementType; 56 | 57 | typedef struct 58 | { 59 | volatile queueElementType queue[QUEUE_SIZE]; 60 | volatile uint32_t head, tail, size; 61 | } stQueueType, *pstQueueType; 62 | QUEUE_EXT stQueueType stQueue; 63 | 64 | /** Function declarations */ 65 | typedef void (*display_element_callback)(void *); 66 | QUEUE_EXT void queue_init(volatile stQueueType *pstQueue); 67 | QUEUE_EXT uint32_t queue_size(volatile stQueueType *pstQueue); 68 | QUEUE_EXT int queue_is_empty(volatile stQueueType *pstQueue); 69 | QUEUE_EXT int queue_is_full(volatile stQueueType *pstQueue); 70 | QUEUE_EXT void enqueue_overwrite(volatile stQueueType *pstQueue, queueElementType element); 71 | QUEUE_EXT void enqueue_safe(volatile stQueueType *pstQueue, queueElementType element); 72 | QUEUE_EXT queueElementType dequeue(volatile stQueueType *pstQueue); 73 | 74 | /** Compatibility with the cplusplus*/ 75 | #ifdef __cplusplus 76 | } /* Extern C */ 77 | #endif 78 | 79 | #endif 80 | -------------------------------------------------------------------------------- /source/mason/mason_flash_partition.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_FLASH_PARTTITION_H 19 | #define MASON_FLASH_PARTTITION_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef MASON_FLASH_PARTTITION_GLOBAL 23 | #define MASON_FLASH_PARTTITION_EXT 24 | #else 25 | #define MASON_FLASH_PARTTITION_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include "mason_errno.h" 35 | #include "eflash.h" 36 | 37 | /** Compatibility with the cplusplus*/ 38 | #ifdef __cplusplus 39 | extern "C" 40 | { 41 | #endif /* __cplusplus */ 42 | 43 | /** Macro definitions*/ 44 | #ifndef FLASH_PAGE_SIZE 45 | #define FLASH_PAGE_SIZE PAGE_SIZE 46 | #endif 47 | 48 | #define FLASH_ADDR_START EFLASH_BASE_ADDR 49 | #define FLASH_ADDR_MAX 0x00040000 50 | #define Reset_Handler_offset 0x00000004 51 | 52 | #define OFFSET(X) ((X) - FLASH_ADDR_START) 53 | 54 | #define FLASH_ADDR_SELECTOR_START FLASH_ADDR_START 55 | #define SELECTOR_SIZE 0x00000800 56 | #define FLASH_ADDR_BOOT1_START (FLASH_ADDR_SELECTOR_START+SELECTOR_SIZE) 57 | #define BOOT1_SIZE 0x00009C00 58 | #define FLASH_ADDR_BOOT2_START (FLASH_ADDR_BOOT1_START+BOOT1_SIZE) 59 | #define BOOT2_SIZE 0x00009C00 60 | #define FLASH_ADDR_APP_START (FLASH_ADDR_BOOT2_START+BOOT2_SIZE) 61 | #define APP_SIZE 0x00024000 62 | #define FLASH_ADDR_PARAM_START (FLASH_ADDR_APP_START+APP_SIZE) // 0x38000 63 | #define PARAM_SIZE 0x00008000 64 | #define FLASH_ADDR_END (FLASH_ADDR_PARAM_START+PARAM_SIZE) 65 | 66 | #if FLASH_ADDR_END>FLASH_ADDR_MAX 67 | #error "flash out of range!" 68 | #endif 69 | 70 | /** Compatibility with the cplusplus*/ 71 | #ifdef __cplusplus 72 | } /* Extern C */ 73 | #endif 74 | 75 | #endif 76 | -------------------------------------------------------------------------------- /source/mason/mason_iap.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define MASON_ISP_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "mason_iap.h" 22 | #include "common.h" 23 | #include "util.h" 24 | #include "eflash.h" 25 | #include "sha2.h" 26 | #include "mason_hdw.h" 27 | #include "crypto_api.h" 28 | #include "version_def.h" 29 | 30 | /** Function implementations */ 31 | /** 32 | * @functionname: mason_iap_pack_verify_process 33 | * @description: 34 | * @para: 35 | * @return: 36 | */ 37 | emRetType mason_iap_pack_verify_process(emFwPackTypeType emFwPackType, uint8_t *pBin, uint32_t binLen) 38 | { 39 | emRetType emRet = ERT_OK; 40 | static SHA256_CTX sha256ctx; 41 | uint8_t *PckHash = NULL; 42 | 43 | switch (emFwPackType) 44 | { 45 | case E_PACK_FIRST: 46 | { 47 | sha256_Init(&sha256ctx); 48 | } 49 | case E_PACK_CONTINUE: 50 | case E_PACK_LAST: 51 | { 52 | uint8_t blk_sha256_buf[SHA256_LEN] = {0}; 53 | uint8_t *blkHash = NULL; 54 | sha256_api(pBin, (binLen - 8), blk_sha256_buf); 55 | blkHash = pBin + binLen - 8; 56 | if (memcmp_ATA(blkHash, blk_sha256_buf, 8)) 57 | { 58 | return ERT_IAP_fileDigest; 59 | } 60 | 61 | sha256_Update(&sha256ctx, pBin, binLen); 62 | break; 63 | } 64 | case E_PACK_HDR: 65 | { 66 | uint8_t bufSHA256[SHA256_LEN] = {0}; 67 | sha256_Final(&sha256ctx, bufSHA256); 68 | 69 | PckHash = pBin + 32; 70 | if (memcmp_ATA(PckHash, bufSHA256, SHA256_LEN)) 71 | { 72 | emRet = ERT_IAP_fileDigest; 73 | } 74 | 75 | //k1 verify 76 | if (ERT_OK == emRet) 77 | { 78 | uint8_t *Sign = pBin + 64; 79 | 80 | //hash again 81 | sha256_api(PckHash, SHA256_LEN, bufSHA256); 82 | if (!ecdsa_verify(CRYPTO_CURVE_SECP256K1, bufSHA256, update_pub_key, Sign)) 83 | { 84 | emRet = ERT_IAP_fileDigest; 85 | } 86 | } 87 | break; 88 | } 89 | default: 90 | break; 91 | } 92 | 93 | return emRet; 94 | } 95 | -------------------------------------------------------------------------------- /source/crypto/slip39_encrypt.h: -------------------------------------------------------------------------------- 1 | // 2 | // encrypt.h 3 | // 4 | // Copyright © 2020 by Blockchain Commons, LLC 5 | // Licensed under the "BSD-2-Clause Plus Patent License" 6 | // 7 | 8 | #ifndef ENCRYPT_H 9 | #define ENCRYPT_H 10 | 11 | #include 12 | 13 | #define BASE_ITERATION_COUNT 2500 14 | #define ROUND_COUNT 4 15 | 16 | /** 17 | * this is the round function described in the slip39 spec for the Fiestel network 18 | * it uses to encrypt/decrypt secrets with a passphrase 19 | * 20 | * inputs: i: round number 21 | * passphrase: ascii encoded passphrase 22 | * exp: exponent for the number of iterations of pbkd to run 23 | * salt: array of bytes to use a salt for the encryption 24 | * salt_lentgh: length of the salt array 25 | * r: array of bytes to encrypt 26 | * r_length: lenght of the r array 27 | * dest: location to store encrypted value 28 | * dest_length: maximum number of bytes to write to dest 29 | */ 30 | void round_function( 31 | uint8_t i, 32 | const char *passphrase, 33 | uint8_t exp, 34 | const uint8_t *salt, 35 | uint32_t salt_length, 36 | const uint8_t *r, 37 | uint32_t r_length, 38 | uint8_t *dest, 39 | uint32_t dest_length 40 | ); 41 | 42 | /** 43 | * encrypts input using passphrase with the Fiestel network described in the slip39 spec 44 | * 45 | * inputs: input: array of bytes to encrypt 46 | * input_length: length of input array 47 | * passphrase: null terminated ascii string 48 | * iteration_exponent: exponent for the number of pbkd rounds to use 49 | * identifier: identifier for the shard set (used as part of the salt) 50 | * output: memory location to write output to (same length as the input) 51 | */ 52 | void slip39_encrypt( 53 | const uint8_t *input, 54 | uint32_t input_length, 55 | const char *passphrase, 56 | uint8_t iteration_exponent, 57 | uint16_t identifier, 58 | uint8_t *output 59 | ); 60 | 61 | /** 62 | * decrypts input using passphrase with the Fiestel network described in the slip39 spec 63 | * 64 | * inputs: input: array of bytes to decrypt 65 | * input_length: length of input array 66 | * passphrase: null terminated ascii string 67 | * iteration_exponent: exponent for the number of pbkd rounds to use 68 | * identifier: identifier for the shard set (used as part of the salt) 69 | * output: memory location to write output to (same length as the input) 70 | */ 71 | void slip39_decrypt( 72 | const uint8_t *input, 73 | uint32_t input_length, 74 | const char *passphrase, 75 | uint8_t iteration_exponent, 76 | uint16_t identifier, 77 | uint8_t *output 78 | ); 79 | 80 | #endif /* ENCRYPT_H */ 81 | -------------------------------------------------------------------------------- /source/crypto/hmac.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2013-2014 Tomas Dzetkulic 3 | * Copyright (c) 2013-2014 Pavol Rusnak 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining 6 | * a copy of this software and associated documentation files (the "Software"), 7 | * to deal in the Software without restriction, including without limitation 8 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | * and/or sell copies of the Software, and to permit persons to whom the 10 | * Software is furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included 13 | * in all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 16 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT HMAC_SHALL 18 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 19 | * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 20 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 21 | * OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | 24 | #ifndef __HMAC_H__ 25 | #define __HMAC_H__ 26 | 27 | #include 28 | #include "sha2.h" 29 | 30 | typedef struct _HMAC_SHA256_CTX { 31 | uint8_t o_key_pad[SHA256_BLOCK_LENGTH]; 32 | SHA256_CTX ctx; 33 | } HMAC_SHA256_CTX; 34 | 35 | typedef struct _HMAC_SHA512_CTX { 36 | uint8_t o_key_pad[SHA512_BLOCK_LENGTH]; 37 | SHA512_CTX ctx; 38 | } HMAC_SHA512_CTX; 39 | 40 | void hmac_sha256_Init(HMAC_SHA256_CTX *hctx, const uint8_t *key, 41 | const uint32_t keylen); 42 | void hmac_sha256_Update(HMAC_SHA256_CTX *hctx, const uint8_t *msg, 43 | const uint32_t msglen); 44 | void hmac_sha256_Final(HMAC_SHA256_CTX *hctx, uint8_t *hmac); 45 | void hmac_sha256(const uint8_t *key, const uint32_t keylen, const uint8_t *msg, 46 | const uint32_t msglen, uint8_t *hmac); 47 | void hmac_sha256_prepare(const uint8_t *key, const uint32_t keylen, 48 | uint32_t *opad_digest, uint32_t *ipad_digest); 49 | 50 | void hmac_sha512_Init(HMAC_SHA512_CTX *hctx, const uint8_t *key, 51 | const uint32_t keylen); 52 | void hmac_sha512_Update(HMAC_SHA512_CTX *hctx, const uint8_t *msg, 53 | const uint32_t msglen); 54 | void hmac_sha512_Final(HMAC_SHA512_CTX *hctx, uint8_t *hmac); 55 | void hmac_sha512(const uint8_t *key, const uint32_t keylen, const uint8_t *msg, 56 | const uint32_t msglen, uint8_t *hmac); 57 | void hmac_sha512_prepare(const uint8_t *key, const uint32_t keylen, 58 | uint64_t *opad_digest, uint64_t *ipad_digest); 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /source/version_def.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef VERSION_DEF_H 19 | #define VERSION_DEF_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef VERSION_DEF_GLOBAL 23 | #define VERSION_DEF_EXT 24 | #else 25 | #define VERSION_DEF_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | 35 | /** Compatibility with the cplusplus*/ 36 | #ifdef __cplusplus 37 | extern "C" 38 | { 39 | #endif /* __cplusplus */ 40 | 41 | /** Macro definitions*/ 42 | #define VER_REL 1 // 0 -- develop mode , 1 -- release mode 43 | 44 | #define VER_Major 2 45 | #define VER_Minor 0 46 | #define VER_Release 0 47 | #define VER_Build 00000 48 | 49 | #if VER_Major > 0x9 || VER_Minor > 0x9 || VER_Release > 0x9 || VER_Build > 0x0FFFFF 50 | #if defined _WIN32 || _WIN64 51 | #pragma message("VERSION define error, please check!") 52 | #else 53 | #error "VERSION define error, please check!" 54 | #endif 55 | #endif 56 | 57 | #define _CONCATENATE_AS_DEC(a, b, c) a##b##c 58 | #define _CONCATENATE_AS_HEX(a, b, c) 0x##a##b##c 59 | #define _VER_F3(a, b, c) (_CONCATENATE_AS_HEX(a, b, c)) 60 | #define VER_F3 (_VER_F3(VER_Major, VER_Minor, VER_Release)) 61 | #define VERSION_BCD (uint32_t)(VER_F3 << 20 | VER_Build) 62 | 63 | #define VER_LEN 12 + 1 64 | #define GET_VERSION_STR(buf, len) \ 65 | do \ 66 | { \ 67 | snprintf(buf, len, "%d.%d.%d.%06d", VER_Major, VER_Minor, VER_Release, VER_Build); \ 68 | } while (0) 69 | 70 | extern uint8_t update_pub_key[64]; 71 | extern uint8_t web_pub_key[64]; 72 | 73 | /** Compatibility with the cplusplus*/ 74 | #ifdef __cplusplus 75 | } /* Extern C */ 76 | #endif 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /source/version_def.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | in the file COPYING. If not, see . 13 | **************************************************************************************************/ 14 | /** Header file reference */ 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | /** Variable declarations */ 23 | 24 | uint8_t update_pub_key[64] = 25 | { 26 | 0x58, 27 | 0x08, 28 | 0xeb, 29 | 0x31, 30 | 0x0e, 31 | 0x69, 32 | 0x55, 33 | 0xc2, 34 | 0x08, 35 | 0xcd, 36 | 0x4d, 37 | 0xc0, 38 | 0x5d, 39 | 0x02, 40 | 0x37, 41 | 0x0d, 42 | 0xbe, 43 | 0xb8, 44 | 0xc7, 45 | 0x8d, 46 | 0x8d, 47 | 0xcf, 48 | 0x74, 49 | 0xb3, 50 | 0x91, 51 | 0x94, 52 | 0x08, 53 | 0xb9, 54 | 0x5e, 55 | 0x63, 56 | 0x6b, 57 | 0xed, 58 | 0x99, 59 | 0xc4, 60 | 0x39, 61 | 0x06, 62 | 0xc4, 63 | 0x18, 64 | 0xa3, 65 | 0x7f, 66 | 0xb0, 67 | 0xa8, 68 | 0x52, 69 | 0x0a, 70 | 0x15, 71 | 0xa4, 72 | 0x15, 73 | 0x93, 74 | 0x57, 75 | 0x75, 76 | 0xec, 77 | 0x23, 78 | 0xe1, 79 | 0x9b, 80 | 0xb3, 81 | 0xb9, 82 | 0x91, 83 | 0x91, 84 | 0x21, 85 | 0x87, 86 | 0x2f, 87 | 0xb6, 88 | 0x8a, 89 | 0xd6, 90 | }; 91 | 92 | uint8_t web_pub_key[64] = 93 | { 94 | 0x37, 95 | 0xfd, 96 | 0x6a, 97 | 0xac, 98 | 0x75, 99 | 0xb1, 100 | 0xf0, 101 | 0xf0, 102 | 0x47, 103 | 0x67, 104 | 0x76, 105 | 0x80, 106 | 0x25, 107 | 0x42, 108 | 0xdb, 109 | 0x6e, 110 | 0xd6, 111 | 0x3f, 112 | 0x41, 113 | 0x8e, 114 | 0xa6, 115 | 0x96, 116 | 0x72, 117 | 0x0a, 118 | 0x98, 119 | 0x81, 120 | 0xfe, 121 | 0x99, 122 | 0xd4, 123 | 0x5b, 124 | 0xe9, 125 | 0x64, 126 | 0x8c, 127 | 0xfe, 128 | 0x34, 129 | 0xb2, 130 | 0x63, 131 | 0x11, 132 | 0x24, 133 | 0x55, 134 | 0xaf, 135 | 0x2d, 136 | 0x73, 137 | 0x64, 138 | 0xf4, 139 | 0xfe, 140 | 0x87, 141 | 0x99, 142 | 0xc5, 143 | 0x22, 144 | 0x13, 145 | 0x77, 146 | 0x06, 147 | 0x07, 148 | 0x34, 149 | 0x4c, 150 | 0xca, 151 | 0x4a, 152 | 0x4c, 153 | 0x63, 154 | 0x32, 155 | 0x98, 156 | 0x37, 157 | 0xfa, 158 | }; 159 | -------------------------------------------------------------------------------- /source/crypto/bip44.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define BIP44_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "bip44.h" 22 | #include "crypto_api.h" 23 | #include "util.h" 24 | 25 | /** Function implementations */ 26 | /** 27 | * @functionname: bip44_str_to_hdpath 28 | * @description: 29 | * @para: 30 | * @return: 31 | */ 32 | BIP44_EXT bool bip44_str_to_hdpath(uint8_t *pStr, uint32_t strLen, stHDPathType *pstHDPath) 33 | { 34 | char cSlash = '/'; 35 | char cApostrophe = '\''; 36 | uint32_t index = 0; 37 | uint8_t *pStrTmp = NULL; 38 | 39 | /*HDPath "m/2147483647'/2147483647'/2147483647'/2147483647'/2147483647'...*/ 40 | if ((NULL == pStr) || (('m' != pStr[0]) && ('M' != pStr[0])) || (0 == strLen) || (strLen > 121)) 41 | { 42 | return false; 43 | } 44 | 45 | pStrTmp = (uint8_t *)calloc(strLen + 1, sizeof(uint8_t)); 46 | if (NULL == pStrTmp) 47 | { 48 | return false; 49 | } 50 | memcpy(pStrTmp, pStr, strLen); 51 | pStrTmp[strLen] = '\0'; 52 | 53 | if ('m' == pStrTmp[0]) 54 | { 55 | pstHDPath->verBytes = SF_VB_INT_MNET_PRV; 56 | } 57 | else if ('M' == pStrTmp[0]) 58 | { 59 | pstHDPath->verBytes = SF_VB_INT_MNET_PUB; 60 | } 61 | pstHDPath->depth = 0; 62 | index++; 63 | 64 | while ((index < strLen) && (cSlash == pStrTmp[index++])) // m/********* 65 | { 66 | uint32_t count = 0; 67 | uint32_t path_index = 0; 68 | if(pstHDPath->depth >= HDPATH_DEPTH) 69 | { 70 | free(pStrTmp); 71 | return false; 72 | } 73 | 74 | while ((index < strLen) && !isdigit(pStrTmp[index])) 75 | { 76 | index++; 77 | } /* non-digit should be skipped */ 78 | if (index >= strLen) 79 | { 80 | free(pStrTmp); 81 | return false; 82 | } 83 | path_index = index; 84 | while (isdigit(pStrTmp[index])) /* non-digit should be skipped */ 85 | { 86 | index++; 87 | if (count++ > 10) 88 | { 89 | free(pStrTmp); 90 | return false; 91 | } 92 | } 93 | pstHDPath->value[pstHDPath->depth] = myatoui((const char *)pStrTmp + path_index); 94 | if (cApostrophe == pStrTmp[index]) 95 | { 96 | index++; 97 | pstHDPath->value[pstHDPath->depth] += 0x80000000; 98 | } 99 | pstHDPath->depth++; 100 | } 101 | 102 | free(pStrTmp); 103 | return true; 104 | } 105 | -------------------------------------------------------------------------------- /source/driver/gpio.h: -------------------------------------------------------------------------------- 1 | #ifndef __GPIO_H__ 2 | #define __GPIO_H__ 3 | 4 | #include "common.h" 5 | 6 | #define BIT0 (1<<0) 7 | #define BIT1 (1<<1) 8 | #define BIT2 (1<<2) 9 | #define BIT3 (1<<3) 10 | #define BIT4 (1<<4) 11 | #define BIT5 (1<<5) 12 | #define BIT6 (1<<6) 13 | #define BIT7 (1<<7) 14 | #define BIT8 (1<<8) 15 | #define BIT9 (1<<9) 16 | #define BIT10 (1<<10) 17 | #define BIT11 (1<<11) 18 | #define BIT12 (1<<12) 19 | #define BIT13 (1<<13) 20 | #define BIT14 (1<<14) 21 | #define BIT15 (1<<15) 22 | #define BIT16 (1<<16) 23 | #define BIT17 (1<<17) 24 | #define BIT18 (1<<18) 25 | #define BIT19 (1<<19) 26 | #define BIT20 (1<<20) 27 | #define BIT21 (1<<21) 28 | #define BIT22 (1<<22) 29 | #define BIT23 (1<<23) 30 | #define BIT24 (1<<24) 31 | #define BIT25 (1<<25) 32 | #define BIT26 (1<<26) 33 | #define BIT27 (1<<27) 34 | #define BIT28 (1<<28) 35 | #define BIT29 (1<<29) 36 | #define BIT30 (1<<30) 37 | #define BIT31 (1UL<<31) 38 | #define BIT(num) (1UL<<(num)) 39 | 40 | #define GPIO_DIR_IN 0 41 | #define GPIO_DIR_OUT 1 42 | #define GPIO_IS_EDGE 0 43 | #define GPIO_IS_LEVEL 1 44 | #define GPIO_IBE_SINGLE 0 45 | #define GPIO_IBE_DOUBLE 1 46 | #define GPIO_IEV_DOWN_LOW 0 47 | #define GPIO_IEV_UP_HIGH 1 48 | 49 | 50 | //mason defines 51 | #define GPIO_DET0 GPIO25 52 | #define GPIO_DET1 GPIO2 53 | #define GPIO_DET2 GPIO3 54 | #define GPIO_DET3 GPIO4 55 | #define GPIO_WAKE_UP GPIO30 56 | 57 | #define PIN_DET0 (25) 58 | #define PIN_DET1 (2) 59 | #define PIN_DET2 (3) 60 | #define PIN_DET3 (4) 61 | #define PIN_WAKE_UP (30) 62 | 63 | #define BIT_DET0 (BIT(25)) 64 | #define BIT_DET1 (BIT(2)) 65 | #define BIT_DET2 (BIT(3)) 66 | #define BIT_DET3 (BIT(4)) 67 | #define BIT_WAKE_UP (BIT(30)) 68 | 69 | 70 | extern volatile bool flag_active_defense_trigger; 71 | extern volatile bool flag_passtive_defense_trigger; 72 | 73 | 74 | /************************************************************************ 75 | * function : gpio_init 76 | * Description: gpio initial 77 | * input : none 78 | * return: none 79 | ************************************************************************/ 80 | void gpio_init(void); 81 | bool gpio_high(uint32_t bit, uint32_t durationMS); 82 | bool gpio_low(uint32_t bit, uint32_t durationMS); 83 | 84 | #endif 85 | 86 | -------------------------------------------------------------------------------- /source/crypto/pbkdf2.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2013-2014 Tomas Dzetkulic 3 | * Copyright (c) 2013-2014 Pavol Rusnak 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining 6 | * a copy of this software and associated documentation files (the "Software"), 7 | * to deal in the Software without restriction, including without limitation 8 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | * and/or sell copies of the Software, and to permit persons to whom the 10 | * Software is furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included 13 | * in all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 16 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 18 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 19 | * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 20 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 21 | * OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | 24 | #ifndef __PBKDF2_H__ 25 | #define __PBKDF2_H__ 26 | 27 | #include 28 | #include "sha2.h" 29 | 30 | typedef struct _PBKDF2_HMAC_SHA256_CTX { 31 | uint32_t odig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)]; 32 | uint32_t idig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)]; 33 | uint32_t f[SHA256_DIGEST_LENGTH / sizeof(uint32_t)]; 34 | uint32_t g[SHA256_BLOCK_LENGTH / sizeof(uint32_t)]; 35 | char first; 36 | } PBKDF2_HMAC_SHA256_CTX; 37 | 38 | typedef struct _PBKDF2_HMAC_SHA512_CTX { 39 | uint64_t odig[SHA512_DIGEST_LENGTH / sizeof(uint64_t)]; 40 | uint64_t idig[SHA512_DIGEST_LENGTH / sizeof(uint64_t)]; 41 | uint64_t f[SHA512_DIGEST_LENGTH / sizeof(uint64_t)]; 42 | uint64_t g[SHA512_BLOCK_LENGTH / sizeof(uint64_t)]; 43 | char first; 44 | } PBKDF2_HMAC_SHA512_CTX; 45 | 46 | void pbkdf2_hmac_sha256_Init(PBKDF2_HMAC_SHA256_CTX *pctx, const uint8_t *pass, 47 | int passlen, const uint8_t *salt, int saltlen, 48 | uint32_t blocknr); 49 | void pbkdf2_hmac_sha256_Update(PBKDF2_HMAC_SHA256_CTX *pctx, 50 | uint32_t iterations); 51 | void pbkdf2_hmac_sha256_Final(PBKDF2_HMAC_SHA256_CTX *pctx, uint8_t *key); 52 | void pbkdf2_hmac_sha256(const uint8_t *pass, int passlen, const uint8_t *salt, 53 | int saltlen, uint32_t iterations, uint8_t *key, 54 | int keylen); 55 | 56 | void pbkdf2_hmac_sha512_Init(PBKDF2_HMAC_SHA512_CTX *pctx, const uint8_t *pass, 57 | int passlen, const uint8_t *salt, int saltlen, 58 | uint32_t blocknr); 59 | void pbkdf2_hmac_sha512_Update(PBKDF2_HMAC_SHA512_CTX *pctx, 60 | uint32_t iterations); 61 | void pbkdf2_hmac_sha512_Final(PBKDF2_HMAC_SHA512_CTX *pctx, uint8_t *key); 62 | void pbkdf2_hmac_sha512(const uint8_t *pass, int passlen, const uint8_t *salt, 63 | int saltlen, uint32_t iterations, uint8_t *key, 64 | int keylen); 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /source/system/system_se.h: -------------------------------------------------------------------------------- 1 | #ifndef __SYSTEM_SE_H__ 2 | #define __SYSTEM_SE_H__ 3 | 4 | #include "common.h" 5 | 6 | #ifdef __cplusplus 7 | extern "C" 8 | { 9 | #endif 10 | 11 | //#define LOW_POWER 12 | 13 | /*----------------lower power bit--------------------*/ 14 | #define BIT_EFC (1<<0) 15 | //#define BIT_RSV (1<<1) 16 | #define BIT_ROM (1<<2) 17 | #define BIT_WDT (1<<3) 18 | #define BIT_TIMER (1<<4) 19 | #define BIT_GPIO (1<<5) 20 | #define BIT_7816MS (1<<6) 21 | #define BIT_USB (1<<7) 22 | #define BIT_SPIA (1<<8) 23 | #define BIT_SPIB (1<<9) 24 | #define BIT_UARTA (1<<10) 25 | #define BIT_UARTB (1<<11) 26 | #define BIT_CRC (1<<12) 27 | #define BIT_I2C (1<<13) 28 | #define BIT_SENSOR (1<<14) 29 | #define BIT_HRNG (1<<15) 30 | #define BIT_DES (1<<16) 31 | #define BIT_SM4 (1<<17) 32 | #define BIT_SM1 (1<<18) 33 | #define BIT_PKI (1<<19) 34 | #define BIT_SM3 (1<<20) 35 | #define BIT_AES (1<<21) 36 | #define enable_module(x) do{ REG_SCU_BCR |= (x); } while(0) 37 | #define disable_module(x) do{ REG_SCU_BCR &= ~(x); } while(0) 38 | #define init_module(value) do{ REG_SCU_BCR = (value); } while(0) 39 | 40 | /*----------------module reset bit--------------------*/ 41 | #define RESET_EFC (1<<16) 42 | #define RESET_SENSOR (1<<17) 43 | #define RESET_I2C (1<<18) 44 | #define RESET_WDT (1<<19) 45 | #define RESET_CRC (1<<20) 46 | #define RESET_GPIO (1<<21) 47 | #define RESET_7816MS (1<<22) 48 | #define RESET_TIMER (1<<23) 49 | #define RESET_UARTB (1<<24) 50 | #define RESET_UARTA (1<<25) 51 | #define RESET_SPIB (1<<26) 52 | #define RESET_SPIA (1<<27) 53 | #define RESET_USB (1<<28) 54 | #define RESET_UAC (1<<29) 55 | #define reset_module(x) do{ REG_SCU_RCR &= ~(x); delay(5); REG_SCU_RCR |= (x); } while(0) 56 | 57 | #define CLK_SRC_RC48M (0x00) //clk src from RC48M 58 | #define CLK_SRC_RC32 (0x01) //clk src from RC32K 59 | #define CLK_SRC_PLL48 (0x02) //clk src from PLL48M 60 | 61 | #define CLK_DIV_CORE (0<<0) //no div freq 62 | #define CLK_DIV_ALG (0<<8) //no div freq 63 | #define CLK_DIV_SPI (1<<12) // 2 div 64 | #define CLK_DIV_HRNGS (47<<17) //HRNGS = 1Mhz 65 | 66 | extern uint32_t SystemCoreClock; //core/HCLK (uint:Hz) 67 | extern uint32_t SRCClock; //source clk_src (uint:Hz) 68 | extern uint32_t PClock; //APB PCLK (uint:Hz) 69 | 70 | /************************************************************************ 71 | * function : SystemInit 72 | * Description: SystemInit 73 | * input : none 74 | * return: none 75 | ************************************************************************/ 76 | void SystemInit(void); 77 | 78 | /************************************************************************ 79 | * function : clock_init 80 | * Description: clock init, initil several clock variables 81 | * input : 82 | * uint32_t system_clk_mhz: expected system core clock 83 | * return: none 84 | ************************************************************************/ 85 | void clock_init(uint32_t system_clk_mhz); 86 | 87 | 88 | void SystemCoreClockUpdate(void); 89 | 90 | 91 | #ifdef __cplusplus 92 | } 93 | #endif 94 | 95 | #endif 96 | -------------------------------------------------------------------------------- /source/driver/eflash.c: -------------------------------------------------------------------------------- 1 | #include "eflash.h" 2 | 3 | UINT8 eflash_write_word(UINT32 addr, UINT32 value) 4 | { 5 | UINT8 vf; 6 | REG_EFC_CTRL |= EFC_WRITE_MODE; 7 | #ifdef EFLASH_VERIFY_EN 8 | REG_EFC_CTRL |= EFC_PROGRAM_VRI_EN; 9 | #endif 10 | REG_EFC_SEC = 0x55AAAA55; 11 | *((volatile UINT32 *)(addr)) = value; 12 | while(!(REG_EFC_STATUS & 0x01)); 13 | REG_EFC_CTRL &= ~EFC_WRITE_MODE; 14 | vf = 0; 15 | 16 | #ifdef EFLASH_VERIFY_EN 17 | while(!(REG_EFC_INTSTATUS & (0x01 << 4))); 18 | REG_EFC_INTSTATUS = (0x01 << 4); 19 | if(REG_EFC_INTSTATUS & (0x01 << 6)) //vf error 20 | { 21 | REG_EFC_INTSTATUS = (0x01 << 6); 22 | vf = 1; 23 | } 24 | REG_EFC_CTRL &= ~EFC_PROGRAM_VRI_EN; 25 | #endif 26 | 27 | return vf; 28 | } 29 | 30 | /************************************************************************ 31 | * function : eflash_erase_page 32 | * Description: eflash erase page 33 | * input : 34 | * UINT32 page_addr: page address 35 | * return: 0--success 1--fail 36 | ************************************************************************/ 37 | UINT8 eflash_erase_page(UINT32 page_addr) 38 | { 39 | UINT8 vf; 40 | 41 | REG_EFC_CTRL |= EFC_PAGE_ERASE_MODE; 42 | REG_EFC_SEC = 0x55AAAA55; 43 | *((volatile UINT32 *)(page_addr)) = 0; 44 | while(!(REG_EFC_STATUS & 0x01)); 45 | REG_EFC_CTRL &= ~EFC_PAGE_ERASE_MODE; 46 | vf = 0; 47 | 48 | #ifdef EFLASH_VERIFY_EN 49 | REG_EFC_ADCT = (page_addr) >> 2; 50 | REG_EFC_CTRL |= EFC_ERASE_VRI_EN; 51 | while(!(REG_EFC_INTSTATUS & (0x01 << 4))); 52 | REG_EFC_INTSTATUS = (0x01 << 4); 53 | if(REG_EFC_INTSTATUS & (0x01 << 3)) //vf error 54 | { 55 | REG_EFC_INTSTATUS = (0x01 << 3); 56 | vf = 1; 57 | } 58 | #endif 59 | 60 | return vf; 61 | } 62 | 63 | 64 | void eflash_read_page(UINT32 *buff, UINT32 pageBaseAddr) 65 | { 66 | UINT32 i; 67 | 68 | for(i = 0; i < (PAGE_SIZE >> 2); i++) 69 | { 70 | buff[i] = eflash_read_word(pageBaseAddr + (i << 2)); 71 | } 72 | } 73 | 74 | void eflash_write_page(UINT32 *buff, UINT32 pageBaseAddr) 75 | { 76 | UINT32 i; 77 | 78 | for(i = 0; i < (PAGE_SIZE >> 2); i++) 79 | { 80 | eflash_write_word(pageBaseAddr + (i << 2), buff[i]); 81 | } 82 | } 83 | 84 | void eflash_erase_pages(UINT32 startPageAddr, UINT32 pageCnt) 85 | { 86 | UINT32 i; 87 | 88 | for(i = 0; i < pageCnt; i++) 89 | { 90 | eflash_erase_page(startPageAddr + i * PAGE_SIZE); 91 | } 92 | } 93 | 94 | void eflash_rewrite_word(UINT32 addr, UINT32 value) 95 | { 96 | UINT32 buff[PAGE_SIZE >> 2]; 97 | UINT32 page_addr; //page base address 98 | 99 | if(eflash_read_word(addr) == value) 100 | { 101 | return; 102 | } 103 | 104 | //if(eflash_read_word(addr) == 0xFFFFFFFF) 105 | if(eflash_read_word(addr) == *((UINT32 *)SM_FLASH_FF_VALUE_ADDR)) 106 | { 107 | eflash_write_word(addr,value); 108 | return; 109 | } 110 | 111 | page_addr = addr & (~(PAGE_SIZE - 1)); 112 | 113 | eflash_read_page(buff, page_addr); 114 | buff[(addr - page_addr) >> 2] = value; 115 | eflash_erase_page(page_addr); 116 | 117 | eflash_write_page(buff, page_addr); 118 | } 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /source/mason/mason_iap.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_ISP_H 19 | #define MASON_ISP_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef MASON_ISP_GLOBAL 23 | #define MASON_ISP_EXT 24 | #else 25 | #define MASON_ISP_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include "mason_errno.h" 35 | #include "mason_flash_partition.h" 36 | #include "mason_storage.h" 37 | 38 | /** Compatibility with the cplusplus*/ 39 | #ifdef __cplusplus 40 | extern "C" 41 | { 42 | #endif /* __cplusplus */ 43 | 44 | /** Macro definitions*/ 45 | #define FLAG_MASK (0x8F3D945A) //just random value 46 | #define ADD_MASK(X) (FLAG_MASK ^ (X)) 47 | #define OFF_MASK(X) (FLAG_MASK ^ (X)) 48 | 49 | #define FLAG_BOOT_ADDR1 ADD_MASK(FLASH_ADDR_BOOT1_START) 50 | #define FLAG_BOOT_ADDR2 ADD_MASK(FLASH_ADDR_BOOT2_START) 51 | #define FLAG_APP_EXIST ADD_MASK(0x3FF307FC) //just random value 52 | #define FLAG_APP_NOT_EXIST (~FLAG_APP_EXIST) 53 | #define FLAG_APP_UPGRADED ADD_MASK(0x2812A242) //just random value 54 | #define FLAG_APP_NO_UPGRAD (~FLAG_APP_UPGRADED) 55 | 56 | /** Variable declarations */ 57 | typedef enum 58 | { 59 | E_PACK_FIRST = 0x00, 60 | E_PACK_CONTINUE, 61 | E_PACK_LAST, 62 | E_PACK_HDR, 63 | E_PACK_ERR 64 | } emFwPackTypeType; 65 | 66 | /** Function declarations */ 67 | __inline emRetType 68 | mason_iap_set_app_not_exist(void) 69 | { 70 | return mason_storage_write_flag_safe(FLASH_ADDR_APP_EXIST_4B, FLAG_APP_NOT_EXIST); 71 | } 72 | 73 | __inline emRetType 74 | mason_iap_set_app_exist(void) 75 | { 76 | return mason_storage_write_flag_safe(FLASH_ADDR_APP_EXIST_4B, FLAG_APP_EXIST); 77 | } 78 | 79 | __inline emRetType 80 | mason_iap_set_app_upgraded(void) 81 | { 82 | return mason_storage_write_flag_safe(FLASH_ADDR_APP_UPGRADED_4B, FLAG_APP_UPGRADED); 83 | } 84 | 85 | __inline emRetType 86 | mason_iap_set_app_not_upgrade(void) 87 | { 88 | return mason_storage_write_flag_safe(FLASH_ADDR_APP_UPGRADED_4B, FLAG_APP_NOT_EXIST); 89 | } 90 | 91 | emRetType 92 | mason_iap_pack_verify_process(emFwPackTypeType emFwPackType, uint8_t *pBin, uint32_t binLen); 93 | 94 | /** Compatibility with the cplusplus*/ 95 | #ifdef __cplusplus 96 | } /* Extern C */ 97 | #endif 98 | 99 | #endif 100 | -------------------------------------------------------------------------------- /source/COMMON/macro.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef _MACRO_H_ 19 | #define _MACRO_H_ 20 | 21 | /** General constants macro definitions*/ 22 | //#define NULL 0 23 | #define EOF -1 24 | #define TRUE 1 25 | #define FALSE 0 26 | #define YES 1 27 | #define NO 0 28 | #define ON 1 29 | #define OFF 0 30 | #define ENABLE 1 31 | #define DISABLE 0 32 | #define CRR 1 33 | #define ERR 0 34 | #define RIGHT 1 35 | #define WRONG 0 36 | #define SUCCESS 1 37 | #define FAILURE 0 38 | #define OK 1 39 | #define FAIL 0 40 | #define PI 3.1415926 //3.1415926535897932 41 | 42 | #ifndef BIT 43 | #define BIT(x) (1 << (x)) 44 | #endif 45 | 46 | #ifndef _BV 47 | #define _BV(x) (1 << (x)) 48 | #endif 49 | /** General expression definitions*/ 50 | #define _CALLOC(a) ((a *)calloc(n, sizeof(a))) 51 | #define _MALLOC(a) ((a *)malloc(sizeof(a))) 52 | #define _MIN(a, b) ((a) < (b) ? (a) : (b)) 53 | #define _MAX(a, b) ((a) > (b) ? (a) : (b)) 54 | #define _EXCHANGE(a,b) { int t; t=(a); (a)=(b); (b)=t; } 55 | #define _SWAP(a,b) { if((a)==(b))return;(a)^=(b);(b)^=(a);(a)^=(b); } 56 | #define _ToLower(c) ((c) + 32) 57 | #define _ToUpper(c) ((c)-32) 58 | 59 | #define SET(Reg, n) Reg |= BIT(n); 60 | #define CLR(Reg, n) Reg &= ~BIT(n); 61 | 62 | #define _atomic(Codes) \ 63 | cli(); \ 64 | Codes; \ 65 | sei(); 66 | 67 | /**FUNCTION**************************************************************************************** 68 | * @functionname: 69 | * @description: changeIntToHex(33),return 0x33 70 | * @para: 71 | * @return: 72 | */ 73 | #define changeIntToHex(dec) ((((dec) / 10) << 4) + ((dec) % 10)) 74 | /**FUNCTION**************************************************************************************** 75 | * @functionname: 76 | * @description: converseIntToHex(33),return 21 77 | * @para: 78 | * @return: 79 | */ 80 | #define converseIntToHex(dec) ((((dec) >> 4) * 10) + ((dec) % 16)) 81 | /**FUNCTION**************************************************************************************** 82 | * @functionname: 83 | * @description: changeHexToInt(0x33),return 33 84 | * @para: 85 | * @return: 86 | */ 87 | #define changeHexToInt(hex) ((((hex) >> 4) * 10) + ((hex) % 16)) 88 | /**FUNCTION**************************************************************************************** 89 | * @functionname: 90 | * @description: converseHexToInt(0x33),return 51 91 | * @para: 92 | * @return: 93 | */ 94 | #define converseHexToInt(hex) ((((hex) / 10) << 4) + ((hex) % 10)) 95 | 96 | #endif -------------------------------------------------------------------------------- /source/COMMON/util.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef UTIL_H 19 | #define UTIL_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef UTIL_GLOBAL 23 | #define UTIL_EXT 24 | #else 25 | #define UTIL_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | /** Compatibility with the cplusplus*/ 38 | #ifdef __cplusplus 39 | extern "C" 40 | { 41 | #endif /* __cplusplus */ 42 | 43 | /** Macro definitions*/ 44 | #define TO_SHORT(H8, L8) ((uint16_t)(((uint16_t)H8 << 8) || ((uint16_t)L8))) 45 | 46 | /** Variable declarations */ 47 | typedef enum 48 | { 49 | ANSIX923, 50 | ISO10126, 51 | PKCS7, 52 | PKCS5, 53 | NoPadding 54 | } emPaddingType; 55 | 56 | /** Function declarations */ 57 | int atou8(uint8_t ascDat); 58 | uint8_t u8toa(uint8_t dat); 59 | void str_to_hex(uint8_t *bufBcd, uint32_t *bufBcdLen, uint8_t *str, int strLen); 60 | void hex_to_str(uint8_t *str, uint32_t *strLen, uint8_t *bufBcd, uint32_t bufBcdLen); 61 | void u16_to_buf(uint8_t *buf, uint16_t u16); 62 | void u32_to_buf(uint8_t *buf, uint32_t u32); 63 | void u64_to_le_buf(uint64_t u64, uint8_t *buf); 64 | void buf_to_u16(uint16_t *pu16, uint8_t *buf); 65 | void buf_to_u32(uint32_t *pu32, uint8_t *buf); 66 | unsigned int myatoui(const char *str); 67 | bool myatoui64(const char *str, uint64_t *ui64); 68 | bool is_number(const uint8_t *pnum, uint16_t len); 69 | uint16_t buf_return_u16(uint8_t *buf); 70 | uint32_t buf_return_u32(uint8_t *buf); 71 | void swap_fast(uint8_t *num1, uint8_t *num2); 72 | uint8_t endian_exchange(uint8_t *buf, uint16_t bufLen, uint8_t alignLen); 73 | void str_reverse(uint8_t *pStr, uint32_t strLen); 74 | int8_t sequence_compare_bit8(const uint8_t *pBuf1, const uint8_t *pBuf2, uint32_t bufLen); 75 | bool sequence_all_zero(const uint8_t *pBuf, uint32_t bufLen); 76 | void data_padding(uint8_t *pMsg, uint16_t *msgLen, emPaddingType emPadding); 77 | void memzero(void* const pnt, const size_t len); 78 | uint8_t get_lrc(uint8_t *pMsg, uint16_t msgLen); 79 | bool memcmp_ATA(const uint8_t *buf1, const uint8_t *buf2, uint16_t len); 80 | void debug_key(char *name, uint8_t *key, uint16_t len); 81 | void gen_random(uint8_t *output_random, uint16_t bits); 82 | 83 | /** Compatibility with the cplusplus*/ 84 | #ifdef __cplusplus 85 | } /* Extern C */ 86 | #endif 87 | 88 | #endif 89 | -------------------------------------------------------------------------------- /source/crypto/crypto_api.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef CRYPTO_API_H 19 | #define CRYPTO_API_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef CRYPTO_API_GLOBAL 23 | #define CRYPTO_API_EXT 24 | #else 25 | #define CRYPTO_API_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include 35 | #include 36 | #include 37 | 38 | /** Compatibility with the cplusplus*/ 39 | #ifdef __cplusplus 40 | extern "C" 41 | { 42 | #endif /* __cplusplus */ 43 | 44 | /** Macro definitions*/ 45 | #ifndef SHA256_LEN 46 | #define SHA256_LEN 32 47 | #endif 48 | #ifndef SHA512_LEN 49 | #define SHA512_LEN 64 50 | #endif 51 | #ifndef RPMD160_LEN 52 | #define RPMD160_LEN 20 53 | #endif 54 | 55 | typedef enum crypto_curve_e 56 | { 57 | CRYPTO_CURVE_SECP256K1 = 0, 58 | CRYPTO_CURVE_SECP256R1, 59 | CRYPTO_CURVE_ED25519, 60 | CRYPTO_CURVE_SR25519, 61 | } crypto_curve_t; 62 | 63 | /** Function declarations */ 64 | bool ecdsa_sign( 65 | crypto_curve_t curve, 66 | uint8_t *hash, 67 | uint16_t hash_len, 68 | uint8_t *private_key, 69 | uint8_t *signature, 70 | uint16_t *signature_len); 71 | 72 | bool ecdsa_verify(crypto_curve_t curve, uint8_t *hash, uint8_t *public_key, uint8_t *signature); 73 | bool is_valid_private_key(crypto_curve_t curve, uint8_t *private_key); 74 | 75 | bool crypto_init(void); 76 | void ed25519_private_key_to_public_key(uint8_t *private_key, uint8_t *public_key); 77 | bool crypto_api_rsa_decrypt(uint8_t *private_key_n, uint16_t n_len, uint8_t *private_key_d, 78 | uint16_t d_len, uint8_t *encrypted_data, uint16_t encrypted_data_len, 79 | uint8_t *output, uint16_t *output_len); 80 | CRYPTO_API_EXT void ripeMD160_api(uint8_t *pData, uint32_t len, uint8_t *pDigest); 81 | CRYPTO_API_EXT void sha256_api(uint8_t *pData, uint32_t len, uint8_t *pDigest); 82 | CRYPTO_API_EXT void sha512_api(uint8_t *pData, uint32_t len, uint8_t *pDigest); 83 | CRYPTO_API_EXT void hmac_sha512_api(uint8_t *pData, uint32_t dataLen, 84 | uint8_t *pKey, uint32_t keyLen, uint8_t *pDigest); 85 | 86 | /** Compatibility with the cplusplus*/ 87 | #ifdef __cplusplus 88 | } /* Extern C */ 89 | #endif 90 | 91 | #endif 92 | -------------------------------------------------------------------------------- /source/COMMON/circular_buffer.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef CIRCULAR_BUFFER_H 19 | #define CIRCULAR_BUFFER_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef CIRCULAR_BUFFER_GLOBAL 23 | #define CIRCULAR_BUFFER_EXT 24 | #else 25 | #define CIRCULAR_BUFFER_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | 35 | /** Compatibility with the cplusplus*/ 36 | #ifdef __cplusplus 37 | extern "C" 38 | { 39 | #endif /* __cplusplus */ 40 | 41 | /** Variable declarations */ 42 | // The hidden definition of our circular buffer structure 43 | struct circular_buf_t 44 | { 45 | uint8_t *buffer; 46 | size_t head; 47 | size_t tail; 48 | size_t max; //of the buffer 49 | bool full; 50 | }; 51 | // Opaque circular buffer structure 52 | typedef struct circular_buf_t circular_buf_t; 53 | // Handle type, the way users interact with the API 54 | typedef circular_buf_t *cbuf_handle_t; 55 | 56 | /** Function declarations */ 57 | /// Pass in a storage buffer and size 58 | /// Returns a circular buffer handle 59 | cbuf_handle_t circular_buf_init(uint8_t *buffer, size_t size); 60 | 61 | /// Free a circular buffer structure. 62 | /// Does not free data buffer; owner is responsible for that 63 | void circular_buf_free(cbuf_handle_t cbuf); 64 | 65 | /// Reset the circular buffer to empty, head == tail 66 | void circular_buf_reset(cbuf_handle_t cbuf); 67 | 68 | /// Put version 1 continues to add data if the buffer is full 69 | /// Old data is overwritten 70 | void circular_buf_put(cbuf_handle_t cbuf, uint8_t data); 71 | 72 | /// Put Version 2 rejects new data if the buffer is full 73 | /// Returns 0 on success, -1 if buffer is full 74 | int circular_buf_put2(cbuf_handle_t cbuf, uint8_t data); 75 | 76 | /// Retrieve a value from the buffer 77 | /// Returns 0 on success, -1 if the buffer is empty 78 | int circular_buf_get(cbuf_handle_t cbuf, uint8_t *data); 79 | 80 | /// Returns true if the buffer is empty 81 | bool circular_buf_empty(cbuf_handle_t cbuf); 82 | 83 | /// Returns true if the buffer is full 84 | bool circular_buf_full(cbuf_handle_t cbuf); 85 | 86 | /// Returns the maximum capacity of the buffer 87 | size_t circular_buf_capacity(cbuf_handle_t cbuf); 88 | 89 | /// Returns the current number of elements in the buffer 90 | size_t circular_buf_size(cbuf_handle_t cbuf); 91 | 92 | /** Compatibility with the cplusplus*/ 93 | #ifdef __cplusplus 94 | } /* Extern C */ 95 | #endif 96 | 97 | #endif 98 | -------------------------------------------------------------------------------- /source/mason/mason_hdw.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_HDW_H 19 | #define MASON_HDW_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef MASON_HDW_GLOBAL 23 | #define MASON_HDW_EXT 24 | #else 25 | #define MASON_HDW_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include "mason_errno.h" 35 | #include "mason_iap.h" 36 | 37 | /** Compatibility with the cplusplus*/ 38 | #ifdef __cplusplus 39 | extern "C" 40 | { 41 | #endif /* __cplusplus */ 42 | 43 | /** Macro definitions*/ 44 | #define PRV_KEY_LEN 32 45 | #define PUB_KEY_LEN 64 46 | #define SHA256_LEN 32 47 | #define SHA512_LEN 64 48 | #define RPMD160_LEN 20 49 | #define HASH_LEN SHA256_LEN 50 | #define MD5_LEN 16 51 | #define SIG_LEN 64 52 | #define CHECKSUM_LEN 4 53 | #define SEED_LEN SHA512_LEN 54 | #define DES3_KEY_LEN 24 55 | #define DES3_IV_LEN 8 56 | #define RSA_KEY_LEN 512 57 | 58 | /* macro below mapped to gstHDWStatus value*/ 59 | #define HDW_STATUS_CHIP 0 60 | #define HDW_STATUS_FACTORY 1 61 | #define HDW_STATUS_ATTACK 2 62 | #define HDW_STATUS_EMPTY 3 63 | #define HDW_STATUS_WALLET 4 64 | #define HDW_STATUS_MAX 5 65 | 66 | /** Variable definitions */ 67 | MASON_HDW_EXT volatile uint8_t gDebugSwitchOn; 68 | typedef enum 69 | { 70 | E_HDWS_CHIP = 0x00, 71 | E_HDWS_FACTORY = 0xFA, 72 | E_HDWS_ATTACK = 0xA0, 73 | E_HDWS_EMPTY = 0xCB, 74 | E_HDWS_WALLET = 0x88, 75 | E_HDWS_MAX = 0x7FFFFFFF 76 | } emHDWStatusType; 77 | MASON_HDW_EXT volatile emHDWStatusType gemHDWStatus; 78 | 79 | typedef struct 80 | { 81 | emHDWStatusType emHDWStatus; 82 | char pSymbol[4]; 83 | } stHDWStatusType; 84 | MASON_HDW_EXT const volatile stHDWStatusType gstHDWStatus[]; 85 | 86 | typedef enum 87 | { 88 | E_HDWM_MNEMONIC = 0x00, 89 | E_HDWM_PASSPHRASE = 0x50, 90 | } emHDWSwitchType; 91 | MASON_HDW_EXT volatile emHDWSwitchType gemHDWSwitch; 92 | 93 | /** Function declarations */ 94 | void mason_HDW_gen_sha256(uint8_t *pText, uint32_t textLen, uint8_t *pCheckSum, uint8_t checkSumLen); 95 | bool mason_HDW_check_sha256(uint8_t *pText, uint32_t textLen, uint8_t *pCheckSum); 96 | void mason_HDW_gen_sha256sha256(uint8_t *pText, uint32_t textLen, uint8_t *pCheckSum, uint8_t checkSumLen); 97 | bool mason_HDW_check_sha256sha256(uint8_t *pText, uint32_t textLen, uint8_t *pCheckSum); 98 | bool mason_get_mode(volatile stHDWStatusType *status); 99 | bool mason_set_mode(uint8_t type); 100 | emRetType mason_get_appvercode(uint32_t *vercode); 101 | emRetType mason_set_appvercode(void); 102 | 103 | /** Compatibility with the cplusplus*/ 104 | #ifdef __cplusplus 105 | } /* Extern C */ 106 | #endif 107 | 108 | #endif 109 | -------------------------------------------------------------------------------- /source/mason/mason_key.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_KEY_H_ 19 | #define MASON_KEY_H_ 20 | 21 | /** Header file reference */ 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | /** Macro definitions*/ 28 | #define PRIVATE_KEY_LEN 32 29 | #define PUBLIC_KEY_LEN 64 30 | #define COMPRESSED_PUBLIC_KEY_LEN 33 31 | #define CHAINCODE_LEN 32 32 | 33 | /** Variable definitions */ 34 | enum key_version_e 35 | { 36 | KEY_VERSION_MAINNET_PUBLIC = 0x0488B21E, 37 | KEY_VERSION_MAINNET_PRIVATE = 0x0488ADE4, 38 | KEY_VERSION_TESTNET_PUBLIC = 0x043587CF, 39 | KEY_VERSION_TESTNET_PRIVATE = 0x04358394 40 | }; 41 | 42 | /*private key*/ 43 | typedef struct private_key_s 44 | { 45 | uint8_t data[PRIVATE_KEY_LEN]; 46 | uint16_t len; 47 | } private_key_t; 48 | 49 | /*public key*/ 50 | typedef struct public_key_s 51 | { 52 | uint8_t data[PUBLIC_KEY_LEN]; 53 | uint16_t len; 54 | } public_key_t; 55 | 56 | /* compressed pub key*/ 57 | typedef struct compressed_public_key_s 58 | { 59 | uint8_t data[COMPRESSED_PUBLIC_KEY_LEN]; 60 | } compressed_public_key_t; 61 | 62 | /* chain code*/ 63 | typedef struct chaincode_s 64 | { 65 | uint8_t data[CHAINCODE_LEN]; 66 | } chaincode_t; 67 | 68 | typedef struct extended_key_s 69 | { 70 | uint8_t version[4]; 71 | uint8_t depth; 72 | uint8_t fingerprint[4]; 73 | uint8_t child_number[4]; 74 | uint8_t chaincode[CHAINCODE_LEN]; 75 | uint8_t key[COMPRESSED_PUBLIC_KEY_LEN]; 76 | uint8_t checksum[4]; 77 | } __attribute__((packed)) extended_key_t; 78 | 79 | /** Function declarations */ 80 | bool ckd_private_to_public( 81 | private_key_t *parent_private_key, 82 | chaincode_t *parent_chaincode, 83 | uint32_t index, 84 | public_key_t *child_public_key, 85 | chaincode_t *child_chaincode); 86 | 87 | bool ckd_private_to_private( 88 | crypto_curve_t curve, 89 | private_key_t *parent_private_key, 90 | chaincode_t *parent_chaincode, 91 | uint32_t index, 92 | private_key_t *child_private_key, 93 | chaincode_t *child_chaincode); 94 | 95 | void private_key_to_public_key( 96 | crypto_curve_t curve, 97 | private_key_t *private_key, 98 | public_key_t *public_key); 99 | 100 | void public_key_to_compressed_public_key( 101 | public_key_t *public_key, 102 | compressed_public_key_t *compressed_public_key); 103 | 104 | void private_key_to_compressed_public_key( 105 | crypto_curve_t curve, 106 | private_key_t *private_key, 107 | compressed_public_key_t *compressed_public_key); 108 | 109 | void private_key_to_fingerprint( 110 | crypto_curve_t curve, 111 | private_key_t *private_key, 112 | uint8_t *fingerprint, 113 | uint16_t fingerprint_len); 114 | 115 | #endif 116 | -------------------------------------------------------------------------------- /source/driver/hrng.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __HRNG_H__ 3 | #define __HRNG_H__ 4 | 5 | #include "common.h" 6 | 7 | /********************************************************************************* 8 | * Function Name : hrng_initial 9 | * Description : config hrng module 10 | * Input : - ctrl : input ctrl reg data; 11 | : - cmpres : input cmpres reg data; 12 | * Output : None 13 | * Return : None 14 | *********************************************************************************/ 15 | void hrng_initial(void); 16 | /********************************************************************************* 17 | * Function Name : hrng_source_disable 18 | * Description : disable hrng source 19 | * Input : - ctrl : input ctrl reg data; 20 | : - cmpres : input cmpres reg data; 21 | * Output : None 22 | * Return : None 23 | *********************************************************************************/ 24 | void hrng_source_disable(void); 25 | /********************************************************************************* 26 | * Function Name : get_hrng8 27 | * Description : get 8bit random number 28 | * Input : None 29 | * Output : None 30 | * Return : 8 bit random number 31 | *********************************************************************************/ 32 | UINT8 get_hrng8(void); 33 | 34 | /********************************************************************************* 35 | * Function Name : get_hrng32 36 | * Description : get 32bit random number 37 | * Input : None 38 | * Output : None 39 | * Return : 32 bit random number 40 | *********************************************************************************/ 41 | UINT32 get_hrng32(void); 42 | 43 | 44 | /********************************************************************************* 45 | * Function Name : get_hrng_16bytes 46 | * Description : get 16bytes random number 47 | * Input : None 48 | * Output : *hdata : the start address of random number the size must be 16bytes 49 | * Return : none 50 | *********************************************************************************/ 51 | void get_hrng_16bytes(UINT8 *hdata); 52 | 53 | /********************************************************************************* 54 | * Function Name : hrng_start_test 55 | * Description : get 16bytes random number,check if the continuous 5bytes is all one or zero 56 | * Input : None 57 | * Output : none 58 | * Return : 0: success; 1:fail 59 | *********************************************************************************/ 60 | UINT8 hrng_start_test(void); 61 | 62 | /********************************************************************************* 63 | * Function Name : hrng_poker_test 64 | * Description : poker 4 test 65 | * Input : n : the bit length of test hrng data 66 | * : m : poker test block length is 4 67 | * : *hdata_buf : test hrng data 68 | * Output : none 69 | * Return : 0: success; 1:fail 70 | *********************************************************************************/ 71 | UINT8 hrng_poker_test(UINT32 n, UINT32 m, UINT8 *hdata_buf); 72 | 73 | /********************************************************************************* 74 | * Function Name : get_hrng 75 | * Description : get random number 76 | * Input : byte_len : the byte length of random number 77 | * Output : *hdata : the start address of random number 78 | * Return : 0: hrng data is ok; 1: hrng data is bad 79 | *********************************************************************************/ 80 | UINT8 get_hrng(UINT8 *hdata, UINT32 byte_len); 81 | 82 | #endif 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /source/CMSIS/Include/core_cmFunc.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************//** 2 | * @file core_cmFunc.h 3 | * @brief CMSIS Cortex-M Core Function Access Header File 4 | * @version V4.30 5 | * @date 20. October 2015 6 | ******************************************************************************/ 7 | /* Copyright (c) 2009 - 2015 ARM LIMITED 8 | 9 | All rights reserved. 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions are met: 12 | - Redistributions of source code must retain the above copyright 13 | notice, this list of conditions and the following disclaimer. 14 | - Redistributions in binary form must reproduce the above copyright 15 | notice, this list of conditions and the following disclaimer in the 16 | documentation and/or other materials provided with the distribution. 17 | - Neither the name of ARM nor the names of its contributors may be used 18 | to endorse or promote products derived from this software without 19 | specific prior written permission. 20 | * 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 22 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE 25 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 26 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 27 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 28 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 29 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 30 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 31 | POSSIBILITY OF SUCH DAMAGE. 32 | ---------------------------------------------------------------------------*/ 33 | 34 | 35 | #if defined ( __ICCARM__ ) 36 | #pragma system_include /* treat file as system include file for MISRA check */ 37 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) 38 | #pragma clang system_header /* treat file as system include file */ 39 | #endif 40 | 41 | #ifndef __CORE_CMFUNC_H 42 | #define __CORE_CMFUNC_H 43 | 44 | 45 | /* ########################### Core Function Access ########################### */ 46 | /** \ingroup CMSIS_Core_FunctionInterface 47 | \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions 48 | @{ 49 | */ 50 | 51 | /*------------------ RealView Compiler -----------------*/ 52 | #if defined ( __CC_ARM ) 53 | #include "cmsis_armcc.h" 54 | 55 | /*------------------ ARM Compiler V6 -------------------*/ 56 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) 57 | #include "cmsis_armcc_V6.h" 58 | 59 | /*------------------ GNU Compiler ----------------------*/ 60 | #elif defined ( __GNUC__ ) 61 | #include "cmsis_gcc.h" 62 | 63 | /*------------------ ICC Compiler ----------------------*/ 64 | #elif defined ( __ICCARM__ ) 65 | #include 66 | 67 | /*------------------ TI CCS Compiler -------------------*/ 68 | #elif defined ( __TMS470__ ) 69 | #include 70 | 71 | /*------------------ TASKING Compiler ------------------*/ 72 | #elif defined ( __TASKING__ ) 73 | /* 74 | * The CMSIS functions have been implemented as intrinsics in the compiler. 75 | * Please use "carm -?i" to get an up to date list of all intrinsics, 76 | * Including the CMSIS ones. 77 | */ 78 | 79 | /*------------------ COSMIC Compiler -------------------*/ 80 | #elif defined ( __CSMC__ ) 81 | #include 82 | 83 | #endif 84 | 85 | /*@} end of CMSIS_Core_RegAccFunctions */ 86 | 87 | #endif /* __CORE_CMFUNC_H */ 88 | -------------------------------------------------------------------------------- /source/CMSIS/Include/core_cmInstr.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************//** 2 | * @file core_cmInstr.h 3 | * @brief CMSIS Cortex-M Core Instruction Access Header File 4 | * @version V4.30 5 | * @date 20. October 2015 6 | ******************************************************************************/ 7 | /* Copyright (c) 2009 - 2015 ARM LIMITED 8 | 9 | All rights reserved. 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions are met: 12 | - Redistributions of source code must retain the above copyright 13 | notice, this list of conditions and the following disclaimer. 14 | - Redistributions in binary form must reproduce the above copyright 15 | notice, this list of conditions and the following disclaimer in the 16 | documentation and/or other materials provided with the distribution. 17 | - Neither the name of ARM nor the names of its contributors may be used 18 | to endorse or promote products derived from this software without 19 | specific prior written permission. 20 | * 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 22 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE 25 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 26 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 27 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 28 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 29 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 30 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 31 | POSSIBILITY OF SUCH DAMAGE. 32 | ---------------------------------------------------------------------------*/ 33 | 34 | 35 | #if defined ( __ICCARM__ ) 36 | #pragma system_include /* treat file as system include file for MISRA check */ 37 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) 38 | #pragma clang system_header /* treat file as system include file */ 39 | #endif 40 | 41 | #ifndef __CORE_CMINSTR_H 42 | #define __CORE_CMINSTR_H 43 | 44 | 45 | /* ########################## Core Instruction Access ######################### */ 46 | /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface 47 | Access to dedicated instructions 48 | @{ 49 | */ 50 | 51 | /*------------------ RealView Compiler -----------------*/ 52 | #if defined ( __CC_ARM ) 53 | #include "cmsis_armcc.h" 54 | 55 | /*------------------ ARM Compiler V6 -------------------*/ 56 | #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) 57 | #include "cmsis_armcc_V6.h" 58 | 59 | /*------------------ GNU Compiler ----------------------*/ 60 | #elif defined ( __GNUC__ ) 61 | #include "cmsis_gcc.h" 62 | 63 | /*------------------ ICC Compiler ----------------------*/ 64 | #elif defined ( __ICCARM__ ) 65 | #include 66 | 67 | /*------------------ TI CCS Compiler -------------------*/ 68 | #elif defined ( __TMS470__ ) 69 | #include 70 | 71 | /*------------------ TASKING Compiler ------------------*/ 72 | #elif defined ( __TASKING__ ) 73 | /* 74 | * The CMSIS functions have been implemented as intrinsics in the compiler. 75 | * Please use "carm -?i" to get an up to date list of all intrinsics, 76 | * Including the CMSIS ones. 77 | */ 78 | 79 | /*------------------ COSMIC Compiler -------------------*/ 80 | #elif defined ( __CSMC__ ) 81 | #include 82 | 83 | #endif 84 | 85 | /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ 86 | 87 | #endif /* __CORE_CMINSTR_H */ 88 | -------------------------------------------------------------------------------- /source/mason/mason_setting.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_SETTING_H 19 | #define MASON_SETTING_H 20 | 21 | /** Header file reference */ 22 | #include 23 | #include 24 | #include 25 | 26 | /** Macro definitions*/ 27 | #define SETTING_STORE_PREFIX "USER" 28 | #define SETTING_STORE_PASS_SUFFIX "PASS" 29 | #define SETTING_STORE_CONT_SUFFIX "CONT" 30 | #define SETTING_STORE_FING_SUFFIX "FING" 31 | #define SETTING_STORE_SETT_SUFFIX "SETT" 32 | 33 | #define SETTING_COUNT_ERR_MAX 5 34 | // userpwd store have prefix and suffix 35 | #define SETTING_USRPWD_LEN (32) 36 | #define SETTING_COUNT_LEN (4) 37 | #define SETTING_USRFING_LEN (64) 38 | #define SETTING_SETTS_LEN (32) 39 | #define SETTING_PRESUF_LEN (8) 40 | #define SETTING_MESSAGE_LEN (32) 41 | #define SETTING_TOKEN_LEN (32) 42 | 43 | // user settings mask define 44 | #define SETTING_USRSETTINGS_SIGNFP (1 << 0) 45 | #define SETTING_USRSETTINGS_PHRASEFP (1 << 1) 46 | 47 | typedef enum 48 | { 49 | E_USRSETTINGS_SIGNFP = 0x00, 50 | E_USRSETTINGS_PHRASEFP = 0x01, 51 | E_USRSETTINGS_ERR, 52 | } emUsrSettingsType; 53 | 54 | /** Variable declarations */ 55 | typedef struct usrpwd_s 56 | { 57 | uint32_t length; 58 | uint8_t pwd[SETTING_USRPWD_LEN + SETTING_PRESUF_LEN]; 59 | } usrpwd_t; 60 | 61 | typedef struct usrcount_s 62 | { 63 | uint8_t count[SETTING_COUNT_LEN + SETTING_PRESUF_LEN]; 64 | } usrcount_t; 65 | 66 | typedef struct usrfing_s 67 | { 68 | uint32_t length; 69 | uint8_t fing[SETTING_USRFING_LEN + SETTING_PRESUF_LEN]; 70 | } usrfing_t; 71 | 72 | typedef struct usrsettings_s 73 | { 74 | uint32_t mask; 75 | uint8_t sett[SETTING_SETTS_LEN + SETTING_PRESUF_LEN]; 76 | } usrsettings_t; 77 | 78 | typedef struct setting_message_s 79 | { 80 | uint32_t length; 81 | uint8_t message[SETTING_MESSAGE_LEN]; 82 | } setting_message_t; 83 | 84 | typedef struct setting_token_s 85 | { 86 | uint32_t length; 87 | uint8_t token[SETTING_TOKEN_LEN]; 88 | } setting_token_t; 89 | 90 | /** Function declarations */ 91 | emRetType mason_usrpwd_verify(uint8_t *passwd, uint16_t passwd_len); 92 | bool mason_usrpwd_store(uint8_t *passwd, uint16_t passwd_len); 93 | void mason_usrcount_check(void); 94 | bool mason_usrcount_reset(void); 95 | void mason_usrcount_ara(void); 96 | bool mason_usrcount_increment(void); 97 | emRetType mason_usrfing_verify(uint8_t *sign, uint16_t sign_len); 98 | bool mason_usrfing_store(uint8_t *fing, uint16_t fing_len); 99 | bool mason_usrsettings_element_load(emUsrSettingsType type, uint8_t *value); 100 | bool mason_usrsettings_element_store(emUsrSettingsType type, uint8_t value); 101 | bool mason_message_gen(void); 102 | setting_message_t *mason_message_get(void); 103 | void mason_message_delete(void); 104 | bool mason_token_gen(void); 105 | setting_token_t *mason_token_get(void); 106 | emRetType mason_token_verify(setting_token_t *token); 107 | void mason_token_delete(void); 108 | void mason_setting_delete(void); 109 | 110 | #endif 111 | -------------------------------------------------------------------------------- /source/crypto/slip39_encrypt.c: -------------------------------------------------------------------------------- 1 | // 2 | // encrypt.c 3 | // 4 | // Copyright © 2020 by Blockchain Commons, LLC 5 | // Licensed under the "BSD-2-Clause Plus Patent License" 6 | // 7 | #include 8 | #include 9 | #include 10 | #include 11 | ////////////////////////////////////////////////// 12 | // encrypt/decrypt 13 | // 14 | 15 | // #include 16 | // #include 17 | // crypto.h used for the version 18 | // #include 19 | 20 | static const uint8_t customization[] = { 21 | 's', 'h', 'a', 'm', 'i', 'r', 22 | }; 23 | 24 | int32_t _get_salt( uint16_t identifier, uint8_t *result, uint32_t result_length); 25 | void feistel(uint8_t forward, const uint8_t *input, uint32_t input_length, const char *passphrase, 26 | uint8_t iteration_exponent, uint16_t identifier, uint8_t *output); 27 | 28 | int32_t _get_salt( 29 | uint16_t identifier, 30 | uint8_t *result, 31 | uint32_t result_length 32 | ) { 33 | if(result_length < 8) { 34 | return -1; 35 | } 36 | 37 | for(unsigned int i=0; i<6; ++i) { 38 | result[i] = customization[i]; 39 | } 40 | 41 | result[6] = identifier >> 8; 42 | result[7] = identifier & 0xff; 43 | return 8; 44 | } 45 | 46 | void round_function( 47 | uint8_t i, 48 | const char *passphrase, 49 | uint8_t exp, 50 | const uint8_t *salt, 51 | uint32_t salt_length, 52 | const uint8_t *r, 53 | uint32_t r_length, 54 | uint8_t *dest, 55 | uint32_t dest_length 56 | ) { 57 | uint32_t pass_length = (uint32_t)strlen(passphrase) + 1; 58 | uint8_t pass[pass_length+2]; 59 | sprintf( (char *) (pass+1), "%s", passphrase); 60 | pass[0] = i; 61 | uint32_t iterations = BASE_ITERATION_COUNT << exp; 62 | uint8_t saltr[salt_length + r_length]; 63 | 64 | memcpy(saltr, salt, salt_length); 65 | memcpy(saltr+salt_length, r, r_length); 66 | 67 | pbkdf2_hmac_sha256(pass, pass_length, 68 | saltr, salt_length+r_length, 69 | iterations, 70 | dest, dest_length); 71 | } 72 | 73 | void feistel( 74 | uint8_t forward, 75 | const uint8_t *input, 76 | uint32_t input_length, 77 | const char *passphrase, 78 | uint8_t iteration_exponent, 79 | uint16_t identifier, 80 | uint8_t *output 81 | ) { 82 | uint32_t half_length = input_length / 2; 83 | uint8_t *l, *r, *t, f[half_length]; 84 | uint8_t salt[8]; 85 | 86 | memcpy(output, input+half_length, half_length); 87 | memcpy(output + half_length, input, half_length); 88 | 89 | r = output; 90 | l = output+half_length; 91 | 92 | _get_salt(identifier, salt, 8); 93 | 94 | for(uint8_t i=0; i. 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_ERROR_DEF_H 19 | #define MASON_ERROR_DEF_H 20 | 21 | /** Header file reference */ 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | /** Compatibility with the cplusplus*/ 28 | #ifdef __cplusplus 29 | extern "C" 30 | { 31 | #endif /* __cplusplus */ 32 | 33 | /** Variable declarations */ 34 | typedef enum 35 | { 36 | ERT_OK = 0, 37 | ERT_Success = 0, 38 | ERT_Pass = 0, 39 | 40 | ERT_INIT_FAIL = 0x0100, 41 | ERT_InitRngFail, 42 | ERT_InitFlashFail, 43 | ERT_InitUartFail, 44 | ERT_InitTimerFail, 45 | 46 | ERT_COMM_FAIL = 0x0200, 47 | ERT_CommTimeOut, 48 | ERT_CommInvalidCMD, 49 | ERT_CommFailEncrypt, 50 | ERT_CommFailLen, 51 | ERT_CommFailEtx, 52 | ERT_CommFailLrc, 53 | ERT_CommFailTLV, 54 | ERT_CommFailParam, 55 | 56 | ERT_BIP_FAIL = 0x0300, 57 | ERT_InvalidKey, 58 | ERT_GenKeyFail, 59 | ERT_ECDSASignFail, 60 | ERT_ECDSAVerifyFail, 61 | ERT_ED25519SignFail, 62 | ERT_ED25519VerifyFail, 63 | ERT_SecpEncryptFail, 64 | ERT_SecpDecryptFail, 65 | ERT_SM2EncryptFail, 66 | ERT_SM2DecryptFail, 67 | ERT_CKD_Fail, 68 | ERT_MnemonicNotMatch, 69 | ERT_CoinTypeInvalid, 70 | ERT_SignFail, 71 | ERT_VerifyFail, 72 | 73 | ERT_CMD_FAIL = 0x0400, 74 | ERT_NeedPreCMD, 75 | ERT_MsgNeedEncrypt, 76 | ERT_USERWithoutPermission, 77 | ERT_TLVArrayExceed, 78 | ERT_tlvArray_to_buf, 79 | ERT_HDPathIllegal, 80 | ERT_VerConflict, 81 | ERT_HDWalletSwitchNeed, 82 | ERT_HDWalletSwitchNotMatch, 83 | ERT_needEntropy, 84 | 85 | ERT_CHIP_FAIL = 0x0500, 86 | ERT_RngFail, 87 | ERT_SFlashFail, 88 | ERT_MallocFail, 89 | ERT_CheckSumFail, 90 | ERT_CheckMD5Fail, 91 | ERT_FuncParamInvalid, 92 | ERT_3DESFail, 93 | ERT_StorageFail, 94 | ERT_GetStatsFail, 95 | ERT_RecIDFail, 96 | ERT_UnexpectedFail, 97 | ERT_RSASubFail, 98 | ERT_LenTooLong, 99 | ERT_SNConflict, 100 | ERT_SNLenInvalid, 101 | ERT_SNInvalid, 102 | 103 | ERT_IAP_FAIL = 0x0600, 104 | ERT_FWUpdateFail, 105 | ERT_PacklenInvalid, 106 | ERT_IAP_fileDigest, 107 | ERT_IAP_beyoundRetry, 108 | 109 | ERT_UsrPassFAIL = 0x0700, 110 | ERT_needUsrPass, 111 | ERT_UsrPassVerifyFail, 112 | ERT_UsrPassNotCreate, 113 | ERT_UsrPassParaERR, 114 | ERT_needUsrFing, 115 | ERT_UsrFingVerifyFail, 116 | ERT_UsrFingNotCreate, 117 | ERT_UsrFingParaERR, 118 | ERT_needMessageSign, 119 | ERT_needToken, 120 | ERT_TokenVerifyFail, 121 | ERT_UsrSettingsLoadFail, 122 | ERT_UsrSettingsStoreFail, 123 | ERT_UsrSettingsNotAllow, 124 | 125 | ERT_Verify_Init = 0x0800, 126 | ERT_VerifyValueFail, 127 | ERT_VerifyLenFail, 128 | 129 | ERT_Verify_Success = 0x5AA5, 130 | 131 | ERT_DebugInvalid = 0xFF00, 132 | ERT_UnderAttack = 0xFFAA, 133 | ERT_Unauthorized = 0xFFFF, 134 | ERT_Total = 0xFFFF 135 | } emRetType; 136 | 137 | /** Compatibility with the cplusplus*/ 138 | #ifdef __cplusplus 139 | } /* Extern C */ 140 | #endif 141 | 142 | #endif 143 | -------------------------------------------------------------------------------- /source/mason/mason_commands.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_COMMANDS_H 19 | #define MASON_COMMANDS_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef MASON_COMMANDS_GLOBAL 23 | #define MASON_COMMANDS_EXT 24 | #else 25 | #define MASON_COMMANDS_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | #include "mason_errno.h" 35 | 36 | /** Compatibility with the cplusplus*/ 37 | #ifdef __cplusplus 38 | extern "C" 39 | { 40 | #endif /* __cplusplus */ 41 | 42 | /** Macro definitions*/ 43 | #define PROT_STX 0x02 44 | #define PROT_ETX 0x03 45 | 46 | #define CMD_H_MAX 10 47 | #define CMD_L_MAX 8 48 | 49 | #define USER_CHIP 0x01 50 | #define USER_FACTORY 0x02 51 | #define USER_ATTACK 0x04 52 | #define USER_EMPTY 0x08 53 | #define USER_WALLET 0x80 54 | #define USER_ALL 0xFF 55 | 56 | /** Variable declarations */ 57 | typedef enum 58 | { 59 | E_CMD_FSM_WAIT_CMD, 60 | E_CMD_FSM_MANAGE_CMD, 61 | E_CMD_FSM_MANAGE_ERR, 62 | E_CMD_FSM_IDLE, 63 | } emCmdFSMType; 64 | MASON_COMMANDS_EXT volatile emCmdFSMType gemCmdFSM; 65 | 66 | typedef enum 67 | { 68 | E_PROT_FSM_STX, 69 | E_PROT_FSM_FLAGS, 70 | E_PROT_FSM_MSG_LEN_H, 71 | E_PROT_FSM_MSG_LEN_L, 72 | E_PROT_FSM_MSG, 73 | E_PROT_FSM_ETX, 74 | E_PROT_FSM_LRC, 75 | } emProtType; 76 | MASON_COMMANDS_EXT volatile emProtType gemProtFSM; 77 | 78 | typedef enum 79 | { 80 | PLAIN = 0, 81 | ENCRYPT, 82 | } emEncryptType; 83 | 84 | typedef struct 85 | { 86 | emEncryptType enc : 1; 87 | uint8_t ver : 3; 88 | uint8_t RFU : 4; 89 | } stFlagType, *pstFlagType; 90 | 91 | typedef union 92 | { 93 | stFlagType stFlag; 94 | uint8_t flag; 95 | } unFlagType, *punFlagType; 96 | 97 | typedef struct 98 | { 99 | uint32_t len; 100 | uint8_t *pV; 101 | unFlagType unFlag; 102 | } stCMDType, *pstCMDType; 103 | MASON_COMMANDS_EXT volatile pstCMDType gpstCMD; 104 | 105 | typedef union 106 | { 107 | uint16_t u16; 108 | uint8_t buf[2]; 109 | } un2ByteOrderType, unCMDNoType; 110 | 111 | typedef struct 112 | { 113 | uint32_t u32_1 : 8; 114 | uint32_t u32_2 : 8; 115 | uint32_t u32_3 : 8; 116 | uint32_t u32_4 : 8; 117 | } st4ByteOrderType; 118 | typedef union 119 | { 120 | uint32_t u32; 121 | uint8_t buf[4]; 122 | } un4ByteOrderType; 123 | 124 | /** Function declarations */ 125 | typedef void (*pfunc_mason_cmd_handler)(void *); 126 | typedef struct 127 | { 128 | uint8_t users; 129 | pfunc_mason_cmd_handler pFunc; 130 | } stCmdHandlerType; 131 | MASON_COMMANDS_EXT volatile stCmdHandlerType gstCmdHandlers[CMD_H_MAX][CMD_L_MAX]; 132 | 133 | emCmdFSMType mason_command_handler(void); 134 | emCmdFSMType mason_command_manager(void); 135 | emCmdFSMType mason_command_manage_error(void); 136 | 137 | /** Compatibility with the cplusplus*/ 138 | #ifdef __cplusplus 139 | } /* Extern C */ 140 | #endif 141 | 142 | #endif 143 | -------------------------------------------------------------------------------- /source/mason/mason_storage.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define MASON_STORAGE_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "mason_storage.h" 22 | #include "eflash.h" 23 | #include "stdio.h" 24 | 25 | /** Function implementations */ 26 | /** 27 | * @functionname: mason_storage_encryption 28 | * @description: 29 | * @para: 30 | * @return: 31 | */ 32 | MASON_STORAGE_EXT emRetType mason_storage_encryption(uint8_t nType, uint8_t *pIn, uint16_t len, uint8_t *pOut) 33 | { 34 | return ERT_OK; 35 | } 36 | /** 37 | * @functionname: mason_storage_read 38 | * @description: 39 | * @para: 40 | * @return: 41 | */ 42 | MASON_STORAGE_EXT emRetType mason_storage_read(uint8_t *pBuf, uint32_t bufLen, uint32_t addr) 43 | { 44 | emRetType emRet = ERT_OK; 45 | uint32_t addrTmp = addr; 46 | uint32_t i = 0; 47 | 48 | for (i = 0; i < bufLen; i++, addrTmp++) 49 | { 50 | pBuf[i] = eflash_read_byte(addrTmp); 51 | } 52 | 53 | return emRet; 54 | } 55 | /** 56 | * @functionname: mason_storage_read_flag 57 | * @description: 58 | * @para: 59 | * @return: 60 | */ 61 | MASON_STORAGE_EXT uint32_t 62 | mason_storage_read_flag(uint32_t addr) 63 | { 64 | return eflash_read_word(addr); 65 | } 66 | /** 67 | * @functionname: mason_storage_write_flag 68 | * @description: 69 | * @para: 70 | * @return: 71 | */ 72 | MASON_STORAGE_EXT emRetType 73 | mason_storage_write_flag(uint32_t addr, uint32_t u32Flag) 74 | { 75 | eflash_rewrite_word(addr, u32Flag); 76 | 77 | return ERT_OK; 78 | } 79 | /** 80 | * @functionname: mason_storage_write_flag_safe 81 | * @description: 82 | * @para: 83 | * @return: 84 | */ 85 | MASON_STORAGE_EXT emRetType 86 | mason_storage_write_flag_safe(uint32_t addr, uint32_t u32Flag) 87 | { 88 | eflash_rewrite_word(addr, u32Flag); 89 | 90 | if (u32Flag != eflash_read_word(addr)) 91 | { 92 | return ERT_StorageFail; 93 | } 94 | 95 | return ERT_OK; 96 | } 97 | /** 98 | * @functionname: mason_storage_check_flag 99 | * @description: 100 | * @para: 101 | * @return: 102 | */ 103 | MASON_STORAGE_EXT bool 104 | mason_storage_check_flag(uint32_t addr, uint32_t u32Flag) 105 | { 106 | return (u32Flag == eflash_read_word(addr)); 107 | } 108 | /** 109 | * @functionname: mason_storage_write_buffer_in_one_page 110 | * @description: 111 | * @para: 112 | * @return: 113 | */ 114 | bool mason_storage_write_buffer_in_one_page(uint8_t *buffer, uint32_t len, uint32_t addr) 115 | { 116 | uint8_t page_buffer[PAGE_SIZE]; 117 | uint32_t page_addr = addr - addr % PAGE_SIZE; 118 | uint32_t addr_offset = addr % PAGE_SIZE; 119 | uint32_t i = 0; 120 | 121 | if (len == 0) 122 | { 123 | return true; 124 | } 125 | 126 | if (addr_offset + len > PAGE_SIZE) 127 | { 128 | return false; 129 | } 130 | 131 | eflash_read_page((uint32_t *)page_buffer, page_addr); 132 | for (i = 0; i < len; i++) 133 | { 134 | page_buffer[addr_offset + i] = buffer[i]; 135 | } 136 | eflash_erase_page(page_addr); 137 | eflash_write_page((uint32_t *)page_buffer, page_addr); 138 | 139 | return true; 140 | } 141 | /** 142 | * @functionname: mason_storage_write_buffer 143 | * @description: 144 | * @para: 145 | * @return: 146 | */ 147 | bool mason_storage_write_buffer(uint8_t *buffer, uint32_t len, uint32_t addr) 148 | { 149 | return mason_storage_write_buffer_in_one_page(buffer, len, addr); 150 | } 151 | -------------------------------------------------------------------------------- /source/driver/ed25519-donna/ed25519.c: -------------------------------------------------------------------------------- 1 | /* 2 | Public domain by Andrew M. 3 | 4 | Ed25519 reference implementation using Ed25519-donna 5 | */ 6 | 7 | 8 | /* define ED25519_SUFFIX to have it appended to the end of each public function */ 9 | #if !defined(ED25519_SUFFIX) 10 | #define ED25519_SUFFIX 11 | #endif 12 | 13 | #define ED25519_FN3(fn,suffix) fn##suffix 14 | #define ED25519_FN2(fn,suffix) ED25519_FN3(fn,suffix) 15 | #define ED25519_FN(fn) ED25519_FN2(fn,ED25519_SUFFIX) 16 | 17 | #include "ed25519-donna.h" 18 | #include "ed25519.h" 19 | #include "ed25519_util.h" 20 | 21 | /* 22 | Generates a (extsk[0..31]) and aExt (extsk[32..63]) 23 | */ 24 | 25 | DONNA_INLINE static void 26 | ed25519_extsk(hash_512bits extsk, ed25519_secret_key sk) { 27 | ed25519_hash(extsk, sk, 32); 28 | extsk[0] &= 248; 29 | extsk[31] &= 127; 30 | extsk[31] |= 64; 31 | } 32 | 33 | static void 34 | ed25519_hram(hash_512bits hram, ed25519_signature RS, ed25519_public_key pk, unsigned char *m, size_t mlen) { 35 | ed25519_hash_context ctx; 36 | ed25519_hash_init(&ctx); 37 | ed25519_hash_update(&ctx, RS, 32); 38 | ed25519_hash_update(&ctx, pk, 32); 39 | ed25519_hash_update(&ctx, m, mlen); 40 | ed25519_hash_final(&ctx, hram); 41 | } 42 | 43 | void 44 | ED25519_FN(ed25519_publickey) (ed25519_secret_key sk, ed25519_public_key pk) { 45 | bignum256modm a = {0}; 46 | ge25519 ALIGN(8) A; 47 | hash_512bits extsk = {0}; 48 | 49 | /* A = aB */ 50 | ed25519_extsk(extsk, sk); 51 | expand256_modm(a, extsk, 32); 52 | ge25519_scalarmult_base_niels(&A, ge25519_niels_base_multiples, a); 53 | ge25519_pack(pk, &A); 54 | } 55 | 56 | 57 | void 58 | ED25519_FN(ed25519_sign) (unsigned char *m, size_t mlen, ed25519_secret_key sk, ed25519_public_key pk, ed25519_signature RS) { 59 | ed25519_hash_context ctx; 60 | bignum256modm r = {0}, S = {0}, a = {0}; 61 | ge25519 ALIGN(8) R = {0}; 62 | hash_512bits extsk = {0}, hashr = {0}, hram = {0}; 63 | 64 | ed25519_extsk(extsk, sk); 65 | 66 | /* r = H(aExt[32..64], m) */ 67 | ed25519_hash_init(&ctx); 68 | ed25519_hash_update(&ctx, extsk + 32, 32); 69 | ed25519_hash_update(&ctx, m, mlen); 70 | ed25519_hash_final(&ctx, hashr); 71 | expand256_modm(r, hashr, 64); 72 | 73 | /* R = rB */ 74 | ge25519_scalarmult_base_niels(&R, ge25519_niels_base_multiples, r); 75 | ge25519_pack(RS, &R); 76 | 77 | /* S = H(R,A,m).. */ 78 | ed25519_hram(hram, RS, pk, m, mlen); 79 | expand256_modm(S, hram, 64); 80 | 81 | /* S = H(R,A,m)a */ 82 | expand256_modm(a, extsk, 32); 83 | mul256_modm(S, S, a); 84 | 85 | /* S = (r + H(R,A,m)a) */ 86 | add256_modm(S, S, r); 87 | 88 | /* S = (r + H(R,A,m)a) mod L */ 89 | contract256_modm(RS + 32, S); 90 | } 91 | 92 | int 93 | ED25519_FN(ed25519_sign_open) (unsigned char *m, size_t mlen, ed25519_public_key pk, ed25519_signature RS) { 94 | ge25519 ALIGN(8) R, A; 95 | hash_512bits hash = {0}; 96 | bignum256modm hram = {0}, S = {0}; 97 | unsigned char checkR[32] = {0}; 98 | 99 | if ((RS[63] & 224) || !ge25519_unpack_negative_vartime(&A, pk)) 100 | return -1; 101 | 102 | /* hram = H(R,A,m) */ 103 | ed25519_hram(hash, RS, pk, m, mlen); 104 | expand256_modm(hram, hash, 64); 105 | 106 | /* S */ 107 | expand256_modm(S, RS + 32, 32); 108 | 109 | /* SB - H(R,A,m)A */ 110 | ge25519_double_scalarmult_vartime(&R, &A, hram, S); 111 | ge25519_pack(checkR, &R); 112 | 113 | /* check that R = SB - H(R,A,m)A */ 114 | return ed25519_verify(RS, checkR, 32) ? 0 : -1; 115 | } 116 | 117 | /* 118 | Fast Curve25519 basepoint scalar multiplication 119 | */ 120 | 121 | void 122 | curved25519_scalarmult_basepoint(curve25519_key pk, const curve25519_key e) { 123 | curve25519_key ec = {0}; 124 | bignum256modm s = {0}; 125 | bignum25519 ALIGN(8) yplusz, zminusy; 126 | ge25519 ALIGN(8) p; 127 | size_t i = 0; 128 | 129 | /* clamp */ 130 | for (i = 0; i < 32; i++) ec[i] = e[i]; 131 | ec[0] &= 248; 132 | ec[31] &= 127; 133 | ec[31] |= 64; 134 | 135 | expand_raw256_modm(s, ec); 136 | 137 | /* scalar * basepoint */ 138 | ge25519_scalarmult_base_niels(&p, ge25519_niels_base_multiples, s); 139 | 140 | /* u = (y + z) / (z - y) */ 141 | curve25519_add(yplusz, p.y, p.z); 142 | curve25519_sub(zminusy, p.z, p.y); 143 | curve25519_recip(zminusy, zminusy); 144 | curve25519_mul(yplusz, yplusz, zminusy); 145 | curve25519_contract(pk, yplusz); 146 | } 147 | 148 | -------------------------------------------------------------------------------- /source/crypto/rmd128mc.h: -------------------------------------------------------------------------------- 1 | /********************************************************************\ 2 | * 3 | * FILE: rmd128mc.h 4 | * 5 | * CONTENTS: Header file for a sample C-implementation of the 6 | * RIPEMD128-MAC function. 7 | * TARGET: any computer with an ANSI C compiler 8 | * 9 | * AUTHOR: Antoon Bosselaers, ESAT-COSIC 10 | * DATE: 26 March 1998 11 | * VERSION: 1.0 12 | * 13 | * Copyright (c) Katholieke Universiteit Leuven 14 | * 1998, All Rights Reserved 15 | * 16 | \********************************************************************/ 17 | 18 | #ifndef RMD128H /* make sure this file is read only once */ 19 | #define RMD128H 20 | 21 | /********************************************************************/ 22 | 23 | /* typedef 8 and 32 bit types, resp. */ 24 | /* adapt these, if necessary, 25 | for your operating system and compiler */ 26 | typedef unsigned char byte; 27 | typedef unsigned long dword; 28 | 29 | /* if this line causes a compiler error, 30 | adapt the defintion of dword above */ 31 | typedef int the_correct_size_was_chosen [sizeof (dword) == 4? 1: -1]; 32 | 33 | /********************************************************************/ 34 | 35 | /* macro definitions */ 36 | 37 | /* collect four bytes into one word: */ 38 | #define BYTES_TO_DWORD(strptr) \ 39 | (((dword) *((strptr)+3) << 24) | \ 40 | ((dword) *((strptr)+2) << 16) | \ 41 | ((dword) *((strptr)+1) << 8) | \ 42 | ((dword) *(strptr))) 43 | 44 | /* ROL(x, n) cyclically rotates x over n bits to the left */ 45 | /* x must be of an unsigned 32 bits type and 0 <= n < 32. */ 46 | #define ROL(x, n) (((x) << (n)) | ((x) >> (32-(n)))) 47 | 48 | /* the four basic functions F(), G() and H() */ 49 | #define F(x, y, z) ((x) ^ (y) ^ (z)) 50 | #define G(x, y, z) (((x) & (y)) | (~(x) & (z))) 51 | #define H(x, y, z) (((x) | ~(y)) ^ (z)) 52 | #define I(x, y, z) (((x) & (z)) | ((y) & ~(z))) 53 | 54 | /* the eight basic operations FF() through III() */ 55 | #define FF(a, b, c, d, x, s) {\ 56 | (a) += F((b), (c), (d)) + (x);\ 57 | (a) = ROL((a), (s));\ 58 | } 59 | #define GG(a, b, c, d, x, s) {\ 60 | (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\ 61 | (a) = ROL((a), (s));\ 62 | } 63 | #define HH(a, b, c, d, x, s) {\ 64 | (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\ 65 | (a) = ROL((a), (s));\ 66 | } 67 | #define II(a, b, c, d, x, s) {\ 68 | (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\ 69 | (a) = ROL((a), (s));\ 70 | } 71 | #define FFF(a, b, c, d, x, s) {\ 72 | (a) += F((b), (c), (d)) + (x);\ 73 | (a) = ROL((a), (s));\ 74 | } 75 | #define GGG(a, b, c, d, x, s) {\ 76 | (a) += G((b), (c), (d)) + (x) + 0x6d703ef3UL;\ 77 | (a) = ROL((a), (s));\ 78 | } 79 | #define HHH(a, b, c, d, x, s) {\ 80 | (a) += H((b), (c), (d)) + (x) + 0x5c4dd124UL;\ 81 | (a) = ROL((a), (s));\ 82 | } 83 | #define III(a, b, c, d, x, s) {\ 84 | (a) += I((b), (c), (d)) + (x) + 0x50a28be6UL;\ 85 | (a) = ROL((a), (s));\ 86 | } 87 | 88 | /********************************************************************/ 89 | 90 | /* function prototypes */ 91 | 92 | void MDMACconstT(void); 93 | /* 94 | * calculates constants T0, T1, T2 95 | */ 96 | 97 | dword *MDMACsetup(byte *key); 98 | /* 99 | * expands 128-bit key into 3*4*32-bit K = K0|K1|K2 100 | */ 101 | 102 | void MDMACinit(dword *K, dword *MDbuf); 103 | /* 104 | * initializes MDbuffer to K0 105 | */ 106 | 107 | void compress(dword *K, dword *MDbuf, dword *X); 108 | /* 109 | * the compression function. 110 | * transforms MDbuf using message bytes X[0] through X[15] and key K1 111 | */ 112 | 113 | void MDMACfinish(dword *K, dword *MDbuf, byte *strptr, 114 | dword lswlen, dword mswlen); 115 | /* 116 | * puts bytes from strptr into X and pad out; appends length and block 117 | * containing the key K2 and finally, compresses the last block(s) 118 | * note: length in bits == 8 * (lswlen + 2^32 mswlen). 119 | * note: there are (lswlen mod 64) bytes left in strptr. 120 | */ 121 | 122 | #endif /* RMD128H */ 123 | 124 | /********************** end of file rmd128mc.h **********************/ 125 | -------------------------------------------------------------------------------- /source/mason/mason_wallet.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_WALLET_H 19 | #define MASON_WALLET_H 20 | 21 | /** Header file reference */ 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | /** Variable declarations */ 29 | enum SupportEntropyBits 30 | { 31 | Entropy128Bits = 128, 32 | Entropy192Bits = 192, 33 | Entropy224Bits = 224, 34 | Entropy256Bits = 256 35 | }; 36 | 37 | #define MAX_MNEMONIC_SIZE 240 38 | #define MAX_ENTROPY_SIZE 32 39 | #define MAX_HDPATH_SIZE 121 40 | #define MAX_PASSPHRASE_SIZE (128 * 4) 41 | #define MAX_SLIP39_SEED_SIZE 32 42 | 43 | typedef struct mnemonic_s 44 | { 45 | uint32_t size; 46 | uint8_t data[MAX_MNEMONIC_SIZE]; 47 | } mnemonic_t; 48 | 49 | typedef struct entropy_s 50 | { 51 | uint32_t size; 52 | uint8_t data[MAX_ENTROPY_SIZE]; 53 | } entropy_t; 54 | 55 | typedef struct wallet_seed_s 56 | { 57 | uint32_t length; 58 | uint8_t data[SHA512_LEN]; 59 | } wallet_seed_t; 60 | 61 | typedef struct wallet_slip39_master_seed_s 62 | { 63 | uint32_t data_size; 64 | uint8_t data[SHA512_LEN]; 65 | uint16_t id; 66 | uint16_t e; 67 | } wallet_slip39_master_seed_t; 68 | 69 | #define MAX_WALLET_SEGMENTS 10 70 | 71 | typedef struct wallet_path_s 72 | { 73 | uint32_t version; 74 | uint32_t segments[MAX_WALLET_SEGMENTS]; 75 | uint8_t num_of_segments; 76 | } wallet_path_t; 77 | 78 | #define MAX_UPDATE_KEY_LEN 510 79 | 80 | typedef struct update_key_s 81 | { 82 | uint16_t len; 83 | uint8_t key[MAX_UPDATE_KEY_LEN]; 84 | } update_key_t; 85 | 86 | extern wallet_seed_t passphrase_seedFromEntropy; 87 | extern wallet_seed_t passphrase_slip39_seed; 88 | /** Function declarations */ 89 | bool mason_generate_entropy(uint8_t *output_entropy, uint16_t bits, bool need_checksum); 90 | bool mason_create_bip39_wallet(uint8_t *mnemonic, uint16_t mnemonic_len, uint8_t *entropy, uint16_t entropy_len); 91 | bool mason_create_slip39_wallet(uint8_t *slip39_seed_data, uint16_t slip39_seed_len, uint16_t slip39_id, uint8_t slip39_e); 92 | bool mason_change_wallet_passphrase(uint8_t *passphrase, uint16_t passphrase_len); 93 | bool mason_delete_wallet(void); 94 | 95 | bool mason_seedFromEntropy_read(wallet_seed_t *seed); 96 | bool mason_slip39_master_seed_read(wallet_slip39_master_seed_t *seed); 97 | bool mason_slip39_dec_seed_read(wallet_seed_t *seed); 98 | 99 | bool mason_update_key_load(update_key_t *update_key); 100 | bool mason_update_key_save(const update_key_t *update_key); 101 | bool mason_wallet_path_is_pub(char *string, uint16_t len); 102 | bool mason_wallet_path_is_priv(char *string, uint16_t len); 103 | bool mason_parse_wallet_path_from_string(char *string, uint16_t len, wallet_path_t *wallet_path); 104 | 105 | bool mason_valid_wallet_path(wallet_path_t *wallet_path); 106 | 107 | emRetType mason_verify_mnemonic(char *mnemonic_str, uint16_t len); 108 | emRetType mason_verify_slip39_seed(uint8_t *slip39_seed_data, uint16_t slip39_seed_len, uint16_t slip39_id); 109 | 110 | bool mason_bip32_generate_master_key_from_root_seed( 111 | crypto_curve_t curve_type, 112 | private_key_t *private_key, 113 | chaincode_t *chaincode); 114 | 115 | bool mason_bip32_derive_keys( 116 | wallet_path_t *wallet_path, 117 | crypto_curve_t curve, 118 | private_key_t *private_key, 119 | chaincode_t *chaincode, 120 | extended_key_t *extended_key); 121 | 122 | bool mason_bip32_derive_master_key_fingerprint(crypto_curve_t curve, uint8_t *fingerprint, uint16_t fingerprint_len); 123 | bool mason_webauth_key_delete(void); 124 | #endif 125 | -------------------------------------------------------------------------------- /source/COMMON/queue.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define QUEUE_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "queue.h" 22 | 23 | /** Variable definitions */ 24 | QUEUE_EXT stQueueType stQueue; 25 | 26 | /** Function implementations */ 27 | /** 28 | * @functionname: queue_init 29 | * @description: 30 | * @para: 31 | * @return: 32 | */ 33 | QUEUE_EXT void queue_init(volatile stQueueType *pstQueue) 34 | { 35 | pstQueue->head = 0; 36 | pstQueue->tail = 0; 37 | pstQueue->size = 0; 38 | memset((void *)pstQueue->queue, (int)NULL, QUEUE_SIZE); 39 | QUEUE_LOG("queue init! max size = %d\r\n", QUEUE_SIZE); 40 | } 41 | /** 42 | * @functionname: queue_size 43 | * @description: 44 | * @para: 45 | * @return: 46 | */ 47 | QUEUE_EXT uint32_t queue_size(volatile stQueueType *pstQueue) 48 | { 49 | QUEUE_LOG("Queue size = %u\r\n", pstQueue->size); 50 | return (pstQueue->size); 51 | } 52 | /** 53 | * @functionname: queue_is_empty 54 | * @description: 55 | * @para: pstQueue: pointer of a queue struct 56 | * @return: 1: queue is empty 57 | 0: queue is not empty 58 | */ 59 | QUEUE_EXT int queue_is_empty(volatile stQueueType *pstQueue) 60 | { 61 | return ((pstQueue->head == pstQueue->tail) && (!pstQueue->size)); 62 | } 63 | /** 64 | * @functionname: queue_is_full 65 | * @description: 66 | * @para: pstQueue: pointer of a queue struct 67 | * @return: 1: queue is full 68 | 0: queue is not full 69 | */ 70 | QUEUE_EXT int queue_is_full(volatile stQueueType *pstQueue) 71 | { 72 | return ((pstQueue->head == pstQueue->tail) && (pstQueue->size)); 73 | } 74 | /** 75 | * @functionname: enqueue_overwrite 76 | * @description: enqueue an element, will overwrite the oldest element 77 | * @para: pstQueue: pointer of a queue struct 78 | element: element in queue type 79 | * @return: void 80 | */ 81 | QUEUE_EXT void enqueue_overwrite(volatile stQueueType *pstQueue, queueElementType element) 82 | { 83 | QUEUE_LOG("enqueue_overwrite!\r\n"); 84 | pstQueue->queue[pstQueue->tail] = element; 85 | pstQueue->tail++; 86 | if (pstQueue->tail >= QUEUE_SIZE) 87 | { 88 | pstQueue->tail = 0; 89 | } 90 | pstQueue->size++; 91 | if (pstQueue->size > QUEUE_SIZE) 92 | { 93 | pstQueue->size = QUEUE_SIZE; 94 | pstQueue->head = pstQueue->tail; 95 | } 96 | } 97 | /** 98 | * @functionname: enqueue_safe 99 | * @description: enqueue an element; preconditon: queue is not full 100 | * @para: pstQueue: pointer of a queue struct 101 | element: element in queue type 102 | * @return: void 103 | */ 104 | QUEUE_EXT void enqueue_safe(volatile stQueueType *pstQueue, queueElementType element) 105 | { 106 | QUEUE_LOG("enqueue_safe!\r\n"); 107 | if (!queue_is_full(pstQueue)) 108 | { 109 | pstQueue->queue[pstQueue->tail] = element; 110 | pstQueue->tail++; 111 | if (pstQueue->tail >= QUEUE_SIZE) 112 | { 113 | pstQueue->tail = 0; 114 | } 115 | pstQueue->size++; 116 | } 117 | else 118 | { 119 | QUEUE_LOG("Queue is full!\r\n"); 120 | } 121 | } 122 | /** 123 | * @functionname: dequeue 124 | * @description: dequeue an element; preconditon: queue is not empty 125 | * @para: pstQueue: pointer of a queue struct 126 | * @return: queue element in the head position 127 | */ 128 | QUEUE_EXT queueElementType dequeue(volatile stQueueType *pstQueue) 129 | { 130 | queueElementType e = (queueElementType)NULL; 131 | 132 | QUEUE_LOG("dequeue!\r\n"); 133 | if (!queue_is_empty(pstQueue)) 134 | { 135 | e = pstQueue->queue[pstQueue->head]; 136 | pstQueue->head++; 137 | if (pstQueue->head >= QUEUE_SIZE) 138 | { 139 | pstQueue->head = 0; 140 | } 141 | pstQueue->size--; 142 | QUEUE_LOG("dequeue element: %d\r\n", *e); 143 | } 144 | else 145 | { 146 | QUEUE_LOG("Queue is empty!\r\n"); 147 | } 148 | 149 | return e; 150 | } 151 | -------------------------------------------------------------------------------- /source/COMMON/stack.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define STACK_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "stack.h" 22 | 23 | /** Variable definitions */ 24 | // STACK_EXT stStackType stStack = 25 | // { 26 | // {NULL}, 27 | // -1}; 28 | 29 | /** Function implementations */ 30 | /** 31 | * @functionname: stack_init 32 | * @description: 33 | * @para: 34 | * @return: 35 | */ 36 | STACK_EXT void stack_init(pstStackType pstStack) 37 | { 38 | pstStackType pstS = pstStack; 39 | pstS->top = -1; 40 | } 41 | /** 42 | * @functionname: stack_empty 43 | * @description: 44 | * @para: 45 | * @return: 46 | */ 47 | STACK_EXT bool stack_empty(pstStackType pstStack) 48 | { 49 | pstStackType pstS = pstStack; 50 | if (-1 == pstS->top) 51 | { 52 | return true; 53 | } 54 | else 55 | { 56 | return false; 57 | } 58 | } 59 | /** 60 | * @functionname: stack_full 61 | * @description: 62 | * @para: 63 | * @return: 64 | */ 65 | STACK_EXT bool stack_full(pstStackType pstStack) 66 | { 67 | pstStackType pstS = pstStack; 68 | if (pstS->top == STACK_SIZE - 1) 69 | { 70 | return true; 71 | } 72 | else 73 | { 74 | return false; 75 | } 76 | } 77 | /** 78 | * @functionname: stack_size 79 | * @description: 80 | * @para: 81 | * @return: 82 | */ 83 | STACK_EXT emStackStatusType stack_size(pstStackType pstStack, size_t *psz) 84 | { 85 | pstStackType pstS = pstStack; 86 | if (stack_empty(pstS)) 87 | { 88 | return EM_STACK_EMPTY; 89 | } 90 | *psz = pstS->top = 1; 91 | 92 | return EM_STACK_OK; 93 | } 94 | /** 95 | * @functionname: stack_push 96 | * @description: 97 | * @para: 98 | * @return: 99 | */ 100 | STACK_EXT emStackStatusType stack_push(pstStackType pstStack, stackElementType element) 101 | { 102 | pstStackType pstS = pstStack; 103 | 104 | if (!stack_full(pstS)) 105 | { 106 | pstS->top++; 107 | pstS->stack[pstS->top] = element; 108 | } 109 | else 110 | { 111 | return EM_STACK_FULL; 112 | } 113 | 114 | return EM_STACK_OK; 115 | } 116 | /** 117 | * @functionname: stack_pop 118 | * @description: 119 | * @para: 120 | * @return: 121 | */ 122 | STACK_EXT emStackStatusType stack_pop(pstStackType pstStack, stackElementType *pelement) 123 | { 124 | pstStackType pstS = pstStack; 125 | 126 | if (!stack_empty(pstS)) 127 | { 128 | *pelement = pstS->stack[pstS->top]; 129 | pstS->top--; 130 | } 131 | else 132 | { 133 | return EM_STACK_EMPTY; 134 | } 135 | 136 | return EM_STACK_OK; 137 | } 138 | /** 139 | * @functionname: stack_top 140 | * @description: 141 | * @para: 142 | * @return: 143 | */ 144 | STACK_EXT emStackStatusType stack_top(pstStackType pstStack, stackElementType *pelement) 145 | { 146 | pstStackType pstS = pstStack; 147 | 148 | if (!stack_empty(pstS)) 149 | { 150 | *pelement = pstS->stack[pstS->top]; 151 | } 152 | else 153 | { 154 | return EM_STACK_EMPTY; 155 | } 156 | 157 | return EM_STACK_OK; 158 | } 159 | /** 160 | * @functionname: stack_get 161 | * @description: 162 | * @para: 163 | * @return: 164 | */ 165 | STACK_EXT emStackStatusType stack_get(pstStackType pstStack, stackElementType *pelement, int index) 166 | { 167 | pstStackType pstS = pstStack; 168 | 169 | if (stack_empty(pstS)) 170 | return EM_STACK_EMPTY; 171 | 172 | if (index > pstS->top) 173 | return EM_STACK_INVALID; 174 | 175 | *pelement = pstS->stack[index]; 176 | 177 | return EM_STACK_OK; 178 | } 179 | /** 180 | * @functionname: stack_destroy 181 | * @description: 182 | * @para: 183 | * @return: 184 | */ 185 | STACK_EXT void stack_destroy(pstStackType pstStack) 186 | { 187 | pstStackType pstS = pstStack; 188 | stackElementType element; 189 | 190 | while (EM_STACK_OK == stack_pop(pstS, &element)) 191 | { 192 | if (NULL != element) 193 | { 194 | free(element); 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /source/crypto/RipeMD160.h: -------------------------------------------------------------------------------- 1 | /********************************************************************\ 2 | * 3 | * FILE: rmd160.h 4 | * 5 | * CONTENTS: Header file for a sample C-implementation of the 6 | * RIPEMD-160 hash-function. 7 | * TARGET: any computer with an ANSI C compiler 8 | * 9 | * AUTHOR: Antoon Bosselaers, ESAT-COSIC 10 | * DATE: 1 March 1996 11 | * VERSION: 1.0 12 | * 13 | * Copyright (c) Katholieke Universiteit Leuven 14 | * 1996, All Rights Reserved 15 | * 16 | \********************************************************************/ 17 | 18 | #ifndef RMD160H /* make sure this file is read only once */ 19 | #define RMD160H 20 | 21 | #include 22 | 23 | /********************************************************************/ 24 | 25 | /* typedef 8 and 32 bit types, resp. */ 26 | /* adapt these, if necessary, 27 | for your operating system and compiler */ 28 | typedef unsigned char byte; 29 | typedef unsigned long dword; 30 | 31 | /* if this line causes a compiler error, 32 | adapt the defintion of dword above */ 33 | typedef int the_correct_size_was_chosen [sizeof (dword) == 4? 1: -1]; 34 | 35 | /********************************************************************/ 36 | 37 | /* macro definitions */ 38 | 39 | /* collect four bytes into one word: */ 40 | #define BYTES_TO_DWORD(strptr) \ 41 | (((dword) *((strptr)+3) << 24) | \ 42 | ((dword) *((strptr)+2) << 16) | \ 43 | ((dword) *((strptr)+1) << 8) | \ 44 | ((dword) *(strptr))) 45 | 46 | /* ROL(x, n) cyclically rotates x over n bits to the left */ 47 | /* x must be of an unsigned 32 bits type and 0 <= n < 32. */ 48 | #define ROL(x, n) (((x) << (n)) | ((x) >> (32-(n)))) 49 | 50 | /* the five basic functions F(), G() and H() */ 51 | #define F(x, y, z) ((x) ^ (y) ^ (z)) 52 | #define G(x, y, z) (((x) & (y)) | (~(x) & (z))) 53 | #define H(x, y, z) (((x) | ~(y)) ^ (z)) 54 | #define I(x, y, z) (((x) & (z)) | ((y) & ~(z))) 55 | #define J(x, y, z) ((x) ^ ((y) | ~(z))) 56 | 57 | /* the ten basic operations FF() through III() */ 58 | #define FF(a, b, c, d, e, x, s) {\ 59 | (a) += F((b), (c), (d)) + (x);\ 60 | (a) = ROL((a), (s)) + (e);\ 61 | (c) = ROL((c), 10);\ 62 | } 63 | #define GG(a, b, c, d, e, x, s) {\ 64 | (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\ 65 | (a) = ROL((a), (s)) + (e);\ 66 | (c) = ROL((c), 10);\ 67 | } 68 | #define HH(a, b, c, d, e, x, s) {\ 69 | (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\ 70 | (a) = ROL((a), (s)) + (e);\ 71 | (c) = ROL((c), 10);\ 72 | } 73 | #define II(a, b, c, d, e, x, s) {\ 74 | (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\ 75 | (a) = ROL((a), (s)) + (e);\ 76 | (c) = ROL((c), 10);\ 77 | } 78 | #define JJ(a, b, c, d, e, x, s) {\ 79 | (a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\ 80 | (a) = ROL((a), (s)) + (e);\ 81 | (c) = ROL((c), 10);\ 82 | } 83 | #define FFF(a, b, c, d, e, x, s) {\ 84 | (a) += F((b), (c), (d)) + (x);\ 85 | (a) = ROL((a), (s)) + (e);\ 86 | (c) = ROL((c), 10);\ 87 | } 88 | #define GGG(a, b, c, d, e, x, s) {\ 89 | (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\ 90 | (a) = ROL((a), (s)) + (e);\ 91 | (c) = ROL((c), 10);\ 92 | } 93 | #define HHH(a, b, c, d, e, x, s) {\ 94 | (a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\ 95 | (a) = ROL((a), (s)) + (e);\ 96 | (c) = ROL((c), 10);\ 97 | } 98 | #define III(a, b, c, d, e, x, s) {\ 99 | (a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\ 100 | (a) = ROL((a), (s)) + (e);\ 101 | (c) = ROL((c), 10);\ 102 | } 103 | #define JJJ(a, b, c, d, e, x, s) {\ 104 | (a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\ 105 | (a) = ROL((a), (s)) + (e);\ 106 | (c) = ROL((c), 10);\ 107 | } 108 | 109 | /********************************************************************/ 110 | 111 | /* function prototypes */ 112 | 113 | void MDinit(dword *MDbuf); 114 | /* 115 | * initializes MDbuffer to "magic constants" 116 | */ 117 | 118 | void compress(dword *MDbuf, dword *X); 119 | /* 120 | * the compression function. 121 | * transforms MDbuf using message bytes X[0] through X[15] 122 | */ 123 | 124 | void MDfinish(dword *MDbuf, byte *strptr, dword lswlen, dword mswlen); 125 | /* 126 | * puts bytes from strptr into X and pad out; appends length 127 | * and finally, compresses the last block(s) 128 | * note: length in bits == 8 * (lswlen + 2^32 mswlen). 129 | * note: there are (lswlen mod 64) bytes left in strptr. 130 | */ 131 | 132 | void RipeMD160(uint8_t *message, uint32_t msgLen, uint8_t *pHash); 133 | 134 | #endif /* RMD160H */ 135 | 136 | /*********************** end of file rmd160.h ***********************/ 137 | -------------------------------------------------------------------------------- /source/mason/mason_tags.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #ifndef MASON_TAGS_H 19 | #define MASON_TAGS_H 20 | 21 | /** Avoid duplicate definitions */ 22 | #ifdef MASON_TAGS_GLOBAL 23 | #define MASON_TAGS_EXT 24 | #else 25 | #define MASON_TAGS_EXT extern 26 | #endif 27 | 28 | /** Header file reference */ 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include //memcpy... 34 | 35 | /** Compatibility with the cplusplus*/ 36 | #ifdef __cplusplus 37 | extern "C" 38 | { 39 | #endif /* __cplusplus */ 40 | 41 | /** Macro definitions*/ 42 | #define TLV_T_CMD 0x0001 43 | #define TLV_T_RESPONSE 0x0002 44 | #define TLV_T_ERR_MSG 0x0003 45 | #define TLV_T_MSG_TYPE 0x0004 46 | 47 | #define TLV_T_ANDROID_STATUS 0x0101 48 | #define TLV_T_FW_STATUS 0x0102 49 | #define TLV_T_SY_FW_VER 0x0103 50 | #define TLV_T_SY_ALG_VER 0x0104 51 | #define TLV_T_BOOT_VER_NAME 0x0105 52 | #define TLV_T_APP_VER_NAME 0x0106 53 | #define TLV_T_FLASH_ADDR 0x0107 54 | #define TLV_T_FLASH_DATA 0x0108 55 | #define TLV_T_UPDATE_PACK 0x0109 56 | #define TLV_T_UPDATE_PACK_TYPE 0x010A 57 | #define TLV_T_UPDATE_PACK_CKM 0x010B 58 | #define TLV_T_UPDATE_FILE_CKM 0x010C 59 | #define TLV_T_COMPILE_TIME 0x010D 60 | #define TLV_T_COMPILE_DATE 0x010E 61 | #define TLV_T_APP_VER_CODE 0x010F 62 | #define TLV_T_BOOT_VER_CODE 0x0110 63 | #define TLV_T_SN 0x0111 64 | #define TLV_T_TAMPER_CNT 0x0112 65 | #define TLV_T_TAMPER_TIME_MAX 0x0113 66 | #define TLV_T_POWERUP_CNT 0x0114 67 | #define TLV_T_FW_UPDATE_CNT 0x0115 68 | #define TLV_T_FW_NAME 0x0116 69 | #define TLV_T_JUST_CHECK_VERSION 0x0117 70 | #define TLV_T_BOOT_TYPE 0x0118 71 | 72 | #define TLV_T_JUMP_TO 0x01FF 73 | 74 | #define TLV_T_ENTROPY_BITS 0x0201 75 | #define TLV_T_ENTROPY 0x0202 76 | #define TLV_T_MNEMONIC 0x0203 77 | #define TLV_T_PASSPHRASE 0x0204 78 | #define TLV_T_HDW_TYPE 0x0205 79 | #define TLV_T_COIN_TYPE 0x0206 80 | #define TLV_T_HD_PATH 0x0207 81 | #define TLV_T_HDP_DEPTH 0x0208 82 | #define TLV_T_ADDRESS 0x0209 83 | #define TLV_T_EXT_KEY 0x020A 84 | #define TLV_T_MASTER_KEY_FP 0x020B 85 | #define TLV_T_SECURITY_SWITCH 0x020F 86 | #define TLV_T_HDW_SWITCH 0x0210 87 | 88 | #define TLV_T_DES_KEY 0x0301 89 | #define TLV_T_PRVKEY 0x0302 90 | #define TLV_T_PUBKEY 0x0303 91 | #define TLV_T_CHAINCODE 0x0304 92 | #define TLV_T_PLAIN_MSG 0x0305 93 | #define TLV_T_ENCRYPT_MSG 0x0306 94 | #define TLV_T_HASH 0x0307 95 | #define TLV_T_SIGNATURE 0x0308 96 | #define TLV_T_CHECKSUM 0x0309 97 | #define TLV_T_DES_IV 0x030A 98 | #define TLV_T_NEED_CKM 0x030B 99 | #define TLV_T_PUBKEYC 0x030C 100 | #define TLV_T_CURVE_TYPE 0x030D 101 | #define TLV_T_NEXT_SIGN 0x030E 102 | #define TLV_T_HASH_FUNC 0x030F 103 | 104 | #define TLV_T_USRPWD_NEW 0x0401 105 | #define TLV_T_USRPWD_CUR 0x0402 106 | #define TLV_T_USRFING 0x0403 107 | #define TLV_T_TOKEN 0x0404 108 | #define TLV_T_RETURN_TOKEN 0x0405 109 | #define TLV_T_MESSAGE 0x0406 110 | #define TLV_T_MESSAGE_SIGN 0x0407 111 | #define TLV_T_SETTINGS_TYPE 0x0408 112 | #define TLV_T_SETTINGS_VALUE 0x0409 113 | 114 | #define TLV_T_WR_RD 0x0701 //0:write; non-0:read 115 | #define TLV_T_UPDATE_KEY 0x0702 116 | 117 | #define TLV_T_DEBUG_SWITCH 0x0800 118 | #define TLV_T_COM_TEST_DATA 0x0801 119 | #define TLV_T_MNEMONIC_LEN 0x0802 120 | #define TLV_T_BIP39_SEED 0x0803 121 | #define TLV_T_READ_DATA_LEN 0x0804 122 | #define TLV_T_GPIO_STATUS 0x0805 123 | #define TLV_T_GPIO_SET 0x0806 124 | #define TLV_T_BIP32_SEED 0x0807 125 | #define TLV_T_BIP32_KEY 0x0808 126 | #define TLV_T_ACTIVE_TAMPER 0x0809 127 | #define TLV_T_PASSIVE_TAMPER 0x080A 128 | #define TLV_T_SLIP39_MASTER_SEED 0x080B 129 | #define TLV_T_SLIP39_ID 0x080C 130 | #define TLV_T_SLIP39_EXPONENT 0x080D 131 | 132 | /** Compatibility with the cplusplus*/ 133 | #ifdef __cplusplus 134 | } /* Extern C */ 135 | #endif 136 | 137 | #endif 138 | -------------------------------------------------------------------------------- /source/crypto/rmd160mc.h: -------------------------------------------------------------------------------- 1 | /********************************************************************\ 2 | * 3 | * FILE: rmd160mc.h 4 | * 5 | * CONTENTS: Header file for a sample C-implementation of the 6 | * RIPEMD160-MAC function. 7 | * TARGET: any computer with an ANSI C compiler 8 | * 9 | * AUTHOR: Antoon Bosselaers, ESAT-COSIC 10 | * DATE: 26 March 1998 11 | * VERSION: 1.0 12 | * 13 | * Copyright (c) Katholieke Universiteit Leuven 14 | * 1998, All Rights Reserved 15 | * 16 | \********************************************************************/ 17 | 18 | #ifndef RMD160H /* make sure this file is read only once */ 19 | #define RMD160H 20 | 21 | /********************************************************************/ 22 | 23 | /* typedef 8 and 32 bit types, resp. */ 24 | /* adapt these, if necessary, 25 | for your operating system and compiler */ 26 | typedef unsigned char byte; 27 | typedef unsigned long dword; 28 | 29 | /* if this line causes a compiler error, 30 | * adapt the defintion of dword above */ 31 | typedef int the_correct_size_was_chosen [sizeof (dword) == 4? 1: -1]; 32 | 33 | /********************************************************************/ 34 | 35 | /* macro definitions */ 36 | 37 | /* collect four bytes into one word: */ 38 | #define BYTES_TO_DWORD(strptr) \ 39 | (((dword) *((strptr)+3) << 24) | \ 40 | ((dword) *((strptr)+2) << 16) | \ 41 | ((dword) *((strptr)+1) << 8) | \ 42 | ((dword) *(strptr))) 43 | 44 | /* ROL(x, n) cyclically rotates x over n bits to the left */ 45 | /* x must be of an unsigned 32 bits type and 0 <= n < 32. */ 46 | #define ROL(x, n) (((x) << (n)) | ((x) >> (32-(n)))) 47 | 48 | /* the five basic functions F(), G() and H() */ 49 | #define F(x, y, z) ((x) ^ (y) ^ (z)) 50 | #define G(x, y, z) (((x) & (y)) | (~(x) & (z))) 51 | #define H(x, y, z) (((x) | ~(y)) ^ (z)) 52 | #define I(x, y, z) (((x) & (z)) | ((y) & ~(z))) 53 | #define J(x, y, z) ((x) ^ ((y) | ~(z))) 54 | 55 | /* the ten basic operations FF() through III() */ 56 | #define FF(a, b, c, d, e, x, s) {\ 57 | (a) += F((b), (c), (d)) + (x);\ 58 | (a) = ROL((a), (s)) + (e);\ 59 | (c) = ROL((c), 10);\ 60 | } 61 | #define GG(a, b, c, d, e, x, s) {\ 62 | (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\ 63 | (a) = ROL((a), (s)) + (e);\ 64 | (c) = ROL((c), 10);\ 65 | } 66 | #define HH(a, b, c, d, e, x, s) {\ 67 | (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\ 68 | (a) = ROL((a), (s)) + (e);\ 69 | (c) = ROL((c), 10);\ 70 | } 71 | #define II(a, b, c, d, e, x, s) {\ 72 | (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\ 73 | (a) = ROL((a), (s)) + (e);\ 74 | (c) = ROL((c), 10);\ 75 | } 76 | #define JJ(a, b, c, d, e, x, s) {\ 77 | (a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\ 78 | (a) = ROL((a), (s)) + (e);\ 79 | (c) = ROL((c), 10);\ 80 | } 81 | #define FFF(a, b, c, d, e, x, s) {\ 82 | (a) += F((b), (c), (d)) + (x);\ 83 | (a) = ROL((a), (s)) + (e);\ 84 | (c) = ROL((c), 10);\ 85 | } 86 | #define GGG(a, b, c, d, e, x, s) {\ 87 | (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\ 88 | (a) = ROL((a), (s)) + (e);\ 89 | (c) = ROL((c), 10);\ 90 | } 91 | #define HHH(a, b, c, d, e, x, s) {\ 92 | (a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\ 93 | (a) = ROL((a), (s)) + (e);\ 94 | (c) = ROL((c), 10);\ 95 | } 96 | #define III(a, b, c, d, e, x, s) {\ 97 | (a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\ 98 | (a) = ROL((a), (s)) + (e);\ 99 | (c) = ROL((c), 10);\ 100 | } 101 | #define JJJ(a, b, c, d, e, x, s) {\ 102 | (a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\ 103 | (a) = ROL((a), (s)) + (e);\ 104 | (c) = ROL((c), 10);\ 105 | } 106 | 107 | /********************************************************************/ 108 | 109 | /* function prototypes */ 110 | 111 | void MDMACconstT(void); 112 | /* 113 | * calculates constants T0, T1, T2 114 | */ 115 | 116 | dword *MDMACsetup(byte *key); 117 | /* 118 | * expands 128-bit key into (5+4+4)*32-bit K = K0|K1|K2 119 | */ 120 | 121 | void MDMACinit(dword *K, dword *MDbuf); 122 | /* 123 | * initializes MDbuffer to K0 124 | */ 125 | 126 | void compress(dword *K, dword *MDbuf, dword *X); 127 | /* 128 | * the compression function. 129 | * transforms MDbuf using message bytes X[0] through X[15] and key K1 130 | */ 131 | 132 | void MDMACfinish(dword *K, dword *MDbuf, byte *strptr, 133 | dword lswlen, dword mswlen); 134 | /* 135 | * puts bytes from strptr into X and pad out; appends length and block 136 | * containing the key K2 and finally, compresses the last block(s) 137 | * note: length in bits == 8 * (lswlen + 2^32 mswlen). 138 | * note: there are (lswlen mod 64) bytes left in strptr. 139 | */ 140 | 141 | #endif /* RMD160H */ 142 | 143 | 144 | /********************** end of file rmd160mc.h **********************/ 145 | -------------------------------------------------------------------------------- /source/driver/sha2.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2000-2001 Aaron D. Gifford 3 | * Copyright (c) 2013-2014 Pavol Rusnak 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holder nor the names of contributors 15 | * may be used to endorse or promote products derived from this software 16 | * without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND 19 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE 22 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 24 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 25 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 26 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 27 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 28 | * SUCH DAMAGE. 29 | */ 30 | 31 | #ifndef __SHA2_H__ 32 | #define __SHA2_H__ 33 | 34 | #include 35 | #include 36 | 37 | #define SHA1_BLOCK_LENGTH 64 38 | #define SHA1_DIGEST_LENGTH 20 39 | #define SHA1_DIGEST_STRING_LENGTH (SHA1_DIGEST_LENGTH * 2 + 1) 40 | #define SHA256_BLOCK_LENGTH 64 41 | #define SHA256_DIGEST_LENGTH 32 42 | #define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) 43 | #define SHA512_BLOCK_LENGTH 128 44 | #define SHA512_DIGEST_LENGTH 64 45 | #define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) 46 | 47 | typedef struct _SHA1_CTX { 48 | uint32_t state[5]; 49 | uint64_t bitcount; 50 | uint32_t buffer[SHA1_BLOCK_LENGTH/sizeof(uint32_t)]; 51 | } SHA1_CTX; 52 | typedef struct _SHA256_CTX { 53 | uint32_t state[8]; 54 | uint64_t bitcount; 55 | uint32_t buffer[SHA256_BLOCK_LENGTH/sizeof(uint32_t)]; 56 | } SHA256_CTX; 57 | typedef struct _SHA512_CTX { 58 | uint64_t state[8]; 59 | uint64_t bitcount[2]; 60 | uint64_t buffer[SHA512_BLOCK_LENGTH/sizeof(uint64_t)]; 61 | } SHA512_CTX; 62 | 63 | /*** ENDIAN REVERSAL MACROS *******************************************/ 64 | #ifndef LITTLE_ENDIAN 65 | #define LITTLE_ENDIAN 1234 66 | #define BIG_ENDIAN 4321 67 | #endif 68 | 69 | #ifndef BYTE_ORDER 70 | #define BYTE_ORDER LITTLE_ENDIAN 71 | #endif 72 | 73 | #if BYTE_ORDER == LITTLE_ENDIAN 74 | #define REVERSE32(w,x) { \ 75 | uint32_t tmp = (w); \ 76 | tmp = (tmp >> 16) | (tmp << 16); \ 77 | (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ 78 | } 79 | #define REVERSE64(w,x) { \ 80 | uint64_t tmp = (w); \ 81 | tmp = (tmp >> 32) | (tmp << 32); \ 82 | tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \ 83 | ((tmp & 0x00ff00ff00ff00ffULL) << 8); \ 84 | (x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \ 85 | ((tmp & 0x0000ffff0000ffffULL) << 16); \ 86 | } 87 | #endif /* BYTE_ORDER == LITTLE_ENDIAN */ 88 | 89 | extern const uint32_t sha256_initial_hash_value[8]; 90 | extern const uint64_t sha512_initial_hash_value[8]; 91 | 92 | void sha1_Transform(const uint32_t* state_in, const uint32_t* data, uint32_t* state_out); 93 | void sha1_Init(SHA1_CTX *); 94 | void sha1_Update(SHA1_CTX*, const uint8_t*, size_t); 95 | void sha1_Final(SHA1_CTX*, uint8_t[SHA1_DIGEST_LENGTH]); 96 | char* sha1_End(SHA1_CTX*, char[SHA1_DIGEST_STRING_LENGTH]); 97 | void sha1_Raw(const uint8_t*, size_t, uint8_t[SHA1_DIGEST_LENGTH]); 98 | char* sha1_Data(const uint8_t*, size_t, char[SHA1_DIGEST_STRING_LENGTH]); 99 | 100 | void sha256_Transform(const uint32_t* state_in, const uint32_t* data, uint32_t* state_out); 101 | void sha256_Init(SHA256_CTX *); 102 | void sha256_Update(SHA256_CTX*, const uint8_t*, size_t); 103 | void sha256_Final(SHA256_CTX*, uint8_t[SHA256_DIGEST_LENGTH]); 104 | char* sha256_End(SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]); 105 | void sha256_Raw(const uint8_t*, size_t, uint8_t[SHA256_DIGEST_LENGTH]); 106 | char* sha256_Data(const uint8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]); 107 | 108 | void sha512_Transform(const uint64_t* state_in, const uint64_t* data, uint64_t* state_out); 109 | void sha512_Init(SHA512_CTX*); 110 | void sha512_Update(SHA512_CTX*, const uint8_t*, size_t); 111 | void sha512_Final(SHA512_CTX*, uint8_t[SHA512_DIGEST_LENGTH]); 112 | char* sha512_End(SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]); 113 | void sha512_Raw(const uint8_t*, size_t, uint8_t[SHA512_DIGEST_LENGTH]); 114 | char* sha512_Data(const uint8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]); 115 | 116 | #endif 117 | -------------------------------------------------------------------------------- /scripts/verify_package.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import pyDes 3 | import intelhex 4 | import struct 5 | import hashlib 6 | import time 7 | from hashlib import sha256 8 | 9 | 10 | 11 | 12 | class FirmwarePacker: 13 | def __init__(self, version, key = '', iv = '', block_size = 512): 14 | self.ih = intelhex.IntelHex() 15 | self.ih.padding = 0xFF 16 | self.key = key 17 | self.iv = iv 18 | self.version = version 19 | self.block_size = block_size 20 | self.blocks = {} 21 | self.version_binary_str = self.parse_version(self.version) 22 | self.packed_buffer = None 23 | self.packed_hash = None 24 | 25 | def load_from_file(self, file): 26 | self.ih.loadhex(file) 27 | min_addr = self.ih.minaddr() 28 | max_addr = self.ih.maxaddr() 29 | 30 | current_addr = min_addr 31 | 32 | while current_addr < max_addr: 33 | page_start = current_addr 34 | page_end = current_addr + self.block_size 35 | current_addr = page_end 36 | #page = self.ih[page_start:page_end] 37 | #page_binary_str = page.tobinstr() 38 | page = self.ih.tobinstr(start=page_start, size=512) 39 | page_binary_str = page 40 | offset = page_start - 0x10000 41 | self.blocks[offset] = page_binary_str 42 | 43 | def write_to_file(self, file): 44 | f = open(file, 'wb') 45 | buffer = self.pack() 46 | f.write(buffer) 47 | 48 | def calculate_checksum(self, content, length = 8): 49 | sha256 = hashlib.sha256() 50 | sha256.update(content) 51 | checksum = sha256.digest()[:length] 52 | return checksum 53 | 54 | def encrypt(self, content): 55 | encryptor = pyDes.triple_des(self.key, mode=pyDes.CBC, IV=self.iv) 56 | encrypted_content = encryptor.encrypt(content) 57 | return encrypted_content 58 | 59 | def parse_version(self, version): 60 | version_numbers = list(map(lambda x : int(x), version.strip().split("."))) 61 | if len(version_numbers) != 4: 62 | return None 63 | 64 | major = version_numbers[0] 65 | minor = version_numbers[1] 66 | release = version_numbers[2] 67 | build = version_numbers[3] 68 | 69 | version_str = '%d%d%d%05X' % (major, minor, release, build) 70 | version_binary_str = bytearray.fromhex(version_str) 71 | return version_binary_str 72 | 73 | def pack(self): 74 | buffer = bytearray() 75 | for address in self.blocks: 76 | content = self.blocks[address] 77 | block_buffer = self.pack_block(address, content) 78 | buffer += block_buffer 79 | sh = hashlib.sha256() 80 | sh.update(buffer) 81 | self.packed_hash = sh.hexdigest() 82 | print("Pack hash: " + self.packed_hash) 83 | header = self.pack_header() 84 | self.packed_buffer = header + buffer 85 | return self.packed_buffer 86 | 87 | def pack_header(self): 88 | header = self.version_binary_str 89 | sha256 = hashlib.sha256() 90 | sha256.update(self.version_binary_str) 91 | checksum = sha256.digest()[:4] 92 | 93 | header = header + checksum 94 | header = header + b'\x00' * (32 - len(header)) 95 | 96 | packhash = bytearray.fromhex(self.packed_hash) 97 | header = header + packhash 98 | 99 | # signature part 100 | header = header + b'\x00' * 64 101 | return header 102 | 103 | def pack_block(self, address, content): 104 | #address = address & 0xFFFF 105 | buffer = struct.pack('>LL%ds' % len(content), address, 0, content) 106 | 107 | encrypted_buffer = self.encrypt(buffer) 108 | # print("%08X" % address, buffer.hex(' '), "\n---\n", encrypted_buffer.hex(' ')) 109 | encrypted_buffer_with_checksum = encrypted_buffer + self.calculate_checksum(encrypted_buffer) 110 | return encrypted_buffer_with_checksum 111 | 112 | def parse_argument(): 113 | parser = argparse.ArgumentParser() 114 | parser.add_argument("-f", "--file", help="Input hex file, like mason_app.hex", type=str, default="mason_app.hex", required=False) 115 | parser.add_argument("-i", "--iv", help="3DES CBC initial vection", type=str, default="DE59B68A", required=False) 116 | parser.add_argument("-k", "--key", help="3DES key, length must be 16 or 24 byte", type=str, default="C6E6B09E45227FCD80BF497C", required=False) 117 | parser.add_argument("-t", "--target-version", help="Target version, format is X.X.X.XXXXX, 1.0.0.000000", default="1.0.0.000000", required=False) 118 | args = parser.parse_args() 119 | return args 120 | 121 | if __name__ == '__main__': 122 | args = parse_argument() 123 | firmware_packer = FirmwarePacker(args.target_version, args.key, args.iv) 124 | print('Loading file from %s ...' % args.file) 125 | firmware_packer.load_from_file(args.file) 126 | current = int(time.time()); 127 | output = f"./artifacts/unsigned_firmware_{current}.bin" 128 | print('Packing and write to file %s ...' % output) 129 | firmware_packer.write_to_file(output) 130 | print('Done.') 131 | exit(0) -------------------------------------------------------------------------------- /upgrade/make_update_package.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import pyDes 3 | import intelhex 4 | import sys 5 | import struct 6 | import hashlib 7 | import ecdsa 8 | from hashlib import sha256 9 | 10 | 11 | 12 | 13 | class FirmwarePacker: 14 | def __init__(self, version, key = '', iv = '', block_size = 512): 15 | self.ih = intelhex.IntelHex() 16 | self.ih.padding = 0xFF 17 | self.key = key 18 | self.iv = iv 19 | self.version = version 20 | self.block_size = block_size 21 | self.blocks = {} 22 | self.version_binary_str = self.parse_version(self.version) 23 | self.packed_buffer = None 24 | self.packed_hash = None 25 | 26 | def load_from_file(self, file): 27 | self.ih.loadhex(file) 28 | min_addr = self.ih.minaddr() 29 | max_addr = self.ih.maxaddr() 30 | 31 | current_addr = min_addr 32 | 33 | while current_addr < max_addr: 34 | page_start = current_addr 35 | page_end = current_addr + self.block_size 36 | current_addr = page_end 37 | #page = self.ih[page_start:page_end] 38 | #page_binary_str = page.tobinstr() 39 | page = self.ih.tobinstr(start=page_start, size=512) 40 | page_binary_str = page 41 | offset = page_start - 0x10000 42 | self.blocks[offset] = page_binary_str 43 | 44 | def write_to_file(self, file): 45 | f = open(file, 'wb') 46 | buffer = self.pack() 47 | f.write(buffer) 48 | 49 | def calculate_checksum(self, content, length = 8): 50 | sha256 = hashlib.sha256() 51 | sha256.update(content) 52 | checksum = sha256.digest()[:length] 53 | return checksum 54 | 55 | def encrypt(self, content): 56 | encryptor = pyDes.triple_des(self.key, mode=pyDes.CBC, IV=self.iv) 57 | print("Block size is %d " % len(content)) 58 | encrypted_content = encryptor.encrypt(content) 59 | return encrypted_content 60 | 61 | def parse_version(self, version): 62 | version_numbers = list(map(lambda x : int(x), version.strip().split("."))) 63 | if len(version_numbers) != 4: 64 | return None 65 | 66 | major = version_numbers[0] 67 | minor = version_numbers[1] 68 | release = version_numbers[2] 69 | build = version_numbers[3] 70 | 71 | version_str = '%d%d%d%05X' % (major, minor, release, build) 72 | version_binary_str = bytearray.fromhex(version_str) 73 | return version_binary_str 74 | 75 | def pack(self): 76 | buffer = bytearray() 77 | for address in self.blocks: 78 | content = self.blocks[address] 79 | block_buffer = self.pack_block(address, content) 80 | buffer += block_buffer 81 | sh = hashlib.sha256() 82 | sh.update(buffer) 83 | self.packed_hash = sh.hexdigest() 84 | print("Pack hash: " + self.packed_hash) 85 | header = self.pack_header() 86 | self.packed_buffer = header + buffer 87 | return self.packed_buffer 88 | 89 | def pack_header(self): 90 | header = self.version_binary_str 91 | sha256 = hashlib.sha256() 92 | sha256.update(self.version_binary_str) 93 | checksum = sha256.digest()[:4] 94 | 95 | header = header + checksum 96 | header = header + b'\x00' * (32 - len(header)) 97 | 98 | packhash = bytearray.fromhex(self.packed_hash) 99 | header = header + packhash 100 | 101 | # signature part 102 | header = header + b'\x00' * 64 103 | return header 104 | 105 | def pack_block(self, address, content): 106 | #address = address & 0xFFFF 107 | buffer = struct.pack('>LL%ds' % len(content), address, 0, content) 108 | 109 | encrypted_buffer = self.encrypt(buffer) 110 | # print("%08X" % address, buffer.hex(' '), "\n---\n", encrypted_buffer.hex(' ')) 111 | print("%08X" % address) 112 | encrypted_buffer_with_checksum = encrypted_buffer + self.calculate_checksum(encrypted_buffer) 113 | return encrypted_buffer_with_checksum 114 | 115 | def parse_argument(): 116 | parser = argparse.ArgumentParser() 117 | parser.add_argument("-f", "--file", help="Input hex file, like mason_app.hex", type=str, default="mason_app.hex", required=False) 118 | parser.add_argument("-i", "--iv", help="3DES CBC initial vection", type=str, default="DE59B68A", required=False) 119 | parser.add_argument("-k", "--key", help="3DES key, length must be 16 or 24 byte", type=str, default="C6E6B09E45227FCD80BF497C", required=False) 120 | parser.add_argument("-t", "--target-version", help="Target version, format is X.X.X.XXXXX, 1.0.0.000000", required=True) 121 | args = parser.parse_args() 122 | return args 123 | 124 | if __name__ == '__main__': 125 | args = parse_argument() 126 | firmware_packer = FirmwarePacker(args.target_version, args.key, args.iv) 127 | print('Loading file from %s ...' % args.file) 128 | firmware_packer.load_from_file(args.file) 129 | output = "app." + args.target_version + ".bin" 130 | print('Packing and write to file %s ...' % output) 131 | firmware_packer.write_to_file(output) 132 | print('Done.') 133 | exit(0) -------------------------------------------------------------------------------- /source/COMMON/circular_buffer.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define CIRCULAR_BUFFER_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "circular_buffer.h" 22 | // #include 23 | #include 24 | 25 | /** Function implementations */ 26 | /** 27 | * @functionname: circular_buf_init 28 | * @description: 29 | * @para: 30 | * @return: 31 | */ 32 | cbuf_handle_t circular_buf_init(uint8_t *buffer, size_t size) 33 | { 34 | cbuf_handle_t cbuf = NULL; 35 | 36 | // assert(buffer && size); 37 | 38 | cbuf = calloc(1, sizeof(circular_buf_t)); 39 | // assert(cbuf); 40 | if(NULL == cbuf) 41 | { 42 | return NULL; 43 | } 44 | 45 | cbuf->buffer = buffer; 46 | cbuf->max = size; 47 | circular_buf_reset(cbuf); 48 | 49 | // assert(circular_buf_empty(cbuf)); 50 | 51 | return cbuf; 52 | } 53 | /** 54 | * @functionname: circular_buf_reset 55 | * @description: 56 | * @para: 57 | * @return: 58 | */ 59 | void circular_buf_reset(cbuf_handle_t cbuf) 60 | { 61 | // assert(cbuf); 62 | 63 | cbuf->head = 0; 64 | cbuf->tail = 0; 65 | cbuf->full = false; 66 | memset(cbuf->buffer, 0, cbuf->max); 67 | } 68 | /** 69 | * @functionname: circular_buf_free 70 | * @description: 71 | * @para: 72 | * @return: 73 | */ 74 | void circular_buf_free(cbuf_handle_t cbuf) 75 | { 76 | // assert(cbuf); 77 | free(cbuf); 78 | } 79 | /** 80 | * @functionname: circular_buf_full 81 | * @description: 82 | * @para: 83 | * @return: 84 | */ 85 | bool circular_buf_full(cbuf_handle_t cbuf) 86 | { 87 | // assert(cbuf); 88 | 89 | return cbuf->full; 90 | } 91 | /** 92 | * @functionname: circular_buf_empty 93 | * @description: 94 | * @para: 95 | * @return: 96 | */ 97 | bool circular_buf_empty(cbuf_handle_t cbuf) 98 | { 99 | // assert(cbuf); 100 | 101 | return (!cbuf->full && (cbuf->head == cbuf->tail)); 102 | } 103 | /** 104 | * @functionname: circular_buf_capacity 105 | * @description: 106 | * @para: 107 | * @return: 108 | */ 109 | size_t circular_buf_capacity(cbuf_handle_t cbuf) 110 | { 111 | // assert(cbuf); 112 | 113 | return cbuf->max; 114 | } 115 | /** 116 | * @functionname: circular_buf_size 117 | * @description: 118 | * @para: 119 | * @return: 120 | */ 121 | size_t circular_buf_size(cbuf_handle_t cbuf) 122 | { 123 | size_t size = 0; 124 | 125 | // assert(cbuf); 126 | 127 | size = cbuf->max; 128 | 129 | if (!cbuf->full) 130 | { 131 | if (cbuf->head >= cbuf->tail) 132 | { 133 | size = (cbuf->head - cbuf->tail); 134 | } 135 | else 136 | { 137 | size = (cbuf->max + cbuf->head - cbuf->tail); 138 | } 139 | } 140 | 141 | return size; 142 | } 143 | /** 144 | * @functionname: advance_pointer 145 | * @description: 146 | * @para: 147 | * @return: 148 | */ 149 | static void advance_pointer(cbuf_handle_t cbuf) 150 | { 151 | // assert(cbuf); 152 | 153 | if (cbuf->full) 154 | { 155 | cbuf->tail = (cbuf->tail + 1) % cbuf->max; 156 | } 157 | 158 | cbuf->head = (cbuf->head + 1) % cbuf->max; 159 | cbuf->full = (cbuf->head == cbuf->tail); 160 | } 161 | /** 162 | * @functionname: retreat_pointer 163 | * @description: 164 | * @para: 165 | * @return: 166 | */ 167 | static void retreat_pointer(cbuf_handle_t cbuf) 168 | { 169 | // assert(cbuf); 170 | 171 | cbuf->full = false; 172 | cbuf->tail = (cbuf->tail + 1) % cbuf->max; 173 | } 174 | /** 175 | * @functionname: circular_buf_put 176 | * @description: 177 | * @para: 178 | * @return: 179 | */ 180 | void circular_buf_put(cbuf_handle_t cbuf, uint8_t data) 181 | { 182 | // assert(cbuf && cbuf->buffer); 183 | 184 | cbuf->buffer[cbuf->head] = data; 185 | 186 | advance_pointer(cbuf); 187 | } 188 | /** 189 | * @functionname: circular_buf_put2 190 | * @description: 191 | * @para: 192 | * @return: 193 | */ 194 | int circular_buf_put2(cbuf_handle_t cbuf, uint8_t data) 195 | { 196 | int r = -1; 197 | 198 | // assert(cbuf && cbuf->buffer); 199 | 200 | if (!circular_buf_full(cbuf)) 201 | { 202 | cbuf->buffer[cbuf->head] = data; 203 | advance_pointer(cbuf); 204 | r = 0; 205 | } 206 | 207 | return r; 208 | } 209 | /** 210 | * @functionname: circular_buf_get 211 | * @description: 212 | * @para: 213 | * @return: 214 | */ 215 | int circular_buf_get(cbuf_handle_t cbuf, uint8_t *data) 216 | { 217 | int r = -1; 218 | 219 | // assert(cbuf && data && cbuf->buffer); 220 | 221 | if (!circular_buf_empty(cbuf)) 222 | { 223 | *data = cbuf->buffer[cbuf->tail]; 224 | retreat_pointer(cbuf); 225 | 226 | r = 0; 227 | } 228 | 229 | return r; 230 | } 231 | -------------------------------------------------------------------------------- /source/crypto/bip39.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | Copyright (c) 2021 Keystone 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | in the file COPYING. If not, see . 16 | **************************************************************************************************/ 17 | /** Avoid duplicate definitions */ 18 | #define BIP39_GLOBAL 19 | 20 | /** Header file reference */ 21 | #include "bip39.h" 22 | #include "crypto_api.h" 23 | #include "stdio.h" 24 | #include 25 | #include 26 | #include 27 | 28 | #define BIP39_PBKDF2_ROUNDS 2048 29 | 30 | /** Function implementations */ 31 | /** 32 | * @functionname: PBKDF2_HMAC_SHA512 33 | * @description: 34 | * @para: 35 | * @return: 36 | * @notice:pPassword is HMAC's key; pSalt is HMAC's text 37 | * BIP39: 38 | * To create a binary seed from the mnemonic, we use the PBKDF2 function 39 | * with a mnemonic sentence (in UTF-8 NFKD) used as the password 40 | * and the string "mnemonic" + passphrase (again in UTF-8 NFKD) used as the salt. 41 | * The iteration count is set to 2048 and HMAC-SHA512 is used as the pseudo-random function. 42 | * The length of the derived key is 512 bits (= 64 bytes). 43 | */ 44 | void PBKDF2_HMAC_SHA512(uint8_t *pPassword, uint32_t passwordLen, 45 | uint8_t *pSalt, uint32_t saltLen, 46 | uint32_t iterC, uint8_t *pOut, int32_t outLen) 47 | { 48 | uint32_t i, j; 49 | uint8_t *pKey = pPassword; 50 | uint32_t keyLen = passwordLen; 51 | char *pPassphrase_prefix = PASSPHRASE_PREFIX; 52 | uint8_t *pText; 53 | uint32_t textLen = 0; 54 | 55 | uint8_t bufSHA512Key[SHA512_LEN]; 56 | uint8_t bufSHA512[SHA512_LEN]; 57 | uint8_t bufSHA512Tmp[SHA512_LEN]; 58 | uint32_t I = 1; 59 | uint8_t bufI[4] = {0x00}; 60 | uint32_t outOffset = 0; 61 | 62 | memset(bufSHA512, 0x00, SHA512_LEN); 63 | memset(bufSHA512Tmp, 0x00, SHA512_LEN); 64 | textLen = strlen(pPassphrase_prefix); 65 | pText = (uint8_t *)calloc(textLen + saltLen + 4, sizeof(uint8_t)); 66 | if (NULL == pText) 67 | { 68 | return; 69 | } 70 | memcpy(pText, pPassphrase_prefix, textLen); 71 | if (saltLen > 0) 72 | { 73 | memcpy(pText + textLen, pSalt, saltLen); 74 | textLen += saltLen; 75 | } 76 | 77 | if (keyLen > 128) 78 | { 79 | sha512_api(pKey, keyLen, bufSHA512Key); 80 | pKey = bufSHA512Key; 81 | keyLen = SHA512_LEN; 82 | } 83 | while (outLen > 0) 84 | { 85 | bufI[0] = (uint8_t)((I >> 24) & 0xff); 86 | bufI[1] = (uint8_t)((I >> 16) & 0xff); 87 | bufI[2] = (uint8_t)((I >> 8) & 0xff); 88 | bufI[3] = (uint8_t)(I & 0xff); 89 | // u32_to_buf(bufI, I); 90 | memcpy(pText + textLen, bufI, 4); 91 | 92 | hmac_sha512_api(pText, textLen + 4, pKey, keyLen, bufSHA512Tmp); 93 | memcpy(bufSHA512, bufSHA512Tmp, SHA512_LEN); 94 | for (i = 1; i < iterC; i++) 95 | { 96 | // feed_dog(); 97 | wdt_feed(); 98 | hmac_sha512_api(bufSHA512Tmp, SHA512_LEN, pKey, keyLen, bufSHA512Tmp); 99 | for (j = 0; j < SHA512_LEN; j++) 100 | { 101 | bufSHA512[j] ^= bufSHA512Tmp[j]; 102 | } 103 | } 104 | memcpy(pOut + outOffset, bufSHA512, outLen >= SHA512_LEN ? SHA512_LEN : outLen); 105 | outOffset += SHA512_LEN; 106 | outLen -= SHA512_LEN; 107 | I++; 108 | } 109 | if (NULL != pText) 110 | { 111 | free(pText); 112 | } 113 | 114 | return; 115 | } 116 | 117 | /** 118 | * @functionname: mnemonic_to_seed 119 | * @description: 120 | * @para: 121 | * @return: 122 | * @notice: pMnemonic -> password;pPassphrase -> salt 123 | * @notice: seed output from BIP39 is BIP32 input seed 124 | */ 125 | void mnemonic_to_seed(const char *mnemonic, int mnemoniclen, const char *passphrase, int passphraselen, uint8_t seed[512 / 8]) 126 | { 127 | 128 | uint8_t salt[8 + 256] = {0}; 129 | memcpy(salt, "mnemonic", 8); 130 | memcpy(salt + 8, passphrase, passphraselen); 131 | static PBKDF2_HMAC_SHA512_CTX pctx; 132 | pbkdf2_hmac_sha512_Init(&pctx, (const uint8_t *)mnemonic, mnemoniclen, salt, 133 | passphraselen + 8, 1); 134 | 135 | for (int i = 0; i < 16; i++) 136 | { 137 | pbkdf2_hmac_sha512_Update(&pctx, BIP39_PBKDF2_ROUNDS / 16); 138 | } 139 | pbkdf2_hmac_sha512_Final(&pctx, seed); 140 | memzero(salt, sizeof(salt)); 141 | } 142 | 143 | /** 144 | * @functionname: bip39_gen_seed_with_mnemonic 145 | * @description: 146 | * @para: 147 | * @return: 148 | * @notice: pMnemonic -> password;pPassphrase -> salt 149 | * @notice: seed output from BIP39 is BIP32 input seed 150 | */ 151 | void bip39_gen_seed_with_mnemonic(uint8_t *pMnemonic, uint32_t mnemonicLen, 152 | uint8_t *pPassphrase, uint32_t passphraseLen, 153 | uint8_t *pSeed, int32_t seedLen) 154 | { 155 | PBKDF2_HMAC_SHA512(pMnemonic, mnemonicLen, pPassphrase, passphraseLen, 156 | 2048, pSeed, seedLen); 157 | } 158 | /** 159 | * @functionname: bip39_gen_seed_with_entropy 160 | * @description: 161 | * @para: 162 | * @return: 163 | * @notice: pEntropy -> password;pPassphrase -> salt 164 | * @notice: seed output from BIP39 is BIP32 input seed 165 | */ 166 | void bip39_gen_seed_with_entropy(uint8_t *pEntropy, uint32_t entropyLen, 167 | uint8_t *pPassphrase, uint32_t passphraseLen, 168 | uint8_t *pSeed, int32_t seedLen) 169 | { 170 | if ((entropyLen < 16) || (entropyLen > 32) || (0 != entropyLen % 4)) 171 | { 172 | return; 173 | } 174 | PBKDF2_HMAC_SHA512(pEntropy, entropyLen, pPassphrase, passphraseLen, 175 | 2048, pSeed, seedLen); 176 | } 177 | -------------------------------------------------------------------------------- /source/driver/timer.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __TIMER_H__ 3 | #define __TIMER_H__ 4 | 5 | #include "common.h" 6 | 7 | /*----------------------TIMER BIT------------------------*/ 8 | #define VAL_TIMER_ENABLE 1 9 | #define VAL_TIMER_DISABLE 0 10 | 11 | #define VAL_TIMER_CONTROL_MOD_FREE 0 12 | #define VAL_TIMER_CONTROL_MOD_CYC 2 13 | #define VAL_TIMER_CONTROL_MOD_SINGLE 3 14 | 15 | #define VAL_TIMER_INT_MASK 1 16 | #define VAL_TIMER_INT_NOMASK 0 17 | 18 | #define VAL_TIMER_COUNT_UP 0 19 | #define VAL_TIMER_COUNT_DOWN 1 20 | #define VAL_TIMER_COUNT_CENTER 2 21 | 22 | #define VAL_TIMER_PRES_DIVISOR_1 0 23 | #define VAL_TIMER_PRES_DIVISOR_2 1 24 | #define VAL_TIMER_PRES_DIVISOR_4 2 25 | #define VAL_TIMER_PRES_DIVISOR_8 3 26 | #define VAL_TIMER_PRES_DIVISOR_16 4 27 | #define VAL_TIMER_PRES_DIVISOR_32 5 28 | #define VAL_TIMER_PRES_DIVISOR_64 6 29 | #define VAL_TIMER_PRES_DIVISOR_128 7 30 | 31 | #define CAPTURE_TRIGGER_RISING 0 32 | #define CAPTURE_TRIGGER_FALLING 1 33 | 34 | extern volatile UINT8 flag_timer0_int; 35 | extern volatile UINT8 flag_timer0_pwm_int; 36 | extern volatile UINT8 flag_timer0_cc_int; 37 | 38 | extern volatile UINT8 flag_timer1_int; 39 | extern volatile UINT8 flag_timer1_cc_int; 40 | extern volatile UINT8 flag_timer1_pwm_int; 41 | 42 | extern volatile UINT8 flag_timer2_int; 43 | 44 | /************************************************************************ 45 | * function : timer_init 46 | * Description: timer initial 47 | * input : none 48 | * return: none 49 | ************************************************************************/ 50 | void timer_init(void); 51 | 52 | /************************************************************************ 53 | * function : timer_set_us 54 | * Description: timer set_us 55 | * input : 56 | * UINT8 num: TIMER0,1,2 57 | * UINT32 timer_us: delay timer_us 58 | * void(*pFunc)() pFunc: processing function 59 | * return: none 60 | ************************************************************************/ 61 | void timer_set_us(UINT8 num, UINT32 timer_us, void (*pFunc)()); 62 | 63 | /************************************************************************ 64 | * function : timer_set_ms 65 | * Description: timer set_ms 66 | * input : 67 | * UINT8 num: TIMER0,1,2 68 | * UINT32 timer_us: delay timer_ms 69 | * void(*pFunc)() pFunc: processing function 70 | * return: none 71 | ************************************************************************/ 72 | void timer_set_ms(UINT8 num, UINT32 timer_ms, void (*pFunc)()); 73 | 74 | /************************************************************************ 75 | * function : timer_start 76 | * Description: timer start 77 | * input : 78 | * UINT8 num: TIMER0,1,2 79 | * return: 80 | ************************************************************************/ 81 | void timer_start(UINT8 num); 82 | 83 | /************************************************************************ 84 | * function : timer_stop 85 | * Description: timer stop 86 | * input : 87 | * UINT8 num: TIMER0,1,2 88 | * return: 89 | ************************************************************************/ 90 | void timer_stop(UINT8 num); 91 | 92 | /************************************************************************ 93 | * function : capture_set 94 | * Description: capture set 95 | * input : 96 | * UINT8 num: only TIMER0,1 97 | * UINT8 source: 0-GPIO,1-USB_RECV,2-AUDIO_RECV_OUT 98 | * UINT8 divider: divider 2^n 99 | * UINT8 trigger: 0 -- CAPTURE_TRIGGER_RISING 100 | * 1 -- CAPTURE_TRIGGER_FALLING 101 | * void(*pFunc)() pFunc: processing function 102 | * return: none 103 | ************************************************************************/ 104 | void capture_set(UINT8 num,UINT8 source,UINT8 divider, UINT8 trigger, void (*pFunc)()); 105 | 106 | /************************************************************************ 107 | * function : capture_start 108 | * Description: capture start 109 | * input : 110 | * UINT8 num: only TIMER0,1 111 | * return: none 112 | ************************************************************************/ 113 | void capture_start(UINT8 num); 114 | 115 | /************************************************************************ 116 | * function : capture_stop 117 | * Description: capture stop 118 | * input : 119 | * UINT8 num: only TIMER0,1 120 | * return: none 121 | ************************************************************************/ 122 | void capture_stop(UINT8 num); 123 | 124 | /************************************************************************ 125 | * function : pwm_set 126 | * Description: pwm set frequence 127 | * input : 128 | * UINT8 num: only TIMER0,1 129 | * UINT32 timer_freq: timer frequence 130 | * UINT32 pwm_freq: pwm frequence 131 | * return: none 132 | ************************************************************************/ 133 | void pwm_set(UINT8 num, UINT32 timer_arr, UINT32 pwm_pr); 134 | 135 | /************************************************************************ 136 | * function : pwm_start 137 | * Description: pwm start 138 | * input : 139 | * UINT8 num: only TIMER0,1 140 | * return: none 141 | ************************************************************************/ 142 | void pwm_start(UINT8 num); 143 | 144 | /************************************************************************ 145 | * function : pwm_stop 146 | * Description: pwm stop 147 | * input : 148 | * UINT8 num: only TIMER0,1 149 | * return: none 150 | ************************************************************************/ 151 | void pwm_stop(UINT8 num); 152 | 153 | /************************************************************************ 154 | * function : pwm_output_wave 155 | * Description: pwm output wave --hz 156 | * input : 157 | * UINT8 num: only TIMER0,1 158 | * UINT32 freq_hz: output freq 159 | * UINT32 duty: 0 - 100 percent 160 | * return: none 161 | ************************************************************************/ 162 | void pwm_output_wave(UINT8 num, UINT32 freq_hz, UINT8 duty); 163 | 164 | void timer_output_stop(UINT8 num); 165 | 166 | 167 | 168 | #endif 169 | 170 | 171 | --------------------------------------------------------------------------------