Added a major refactoring to include Emulated interface.

It works in combination with virtualsmarcard module (vpcd). It properly installed, it creates a virtual reader that can be interfaced via PCSC+vcpd. At user app level, it has no difference of having a physical smart card.

At this moment, it only works emulating a CCID interface.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
This commit is contained in:
Pol Henarejos
2023-01-09 18:06:21 +01:00
parent 2d511df5d8
commit 4919eb980f
24 changed files with 617 additions and 141 deletions

View File

@@ -17,24 +17,31 @@
cmake_minimum_required(VERSION 3.13) cmake_minimum_required(VERSION 3.13)
include(pico_sdk_import.cmake) project(pico_hsm_sdk C)
project(pico_hsm_sdk C CXX ASM)
set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
if(ENABLE_EMULATION)
else()
include(pico_sdk_import.cmake)
pico_sdk_init() pico_sdk_init()
endif()
add_executable(pico_hsm_sdk_exe) add_executable(pico_hsm_sdk_exe)
include(pico_hsm_sdk.cmake) set(USB_ITF_HID 1)
set(USB_ITF_CCID 1)
include(pico_hsm_sdk_import.cmake)
target_compile_options(pico_hsm_sdk_exe PUBLIC target_compile_options(pico_hsm_sdk_exe PUBLIC
-Wall -Wall
-Werror -Werror
) )
if(ENABLE_EMULATION)
else()
pico_add_extra_outputs(pico_hsm_sdk_exe) pico_add_extra_outputs(pico_hsm_sdk_exe)
target_link_libraries(pico_hsm_sdk_exe PRIVATE pico_hsm_sdk pico_stdlib pico_multicore hardware_flash hardware_sync hardware_adc pico_unique_id hardware_rtc tinyusb_device tinyusb_board) target_link_libraries(pico_hsm_sdk_exe PRIVATE pico_hsm_sdk pico_stdlib pico_multicore hardware_flash hardware_sync hardware_adc pico_unique_id hardware_rtc tinyusb_device tinyusb_board)
endif()

View File

@@ -26,6 +26,9 @@ add_definitions(-DUSB_PID=${USB_PID})
if (NOT DEFINED DEBUG_APDU) if (NOT DEFINED DEBUG_APDU)
set(DEBUG_APDU 0) set(DEBUG_APDU 0)
endif() endif()
if (NOT DEFINED ENABLE_EMULATION)
set(ENABLE_EMULATION 0)
endif()
option(ENABLE_DELAYED_BOOT "Enable/disable delayed boot" OFF) option(ENABLE_DELAYED_BOOT "Enable/disable delayed boot" OFF)
if(ENABLE_DELAYED_BOOT) if(ENABLE_DELAYED_BOOT)
@@ -34,14 +37,17 @@ if(ENABLE_DELAYED_BOOT)
else() else()
message(STATUS "Delayed boot:\t\t disabled") message(STATUS "Delayed boot:\t\t disabled")
endif(ENABLE_DELAYED_BOOT) endif(ENABLE_DELAYED_BOOT)
if(USB_ITF_HID) if(ENABLE_EMULATION)
add_definitions(-DUSB_ITF_HID=1) else()
message(STATUS "USB HID Interface:\t\t enabled") if(USB_ITF_HID)
endif(USB_ITF_HID) add_definitions(-DUSB_ITF_HID=1)
if(USB_ITF_CCID) message(STATUS "USB HID Interface:\t\t enabled")
add_definitions(-DUSB_ITF_CCID=1) endif(USB_ITF_HID)
message(STATUS "USB CCID Interface:\t\t enabled") if(USB_ITF_CCID)
endif(USB_ITF_CCID) add_definitions(-DUSB_ITF_CCID=1)
message(STATUS "USB CCID Interface:\t\t enabled")
endif(USB_ITF_CCID)
endif()
add_definitions(-DDEBUG_APDU=${DEBUG_APDU}) add_definitions(-DDEBUG_APDU=${DEBUG_APDU})
configure_file(${CMAKE_CURRENT_LIST_DIR}/config/mbedtls_config.h ${CMAKE_CURRENT_LIST_DIR}/mbedtls/include/mbedtls COPYONLY) configure_file(${CMAKE_CURRENT_LIST_DIR}/config/mbedtls_config.h ${CMAKE_CURRENT_LIST_DIR}/mbedtls/include/mbedtls COPYONLY)
@@ -50,92 +56,136 @@ message(STATUS "USB VID/PID: ${USB_VID}:${USB_PID}")
configure_file(${CMAKE_CURRENT_LIST_DIR}/config/mbedtls_config.h ${CMAKE_CURRENT_LIST_DIR}/mbedtls/include/mbedtls COPYONLY) configure_file(${CMAKE_CURRENT_LIST_DIR}/config/mbedtls_config.h ${CMAKE_CURRENT_LIST_DIR}/mbedtls/include/mbedtls COPYONLY)
if (NOT TARGET pico_hsm_sdk) set(SOURCES ${SOURCES}
pico_add_impl_library(pico_hsm_sdk) ${CMAKE_CURRENT_LIST_DIR}/src/main.c
${CMAKE_CURRENT_LIST_DIR}/src/usb/usb.c
${CMAKE_CURRENT_LIST_DIR}/src/fs/file.c
${CMAKE_CURRENT_LIST_DIR}/src/fs/flash.c
${CMAKE_CURRENT_LIST_DIR}/src/fs/low_flash.c
${CMAKE_CURRENT_LIST_DIR}/src/rng/random.c
${CMAKE_CURRENT_LIST_DIR}/src/rng/hwrng.c
${CMAKE_CURRENT_LIST_DIR}/src/eac.c
${CMAKE_CURRENT_LIST_DIR}/src/crypto_utils.c
${CMAKE_CURRENT_LIST_DIR}/src/asn1.c
${CMAKE_CURRENT_LIST_DIR}/src/apdu.c
target_sources(pico_hsm_sdk INTERFACE ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/aes.c
${CMAKE_CURRENT_LIST_DIR}/src/main.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/asn1parse.c
${CMAKE_CURRENT_LIST_DIR}/src/usb/usb.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/asn1write.c
${CMAKE_CURRENT_LIST_DIR}/src/usb/usb_descriptors.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/bignum.c
${CMAKE_CURRENT_LIST_DIR}/src/fs/file.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/cmac.c
${CMAKE_CURRENT_LIST_DIR}/src/fs/flash.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/cipher.c
${CMAKE_CURRENT_LIST_DIR}/src/fs/low_flash.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/cipher_wrap.c
${CMAKE_CURRENT_LIST_DIR}/src/rng/random.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/constant_time.c
${CMAKE_CURRENT_LIST_DIR}/src/rng/hwrng.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecdsa.c
${CMAKE_CURRENT_LIST_DIR}/src/eac.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecdh.c
${CMAKE_CURRENT_LIST_DIR}/src/crypto_utils.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecp.c
${CMAKE_CURRENT_LIST_DIR}/src/asn1.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecp_curves.c
${CMAKE_CURRENT_LIST_DIR}/src/apdu.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/hkdf.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/md.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/md5.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/oid.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pkcs5.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/platform_util.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ripemd160.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/rsa.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/rsa_alt_helpers.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/sha1.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/sha256.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/sha512.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/chachapoly.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/chacha20.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/poly1305.c
)
set(INCLUDES ${INCLUDES}
${CMAKE_CURRENT_LIST_DIR}/src
${CMAKE_CURRENT_LIST_DIR}/src/usb
${CMAKE_CURRENT_LIST_DIR}/src/fs
${CMAKE_CURRENT_LIST_DIR}/src/rng
${CMAKE_CURRENT_LIST_DIR}/mbedtls/include
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library
)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/aes.c if(${USB_ITF_HID} OR ${ENABLE_EMULATION})
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/asn1parse.c set(SOURCES ${SOURCES}
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/asn1write.c ${CMAKE_CURRENT_LIST_DIR}/tinycbor/src/cborencoder.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/bignum.c ${CMAKE_CURRENT_LIST_DIR}/tinycbor/src/cborparser.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/cmac.c ${CMAKE_CURRENT_LIST_DIR}/tinycbor/src/cborparser_dup_string.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/cipher.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/x509write_crt.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/cipher_wrap.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/x509_create.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/constant_time.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/x509write_csr.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecdsa.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pk.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecdh.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pk_wrap.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecp.c ${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pkwrite.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ecp_curves.c )
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/hkdf.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/md.c set(INCLUDES ${INCLUDES}
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/md5.c ${CMAKE_CURRENT_LIST_DIR}/tinycbor/src
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/oid.c )
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pkcs5.c endif()
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/platform_util.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ripemd160.c function(add_impl_library target)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/rsa.c add_library(${target} INTERFACE)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/rsa_alt_helpers.c string(TOUPPER ${target} TARGET_UPPER)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/sha1.c target_compile_definitions(${target} INTERFACE LIB_${TARGET_UPPER}=1)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/sha256.c endfunction()
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/sha512.c if (ENABLE_EMULATION)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/chachapoly.c set(CMAKE_OSX_SYSROOT "/Library/Developer/CommandLineTools//SDKs/MacOSX11.3.sdk")
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/chacha20.c add_definitions(-DENABLE_EMULATION)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/poly1305.c set(SOURCES ${SOURCES}
) ${CMAKE_CURRENT_LIST_DIR}/src/usb/emulation/emulation.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/ctr_drbg.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/entropy.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/entropy_poll.c
)
set(INCLUDES ${INCLUDES}
${CMAKE_CURRENT_LIST_DIR}/src/usb/emulation
)
if (NOT TARGET pico_hsm_sdk)
add_impl_library(pico_hsm_sdk)
target_sources(pico_hsm_sdk INTERFACE
${SOURCES}
)
target_include_directories(pico_hsm_sdk INTERFACE
${INCLUDES}
)
endif()
else()
if(${USB_ITF_HID})
set(SOURCES ${SOURCES}
${CMAKE_CURRENT_LIST_DIR}/src/usb/hid/hid.c
)
set(INCLUDES ${INCLUDES}
${CMAKE_CURRENT_LIST_DIR}/src/usb/hid
)
endif()
if (${USB_ITF_CCID}) if (${USB_ITF_CCID})
target_sources(pico_hsm_sdk INTERFACE set(SOURCES ${SOURCES}
${CMAKE_CURRENT_LIST_DIR}/src/usb/ccid/ccid.c ${CMAKE_CURRENT_LIST_DIR}/src/usb/ccid/ccid.c
) )
target_include_directories(pico_hsm_sdk INTERFACE set(INCLUDES ${INCLUDES}
${CMAKE_CURRENT_LIST_DIR}/src/usb/ccid ${CMAKE_CURRENT_LIST_DIR}/src/usb/ccid
) )
endif()
if (${USB_ITF_HID})
target_sources(pico_hsm_sdk INTERFACE
${CMAKE_CURRENT_LIST_DIR}/src/usb/hid/hid.c
${CMAKE_CURRENT_LIST_DIR}/tinycbor/src/cborencoder.c
${CMAKE_CURRENT_LIST_DIR}/tinycbor/src/cborparser.c
${CMAKE_CURRENT_LIST_DIR}/tinycbor/src/cborparser_dup_string.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/x509write_crt.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/x509_create.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/x509write_csr.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pk.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pk_wrap.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pkwrite.c
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library/pkwrite.c
)
target_include_directories(pico_hsm_sdk INTERFACE
${CMAKE_CURRENT_LIST_DIR}/src/usb/hid
${CMAKE_CURRENT_LIST_DIR}/tinycbor/src
)
endif() endif()
target_include_directories(pico_hsm_sdk INTERFACE set(SOURCES ${SOURCES}
${CMAKE_CURRENT_LIST_DIR}/src ${CMAKE_CURRENT_LIST_DIR}/src/usb/usb_descriptors.c
${CMAKE_CURRENT_LIST_DIR}/src/usb )
${CMAKE_CURRENT_LIST_DIR}/src/fs if (NOT TARGET pico_hsm_sdk)
${CMAKE_CURRENT_LIST_DIR}/src/rng pico_add_impl_library(pico_hsm_sdk)
${CMAKE_CURRENT_LIST_DIR}/mbedtls/include
${CMAKE_CURRENT_LIST_DIR}/mbedtls/library
)
target_link_libraries(pico_hsm_sdk INTERFACE pico_stdlib pico_multicore hardware_flash hardware_sync hardware_adc pico_unique_id hardware_rtc tinyusb_device tinyusb_board) target_sources(pico_hsm_sdk INTERFACE
${SOURCES}
)
target_include_directories(pico_hsm_sdk INTERFACE
${INCLUDES}
)
target_link_libraries(pico_hsm_sdk INTERFACE pico_stdlib pico_multicore hardware_flash hardware_sync hardware_adc pico_unique_id hardware_rtc tinyusb_device tinyusb_board)
endif()
endif() endif()

View File

@@ -142,6 +142,7 @@ uint16_t set_res_sw(uint8_t sw1, uint8_t sw2) {
return make_uint16_t(sw1, sw2); return make_uint16_t(sw1, sw2);
} }
#ifndef ENABLE_EMULATION
void apdu_thread() { void apdu_thread() {
card_init_core1(); card_init_core1();
while (1) { while (1) {
@@ -171,6 +172,7 @@ void apdu_thread() {
current_app = NULL; current_app = NULL;
} }
} }
#endif
void apdu_finish() { void apdu_finish() {
apdu.rdata[apdu.rlen] = apdu.sw >> 8; apdu.rdata[apdu.rlen] = apdu.sw >> 8;

View File

@@ -19,8 +19,11 @@
#define _APDU_H_ #define _APDU_H_
#include <stdlib.h> #include <stdlib.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#endif
#include <stdio.h> #include <stdio.h>
#include <inttypes.h>
typedef struct app { typedef struct app {
const uint8_t *aid; const uint8_t *aid;
@@ -40,9 +43,9 @@ typedef struct cmd
#if defined(DEBUG_APDU) && DEBUG_APDU == 1 #if defined(DEBUG_APDU) && DEBUG_APDU == 1
#define DEBUG_PAYLOAD(_p,_s) { \ #define DEBUG_PAYLOAD(_p,_s) { \
printf("Payload %s (%d bytes):\r\n", #_p,_s);\ printf("Payload %s (%d bytes):\r\n", #_p,(int)(_s));\
for (int _i = 0; _i < _s; _i += 16) {\ for (int _i = 0; _i < _s; _i += 16) {\
printf("%07Xh : ",(unsigned int)(_i+_p));\ printf("%"PRIxPTR"h : ",(uintptr_t)(_i+_p));\
for (int _j = 0; _j < 16; _j++) {\ for (int _j = 0; _j < 16; _j++) {\
if (_j < _s-_i) printf("%02X ",(_p)[_i+_j]);\ if (_j < _s-_i) printf("%02X ",(_p)[_i+_j]);\
else printf(" ");\ else printf(" ");\
@@ -57,7 +60,7 @@ typedef struct cmd
} }
#define DEBUG_DATA(_p, _s) \ #define DEBUG_DATA(_p, _s) \
{ \ { \
printf("Data %s (%d bytes):\r\n", #_p, _s); \ printf("Data %s (%d bytes):\r\n", #_p, (int)(_s)); \
char *tmp = (char *)calloc(1, 2 * _s + 1); \ char *tmp = (char *)calloc(1, 2 * _s + 1); \
for (int _i = 0; _i < _s; _i++) \ for (int _i = 0; _i < _s; _i++) \
{ \ { \

View File

@@ -19,7 +19,12 @@
#define _ASN1_H_ #define _ASN1_H_
#include <stdlib.h> #include <stdlib.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#else
#include <stdint.h>
#include <stdbool.h>
#endif
extern int walk_tlv(const uint8_t *cdata, size_t cdata_len, uint8_t **p, uint16_t *tag, size_t *tag_len, uint8_t **data); extern int walk_tlv(const uint8_t *cdata, size_t cdata_len, uint8_t **p, uint16_t *tag, size_t *tag_len, uint8_t **data);
extern int format_tlv_len(size_t len, uint8_t *out); extern int format_tlv_len(size_t len, uint8_t *out);

View File

@@ -15,7 +15,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef ENABLE_EMULATION
#include <pico/unique_id.h> #include <pico/unique_id.h>
#endif
#include "mbedtls/md.h" #include "mbedtls/md.h"
#include "mbedtls/sha256.h" #include "mbedtls/sha256.h"
#include "mbedtls/aes.h" #include "mbedtls/aes.h"
@@ -34,12 +36,15 @@ void hash_multi(const uint8_t *input, size_t len, uint8_t output[32]) {
mbedtls_sha256_context ctx; mbedtls_sha256_context ctx;
mbedtls_sha256_init(&ctx); mbedtls_sha256_init(&ctx);
int iters = 256; int iters = 256;
#ifndef ENABLE_EMULATION
pico_unique_board_id_t unique_id; pico_unique_board_id_t unique_id;
pico_get_unique_board_id(&unique_id); pico_get_unique_board_id(&unique_id);
#endif
mbedtls_sha256_starts (&ctx, 0); mbedtls_sha256_starts (&ctx, 0);
#ifndef ENABLE_EMULATION
mbedtls_sha256_update (&ctx, unique_id.id, sizeof(unique_id.id)); mbedtls_sha256_update (&ctx, unique_id.id, sizeof(unique_id.id));
#endif
while (iters > len) while (iters > len)
{ {

View File

@@ -19,7 +19,9 @@
#define _CRYPTO_UTILS_H_ #define _CRYPTO_UTILS_H_
#include "stdlib.h" #include "stdlib.h"
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#endif
#include "mbedtls/ecp.h" #include "mbedtls/ecp.h"
#include "mbedtls/md.h" #include "mbedtls/md.h"

View File

@@ -19,7 +19,9 @@
#define _EAC_H_ #define _EAC_H_
#include <stdlib.h> #include <stdlib.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#endif
#include "hsm.h" #include "hsm.h"
typedef enum MSE_protocol { typedef enum MSE_protocol {

View File

@@ -223,7 +223,7 @@ void scan_region(bool persistent) {
break; break;
uint16_t fid = flash_read_uint16(base+sizeof(uintptr_t)+sizeof(uintptr_t)); uint16_t fid = flash_read_uint16(base+sizeof(uintptr_t)+sizeof(uintptr_t));
printf("[%x] scan fid %x, len %d\r\n",base,fid,flash_read_uint16(base+sizeof(uintptr_t)+sizeof(uintptr_t)+sizeof(uint16_t))); printf("[%x] scan fid %x, len %d\r\n",(unsigned int)base,fid,flash_read_uint16(base+sizeof(uintptr_t)+sizeof(uintptr_t)+sizeof(uint16_t)));
file_t *file = (file_t *)search_by_fid(fid, NULL, SPECIFY_EF); file_t *file = (file_t *)search_by_fid(fid, NULL, SPECIFY_EF);
if (!file) { if (!file) {
file = file_new(fid); file = file_new(fid);

View File

@@ -20,7 +20,12 @@
#define _FILE_H_ #define _FILE_H_
#include <stdlib.h> #include <stdlib.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#else
#include <stdbool.h>
#include <stdint.h>
#endif
#define FILE_TYPE_UNKNOWN 0x00 #define FILE_TYPE_UNKNOWN 0x00
#define FILE_TYPE_DF 0x04 #define FILE_TYPE_DF 0x04

View File

@@ -19,8 +19,14 @@
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#include "hardware/flash.h" #include "hardware/flash.h"
#else
#define XIP_BASE 0
#define FLASH_SECTOR_SIZE 4096
#define PICO_FLASH_SIZE_BYTES (8*1024*1024)
#endif
#include "hsm.h" #include "hsm.h"
#include "file.h" #include "file.h"

View File

@@ -20,12 +20,22 @@
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#include "hardware/flash.h" #include "hardware/flash.h"
#include "hardware/sync.h" #include "hardware/sync.h"
#include "pico/mutex.h" #include "pico/mutex.h"
#include "pico/sem.h" #include "pico/sem.h"
#include "pico/multicore.h" #include "pico/multicore.h"
#else
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#define FLASH_SECTOR_SIZE 4096
#define PICO_FLASH_SIZE_BYTES (8*1024*1024)
int fd_map = 0;
uint8_t *map = NULL;
#endif
#include "hsm.h" #include "hsm.h"
#include <string.h> #include <string.h>
@@ -41,23 +51,28 @@ typedef struct page_flash {
static page_flash_t flash_pages[TOTAL_FLASH_PAGES]; static page_flash_t flash_pages[TOTAL_FLASH_PAGES];
#ifndef ENABLE_EMULATION
static mutex_t mtx_flash; static mutex_t mtx_flash;
static semaphore_t sem_wait; static semaphore_t sem_wait;
#endif
static bool locked_out = false;
static uint8_t ready_pages = 0; static uint8_t ready_pages = 0;
bool flash_available = false; bool flash_available = false;
static bool locked_out = false;
//this function has to be called from the core 0 //this function has to be called from the core 0
void do_flash() void do_flash()
{ {
#ifndef ENABLE_EMULATION
if (mutex_try_enter(&mtx_flash, NULL) == true) { if (mutex_try_enter(&mtx_flash, NULL) == true) {
#endif
if (locked_out == true && flash_available == true && ready_pages > 0) { if (locked_out == true && flash_available == true && ready_pages > 0) {
//printf(" DO_FLASH AVAILABLE\r\n"); //printf(" DO_FLASH AVAILABLE\r\n");
for (int r = 0; r < TOTAL_FLASH_PAGES; r++) { for (int r = 0; r < TOTAL_FLASH_PAGES; r++) {
if (flash_pages[r].ready == true) { if (flash_pages[r].ready == true) {
#ifndef ENABLE_EMULATION
//printf("WRITTING %X\r\n",flash_pages[r].address-XIP_BASE); //printf("WRITTING %X\r\n",flash_pages[r].address-XIP_BASE);
while (multicore_lockout_start_timeout_us(1000) == false); while (multicore_lockout_start_timeout_us(1000) == false);
//printf("WRITTING %X\r\n",flash_pages[r].address-XIP_BASE); //printf("WRITTING %X\r\n",flash_pages[r].address-XIP_BASE);
@@ -67,53 +82,81 @@ void do_flash()
restore_interrupts (ints); restore_interrupts (ints);
while (multicore_lockout_end_timeout_us(1000) == false); while (multicore_lockout_end_timeout_us(1000) == false);
//printf("WRITEN %X !\r\n",flash_pages[r].address); //printf("WRITEN %X !\r\n",flash_pages[r].address);
#else
memcpy(map + flash_pages[r].address, flash_pages[r].page, FLASH_SECTOR_SIZE);
#endif
flash_pages[r].ready = false; flash_pages[r].ready = false;
ready_pages--; ready_pages--;
} }
else if (flash_pages[r].erase == true) { else if (flash_pages[r].erase == true) {
#ifndef ENABLE_EMULATION
while (multicore_lockout_start_timeout_us(1000) == false); while (multicore_lockout_start_timeout_us(1000) == false);
//printf("WRITTING\r\n"); //printf("WRITTING\r\n");
flash_range_erase(flash_pages[r].address-XIP_BASE, flash_pages[r].page_size ? ((int)(flash_pages[r].page_size/FLASH_SECTOR_SIZE))*FLASH_SECTOR_SIZE : FLASH_SECTOR_SIZE); flash_range_erase(flash_pages[r].address-XIP_BASE, flash_pages[r].page_size ? ((int)(flash_pages[r].page_size/FLASH_SECTOR_SIZE))*FLASH_SECTOR_SIZE : FLASH_SECTOR_SIZE);
while (multicore_lockout_end_timeout_us(1000) == false); while (multicore_lockout_end_timeout_us(1000) == false);
#else
memset(map + flash_pages[r].address, 0, FLASH_SECTOR_SIZE);
#endif
flash_pages[r].erase = false; flash_pages[r].erase = false;
ready_pages--; ready_pages--;
} }
} }
#ifdef ENABLE_EMULATION
msync(map, PICO_FLASH_SIZE_BYTES, MS_SYNC);
#endif
flash_available = false; flash_available = false;
if (ready_pages != 0) { if (ready_pages != 0) {
printf("ERROR: DO FLASH DOES NOT HAVE ZERO PAGES\n"); printf("ERROR: DO FLASH DOES NOT HAVE ZERO PAGES\n");
} }
} }
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
} }
sem_release(&sem_wait); sem_release(&sem_wait);
#endif
} }
//this function has to be called from the core 0 //this function has to be called from the core 0
void low_flash_init() { void low_flash_init() {
memset(flash_pages, 0, sizeof(page_flash_t)*TOTAL_FLASH_PAGES);
#ifndef ENABLE_EMULATION
mutex_init(&mtx_flash); mutex_init(&mtx_flash);
sem_init(&sem_wait, 0, 1); sem_init(&sem_wait, 0, 1);
memset(flash_pages, 0, sizeof(page_flash_t)*TOTAL_FLASH_PAGES); #else
fd_map = open("memory.flash", O_RDWR | O_CREAT, (mode_t)0600);
lseek(fd_map, PICO_FLASH_SIZE_BYTES-1, SEEK_SET);
write(fd_map, "", 1);
map = mmap(0, PICO_FLASH_SIZE_BYTES, PROT_READ | PROT_WRITE, MAP_SHARED, fd_map, 0);
#endif
} }
void low_flash_init_core1() { void low_flash_init_core1() {
#ifndef ENABLE_EMULATION
mutex_enter_blocking(&mtx_flash); mutex_enter_blocking(&mtx_flash);
multicore_lockout_victim_init(); multicore_lockout_victim_init();
#endif
locked_out = true; locked_out = true;
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
} }
void wait_flash_finish() { void wait_flash_finish() {
#ifndef ENABLE_EMULATION
sem_acquire_blocking(&sem_wait); //blocks until released sem_acquire_blocking(&sem_wait); //blocks until released
//wake up //wake up
sem_acquire_blocking(&sem_wait); //decrease permits sem_acquire_blocking(&sem_wait); //decrease permits
#endif
} }
void low_flash_available() { void low_flash_available() {
#ifndef ENABLE_EMULATION
mutex_enter_blocking(&mtx_flash); mutex_enter_blocking(&mtx_flash);
#endif
flash_available = true; flash_available = true;
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
} }
page_flash_t *find_free_page(uintptr_t addr) { page_flash_t *find_free_page(uintptr_t addr) {
@@ -143,21 +186,29 @@ int flash_program_block(uintptr_t addr, const uint8_t *data, size_t len) {
if (!data || len == 0) if (!data || len == 0)
return CCID_ERR_NULL_PARAM; return CCID_ERR_NULL_PARAM;
#ifndef ENABLE_EMULATION
mutex_enter_blocking(&mtx_flash); mutex_enter_blocking(&mtx_flash);
#endif
if (ready_pages == TOTAL_FLASH_PAGES) { if (ready_pages == TOTAL_FLASH_PAGES) {
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
printf("ERROR: ALL FLASH PAGES CACHED\r\n"); printf("ERROR: ALL FLASH PAGES CACHED\r\n");
return CCID_ERR_NO_MEMORY; return CCID_ERR_NO_MEMORY;
} }
if (!(p = find_free_page(addr))) if (!(p = find_free_page(addr)))
{ {
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
printf("ERROR: FLASH CANNOT FIND A PAGE (rare error)\r\n"); printf("ERROR: FLASH CANNOT FIND A PAGE (rare error)\r\n");
return CCID_ERR_MEMORY_FATAL; return CCID_ERR_MEMORY_FATAL;
} }
memcpy(&p->page[addr&(FLASH_SECTOR_SIZE-1)], data, len); memcpy(&p->page[addr&(FLASH_SECTOR_SIZE-1)], data, len);
//printf("Flash: modified page %X with data %x at [%x] (top page %X)\r\n",addr_alg,data,addr&(FLASH_SECTOR_SIZE-1),addr); //printf("Flash: modified page %X with data %x at [%x] (top page %X)\r\n",addr_alg,data,addr&(FLASH_SECTOR_SIZE-1),addr);
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
return CCID_OK; return CCID_OK;
} }
@@ -175,19 +226,25 @@ int flash_program_uintptr (uintptr_t addr, uintptr_t data) {
uint8_t *flash_read(uintptr_t addr) { uint8_t *flash_read(uintptr_t addr) {
uintptr_t addr_alg = addr & -FLASH_SECTOR_SIZE; uintptr_t addr_alg = addr & -FLASH_SECTOR_SIZE;
#ifndef ENABLE_EMULATION
mutex_enter_blocking(&mtx_flash); mutex_enter_blocking(&mtx_flash);
#endif
if (ready_pages > 0) { if (ready_pages > 0) {
for (int r = 0; r < TOTAL_FLASH_PAGES; r++) for (int r = 0; r < TOTAL_FLASH_PAGES; r++)
{ {
if (flash_pages[r].ready && flash_pages[r].address == addr_alg) { if (flash_pages[r].ready && flash_pages[r].address == addr_alg) {
uint8_t *v = &flash_pages[r].page[addr&(FLASH_SECTOR_SIZE-1)]; uint8_t *v = &flash_pages[r].page[addr&(FLASH_SECTOR_SIZE-1)];
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
return v; return v;
} }
} }
} }
uint8_t *v = (uint8_t *)addr; uint8_t *v = (uint8_t *)addr;
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
return v; return v;
} }
@@ -214,21 +271,29 @@ uint8_t flash_read_uint8(uintptr_t addr) {
int flash_erase_page (uintptr_t addr, size_t page_size) { int flash_erase_page (uintptr_t addr, size_t page_size) {
page_flash_t *p = NULL; page_flash_t *p = NULL;
#ifndef ENABLE_EMULATION
mutex_enter_blocking(&mtx_flash); mutex_enter_blocking(&mtx_flash);
#endif
if (ready_pages == TOTAL_FLASH_PAGES) { if (ready_pages == TOTAL_FLASH_PAGES) {
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
printf("ERROR: ALL FLASH PAGES CACHED\r\n"); printf("ERROR: ALL FLASH PAGES CACHED\r\n");
return CCID_ERR_NO_MEMORY; return CCID_ERR_NO_MEMORY;
} }
if (!(p = find_free_page(addr))) { if (!(p = find_free_page(addr))) {
printf("ERROR: FLASH CANNOT FIND A PAGE (rare error)\r\n"); printf("ERROR: FLASH CANNOT FIND A PAGE (rare error)\r\n");
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
return CCID_ERR_MEMORY_FATAL; return CCID_ERR_MEMORY_FATAL;
} }
p->erase = true; p->erase = true;
p->ready = false; p->ready = false;
p->page_size = page_size; p->page_size = page_size;
#ifndef ENABLE_EMULATION
mutex_exit(&mtx_flash); mutex_exit(&mtx_flash);
#endif
return CCID_OK; return CCID_OK;
} }

View File

@@ -19,7 +19,16 @@
#define _HSM_H_ #define _HSM_H_
#include "file.h" #include "file.h"
#ifndef ENABLE_EMULATION
#include "pico/unique_id.h" #include "pico/unique_id.h"
#else
#include <stdint.h>
extern uint32_t board_millis();
#define MIN(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
#endif
#include <string.h> #include <string.h>
extern bool wait_button(); extern bool wait_button();
@@ -32,7 +41,7 @@ static inline const uint16_t make_uint16_t(uint8_t b1, uint8_t b2) {
static inline const uint16_t get_uint16_t(const uint8_t *b, uint16_t offset) { static inline const uint16_t get_uint16_t(const uint8_t *b, uint16_t offset) {
return make_uint16_t(b[offset], b[offset+1]); return make_uint16_t(b[offset], b[offset+1]);
} }
static inline const void put_uint16_t(uint16_t n, uint8_t *b) { static inline void put_uint16_t(uint16_t n, uint8_t *b) {
*b++ = (n >> 8) & 0xff; *b++ = (n >> 8) & 0xff;
*b = n & 0xff; *b = n & 0xff;
} }
@@ -41,7 +50,8 @@ extern int flash_write_data_to_file(file_t *file, const uint8_t *data, uint16_t
extern void low_flash_available(); extern void low_flash_available();
extern int flash_clear_file(file_t *file); extern int flash_clear_file(file_t *file);
extern pico_unique_board_id_t unique_id; extern void timeout_stop();
extern void timeout_start();
enum { enum {
BLINK_NOT_MOUNTED = (250 << 16) | 250, BLINK_NOT_MOUNTED = (250 << 16) | 250,

View File

@@ -18,11 +18,17 @@
#include <stdio.h> #include <stdio.h>
// Pico // Pico
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#else
#include <sys/time.h>
#include "emulation.h"
#endif
// For memcpy // For memcpy
#include <string.h> #include <string.h>
#ifndef ENABLE_EMULATION
// Include descriptor struct definitions // Include descriptor struct definitions
//#include "usb_common.h" //#include "usb_common.h"
// USB register definitions from pico-sdk // USB register definitions from pico-sdk
@@ -35,12 +41,16 @@
#include "hardware/resets.h" #include "hardware/resets.h"
#include "pico/multicore.h" #include "pico/multicore.h"
#endif
#include "random.h" #include "random.h"
#include "hsm.h" #include "hsm.h"
#include "apdu.h" #include "apdu.h"
#ifndef ENABLE_EMULATION
#include "usb.h" #include "usb.h"
#include "hardware/rtc.h" #include "hardware/rtc.h"
#include "bsp/board.h" #include "bsp/board.h"
#endif
extern void do_flash(); extern void do_flash();
extern void low_flash_init(); extern void low_flash_init();
@@ -50,6 +60,8 @@ uint8_t num_apps = 0;
app_t *current_app = NULL; app_t *current_app = NULL;
const uint8_t *ccid_atr = NULL;
int register_app(app_t * (*select_aid)(app_t *, const uint8_t *, uint8_t)) { int register_app(app_t * (*select_aid)(app_t *, const uint8_t *, uint8_t)) {
if (num_apps < sizeof(apps)/sizeof(app_t)) { if (num_apps < sizeof(apps)/sizeof(app_t)) {
apps[num_apps].select_aid = select_aid; apps[num_apps].select_aid = select_aid;
@@ -65,6 +77,15 @@ void led_set_blink(uint32_t mode) {
blink_interval_ms = mode; blink_interval_ms = mode;
} }
uint32_t timeout = 0;
void timeout_stop() {
timeout = 0;
}
void timeout_start() {
timeout = board_millis();
}
void execute_tasks(); void execute_tasks();
static bool req_button_pending = false; static bool req_button_pending = false;
@@ -76,6 +97,14 @@ bool is_req_button_pending() {
uint32_t button_timeout = 15000; uint32_t button_timeout = 15000;
bool cancel_button = false; bool cancel_button = false;
#ifdef ENABLE_EMULATION
uint32_t board_millis() {
struct timeval start;
gettimeofday(&start, NULL);
return (start.tv_sec * 1000 + start.tv_usec/1000);
}
#else
bool wait_button() { bool wait_button() {
uint32_t start_button = board_millis(); uint32_t start_button = board_millis();
bool timeout = false; bool timeout = false;
@@ -104,6 +133,7 @@ bool wait_button() {
req_button_pending = false; req_button_pending = false;
return timeout || cancel_button; return timeout || cancel_button;
} }
#endif
struct apdu apdu; struct apdu apdu;
@@ -142,7 +172,7 @@ void led_off_all() {
} }
void init_rtc() { void init_rtc() {
#ifndef ENABLE_EMULATION
rtc_init(); rtc_init();
datetime_t dt = { datetime_t dt = {
.year = 2020, .year = 2020,
@@ -154,19 +184,22 @@ void init_rtc() {
.sec = 00 .sec = 00
}; };
rtc_set_datetime(&dt); rtc_set_datetime(&dt);
#endif
} }
extern void neug_task(); extern void neug_task();
extern void usb_task();
pico_unique_board_id_t unique_id;
void execute_tasks() { void execute_tasks() {
usb_task(); usb_task();
#ifndef ENABLE_EMULATION
tud_task(); // tinyusb device task tud_task(); // tinyusb device task
#endif
led_blinking_task(); led_blinking_task();
} }
int main(void) { int main(void) {
#ifndef ENABLE_EMULATION
usb_init(); usb_init();
board_init(); board_init();
@@ -191,6 +224,9 @@ int main(void) {
tusb_init(); tusb_init();
//prepare_ccid(); //prepare_ccid();
#else
emul_init("127.0.0.1",35963);
#endif
random_init(); random_init();

View File

@@ -18,28 +18,39 @@
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#include "hwrng.h" #include "hwrng.h"
#include "hardware/structs/rosc.h" #include "hardware/structs/rosc.h"
#include "hardware/gpio.h" #include "hardware/gpio.h"
#include "hardware/adc.h" #include "hardware/adc.h"
#include "pico/unique_id.h" #include "bsp/board.h"
#include "pico/time.h" #include "pico/time.h"
static inline uint32_t board_millis(void) #else
{ #include "mbedtls/entropy.h"
return to_ms_since_boot(get_absolute_time()); #include "mbedtls/ctr_drbg.h"
}
mbedtls_ctr_drbg_context ctr_drbg;
extern uint32_t board_millis();
#endif
void adc_start() { void adc_start() {
#ifndef ENABLE_EMULATION
adc_init(); adc_init();
adc_gpio_init(27); adc_gpio_init(27);
adc_select_input(1); adc_select_input(1);
#endif
} }
void adc_stop() { void adc_stop() {
} }
#ifdef ENABLE_EMULATION
uint32_t adc_read() {
return 0;
}
#endif
static uint64_t random_word = 0xcbf29ce484222325; static uint64_t random_word = 0xcbf29ce484222325;
static uint8_t ep_round = 0; static uint8_t ep_round = 0;
@@ -47,6 +58,12 @@ static uint8_t ep_round = 0;
static void ep_init() { static void ep_init() {
random_word = 0xcbf29ce484222325; random_word = 0xcbf29ce484222325;
ep_round = 0; ep_round = 0;
#ifdef ENABLE_EMULATION
mbedtls_entropy_context entropy;
mbedtls_entropy_init( &entropy );
mbedtls_ctr_drbg_init( &ctr_drbg );
mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *) "RANDOM_GEN", 10 );
#endif
} }
/* Here, we assume a little endian architecture. */ /* Here, we assume a little endian architecture. */
@@ -55,6 +72,7 @@ static int ep_process () {
ep_init(); ep_init();
} }
uint64_t word = 0x0; uint64_t word = 0x0;
#ifndef ENABLE_EMULATION
for (int n = 0; n < 64; n++) { for (int n = 0; n < 64; n++) {
uint8_t bit1, bit2; uint8_t bit1, bit2;
do do
@@ -65,6 +83,9 @@ static int ep_process () {
} while(bit1 == bit2); } while(bit1 == bit2);
word = (word << 1) | bit1; word = (word << 1) | bit1;
} }
#else
mbedtls_ctr_drbg_random( &ctr_drbg, (uint8_t *)&word, sizeof( word ) );
#endif
random_word ^= word^board_millis()^adc_read(); random_word ^= word^board_millis()^adc_read();
random_word *= 0x00000100000001B3; random_word *= 0x00000100000001B3;
if (++ep_round == 8) { if (++ep_round == 8) {
@@ -87,6 +108,8 @@ struct rng_rb {
}; };
static void rb_init(struct rng_rb *rb, uint32_t *p, uint8_t size) { static void rb_init(struct rng_rb *rb, uint32_t *p, uint8_t size) {
#ifdef ENABLE_EMULATION
#endif
rb->buf = p; rb->buf = p;
rb->size = size; rb->size = size;
rb->head = rb->tail = 0; rb->head = rb->tail = 0;
@@ -125,7 +148,6 @@ void *neug_task() {
if ((n = ep_process())) { if ((n = ep_process())) {
int i; int i;
const uint32_t *vp; const uint32_t *vp;
vp = ep_output(); vp = ep_output();
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
@@ -134,13 +156,10 @@ void *neug_task() {
break; break;
} }
} }
return NULL; return NULL;
} }
void neug_init(uint32_t *buf, uint8_t size) { void neug_init(uint32_t *buf, uint8_t size) {
pico_unique_board_id_t unique_id;
pico_get_unique_board_id(&unique_id);
struct rng_rb *rb = &the_ring_buffer; struct rng_rb *rb = &the_ring_buffer;
rb_init(rb, buf, size); rb_init(rb, buf, size);
@@ -170,11 +189,15 @@ uint32_t neug_get() {
void neug_wait_full() { void neug_wait_full() {
struct rng_rb *rb = &the_ring_buffer; struct rng_rb *rb = &the_ring_buffer;
#ifndef ENABLE_EMULATION
uint core = get_core_num(); uint core = get_core_num();
#endif
while (!rb->full) { while (!rb->full) {
#ifndef ENABLE_EMULATION
if (core == 1) if (core == 1)
sleep_ms(1); sleep_ms(1);
else else
#endif
neug_task(); neug_task();
} }
} }

View File

@@ -21,7 +21,9 @@
#define NEUG_PRE_LOOP 32 #define NEUG_PRE_LOOP 32
#include <stdlib.h> #include <stdlib.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#endif
void neug_init(uint32_t *buf, uint8_t size); void neug_init(uint32_t *buf, uint8_t size);
uint32_t neug_get(); uint32_t neug_get();

View File

@@ -19,8 +19,10 @@
#ifndef _RANDOM_H_ #ifndef _RANDOM_H_
#define _RANDOM_H_ #define _RANDOM_H_
#include "stdlib.h" #include <stdlib.h>
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#endif
void random_init (void); void random_init (void);
void random_fini (void); void random_fini (void);

View File

@@ -44,8 +44,6 @@
#include "apdu.h" #include "apdu.h"
#include "usb.h" #include "usb.h"
const uint8_t *ccid_atr = NULL;
#if MAX_RES_APDU_DATA_SIZE > MAX_CMD_APDU_DATA_SIZE #if MAX_RES_APDU_DATA_SIZE > MAX_CMD_APDU_DATA_SIZE
#define USB_BUF_SIZE (MAX_RES_APDU_DATA_SIZE+20+9) #define USB_BUF_SIZE (MAX_RES_APDU_DATA_SIZE+20+9)
#else #else

View File

@@ -0,0 +1,169 @@
/*
* This file is part of the Pico HSM SDK distribution (https://github.com/polhenarejos/pico-hsm-sdk).
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "emulation.h"
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include "hsm.h"
#include "apdu.h"
#include "usb.h"
#include "ccid/ccid.h"
int sock = 0;
int msleep(long msec)
{
struct timespec ts;
int res;
if (msec < 0)
{
errno = EINVAL;
return -1;
}
ts.tv_sec = msec / 1000;
ts.tv_nsec = (msec % 1000) * 1000000;
do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);
return res;
}
int emul_init(char *host, uint16_t port) {
struct sockaddr_in serv_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
// Convert IPv4 and IPv6 addresses from text to binary
// form
if (inet_pton(AF_INET, host, &serv_addr.sin_addr) <= 0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
int x = fcntl(sock ,F_GETFL, 0);
fcntl(sock, F_SETFL, x | O_NONBLOCK);
return 0;
}
uint8_t *driver_prepare_response_emul() {
apdu.rdata = usb_get_tx(ITF_EMUL);
return apdu.rdata;
}
int driver_write_emul(const uint8_t *buffer, size_t buffer_size) {
uint16_t size = htons(buffer_size);
DEBUG_PAYLOAD(buffer,buffer_size);
int ret = 0;
do {
ret = send(sock, &size, sizeof(size), 0);
if (ret < 0)
msleep(10);
} while(ret <= 0);
do {
ret = send(sock, buffer, (uint16_t)buffer_size, 0);
if (ret < 0)
msleep(10);
} while(ret <= 0);
return buffer_size;
}
uint32_t emul_write_offset(uint16_t size, uint16_t offset) {
//DEBUG_PAYLOAD(usb_get_tx(ITF_EMUL)+offset, size);
return usb_write_offset(ITF_EMUL, size, offset);
}
uint32_t emul_write(uint16_t size) {
return emul_write_offset(size, 0);
}
void driver_exec_finished_cont_emul(size_t size_next, size_t offset) {
}
int driver_process_usb_packet_emul(uint16_t len) {
if (len > 0) {
uint8_t *data = usb_get_rx(ITF_EMUL), *rdata = usb_get_tx(ITF_EMUL);
if (len == 1) {
uint8_t c = data[0];
if (c == 4) {
if (ccid_atr)
memcpy(rdata, ccid_atr+1, ccid_atr[0]);
emul_write(ccid_atr ? ccid_atr[0] : 0);
}
}
else {
DEBUG_PAYLOAD(data, len);
apdu_process(ITF_EMUL, data, len);
process_apdu();
apdu_finish();
size_t ret = apdu_next();
emul_write(ret);
}
}
usb_clear_rx(ITF_EMUL);
return 0;
}
uint16_t emul_read() {
uint16_t len = 0;
fd_set input;
FD_ZERO(&input);
FD_SET(sock, &input);
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0 * 1000;
int n = select(sock + 1, &input, NULL, NULL, &timeout);
if (n == -1) {
printf("read wrong\n");
//something wrong
} else if (n == 0) {
printf("read timeout\n");
}
if (FD_ISSET(sock, &input)) {
int valread = recv(sock, &len, sizeof(len), 0);
len = ntohs(len);
if (len > 0) {
while (true) {
valread = recv(sock, usb_get_rx(ITF_EMUL), len, 0);
if (valread > 0)
return valread;
msleep(10);
}
}
}
return 0;
}

View File

@@ -0,0 +1,24 @@
/*
* This file is part of the Pico HSM SDK distribution (https://github.com/polhenarejos/pico-hsm-sdk).
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _EMULATION_H_
#define _EMULATION_H_
#include <stdint.h>
extern int emul_init(char *host, uint16_t port);
#endif // _EMULATION_H_

View File

@@ -25,6 +25,7 @@ typedef unsigned int uint32_t;
typedef unsigned long int uint64_t; typedef unsigned long int uint64_t;
#else #else
#include <stdint.h> #include <stdint.h>
#include <stdlib.h>
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
@@ -58,7 +59,9 @@ typedef struct {
uint8_t data[HID_RPT_SIZE - 5]; // Data payload uint8_t data[HID_RPT_SIZE - 5]; // Data payload
} cont; } cont;
}; };
}__packed CTAPHID_FRAME; } __attribute__ ((__packed__)) CTAPHID_FRAME;
extern CTAPHID_FRAME *ctap_req, *ctap_resp;
#define FRAME_TYPE(f) ((f)->type & TYPE_MASK) #define FRAME_TYPE(f) ((f)->type & TYPE_MASK)
#define FRAME_CMD(f) ((f)->init.cmd & ~TYPE_MASK) #define FRAME_CMD(f) ((f)->init.cmd & ~TYPE_MASK)
@@ -106,7 +109,7 @@ typedef struct {
typedef struct { typedef struct {
uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce
}__packed CTAPHID_INIT_REQ; } __attribute__ ((__packed__)) CTAPHID_INIT_REQ;
typedef struct { typedef struct {
uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce
@@ -116,7 +119,7 @@ typedef struct {
uint8_t versionMinor; // Minor version number uint8_t versionMinor; // Minor version number
uint8_t versionBuild; // Build version number uint8_t versionBuild; // Build version number
uint8_t capFlags; // Capabilities flags uint8_t capFlags; // Capabilities flags
}__packed CTAPHID_INIT_RESP; } __attribute__ ((__packed__)) CTAPHID_INIT_RESP;
// CTAPHID_SYNC command defines // CTAPHID_SYNC command defines

View File

@@ -74,10 +74,12 @@ uint16_t tud_hid_get_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t
(void) report_type; (void) report_type;
(void) buffer; (void) buffer;
(void) reqlen; (void) reqlen;
printf("get_report\n"); printf("get_report %d %d %d\n",itf,report_id,report_type);
DEBUG_PAYLOAD(buffer, reqlen); DEBUG_PAYLOAD(buffer, reqlen);
buffer[1] = HSM_SDK_VERSION_MAJOR;
buffer[2] = HSM_SDK_VERSION_MINOR;
return 0; return reqlen;
} }
uint32_t hid_write_offset(uint16_t size, uint16_t offset) { uint32_t hid_write_offset(uint16_t size, uint16_t offset) {
@@ -189,7 +191,9 @@ void tud_hid_set_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t rep
(void) itf; (void) itf;
(void) report_id; (void) report_id;
(void) report_type; (void) report_type;
printf("set_report %d %d %d\n",itf,report_id,report_type);
if (itf == ITF_KEYBOARD)
DEBUG_PAYLOAD(buffer,bufsize);
usb_rx(itf, buffer, bufsize); usb_rx(itf, buffer, bufsize);
} }
@@ -229,7 +233,6 @@ extern const uint8_t fido_aid[];
int driver_process_usb_packet_hid(uint16_t read) { int driver_process_usb_packet_hid(uint16_t read) {
int apdu_sent = 0; int apdu_sent = 0;
apdu.sw = 0;
if (read >= 5) { if (read >= 5) {
driver_init_hid(); driver_init_hid();
last_packet_time = board_millis(); last_packet_time = board_millis();
@@ -296,7 +299,7 @@ int driver_process_usb_packet_hid(uint16_t read) {
ctap_resp->init.cmd = CTAPHID_INIT; ctap_resp->init.cmd = CTAPHID_INIT;
ctap_resp->init.bcntl = 17; ctap_resp->init.bcntl = 17;
ctap_resp->init.bcnth = 0; ctap_resp->init.bcnth = 0;
driver_exec_finished_hid(17); hid_write(64);
msg_packet.len = msg_packet.current_len = 0; msg_packet.len = msg_packet.current_len = 0;
last_packet_time = 0; last_packet_time = 0;
} }

View File

@@ -16,20 +16,19 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "pico/unique_id.h"
#include <stdio.h> #include <stdio.h>
// Pico // Pico
#ifndef ENABLE_EMULATION
#include "pico/stdlib.h" #include "pico/stdlib.h"
#include "pico/multicore.h" #include "pico/multicore.h"
#include "tusb.h" #include "tusb.h"
#include "bsp/board.h"
#endif
#include "hsm.h" #include "hsm.h"
#include "usb.h" #include "usb.h"
#include "apdu.h" #include "apdu.h"
#include "bsp/board.h"
// For memcpy // For memcpy
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
@@ -46,7 +45,9 @@ void usb_set_timeout_counter(uint8_t itf, uint32_t v) {
} }
uint32_t usb_write_offset(uint8_t itf, uint16_t len, uint16_t offset) { uint32_t usb_write_offset(uint8_t itf, uint16_t len, uint16_t offset) {
#ifndef ENABLE_EMULATION
uint8_t pkt_max = 64; uint8_t pkt_max = 64;
#endif
int w = 0; int w = 0;
if (len > sizeof(tx_buffer[itf])) if (len > sizeof(tx_buffer[itf]))
len = sizeof(tx_buffer[itf]); len = sizeof(tx_buffer[itf]);
@@ -59,6 +60,10 @@ uint32_t usb_write_offset(uint8_t itf, uint16_t len, uint16_t offset) {
#ifdef USB_ITF_CCID #ifdef USB_ITF_CCID
if (itf == ITF_CCID) if (itf == ITF_CCID)
w = driver_write_ccid(tx_buffer[itf]+offset, MIN(len, pkt_max)); w = driver_write_ccid(tx_buffer[itf]+offset, MIN(len, pkt_max));
#endif
#ifdef ENABLE_EMULATION
if (itf == ITF_EMUL)
w = driver_write_emul(tx_buffer[itf]+offset, len);
#endif #endif
w_len[itf] -= w; w_len[itf] -= w;
tx_r_offset[itf] += w; tx_r_offset[itf] += w;
@@ -95,6 +100,10 @@ uint32_t usb_write_flush(uint8_t itf) {
#ifdef USB_ITF_CCID #ifdef USB_ITF_CCID
if (itf == ITF_CCID) if (itf == ITF_CCID)
w = driver_write_ccid(tx_buffer[itf]+tx_r_offset[itf], MIN(w_len[itf], 64)); w = driver_write_ccid(tx_buffer[itf]+tx_r_offset[itf], MIN(w_len[itf], 64));
#endif
#ifdef ENABLE_EMULATION
if (itf == ITF_EMUL)
w = driver_write_emul(tx_buffer[itf]+tx_r_offset[itf], w_len[itf]);
#endif #endif
tx_r_offset[itf] += w; tx_r_offset[itf] += w;
w_len[itf] -= w; w_len[itf] -= w;
@@ -135,20 +144,27 @@ void usb_clear_rx(uint8_t itf) {
#define USB_BCD 0x0200 #define USB_BCD 0x0200
uint32_t timeout = 0; #ifndef ENABLE_EMULATION
queue_t usb_to_card_q; queue_t usb_to_card_q;
queue_t card_to_usb_q; queue_t card_to_usb_q;
#endif
void usb_init() { void usb_init() {
#ifndef ENABLE_EMULATION
queue_init(&card_to_usb_q, sizeof(uint32_t), 64); queue_init(&card_to_usb_q, sizeof(uint32_t), 64);
queue_init(&usb_to_card_q, sizeof(uint32_t), 64); queue_init(&usb_to_card_q, sizeof(uint32_t), 64);
#endif
} }
extern int driver_process_usb_nopacket(); extern int driver_process_usb_nopacket();
extern uint32_t timeout;
static int usb_event_handle(uint8_t itf) { static int usb_event_handle(uint8_t itf) {
#ifndef ENABLE_EMULATION
uint16_t rx_read = usb_read_available(itf); uint16_t rx_read = usb_read_available(itf);
#else
uint16_t rx_read = emul_read();
#endif
int proc_packet = 0; int proc_packet = 0;
#ifdef USB_ITF_HID #ifdef USB_ITF_HID
if (itf == ITF_HID) if (itf == ITF_HID)
@@ -157,11 +173,17 @@ static int usb_event_handle(uint8_t itf) {
#ifdef USB_ITF_CCID #ifdef USB_ITF_CCID
if (itf == ITF_CCID) if (itf == ITF_CCID)
proc_packet = driver_process_usb_packet_ccid(rx_read); proc_packet = driver_process_usb_packet_ccid(rx_read);
#endif
#ifdef ENABLE_EMULATION
if (itf == ITF_EMUL)
proc_packet = driver_process_usb_packet_emul(rx_read);
#endif #endif
if (proc_packet > 0) { if (proc_packet > 0) {
card_locked_itf = itf; card_locked_itf = itf;
#ifndef ENABLE_EMULATION
uint32_t flag = EV_CMD_AVAILABLE; uint32_t flag = EV_CMD_AVAILABLE;
queue_add_blocking(&usb_to_card_q, &flag); queue_add_blocking(&usb_to_card_q, &flag);
#endif
timeout_start(); timeout_start();
} }
else { else {
@@ -179,12 +201,15 @@ static int usb_event_handle(uint8_t itf) {
extern void low_flash_init(); extern void low_flash_init();
void card_init_core1() { void card_init_core1() {
#ifndef ENABLE_EMULATION
low_flash_init_core1(); low_flash_init_core1();
#endif
} }
size_t finished_data_size = 0; size_t finished_data_size = 0;
void card_start(void (*func)(void)) { void card_start(void (*func)(void)) {
#ifndef ENABLE_EMULATION
uint32_t m = 0; uint32_t m = 0;
while (queue_is_empty(&usb_to_card_q) == false) { while (queue_is_empty(&usb_to_card_q) == false) {
if (queue_try_remove(&usb_to_card_q, &m) == false) if (queue_try_remove(&usb_to_card_q, &m) == false)
@@ -197,17 +222,24 @@ void card_start(void (*func)(void)) {
multicore_reset_core1(); multicore_reset_core1();
multicore_launch_core1(func); multicore_launch_core1(func);
led_set_blink(BLINK_MOUNTED); led_set_blink(BLINK_MOUNTED);
#endif
} }
void card_exit() { void card_exit() {
#ifndef ENABLE_EMULATION
uint32_t flag = EV_EXIT; uint32_t flag = EV_EXIT;
queue_try_add(&usb_to_card_q, &flag); queue_try_add(&usb_to_card_q, &flag);
led_set_blink(BLINK_SUSPENDED); led_set_blink(BLINK_SUSPENDED);
#endif
card_locked_itf = ITF_TOTAL; card_locked_itf = ITF_TOTAL;
} }
extern void hid_task(); extern void hid_task();
void usb_task() { void usb_task() {
#ifndef ENABLE_EMULATION
bool mounted = false; bool mounted = false;
#else
bool mounted = true;
#endif
for (uint8_t itf = 0; itf < ITF_TOTAL; itf++) { for (uint8_t itf = 0; itf < ITF_TOTAL; itf++) {
#ifdef USB_ITF_HID #ifdef USB_ITF_HID
if (itf == ITF_HID) if (itf == ITF_HID)
@@ -223,6 +255,7 @@ void usb_task() {
} }
usb_write_flush(itf); usb_write_flush(itf);
#ifndef ENABLE_EMULATION
if (card_locked_itf == itf) { if (card_locked_itf == itf) {
uint32_t m = 0x0; uint32_t m = 0x0;
bool has_m = queue_try_remove(&card_to_usb_q, &m); bool has_m = queue_try_remove(&card_to_usb_q, &m);
@@ -263,18 +296,14 @@ void usb_task() {
} }
} }
} }
#endif
} }
} }
#ifdef USB_ITF_HID
hid_task(); hid_task();
#endif
} }
void timeout_stop() {
timeout = 0;
}
void timeout_start() {
timeout = board_millis();
}
uint8_t *usb_prepare_response(uint8_t itf) { uint8_t *usb_prepare_response(uint8_t itf) {
#ifdef USB_ITF_HID #ifdef USB_ITF_HID
@@ -284,6 +313,10 @@ uint8_t *usb_prepare_response(uint8_t itf) {
#ifdef USB_ITF_CCID #ifdef USB_ITF_CCID
if (itf == ITF_CCID) if (itf == ITF_CCID)
return driver_prepare_response_ccid(); return driver_prepare_response_ccid();
#endif
#ifdef ENABLE_EMULATION
if (itf == ITF_EMUL)
return driver_prepare_response_emul();
#endif #endif
return NULL; return NULL;
} }

View File

@@ -18,7 +18,11 @@
#ifndef _USB_H_ #ifndef _USB_H_
#define _USB_H_ #define _USB_H_
#ifndef ENABLE_EMULATION
#include "pico/util/queue.h" #include "pico/util/queue.h"
#else
#include <stdbool.h>
#endif
/* USB thread */ /* USB thread */
#define EV_CARD_CHANGE 1 #define EV_CARD_CHANGE 1
@@ -38,12 +42,16 @@
enum { enum {
#ifndef ENABLE_EMULATION
#ifdef USB_ITF_HID #ifdef USB_ITF_HID
ITF_HID = 0, ITF_HID = 0,
ITF_KEYBOARD, ITF_KEYBOARD,
#endif #endif
#ifdef USB_ITF_CCID #ifdef USB_ITF_CCID
ITF_CCID, ITF_CCID,
#endif
#else
ITF_EMUL = 0,
#endif #endif
ITF_TOTAL ITF_TOTAL
}; };
@@ -55,8 +63,10 @@ enum
}; };
extern void usb_task(); extern void usb_task();
#ifndef ENABLE_EMULATION
extern queue_t usb_to_card_q; extern queue_t usb_to_card_q;
extern queue_t card_to_usb_q; extern queue_t card_to_usb_q;
#endif
extern uint8_t card_locked_itf; extern uint8_t card_locked_itf;
#ifdef USB_ITF_HID #ifdef USB_ITF_HID
@@ -83,14 +93,25 @@ extern size_t driver_read_ccid(uint8_t *, size_t);
extern int driver_process_usb_nopacket_ccid(); extern int driver_process_usb_nopacket_ccid();
#endif #endif
#ifdef ENABLE_EMULATION
extern int driver_process_usb_packet_emul(uint16_t rx_read);
extern void driver_exec_finished_emul(size_t size_next);
extern void driver_exec_finished_cont_emul(size_t size_next, size_t offset);
extern void driver_exec_timeout_emul();
extern bool driver_mounted_emul();
extern uint8_t *driver_prepare_response_emul();
extern int driver_write_emul(const uint8_t *, size_t);
extern size_t driver_read_emul(uint8_t *, size_t);
extern int driver_process_usb_nopacket_emul();
extern uint16_t emul_read();
#endif
extern size_t usb_rx(uint8_t itf, const uint8_t *buffer, size_t len); extern size_t usb_rx(uint8_t itf, const uint8_t *buffer, size_t len);
extern void card_start(void (*func)(void)); extern void card_start(void (*func)(void));
extern void card_exit(); extern void card_exit();
extern void usb_init(); extern void usb_init();
extern uint8_t *usb_prepare_response(uint8_t itf); extern uint8_t *usb_prepare_response(uint8_t itf);
extern void timeout_stop();
extern void timeout_start();
extern uint8_t *usb_get_rx(uint8_t itf); extern uint8_t *usb_get_rx(uint8_t itf);
extern uint8_t *usb_get_tx(uint8_t itf); extern uint8_t *usb_get_tx(uint8_t itf);
extern uint32_t usb_write_offset(uint8_t itf, uint16_t len, uint16_t offset); extern uint32_t usb_write_offset(uint8_t itf, uint16_t len, uint16_t offset);