From c6ba90ba1ca606b63373caaba16cb4fcc65d00f9 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 9 Jan 2017 18:30:29 +0100 Subject: Remove unused inttypes Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 2 +- include/CommandFailedException.h | 2 +- include/command_id.h | 2 +- include/device.h | 2 +- include/device_proto.h | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index ddec600..c49a449 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -84,7 +84,7 @@ namespace nitrokey{ shared_ptr NitrokeyManager::instance() { if (_instance == nullptr){ - _instance = shared_ptr(new NitrokeyManager()); + _instance = make_shared(); } return _instance; } diff --git a/include/CommandFailedException.h b/include/CommandFailedException.h index 9b0c59e..8bcdcae 100644 --- a/include/CommandFailedException.h +++ b/include/CommandFailedException.h @@ -7,7 +7,7 @@ #include #include -#include +#include "log.h" class CommandFailedException : public std::exception { public: diff --git a/include/command_id.h b/include/command_id.h index 346b750..9d12f93 100644 --- a/include/command_id.h +++ b/include/command_id.h @@ -1,6 +1,6 @@ #ifndef COMMAND_ID_H #define COMMAND_ID_H -#include "inttypes.h" +#include namespace nitrokey { namespace proto { diff --git a/include/device.h b/include/device.h index 62c4073..f686fbd 100644 --- a/include/device.h +++ b/include/device.h @@ -2,7 +2,7 @@ #define DEVICE_H #include #include -#include "inttypes.h" +#include #define HID_REPORT_SIZE 65 diff --git a/include/device_proto.h b/include/device_proto.h index 0953566..667b8db 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -8,7 +8,7 @@ #include #include // a local version for compatibility with Windows -#include "inttypes.h" +#include #include "cxx_semantics.h" #include "device.h" #include "misc.h" -- cgit v1.2.3 From 0c6f3234acea5888dd6c3c3aeee8cebcce59ba06 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 15:57:45 +0100 Subject: Use stdint instead of inttypes Signed-off-by: Szczepan Zalega --- include/stick10_commands.h | 2 +- include/stick10_commands_0.8.h | 2 +- include/stick20_commands.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/include/stick10_commands.h b/include/stick10_commands.h index f02fd70..9b72e92 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -4,7 +4,7 @@ #include #include #include -#include "inttypes.h" +#include #include "command.h" #include "device_proto.h" diff --git a/include/stick10_commands_0.8.h b/include/stick10_commands_0.8.h index 9594d1e..ead5add 100644 --- a/include/stick10_commands_0.8.h +++ b/include/stick10_commands_0.8.h @@ -9,7 +9,7 @@ #include #include #include -#include "inttypes.h" +#include #include "command.h" #include "device_proto.h" #include "stick10_commands.h" diff --git a/include/stick20_commands.h b/include/stick20_commands.h index e6df770..386cbda 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -1,7 +1,7 @@ #ifndef STICK20_COMMANDS_H #define STICK20_COMMANDS_H -#include "inttypes.h" +#include #include "command.h" #include #include -- cgit v1.2.3 From c2d3de8820cc2ad3f394b6672853af257d32e6f6 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 16:04:52 +0100 Subject: Helper functions for getting device state get status for Pro and Storage check is device connected use make_shared for keeping instance reference fixed accessing active volume flag Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 2 +- NitrokeyManager.cc | 22 ++++++++++++++++++++-- include/NitrokeyManager.h | 11 +++++++---- include/stick20_commands.h | 9 ++++++++- 4 files changed, 36 insertions(+), 8 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index e513a3b..224a3a8 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -168,7 +168,7 @@ void clear_string(std::string &s){ extern const char * NK_status() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ - string && s = m->get_status(); + string && s = m->get_status_as_string(); char * rs = strdup(s.c_str()); clear_string(s); return rs; diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index c49a449..f71c362 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -90,7 +90,7 @@ namespace nitrokey{ } bool NitrokeyManager::disconnect() { - if (device == nullptr){ + if (!is_connected()){ return false; } const auto res = device->disconnect(); @@ -98,6 +98,10 @@ namespace nitrokey{ return res; } + bool NitrokeyManager::is_connected(){ + return device != nullptr; + } + void NitrokeyManager::set_debug(bool state) { if (state){ Log::instance().set_loglevel(Loglevel::DEBUG); @@ -111,7 +115,12 @@ namespace nitrokey{ return response.data().get_card_serial_hex(); } - string NitrokeyManager::get_status() { + stick10::GetStatus::ResponsePayload NitrokeyManager::get_status(){ + auto response = GetStatus::CommandTransaction::run(*device); + return response.data(); + } + + string NitrokeyManager::get_status_as_string() { auto response = GetStatus::CommandTransaction::run(*device); return response.data().dissect(); } @@ -597,6 +606,10 @@ namespace nitrokey{ return get_major_firmware_version() <= m[device->get_device_model()]; } + DeviceModel NitrokeyManager::get_connected_device_model(){ + return device->get_device_model(); + } + int NitrokeyManager::get_major_firmware_version(){ switch(device->get_device_model()){ case DeviceModel::PRO:{ @@ -682,6 +695,11 @@ namespace nitrokey{ return strdup(p.data().dissect().c_str()); } + stick20::DeviceConfigurationResponsePacket::ResponsePayload NitrokeyManager::get_status_storage(){ + auto p = stick20::GetDeviceStatus::CommandTransaction::run(*device); + return p.data(); + } + const char * NitrokeyManager::get_SD_usage_data_as_string(){ auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(*device); return strdup(p.data().dissect().c_str()); diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index fd39445..d6b70a4 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -39,8 +39,11 @@ namespace nitrokey { bool connect(const char *device_model); bool connect(); bool disconnect(); - void set_debug(bool state); - string get_status(); + bool is_connected(); + DeviceModel get_connected_device_model(); + void set_debug(bool state); + stick10::GetStatus::ResponsePayload get_status(); + string get_status_as_string(); string get_serial_number(); const char * get_totp_slot_name(uint8_t slot_number); @@ -105,6 +108,7 @@ namespace nitrokey { void send_startup(uint64_t seconds_from_epoch); const char * get_status_storage_as_string(); + stick20::DeviceConfigurationResponsePacket::ResponsePayload get_status_storage(); const char *get_SD_usage_data_as_string(); @@ -117,11 +121,10 @@ namespace nitrokey { void authorize_packet(T &package, const char *admin_temporary_password, shared_ptr device); int get_major_firmware_version(); + explicit NitrokeyManager(); private: - NitrokeyManager(); static shared_ptr _instance; - bool connected; std::shared_ptr device; bool is_valid_hotp_slot_number(uint8_t slot_number) const; diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 386cbda..8080117 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -141,7 +141,14 @@ namespace nitrokey { uint8_t NewSDCardFound_u8; uint8_t SDFillWithRandomChars_u8; uint32_t ActiveSD_CardID_u32; - uint8_t VolumeActiceFlag_u8; + union{ + uint8_t VolumeActiceFlag_u8; + struct { + bool unencrypted :1; + bool encrypted :1; + bool hidden :1; + } __packed VolumeActiceFlag_st; + } __packed; uint8_t NewSmartCardFound_u8; uint8_t UserPwRetryCount; uint8_t AdminPwRetryCount; -- cgit v1.2.3 From 774f3a0d93bac42aa50d4d30753e00f769b17881 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 16:09:08 +0100 Subject: Make device configuration const, protect non-const with ::atomic Signed-off-by: Szczepan Zalega --- device.cc | 49 +++++++++++++++++++++++-------------------------- include/device.h | 42 +++++++++++++++++++++++++----------------- 2 files changed, 48 insertions(+), 43 deletions(-) diff --git a/device.cc b/device.cc index 8c3c799..6eaaca5 100644 --- a/device.cc +++ b/device.cc @@ -9,20 +9,26 @@ using namespace nitrokey::device; using namespace nitrokey::log; +using namespace std::chrono; -Device::Device() - : m_vid(0), - m_pid(0), +Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, + const milliseconds send_receive_delay, const int retry_receiving_count, + const milliseconds retry_timeout) + : m_vid(vid), + m_pid(pid), m_retry_sending_count(3), - m_retry_receiving_count(40), - m_retry_timeout(100), + m_retry_receiving_count(retry_receiving_count), + m_retry_timeout(retry_timeout), mp_devhandle(NULL), - last_command_status(0){} + last_command_status(0), + m_model(model), + m_send_receive_delay(send_receive_delay) +{} bool Device::disconnect() { Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); - if(mp_devhandle== nullptr) return false; + if(mp_devhandle == nullptr) return false; hid_close(mp_devhandle); mp_devhandle = NULL; hid_exit(); @@ -31,9 +37,8 @@ bool Device::disconnect() { bool Device::connect() { Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); -// hid_init(); +// hid_init(); // done automatically on hid_open mp_devhandle = hid_open(m_vid, m_pid, NULL); - // hid_init(); return mp_devhandle != NULL; } @@ -41,7 +46,7 @@ int Device::send(const void *packet) { Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); if (mp_devhandle == NULL) - throw std::runtime_error("Attempted HID send on an invalid descriptor."); + throw std::runtime_error("Attempted HID send on an invalid descriptor."); //TODO migrate except to library_error return (hid_send_feature_report( mp_devhandle, (const unsigned char *)(packet), HID_REPORT_SIZE)); @@ -54,7 +59,7 @@ int Device::recv(void *packet) { Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); if (mp_devhandle == NULL) - throw std::runtime_error("Attempted HID receive on an invalid descriptor."); + throw std::runtime_error("Attempted HID receive on an invalid descriptor."); //TODO migrate except to library_error // FIXME extract error handling and repeating to parent function in // device_proto:192 @@ -84,19 +89,11 @@ int Device::recv(void *packet) { return status; } -Stick10::Stick10() { - m_vid = 0x20a0; - m_pid = 0x4108; - m_model = DeviceModel::PRO; - m_send_receive_delay = 100ms; - m_retry_receiving_count = 100; -} +Stick10::Stick10(): + Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 100, 100ms) + {} -Stick20::Stick20() { - m_vid = 0x20a0; - m_pid = 0x4109; - m_retry_timeout = 200ms; - m_model = DeviceModel::STORAGE; - m_send_receive_delay = 200ms; - m_retry_receiving_count = 40; -} + +Stick20::Stick20(): + Device(0x20a0, 0x4109, DeviceModel::STORAGE, 200ms, 40, 200ms) + {} diff --git a/include/device.h b/include/device.h index f686fbd..938fc75 100644 --- a/include/device.h +++ b/include/device.h @@ -8,9 +8,12 @@ // TODO !! SEMAPHORE +#include + namespace nitrokey { namespace device { using namespace std::chrono_literals; + using std::chrono::milliseconds; struct EnumClassHash { @@ -22,6 +25,7 @@ namespace device { }; enum class DeviceModel{ + UNKNOWN, PRO, STORAGE }; @@ -29,8 +33,11 @@ enum class DeviceModel{ class Device { public: - Device(); - virtual ~Device(){disconnect();} + Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, + const milliseconds send_receive_delay, const int retry_receiving_count, + const milliseconds retry_timeout); + + virtual ~Device(){disconnect();} // lack of device is not actually an error, // so it doesn't throw @@ -51,31 +58,32 @@ public: int get_retry_receiving_count() const { return m_retry_receiving_count; }; int get_retry_sending_count() const { return m_retry_sending_count; }; std::chrono::milliseconds get_retry_timeout() const { return m_retry_timeout; }; - std::chrono::milliseconds get_send_receive_delay() const {return m_send_receive_delay;} + std::chrono::milliseconds get_send_receive_delay() const {return m_send_receive_delay;} - int get_last_command_status() {auto a = last_command_status; last_command_status = 0; return a;}; - void set_last_command_status(uint8_t _err) { last_command_status = _err;} ; - bool last_command_sucessfull() const {return last_command_status == 0;}; - DeviceModel get_device_model() const {return m_model;} + int get_last_command_status() {int a = last_command_status; last_command_status = 0; return a;}; + void set_last_command_status(uint8_t _err) { last_command_status = _err;} ; + bool last_command_sucessfull() const {return last_command_status == 0;}; + DeviceModel get_device_model() const {return m_model;} private: - uint8_t last_command_status; + std::atomic last_command_status; - protected: - uint16_t m_vid; - uint16_t m_pid; - DeviceModel m_model; +protected: + const uint16_t m_vid; + const uint16_t m_pid; + const DeviceModel m_model; /* * While the project uses Signal11 portable HIDAPI * library, there's no way of doing it asynchronously, * hence polling. */ - int m_retry_sending_count; - int m_retry_receiving_count; - std::chrono::milliseconds m_retry_timeout; - std::chrono::milliseconds m_send_receive_delay; + const int m_retry_sending_count; + const int m_retry_receiving_count; + const std::chrono::milliseconds m_retry_timeout; + const std::chrono::milliseconds m_send_receive_delay; + + std::atomicmp_devhandle; - hid_device *mp_devhandle; }; class Stick10 : public Device { -- cgit v1.2.3 From 2dec896b3f853d2e509c4eb15fe5dd6c28e0a1d7 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 16:10:30 +0100 Subject: Use lock_guard while accessing hid_api Signed-off-by: Szczepan Zalega --- device.cc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/device.cc b/device.cc index 6eaaca5..7bdbe9a 100644 --- a/device.cc +++ b/device.cc @@ -6,6 +6,9 @@ #include "include/misc.h" #include "include/device.h" #include "include/log.h" +#include + +std::mutex mex_dev_com; using namespace nitrokey::device; using namespace nitrokey::log; @@ -26,6 +29,7 @@ Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, {} bool Device::disconnect() { + std::lock_guard lock(mex_dev_com); Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); if(mp_devhandle == nullptr) return false; @@ -35,6 +39,7 @@ bool Device::disconnect() { return true; } bool Device::connect() { + std::lock_guard lock(mex_dev_com); Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); // hid_init(); // done automatically on hid_open @@ -43,6 +48,7 @@ bool Device::connect() { } int Device::send(const void *packet) { + std::lock_guard lock(mex_dev_com); Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); if (mp_devhandle == NULL) @@ -53,6 +59,7 @@ int Device::send(const void *packet) { } int Device::recv(void *packet) { + std::lock_guard lock(mex_dev_com); int status; int retry_count = 0; -- cgit v1.2.3 From 55745fccf0c4233c536d8bacead3443a8e431b8d Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 16:40:05 +0100 Subject: Use nullptr instead of NULL Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 3 ++- device.cc | 14 +++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index f71c362..73a704a 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -49,7 +49,8 @@ namespace nitrokey{ shared_ptr NitrokeyManager::_instance = nullptr; - NitrokeyManager::NitrokeyManager() { + NitrokeyManager::NitrokeyManager() : device(nullptr) + { set_debug(true); } NitrokeyManager::~NitrokeyManager() { diff --git a/device.cc b/device.cc index 7bdbe9a..6ff370f 100644 --- a/device.cc +++ b/device.cc @@ -22,7 +22,7 @@ Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, m_retry_sending_count(3), m_retry_receiving_count(retry_receiving_count), m_retry_timeout(retry_timeout), - mp_devhandle(NULL), + mp_devhandle(nullptr), last_command_status(0), m_model(model), m_send_receive_delay(send_receive_delay) @@ -34,7 +34,7 @@ bool Device::disconnect() { if(mp_devhandle == nullptr) return false; hid_close(mp_devhandle); - mp_devhandle = NULL; + mp_devhandle = nullptr; hid_exit(); return true; } @@ -43,15 +43,15 @@ bool Device::connect() { Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); // hid_init(); // done automatically on hid_open - mp_devhandle = hid_open(m_vid, m_pid, NULL); - return mp_devhandle != NULL; + mp_devhandle = hid_open(m_vid, m_pid, nullptr); + return mp_devhandle != nullptr; } int Device::send(const void *packet) { std::lock_guard lock(mex_dev_com); Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); - if (mp_devhandle == NULL) + if (mp_devhandle == nullptr) throw std::runtime_error("Attempted HID send on an invalid descriptor."); //TODO migrate except to library_error return (hid_send_feature_report( @@ -65,7 +65,7 @@ int Device::recv(void *packet) { Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); - if (mp_devhandle == NULL) + if (mp_devhandle == nullptr) throw std::runtime_error("Attempted HID receive on an invalid descriptor."); //TODO migrate except to library_error // FIXME extract error handling and repeating to parent function in @@ -76,7 +76,7 @@ int Device::recv(void *packet) { // FIXME handle getting libhid error message somewhere else auto pwherr = hid_error(mp_devhandle); - std::wstring wherr = (pwherr != NULL) ? pwherr : L"No error message"; + std::wstring wherr = (pwherr != nullptr) ? pwherr : L"No error message"; std::string herr(wherr.begin(), wherr.end()); Log::instance()(std::string("libhid error message: ") + herr, Loglevel::DEBUG_L2); -- cgit v1.2.3 From fc986f87fd256e2cfdd5edcc5b0cf14faf694441 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 16:52:33 +0100 Subject: Use atomic_exchange for atomic operations Signed-off-by: Szczepan Zalega --- include/device.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/include/device.h b/include/device.h index 938fc75..42865ee 100644 --- a/include/device.h +++ b/include/device.h @@ -6,8 +6,6 @@ #define HID_REPORT_SIZE 65 -// TODO !! SEMAPHORE - #include namespace nitrokey { @@ -60,7 +58,7 @@ public: std::chrono::milliseconds get_retry_timeout() const { return m_retry_timeout; }; std::chrono::milliseconds get_send_receive_delay() const {return m_send_receive_delay;} - int get_last_command_status() {int a = last_command_status; last_command_status = 0; return a;}; + int get_last_command_status() {int a = std::atomic_exchange(&last_command_status, static_cast(0)); return a;}; void set_last_command_status(uint8_t _err) { last_command_status = _err;} ; bool last_command_sucessfull() const {return last_command_status == 0;}; DeviceModel get_device_model() const {return m_model;} -- cgit v1.2.3 From 02189413ce463116694478fcdcb418fed7e42027 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 20:09:53 +0100 Subject: Remove UNKNOWN type of the device Signed-off-by: Szczepan Zalega --- include/device.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/device.h b/include/device.h index 42865ee..4001d45 100644 --- a/include/device.h +++ b/include/device.h @@ -23,7 +23,6 @@ namespace device { }; enum class DeviceModel{ - UNKNOWN, PRO, STORAGE }; -- cgit v1.2.3 From 73eac5050abad1b8f0ddbc7e94a11170a640e130 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 11 Jan 2017 20:11:01 +0100 Subject: Protect concurrent use with lock guard Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 11 ++++++++++- include/NitrokeyManager.h | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 73a704a..b270eb3 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -6,9 +6,13 @@ #include #include #include "include/misc.h" +#include namespace nitrokey{ + std::mutex mex_dev_com; + + template void strcpyT(T& dest, const char* src){ @@ -58,6 +62,7 @@ namespace nitrokey{ bool NitrokeyManager::connect() { this->disconnect(); + std::lock_guard lock(mex_dev_com); vector< shared_ptr > devices = { make_shared(), make_shared() }; for( auto & d : devices ){ if (d->connect()){ @@ -70,6 +75,7 @@ namespace nitrokey{ bool NitrokeyManager::connect(const char *device_model) { this->disconnect(); + std::lock_guard lock(mex_dev_com); switch (device_model[0]){ case 'P': device = make_shared(); @@ -90,7 +96,10 @@ namespace nitrokey{ return _instance; } + + bool NitrokeyManager::disconnect() { + std::lock_guard lock(mex_dev_com); if (!is_connected()){ return false; } @@ -99,7 +108,7 @@ namespace nitrokey{ return res; } - bool NitrokeyManager::is_connected(){ + bool NitrokeyManager::is_connected() const throw(){ return device != nullptr; } diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index d6b70a4..6551c1a 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -39,7 +39,7 @@ namespace nitrokey { bool connect(const char *device_model); bool connect(); bool disconnect(); - bool is_connected(); + bool is_connected() const throw() ; DeviceModel get_connected_device_model(); void set_debug(bool state); stick10::GetStatus::ResponsePayload get_status(); -- cgit v1.2.3 From 90e626b52c75e9e117494f15f57177aaf912468c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 10:43:15 +0100 Subject: Add lock_guard for complete send-receive cycle Signed-off-by: Szczepan Zalega --- include/device_proto.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/include/device_proto.h b/include/device_proto.h index 667b8db..31bfe11 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -32,6 +32,8 @@ #define PWS_SEND_TAB 2 #define PWS_SEND_CR 3 +#include + namespace nitrokey { namespace proto { /* @@ -204,13 +206,15 @@ namespace nitrokey { bzero(&st, sizeof(st)); } - static ClearingProxy run(device::Device &dev, const command_payload &payload) { using namespace ::nitrokey::device; using namespace ::nitrokey::log; using namespace std::chrono_literals; + static std::mutex send_receive_mtx; + std::lock_guard guard(send_receive_mtx); + Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); int status; -- cgit v1.2.3 From 8f2e6ad0673e2fe2e3407c895eecbd478885f2c5 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 10:48:18 +0100 Subject: Do not call disconnect on connect device will be disconnected automatically in its destructor Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 2 -- 1 file changed, 2 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index b270eb3..833e916 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -61,7 +61,6 @@ namespace nitrokey{ } bool NitrokeyManager::connect() { - this->disconnect(); std::lock_guard lock(mex_dev_com); vector< shared_ptr > devices = { make_shared(), make_shared() }; for( auto & d : devices ){ @@ -74,7 +73,6 @@ namespace nitrokey{ bool NitrokeyManager::connect(const char *device_model) { - this->disconnect(); std::lock_guard lock(mex_dev_com); switch (device_model[0]){ case 'P': -- cgit v1.2.3 From 5558c22eefb35dabb341b568b3f233fca51ff056 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 10:50:20 +0100 Subject: More debug log info during dev connection Signed-off-by: Szczepan Zalega --- device.cc | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/device.cc b/device.cc index 6ff370f..e6fe98e 100644 --- a/device.cc +++ b/device.cc @@ -29,27 +29,36 @@ Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, {} bool Device::disconnect() { - std::lock_guard lock(mex_dev_com); + //called in object's destructor Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + std::lock_guard lock(mex_dev_com); + Log::instance()(std::string(__FUNCTION__) + std::string(m_model==DeviceModel::PRO?"PRO":"STORAGE"), Loglevel::DEBUG_L2); + Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); + Log::instance()(std::string("Disconnection success: ") + std::to_string(mp_devhandle == nullptr), Loglevel::DEBUG_L2); if(mp_devhandle == nullptr) return false; + hid_close(mp_devhandle); mp_devhandle = nullptr; hid_exit(); return true; } bool Device::connect() { - std::lock_guard lock(mex_dev_com); Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + std::lock_guard lock(mex_dev_com); + Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); // hid_init(); // done automatically on hid_open mp_devhandle = hid_open(m_vid, m_pid, nullptr); - return mp_devhandle != nullptr; + const auto success = mp_devhandle != nullptr; + Log::instance()(std::string("Connection success: ") + std::to_string(success), Loglevel::DEBUG_L2); + return success; } int Device::send(const void *packet) { - std::lock_guard lock(mex_dev_com); Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + std::lock_guard lock(mex_dev_com); + Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); if (mp_devhandle == nullptr) throw std::runtime_error("Attempted HID send on an invalid descriptor."); //TODO migrate except to library_error @@ -59,11 +68,12 @@ int Device::send(const void *packet) { } int Device::recv(void *packet) { + Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); + Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); int status; int retry_count = 0; - Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); if (mp_devhandle == nullptr) throw std::runtime_error("Attempted HID receive on an invalid descriptor."); //TODO migrate except to library_error -- cgit v1.2.3 From daf51e7e6a6f6569472f2a5fae5a376f105f858a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 10:51:14 +0100 Subject: Add const qualifier to functions Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 3 ++- include/NitrokeyManager.h | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 833e916..1753a73 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -614,7 +614,8 @@ namespace nitrokey{ return get_major_firmware_version() <= m[device->get_device_model()]; } - DeviceModel NitrokeyManager::get_connected_device_model(){ + DeviceModel NitrokeyManager::get_connected_device_model() const{ + //FIXME throw if no device is connected or return unknown/unconnected value return device->get_device_model(); } diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 6551c1a..e96ac22 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -40,7 +40,7 @@ namespace nitrokey { bool connect(); bool disconnect(); bool is_connected() const throw() ; - DeviceModel get_connected_device_model(); + DeviceModel get_connected_device_model() const; void set_debug(bool state); stick10::GetStatus::ResponsePayload get_status(); string get_status_as_string(); -- cgit v1.2.3 From 87252d46294515cc5fcf49eb08c8b1c19b49d27a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 10:51:32 +0100 Subject: Comments - fixme Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 1753a73..f92f5f7 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -88,6 +88,7 @@ namespace nitrokey{ } shared_ptr NitrokeyManager::instance() { + //FIXME check thread safety - add atomic for instance, add lock guard if (_instance == nullptr){ _instance = make_shared(); } -- cgit v1.2.3 From deed3e733e7158859fd48ef51b64d924ea4e8184 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 12:04:52 +0100 Subject: Decrease retry count to 20 Update log message to be more readable Signed-off-by: Szczepan Zalega --- device.cc | 2 +- include/device_proto.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/device.cc b/device.cc index e6fe98e..532ba2e 100644 --- a/device.cc +++ b/device.cc @@ -107,7 +107,7 @@ int Device::recv(void *packet) { } Stick10::Stick10(): - Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 100, 100ms) + Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 20, 100ms) {} diff --git a/include/device_proto.h b/include/device_proto.h index 31bfe11..2105f30 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -296,7 +296,7 @@ namespace nitrokey { successful_communication = true; break; } - Log::instance()(std::string("Retry status - dev status, equal crc, correct CRC: ") + Log::instance()(std::string("Retry status - dev status, awaited cmd crc, correct packet CRC: ") + std::to_string(resp.device_status) + " " + std::to_string(resp.last_command_crc == outp.crc) + " " + std::to_string(resp.isCRCcorrect()), Loglevel::DEBUG_L2); -- cgit v1.2.3 From ffcb53e4cb3419ea31bf7b22e5f0c42fd54041da Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 12:11:18 +0100 Subject: Name fix for firmware version getter Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 2 +- NitrokeyManager.cc | 4 ++-- include/NitrokeyManager.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index 224a3a8..f396fcb 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -474,7 +474,7 @@ extern int NK_get_progress_bar_value() { extern int NK_get_major_firmware_version(){ auto m = NitrokeyManager::instance(); return get_with_result([&](){ - return m->get_major_firmware_version(); + return m->get_minor_firmware_version(); }); } diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index f92f5f7..37e35e5 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -612,7 +612,7 @@ namespace nitrokey{ {DeviceModel::PRO, 7}, {DeviceModel::STORAGE, 43}, }); - return get_major_firmware_version() <= m[device->get_device_model()]; + return get_minor_firmware_version() <= m[device->get_device_model()]; } DeviceModel NitrokeyManager::get_connected_device_model() const{ @@ -620,7 +620,7 @@ namespace nitrokey{ return device->get_device_model(); } - int NitrokeyManager::get_major_firmware_version(){ + int NitrokeyManager::get_minor_firmware_version(){ switch(device->get_device_model()){ case DeviceModel::PRO:{ auto status_p = GetStatus::CommandTransaction::run(*device); diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index e96ac22..c7d7704 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -119,7 +119,7 @@ namespace nitrokey { template void authorize_packet(T &package, const char *admin_temporary_password, shared_ptr device); - int get_major_firmware_version(); + int get_minor_firmware_version(); explicit NitrokeyManager(); private: -- cgit v1.2.3 From 185b318b9134da163bbfb160d2d737c835927f30 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 13 Jan 2017 12:55:08 +0100 Subject: Fix firmware version in device status Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 2 +- include/stick20_commands.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 37e35e5..d85af91 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -628,7 +628,7 @@ namespace nitrokey{ } case DeviceModel::STORAGE:{ auto status = stick20::GetDeviceStatus::CommandTransaction::run(*device); - return status.data().versionInfo.major; + return status.data().versionInfo.minor; } } return 0; diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 8080117..fd72f1e 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -130,9 +130,9 @@ namespace nitrokey { uint8_t VersionInfo_au8[4]; struct { uint8_t __unused; - uint8_t major; - uint8_t __unused2; uint8_t minor; + uint8_t __unused2; + uint8_t major; } __packed versionInfo; }; -- cgit v1.2.3 From c551b27792774b87a1be7fd0dcfd9e209eaef5ec Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 14 Jan 2017 13:37:29 +0100 Subject: Method to get commands failure cause Signed-off-by: Szczepan Zalega --- include/CommandFailedException.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/include/CommandFailedException.h b/include/CommandFailedException.h index 8bcdcae..3753ad4 100644 --- a/include/CommandFailedException.h +++ b/include/CommandFailedException.h @@ -11,8 +11,8 @@ class CommandFailedException : public std::exception { public: - uint8_t last_command_code; - uint8_t last_command_status; + const uint8_t last_command_code; + const uint8_t last_command_status; CommandFailedException(uint8_t last_command_code, uint8_t last_command_status) : last_command_code(last_command_code), @@ -24,6 +24,10 @@ public: return "Command execution has failed on device"; } + bool reason_slot_not_programmed() const throw(){ + return last_command_status == 3; //FIXME use enum status codes + } + }; -- cgit v1.2.3 From 56bd3e2c4353cfc1b902c6dfb55df0ef563c5372 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 17 Jan 2017 15:35:44 +0100 Subject: Check command's fail reason within exception Signed-off-by: Szczepan Zalega --- include/CommandFailedException.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/include/CommandFailedException.h b/include/CommandFailedException.h index 3753ad4..190eabc 100644 --- a/include/CommandFailedException.h +++ b/include/CommandFailedException.h @@ -8,6 +8,9 @@ #include #include #include "log.h" +#include "command_id.h" + +using cs = nitrokey::proto::stick10::command_status; class CommandFailedException : public std::exception { public: @@ -25,7 +28,11 @@ public: } bool reason_slot_not_programmed() const throw(){ - return last_command_status == 3; //FIXME use enum status codes + return last_command_status == static_cast(cs::slot_not_programmed); + } + + bool reason_wrong_password() const throw(){ + return last_command_status == static_cast(cs::wrong_password); } }; -- cgit v1.2.3 From 3d54b4ea0c96a2420973dc840c1b32545bf2b05d Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 18 Jan 2017 00:11:25 +0100 Subject: Fix getting card serial todo: remove whitespace at the string end Signed-off-by: Szczepan Zalega --- include/misc.h | 3 ++- include/stick10_commands.h | 2 +- misc.cc | 23 +++++++++++++---------- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/include/misc.h b/include/misc.h index 5158de0..9e4659d 100644 --- a/include/misc.h +++ b/include/misc.h @@ -44,7 +44,8 @@ typename T::CommandPayload get_payload(){ CMDTYPE::CommandTransaction::run(stick, p); } - std::string hexdump(const char *p, size_t size, bool print_header=true); + std::string hexdump(const char *p, size_t size, bool print_header=true, bool print_ascii=true, + bool print_empty=true); uint32_t stm_crc32(const uint8_t *data, size_t size); std::vector hex_string_to_byte(const char* hexString); } diff --git a/include/stick10_commands.h b/include/stick10_commands.h index 9b72e92..fb362fb 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -332,7 +332,7 @@ class GetStatus : Command { std::string get_card_serial_hex() const { return ::nitrokey::misc::hexdump((const char *)(card_serial), - sizeof card_serial, false); + sizeof card_serial, false, false, false); } std::string dissect() const { diff --git a/misc.cc b/misc.cc index 3f15520..a76bfb6 100644 --- a/misc.cc +++ b/misc.cc @@ -36,7 +36,8 @@ std::vector hex_string_to_byte(const char* hexString){ }; #include -std::string hexdump(const char *p, size_t size, bool print_header) { +std::string hexdump(const char *p, size_t size, bool print_header, + bool print_ascii, bool print_empty) { std::stringstream out; char formatbuf[128]; const char *pstart = p; @@ -53,18 +54,20 @@ std::string hexdump(const char *p, size_t size, bool print_header) { snprintf(formatbuf, 128, "%02x ", uint8_t(*p)); out << formatbuf; } else { - out << "-- "; + if(print_empty) + out << "-- "; } } - out << "\t"; - - for (const char *le = pp + 16; pp < le && pp < pend; pp++) { - if (std::isgraph(*pp)) - out << uint8_t(*pp); - else - out << '.'; - } + if(print_ascii){ + out << "\t"; + for (const char *le = pp + 16; pp < le && pp < pend; pp++) { + if (std::isgraph(*pp)) + out << uint8_t(*pp); + else + out << '.'; + } + } out << std::endl; } return out.str(); -- cgit v1.2.3 From 4f0ae6f59bc086f5ac9a1af14195b54c397641b2 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 23 Jan 2017 18:40:10 +0100 Subject: Throw on not connected device when requesting model Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index d85af91..e0e6ae3 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -617,6 +617,9 @@ namespace nitrokey{ DeviceModel NitrokeyManager::get_connected_device_model() const{ //FIXME throw if no device is connected or return unknown/unconnected value + if (device == nullptr){ + throw std::runtime_error("device not connected"); + } return device->get_device_model(); } -- cgit v1.2.3 From 02ac032b7493749bfd64533fe0c7f1e8ff46fe75 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 24 Jan 2017 15:17:22 +0100 Subject: Remove support for new authorization protocol for storage Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index e0e6ae3..09a0def 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -610,7 +610,7 @@ namespace nitrokey{ //authorization command is supported for versions equal or below: auto m = std::unordered_map({ {DeviceModel::PRO, 7}, - {DeviceModel::STORAGE, 43}, + {DeviceModel::STORAGE, 99}, }); return get_minor_firmware_version() <= m[device->get_device_model()]; } -- cgit v1.2.3 From 2543e09fa25fa8ed54920c519de32d4b4da074d4 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 24 Jan 2017 17:33:49 +0100 Subject: Read slot command support Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 22 +++++++++++++++++++++- include/NitrokeyManager.h | 7 ++++++- include/stick10_commands.h | 38 ++++++++++++++++++++++++++++++++------ 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 09a0def..b12895d 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -468,6 +468,7 @@ namespace nitrokey{ auto response = GetUserPasswordRetryCount::CommandTransaction::run(*device); return response.data().password_retry_count; } + uint8_t NitrokeyManager::get_admin_retry_count() { if(device->get_device_model() == DeviceModel::STORAGE){ stick20::GetDeviceStatus::CommandTransaction::run(*device); @@ -728,4 +729,23 @@ namespace nitrokey{ } } - } + uint32_t NitrokeyManager::get_TOTP_code(uint8_t slot_number, const char *user_temporary_password) { + return get_TOTP_code(slot_number, 0, 0, 0, user_temporary_password); + } + + stick10::ReadSlot::ResponsePayload NitrokeyManager::get_OTP_slot_data(const uint8_t slot_number) { + auto p = get_payload(); + p.slot_number = slot_number; + auto data = stick10::ReadSlot::CommandTransaction::run(*device, p); + return data.data(); + } + + stick10::ReadSlot::ResponsePayload NitrokeyManager::get_TOTP_slot_data(const uint8_t slot_number) { + return get_OTP_slot_data(get_internal_slot_number_for_totp(slot_number)); + } + + stick10::ReadSlot::ResponsePayload NitrokeyManager::get_HOTP_slot_data(const uint8_t slot_number) { + return get_OTP_slot_data(get_internal_slot_number_for_hotp(slot_number)); + } + +} diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index c7d7704..03f1a86 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -32,6 +32,10 @@ namespace nitrokey { uint32_t get_HOTP_code(uint8_t slot_number, const char *user_temporary_password); uint32_t get_TOTP_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, uint8_t last_interval, const char *user_temporary_password); + uint32_t get_TOTP_code(uint8_t slot_number, const char *user_temporary_password); + stick10::ReadSlot::ResponsePayload get_TOTP_slot_data(const uint8_t slot_number); + stick10::ReadSlot::ResponsePayload get_HOTP_slot_data(const uint8_t slot_number); + bool set_time(uint64_t time); bool get_time(); bool erase_totp_slot(uint8_t slot_number, const char *temporary_password); @@ -127,7 +131,8 @@ namespace nitrokey { static shared_ptr _instance; std::shared_ptr device; - bool is_valid_hotp_slot_number(uint8_t slot_number) const; + stick10::ReadSlot::ResponsePayload get_OTP_slot_data(const uint8_t slot_number); + bool is_valid_hotp_slot_number(uint8_t slot_number) const; bool is_valid_totp_slot_number(uint8_t slot_number) const; bool is_valid_password_safe_slot_number(uint8_t slot_number) const; uint8_t get_internal_slot_number_for_hotp(uint8_t slot_number) const; diff --git a/include/stick10_commands.h b/include/stick10_commands.h index fb362fb..b66a9b4 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -293,18 +293,44 @@ class ReadSlot : Command { struct ResponsePayload { uint8_t slot_name[15]; - uint8_t config; - uint8_t token_id[13]; - uint64_t counter; + union{ + uint8_t _slot_config; + struct{ + bool use_8_digits : 1; + bool use_enter : 1; + bool use_tokenID : 1; + }; + }; + union{ + uint8_t slot_token_id[13]; /** OATH Token Identifier */ + struct{ /** @see https://openauthentication.org/token-specs/ */ + uint8_t omp[2]; + uint8_t tt[2]; + uint8_t mui[8]; + uint8_t keyboard_layout; //disabled feature in nitroapp as of 20160805 + } slot_token_fields; + }; + union{ + uint64_t slot_counter; + uint8_t slot_counter_s[8]; + } __packed; bool isValid() const { return true; } std::string dissect() const { std::stringstream ss; ss << "slot_name:\t" << slot_name << std::endl; - ss << "config:\t" << config << std::endl; - ss << "token_id:\t" << token_id << std::endl; - ss << "counter:\t" << counter << std::endl; + ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl; + ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl; + ss << "\tuse_enter(1):\t" << use_enter << std::endl; + ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl; + + ss << "slot_token_id:\t"; + for (auto i : slot_token_id) + ss << std::hex << std::setw(2) << std::setfill('0')<< (int) i << " " ; + ss << std::endl; + ss << "slot_counter:\t[" << (int)slot_counter << "]\t" + << ::nitrokey::misc::hexdump((const char *)(&slot_counter), sizeof slot_counter, false); return ss.str(); } } __packed; -- cgit v1.2.3 From a721ca6391d1f6494d5493fb0e56c868bcd2b60c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 26 Jan 2017 10:28:12 +0100 Subject: Use const char pointers for C strings Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 6 +++--- include/NitrokeyManager.h | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index b12895d..c5259d2 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -406,16 +406,16 @@ namespace nitrokey{ return false; } - void NitrokeyManager::change_user_PIN(char *current_PIN, char *new_PIN) { + void NitrokeyManager::change_user_PIN(const char *current_PIN, const char *new_PIN) { change_PIN_general(current_PIN, new_PIN); } - void NitrokeyManager::change_admin_PIN(char *current_PIN, char *new_PIN) { + void NitrokeyManager::change_admin_PIN(const char *current_PIN, const char *new_PIN) { change_PIN_general(current_PIN, new_PIN); } template - void NitrokeyManager::change_PIN_general(char *current_PIN, char *new_PIN) { + void NitrokeyManager::change_PIN_general(const char *current_PIN, const char *new_PIN) { switch (device->get_device_model()){ case DeviceModel::PRO: { diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 03f1a86..f0cab68 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -53,8 +53,8 @@ namespace nitrokey { const char * get_totp_slot_name(uint8_t slot_number); const char * get_hotp_slot_name(uint8_t slot_number); - void change_user_PIN(char *current_PIN, char *new_PIN); - void change_admin_PIN(char *current_PIN, char *new_PIN); + void change_user_PIN(const char *current_PIN, const char *new_PIN); + void change_admin_PIN(const char *current_PIN, const char *new_PIN); void enable_password_safe(const char *user_pin); @@ -141,7 +141,7 @@ namespace nitrokey { const char * get_slot_name(uint8_t slot_number); template - void change_PIN_general(char *current_PIN, char *new_PIN); + void change_PIN_general(const char *current_PIN, const char *new_PIN); void write_HOTP_slot_authorize(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter, bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID, -- cgit v1.2.3 From 84a98c04c6c79455b04ba300ebfa5ec752abb721 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 30 Jan 2017 17:29:53 +0100 Subject: Send current time when checking time synchronization Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 2 +- NitrokeyManager.cc | 5 +++-- include/NitrokeyManager.h | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index f396fcb..6d18e52 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -273,7 +273,7 @@ extern int NK_totp_set_time(uint64_t time){ extern int NK_totp_get_time(){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ - m->get_time(); // FIXME check how that should work + m->get_time(0); // FIXME check how that should work }); } diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index c5259d2..dc58e4d 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -399,11 +399,12 @@ namespace nitrokey{ return false; } - bool NitrokeyManager::get_time() { + bool NitrokeyManager::get_time(uint64_t time) { auto p = get_payload(); p.reset = 0; + p.time = time; SetTime::CommandTransaction::run(*device, p); - return false; + return true; } void NitrokeyManager::change_user_PIN(const char *current_PIN, const char *new_PIN) { diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index f0cab68..3e38cc3 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -37,7 +37,7 @@ namespace nitrokey { stick10::ReadSlot::ResponsePayload get_HOTP_slot_data(const uint8_t slot_number); bool set_time(uint64_t time); - bool get_time(); + bool get_time(uint64_t time = 0); bool erase_totp_slot(uint8_t slot_number, const char *temporary_password); bool erase_hotp_slot(uint8_t slot_number, const char *temporary_password); bool connect(const char *device_model); -- cgit v1.2.3 From 48ec48d2c680b9f40d2b038fda9555bfd024bb97 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 30 Jan 2017 20:31:18 +0100 Subject: Use local hexdumping function for getting serial number Signed-off-by: Szczepan Zalega --- include/stick10_commands.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/include/stick10_commands.h b/include/stick10_commands.h index b66a9b4..8d37dbd 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -357,8 +357,14 @@ class GetStatus : Command { bool isValid() const { return enable_user_password!=delete_user_password; } std::string get_card_serial_hex() const { - return ::nitrokey::misc::hexdump((const char *)(card_serial), - sizeof card_serial, false, false, false); +// return ::nitrokey::misc::hexdump((const char *)(card_serial), +// sizeof card_serial, false, false, false); + std::stringstream ss; + ss << std::hex << std::setfill('0'); + for (int i = 0; i < sizeof(card_serial); ++i) { + ss << std::setw(2) << static_cast(card_serial[i]); + } + return ss.str(); } std::string dissect() const { -- cgit v1.2.3 From aa668f74e95617fd0544327a2b57bf654a6f9a2d Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 31 Jan 2017 18:07:55 +0100 Subject: Be tread-safe on initializing instance Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 3 ++- include/DeviceCommunicationExceptions.h | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 include/DeviceCommunicationExceptions.h diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index dc58e4d..ee7ca92 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -88,7 +88,8 @@ namespace nitrokey{ } shared_ptr NitrokeyManager::instance() { - //FIXME check thread safety - add atomic for instance, add lock guard + static std::mutex mutex; + std::lock_guard lock(mutex); if (_instance == nullptr){ _instance = make_shared(); } diff --git a/include/DeviceCommunicationExceptions.h b/include/DeviceCommunicationExceptions.h new file mode 100644 index 0000000..78fc625 --- /dev/null +++ b/include/DeviceCommunicationExceptions.h @@ -0,0 +1,31 @@ +#ifndef LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H +#define LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H + +#include +#include +//class DeviceCommunicationException: public std::exception { +class DeviceCommunicationException: public std::runtime_error{ + std::string message; +public: + DeviceCommunicationException(std::string _msg): runtime_error(_msg), message(_msg){} +// virtual const char* what() const throw() override { +// return message.c_str(); +// } +}; + +class DeviceNotConnected: public DeviceCommunicationException { +public: + DeviceNotConnected(std::string msg) : DeviceCommunicationException(msg){} +}; + +class DeviceSendingFailure: public DeviceCommunicationException { +public: + DeviceSendingFailure(std::string msg) : DeviceCommunicationException(msg){} +}; + +class DeviceReceivingFailure: public DeviceCommunicationException { +public: + DeviceReceivingFailure(std::string msg) : DeviceCommunicationException(msg){} +}; + +#endif //LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H -- cgit v1.2.3 From cb6b2dd65e1f0132353159b83ae05c944d8e62f0 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 31 Jan 2017 18:10:59 +0100 Subject: Make disconnect thread safe. Check is device actually connected by invoking its checking method Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 32 ++++++++++++++++++++++++-------- include/NitrokeyManager.h | 3 ++- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index ee7ca92..3213417 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -100,16 +100,32 @@ namespace nitrokey{ bool NitrokeyManager::disconnect() { std::lock_guard lock(mex_dev_com); - if (!is_connected()){ - return false; - } - const auto res = device->disconnect(); - device = nullptr; - return res; + return _disconnect_no_lock(); } - bool NitrokeyManager::is_connected() const throw(){ - return device != nullptr; + bool NitrokeyManager::_disconnect_no_lock() { + //do not use directly without locked mutex, + //used by is_connected, disconnect + if (device == nullptr){ + return false; + } + const auto res = device->disconnect(); + device = nullptr; + return res; + } + + bool NitrokeyManager::is_connected() throw(){ + std::lock_guard lock(mex_dev_com); + if(device != nullptr){ + auto connected = device->is_connected(); + if(connected){ + return true; + } else { + _disconnect_no_lock(); + return false; + } + } + return false; } void NitrokeyManager::set_debug(bool state) { diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 3e38cc3..4a98e94 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -43,7 +43,7 @@ namespace nitrokey { bool connect(const char *device_model); bool connect(); bool disconnect(); - bool is_connected() const throw() ; + bool is_connected() throw() ; DeviceModel get_connected_device_model() const; void set_debug(bool state); stick10::GetStatus::ResponsePayload get_status(); @@ -156,6 +156,7 @@ namespace nitrokey { bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID, const char *temporary_password) const; + bool _disconnect_no_lock(); }; } -- cgit v1.2.3 From 0503db5b47f247568b78504fa781e083e108eab9 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 31 Jan 2017 18:12:31 +0100 Subject: Pass devices shared pointer to methods instead of ref Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 126 ++++++++++++++++++++++++------------------------- include/device_proto.h | 22 ++++----- 2 files changed, 74 insertions(+), 74 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 3213417..65b3c68 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -48,7 +48,7 @@ namespace nitrokey{ auto auth = get_payload(); strcpyT(auth.temporary_password, admin_temporary_password); auth.crc_to_authorize = S::CommandTransaction::getCRC(package); - A::CommandTransaction::run(*device, auth); + A::CommandTransaction::run(device, auth); } shared_ptr NitrokeyManager::_instance = nullptr; @@ -137,17 +137,17 @@ namespace nitrokey{ } string NitrokeyManager::get_serial_number() { - auto response = GetStatus::CommandTransaction::run(*device); + auto response = GetStatus::CommandTransaction::run(device); return response.data().get_card_serial_hex(); } stick10::GetStatus::ResponsePayload NitrokeyManager::get_status(){ - auto response = GetStatus::CommandTransaction::run(*device); + auto response = GetStatus::CommandTransaction::run(device); return response.data(); } string NitrokeyManager::get_status_as_string() { - auto response = GetStatus::CommandTransaction::run(*device); + auto response = GetStatus::CommandTransaction::run(device); return response.data().dissect(); } @@ -160,7 +160,7 @@ namespace nitrokey{ if(user_temporary_password != nullptr && strlen(user_temporary_password)!=0){ //FIXME use string instead of strlen authorize_packet(gh, user_temporary_password, device); } - auto resp = GetHOTP::CommandTransaction::run(*device, gh); + auto resp = GetHOTP::CommandTransaction::run(device, gh); return resp.data().code; } else { auto gh = get_payload(); @@ -168,7 +168,7 @@ namespace nitrokey{ if(user_temporary_password != nullptr && strlen(user_temporary_password)!=0) { strcpyT(gh.temporary_user_password, user_temporary_password); } - auto resp = stick10_08::GetHOTP::CommandTransaction::run(*device, gh); + auto resp = stick10_08::GetHOTP::CommandTransaction::run(device, gh); return resp.data().code; } } @@ -195,13 +195,13 @@ namespace nitrokey{ if(user_temporary_password != nullptr && strlen(user_temporary_password)!=0){ //FIXME use string instead of strlen authorize_packet(gt, user_temporary_password, device); } - auto resp = GetTOTP::CommandTransaction::run(*device, gt); + auto resp = GetTOTP::CommandTransaction::run(device, gt); return resp.data().code; } else { auto gt = get_payload(); strcpyT(gt.temporary_user_password, user_temporary_password); gt.slot_number = slot_number; - auto resp = stick10_08::GetTOTP::CommandTransaction::run(*device, gt); + auto resp = stick10_08::GetTOTP::CommandTransaction::run(device, gt); return resp.data().code; } @@ -212,12 +212,12 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; authorize_packet(p, temporary_password, device); - auto resp = EraseSlot::CommandTransaction::run(*device,p); + auto resp = EraseSlot::CommandTransaction::run(device,p); } else { auto p = get_payload(); p.slot_number = slot_number; strcpyT(p.temporary_admin_password, temporary_password); - auto resp = stick10_08::EraseSlot::CommandTransaction::run(*device,p); + auto resp = stick10_08::EraseSlot::CommandTransaction::run(device,p); } return true; } @@ -301,7 +301,7 @@ namespace nitrokey{ authorize_packet(payload, temporary_password, device); - auto resp = WriteToHOTPSlot::CommandTransaction::run(*device, payload); + auto resp = WriteToHOTPSlot::CommandTransaction::run(device, payload); } bool NitrokeyManager::write_TOTP_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window, @@ -331,7 +331,7 @@ namespace nitrokey{ strcpyT(payload2.temporary_admin_password, temporary_password); strcpyT(payload2.data, slot_name); payload2.setTypeName(); - stick10_08::SendOTPData::CommandTransaction::run(*device, payload2); + stick10_08::SendOTPData::CommandTransaction::run(device, payload2); payload2.setTypeSecret(); payload2.id = 0; @@ -347,7 +347,7 @@ namespace nitrokey{ const auto start = secret_bin.size() - remaining_secret_length; memset(payload2.data, 0, sizeof(payload2.data)); vector_copy_ranged(payload2.data, secret_bin, start, bytesToCopy); - stick10_08::SendOTPData::CommandTransaction::run(*device, payload2); + stick10_08::SendOTPData::CommandTransaction::run(device, payload2); remaining_secret_length -= bytesToCopy; payload2.id++; } @@ -360,7 +360,7 @@ namespace nitrokey{ payload.use_tokenID = use_tokenID; payload.slot_counter_or_interval = counter_or_interval; payload.slot_number = internal_slot_number; - stick10_08::WriteToOTPSlot::CommandTransaction::run(*device, payload); + stick10_08::WriteToOTPSlot::CommandTransaction::run(device, payload); } void NitrokeyManager::write_TOTP_slot_authorize(uint8_t slot_number, const char *slot_name, const char *secret, @@ -379,7 +379,7 @@ namespace nitrokey{ authorize_packet(payload, temporary_password, device); - auto resp = WriteToTOTPSlot::CommandTransaction::run(*device, payload); + auto resp = WriteToTOTPSlot::CommandTransaction::run(device, payload); } const char * NitrokeyManager::get_totp_slot_name(uint8_t slot_number) { @@ -396,7 +396,7 @@ namespace nitrokey{ const char * NitrokeyManager::get_slot_name(uint8_t slot_number) { auto payload = get_payload(); payload.slot_number = slot_number; - auto resp = GetSlotName::CommandTransaction::run(*device, payload); + auto resp = GetSlotName::CommandTransaction::run(device, payload); return strdup((const char *) resp.data().slot_name); } @@ -404,7 +404,7 @@ namespace nitrokey{ auto authreq = get_payload(); strcpyT(authreq.card_password, pin); strcpyT(authreq.temporary_password, temporary_password); - FirstAuthenticate::CommandTransaction::run(*device, authreq); + FirstAuthenticate::CommandTransaction::run(device, authreq); return true; } @@ -412,7 +412,7 @@ namespace nitrokey{ auto p = get_payload(); p.reset = 1; p.time = time; - SetTime::CommandTransaction::run(*device, p); + SetTime::CommandTransaction::run(device, p); return false; } @@ -420,7 +420,7 @@ namespace nitrokey{ auto p = get_payload(); p.reset = 0; p.time = time; - SetTime::CommandTransaction::run(*device, p); + SetTime::CommandTransaction::run(device, p); return true; } @@ -440,7 +440,7 @@ namespace nitrokey{ auto p = get_payload(); strcpyT(p.old_pin, current_PIN); strcpyT(p.new_pin, new_PIN); - ProCommand::CommandTransaction::run(*device, p); + ProCommand::CommandTransaction::run(device, p); } break; //in Storage change admin/user pin is divided to two commands with 20 chars field len @@ -452,8 +452,8 @@ namespace nitrokey{ auto p2 = get_payload(); strcpyT(p2.password, new_PIN); p2.set_kind(StoKind); - ChangeAdminUserPin20Current::CommandTransaction::run(*device, p); - ChangeAdminUserPin20New::CommandTransaction::run(*device, p2); + ChangeAdminUserPin20Current::CommandTransaction::run(device, p); + ChangeAdminUserPin20New::CommandTransaction::run(device, p2); } break; } @@ -464,15 +464,15 @@ namespace nitrokey{ //The following command will cancel enabling PWS if it is not supported auto a = get_payload(); strcpyT(a.user_password, user_pin); - IsAESSupported::CommandTransaction::run(*device, a); + IsAESSupported::CommandTransaction::run(device, a); auto p = get_payload(); strcpyT(p.user_password, user_pin); - EnablePasswordSafe::CommandTransaction::run(*device, p); + EnablePasswordSafe::CommandTransaction::run(device, p); } vector NitrokeyManager::get_password_safe_slot_status() { - auto responsePayload = GetPasswordSafeSlotStatus::CommandTransaction::run(*device); + auto responsePayload = GetPasswordSafeSlotStatus::CommandTransaction::run(device); vector v = vector(responsePayload.data().password_safe_status, responsePayload.data().password_safe_status + sizeof(responsePayload.data().password_safe_status)); @@ -481,29 +481,29 @@ namespace nitrokey{ uint8_t NitrokeyManager::get_user_retry_count() { if(device->get_device_model() == DeviceModel::STORAGE){ - stick20::GetDeviceStatus::CommandTransaction::run(*device); + stick20::GetDeviceStatus::CommandTransaction::run(device); } - auto response = GetUserPasswordRetryCount::CommandTransaction::run(*device); + auto response = GetUserPasswordRetryCount::CommandTransaction::run(device); return response.data().password_retry_count; } uint8_t NitrokeyManager::get_admin_retry_count() { if(device->get_device_model() == DeviceModel::STORAGE){ - stick20::GetDeviceStatus::CommandTransaction::run(*device); + stick20::GetDeviceStatus::CommandTransaction::run(device); } - auto response = GetPasswordRetryCount::CommandTransaction::run(*device); + auto response = GetPasswordRetryCount::CommandTransaction::run(device); return response.data().password_retry_count; } void NitrokeyManager::lock_device() { - LockDevice::CommandTransaction::run(*device); + LockDevice::CommandTransaction::run(device); } const char *NitrokeyManager::get_password_safe_slot_name(uint8_t slot_number) { if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number); auto p = get_payload(); p.slot_number = slot_number; - auto response = GetPasswordSafeSlotName::CommandTransaction::run(*device, p); + auto response = GetPasswordSafeSlotName::CommandTransaction::run(device, p); return strdup((const char *) response.data().slot_name); } @@ -513,7 +513,7 @@ namespace nitrokey{ if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number); auto p = get_payload(); p.slot_number = slot_number; - auto response = GetPasswordSafeSlotLogin::CommandTransaction::run(*device, p); + auto response = GetPasswordSafeSlotLogin::CommandTransaction::run(device, p); return strdup((const char *) response.data().slot_login); } @@ -521,7 +521,7 @@ namespace nitrokey{ if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number); auto p = get_payload(); p.slot_number = slot_number; - auto response = GetPasswordSafeSlotPassword::CommandTransaction::run(*device, p); + auto response = GetPasswordSafeSlotPassword::CommandTransaction::run(device, p); return strdup((const char *) response.data().slot_password); } @@ -532,26 +532,26 @@ namespace nitrokey{ p.slot_number = slot_number; strcpyT(p.slot_name, slot_name); strcpyT(p.slot_password, slot_password); - SetPasswordSafeSlotData::CommandTransaction::run(*device, p); + SetPasswordSafeSlotData::CommandTransaction::run(device, p); auto p2 = get_payload(); p2.slot_number = slot_number; strcpyT(p2.slot_login_name, slot_login); - SetPasswordSafeSlotData2::CommandTransaction::run(*device, p2); + SetPasswordSafeSlotData2::CommandTransaction::run(device, p2); } void NitrokeyManager::erase_password_safe_slot(uint8_t slot_number) { if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number); auto p = get_payload(); p.slot_number = slot_number; - ErasePasswordSafeSlot::CommandTransaction::run(*device, p); + ErasePasswordSafeSlot::CommandTransaction::run(device, p); } void NitrokeyManager::user_authenticate(const char *user_password, const char *temporary_password) { auto p = get_payload(); strcpyT(p.card_password, user_password); strcpyT(p.temporary_password, temporary_password); - UserAuthenticate::CommandTransaction::run(*device, p); + UserAuthenticate::CommandTransaction::run(device, p); } void NitrokeyManager::build_aes_key(const char *admin_password) { @@ -559,14 +559,14 @@ namespace nitrokey{ case DeviceModel::PRO: { auto p = get_payload(); strcpyT(p.admin_password, admin_password); - BuildAESKey::CommandTransaction::run(*device, p); + BuildAESKey::CommandTransaction::run(device, p); break; } case DeviceModel::STORAGE : { auto p = get_payload(); strcpyT(p.password, admin_password); p.set_defaults(); - stick20::CreateNewKeys::CommandTransaction::run(*device, p); + stick20::CreateNewKeys::CommandTransaction::run(device, p); break; } } @@ -575,7 +575,7 @@ namespace nitrokey{ void NitrokeyManager::factory_reset(const char *admin_password) { auto p = get_payload(); strcpyT(p.admin_password, admin_password); - FactoryReset::CommandTransaction::run(*device, p); + FactoryReset::CommandTransaction::run(device, p); } void NitrokeyManager::unlock_user_password(const char *admin_password, const char *new_user_password) { @@ -584,18 +584,18 @@ namespace nitrokey{ auto p = get_payload(); strcpyT(p.admin_password, admin_password); strcpyT(p.user_new_password, new_user_password); - stick10::UnlockUserPassword::CommandTransaction::run(*device, p); + stick10::UnlockUserPassword::CommandTransaction::run(device, p); break; } case DeviceModel::STORAGE : { auto p2 = get_payload(); p2.set_defaults(); strcpyT(p2.password, admin_password); - ChangeAdminUserPin20Current::CommandTransaction::run(*device, p2); + ChangeAdminUserPin20Current::CommandTransaction::run(device, p2); auto p3 = get_payload(); p3.set_defaults(); strcpyT(p3.password, new_user_password); - stick20::UnlockUserPin::CommandTransaction::run(*device, p3); + stick20::UnlockUserPin::CommandTransaction::run(device, p3); break; } } @@ -615,11 +615,11 @@ namespace nitrokey{ } else { strcpyT(p.temporary_admin_password, admin_temporary_password); } - stick10_08::WriteGeneralConfig::CommandTransaction::run(*device, p); + stick10_08::WriteGeneralConfig::CommandTransaction::run(device, p); } vector NitrokeyManager::read_config() { - auto responsePayload = GetStatus::CommandTransaction::run(*device); + auto responsePayload = GetStatus::CommandTransaction::run(device); vector v = vector(responsePayload.data().general_config, responsePayload.data().general_config+sizeof(responsePayload.data().general_config)); return v; @@ -645,11 +645,11 @@ namespace nitrokey{ int NitrokeyManager::get_minor_firmware_version(){ switch(device->get_device_model()){ case DeviceModel::PRO:{ - auto status_p = GetStatus::CommandTransaction::run(*device); + auto status_p = GetStatus::CommandTransaction::run(device); return status_p.data().firmware_version; //7 or 8 } case DeviceModel::STORAGE:{ - auto status = stick20::GetDeviceStatus::CommandTransaction::run(*device); + auto status = stick20::GetDeviceStatus::CommandTransaction::run(device); return status.data().versionInfo.minor; } } @@ -659,7 +659,7 @@ namespace nitrokey{ bool NitrokeyManager::is_AES_supported(const char *user_password) { auto a = get_payload(); strcpyT(a.user_password, user_password); - IsAESSupported::CommandTransaction::run(*device, a); + IsAESSupported::CommandTransaction::run(device, a); return true; } @@ -669,15 +669,15 @@ namespace nitrokey{ auto p = get_payload(); // p.set_defaults(); //set current time p.localtime = seconds_from_epoch; - stick20::SendStartup::CommandTransaction::run(*device, p); + stick20::SendStartup::CommandTransaction::run(device, p); } void NitrokeyManager::unlock_encrypted_volume(const char* user_pin){ - misc::execute_password_command(*device, user_pin); + misc::execute_password_command(device, user_pin); } void NitrokeyManager::unlock_hidden_volume(const char* hidden_volume_password) { - misc::execute_password_command(*device, hidden_volume_password); + misc::execute_password_command(device, hidden_volume_password); } //TODO check is encrypted volume unlocked before execution @@ -689,57 +689,57 @@ namespace nitrokey{ p.StartBlockPercent_u8 = start_percent; p.EndBlockPercent_u8 = end_percent; strcpyT(p.HiddenVolumePassword_au8, hidden_volume_password); - stick20::SetupHiddenVolume::CommandTransaction::run(*device, p); + stick20::SetupHiddenVolume::CommandTransaction::run(device, p); } void NitrokeyManager::set_unencrypted_read_only(const char* user_pin) { - misc::execute_password_command(*device, user_pin); + misc::execute_password_command(device, user_pin); } void NitrokeyManager::set_unencrypted_read_write(const char* user_pin) { - misc::execute_password_command(*device, user_pin); + misc::execute_password_command(device, user_pin); } void NitrokeyManager::export_firmware(const char* admin_pin) { - misc::execute_password_command(*device, admin_pin); + misc::execute_password_command(device, admin_pin); } void NitrokeyManager::clear_new_sd_card_warning(const char* admin_pin) { - misc::execute_password_command(*device, admin_pin); + misc::execute_password_command(device, admin_pin); } void NitrokeyManager::fill_SD_card_with_random_data(const char* admin_pin) { auto p = get_payload(); p.set_defaults(); strcpyT(p.admin_pin, admin_pin); - stick20::FillSDCardWithRandomChars::CommandTransaction::run(*device, p); + stick20::FillSDCardWithRandomChars::CommandTransaction::run(device, p); } void NitrokeyManager::change_update_password(const char* current_update_password, const char* new_update_password) { auto p = get_payload(); strcpyT(p.current_update_password, current_update_password); strcpyT(p.new_update_password, new_update_password); - stick20::ChangeUpdatePassword::CommandTransaction::run(*device, p); + stick20::ChangeUpdatePassword::CommandTransaction::run(device, p); } const char * NitrokeyManager::get_status_storage_as_string(){ - auto p = stick20::GetDeviceStatus::CommandTransaction::run(*device); + auto p = stick20::GetDeviceStatus::CommandTransaction::run(device); return strdup(p.data().dissect().c_str()); } stick20::DeviceConfigurationResponsePacket::ResponsePayload NitrokeyManager::get_status_storage(){ - auto p = stick20::GetDeviceStatus::CommandTransaction::run(*device); + auto p = stick20::GetDeviceStatus::CommandTransaction::run(device); return p.data(); } const char * NitrokeyManager::get_SD_usage_data_as_string(){ - auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(*device); + auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(device); return strdup(p.data().dissect().c_str()); } int NitrokeyManager::get_progress_bar_value(){ try{ - stick20::GetDeviceStatus::CommandTransaction::run(*device); + stick20::GetDeviceStatus::CommandTransaction::run(device); return -1; } catch (LongOperationInProgressException &e){ @@ -754,7 +754,7 @@ namespace nitrokey{ stick10::ReadSlot::ResponsePayload NitrokeyManager::get_OTP_slot_data(const uint8_t slot_number) { auto p = get_payload(); p.slot_number = slot_number; - auto data = stick10::ReadSlot::CommandTransaction::run(*device, p); + auto data = stick10::ReadSlot::CommandTransaction::run(device, p); return data.data(); } diff --git a/include/device_proto.h b/include/device_proto.h index 2105f30..ba314f4 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -206,7 +206,7 @@ namespace nitrokey { bzero(&st, sizeof(st)); } - static ClearingProxy run(device::Device &dev, + static ClearingProxy run(std::shared_ptr dev, const command_payload &payload) { using namespace ::nitrokey::device; using namespace ::nitrokey::log; @@ -235,22 +235,22 @@ namespace nitrokey { bool successful_communication = false; int receiving_retry_counter = 0; - int sending_retry_counter = dev.get_retry_sending_count(); + int sending_retry_counter = dev->get_retry_sending_count(); while (sending_retry_counter-- > 0) { - status = dev.send(&outp); + status = dev->send(&outp); if (status <= 0) - throw std::runtime_error( + throw DeviceSendingFailure( std::string("Device error while sending command ") + std::to_string(status)); - std::this_thread::sleep_for(dev.get_send_receive_delay()); + std::this_thread::sleep_for(dev->get_send_receive_delay()); // FIXME make checks done in device:recv here - receiving_retry_counter = dev.get_retry_receiving_count(); + receiving_retry_counter = dev->get_retry_receiving_count(); while (receiving_retry_counter-- > 0) { - status = dev.recv(&resp); + status = dev->recv(&resp); - if (dev.get_device_model() == DeviceModel::STORAGE && + if (dev->get_device_model() == DeviceModel::STORAGE && resp.command_id >= stick20::CMD_START_VALUE && resp.command_id < stick20::CMD_END_VALUE ) { Log::instance()(std::string("Detected storage device cmd, status: ") + @@ -306,7 +306,7 @@ namespace nitrokey { Loglevel::DEBUG); Log::instance()("Invalid incoming HID packet:", Loglevel::DEBUG_L2); Log::instance()(static_cast(resp), Loglevel::DEBUG_L2); - std::this_thread::sleep_for(dev.get_retry_timeout()); + std::this_thread::sleep_for(dev->get_retry_timeout()); continue; } if (successful_communication) break; @@ -315,7 +315,7 @@ namespace nitrokey { Loglevel::DEBUG); } - dev.set_last_command_status(resp.last_command_status); // FIXME should be handled on device.recv + dev->set_last_command_status(resp.last_command_status); // FIXME should be handled on device.recv clear_packet(outp); @@ -348,7 +348,7 @@ namespace nitrokey { return resp; } - static ClearingProxy run(device::Device &dev) { + static ClearingProxy run(std::shared_ptr dev) { command_payload empty_payload; return run(dev, empty_payload); } -- cgit v1.2.3 From d69cf0b866fa3cc5afda2bb1a321a900520fbcc1 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 31 Jan 2017 18:15:48 +0100 Subject: Add method for checking is the device listed as connected in OS Signed-off-by: Szczepan Zalega --- device.cc | 18 ++++++++++++++++++ include/device.h | 2 ++ 2 files changed, 20 insertions(+) diff --git a/device.cc b/device.cc index 532ba2e..42c6883 100644 --- a/device.cc +++ b/device.cc @@ -106,6 +106,24 @@ int Device::recv(void *packet) { return status; } +bool Device::is_connected() { + Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + std::lock_guard lock(mex_dev_com); + if (mp_devhandle==nullptr){ + return false; + } + auto pInfo = hid_enumerate(m_vid, m_pid); + if (pInfo != nullptr){ + hid_free_enumeration(pInfo); + return true; + } + return false; + +// alternative: +// unsigned char buf[1]; +// return hid_read_timeout(mp_devhandle, buf, sizeof(buf), 20) != -1; +} + Stick10::Stick10(): Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 20, 100ms) {} diff --git a/include/device.h b/include/device.h index 4001d45..5965f99 100644 --- a/include/device.h +++ b/include/device.h @@ -52,6 +52,8 @@ public: */ virtual int recv(void *packet); + bool is_connected(); + int get_retry_receiving_count() const { return m_retry_receiving_count; }; int get_retry_sending_count() const { return m_retry_sending_count; }; std::chrono::milliseconds get_retry_timeout() const { return m_retry_timeout; }; -- cgit v1.2.3 From 03f444905d3a7af3091c2401280e83146f08443a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 31 Jan 2017 18:17:23 +0100 Subject: Add more shortcuts for checking devices error code Signed-off-by: Szczepan Zalega --- include/CommandFailedException.h | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/include/CommandFailedException.h b/include/CommandFailedException.h index 190eabc..6ff9a2d 100644 --- a/include/CommandFailedException.h +++ b/include/CommandFailedException.h @@ -14,11 +14,11 @@ using cs = nitrokey::proto::stick10::command_status; class CommandFailedException : public std::exception { public: - const uint8_t last_command_code; + const uint8_t last_command_id; const uint8_t last_command_status; - CommandFailedException(uint8_t last_command_code, uint8_t last_command_status) : - last_command_code(last_command_code), + CommandFailedException(uint8_t last_command_id, uint8_t last_command_status) : + last_command_id(last_command_id), last_command_status(last_command_status){ nitrokey::log::Log::instance()(std::string("CommandFailedException, status: ")+ std::to_string(last_command_status), nitrokey::log::Loglevel::DEBUG); } @@ -27,6 +27,19 @@ public: return "Command execution has failed on device"; } + + bool reason_timestamp_warning() const throw(){ + return last_command_status == static_cast(cs::timestamp_warning); + } + + bool reason_AES_not_initialized() const throw(){ + return last_command_status == static_cast(cs::AES_dec_failed); + } + + bool reason_not_authorized() const throw(){ + return last_command_status == static_cast(cs::not_authorized); + } + bool reason_slot_not_programmed() const throw(){ return last_command_status == static_cast(cs::slot_not_programmed); } -- cgit v1.2.3 From 9bc6b85e12d73a43b8d85ba109acff8778f4c08a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 31 Jan 2017 18:17:58 +0100 Subject: Throw before communicating with device if it is not initialized Signed-off-by: Szczepan Zalega --- device.cc | 13 +++++++++---- include/LibraryException.h | 2 -- include/device_proto.h | 7 ++++++- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/device.cc b/device.cc index 42c6883..ce1eeb6 100644 --- a/device.cc +++ b/device.cc @@ -7,6 +7,7 @@ #include "include/device.h" #include "include/log.h" #include +#include "DeviceCommunicationExceptions.h" std::mutex mex_dev_com; @@ -60,8 +61,10 @@ int Device::send(const void *packet) { std::lock_guard lock(mex_dev_com); Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); - if (mp_devhandle == nullptr) - throw std::runtime_error("Attempted HID send on an invalid descriptor."); //TODO migrate except to library_error + if (mp_devhandle == nullptr) { + Log::instance()(std::string("Connection fail") , Loglevel::DEBUG_L2); + throw DeviceNotConnected("Attempted HID send on an invalid descriptor."); + } return (hid_send_feature_report( mp_devhandle, (const unsigned char *)(packet), HID_REPORT_SIZE)); @@ -75,8 +78,10 @@ int Device::recv(void *packet) { int retry_count = 0; - if (mp_devhandle == nullptr) - throw std::runtime_error("Attempted HID receive on an invalid descriptor."); //TODO migrate except to library_error + if (mp_devhandle == nullptr){ + Log::instance()(std::string("Connection fail") , Loglevel::DEBUG_L2); + throw DeviceNotConnected("Attempted HID receive on an invalid descriptor."); + } // FIXME extract error handling and repeating to parent function in // device_proto:192 diff --git a/include/LibraryException.h b/include/LibraryException.h index 3c3fab4..e62788d 100644 --- a/include/LibraryException.h +++ b/include/LibraryException.h @@ -11,8 +11,6 @@ public: virtual uint8_t exception_id()= 0; }; - - class TargetBufferSmallerThanSource: public LibraryException { public: virtual uint8_t exception_id() override { diff --git a/include/device_proto.h b/include/device_proto.h index ba314f4..9401428 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -33,6 +33,7 @@ #define PWS_SEND_CR 3 #include +#include "DeviceCommunicationExceptions.h" namespace nitrokey { namespace proto { @@ -217,6 +218,10 @@ namespace nitrokey { Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + if (dev == nullptr){ + throw DeviceNotConnected("Device not initialized"); + } + int status; OutgoingPacket outp; ResponsePacket resp; @@ -320,7 +325,7 @@ namespace nitrokey { clear_packet(outp); if (status <= 0) - throw std::runtime_error( //FIXME replace with CriticalErrorException + throw DeviceReceivingFailure( //FIXME replace with CriticalErrorException std::string("Device error while executing command ") + std::to_string(status)); -- cgit v1.2.3 From 43bb63424fb7e78c245341c1baf326557ef896e8 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 31 Jan 2017 18:53:14 +0100 Subject: C++ tests fixed Signed-off-by: Szczepan Zalega --- unittest/test.cc | 9 +++++---- unittest/test2.cc | 27 ++++++++++++++------------- unittest/test3.cc | 21 ++++++++++++--------- unittest/test_HOTP.cc | 6 +++--- 4 files changed, 34 insertions(+), 29 deletions(-) diff --git a/unittest/test.cc b/unittest/test.cc index 6744b45..99f96ac 100644 --- a/unittest/test.cc +++ b/unittest/test.cc @@ -13,8 +13,9 @@ using namespace nitrokey::proto::stick10; using namespace nitrokey::log; using namespace nitrokey::misc; +using Dev10 = std::shared_ptr; -std::string getSlotName(Stick10 &stick, int slotNo) { +std::string getSlotName(Dev10 stick, int slotNo) { auto slot_req = get_payload(); slot_req.slot_number = slotNo; auto slot = ReadSlot::CommandTransaction::run(stick, slot_req); @@ -23,8 +24,8 @@ std::string getSlotName(Stick10 &stick, int slotNo) { } TEST_CASE("Slot names are correct", "[slotNames]") { - Stick10 stick; - bool connected = stick.connect(); + auto stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); @@ -79,5 +80,5 @@ TEST_CASE("Slot names are correct", "[slotNames]") { REQUIRE(sName == std::string("login1")); } - stick.disconnect(); + stick->disconnect(); } diff --git a/unittest/test2.cc b/unittest/test2.cc index 00e70e3..4b61a3c 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -20,9 +20,10 @@ using namespace nitrokey::proto::stick20; using namespace nitrokey::log; using namespace nitrokey::misc; +#include template -void execute_password_command(Device &stick, const char *password, const char kind = 'P') { +void execute_password_command(std::shared_ptr stick, const char *password, const char kind = 'P') { auto p = get_payload(); if (kind == 'P'){ p.set_kind_user(); @@ -47,8 +48,8 @@ void SKIP_TEST() { TEST_CASE("long operation test", "[test_long]") { SKIP_TEST(); - Stick20 stick; - bool connected = stick.connect(); + auto stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); try{ @@ -123,8 +124,8 @@ TEST_CASE("test device commands ids", "[fast]") { } TEST_CASE("test device internal status with various commands", "[fast]") { - Stick20 stick; - bool connected = stick.connect(); + auto stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); @@ -147,8 +148,8 @@ TEST_CASE("test device internal status with various commands", "[fast]") { } TEST_CASE("setup hidden volume test", "[hidden]") { - Stick20 stick; - bool connected = stick.connect(); + auto stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); stick10::LockDevice::CommandTransaction::run(stick); @@ -170,8 +171,8 @@ TEST_CASE("setup hidden volume test", "[hidden]") { } TEST_CASE("setup multiple hidden volumes", "[hidden]") { - Stick20 stick; - bool connected = stick.connect(); + auto stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); @@ -207,8 +208,8 @@ TEST_CASE("setup multiple hidden volumes", "[hidden]") { TEST_CASE("update password change", "[dangerous]") { SKIP_TEST(); - Stick20 stick; - bool connected = stick.connect(); + auto stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); @@ -228,8 +229,8 @@ TEST_CASE("update password change", "[dangerous]") { } TEST_CASE("general test", "[test]") { - Stick20 stick; - bool connected = stick.connect(); + auto stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); diff --git a/unittest/test3.cc b/unittest/test3.cc index 9049365..215df78 100644 --- a/unittest/test3.cc +++ b/unittest/test3.cc @@ -26,13 +26,15 @@ using namespace nitrokey::proto::stick10_08; using namespace nitrokey::log; using namespace nitrokey::misc; -void connect_and_setup(Stick10 &stick) { - bool connected = stick.connect(); +using Dev10 = std::shared_ptr; + +void connect_and_setup(Dev10 stick) { + bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); } -void authorize(Stick10 &stick) { +void authorize(Dev10 stick) { auto authreq = get_payload(); strcpy((char *) (authreq.card_password), default_admin_pin); strcpy((char *) (authreq.temporary_password), temporary_password); @@ -45,7 +47,8 @@ void authorize(Stick10 &stick) { } TEST_CASE("write slot", "[pronew]"){ - Stick10 stick; + auto stick = make_shared(); + connect_and_setup(stick); authorize(stick); @@ -81,7 +84,7 @@ TEST_CASE("write slot", "[pronew]"){ TEST_CASE("erase slot", "[pronew]"){ - Stick10 stick; + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); @@ -107,7 +110,7 @@ TEST_CASE("erase slot", "[pronew]"){ } TEST_CASE("write general config", "[pronew]") { - Stick10 stick; + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); @@ -121,7 +124,7 @@ TEST_CASE("write general config", "[pronew]") { } TEST_CASE("authorize user HOTP", "[pronew]") { - Stick10 stick; + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); @@ -164,7 +167,7 @@ TEST_CASE("authorize user HOTP", "[pronew]") { } TEST_CASE("check firmware version", "[pronew]") { - Stick10 stick; + auto stick = make_shared(); connect_and_setup(stick); auto p = GetStatus::CommandTransaction::run(stick); @@ -172,7 +175,7 @@ TEST_CASE("check firmware version", "[pronew]") { } TEST_CASE("authorize user TOTP", "[pronew]") { - Stick10 stick; + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); diff --git a/unittest/test_HOTP.cc b/unittest/test_HOTP.cc index d31df55..c6b62a3 100644 --- a/unittest/test_HOTP.cc +++ b/unittest/test_HOTP.cc @@ -34,8 +34,8 @@ TEST_CASE("test secret", "[functions]") { } TEST_CASE("Test HOTP codes according to RFC", "[HOTP]") { - Stick10 stick; - bool connected = stick.connect(); + std::shared_ptr stick = make_shared(); + bool connected = stick->connect(); REQUIRE(connected == true); @@ -98,5 +98,5 @@ TEST_CASE("Test HOTP codes according to RFC", "[HOTP]") { } - stick.disconnect(); + stick->disconnect(); } -- cgit v1.2.3 From 69fedd655a87c32c0c54eac46a1d6df7450873d6 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 2 Feb 2017 18:22:40 +0100 Subject: Add description for some Storage variables Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index fd72f1e..a3f1609 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -123,6 +123,9 @@ namespace nitrokey { StorageCommandResponsePayload::TransmissionData transmission_data; uint16_t MagicNumber_StickConfig_u16; + /** + * READ_WRITE_ACTIVE = ReadWriteFlagUncryptedVolume_u8 == 0; + */ uint8_t ReadWriteFlagUncryptedVolume_u8; uint8_t ReadWriteFlagCryptedVolume_u8; @@ -134,11 +137,22 @@ namespace nitrokey { uint8_t __unused2; uint8_t major; } __packed versionInfo; - }; + } __packed; uint8_t ReadWriteFlagHiddenVolume_u8; uint8_t FirmwareLocked_u8; - uint8_t NewSDCardFound_u8; + + union{ + uint8_t NewSDCardFound_u8; + struct { + bool NewCard :1; + uint8_t Counter :7; + } __packed NewSDCardFound_st; + } __packed; + + /** + * SD card FILLED with random chars + */ uint8_t SDFillWithRandomChars_u8; uint32_t ActiveSD_CardID_u32; union{ -- cgit v1.2.3 From 767e24572db2bbc4b9837c32ffc0bab4e1ad0b81 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 3 Feb 2017 17:07:32 +0100 Subject: Disconnect device as soon as the communication issue appears Signed-off-by: Szczepan Zalega --- include/device_proto.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/include/device_proto.h b/include/device_proto.h index 9401428..1e07277 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -243,10 +243,13 @@ namespace nitrokey { int sending_retry_counter = dev->get_retry_sending_count(); while (sending_retry_counter-- > 0) { status = dev->send(&outp); - if (status <= 0) + if (status <= 0){ + Log::instance()("Encountered communication error, disconnecting device", Loglevel::DEBUG_L2); + dev->disconnect(); throw DeviceSendingFailure( std::string("Device error while sending command ") + std::to_string(status)); + } std::this_thread::sleep_for(dev->get_send_receive_delay()); -- cgit v1.2.3 From db76ae5299f3650385f66e4c596b18fd54250d38 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 3 Feb 2017 17:23:44 +0100 Subject: Allow users to lock encrypted volumes specifically Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 8 ++++++++ include/NitrokeyManager.h | 2 ++ include/stick20_commands.h | 5 ++++- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 65b3c68..74a6ecf 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -766,4 +766,12 @@ namespace nitrokey{ return get_OTP_slot_data(get_internal_slot_number_for_hotp(slot_number)); } + void NitrokeyManager::lock_encrypted_volume() { + misc::execute_password_command(device, ""); + } + + void NitrokeyManager::lock_hidden_volume() { + misc::execute_password_command(device, ""); + } + } diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 4a98e94..b89db63 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -91,8 +91,10 @@ namespace nitrokey { bool is_AES_supported(const char *user_password); void unlock_encrypted_volume(const char *user_password); + void lock_encrypted_volume(); void unlock_hidden_volume(const char *hidden_volume_password); + void lock_hidden_volume(); void set_unencrypted_read_only(const char *user_pin); diff --git a/include/stick20_commands.h b/include/stick20_commands.h index a3f1609..b887636 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -26,9 +26,12 @@ namespace nitrokey { public PasswordCommand {}; class EnableEncryptedPartition : public PasswordCommand {}; - class DisableEncryptedPartition : public PasswordCommand {}; class EnableHiddenEncryptedPartition : public PasswordCommand {}; + + //FIXME the volume disabling commands do not need password + class DisableEncryptedPartition : public PasswordCommand {}; class DisableHiddenEncryptedPartition : public PasswordCommand {}; + class EnableFirmwareUpdate : public PasswordCommand {}; class ChangeUpdatePassword : Command { -- cgit v1.2.3 From 3fcbb90176fb02816cc47ad7172b7b89bf6cb67d Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 4 Feb 2017 16:13:02 +0100 Subject: Make statistics about device's connection Signed-off-by: Szczepan Zalega --- device.cc | 24 ++++++++++++++++++++++++ include/device.h | 22 ++++++++++++++++++++-- include/device_proto.h | 18 +++++++++++++++--- 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/device.cc b/device.cc index ce1eeb6..d904fd9 100644 --- a/device.cc +++ b/device.cc @@ -101,6 +101,9 @@ int Device::recv(void *packet) { Log::instance()( "Maximum retry count reached" + std::to_string(retry_count), Loglevel::WARNING); + Log::instance()( + std::string("Counter stats") + m_counters.get_as_string(), + Loglevel::DEBUG); break; } Log::instance()("Retrying... " + std::to_string(retry_count), @@ -129,6 +132,11 @@ bool Device::is_connected() { // return hid_read_timeout(mp_devhandle, buf, sizeof(buf), 20) != -1; } +void Device::show_stats() { + auto s = m_counters.get_as_string(); + Log::instance()(s, Loglevel::DEBUG_L2); +} + Stick10::Stick10(): Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 20, 100ms) {} @@ -137,3 +145,19 @@ Stick10::Stick10(): Stick20::Stick20(): Device(0x20a0, 0x4109, DeviceModel::STORAGE, 200ms, 40, 200ms) {} + +#include +#define p(x) ss << #x << " " << x << ", "; +std::string Device::ErrorCounters::get_as_string() { + std::stringstream ss; + p(wrong_CRC); + p(CRC_other_than_awaited); + p(busy); + p(total_retries); + p(sending_error); + p(receiving_error); + p(total_comm_runs); + p(storage_commands); + p(successful ); + return ss.str(); +} diff --git a/include/device.h b/include/device.h index 5965f99..a23e1b3 100644 --- a/include/device.h +++ b/include/device.h @@ -2,7 +2,8 @@ #define DEVICE_H #include #include -#include +#include +#include #define HID_REPORT_SIZE 65 @@ -30,11 +31,26 @@ enum class DeviceModel{ class Device { public: + + struct ErrorCounters{ + int wrong_CRC; + int CRC_other_than_awaited; + int busy; + int total_retries; + int sending_error; + int receiving_error; + int total_comm_runs; + int storage_commands; + int successful; + std::string get_as_string(); + } m_counters = {}; + + Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, const milliseconds send_receive_delay, const int retry_receiving_count, const milliseconds retry_timeout); - virtual ~Device(){disconnect();} + virtual ~Device(){show_stats(); disconnect();} // lack of device is not actually an error, // so it doesn't throw @@ -54,6 +70,8 @@ public: bool is_connected(); + void show_stats(); + ErrorCounters get_stats(){ return m_counters; } int get_retry_receiving_count() const { return m_retry_receiving_count; }; int get_retry_sending_count() const { return m_retry_sending_count; }; std::chrono::milliseconds get_retry_timeout() const { return m_retry_timeout; }; diff --git a/include/device_proto.h b/include/device_proto.h index 1e07277..e3a217d 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -221,6 +221,7 @@ namespace nitrokey { if (dev == nullptr){ throw DeviceNotConnected("Device not initialized"); } + dev->m_counters.total_comm_runs++; int status; OutgoingPacket outp; @@ -246,6 +247,7 @@ namespace nitrokey { if (status <= 0){ Log::instance()("Encountered communication error, disconnecting device", Loglevel::DEBUG_L2); dev->disconnect(); + dev->m_counters.sending_error++; throw DeviceSendingFailure( std::string("Device error while sending command ") + std::to_string(status)); @@ -263,6 +265,7 @@ namespace nitrokey { resp.command_id < stick20::CMD_END_VALUE ) { Log::instance()(std::string("Detected storage device cmd, status: ") + std::to_string(resp.storage_status.device_status), Loglevel::DEBUG_L2); + dev->m_counters.storage_commands++; resp.last_command_status = static_cast(stick10::command_status::ok); switch (static_cast(resp.storage_status.device_status)) { @@ -288,8 +291,9 @@ namespace nitrokey { //SENDPASSWORD gives wrong CRC , for now rely on !=0 (TODO report) // if (resp.device_status == 0 && resp.last_command_crc == outp.crc && resp.isCRCcorrect()) break; + auto CRC_equal_awaited = resp.last_command_crc == outp.crc; if (resp.device_status == static_cast(stick10::device_status::ok) && - resp.last_command_crc == outp.crc && resp.isValid()){ + CRC_equal_awaited && resp.isValid()){ successful_communication = true; break; } @@ -306,14 +310,19 @@ namespace nitrokey { } Log::instance()(std::string("Retry status - dev status, awaited cmd crc, correct packet CRC: ") + std::to_string(resp.device_status) + " " + - std::to_string(resp.last_command_crc == outp.crc) + + std::to_string(CRC_equal_awaited) + " " + std::to_string(resp.isCRCcorrect()), Loglevel::DEBUG_L2); + if (!resp.isCRCcorrect()) dev->m_counters.wrong_CRC++; + if (!CRC_equal_awaited) dev->m_counters.CRC_other_than_awaited++; + + Log::instance()( "Device is not ready or received packet's last CRC is not equal to sent CRC packet, retrying...", Loglevel::DEBUG); Log::instance()("Invalid incoming HID packet:", Loglevel::DEBUG_L2); Log::instance()(static_cast(resp), Loglevel::DEBUG_L2); + dev->m_counters.total_retries++; std::this_thread::sleep_for(dev->get_retry_timeout()); continue; } @@ -327,10 +336,12 @@ namespace nitrokey { clear_packet(outp); - if (status <= 0) + if (status <= 0) { + dev->m_counters.receiving_error++; throw DeviceReceivingFailure( //FIXME replace with CriticalErrorException std::string("Device error while executing command ") + std::to_string(status)); + } Log::instance()("Incoming HID packet:", Loglevel::DEBUG); Log::instance()(static_cast(resp), Loglevel::DEBUG); @@ -351,6 +362,7 @@ namespace nitrokey { if (resp.last_command_status != static_cast(stick10::command_status::ok)) throw CommandFailedException(resp.command_id, resp.last_command_status); + dev->m_counters.successful++; // See: DeviceResponse return resp; -- cgit v1.2.3 From 832ae0720e7ce2a9666baaf9b86c1c9b9c150697 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 4 Feb 2017 16:14:55 +0100 Subject: Allow device to reply 10 times with busy status in a try Signed-off-by: Szczepan Zalega --- include/device_proto.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/include/device_proto.h b/include/device_proto.h index e3a217d..ea740b3 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -298,9 +298,17 @@ namespace nitrokey { break; } if (resp.device_status == static_cast(stick10::device_status::busy)) { - receiving_retry_counter++; - Log::instance()("Status busy, not decresing receiving_retry_counter counter: " + - std::to_string(receiving_retry_counter), Loglevel::DEBUG_L2); + static int busy_counter = 0; + if (busy_counter++<10) { + receiving_retry_counter++; + dev->m_counters.busy++; + Log::instance()("Status busy, not decreasing receiving_retry_counter counter: " + + std::to_string(receiving_retry_counter), Loglevel::DEBUG_L2); + } else { + busy_counter = 0; + Log::instance()("Status busy, decreasing receiving_retry_counter counter: " + + std::to_string(receiving_retry_counter), Loglevel::DEBUG); + } } if (resp.device_status == static_cast(stick10::device_status::busy) && static_cast(resp.storage_status.device_status) -- cgit v1.2.3 From b16667ba57ef301ef961801676de66cce30d4c52 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 4 Feb 2017 16:16:03 +0100 Subject: Disable early device disconnection on communication error Signed-off-by: Szczepan Zalega --- include/device_proto.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/include/device_proto.h b/include/device_proto.h index ea740b3..cd91952 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -245,8 +245,9 @@ namespace nitrokey { while (sending_retry_counter-- > 0) { status = dev->send(&outp); if (status <= 0){ - Log::instance()("Encountered communication error, disconnecting device", Loglevel::DEBUG_L2); - dev->disconnect(); + //FIXME early disconnection not yet working properly +// Log::instance()("Encountered communication error, disconnecting device", Loglevel::DEBUG_L2); +// dev->disconnect(); dev->m_counters.sending_error++; throw DeviceSendingFailure( std::string("Device error while sending command ") + -- cgit v1.2.3 From fa02c23ee2f4bef6be8a502e11fc568dc74b4235 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 09:25:03 +0100 Subject: Use CMake instead of Make Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 23 ++++++++++++++++++----- unittest/test.cc | 1 - unittest/test2.cc | 1 - unittest/test3.cc | 5 ----- unittest/test_HOTP.cc | 3 +-- 5 files changed, 19 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c324067..aa6208e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,12 +29,25 @@ set(SOURCE_FILES misc.cc NitrokeyManager.cc NK_C_API.cc include/CommandFailedException.h include/LibraryException.h - unittest/test_C_API.cpp - unittest/catch_main.cpp - unittest/test2.cc - unittest/test3.cc include/LongOperationInProgressException.h include/stick10_commands_0.8.h ) -add_executable(libnitrokey ${SOURCE_FILES}) \ No newline at end of file +#add_library(libnitrokey STATIC ${SOURCE_FILES}) +add_library(nitrokey SHARED ${SOURCE_FILES}) +add_library(catch STATIC unittest/catch_main.cpp ) + +add_executable (test_C_API unittest/test_C_API.cpp) +target_link_libraries (test_C_API PUBLIC nitrokey catch) + +add_executable (test2 unittest/test2.cc) +target_link_libraries (test2 PUBLIC nitrokey catch) + +add_executable (test3 unittest/test3.cc) +target_link_libraries (test3 PUBLIC nitrokey catch) + +add_executable (test_HOTP unittest/test_HOTP.cc) +target_link_libraries (test_HOTP PUBLIC nitrokey catch) + +add_executable (test1 unittest/test.cc) +target_link_libraries (test1 PUBLIC nitrokey catch) diff --git a/unittest/test.cc b/unittest/test.cc index 99f96ac..15235bd 100644 --- a/unittest/test.cc +++ b/unittest/test.cc @@ -1,4 +1,3 @@ -#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #include "catch.hpp" #include diff --git a/unittest/test2.cc b/unittest/test2.cc index 4b61a3c..31dbce8 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -1,4 +1,3 @@ -#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() static const char *const default_admin_pin = "12345678"; static const char *const default_user_pin = "123456"; diff --git a/unittest/test3.cc b/unittest/test3.cc index 215df78..5302044 100644 --- a/unittest/test3.cc +++ b/unittest/test3.cc @@ -1,8 +1,3 @@ -// -// Created by sz on 08.11.16. -// - -#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() static const char *const default_admin_pin = "12345678"; static const char *const default_user_pin = "123456"; diff --git a/unittest/test_HOTP.cc b/unittest/test_HOTP.cc index c6b62a3..e6f7d7c 100644 --- a/unittest/test_HOTP.cc +++ b/unittest/test_HOTP.cc @@ -1,4 +1,3 @@ -#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #include "catch.hpp" #include #include "device_proto.h" @@ -14,7 +13,7 @@ using namespace nitrokey::log; using namespace nitrokey::misc; void hexStringToByte(uint8_t data[], const char* hexString){ - assert(strlen(hexString)%2==0); + REQUIRE(strlen(hexString)%2==0); char buf[2]; for(int i=0; i Date: Mon, 6 Feb 2017 10:53:08 +0100 Subject: Use alias for easy device change Signed-off-by: Szczepan Zalega --- unittest/test3.cc | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/unittest/test3.cc b/unittest/test3.cc index 5302044..9e0ef11 100644 --- a/unittest/test3.cc +++ b/unittest/test3.cc @@ -21,7 +21,8 @@ using namespace nitrokey::proto::stick10_08; using namespace nitrokey::log; using namespace nitrokey::misc; -using Dev10 = std::shared_ptr; +using Dev = Stick10; +using Dev10 = std::shared_ptr; void connect_and_setup(Dev10 stick) { bool connected = stick->connect(); @@ -42,7 +43,7 @@ void authorize(Dev10 stick) { } TEST_CASE("write slot", "[pronew]"){ - auto stick = make_shared(); + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); @@ -79,7 +80,7 @@ TEST_CASE("write slot", "[pronew]"){ TEST_CASE("erase slot", "[pronew]"){ - auto stick = make_shared(); + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); @@ -105,7 +106,7 @@ TEST_CASE("erase slot", "[pronew]"){ } TEST_CASE("write general config", "[pronew]") { - auto stick = make_shared(); + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); @@ -119,7 +120,7 @@ TEST_CASE("write general config", "[pronew]") { } TEST_CASE("authorize user HOTP", "[pronew]") { - auto stick = make_shared(); + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); @@ -162,7 +163,7 @@ TEST_CASE("authorize user HOTP", "[pronew]") { } TEST_CASE("check firmware version", "[pronew]") { - auto stick = make_shared(); + auto stick = make_shared(); connect_and_setup(stick); auto p = GetStatus::CommandTransaction::run(stick); @@ -170,7 +171,7 @@ TEST_CASE("check firmware version", "[pronew]") { } TEST_CASE("authorize user TOTP", "[pronew]") { - auto stick = make_shared(); + auto stick = make_shared(); connect_and_setup(stick); authorize(stick); -- cgit v1.2.3 From 761765b54cb160e4b9f51376aff29a83ff693596 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 10:54:07 +0100 Subject: Remove GCC specific settings. Make tests compilation optional. Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 67 ++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 23 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index aa6208e..fe1c755 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,14 +1,20 @@ cmake_minimum_required(VERSION 3.5) -project(libnitrokey) -set(CMAKE_CXX_COMPILER "/usr/bin/clang++-3.8" CACHE string "clang++ compiler" FORCE) +IF (UNIX) + OPTION(USE_CLANG "Use CLang" TRUE) + IF(USE_CLANG) + set(CMAKE_CXX_COMPILER "/usr/bin/clang++-3.8" CACHE string "clang++ compiler" FORCE) + ENDIF() +ENDIF() -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") -SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wno-gnu-variable-sized-type-not-at-end -g3" ) -SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lhidapi-libusb" ) +project(libnitrokey CXX) +set(CMAKE_CXX_STANDARD 14) -include_directories(include unittest/Catch/include) +#OPTION(COMPILE_TESTS "Compile tests" FALSE) +OPTION(COMPILE_TESTS "Compile tests" TRUE) +set(CMAKE_BUILD_TYPE RelWithDebInfo) +include_directories(include) set(SOURCE_FILES include/command.h include/command_id.h @@ -22,32 +28,47 @@ set(SOURCE_FILES include/NitrokeyManager.h include/stick10_commands.h include/stick20_commands.h - NK_C_API.h + include/CommandFailedException.h + include/LibraryException.h + include/LongOperationInProgressException.h + include/stick10_commands_0.8.h command_id.cc device.cc log.cc misc.cc NitrokeyManager.cc - NK_C_API.cc include/CommandFailedException.h include/LibraryException.h - include/LongOperationInProgressException.h - include/stick10_commands_0.8.h - ) + NK_C_API.h + NK_C_API.cc +) + -#add_library(libnitrokey STATIC ${SOURCE_FILES}) add_library(nitrokey SHARED ${SOURCE_FILES}) -add_library(catch STATIC unittest/catch_main.cpp ) +target_link_libraries(nitrokey hidapi-libusb) + +IF (COMPILE_TESTS) + include_directories(unittest/Catch/include) + + add_library(catch SHARED unittest/catch_main.cpp ) + + add_executable (test_C_API unittest/test_C_API.cpp) + target_link_libraries (test_C_API PUBLIC nitrokey catch) + + add_executable (test2 unittest/test2.cc) + target_link_libraries (test2 PUBLIC nitrokey catch) -add_executable (test_C_API unittest/test_C_API.cpp) -target_link_libraries (test_C_API PUBLIC nitrokey catch) + add_executable (test3 unittest/test3.cc) + target_link_libraries (test3 PUBLIC nitrokey catch) -add_executable (test2 unittest/test2.cc) -target_link_libraries (test2 PUBLIC nitrokey catch) + add_executable (test_HOTP unittest/test_HOTP.cc) + target_link_libraries (test_HOTP PUBLIC nitrokey catch) -add_executable (test3 unittest/test3.cc) -target_link_libraries (test3 PUBLIC nitrokey catch) + add_executable (test1 unittest/test.cc) + target_link_libraries (test1 PUBLIC nitrokey catch) -add_executable (test_HOTP unittest/test_HOTP.cc) -target_link_libraries (test_HOTP PUBLIC nitrokey catch) + #run with 'make test' or 'ctest' + #needs connected PRO device for success + #warning: it may delete data on the device + include (CTest) + add_test (runs test_C_API) +ENDIF() -add_executable (test1 unittest/test.cc) -target_link_libraries (test1 PUBLIC nitrokey catch) -- cgit v1.2.3 From 2d518b08787575914160ea0b1057c26d1d05b764 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 10:54:34 +0100 Subject: Remove Makefile Signed-off-by: Szczepan Zalega --- Makefile | 45 --------------------------------------------- unittest/Makefile | 33 --------------------------------- 2 files changed, 78 deletions(-) delete mode 100644 Makefile delete mode 100644 unittest/Makefile diff --git a/Makefile b/Makefile deleted file mode 100644 index 977eae6..0000000 --- a/Makefile +++ /dev/null @@ -1,45 +0,0 @@ -CC = $(PREFIX)-gcc -#CXX = $(PREFIX)-g++ -CXX = clang++-3.8 -LD = $(CXX) - -INCLUDE = -Iinclude/ -LIB = -lhidapi-libusb -BUILD = build - -CXXFLAGS = -std=c++14 -fPIC -Wno-gnu-variable-sized-type-not-at-end -SOFLAGS = -shared - -CXXSOURCES = $(wildcard *.cc) -OBJ = $(CXXSOURCES:%.cc=$(BUILD)/%.o) -DEPENDS = $(CXXSOURCES:%.cc=$(BUILD)/%.d) - -all: $(OBJ) $(BUILD)/libnitrokey.so unittest - -lib: $(OBJ) $(BUILD)/libnitrokey.so - -$(BUILD)/libnitrokey.so: $(OBJ) $(DEPENDS) - $(CXX) $(SOFLAGS) $(OBJ) $(LIB) -o $@ - -$(BUILD)/%.d: %.cc - $(CXX) -M $< -o $@ $(INCLUDE) $(CXXFLAGS) - -$(BUILD)/%.o: %.cc $(DEPENDS) - $(CXX) -c $< -o $@ $(INCLUDE) $(CXXFLAGS) - -clean: - rm -f $(OBJ) - rm -f $(BUILD)/libnitrokey.so - ${MAKE} -C unittest clean - -mrproper: clean - rm -f $(BUILD)/*.d - ${MAKE} -C unittest mrproper - -unittest: $(BUILD)/libnitrokey.so - ${MAKE} -C unittest - cd unittest/build && ln -fs ../../build/libnitrokey.so . - -.PHONY: all clean mrproper unittest - -include $(wildcard build/*.d) diff --git a/unittest/Makefile b/unittest/Makefile deleted file mode 100644 index dbd003e..0000000 --- a/unittest/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -CC = $(PREFIX)-gcc -#CXX = $(PREFIX)-g++ -CXX = clang++-3.8 -LD = $(CXX) - -INCLUDE = -I../include -ICatch/single_include/ -LIB = -L../build -LDLIBS = -lnitrokey -BUILD = build - -CXXFLAGS = -std=c++14 -fPIC -Wno-gnu-variable-sized-type-not-at-end - -CXXSOURCES = $(wildcard *.cc) -TARGETS = $(CXXSOURCES:%.cc=$(BUILD)/%) -DEPENDS = $(CXXSOURCES:%.cc=$(BUILD)/%.d) - -$(BUILD)/%.d: %.cc - $(CXX) -M $< -o $@ $(INCLUDE) $(CXXFLAGS) - -$(BUILD)/%: %.cc $(DEPENDS) - $(CXX) $< -o $@ $(INCLUDE) $(LIB) $(CXXFLAGS) $(LDLIBS) - -all: $(TARGETS) - -clean: - rm -f $(TARGETS) - -mrproper: clean - rm -f $(BUILD)/*.d - -.PHONY: all clean mrproper - -include $(wildcard build/*.d) -- cgit v1.2.3 From 473f1bf1854305c6ab5e926f369d07a37e081f3c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 11:29:02 +0100 Subject: Support ASAN and Clang optionally Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index fe1c755..21fe7ab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,19 +1,28 @@ cmake_minimum_required(VERSION 3.5) IF (UNIX) - OPTION(USE_CLANG "Use CLang" TRUE) + OPTION(ADD_ASAN "Use ASAN to show memory issues" FALSE) + OPTION(USE_CLANG "Use CLang" FALSE) IF(USE_CLANG) set(CMAKE_CXX_COMPILER "/usr/bin/clang++-3.8" CACHE string "clang++ compiler" FORCE) + ELSE() + set(CMAKE_CXX_COMPILER) + ENDIF() + IF(ADD_ASAN) + SET(EXTRA_LIBS ${EXTRA_LIBS} asan ) + ADD_DEFINITIONS(-fsanitize=address -fno-omit-frame-pointer) + # ADD_DEFINITIONS(-fsanitize=thread -fno-omit-frame-pointer -fPIE -pie -g) ENDIF() ENDIF() project(libnitrokey CXX) set(CMAKE_CXX_STANDARD 14) -#OPTION(COMPILE_TESTS "Compile tests" FALSE) -OPTION(COMPILE_TESTS "Compile tests" TRUE) +OPTION(COMPILE_TESTS "Compile tests" FALSE) set(CMAKE_BUILD_TYPE RelWithDebInfo) +MESSAGE("Build type: ${CMAKE_BUILD_TYPE}") + include_directories(include) set(SOURCE_FILES include/command.h @@ -51,19 +60,19 @@ IF (COMPILE_TESTS) add_library(catch SHARED unittest/catch_main.cpp ) add_executable (test_C_API unittest/test_C_API.cpp) - target_link_libraries (test_C_API PUBLIC nitrokey catch) + target_link_libraries (test_C_API ${EXTRA_LIBS} nitrokey catch) add_executable (test2 unittest/test2.cc) - target_link_libraries (test2 PUBLIC nitrokey catch) + target_link_libraries (test2 ${EXTRA_LIBS} nitrokey catch) add_executable (test3 unittest/test3.cc) - target_link_libraries (test3 PUBLIC nitrokey catch) + target_link_libraries (test3 ${EXTRA_LIBS} nitrokey catch) add_executable (test_HOTP unittest/test_HOTP.cc) - target_link_libraries (test_HOTP PUBLIC nitrokey catch) + target_link_libraries (test_HOTP ${EXTRA_LIBS} nitrokey catch) add_executable (test1 unittest/test.cc) - target_link_libraries (test1 PUBLIC nitrokey catch) + target_link_libraries (test1 ${EXTRA_LIBS} nitrokey catch) #run with 'make test' or 'ctest' #needs connected PRO device for success -- cgit v1.2.3 From 9c24f835372cc28d255557bd00f9d28598a07ebe Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 12:12:13 +0100 Subject: Build Release with debug info when none build type selected Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 21fe7ab..6ed4498 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,8 +19,9 @@ project(libnitrokey CXX) set(CMAKE_CXX_STANDARD 14) OPTION(COMPILE_TESTS "Compile tests" FALSE) -set(CMAKE_BUILD_TYPE RelWithDebInfo) - +IF (NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE RelWithDebInfo) +ENDIF() MESSAGE("Build type: ${CMAKE_BUILD_TYPE}") include_directories(include) -- cgit v1.2.3 From d93e321832d7e44b76d80d5c13814b7e151d10e9 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 12:12:57 +0100 Subject: Use CPack to generate packages Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6ed4498..4c37e31 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,6 @@ -cmake_minimum_required(VERSION 3.5) +SET(PROJECT_VERSION "3.0-alpha") +cmake_minimum_required(VERSION 3.5) IF (UNIX) OPTION(ADD_ASAN "Use ASAN to show memory issues" FALSE) OPTION(USE_CLANG "Use CLang" FALSE) @@ -55,6 +56,10 @@ set(SOURCE_FILES add_library(nitrokey SHARED ${SOURCE_FILES}) target_link_libraries(nitrokey hidapi-libusb) +install (TARGETS nitrokey DESTINATION "lib") +file(GLOB LIB_INCLUDES "include/libnitrokey/*.h") +install (FILES ${LIB_INCLUDES} DESTINATION "include") + IF (COMPILE_TESTS) include_directories(unittest/Catch/include) @@ -82,3 +87,10 @@ IF (COMPILE_TESTS) add_test (runs test_C_API) ENDIF() + +# build a CPack driven installer package +include (InstallRequiredSystemLibraries) +set (CPACK_RESOURCE_FILE_LICENSE + "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") +set (CPACK_PACKAGE_VERSION "${PROJECT_VERSION}") +include (CPack) \ No newline at end of file -- cgit v1.2.3 From 5f9927f86a8257ff3da8cdbbcd47de98ad09e7b6 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 13:24:32 +0100 Subject: Compile both dynamic and static library versions Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c37e31..b840e07 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,7 +54,9 @@ set(SOURCE_FILES add_library(nitrokey SHARED ${SOURCE_FILES}) +add_library(nitrokey-static STATIC ${SOURCE_FILES}) target_link_libraries(nitrokey hidapi-libusb) +target_link_libraries(nitrokey-static hidapi-libusb) install (TARGETS nitrokey DESTINATION "lib") file(GLOB LIB_INCLUDES "include/libnitrokey/*.h") -- cgit v1.2.3 From 08ecabdd888a322bd6499366be446d4d03443c1e Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 13:24:53 +0100 Subject: Fix project version Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b840e07..7f183ef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,3 @@ -SET(PROJECT_VERSION "3.0-alpha") - cmake_minimum_required(VERSION 3.5) IF (UNIX) OPTION(ADD_ASAN "Use ASAN to show memory issues" FALSE) @@ -17,13 +15,14 @@ IF (UNIX) ENDIF() project(libnitrokey CXX) +SET(PROJECT_VERSION "3.0-alpha") set(CMAKE_CXX_STANDARD 14) OPTION(COMPILE_TESTS "Compile tests" FALSE) IF (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE RelWithDebInfo) ENDIF() -MESSAGE("Build type: ${CMAKE_BUILD_TYPE}") +MESSAGE("${PROJECT_NAME}: Build type: ${CMAKE_BUILD_TYPE}") include_directories(include) set(SOURCE_FILES @@ -90,6 +89,8 @@ IF (COMPILE_TESTS) ENDIF() +#SET(CPACK_GENERATOR +# "DEB;RPM") # build a CPack driven installer package include (InstallRequiredSystemLibraries) set (CPACK_RESOURCE_FILE_LICENSE -- cgit v1.2.3 From 1792b8d6a843a79f5b333163bd74b99ac2cfdb30 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 14:06:02 +0100 Subject: Mark issues with FIXME Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 74a6ecf..6ce9910 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -522,7 +522,7 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; auto response = GetPasswordSafeSlotPassword::CommandTransaction::run(device, p); - return strdup((const char *) response.data().slot_password); + return strdup((const char *) response.data().slot_password); //FIXME use secure way } void NitrokeyManager::write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login, -- cgit v1.2.3 From 166b2e39f3815216871c0f505e9d879e11ca5080 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 15:36:07 +0100 Subject: Allow user to build only one version (static/dynamic) of the lib at once Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f183ef..715c61d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,6 +18,8 @@ project(libnitrokey CXX) SET(PROJECT_VERSION "3.0-alpha") set(CMAKE_CXX_STANDARD 14) +OPTION(LIBNITROKEY_STATIC "Build libnitrokey statically" TRUE) + OPTION(COMPILE_TESTS "Compile tests" FALSE) IF (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE RelWithDebInfo) @@ -52,12 +54,15 @@ set(SOURCE_FILES ) -add_library(nitrokey SHARED ${SOURCE_FILES}) -add_library(nitrokey-static STATIC ${SOURCE_FILES}) -target_link_libraries(nitrokey hidapi-libusb) -target_link_libraries(nitrokey-static hidapi-libusb) +IF (NOT LIBNITROKEY_STATIC) + add_library(nitrokey SHARED ${SOURCE_FILES}) + target_link_libraries(nitrokey hidapi-libusb) + install (TARGETS nitrokey DESTINATION "lib") +ELSE() + add_library(nitrokey-static STATIC ${SOURCE_FILES}) + target_link_libraries(nitrokey-static hidapi-libusb) +ENDIF() -install (TARGETS nitrokey DESTINATION "lib") file(GLOB LIB_INCLUDES "include/libnitrokey/*.h") install (FILES ${LIB_INCLUDES} DESTINATION "include") -- cgit v1.2.3 From 2781c2ed38d778c5bfd258678163949f3593a3e7 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 16:07:33 +0100 Subject: Support TSAN Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 715c61d..58443c0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,16 +1,20 @@ cmake_minimum_required(VERSION 3.5) IF (UNIX) - OPTION(ADD_ASAN "Use ASAN to show memory issues" FALSE) OPTION(USE_CLANG "Use CLang" FALSE) IF(USE_CLANG) set(CMAKE_CXX_COMPILER "/usr/bin/clang++-3.8" CACHE string "clang++ compiler" FORCE) ELSE() set(CMAKE_CXX_COMPILER) ENDIF() + OPTION(ADD_ASAN "Use ASAN to show memory issues" FALSE) + OPTION(ADD_TSAN "Use TSAN to show thread issues" FALSE) IF(ADD_ASAN) SET(EXTRA_LIBS ${EXTRA_LIBS} asan ) ADD_DEFINITIONS(-fsanitize=address -fno-omit-frame-pointer) - # ADD_DEFINITIONS(-fsanitize=thread -fno-omit-frame-pointer -fPIE -pie -g) + ENDIF() + IF(ADD_TSAN) + SET(EXTRA_LIBS ${EXTRA_LIBS} tsan ) + ADD_DEFINITIONS(-fsanitize=thread -fno-omit-frame-pointer -fPIE -pie -g) ENDIF() ENDIF() -- cgit v1.2.3 From 37da4df5995e0f8fa746c39e8d0ff83e32de03a9 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 16:14:57 +0100 Subject: Do not let to enable both ASAN and TSAN Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 58443c0..d44dba9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,6 +16,9 @@ IF (UNIX) SET(EXTRA_LIBS ${EXTRA_LIBS} tsan ) ADD_DEFINITIONS(-fsanitize=thread -fno-omit-frame-pointer -fPIE -pie -g) ENDIF() + IF(ADD_TSAN AND ADD_ASAN) + message(FATAL_ERROR "TSAN and ASAN cannot be used at the same time") + ENDIF() ENDIF() project(libnitrokey CXX) -- cgit v1.2.3 From 99b490a17d17611f7499eab84789fc9ba6e66885 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Feb 2017 18:30:21 +0100 Subject: For Clang use default compiler name Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d44dba9..57c3057 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.5) IF (UNIX) OPTION(USE_CLANG "Use CLang" FALSE) IF(USE_CLANG) - set(CMAKE_CXX_COMPILER "/usr/bin/clang++-3.8" CACHE string "clang++ compiler" FORCE) + set(CMAKE_CXX_COMPILER "/usr/bin/clang++" CACHE string "clang++ compiler" FORCE) ELSE() set(CMAKE_CXX_COMPILER) ENDIF() -- cgit v1.2.3 From c3aec5d004968c103a65398a1fd66f0d5ced63af Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 10 Feb 2017 12:39:25 +0100 Subject: Count all busy status Signed-off-by: Szczepan Zalega --- include/device_proto.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/device_proto.h b/include/device_proto.h index cd91952..cbb74fb 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -300,9 +300,9 @@ namespace nitrokey { } if (resp.device_status == static_cast(stick10::device_status::busy)) { static int busy_counter = 0; + dev->m_counters.busy++; if (busy_counter++<10) { receiving_retry_counter++; - dev->m_counters.busy++; Log::instance()("Status busy, not decreasing receiving_retry_counter counter: " + std::to_string(receiving_retry_counter), Loglevel::DEBUG_L2); } else { -- cgit v1.2.3 From c69604e8ba099b1421af86c34d904b0b380f996c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 9 Mar 2017 18:49:02 +0100 Subject: Test compilation under windows --- CMakeLists.txt | 31 ++-- hidapi | 1 + include/hidapi/hidapi.h | 391 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 412 insertions(+), 11 deletions(-) create mode 160000 hidapi create mode 100644 include/hidapi/hidapi.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 57c3057..2b9f580 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,7 @@ IF (UNIX) ENDIF() ENDIF() -project(libnitrokey CXX) +project(libnitrokey) SET(PROJECT_VERSION "3.0-alpha") set(CMAKE_CXX_STANDARD 14) @@ -33,6 +33,7 @@ IF (NOT CMAKE_BUILD_TYPE) ENDIF() MESSAGE("${PROJECT_NAME}: Build type: ${CMAKE_BUILD_TYPE}") +include_directories(hidapi) include_directories(include) set(SOURCE_FILES include/command.h @@ -60,15 +61,23 @@ set(SOURCE_FILES NK_C_API.cc ) +#IF(UNIX) +# add_library(hidapi-libusb STATIC hidapi/libusb/hid.c ) +#ELSE() + include_directories(hidapi/hidapi) + add_library(hidapi-libusb STATIC hidapi/windows/hid.c ) + target_link_libraries(hidapi-libusb setupapi setupapi kernel32 user32 gdi32 winspool comdlg32 advapi32 shell32 ole32 oleaut32 uuid odbc32 odbccp32) +#ENDIF() IF (NOT LIBNITROKEY_STATIC) add_library(nitrokey SHARED ${SOURCE_FILES}) - target_link_libraries(nitrokey hidapi-libusb) install (TARGETS nitrokey DESTINATION "lib") + SET(LIBNAME nitrokey) ELSE() - add_library(nitrokey-static STATIC ${SOURCE_FILES}) - target_link_libraries(nitrokey-static hidapi-libusb) + add_library(nitrokey-static STATIC ${SOURCE_FILES}) + SET(LIBNAME nitrokey-static) ENDIF() +target_link_libraries(${LIBNAME} hidapi-libusb) file(GLOB LIB_INCLUDES "include/libnitrokey/*.h") install (FILES ${LIB_INCLUDES} DESTINATION "include") @@ -76,22 +85,22 @@ install (FILES ${LIB_INCLUDES} DESTINATION "include") IF (COMPILE_TESTS) include_directories(unittest/Catch/include) - add_library(catch SHARED unittest/catch_main.cpp ) - + add_library(catch STATIC unittest/catch_main.cpp ) + add_executable (test_C_API unittest/test_C_API.cpp) - target_link_libraries (test_C_API ${EXTRA_LIBS} nitrokey catch) + target_link_libraries (test_C_API ${EXTRA_LIBS} ${LIBNAME} catch) add_executable (test2 unittest/test2.cc) - target_link_libraries (test2 ${EXTRA_LIBS} nitrokey catch) + target_link_libraries (test2 ${EXTRA_LIBS} ${LIBNAME} catch) add_executable (test3 unittest/test3.cc) - target_link_libraries (test3 ${EXTRA_LIBS} nitrokey catch) + target_link_libraries (test3 ${EXTRA_LIBS} ${LIBNAME} catch) add_executable (test_HOTP unittest/test_HOTP.cc) - target_link_libraries (test_HOTP ${EXTRA_LIBS} nitrokey catch) + target_link_libraries (test_HOTP ${EXTRA_LIBS} ${LIBNAME} catch) add_executable (test1 unittest/test.cc) - target_link_libraries (test1 ${EXTRA_LIBS} nitrokey catch) + target_link_libraries (test1 ${EXTRA_LIBS} ${LIBNAME} catch) #run with 'make test' or 'ctest' #needs connected PRO device for success diff --git a/hidapi b/hidapi new file mode 160000 index 0000000..a6a622f --- /dev/null +++ b/hidapi @@ -0,0 +1 @@ +Subproject commit a6a622ffb680c55da0de787ff93b80280498330f diff --git a/include/hidapi/hidapi.h b/include/hidapi/hidapi.h new file mode 100644 index 0000000..e5bc2dc --- /dev/null +++ b/include/hidapi/hidapi.h @@ -0,0 +1,391 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + Alan Ott + Signal 11 Software + + 8/22/2009 + + Copyright 2009, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + http://github.com/signal11/hidapi . +********************************************************/ + +/** @file + * @defgroup API hidapi API + */ + +#ifndef HIDAPI_H__ +#define HIDAPI_H__ + +#include + +#ifdef _WIN32 + #define HID_API_EXPORT __declspec(dllexport) + #define HID_API_CALL +#else + #define HID_API_EXPORT /**< API export macro */ + #define HID_API_CALL /**< API call macro */ +#endif + +#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/ + +#ifdef __cplusplus +extern "C" { +#endif + struct hid_device_; + typedef struct hid_device_ hid_device; /**< opaque hidapi structure */ + + /** hidapi info structure */ + struct hid_device_info { + /** Platform-specific device path */ + char *path; + /** Device Vendor ID */ + unsigned short vendor_id; + /** Device Product ID */ + unsigned short product_id; + /** Serial Number */ + wchar_t *serial_number; + /** Device Release Number in binary-coded decimal, + also known as Device Version Number */ + unsigned short release_number; + /** Manufacturer String */ + wchar_t *manufacturer_string; + /** Product string */ + wchar_t *product_string; + /** Usage Page for this Device/Interface + (Windows/Mac only). */ + unsigned short usage_page; + /** Usage for this Device/Interface + (Windows/Mac only).*/ + unsigned short usage; + /** The USB interface which this logical device + represents. Valid on both Linux implementations + in all cases, and valid on the Windows implementation + only if the device contains more than one interface. */ + int interface_number; + + /** Pointer to the next device */ + struct hid_device_info *next; + }; + + + /** @brief Initialize the HIDAPI library. + + This function initializes the HIDAPI library. Calling it is not + strictly necessary, as it will be called automatically by + hid_enumerate() and any of the hid_open_*() functions if it is + needed. This function should be called at the beginning of + execution however, if there is a chance of HIDAPI handles + being opened by different threads simultaneously. + + @ingroup API + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT HID_API_CALL hid_init(void); + + /** @brief Finalize the HIDAPI library. + + This function frees all of the static data associated with + HIDAPI. It should be called at the end of execution to avoid + memory leaks. + + @ingroup API + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT HID_API_CALL hid_exit(void); + + /** @brief Enumerate the HID Devices. + + This function returns a linked list of all the HID devices + attached to the system which match vendor_id and product_id. + If @p vendor_id is set to 0 then any vendor matches. + If @p product_id is set to 0 then any product matches. + If @p vendor_id and @p product_id are both set to 0, then + all HID devices will be returned. + + @ingroup API + @param vendor_id The Vendor ID (VID) of the types of device + to open. + @param product_id The Product ID (PID) of the types of + device to open. + + @returns + This function returns a pointer to a linked list of type + struct #hid_device, containing information about the HID devices + attached to the system, or NULL in the case of failure. Free + this linked list by calling hid_free_enumeration(). + */ + struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id); + + /** @brief Free an enumeration Linked List + + This function frees a linked list created by hid_enumerate(). + + @ingroup API + @param devs Pointer to a list of struct_device returned from + hid_enumerate(). + */ + void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs); + + /** @brief Open a HID device using a Vendor ID (VID), Product ID + (PID) and optionally a serial number. + + If @p serial_number is NULL, the first device with the + specified VID and PID is opened. + + @ingroup API + @param vendor_id The Vendor ID (VID) of the device to open. + @param product_id The Product ID (PID) of the device to open. + @param serial_number The Serial Number of the device to open + (Optionally NULL). + + @returns + This function returns a pointer to a #hid_device object on + success or NULL on failure. + */ + HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); + + /** @brief Open a HID device by its path name. + + The path name be determined by calling hid_enumerate(), or a + platform-specific path name can be used (eg: /dev/hidraw0 on + Linux). + + @ingroup API + @param path The path name of the device to open + + @returns + This function returns a pointer to a #hid_device object on + success or NULL on failure. + */ + HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path); + + /** @brief Write an Output report to a HID device. + + The first byte of @p data[] must contain the Report ID. For + devices which only support a single report, this must be set + to 0x0. The remaining bytes contain the report data. Since + the Report ID is mandatory, calls to hid_write() will always + contain one more byte than the report contains. For example, + if a hid report is 16 bytes long, 17 bytes must be passed to + hid_write(), the Report ID (or 0x0, for devices with a + single report), followed by the report data (16 bytes). In + this example, the length passed in would be 17. + + hid_write() will send the data on the first OUT endpoint, if + one exists. If it does not, it will send the data through + the Control Endpoint (Endpoint 0). + + @ingroup API + @param device A device handle returned from hid_open(). + @param data The data to send, including the report number as + the first byte. + @param length The length in bytes of the data to send. + + @returns + This function returns the actual number of bytes written and + -1 on error. + */ + int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length); + + /** @brief Read an Input report from a HID device with timeout. + + Input reports are returned + to the host through the INTERRUPT IN endpoint. The first byte will + contain the Report number if the device uses numbered reports. + + @ingroup API + @param device A device handle returned from hid_open(). + @param data A buffer to put the read data into. + @param length The number of bytes to read. For devices with + multiple reports, make sure to read an extra byte for + the report number. + @param milliseconds timeout in milliseconds or -1 for blocking wait. + + @returns + This function returns the actual number of bytes read and + -1 on error. If no packet was available to be read within + the timeout period, this function returns 0. + */ + int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds); + + /** @brief Read an Input report from a HID device. + + Input reports are returned + to the host through the INTERRUPT IN endpoint. The first byte will + contain the Report number if the device uses numbered reports. + + @ingroup API + @param device A device handle returned from hid_open(). + @param data A buffer to put the read data into. + @param length The number of bytes to read. For devices with + multiple reports, make sure to read an extra byte for + the report number. + + @returns + This function returns the actual number of bytes read and + -1 on error. If no packet was available to be read and + the handle is in non-blocking mode, this function returns 0. + */ + int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length); + + /** @brief Set the device handle to be non-blocking. + + In non-blocking mode calls to hid_read() will return + immediately with a value of 0 if there is no data to be + read. In blocking mode, hid_read() will wait (block) until + there is data to read before returning. + + Nonblocking can be turned on and off at any time. + + @ingroup API + @param device A device handle returned from hid_open(). + @param nonblock enable or not the nonblocking reads + - 1 to enable nonblocking + - 0 to disable nonblocking. + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock); + + /** @brief Send a Feature report to the device. + + Feature reports are sent over the Control endpoint as a + Set_Report transfer. The first byte of @p data[] must + contain the Report ID. For devices which only support a + single report, this must be set to 0x0. The remaining bytes + contain the report data. Since the Report ID is mandatory, + calls to hid_send_feature_report() will always contain one + more byte than the report contains. For example, if a hid + report is 16 bytes long, 17 bytes must be passed to + hid_send_feature_report(): the Report ID (or 0x0, for + devices which do not use numbered reports), followed by the + report data (16 bytes). In this example, the length passed + in would be 17. + + @ingroup API + @param device A device handle returned from hid_open(). + @param data The data to send, including the report number as + the first byte. + @param length The length in bytes of the data to send, including + the report number. + + @returns + This function returns the actual number of bytes written and + -1 on error. + */ + int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length); + + /** @brief Get a feature report from a HID device. + + Set the first byte of @p data[] to the Report ID of the + report to be read. Make sure to allow space for this + extra byte in @p data[]. Upon return, the first byte will + still contain the Report ID, and the report data will + start in data[1]. + + @ingroup API + @param device A device handle returned from hid_open(). + @param data A buffer to put the read data into, including + the Report ID. Set the first byte of @p data[] to the + Report ID of the report to be read, or set it to zero + if your device does not use numbered reports. + @param length The number of bytes to read, including an + extra byte for the report ID. The buffer can be longer + than the actual report. + + @returns + This function returns the number of bytes read plus + one for the report ID (which is still in the first + byte), or -1 on error. + */ + int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length); + + /** @brief Close a HID device. + + @ingroup API + @param device A device handle returned from hid_open(). + */ + void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device); + + /** @brief Get The Manufacturer String from a HID device. + + @ingroup API + @param device A device handle returned from hid_open(). + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen); + + /** @brief Get The Product String from a HID device. + + @ingroup API + @param device A device handle returned from hid_open(). + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen); + + /** @brief Get The Serial Number String from a HID device. + + @ingroup API + @param device A device handle returned from hid_open(). + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen); + + /** @brief Get a string from a HID device, based on its string index. + + @ingroup API + @param device A device handle returned from hid_open(). + @param string_index The index of the string to get. + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen); + + /** @brief Get a string describing the last error which occurred. + + @ingroup API + @param device A device handle returned from hid_open(). + + @returns + This function returns a string containing the last error + which occurred or NULL if none has occurred. + */ + HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device); + +#ifdef __cplusplus +} +#endif + +#endif + -- cgit v1.2.3 From adbc664125142c434294bfa795666c90c7608429 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 9 Mar 2017 18:49:24 +0100 Subject: Adjust for compilation on Visual Studio 2017 Building works however tests are not. Possibly linking with original hidapi solution would work. --- .gitignore | 1 + CMakeLists.txt | 4 ++-- CMakeSettings.json | 37 +++++++++++++++++++++++++++++++++++++ NK_C_API.cc | 4 ++-- NitrokeyManager.cc | 12 ++++++------ device.cc | 12 ++++++------ include/LibraryException.h | 2 +- include/command.h | 7 +++++-- include/cxx_semantics.h | 4 ++++ include/device_proto.h | 8 +++++--- include/misc.h | 2 +- include/stick10_commands.h | 8 ++++++++ include/stick20_commands.h | 5 +++++ misc.cc | 11 ++++++----- 14 files changed, 89 insertions(+), 28 deletions(-) create mode 100644 CMakeSettings.json diff --git a/.gitignore b/.gitignore index 47b7703..c98c3a9 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ core .cache/ .idea/ CMakeFiles/ +/.vs diff --git a/CMakeLists.txt b/CMakeLists.txt index 2b9f580..e77de6e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -65,7 +65,7 @@ set(SOURCE_FILES # add_library(hidapi-libusb STATIC hidapi/libusb/hid.c ) #ELSE() include_directories(hidapi/hidapi) - add_library(hidapi-libusb STATIC hidapi/windows/hid.c ) + add_library(hidapi-libusb SHARED hidapi/windows/hid.c ) target_link_libraries(hidapi-libusb setupapi setupapi kernel32 user32 gdi32 winspool comdlg32 advapi32 shell32 ole32 oleaut32 uuid odbc32 odbccp32) #ENDIF() @@ -85,7 +85,7 @@ install (FILES ${LIB_INCLUDES} DESTINATION "include") IF (COMPILE_TESTS) include_directories(unittest/Catch/include) - add_library(catch STATIC unittest/catch_main.cpp ) + add_library(catch SHARED unittest/catch_main.cpp ) add_executable (test_C_API unittest/test_C_API.cpp) target_link_libraries (test_C_API ${EXTRA_LIBS} ${LIBNAME} catch) diff --git a/CMakeSettings.json b/CMakeSettings.json new file mode 100644 index 0000000..e8c1f1d --- /dev/null +++ b/CMakeSettings.json @@ -0,0 +1,37 @@ +{ + // See https://go.microsoft.com//fwlink//?linkid=834763 for more information about this file. + "configurations": [ + { + "name": "x86-Debug", + "generator": "Visual Studio 15 2017", + "configurationType" : "Debug", + "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", + "cmakeCommandArgs": "", + "buildCommandArgs": "-m -v:minimal" + }, + { + "name": "x86-Release", + "generator": "Visual Studio 15 2017", + "configurationType" : "Release", + "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", + "cmakeCommandArgs": "", + "buildCommandArgs": "-m -v:minimal" + }, + { + "name": "x64-Debug", + "generator": "Visual Studio 15 2017 Win64", + "configurationType" : "Debug", + "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", + "cmakeCommandArgs": "", + "buildCommandArgs": "-m -v:minimal" + }, + { + "name": "x64-Release", + "generator": "Visual Studio 15 2017 Win64", + "configurationType" : "Release", + "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", + "cmakeCommandArgs": "", + "buildCommandArgs": "-m -v:minimal" + } + ] +} \ No newline at end of file diff --git a/NK_C_API.cc b/NK_C_API.cc index 6d18e52..4e53cd1 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -169,7 +169,7 @@ extern const char * NK_status() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ string && s = m->get_status_as_string(); - char * rs = strdup(s.c_str()); + char * rs = _strdup(s.c_str()); clear_string(s); return rs; }); @@ -179,7 +179,7 @@ extern const char * NK_device_serial_number(){ auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ string && s = m->get_serial_number(); - char * rs = strdup(s.c_str()); + char * rs = _strdup(s.c_str()); clear_string(s); return rs; }); diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 6ce9910..a120085 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -397,7 +397,7 @@ namespace nitrokey{ auto payload = get_payload(); payload.slot_number = slot_number; auto resp = GetSlotName::CommandTransaction::run(device, payload); - return strdup((const char *) resp.data().slot_name); + return _strdup((const char *) resp.data().slot_name); } bool NitrokeyManager::first_authenticate(const char *pin, const char *temporary_password) { @@ -504,7 +504,7 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; auto response = GetPasswordSafeSlotName::CommandTransaction::run(device, p); - return strdup((const char *) response.data().slot_name); + return _strdup((const char *) response.data().slot_name); } bool NitrokeyManager::is_valid_password_safe_slot_number(uint8_t slot_number) const { return slot_number < 16; } @@ -514,7 +514,7 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; auto response = GetPasswordSafeSlotLogin::CommandTransaction::run(device, p); - return strdup((const char *) response.data().slot_login); + return _strdup((const char *) response.data().slot_login); } const char *NitrokeyManager::get_password_safe_slot_password(uint8_t slot_number) { @@ -522,7 +522,7 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; auto response = GetPasswordSafeSlotPassword::CommandTransaction::run(device, p); - return strdup((const char *) response.data().slot_password); //FIXME use secure way + return _strdup((const char *) response.data().slot_password); //FIXME use secure way } void NitrokeyManager::write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login, @@ -724,7 +724,7 @@ namespace nitrokey{ const char * NitrokeyManager::get_status_storage_as_string(){ auto p = stick20::GetDeviceStatus::CommandTransaction::run(device); - return strdup(p.data().dissect().c_str()); + return _strdup(p.data().dissect().c_str()); } stick20::DeviceConfigurationResponsePacket::ResponsePayload NitrokeyManager::get_status_storage(){ @@ -734,7 +734,7 @@ namespace nitrokey{ const char * NitrokeyManager::get_SD_usage_data_as_string(){ auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(device); - return strdup(p.data().dissect().c_str()); + return _strdup(p.data().dissect().c_str()); } int NitrokeyManager::get_progress_bar_value(){ diff --git a/device.cc b/device.cc index d904fd9..0111572 100644 --- a/device.cc +++ b/device.cc @@ -2,7 +2,7 @@ #include #include #include -#include +#include "hidapi/hidapi.h" #include "include/misc.h" #include "include/device.h" #include "include/log.h" @@ -31,7 +31,7 @@ Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, bool Device::disconnect() { //called in object's destructor - Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); Log::instance()(std::string(__FUNCTION__) + std::string(m_model==DeviceModel::PRO?"PRO":"STORAGE"), Loglevel::DEBUG_L2); Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); @@ -45,7 +45,7 @@ bool Device::disconnect() { return true; } bool Device::connect() { - Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); @@ -57,7 +57,7 @@ bool Device::connect() { } int Device::send(const void *packet) { - Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); @@ -71,7 +71,7 @@ int Device::send(const void *packet) { } int Device::recv(void *packet) { - Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); int status; @@ -115,7 +115,7 @@ int Device::recv(void *packet) { } bool Device::is_connected() { - Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); if (mp_devhandle==nullptr){ return false; diff --git a/include/LibraryException.h b/include/LibraryException.h index e62788d..daf0155 100644 --- a/include/LibraryException.h +++ b/include/LibraryException.h @@ -27,7 +27,7 @@ public: virtual const char *what() const throw() override { std::string s = " "; - auto ts = [](int x){ return std::to_string(x); }; + auto ts = [](size_t x){ return std::to_string(x); }; std::string msg = std::string("Target buffer size is smaller than source: [source size, buffer size]") +s+ ts(source_size) +s+ ts(target_size); return msg.c_str(); diff --git a/include/command.h b/include/command.h index 0a875e4..fc374f7 100644 --- a/include/command.h +++ b/include/command.h @@ -28,6 +28,7 @@ namespace stick20{ template class PasswordCommand : public Command { + constexpr static CommandID _command_id() { return cmd_id; } public: struct CommandPayload { uint8_t kind; @@ -69,8 +70,10 @@ namespace stick20{ } __packed; - typedef Transaction::command_id(), struct CommandPayload, struct EmptyPayload> - CommandTransaction; + //typedef Transaction::command_id(), struct CommandPayload, struct EmptyPayload> + // CommandTransaction; + using CommandTransaction = Transaction; + //using CommandTransaction = Transaction<_command_id(), CommandPayload, EmptyPayload>; }; } diff --git a/include/cxx_semantics.h b/include/cxx_semantics.h index b846317..29e51c3 100644 --- a/include/cxx_semantics.h +++ b/include/cxx_semantics.h @@ -1,7 +1,11 @@ #ifndef CXX_SEMANTICS_H #define CXX_SEMANTICS_H +#ifndef _WINDOWS #define __packed __attribute__((__packed__)) +#else +#define __packed +#endif /* * There's no need to include Boost for a simple subset this project needs. diff --git a/include/device_proto.h b/include/device_proto.h index cbb74fb..1e381dd 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -6,7 +6,6 @@ #include #include #include -#include // a local version for compatibility with Windows #include #include "cxx_semantics.h" @@ -34,6 +33,7 @@ #include #include "DeviceCommunicationExceptions.h" +#define bzero(b,len) (memset((b), '\0', (len)), (void) 0) namespace nitrokey { namespace proto { @@ -43,7 +43,7 @@ namespace nitrokey { * * TODO (future) support for Big Endian */ - +#pragma pack (push,1) /* * Every packet is a USB HID report (check USB spec) */ @@ -181,8 +181,10 @@ namespace nitrokey { typedef command_payload CommandPayload; typedef response_payload ResponsePayload; + typedef struct HIDReport OutgoingPacket; typedef struct DeviceResponse ResponsePacket; +#pragma pack (pop) static_assert(std::is_pod::value, "outgoingpacket must be a pod type"); @@ -216,7 +218,7 @@ namespace nitrokey { static std::mutex send_receive_mtx; std::lock_guard guard(send_receive_mtx); - Log::instance()(__PRETTY_FUNCTION__, Loglevel::DEBUG_L2); + Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); if (dev == nullptr){ throw DeviceNotConnected("Device not initialized"); diff --git a/include/misc.h b/include/misc.h index 9e4659d..330654a 100644 --- a/include/misc.h +++ b/include/misc.h @@ -27,7 +27,7 @@ namespace misc { strncpy((char*) &dest, src, s_dest); } - +#define bzero(b,len) (memset((b), '\0', (len)), (void) 0) template typename T::CommandPayload get_payload(){ //Create, initialize and return by value command payload diff --git a/include/stick10_commands.h b/include/stick10_commands.h index 8d37dbd..3d9e234 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -1,5 +1,6 @@ #ifndef STICK10_COMMANDS_H #define STICK10_COMMANDS_H + #include #include #include @@ -8,9 +9,13 @@ #include "command.h" #include "device_proto.h" +#pragma pack (push,1) + namespace nitrokey { namespace proto { + + /* * Stick10 protocol definition */ @@ -844,8 +849,11 @@ class BuildAESKey : Command { typedef Transaction CommandTransaction; + }; + } } } +#pragma pack (pop) #endif diff --git a/include/stick20_commands.h b/include/stick20_commands.h index b887636..e3bea3f 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -1,12 +1,15 @@ #ifndef STICK20_COMMANDS_H #define STICK20_COMMANDS_H + + #include #include "command.h" #include #include #include "device_proto.h" +#pragma pack (push,1) namespace nitrokey { namespace proto { @@ -332,10 +335,12 @@ namespace nitrokey { typedef Transaction CommandTransaction; }; + } } } #undef print_to_ss +#pragma pack (pop) #endif diff --git a/misc.cc b/misc.cc index a76bfb6..f85d486 100644 --- a/misc.cc +++ b/misc.cc @@ -5,18 +5,19 @@ #include #include #include "LibraryException.h" +#include namespace nitrokey { namespace misc { -std::vector hex_string_to_byte(const char* hexString){ +::std::vector hex_string_to_byte(const char* hexString){ const size_t big_string_size = 256; //arbitrary 'big' number const size_t s_size = strlen(hexString); const size_t d_size = s_size/2; if (s_size%2!=0 || s_size>big_string_size){ throw InvalidHexString(0); } - auto data = std::vector(); + auto data = ::std::vector(); data.reserve(d_size); char buf[2]; @@ -36,9 +37,9 @@ std::vector hex_string_to_byte(const char* hexString){ }; #include -std::string hexdump(const char *p, size_t size, bool print_header, +::std::string hexdump(const char *p, size_t size, bool print_header, bool print_ascii, bool print_empty) { - std::stringstream out; + ::std::stringstream out; char formatbuf[128]; const char *pstart = p; @@ -68,7 +69,7 @@ std::string hexdump(const char *p, size_t size, bool print_header, out << '.'; } } - out << std::endl; + out << ::std::endl; } return out.str(); } -- cgit v1.2.3 From 6ee68fa294d1d9ab8fa8e61a009845dc31a9b771 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 14 Feb 2017 11:53:25 +0100 Subject: Compiles on MXE, but not working on Windows Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 10 +++++----- NK_C_API.cc | 4 ++-- NitrokeyManager.cc | 12 ++++++------ hidapi | 2 +- include/device.h | 2 +- include/log.h | 4 ++++ 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e77de6e..89ab66d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -61,13 +61,13 @@ set(SOURCE_FILES NK_C_API.cc ) -#IF(UNIX) +IF(UNIX) # add_library(hidapi-libusb STATIC hidapi/libusb/hid.c ) -#ELSE() +ELSEIF(WIN32) include_directories(hidapi/hidapi) - add_library(hidapi-libusb SHARED hidapi/windows/hid.c ) - target_link_libraries(hidapi-libusb setupapi setupapi kernel32 user32 gdi32 winspool comdlg32 advapi32 shell32 ole32 oleaut32 uuid odbc32 odbccp32) -#ENDIF() + add_library(hidapi-libusb STATIC hidapi/windows/hid.c ) + target_link_libraries(hidapi-libusb setupapi) +ENDIF() IF (NOT LIBNITROKEY_STATIC) add_library(nitrokey SHARED ${SOURCE_FILES}) diff --git a/NK_C_API.cc b/NK_C_API.cc index 4e53cd1..6d18e52 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -169,7 +169,7 @@ extern const char * NK_status() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ string && s = m->get_status_as_string(); - char * rs = _strdup(s.c_str()); + char * rs = strdup(s.c_str()); clear_string(s); return rs; }); @@ -179,7 +179,7 @@ extern const char * NK_device_serial_number(){ auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ string && s = m->get_serial_number(); - char * rs = _strdup(s.c_str()); + char * rs = strdup(s.c_str()); clear_string(s); return rs; }); diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index a120085..6ce9910 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -397,7 +397,7 @@ namespace nitrokey{ auto payload = get_payload(); payload.slot_number = slot_number; auto resp = GetSlotName::CommandTransaction::run(device, payload); - return _strdup((const char *) resp.data().slot_name); + return strdup((const char *) resp.data().slot_name); } bool NitrokeyManager::first_authenticate(const char *pin, const char *temporary_password) { @@ -504,7 +504,7 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; auto response = GetPasswordSafeSlotName::CommandTransaction::run(device, p); - return _strdup((const char *) response.data().slot_name); + return strdup((const char *) response.data().slot_name); } bool NitrokeyManager::is_valid_password_safe_slot_number(uint8_t slot_number) const { return slot_number < 16; } @@ -514,7 +514,7 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; auto response = GetPasswordSafeSlotLogin::CommandTransaction::run(device, p); - return _strdup((const char *) response.data().slot_login); + return strdup((const char *) response.data().slot_login); } const char *NitrokeyManager::get_password_safe_slot_password(uint8_t slot_number) { @@ -522,7 +522,7 @@ namespace nitrokey{ auto p = get_payload(); p.slot_number = slot_number; auto response = GetPasswordSafeSlotPassword::CommandTransaction::run(device, p); - return _strdup((const char *) response.data().slot_password); //FIXME use secure way + return strdup((const char *) response.data().slot_password); //FIXME use secure way } void NitrokeyManager::write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login, @@ -724,7 +724,7 @@ namespace nitrokey{ const char * NitrokeyManager::get_status_storage_as_string(){ auto p = stick20::GetDeviceStatus::CommandTransaction::run(device); - return _strdup(p.data().dissect().c_str()); + return strdup(p.data().dissect().c_str()); } stick20::DeviceConfigurationResponsePacket::ResponsePayload NitrokeyManager::get_status_storage(){ @@ -734,7 +734,7 @@ namespace nitrokey{ const char * NitrokeyManager::get_SD_usage_data_as_string(){ auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(device); - return _strdup(p.data().dissect().c_str()); + return strdup(p.data().dissect().c_str()); } int NitrokeyManager::get_progress_bar_value(){ diff --git a/hidapi b/hidapi index a6a622f..69c45b0 160000 --- a/hidapi +++ b/hidapi @@ -1 +1 @@ -Subproject commit a6a622ffb680c55da0de787ff93b80280498330f +Subproject commit 69c45b083821037667a9409b952282f9cb4dcca2 diff --git a/include/device.h b/include/device.h index a23e1b3..281c4d9 100644 --- a/include/device.h +++ b/include/device.h @@ -1,7 +1,7 @@ #ifndef DEVICE_H #define DEVICE_H #include -#include +#include "hidapi/hidapi.h" #include #include diff --git a/include/log.h b/include/log.h index 8eda4fb..0b0df8c 100644 --- a/include/log.h +++ b/include/log.h @@ -6,6 +6,10 @@ namespace nitrokey { namespace log { +#ifdef ERROR +#undef ERROR +#endif + enum class Loglevel : int { DEBUG_L2, DEBUG, INFO, WARNING, ERROR }; class LogHandler { -- cgit v1.2.3 From fd254e6789bfc00467c94bd210434dc74a7c1f6a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 16 Feb 2017 11:30:25 +0100 Subject: Hidapi added as a submodule Signed-off-by: Szczepan Zalega --- .gitmodules | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitmodules b/.gitmodules index 6e2a0ec..4c898f5 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "pybind11"] path = python_bindings/pybind11 url = https://github.com/pybind/pybind11.git +[submodule "hidapi"] + path = hidapi + url = git@github.com:szszszsz/hidapi.git -- cgit v1.2.3 From a0df25c10bfc21574d474547bf2f25372bdbb417 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 16 Feb 2017 12:29:28 +0100 Subject: Rename strdup to _strdup under MSVC Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 1 + NitrokeyManager.cc | 2 ++ include/cxx_semantics.h | 6 +++++- 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index 6d18e52..0fde829 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -1,6 +1,7 @@ #include #include "NK_C_API.h" #include "include/LibraryException.h" +#include "include/cxx_semantics.h" using namespace nitrokey; diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 6ce9910..fa32557 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -7,6 +7,8 @@ #include #include "include/misc.h" #include +#include "include/cxx_semantics.h" + namespace nitrokey{ diff --git a/include/cxx_semantics.h b/include/cxx_semantics.h index 29e51c3..f358e8f 100644 --- a/include/cxx_semantics.h +++ b/include/cxx_semantics.h @@ -1,12 +1,16 @@ #ifndef CXX_SEMANTICS_H #define CXX_SEMANTICS_H -#ifndef _WINDOWS +#ifndef _MSC_VER #define __packed __attribute__((__packed__)) #else #define __packed #endif +#ifdef _MSC_VER +#define strdup _strdup +#endif + /* * There's no need to include Boost for a simple subset this project needs. */ -- cgit v1.2.3 From 3d96df28fe95deb096a19e3886381ef360b978d8 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 16 Feb 2017 17:48:13 +0100 Subject: Correct device counters Signed-off-by: Szczepan Zalega --- device.cc | 21 +++++++++++++++------ include/device.h | 29 +++++++++++++++++++---------- include/device_proto.h | 18 +++++++++++++++--- 3 files changed, 49 insertions(+), 19 deletions(-) diff --git a/device.cc b/device.cc index 0111572..facdc3e 100644 --- a/device.cc +++ b/device.cc @@ -150,14 +150,23 @@ Stick20::Stick20(): #define p(x) ss << #x << " " << x << ", "; std::string Device::ErrorCounters::get_as_string() { std::stringstream ss; - p(wrong_CRC); - p(CRC_other_than_awaited); - p(busy); + p(total_comm_runs); + p(communication_successful); + ss << "("; + p(command_successful_recv); + p(command_result_not_equal_0_recv); + ss << "), "; + p(sends_executed); + p(recv_executed); + p(successful_storage_commands); p(total_retries); + ss << "("; + p(busy); + p(busy_progressbar); + p(CRC_other_than_awaited); + p(wrong_CRC); + ss << "), "; p(sending_error); p(receiving_error); - p(total_comm_runs); - p(storage_commands); - p(successful ); return ss.str(); } diff --git a/include/device.h b/include/device.h index 281c4d9..40eb376 100644 --- a/include/device.h +++ b/include/device.h @@ -28,21 +28,30 @@ enum class DeviceModel{ STORAGE }; +#include + class Device { public: struct ErrorCounters{ - int wrong_CRC; - int CRC_other_than_awaited; - int busy; - int total_retries; - int sending_error; - int receiving_error; - int total_comm_runs; - int storage_commands; - int successful; + using cnt = std::atomic_int; + cnt wrong_CRC; + cnt CRC_other_than_awaited; + cnt busy; + cnt total_retries; + cnt sending_error; + cnt receiving_error; + cnt total_comm_runs; + cnt successful_storage_commands; + cnt command_successful_recv; + cnt recv_executed; + cnt sends_executed; + cnt busy_progressbar; + cnt command_result_not_equal_0_recv; + cnt communication_successful; std::string get_as_string(); + } m_counters = {}; @@ -71,7 +80,7 @@ public: bool is_connected(); void show_stats(); - ErrorCounters get_stats(){ return m_counters; } +// ErrorCounters get_stats(){ return m_counters; } int get_retry_receiving_count() const { return m_retry_receiving_count; }; int get_retry_sending_count() const { return m_retry_sending_count; }; std::chrono::milliseconds get_retry_timeout() const { return m_retry_timeout; }; diff --git a/include/device_proto.h b/include/device_proto.h index 1e381dd..3519123 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -245,6 +245,7 @@ namespace nitrokey { int receiving_retry_counter = 0; int sending_retry_counter = dev->get_retry_sending_count(); while (sending_retry_counter-- > 0) { + dev->m_counters.sends_executed++; status = dev->send(&outp); if (status <= 0){ //FIXME early disconnection not yet working properly @@ -261,6 +262,7 @@ namespace nitrokey { // FIXME make checks done in device:recv here receiving_retry_counter = dev->get_retry_receiving_count(); while (receiving_retry_counter-- > 0) { + dev->m_counters.recv_executed++; status = dev->recv(&resp); if (dev->get_device_model() == DeviceModel::STORAGE && @@ -268,7 +270,6 @@ namespace nitrokey { resp.command_id < stick20::CMD_END_VALUE ) { Log::instance()(std::string("Detected storage device cmd, status: ") + std::to_string(resp.storage_status.device_status), Loglevel::DEBUG_L2); - dev->m_counters.storage_commands++; resp.last_command_status = static_cast(stick10::command_status::ok); switch (static_cast(resp.storage_status.device_status)) { @@ -362,6 +363,7 @@ namespace nitrokey { if (resp.device_status == static_cast(stick10::device_status::busy) && static_cast(resp.storage_status.device_status) == stick20::device_status::busy_progressbar){ + dev->m_counters.busy_progressbar++; throw LongOperationInProgressException( resp.command_id, resp.device_status, resp.storage_status.progress_bar_value); } @@ -370,10 +372,20 @@ namespace nitrokey { if (receiving_retry_counter <= 0) throw std::runtime_error( "Maximum receiving_retry_counter count reached for receiving response from the device!"); - if (resp.last_command_status != static_cast(stick10::command_status::ok)) + dev->m_counters.communication_successful++; + + if (resp.last_command_status != static_cast(stick10::command_status::ok)){ + dev->m_counters.command_result_not_equal_0_recv++; throw CommandFailedException(resp.command_id, resp.last_command_status); + } - dev->m_counters.successful++; + dev->m_counters.command_successful_recv++; + + if (dev->get_device_model() == DeviceModel::STORAGE && + resp.command_id >= stick20::CMD_START_VALUE && + resp.command_id < stick20::CMD_END_VALUE ) { + dev->m_counters.successful_storage_commands++; + } // See: DeviceResponse return resp; -- cgit v1.2.3 From c8ac8481134aaf8d04e4e8ece266d43472034157 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 16 Feb 2017 21:46:49 +0100 Subject: Handle disconnection while requesting device's status Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index fa32557..57ef878 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -144,8 +144,14 @@ namespace nitrokey{ } stick10::GetStatus::ResponsePayload NitrokeyManager::get_status(){ - auto response = GetStatus::CommandTransaction::run(device); - return response.data(); + try{ + auto response = GetStatus::CommandTransaction::run(device); + return response.data(); + } + catch (DeviceSendingFailure &e){ + disconnect(); + throw; + } } string NitrokeyManager::get_status_as_string() { -- cgit v1.2.3 From bb72ba6d7850d46df3a9959fa2598e7aadf0fd89 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 16 Feb 2017 21:47:36 +0100 Subject: Do not call hid_exit on each device disconnection Signed-off-by: Szczepan Zalega --- device.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/device.cc b/device.cc index facdc3e..dcba735 100644 --- a/device.cc +++ b/device.cc @@ -41,7 +41,8 @@ bool Device::disconnect() { hid_close(mp_devhandle); mp_devhandle = nullptr; - hid_exit(); + //FIXME hidexit should not be called if some devices are still active - use static active devices counter + // hid_exit(); return true; } bool Device::connect() { -- cgit v1.2.3 From 5a5205a0591757919a1ff4cbe31cda3b427fa19f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 16 Feb 2017 21:47:57 +0100 Subject: Fix typos Signed-off-by: Szczepan Zalega --- device.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/device.cc b/device.cc index dcba735..32869ae 100644 --- a/device.cc +++ b/device.cc @@ -100,10 +100,10 @@ int Device::recv(void *packet) { if (status > 0) break; // success if (retry_count++ >= m_retry_receiving_count) { Log::instance()( - "Maximum retry count reached" + std::to_string(retry_count), + "Maximum retry count reached: " + std::to_string(retry_count), Loglevel::WARNING); Log::instance()( - std::string("Counter stats") + m_counters.get_as_string(), + std::string("Counter stats: ") + m_counters.get_as_string(), Loglevel::DEBUG); break; } -- cgit v1.2.3 From bf63972b2f9c90180d491f5ad314702fa7b8051f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 16 Feb 2017 21:48:25 +0100 Subject: Decrease retry count in the lowest level Signed-off-by: Szczepan Zalega --- device.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/device.cc b/device.cc index 32869ae..8fdf99a 100644 --- a/device.cc +++ b/device.cc @@ -139,12 +139,12 @@ void Device::show_stats() { } Stick10::Stick10(): - Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 20, 100ms) + Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 5, 100ms) {} Stick20::Stick20(): - Device(0x20a0, 0x4109, DeviceModel::STORAGE, 200ms, 40, 200ms) + Device(0x20a0, 0x4109, DeviceModel::STORAGE, 200ms, 5, 200ms) {} #include -- cgit v1.2.3 From 8617a13371d087b1eb67bd066926038d289ab331 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 17 Feb 2017 09:27:38 +0100 Subject: Handle SD card related functions Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 10 ++++++++++ include/NitrokeyManager.h | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 57ef878..176f516 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -745,6 +745,11 @@ namespace nitrokey{ return strdup(p.data().dissect().c_str()); } + std::pair NitrokeyManager::get_SD_usage_data(){ + auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(device); + return std::make_pair(p.data().WriteLevelMin, p.data().WriteLevelMax); + } + int NitrokeyManager::get_progress_bar_value(){ try{ stick20::GetDeviceStatus::CommandTransaction::run(device); @@ -782,4 +787,9 @@ namespace nitrokey{ misc::execute_password_command(device, ""); } + int NitrokeyManager::get_SD_card_size() { + auto data = stick20::ProductionTest::CommandTransaction::run(device); + return data.data().SD_Card_Size_u8; + } + } diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index b89db63..2200955 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -106,6 +106,8 @@ namespace nitrokey { void fill_SD_card_with_random_data(const char *admin_pin); + int get_SD_card_size(); + void change_update_password(const char *current_update_password, const char *new_update_password); void create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent, @@ -117,8 +119,10 @@ namespace nitrokey { stick20::DeviceConfigurationResponsePacket::ResponsePayload get_status_storage(); const char *get_SD_usage_data_as_string(); + std::pair get_SD_usage_data(); + - int get_progress_bar_value(); + int get_progress_bar_value(); ~NitrokeyManager(); bool is_authorization_command_supported(); @@ -159,6 +163,7 @@ namespace nitrokey { const char *temporary_password) const; bool _disconnect_no_lock(); + }; } -- cgit v1.2.3 From 4e26fdee0c1435016d6642cf8c1f88c3dd5495fa Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 17 Feb 2017 11:16:48 +0100 Subject: Return SD card size as get from the device Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 2 +- include/NitrokeyManager.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 176f516..20d1a98 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -787,7 +787,7 @@ namespace nitrokey{ misc::execute_password_command(device, ""); } - int NitrokeyManager::get_SD_card_size() { + uint8_t NitrokeyManager::get_SD_card_size() { auto data = stick20::ProductionTest::CommandTransaction::run(device); return data.data().SD_Card_Size_u8; } diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 2200955..7cf55c7 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -106,7 +106,7 @@ namespace nitrokey { void fill_SD_card_with_random_data(const char *admin_pin); - int get_SD_card_size(); + uint8_t get_SD_card_size(); void change_update_password(const char *current_update_password, const char *new_update_password); -- cgit v1.2.3 From 5650e48b114529075d89dbdde0330901351b8460 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 17 Feb 2017 16:29:21 +0100 Subject: Get proper card serial for Storage. Get serial as one number. Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 17 +++++++++++++++-- include/misc.h | 11 +++++++++++ include/stick10_commands.h | 19 ++++++++----------- misc.cc | 2 ++ 4 files changed, 36 insertions(+), 13 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 20d1a98..ac1074b 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -138,9 +138,22 @@ namespace nitrokey{ } } + string NitrokeyManager::get_serial_number() { - auto response = GetStatus::CommandTransaction::run(device); - return response.data().get_card_serial_hex(); + switch (device->get_device_model()) { + case DeviceModel::PRO: { + auto response = GetStatus::CommandTransaction::run(device); + return nitrokey::misc::toHex(response.data().card_serial_i); + } + break; + + case DeviceModel::STORAGE: + { + auto response = stick20::GetDeviceStatus::CommandTransaction::run(device); + return nitrokey::misc::toHex(response.data().ActiveSmartCardID_u32); + } + break; + } } stick10::GetStatus::ResponsePayload NitrokeyManager::get_status(){ diff --git a/include/misc.h b/include/misc.h index 330654a..c39c741 100644 --- a/include/misc.h +++ b/include/misc.h @@ -6,10 +6,21 @@ #include #include "log.h" #include "LibraryException.h" +#include +#include + namespace nitrokey { namespace misc { + template + std::string toHex(T value){ + using namespace std; + std::ostringstream oss; + oss << std::hex << std::setw(sizeof(value)*2) << std::setfill('0') << value; + return oss.str(); + } + template void strcpyT(T& dest, const char* src){ diff --git a/include/stick10_commands.h b/include/stick10_commands.h index 3d9e234..843d8bd 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -348,7 +348,10 @@ class GetStatus : Command { public: struct ResponsePayload { uint16_t firmware_version; - uint8_t card_serial[4]; + union{ + uint8_t card_serial[4]; + uint32_t card_serial_i; + } __packed; union { uint8_t general_config[5]; struct{ @@ -357,19 +360,12 @@ class GetStatus : Command { uint8_t scrolllock; /** same as numlock */ uint8_t enable_user_password; uint8_t delete_user_password; - }; - }; + } __packed; + } __packed; bool isValid() const { return enable_user_password!=delete_user_password; } std::string get_card_serial_hex() const { -// return ::nitrokey::misc::hexdump((const char *)(card_serial), -// sizeof card_serial, false, false, false); - std::stringstream ss; - ss << std::hex << std::setfill('0'); - for (int i = 0; i < sizeof(card_serial); ++i) { - ss << std::setw(2) << static_cast(card_serial[i]); - } - return ss.str(); + return nitrokey::misc::toHex(card_serial_i); } std::string dissect() const { @@ -378,6 +374,7 @@ class GetStatus : Command { << "[" << firmware_version << "]" << "\t" << ::nitrokey::misc::hexdump( (const char *)(&firmware_version), sizeof firmware_version, false); + ss << "card_serial_i:\t" << std::hex << card_serial_i << std::endl; ss << "card_serial:\t" << ::nitrokey::misc::hexdump((const char *)(card_serial), sizeof card_serial, false); diff --git a/misc.cc b/misc.cc index f85d486..5eb81b5 100644 --- a/misc.cc +++ b/misc.cc @@ -10,6 +10,8 @@ namespace nitrokey { namespace misc { + + ::std::vector hex_string_to_byte(const char* hexString){ const size_t big_string_size = 256; //arbitrary 'big' number const size_t s_size = strlen(hexString); -- cgit v1.2.3 From 6061ee1af573147e41a0834d1c6628eda2fa2f7c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 17 Feb 2017 17:49:20 +0100 Subject: Rename is_connected to be more specific Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 4 ++-- device.cc | 2 +- include/device.h | 7 ++++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index ac1074b..4fed0a6 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -107,7 +107,7 @@ namespace nitrokey{ bool NitrokeyManager::_disconnect_no_lock() { //do not use directly without locked mutex, - //used by is_connected, disconnect + //used by could_be_enumerated, disconnect if (device == nullptr){ return false; } @@ -119,7 +119,7 @@ namespace nitrokey{ bool NitrokeyManager::is_connected() throw(){ std::lock_guard lock(mex_dev_com); if(device != nullptr){ - auto connected = device->is_connected(); + auto connected = device->could_be_enumerated(); if(connected){ return true; } else { diff --git a/device.cc b/device.cc index 8fdf99a..fcc3ba7 100644 --- a/device.cc +++ b/device.cc @@ -115,7 +115,7 @@ int Device::recv(void *packet) { return status; } -bool Device::is_connected() { +bool Device::could_be_enumerated() { Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); if (mp_devhandle==nullptr){ diff --git a/include/device.h b/include/device.h index 40eb376..5d7ee12 100644 --- a/include/device.h +++ b/include/device.h @@ -77,7 +77,12 @@ public: */ virtual int recv(void *packet); - bool is_connected(); + /*** + * Returns true if some device is visible by OS with given VID and PID + * whether the device is connected through HID API or not. + * @return true if visible by OS + */ + bool could_be_enumerated(); void show_stats(); // ErrorCounters get_stats(){ return m_counters; } -- cgit v1.2.3 From 0fb8c08704a338bb9f1b7d3ead4b488bf65cf51e Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 17 Feb 2017 17:52:54 +0100 Subject: Make names more consistent Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 2 +- include/stick10_commands.h | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 4fed0a6..2858a18 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -143,7 +143,7 @@ namespace nitrokey{ switch (device->get_device_model()) { case DeviceModel::PRO: { auto response = GetStatus::CommandTransaction::run(device); - return nitrokey::misc::toHex(response.data().card_serial_i); + return nitrokey::misc::toHex(response.data().card_serial_u32); } break; diff --git a/include/stick10_commands.h b/include/stick10_commands.h index 843d8bd..676aabc 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -350,7 +350,7 @@ class GetStatus : Command { uint16_t firmware_version; union{ uint8_t card_serial[4]; - uint32_t card_serial_i; + uint32_t card_serial_u32; } __packed; union { uint8_t general_config[5]; @@ -365,7 +365,7 @@ class GetStatus : Command { bool isValid() const { return enable_user_password!=delete_user_password; } std::string get_card_serial_hex() const { - return nitrokey::misc::toHex(card_serial_i); + return nitrokey::misc::toHex(card_serial_u32); } std::string dissect() const { @@ -374,7 +374,7 @@ class GetStatus : Command { << "[" << firmware_version << "]" << "\t" << ::nitrokey::misc::hexdump( (const char *)(&firmware_version), sizeof firmware_version, false); - ss << "card_serial_i:\t" << std::hex << card_serial_i << std::endl; + ss << "card_serial_u32:\t" << std::hex << card_serial_u32 << std::endl; ss << "card_serial:\t" << ::nitrokey::misc::hexdump((const char *)(card_serial), sizeof card_serial, false); -- cgit v1.2.3 From 735d7eebcf132c1146da14989ed70fda2f01c06f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 18 Feb 2017 17:02:33 +0100 Subject: Add script for installing python dependencies for unit tests Signed-off-by: Szczepan Zalega --- unittest/setup_python_dependencies.sh | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 unittest/setup_python_dependencies.sh diff --git a/unittest/setup_python_dependencies.sh b/unittest/setup_python_dependencies.sh new file mode 100644 index 0000000..0f1a0f7 --- /dev/null +++ b/unittest/setup_python_dependencies.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +pip install -r requirements.txt --user -- cgit v1.2.3 From bd5fd5d6cf42732c4a34c10d390d3596615e9a47 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 18 Feb 2017 17:03:16 +0100 Subject: Remove unnecessary extern keyword from C API Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 121 +++++++++++++++++++++++++++++---------------------- NK_C_API.h | 120 ++++++++++++++++++++++++++++---------------------- unittest/conftest.py | 4 +- 3 files changed, 137 insertions(+), 108 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index 0fde829..05102cc 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -76,15 +76,16 @@ uint8_t get_without_result(T func){ return NK_last_command_status; } + extern "C" { -extern uint8_t NK_get_last_command_status(){ +NK_C_API uint8_t NK_get_last_command_status(){ auto _copy = NK_last_command_status; NK_last_command_status = 0; return _copy; } -extern int NK_login(const char *device_model) { +NK_C_API int NK_login(const char *device_model) { auto m = NitrokeyManager::instance(); try { NK_last_command_status = 0; @@ -101,14 +102,14 @@ extern int NK_login(const char *device_model) { return 0; } -extern int NK_logout() { +NK_C_API int NK_logout() { auto m = NitrokeyManager::instance(); return get_without_result( [&](){ m->disconnect(); }); } -extern int NK_first_authenticate(const char* admin_password, const char* admin_temporary_password){ +NK_C_API int NK_first_authenticate(const char* admin_password, const char* admin_temporary_password){ auto m = NitrokeyManager::instance(); return get_without_result( [&](){ return m->first_authenticate(admin_password, admin_temporary_password); @@ -116,34 +117,34 @@ extern int NK_first_authenticate(const char* admin_password, const char* admin_t } -extern int NK_user_authenticate(const char* user_password, const char* user_temporary_password){ +NK_C_API int NK_user_authenticate(const char* user_password, const char* user_temporary_password){ auto m = NitrokeyManager::instance(); return get_without_result( [&](){ m->user_authenticate(user_password, user_temporary_password); }); } -extern int NK_factory_reset(const char* admin_password){ +NK_C_API int NK_factory_reset(const char* admin_password){ auto m = NitrokeyManager::instance(); return get_without_result( [&](){ m->factory_reset(admin_password); }); } -extern int NK_build_aes_key(const char* admin_password){ +NK_C_API int NK_build_aes_key(const char* admin_password){ auto m = NitrokeyManager::instance(); return get_without_result( [&](){ m->build_aes_key(admin_password); }); } -extern int NK_unlock_user_password(const char *admin_password, const char *new_user_password) { +NK_C_API int NK_unlock_user_password(const char *admin_password, const char *new_user_password) { auto m = NitrokeyManager::instance(); return get_without_result( [&](){ m->unlock_user_password(admin_password, new_user_password); }); } -extern int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock, bool enable_user_password, +NK_C_API int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock, bool enable_user_password, bool delete_user_password, const char *admin_temporary_password) { auto m = NitrokeyManager::instance(); @@ -153,7 +154,7 @@ extern int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock } -extern uint8_t* NK_read_config(){ +NK_C_API uint8_t* NK_read_config(){ auto m = NitrokeyManager::instance(); return get_with_array_result( [&](){ auto v = m->read_config(); @@ -166,7 +167,7 @@ void clear_string(std::string &s){ std::fill(s.begin(), s.end(), ' '); } -extern const char * NK_status() { +NK_C_API const char * NK_status() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ string && s = m->get_status_as_string(); @@ -176,7 +177,7 @@ extern const char * NK_status() { }); } -extern const char * NK_device_serial_number(){ +NK_C_API const char * NK_device_serial_number(){ auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ string && s = m->get_serial_number(); @@ -186,23 +187,23 @@ extern const char * NK_device_serial_number(){ }); } -extern uint32_t NK_get_hotp_code(uint8_t slot_number) { +NK_C_API uint32_t NK_get_hotp_code(uint8_t slot_number) { return NK_get_hotp_code_PIN(slot_number, ""); } -extern uint32_t NK_get_hotp_code_PIN(uint8_t slot_number, const char* user_temporary_password){ +NK_C_API uint32_t NK_get_hotp_code_PIN(uint8_t slot_number, const char* user_temporary_password){ auto m = NitrokeyManager::instance(); return get_with_result([&](){ return m->get_HOTP_code(slot_number, user_temporary_password); }); } -extern uint32_t NK_get_totp_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, +NK_C_API uint32_t NK_get_totp_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, uint8_t last_interval){ return NK_get_totp_code_PIN(slot_number, challenge, last_totp_time, last_interval, ""); } -extern uint32_t NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, +NK_C_API uint32_t NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, uint8_t last_interval, const char* user_temporary_password){ auto m = NitrokeyManager::instance(); return get_with_result([&](){ @@ -210,21 +211,21 @@ extern uint32_t NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge, ui }); } -extern int NK_erase_hotp_slot(uint8_t slot_number, const char *temporary_password) { +NK_C_API int NK_erase_hotp_slot(uint8_t slot_number, const char *temporary_password) { auto m = NitrokeyManager::instance(); return get_without_result([&]{ m->erase_hotp_slot(slot_number, temporary_password); }); } -extern int NK_erase_totp_slot(uint8_t slot_number, const char *temporary_password) { +NK_C_API int NK_erase_totp_slot(uint8_t slot_number, const char *temporary_password) { auto m = NitrokeyManager::instance(); return get_without_result([&]{ m->erase_totp_slot(slot_number, temporary_password); }); } -extern int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter, +NK_C_API int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter, bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID, const char *temporary_password) { auto m = NitrokeyManager::instance(); @@ -234,7 +235,7 @@ extern int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const }); } -extern int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window, +NK_C_API int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window, bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID, const char *temporary_password) { auto m = NitrokeyManager::instance(); @@ -244,14 +245,14 @@ extern int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const }); } -extern const char* NK_get_totp_slot_name(uint8_t slot_number){ +NK_C_API const char* NK_get_totp_slot_name(uint8_t slot_number){ auto m = NitrokeyManager::instance(); return get_with_string_result([&]() { const auto slot_name = m->get_totp_slot_name(slot_number); return slot_name; }); } -extern const char* NK_get_hotp_slot_name(uint8_t slot_number){ +NK_C_API const char* NK_get_hotp_slot_name(uint8_t slot_number){ auto m = NitrokeyManager::instance(); return get_with_string_result([&]() { const auto slot_name = m->get_hotp_slot_name(slot_number); @@ -259,46 +260,46 @@ extern const char* NK_get_hotp_slot_name(uint8_t slot_number){ }); } -extern void NK_set_debug(bool state){ +NK_C_API void NK_set_debug(bool state){ auto m = NitrokeyManager::instance(); m->set_debug(state); } -extern int NK_totp_set_time(uint64_t time){ +NK_C_API int NK_totp_set_time(uint64_t time){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->set_time(time); }); } -extern int NK_totp_get_time(){ +NK_C_API int NK_totp_get_time(){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->get_time(0); // FIXME check how that should work }); } -extern int NK_change_admin_PIN(char *current_PIN, char *new_PIN){ +NK_C_API int NK_change_admin_PIN(char *current_PIN, char *new_PIN){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->change_admin_PIN(current_PIN, new_PIN); }); } -extern int NK_change_user_PIN(char *current_PIN, char *new_PIN){ +NK_C_API int NK_change_user_PIN(char *current_PIN, char *new_PIN){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->change_user_PIN(current_PIN, new_PIN); }); } -extern int NK_enable_password_safe(const char *user_pin){ +NK_C_API int NK_enable_password_safe(const char *user_pin){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->enable_password_safe(user_pin); }); } -extern uint8_t * NK_get_password_safe_slot_status(){ +NK_C_API uint8_t * NK_get_password_safe_slot_status(){ auto m = NitrokeyManager::instance(); return get_with_array_result( [&](){ auto slot_status = m->get_password_safe_slot_status(); @@ -307,47 +308,47 @@ extern uint8_t * NK_get_password_safe_slot_status(){ } -extern uint8_t NK_get_user_retry_count(){ +NK_C_API uint8_t NK_get_user_retry_count(){ auto m = NitrokeyManager::instance(); return get_with_result([&](){ return m->get_user_retry_count(); }); } -extern uint8_t NK_get_admin_retry_count(){ +NK_C_API uint8_t NK_get_admin_retry_count(){ auto m = NitrokeyManager::instance(); return get_with_result([&](){ return m->get_admin_retry_count(); }); } -extern int NK_lock_device(){ +NK_C_API int NK_lock_device(){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->lock_device(); }); } -extern const char *NK_get_password_safe_slot_name(uint8_t slot_number) { +NK_C_API const char *NK_get_password_safe_slot_name(uint8_t slot_number) { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ return m->get_password_safe_slot_name(slot_number); }); } -extern const char *NK_get_password_safe_slot_login(uint8_t slot_number) { +NK_C_API const char *NK_get_password_safe_slot_login(uint8_t slot_number) { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ return m->get_password_safe_slot_login(slot_number); }); } -extern const char *NK_get_password_safe_slot_password(uint8_t slot_number) { +NK_C_API const char *NK_get_password_safe_slot_password(uint8_t slot_number) { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ return m->get_password_safe_slot_password(slot_number); }); } -extern int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login, +NK_C_API int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login, const char *slot_password) { auto m = NitrokeyManager::instance(); return get_without_result([&](){ @@ -355,21 +356,21 @@ extern int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_nam }); } -extern int NK_erase_password_safe_slot(uint8_t slot_number) { +NK_C_API int NK_erase_password_safe_slot(uint8_t slot_number) { auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->erase_password_safe_slot(slot_number); }); } -extern int NK_is_AES_supported(const char *user_password) { +NK_C_API int NK_is_AES_supported(const char *user_password) { auto m = NitrokeyManager::instance(); return get_with_result([&](){ return (uint8_t) m->is_AES_supported(user_password); }); } -extern int NK_login_auto() { +NK_C_API int NK_login_auto() { auto m = NitrokeyManager::instance(); return get_with_result([&](){ return (uint8_t) m->connect(); @@ -378,28 +379,42 @@ extern int NK_login_auto() { // storage commands -extern int NK_send_startup(uint64_t seconds_from_epoch){ +NK_C_API int NK_send_startup(uint64_t seconds_from_epoch){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->send_startup(seconds_from_epoch); }); } -extern int NK_unlock_encrypted_volume(const char* user_pin){ +NK_C_API int NK_unlock_encrypted_volume(const char* user_pin){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->unlock_encrypted_volume(user_pin); }); } -extern int NK_unlock_hidden_volume(const char* hidden_volume_password){ +NK_C_API int NK_lock_encrypted_volume(){ + auto m = NitrokeyManager::instance(); + return get_without_result([&](){ + m->lock_encrypted_volume(); + }); +} + +NK_C_API int NK_unlock_hidden_volume(const char* hidden_volume_password){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->unlock_hidden_volume(hidden_volume_password); }); } -extern int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent, +NK_C_API int NK_lock_hidden_volume(){ + auto m = NitrokeyManager::instance(); + return get_without_result([&](){ + m->lock_hidden_volume(); + }); +} + +NK_C_API int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent, const char *hidden_volume_password){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ @@ -408,42 +423,42 @@ extern int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8 }); } -extern int NK_set_unencrypted_read_only(const char* user_pin){ +NK_C_API int NK_set_unencrypted_read_only(const char* user_pin){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->set_unencrypted_read_only(user_pin); }); } -extern int NK_set_unencrypted_read_write(const char* user_pin){ +NK_C_API int NK_set_unencrypted_read_write(const char* user_pin){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->set_unencrypted_read_write(user_pin); }); } -extern int NK_export_firmware(const char* admin_pin) { +NK_C_API int NK_export_firmware(const char* admin_pin) { auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->export_firmware(admin_pin) ; }); } -extern int NK_clear_new_sd_card_warning(const char* admin_pin) { +NK_C_API int NK_clear_new_sd_card_warning(const char* admin_pin) { auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->clear_new_sd_card_warning(admin_pin); }); } -extern int NK_fill_SD_card_with_random_data(const char* admin_pin) { +NK_C_API int NK_fill_SD_card_with_random_data(const char* admin_pin) { auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->fill_SD_card_with_random_data(admin_pin); }); } -extern int NK_change_update_password(const char* current_update_password, +NK_C_API int NK_change_update_password(const char* current_update_password, const char* new_update_password) { auto m = NitrokeyManager::instance(); return get_without_result([&](){ @@ -451,28 +466,28 @@ extern int NK_change_update_password(const char* current_update_password, }); } -extern const char* NK_get_status_storage_as_string() { +NK_C_API const char* NK_get_status_storage_as_string() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ return m->get_status_storage_as_string(); }); } -extern const char* NK_get_SD_usage_data_as_string() { +NK_C_API const char* NK_get_SD_usage_data_as_string() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ return m->get_SD_usage_data_as_string(); }); } -extern int NK_get_progress_bar_value() { +NK_C_API int NK_get_progress_bar_value() { auto m = NitrokeyManager::instance(); return get_with_result([&](){ return m->get_progress_bar_value(); }); } -extern int NK_get_major_firmware_version(){ +NK_C_API int NK_get_major_firmware_version(){ auto m = NitrokeyManager::instance(); return get_with_result([&](){ return m->get_minor_firmware_version(); diff --git a/NK_C_API.h b/NK_C_API.h index 7f01900..dd31287 100644 --- a/NK_C_API.h +++ b/NK_C_API.h @@ -6,57 +6,59 @@ #include "include/NitrokeyManager.h" #include "include/inttypes.h" +#define NK_C_API + extern "C" { /** * Set debug level of messages written on stderr * @param state state=True - all messages, state=False - only errors level */ -extern void NK_set_debug(bool state); +NK_C_API void NK_set_debug(bool state); /** * Connect to device of given model. Currently library can be connected only to one device at once. * @param device_model char 'S': Nitrokey Storage, 'P': Nitrokey Pro * @return 1 if connected, 0 if wrong model or cannot connect */ -extern int NK_login(const char *device_model); +NK_C_API int NK_login(const char *device_model); /** * Connect to first available device, starting checking from Pro 1st to Storage 2nd. * @return 1 if connected, 0 if wrong model or cannot connect */ -extern int NK_login_auto(); +NK_C_API int NK_login_auto(); /** * Disconnect from the device. * @return command processing error code */ -extern int NK_logout(); +NK_C_API int NK_logout(); /** * Return the debug status string. Debug purposes. * @return command processing error code */ -extern const char * NK_status(); +NK_C_API const char * NK_status(); /** * Return the device's serial number string in hex. * @return string device's serial number in hex */ -extern const char * NK_device_serial_number(); +NK_C_API const char * NK_device_serial_number(); /** * Get last command processing status. Useful for commands which returns the results of their own and could not return * an error code. * @return previous command processing error code */ -extern uint8_t NK_get_last_command_status(); +NK_C_API uint8_t NK_get_last_command_status(); /** * Lock device - cancel any user device unlocking. * @return command processing error code */ -extern int NK_lock_device(); +NK_C_API int NK_lock_device(); /** * Authenticates the user on USER privilages with user_password and sets user's temporary password on device to user_temporary_password. @@ -64,7 +66,7 @@ extern int NK_lock_device(); * @param user_temporary_password char[25](Pro) user temporary password to be set on device for further communication (authentication command) * @return command processing error code */ -extern int NK_user_authenticate(const char* user_password, const char* user_temporary_password); +NK_C_API int NK_user_authenticate(const char* user_password, const char* user_temporary_password); /** * Authenticates the user on ADMIN privilages with admin_password and sets user's temporary password on device to admin_temporary_password. @@ -72,28 +74,28 @@ extern int NK_user_authenticate(const char* user_password, const char* user_temp * @param admin_temporary_password char[25](Pro) admin temporary password to be set on device for further communication (authentication command) * @return command processing error code */ -extern int NK_first_authenticate(const char* admin_password, const char* admin_temporary_password); +NK_C_API int NK_first_authenticate(const char* admin_password, const char* admin_temporary_password); /** * Execute a factory reset. * @param admin_password char[20](Pro) current administrator PIN * @return command processing error code */ -extern int NK_factory_reset(const char* admin_password); +NK_C_API int NK_factory_reset(const char* admin_password); /** * Generates AES key on the device * @param admin_password char[20](Pro) current administrator PIN * @return command processing error code */ -extern int NK_build_aes_key(const char* admin_password); +NK_C_API int NK_build_aes_key(const char* admin_password); /** * Unlock user PIN locked after 3 incorrect codes tries. * @param admin_password char[20](Pro) current administrator PIN * @return command processing error code */ -extern int NK_unlock_user_password(const char *admin_password, const char *new_user_password); +NK_C_API int NK_unlock_user_password(const char *admin_password, const char *new_user_password); /** * Write general config to the device @@ -106,7 +108,7 @@ extern int NK_unlock_user_password(const char *admin_password, const char *new_u * @param admin_temporary_password current admin temporary password * @return command processing error code */ -extern int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock, +NK_C_API int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock, bool enable_user_password, bool delete_user_password, const char *admin_temporary_password); /** @@ -120,7 +122,7 @@ extern int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock uint8_t delete_user_password; */ -extern uint8_t* NK_read_config(); +NK_C_API uint8_t* NK_read_config(); //OTP @@ -129,14 +131,14 @@ extern uint8_t* NK_read_config(); * @param slot_number TOTP slot number, slot_number<15 * @return char[20](Pro) the name of the slot */ -extern const char * NK_get_totp_slot_name(uint8_t slot_number); +NK_C_API const char * NK_get_totp_slot_name(uint8_t slot_number); /** * * @param slot_number HOTP slot number, slot_number<3 * @return char[20](Pro) the name of the slot */ -extern const char * NK_get_hotp_slot_name(uint8_t slot_number); +NK_C_API const char * NK_get_hotp_slot_name(uint8_t slot_number); /** * Erase HOTP slot data from the device @@ -144,7 +146,7 @@ extern const char * NK_get_hotp_slot_name(uint8_t slot_number); * @param temporary_password admin temporary password * @return command processing error code */ -extern int NK_erase_hotp_slot(uint8_t slot_number, const char *temporary_password); +NK_C_API int NK_erase_hotp_slot(uint8_t slot_number, const char *temporary_password); /** * Erase TOTP slot data from the device @@ -152,7 +154,7 @@ extern int NK_erase_hotp_slot(uint8_t slot_number, const char *temporary_passwor * @param temporary_password admin temporary password * @return command processing error code */ -extern int NK_erase_totp_slot(uint8_t slot_number, const char *temporary_password); +NK_C_API int NK_erase_totp_slot(uint8_t slot_number, const char *temporary_password); /** * Write HOTP slot data to the device @@ -167,7 +169,7 @@ extern int NK_erase_totp_slot(uint8_t slot_number, const char *temporary_passwor * @param temporary_password char[25](Pro) admin temporary password * @return command processing error code */ -extern int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter, +NK_C_API int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter, bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID, const char *temporary_password); @@ -184,7 +186,7 @@ extern int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const * @param temporary_password char[20](Pro) admin temporary password * @return command processing error code */ -extern int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window, +NK_C_API int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window, bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID, const char *temporary_password); @@ -193,7 +195,7 @@ extern int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const * @param slot_number HOTP slot number, slot_number<3 * @return HOTP code */ -extern uint32_t NK_get_hotp_code(uint8_t slot_number); +NK_C_API uint32_t NK_get_hotp_code(uint8_t slot_number); /** * Get HOTP code from the device (PIN protected) @@ -202,7 +204,7 @@ extern uint32_t NK_get_hotp_code(uint8_t slot_number); * otherwise should be set to empty string - '' * @return HOTP code */ -extern uint32_t NK_get_hotp_code_PIN(uint8_t slot_number, const char* user_temporary_password); +NK_C_API uint32_t NK_get_hotp_code_PIN(uint8_t slot_number, const char* user_temporary_password); /** * Get TOTP code from the device @@ -212,7 +214,7 @@ extern uint32_t NK_get_hotp_code_PIN(uint8_t slot_number, const char* user_tempo * @param last_interval last interval * @return TOTP code */ -extern uint32_t NK_get_totp_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, uint8_t last_interval); +NK_C_API uint32_t NK_get_totp_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, uint8_t last_interval); /** * Get TOTP code from the device (PIN protected) @@ -224,7 +226,7 @@ extern uint32_t NK_get_totp_code(uint8_t slot_number, uint64_t challenge, uint64 * otherwise should be set to empty string - '' * @return TOTP code */ -extern uint32_t NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge, +NK_C_API uint32_t NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time, uint8_t last_interval, const char* user_temporary_password); /** @@ -232,9 +234,9 @@ extern uint32_t NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge, * @param time seconds in unix epoch (from 01.01.1970) * @return command processing error code */ -extern int NK_totp_set_time(uint64_t time); +NK_C_API int NK_totp_set_time(uint64_t time); -extern int NK_totp_get_time(); +NK_C_API int NK_totp_get_time(); //passwords /** * Change administrator PIN @@ -242,7 +244,7 @@ extern int NK_totp_get_time(); * @param new_PIN char[25](Pro) new PIN * @return command processing error code */ -extern int NK_change_admin_PIN(char *current_PIN, char *new_PIN); +NK_C_API int NK_change_admin_PIN(char *current_PIN, char *new_PIN); /** * Change user PIN @@ -250,20 +252,20 @@ extern int NK_change_admin_PIN(char *current_PIN, char *new_PIN); * @param new_PIN char[25](Pro) new PIN * @return command processing error code */ -extern int NK_change_user_PIN(char *current_PIN, char *new_PIN); +NK_C_API int NK_change_user_PIN(char *current_PIN, char *new_PIN); /** * Get retry count of user PIN * @return user PIN retry count */ -extern uint8_t NK_get_user_retry_count(); +NK_C_API uint8_t NK_get_user_retry_count(); /** * Get retry count of admin PIN * @return admin PIN retry count */ -extern uint8_t NK_get_admin_retry_count(); +NK_C_API uint8_t NK_get_admin_retry_count(); //password safe /** @@ -271,34 +273,34 @@ extern uint8_t NK_get_admin_retry_count(); * @param user_pin char[30](Pro) current user PIN * @return command processing error code */ -extern int NK_enable_password_safe(const char *user_pin); +NK_C_API int NK_enable_password_safe(const char *user_pin); /** * Get password safe slots' status * @return uint8_t[16] slot statuses - each byte represents one slot with 0 (not programmed) and 1 (programmed) */ -extern uint8_t * NK_get_password_safe_slot_status(); +NK_C_API uint8_t * NK_get_password_safe_slot_status(); /** * Get password safe slot name * @param slot_number password safe slot number, slot_number<16 * @return slot name */ -extern const char *NK_get_password_safe_slot_name(uint8_t slot_number); +NK_C_API const char *NK_get_password_safe_slot_name(uint8_t slot_number); /** * Get password safe slot login * @param slot_number password safe slot number, slot_number<16 * @return login from the PWS slot */ -extern const char *NK_get_password_safe_slot_login(uint8_t slot_number); +NK_C_API const char *NK_get_password_safe_slot_login(uint8_t slot_number); /** * Get the password safe slot password * @param slot_number password safe slot number, slot_number<16 * @return password from the PWS slot */ -extern const char *NK_get_password_safe_slot_password(uint8_t slot_number); +NK_C_API const char *NK_get_password_safe_slot_password(uint8_t slot_number); /** * Write password safe data to the slot @@ -308,7 +310,7 @@ extern const char *NK_get_password_safe_slot_password(uint8_t slot_number); * @param slot_password char[20](Pro) password string * @return command processing error code */ -extern int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_name, +NK_C_API int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login, const char *slot_password); /** @@ -316,19 +318,19 @@ extern int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_nam * @param slot_number password safe slot number, slot_number<16 * @return command processing error code */ -extern int NK_erase_password_safe_slot(uint8_t slot_number); +NK_C_API int NK_erase_password_safe_slot(uint8_t slot_number); /** * Check whether AES is supported by the device * @return 0 for no and 1 for yes */ -extern int NK_is_AES_supported(const char *user_password); +NK_C_API int NK_is_AES_supported(const char *user_password); /** * Get device's major firmware version * @return 7,8 for Pro and major for Storage */ -extern int NK_get_major_firmware_version(); +NK_C_API int NK_get_major_firmware_version(); @@ -340,7 +342,7 @@ extern int NK_get_major_firmware_version(); * Storage only * @param seconds_from_epoch date and time expressed in seconds */ -extern int NK_send_startup(uint64_t seconds_from_epoch); +NK_C_API int NK_send_startup(uint64_t seconds_from_epoch); /** * Unlock encrypted volume. @@ -348,7 +350,13 @@ extern int NK_send_startup(uint64_t seconds_from_epoch); * @param user_pin user pin 20 characters * @return command processing error code */ -extern int NK_unlock_encrypted_volume(const char* user_pin); +NK_C_API int NK_unlock_encrypted_volume(const char* user_pin); + +/** + * Locks encrypted volume + * @return command processing error code + */ +NK_C_API int NK_lock_encrypted_volume(); /** * Unlock hidden volume and lock encrypted volume. @@ -357,7 +365,13 @@ extern int NK_unlock_encrypted_volume(const char* user_pin); * @param hidden_volume_password 20 characters * @return command processing error code */ -extern int NK_unlock_hidden_volume(const char* hidden_volume_password); +NK_C_API int NK_unlock_hidden_volume(const char* hidden_volume_password); + +/** + * Locks hidden volume + * @return command processing error code + */ +NK_C_API int NK_lock_hidden_volume(); /** * Create hidden volume. @@ -369,7 +383,7 @@ extern int NK_unlock_hidden_volume(const char* hidden_volume_password); * @param hidden_volume_password 20 characters * @return command processing error code */ -extern int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent, +NK_C_API int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent, const char *hidden_volume_password); /** @@ -380,7 +394,7 @@ extern int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8 * @param user_pin 20 characters * @return command processing error code */ -extern int NK_set_unencrypted_read_only(const char* user_pin); +NK_C_API int NK_set_unencrypted_read_only(const char* user_pin); /** * Make unencrypted volume read-write. @@ -390,7 +404,7 @@ extern int NK_set_unencrypted_read_only(const char* user_pin); * @param user_pin 20 characters * @return command processing error code */ -extern int NK_set_unencrypted_read_write(const char* user_pin); +NK_C_API int NK_set_unencrypted_read_write(const char* user_pin); /** * Exports device's firmware to unencrypted volume. @@ -398,7 +412,7 @@ extern int NK_set_unencrypted_read_write(const char* user_pin); * @param admin_pin 20 characters * @return command processing error code */ -extern int NK_export_firmware(const char* admin_pin) ; +NK_C_API int NK_export_firmware(const char* admin_pin) ; /** * Clear new SD card notification. It is set after factory reset. @@ -406,7 +420,7 @@ extern int NK_export_firmware(const char* admin_pin) ; * @param admin_pin 20 characters * @return command processing error code */ -extern int NK_clear_new_sd_card_warning(const char* admin_pin) ; +NK_C_API int NK_clear_new_sd_card_warning(const char* admin_pin) ; /** * Fill SD card with random data. @@ -415,7 +429,7 @@ extern int NK_clear_new_sd_card_warning(const char* admin_pin) ; * @param admin_pin 20 characters * @return command processing error code */ -extern int NK_fill_SD_card_with_random_data(const char* admin_pin) ; +NK_C_API int NK_fill_SD_card_with_random_data(const char* admin_pin) ; /** * Change update password. @@ -426,7 +440,7 @@ extern int NK_fill_SD_card_with_random_data(const char* admin_pin) ; * @param new_update_password 20 characters * @return command processing error code */ -extern int NK_change_update_password(const char* current_update_password, +NK_C_API int NK_change_update_password(const char* current_update_password, const char* new_update_password); /** @@ -434,7 +448,7 @@ extern int NK_change_update_password(const char* current_update_password, * Storage only * @return string with devices attributes */ -extern const char* NK_get_status_storage_as_string(); +NK_C_API const char* NK_get_status_storage_as_string(); /** * Get SD card usage attributes as string. @@ -442,14 +456,14 @@ extern const char* NK_get_status_storage_as_string(); * Storage only * @return string with SD card usage attributes */ -extern const char* NK_get_SD_usage_data_as_string(); +NK_C_API const char* NK_get_SD_usage_data_as_string(); /** * Get progress value of current long operation. * Storage only * @return int in range 0-100 or -1 if device is not busy */ -extern int NK_get_progress_bar_value(); +NK_C_API int NK_get_progress_bar_value(); } diff --git a/unittest/conftest.py b/unittest/conftest.py index 88bf7d0..f43f153 100644 --- a/unittest/conftest.py +++ b/unittest/conftest.py @@ -22,8 +22,8 @@ def C(request): a = iter(declarations) for declaration in a: - if declaration.startswith('extern') and not '"C"' in declaration: - declaration = declaration.replace('extern', '').strip() + if declaration.startswith('NK_C_API'): + declaration = declaration.replace('NK_C_API', '').strip() while not ';' in declaration: declaration += (next(a)).strip() print(declaration) -- cgit v1.2.3 From e8f6df836522250b9a9d4052722fb9780683058b Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 18 Feb 2017 17:05:02 +0100 Subject: Use proper command code for disabling hidden volume Signed-off-by: Szczepan Zalega --- include/command_id.h | 4 ++-- include/stick20_commands.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/include/command_id.h b/include/command_id.h index 9d12f93..d0b1454 100644 --- a/include/command_id.h +++ b/include/command_id.h @@ -69,9 +69,9 @@ enum class CommandID : uint8_t { SEND_OTP_DATA = 0x17, ENABLE_CRYPTED_PARI = 0x20, - DISABLE_CRYPTED_PARI = 0x20 + 1, //@unused + DISABLE_CRYPTED_PARI = 0x20 + 1, ENABLE_HIDDEN_CRYPTED_PARI = 0x20 + 2, - DISABLE_HIDDEN_CRYPTED_PARI = 0x20 + 3, //@unused + DISABLE_HIDDEN_CRYPTED_PARI = 0x20 + 3, ENABLE_FIRMWARE_UPDATE = 0x20 + 4, //enables update mode EXPORT_FIRMWARE_TO_FILE = 0x20 + 5, GENERATE_NEW_KEYS = 0x20 + 6, diff --git a/include/stick20_commands.h b/include/stick20_commands.h index e3bea3f..d88919b 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -33,7 +33,7 @@ namespace nitrokey { //FIXME the volume disabling commands do not need password class DisableEncryptedPartition : public PasswordCommand {}; - class DisableHiddenEncryptedPartition : public PasswordCommand {}; + class DisableHiddenEncryptedPartition : public PasswordCommand {}; class EnableFirmwareUpdate : public PasswordCommand {}; -- cgit v1.2.3 From e3d88377463f4706372ae7fd6c85937f6035b5ef Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 18 Feb 2017 17:06:10 +0100 Subject: Show Storage status only on matching command code Should not show on commands where it is not supplied Signed-off-by: Szczepan Zalega --- include/dissect.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/include/dissect.h b/include/dissect.h index 8c975c5..8992c56 100644 --- a/include/dissect.h +++ b/include/dissect.h @@ -98,7 +98,8 @@ class ResponseDissector : semantics::non_constructible { out << "CRC:\t" << std::hex << std::setw(2) << std::setfill('0') << pod.crc << std::endl; - out << "Storage stick status:" << std::endl; + if((int)pod.command_id == pod.storage_status.command_id){ + out << "Storage stick status (where applicable):" << std::endl; #define d(x) out << " "#x": \t"<< std::hex << std::setw(2) \ << std::setfill('0')<< static_cast(x) << std::endl; d(pod.storage_status.command_counter); @@ -106,6 +107,7 @@ class ResponseDissector : semantics::non_constructible { d(pod.storage_status.device_status); d(pod.storage_status.progress_bar_value); #undef d + } out << "Payload:" << std::endl; out << pod.payload.dissect(); -- cgit v1.2.3 From bbbb596a0e6e5b22a19d5543d20e7b2dfc1a0f83 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 18 Feb 2017 17:06:32 +0100 Subject: Add oath to Pythons unittest requirements Signed-off-by: Szczepan Zalega --- unittest/requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/unittest/requirements.txt b/unittest/requirements.txt index 7224741..2cb9c05 100644 --- a/unittest/requirements.txt +++ b/unittest/requirements.txt @@ -2,3 +2,4 @@ cffi pytest-repeat pytest-randomly enum +oath \ No newline at end of file -- cgit v1.2.3 From 544d68631303fa35b5e6a538f8afb4e054ad9302 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 18 Feb 2017 17:08:07 +0100 Subject: Add some complex unit tests to find out corruption cause Signed-off-by: Szczepan Zalega --- unittest/test_pro.py | 70 +++++++++++++++++++++- unittest/test_storage.py | 147 ++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 214 insertions(+), 3 deletions(-) diff --git a/unittest/test_pro.py b/unittest/test_pro.py index 4a2a504..0ad42e1 100644 --- a/unittest/test_pro.py +++ b/unittest/test_pro.py @@ -22,6 +22,71 @@ def test_write_password_safe_slot(C): assert C.NK_write_password_safe_slot(0, 'slotname1', 'login1', 'pass1') == DeviceErrorCode.STATUS_OK +@pytest.mark.slowtest +def test_write_all_password_safe_slots_and_read_10_times(C): + def fill(s, wid): + assert wid >= len(s) + numbers = '1234567890'*4 + s += numbers[:wid-len(s)] + assert len(s) == wid + return s + + def get_pass(suffix): + return fill('pass' + suffix, 20) + + def get_loginname(suffix): + return fill('login' + suffix, 32) + + def get_slotname(suffix): + return fill('slotname' + suffix, 11) + + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + PWS_slot_count = 16 + for i in range(0, PWS_slot_count): + iss = str(i) + assert C.NK_write_password_safe_slot(i, + get_slotname(iss), get_loginname(iss), + get_pass(iss)) == DeviceErrorCode.STATUS_OK + + for j in range(0, 10): + for i in range(0, PWS_slot_count): + iss = str(i) + assert gs(C.NK_get_password_safe_slot_name(i)) == get_slotname(iss) + assert gs(C.NK_get_password_safe_slot_login(i)) == get_loginname(iss) + assert gs(C.NK_get_password_safe_slot_password(i)) == get_pass(iss) + + +@pytest.mark.slowtest +def test_read_all_password_safe_slots_10_times(C): + def fill(s, wid): + assert wid >= len(s) + numbers = '1234567890'*4 + s += numbers[:wid-len(s)] + assert len(s) == wid + return s + + def get_pass(suffix): + return fill('pass' + suffix, 20) + + def get_loginname(suffix): + return fill('login' + suffix, 32) + + def get_slotname(suffix): + return fill('slotname' + suffix, 11) + + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + PWS_slot_count = 16 + + for j in range(0, 10): + for i in range(0, PWS_slot_count): + iss = str(i) + assert gs(C.NK_get_password_safe_slot_name(i)) == get_slotname(iss) + assert gs(C.NK_get_password_safe_slot_login(i)) == get_loginname(iss) + assert gs(C.NK_get_password_safe_slot_password(i)) == get_pass(iss) + + def test_get_password_safe_slot_name(C): assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_write_password_safe_slot(0, 'slotname1', 'login1', 'pass1') == DeviceErrorCode.STATUS_OK @@ -645,10 +710,11 @@ def test_TOTP_secrets(C, secret): @pytest.mark.parametrize("secret", [RFC_SECRET, 2*RFC_SECRET, '12'*10, '12'*30] ) def test_HOTP_secrets(C, secret): """ - NK Pro 0.8+, NK Storage 0.44+ + NK Pro 0.8+ feature needed: support for 320bit secrets """ - skip_if_device_version_lower_than({'S': 44, 'P': 8}) + if len(secret)>40: + skip_if_device_version_lower_than({'P': 8}) slot_number = 0 counter = 0 diff --git a/unittest/test_storage.py b/unittest/test_storage.py index a1c59aa..9c01382 100644 --- a/unittest/test_storage.py +++ b/unittest/test_storage.py @@ -57,6 +57,7 @@ def test_encrypted_volume_unlock_hidden(C): assert C.NK_create_hidden_volume(0, 20, 21, hidden_volume_password) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(hidden_volume_password) == DeviceErrorCode.STATUS_OK + @pytest.mark.skip(reason='hangs device, to report') def test_encrypted_volume_setup_multiple_hidden(C): skip_if_device_version_lower_than({'S': 43}) @@ -72,6 +73,149 @@ def test_encrypted_volume_setup_multiple_hidden(C): assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK +@pytest.mark.parametrize("volumes_to_setup", range(1, 5)) +def test_encrypted_volume_setup_multiple_hidden_no_lock_device_volumes(C, volumes_to_setup): + skip_if_device_version_lower_than({'S': 43}) + hidden_volume_password = 'hiddenpassword' + p = lambda i: hidden_volume_password + str(i) + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + for i in range(volumes_to_setup): + assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK + + assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + for i in range(volumes_to_setup): + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + # TODO mount and test for files + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + + +@pytest.mark.parametrize("volumes_to_setup", range(1, 5)) +def test_encrypted_volume_setup_multiple_hidden_no_lock_device_volumes_unlock_at_once(C, volumes_to_setup): + skip_if_device_version_lower_than({'S': 43}) + hidden_volume_password = 'hiddenpassword' + p = lambda i: hidden_volume_password + str(i) + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + for i in range(volumes_to_setup): + assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + + assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + for i in range(volumes_to_setup): + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + # TODO mount and test for files + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + + +@pytest.mark.parametrize("use_slot", range(4)) +def test_encrypted_volume_setup_one_hidden_no_lock_device_slot(C, use_slot): + skip_if_device_version_lower_than({'S': 43}) + hidden_volume_password = 'hiddenpassword' + p = lambda i: hidden_volume_password + str(i) + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + i = use_slot + assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + + assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + for j in range(3): + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + # TODO mount and test for files + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + + +def test_password_safe_slot_name_corruption(C): + skip_if_device_version_lower_than({'S': 43}) + volumes_to_setup = 4 + # connected with encrypted volumes, possible also with hidden + def fill(s, wid): + assert wid >= len(s) + numbers = '1234567890' * 4 + s += numbers[:wid - len(s)] + assert len(s) == wid + return s + + def get_pass(suffix): + return fill('pass' + suffix, 20) + + def get_loginname(suffix): + return fill('login' + suffix, 32) + + def get_slotname(suffix): + return fill('slotname' + suffix, 11) + + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + PWS_slot_count = 16 + for i in range(0, PWS_slot_count): + iss = str(i) + assert C.NK_write_password_safe_slot(i, + get_slotname(iss), get_loginname(iss), + get_pass(iss)) == DeviceErrorCode.STATUS_OK + + def check_PWS_correctness(C): + for i in range(0, PWS_slot_count): + iss = str(i) + assert gs(C.NK_get_password_safe_slot_name(i)) == get_slotname(iss) + assert gs(C.NK_get_password_safe_slot_login(i)) == get_loginname(iss) + assert gs(C.NK_get_password_safe_slot_password(i)) == get_pass(iss) + + hidden_volume_password = 'hiddenpassword' + p = lambda i: hidden_volume_password + str(i) + def check_volumes_correctness(C): + for i in range(volumes_to_setup): + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + # TODO mount and test for files + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + + check_PWS_correctness(C) + + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + for i in range(volumes_to_setup): + assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + + assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + check_volumes_correctness(C) + check_PWS_correctness(C) + check_volumes_correctness(C) + check_PWS_correctness(C) + + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + check_volumes_correctness(C) + check_PWS_correctness(C) + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + check_volumes_correctness(C) + check_PWS_correctness(C) + +def test_hidden_volume_corruption(C): + # bug: this should return error without unlocking encrypted volume each hidden volume lock, but it does not + assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + hidden_volume_password = 'hiddenpassword' + p = lambda i: hidden_volume_password + str(i) + for i in range(4): + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + wait(2) + assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK + def test_unencrypted_volume_set_read_only(C): skip_if_device_version_lower_than({'S': 43}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK @@ -94,7 +238,8 @@ def test_clear_new_sd_card_notification(C): assert C.NK_clear_new_sd_card_warning(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK -@pytest.mark.skip +@pytest.mark.slowtest +@pytest.mark.skip(reason='long test (about 1h)') def test_fill_SD_card(C): skip_if_device_version_lower_than({'S': 43}) status = C.NK_fill_SD_card_with_random_data(DefaultPasswords.ADMIN) -- cgit v1.2.3 From 343b77dde196ab2e8ea82e7149b5703a771a9699 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 21 Feb 2017 13:11:40 +0100 Subject: Project info for repositories Signed-off-by: Szczepan Zalega --- .idea/vcs.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 94a25f7..486a99a 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,5 +2,8 @@ + + + \ No newline at end of file -- cgit v1.2.3 From ad286a23ba8a542afe0095b97caf52320778c5e6 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 21 Feb 2017 13:12:12 +0100 Subject: Feature check for 320 bits OTP secret Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 11 ++++++++++- include/NitrokeyManager.h | 6 ++++-- include/log.h | 2 +- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 2858a18..62687b3 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -650,11 +650,20 @@ namespace nitrokey{ //authorization command is supported for versions equal or below: auto m = std::unordered_map({ {DeviceModel::PRO, 7}, - {DeviceModel::STORAGE, 99}, + {DeviceModel::STORAGE, 999}, }); return get_minor_firmware_version() <= m[device->get_device_model()]; } + bool NitrokeyManager::is_320_OTP_secret_supported(){ + //authorization command is supported for versions equal or below: + auto m = std::unordered_map({ + {DeviceModel::PRO, 8}, + {DeviceModel::STORAGE, 999}, + }); + return get_minor_firmware_version() >= m[device->get_device_model()]; + } + DeviceModel NitrokeyManager::get_connected_device_model() const{ //FIXME throw if no device is connected or return unknown/unconnected value if (device == nullptr){ diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 7cf55c7..d49941e 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -122,12 +122,14 @@ namespace nitrokey { std::pair get_SD_usage_data(); - int get_progress_bar_value(); + int get_progress_bar_value(); ~NitrokeyManager(); bool is_authorization_command_supported(); + bool is_320_OTP_secret_supported(); - template + + template void authorize_packet(T &package, const char *admin_temporary_password, shared_ptr device); int get_minor_firmware_version(); diff --git a/include/log.h b/include/log.h index 0b0df8c..30fc7fa 100644 --- a/include/log.h +++ b/include/log.h @@ -5,7 +5,7 @@ namespace nitrokey { namespace log { - + #ifdef ERROR #undef ERROR #endif -- cgit v1.2.3 From c13c7fda5b9f69cd46ba40ac5e6cf1cc4bc7e71d Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 21 Feb 2017 14:52:36 +0100 Subject: Comments Signed-off-by: Szczepan Zalega --- include/log.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/include/log.h b/include/log.h index 30fc7fa..695884b 100644 --- a/include/log.h +++ b/include/log.h @@ -5,11 +5,13 @@ namespace nitrokey { namespace log { - + +//for MSVC #ifdef ERROR #undef ERROR #endif + enum class Loglevel : int { DEBUG_L2, DEBUG, INFO, WARNING, ERROR }; class LogHandler { -- cgit v1.2.3 From 29fc4839b7aaf76c3587cf0d268546fd1d1390c4 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 21 Feb 2017 14:56:07 +0100 Subject: Build debug-log-free library for increased security Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 6 +++++ NitrokeyManager.cc | 6 ++--- device.cc | 38 +++++++++++++++--------------- include/CommandFailedException.h | 2 +- include/LibraryException.h | 2 +- include/LongOperationInProgressException.h | 2 +- include/device_proto.h | 34 +++++++++++++------------- include/log.h | 7 ++++++ include/misc.h | 2 +- 9 files changed, 56 insertions(+), 43 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 89ab66d..0ed907b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -71,13 +71,19 @@ ENDIF() IF (NOT LIBNITROKEY_STATIC) add_library(nitrokey SHARED ${SOURCE_FILES}) + add_library(nitrokey-log SHARED ${SOURCE_FILES}) install (TARGETS nitrokey DESTINATION "lib") SET(LIBNAME nitrokey) ELSE() add_library(nitrokey-static STATIC ${SOURCE_FILES}) + add_library(nitrokey-static-log STATIC ${SOURCE_FILES}) SET(LIBNAME nitrokey-static) ENDIF() target_link_libraries(${LIBNAME} hidapi-libusb) +target_link_libraries(${LIBNAME}-log hidapi-libusb) + +SET_TARGET_PROPERTIES(${LIBNAME} PROPERTIES COMPILE_DEFINITIONS "NO_LOG") + file(GLOB LIB_INCLUDES "include/libnitrokey/*.h") install (FILES ${LIB_INCLUDES} DESTINATION "include") diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 62687b3..1e5c14e 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -22,7 +22,7 @@ namespace nitrokey{ // throw EmptySourceStringException(slot_number); return; const size_t s_dest = sizeof dest; - nitrokey::log::Log::instance()(std::string("strcpyT sizes dest src ") + LOG(std::string("strcpyT sizes dest src ") +std::to_string(s_dest)+ " " +std::to_string(strlen(src))+ " " ,nitrokey::log::Loglevel::DEBUG_L2); @@ -45,7 +45,7 @@ namespace nitrokey{ template void NitrokeyManager::authorize_packet(T &package, const char *admin_temporary_password, shared_ptr device){ if (!is_authorization_command_supported()){ - Log::instance()("Authorization command not supported, skipping", Loglevel::WARNING); + LOG("Authorization command not supported, skipping", Loglevel::WARNING); } auto auth = get_payload(); strcpyT(auth.temporary_password, admin_temporary_password); @@ -311,7 +311,7 @@ namespace nitrokey{ break; } default: - Log::instance()(string(__FILE__) + to_string(__LINE__) + + LOG(string(__FILE__) + to_string(__LINE__) + string(__FUNCTION__) + string(" Unhandled device model for HOTP") , Loglevel::DEBUG); break; diff --git a/device.cc b/device.cc index fcc3ba7..7201087 100644 --- a/device.cc +++ b/device.cc @@ -31,12 +31,12 @@ Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, bool Device::disconnect() { //called in object's destructor - Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); + LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); - Log::instance()(std::string(__FUNCTION__) + std::string(m_model==DeviceModel::PRO?"PRO":"STORAGE"), Loglevel::DEBUG_L2); - Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); + LOG(std::string(__FUNCTION__) + std::string(m_model==DeviceModel::PRO?"PRO":"STORAGE"), Loglevel::DEBUG_L2); + LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); - Log::instance()(std::string("Disconnection success: ") + std::to_string(mp_devhandle == nullptr), Loglevel::DEBUG_L2); + LOG(std::string("Disconnection success: ") + std::to_string(mp_devhandle == nullptr), Loglevel::DEBUG_L2); if(mp_devhandle == nullptr) return false; hid_close(mp_devhandle); @@ -46,24 +46,24 @@ bool Device::disconnect() { return true; } bool Device::connect() { - Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); + LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); - Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); + LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); // hid_init(); // done automatically on hid_open mp_devhandle = hid_open(m_vid, m_pid, nullptr); const auto success = mp_devhandle != nullptr; - Log::instance()(std::string("Connection success: ") + std::to_string(success), Loglevel::DEBUG_L2); + LOG(std::string("Connection success: ") + std::to_string(success), Loglevel::DEBUG_L2); return success; } int Device::send(const void *packet) { - Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); + LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); - Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); + LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); if (mp_devhandle == nullptr) { - Log::instance()(std::string("Connection fail") , Loglevel::DEBUG_L2); + LOG(std::string("Connection fail") , Loglevel::DEBUG_L2); throw DeviceNotConnected("Attempted HID send on an invalid descriptor."); } @@ -72,15 +72,15 @@ int Device::send(const void *packet) { } int Device::recv(void *packet) { - Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); + LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); - Log::instance()(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); + LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); int status; int retry_count = 0; if (mp_devhandle == nullptr){ - Log::instance()(std::string("Connection fail") , Loglevel::DEBUG_L2); + LOG(std::string("Connection fail") , Loglevel::DEBUG_L2); throw DeviceNotConnected("Attempted HID receive on an invalid descriptor."); } @@ -94,20 +94,20 @@ int Device::recv(void *packet) { auto pwherr = hid_error(mp_devhandle); std::wstring wherr = (pwherr != nullptr) ? pwherr : L"No error message"; std::string herr(wherr.begin(), wherr.end()); - Log::instance()(std::string("libhid error message: ") + herr, + LOG(std::string("libhid error message: ") + herr, Loglevel::DEBUG_L2); if (status > 0) break; // success if (retry_count++ >= m_retry_receiving_count) { - Log::instance()( + LOG( "Maximum retry count reached: " + std::to_string(retry_count), Loglevel::WARNING); - Log::instance()( + LOG( std::string("Counter stats: ") + m_counters.get_as_string(), Loglevel::DEBUG); break; } - Log::instance()("Retrying... " + std::to_string(retry_count), + LOG("Retrying... " + std::to_string(retry_count), Loglevel::DEBUG); std::this_thread::sleep_for(m_retry_timeout); } @@ -116,7 +116,7 @@ int Device::recv(void *packet) { } bool Device::could_be_enumerated() { - Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); + LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); if (mp_devhandle==nullptr){ return false; @@ -135,7 +135,7 @@ bool Device::could_be_enumerated() { void Device::show_stats() { auto s = m_counters.get_as_string(); - Log::instance()(s, Loglevel::DEBUG_L2); + LOG(s, Loglevel::DEBUG_L2); } Stick10::Stick10(): diff --git a/include/CommandFailedException.h b/include/CommandFailedException.h index 6ff9a2d..417e850 100644 --- a/include/CommandFailedException.h +++ b/include/CommandFailedException.h @@ -20,7 +20,7 @@ public: CommandFailedException(uint8_t last_command_id, uint8_t last_command_status) : last_command_id(last_command_id), last_command_status(last_command_status){ - nitrokey::log::Log::instance()(std::string("CommandFailedException, status: ")+ std::to_string(last_command_status), nitrokey::log::Loglevel::DEBUG); + LOG(std::string("CommandFailedException, status: ")+ std::to_string(last_command_status), nitrokey::log::Loglevel::DEBUG); } virtual const char *what() const throw() { diff --git a/include/LibraryException.h b/include/LibraryException.h index daf0155..b9303ad 100644 --- a/include/LibraryException.h +++ b/include/LibraryException.h @@ -83,7 +83,7 @@ public: TooLongStringException(size_t size_source, size_t size_destination, const std::string &message = "") : size_source( size_source), size_destination(size_destination), message(message) { - nitrokey::log::Log::instance()(std::string("TooLongStringException, size diff: ")+ std::to_string(size_source-size_destination), nitrokey::log::Loglevel::DEBUG); + LOG(std::string("TooLongStringException, size diff: ")+ std::to_string(size_source-size_destination), nitrokey::log::Loglevel::DEBUG); } diff --git a/include/LongOperationInProgressException.h b/include/LongOperationInProgressException.h index 7f182b0..5b441c0 100644 --- a/include/LongOperationInProgressException.h +++ b/include/LongOperationInProgressException.h @@ -15,7 +15,7 @@ public: LongOperationInProgressException( unsigned char _command_id, uint8_t last_command_status, unsigned char _progress_bar_value) : CommandFailedException(_command_id, last_command_status), progress_bar_value(_progress_bar_value){ - nitrokey::log::Log::instance()( + LOG( std::string("LongOperationInProgressException, progress bar status: ")+ std::to_string(progress_bar_value), nitrokey::log::Loglevel::DEBUG); } diff --git a/include/device_proto.h b/include/device_proto.h index 3519123..ea8f136 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -218,7 +218,7 @@ namespace nitrokey { static std::mutex send_receive_mtx; std::lock_guard guard(send_receive_mtx); - Log::instance()(__FUNCTION__, Loglevel::DEBUG_L2); + LOG(__FUNCTION__, Loglevel::DEBUG_L2); if (dev == nullptr){ throw DeviceNotConnected("Device not initialized"); @@ -236,8 +236,8 @@ namespace nitrokey { outp.payload = payload; outp.update_CRC(); - Log::instance()("Outgoing HID packet:", Loglevel::DEBUG); - Log::instance()(static_cast(outp), Loglevel::DEBUG); + LOG("Outgoing HID packet:", Loglevel::DEBUG); + LOG(static_cast(outp), Loglevel::DEBUG); if (!outp.isValid()) throw std::runtime_error("Invalid outgoing packet"); @@ -249,7 +249,7 @@ namespace nitrokey { status = dev->send(&outp); if (status <= 0){ //FIXME early disconnection not yet working properly -// Log::instance()("Encountered communication error, disconnecting device", Loglevel::DEBUG_L2); +// LOG("Encountered communication error, disconnecting device", Loglevel::DEBUG_L2); // dev->disconnect(); dev->m_counters.sending_error++; throw DeviceSendingFailure( @@ -268,7 +268,7 @@ namespace nitrokey { if (dev->get_device_model() == DeviceModel::STORAGE && resp.command_id >= stick20::CMD_START_VALUE && resp.command_id < stick20::CMD_END_VALUE ) { - Log::instance()(std::string("Detected storage device cmd, status: ") + + LOG(std::string("Detected storage device cmd, status: ") + std::to_string(resp.storage_status.device_status), Loglevel::DEBUG_L2); resp.last_command_status = static_cast(stick10::command_status::ok); @@ -286,7 +286,7 @@ namespace nitrokey { resp.device_status = static_cast(stick10::device_status::ok); break; default: - Log::instance()(std::string("Unknown storage device status, cannot translate: ") + + LOG(std::string("Unknown storage device status, cannot translate: ") + std::to_string(resp.storage_status.device_status), Loglevel::DEBUG); resp.device_status = resp.storage_status.device_status; break; @@ -306,11 +306,11 @@ namespace nitrokey { dev->m_counters.busy++; if (busy_counter++<10) { receiving_retry_counter++; - Log::instance()("Status busy, not decreasing receiving_retry_counter counter: " + + LOG("Status busy, not decreasing receiving_retry_counter counter: " + std::to_string(receiving_retry_counter), Loglevel::DEBUG_L2); } else { busy_counter = 0; - Log::instance()("Status busy, decreasing receiving_retry_counter counter: " + + LOG("Status busy, decreasing receiving_retry_counter counter: " + std::to_string(receiving_retry_counter), Loglevel::DEBUG); } } @@ -320,7 +320,7 @@ namespace nitrokey { successful_communication = true; break; } - Log::instance()(std::string("Retry status - dev status, awaited cmd crc, correct packet CRC: ") + LOG(std::string("Retry status - dev status, awaited cmd crc, correct packet CRC: ") + std::to_string(resp.device_status) + " " + std::to_string(CRC_equal_awaited) + " " + std::to_string(resp.isCRCcorrect()), Loglevel::DEBUG_L2); @@ -329,18 +329,18 @@ namespace nitrokey { if (!CRC_equal_awaited) dev->m_counters.CRC_other_than_awaited++; - Log::instance()( + LOG( "Device is not ready or received packet's last CRC is not equal to sent CRC packet, retrying...", Loglevel::DEBUG); - Log::instance()("Invalid incoming HID packet:", Loglevel::DEBUG_L2); - Log::instance()(static_cast(resp), Loglevel::DEBUG_L2); + LOG("Invalid incoming HID packet:", Loglevel::DEBUG_L2); + LOG(static_cast(resp), Loglevel::DEBUG_L2); dev->m_counters.total_retries++; std::this_thread::sleep_for(dev->get_retry_timeout()); continue; } if (successful_communication) break; - Log::instance()(std::string("Resending (outer loop) "), Loglevel::DEBUG_L2); - Log::instance()(std::string("sending_retry_counter count: ") + std::to_string(sending_retry_counter), + LOG(std::string("Resending (outer loop) "), Loglevel::DEBUG_L2); + LOG(std::string("sending_retry_counter count: ") + std::to_string(sending_retry_counter), Loglevel::DEBUG); } @@ -355,9 +355,9 @@ namespace nitrokey { std::to_string(status)); } - Log::instance()("Incoming HID packet:", Loglevel::DEBUG); - Log::instance()(static_cast(resp), Loglevel::DEBUG); - Log::instance()(std::string("receiving_retry_counter count: ") + std::to_string(receiving_retry_counter), + LOG("Incoming HID packet:", Loglevel::DEBUG); + LOG(static_cast(resp), Loglevel::DEBUG); + LOG(std::string("receiving_retry_counter count: ") + std::to_string(receiving_retry_counter), Loglevel::DEBUG); if (resp.device_status == static_cast(stick10::device_status::busy) && diff --git a/include/log.h b/include/log.h index 695884b..a3e8281 100644 --- a/include/log.h +++ b/include/log.h @@ -53,4 +53,11 @@ class Log { } } + +#ifdef NO_LOG +#define LOG(string, level) while(false){} +#else +#define LOG(string, level) nitrokey::log::Log::instance()((string), (level)) +#endif + #endif diff --git a/include/misc.h b/include/misc.h index c39c741..111d772 100644 --- a/include/misc.h +++ b/include/misc.h @@ -28,7 +28,7 @@ namespace misc { // throw EmptySourceStringException(slot_number); return; const size_t s_dest = sizeof dest; - nitrokey::log::Log::instance()(std::string("strcpyT sizes dest src ") + LOG(std::string("strcpyT sizes dest src ") +std::to_string(s_dest)+ " " +std::to_string(strlen(src))+ " " ,nitrokey::log::Loglevel::DEBUG); -- cgit v1.2.3 From 49e45d532f80c6ffc60c2fbd754030a11dfc8893 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 21 Feb 2017 15:58:47 +0100 Subject: Use nullptr instead of NULL Signed-off-by: Szczepan Zalega --- include/log.h | 2 +- log.cc | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/include/log.h b/include/log.h index a3e8281..7c25918 100644 --- a/include/log.h +++ b/include/log.h @@ -34,7 +34,7 @@ class Log { Log() : mp_loghandler(&stdlog_handler), m_loglevel(Loglevel::WARNING) {} static Log &instance() { - if (mp_instance == NULL) mp_instance = new Log; + if (mp_instance == nullptr) mp_instance = new Log; return *mp_instance; } diff --git a/log.cc b/log.cc index 5889a1e..70853fc 100644 --- a/log.cc +++ b/log.cc @@ -7,7 +7,7 @@ namespace nitrokey { namespace log { -Log *Log::mp_instance = NULL; +Log *Log::mp_instance = nullptr; StdlogHandler stdlog_handler; std::string LogHandler::loglevel_to_str(Loglevel lvl) { @@ -27,7 +27,7 @@ std::string LogHandler::loglevel_to_str(Loglevel lvl) { } void Log::operator()(const std::string &logstr, Loglevel lvl) { - if (mp_loghandler != NULL) + if (mp_loghandler != nullptr) if ((int)(lvl) >= (int)(m_loglevel)) mp_loghandler->print(logstr, lvl); } -- cgit v1.2.3 From 894cef6e839785700250e7ffaf5c8892afecd394 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 22 Feb 2017 18:06:39 +0100 Subject: Comments Signed-off-by: Szczepan Zalega --- include/command_id.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/command_id.h b/include/command_id.h index d0b1454..d1246dd 100644 --- a/include/command_id.h +++ b/include/command_id.h @@ -12,7 +12,7 @@ namespace proto { wrong_password, busy_progressbar, password_matrix_ready, - no_user_password_unlock, + no_user_password_unlock, // FIXME: translate on receive to command status error (fix in firmware?) smartcard_error, security_bit_active }; -- cgit v1.2.3 From 9e40106072be4783a39c3fec37e46922d57a6ee2 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 23 Feb 2017 22:49:51 +0100 Subject: Comment: use clang with TSAN Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0ed907b..d0bc1f8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,7 +14,8 @@ IF (UNIX) ENDIF() IF(ADD_TSAN) SET(EXTRA_LIBS ${EXTRA_LIBS} tsan ) - ADD_DEFINITIONS(-fsanitize=thread -fno-omit-frame-pointer -fPIE -pie -g) + SET(USE_CLANG TRUE) + ADD_DEFINITIONS(-fsanitize=thread -fno-omit-frame-pointer -fPIC -g) #use with clang ENDIF() IF(ADD_TSAN AND ADD_ASAN) message(FATAL_ERROR "TSAN and ASAN cannot be used at the same time") -- cgit v1.2.3 From ee78540d7d9a5d555085b4608ba0ccb4f9ec1801 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 23 Feb 2017 22:50:36 +0100 Subject: Log execution of connect function Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 1e5c14e..4a4f1d9 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -76,6 +76,7 @@ namespace nitrokey{ bool NitrokeyManager::connect(const char *device_model) { std::lock_guard lock(mex_dev_com); + LOG(__FUNCTION__, nitrokey::log::Loglevel::DEBUG_L2); switch (device_model[0]){ case 'P': device = make_shared(); -- cgit v1.2.3 From 34daa03a2be13f9f38fc29336350236a3e9f541e Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 28 Feb 2017 17:32:47 +0100 Subject: Count lifetime instances of device communication exception Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 2 +- DeviceCommunicationExceptions.cpp | 3 +++ include/DeviceCommunicationExceptions.h | 15 ++++++++++++--- 3 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 DeviceCommunicationExceptions.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d0bc1f8..46f5bee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,7 +60,7 @@ set(SOURCE_FILES NitrokeyManager.cc NK_C_API.h NK_C_API.cc -) + DeviceCommunicationExceptions.cpp) IF(UNIX) # add_library(hidapi-libusb STATIC hidapi/libusb/hid.c ) diff --git a/DeviceCommunicationExceptions.cpp b/DeviceCommunicationExceptions.cpp new file mode 100644 index 0000000..a470a48 --- /dev/null +++ b/DeviceCommunicationExceptions.cpp @@ -0,0 +1,3 @@ +#include "DeviceCommunicationExceptions.h" + +std::atomic_int DeviceCommunicationException::occurred {0}; diff --git a/include/DeviceCommunicationExceptions.h b/include/DeviceCommunicationExceptions.h index 78fc625..6d21561 100644 --- a/include/DeviceCommunicationExceptions.h +++ b/include/DeviceCommunicationExceptions.h @@ -1,16 +1,24 @@ #ifndef LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H #define LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H +#include #include +#include #include -//class DeviceCommunicationException: public std::exception { -class DeviceCommunicationException: public std::runtime_error{ + +class DeviceCommunicationException: public std::runtime_error +{ std::string message; + static std::atomic_int occurred; public: - DeviceCommunicationException(std::string _msg): runtime_error(_msg), message(_msg){} + DeviceCommunicationException(std::string _msg): std::runtime_error(_msg), message(_msg){ + ++occurred; + } // virtual const char* what() const throw() override { // return message.c_str(); // } + static bool has_occurred(){ return occurred > 0; }; + static void reset_occurred_flag(){ occurred = 0; }; }; class DeviceNotConnected: public DeviceCommunicationException { @@ -28,4 +36,5 @@ public: DeviceReceivingFailure(std::string msg) : DeviceCommunicationException(msg){} }; + #endif //LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H -- cgit v1.2.3 From f12b6a9c29f8d236ca969f45d3be1cd9ee5a749f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 28 Feb 2017 19:13:01 +0100 Subject: Reorder includes Signed-off-by: Szczepan Zalega --- include/stick10_commands.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/stick10_commands.h b/include/stick10_commands.h index 676aabc..a50d0ae 100644 --- a/include/stick10_commands.h +++ b/include/stick10_commands.h @@ -6,8 +6,8 @@ #include #include #include -#include "command.h" #include "device_proto.h" +#include "command.h" #pragma pack (push,1) -- cgit v1.2.3 From 802dd4543b7634f498bd44909461eae6d7975abb Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 28 Feb 2017 21:02:30 +0100 Subject: Make device-level reconnect on problem with sending Make it 3 times before throwing exception Call hid_exit on last device disconnection Signed-off-by: Szczepan Zalega --- device.cc | 56 +++++++++++++++++++++++++++++++++++++++++++++++++------- include/device.h | 8 +++++++- 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/device.cc b/device.cc index 7201087..44ec5c3 100644 --- a/device.cc +++ b/device.cc @@ -15,6 +15,8 @@ using namespace nitrokey::device; using namespace nitrokey::log; using namespace std::chrono; +std::atomic_int Device::instances_count{0}; + Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, const milliseconds send_receive_delay, const int retry_receiving_count, const milliseconds retry_timeout) @@ -27,13 +29,19 @@ Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model, last_command_status(0), m_model(model), m_send_receive_delay(send_receive_delay) -{} +{ + instances_count++; +} bool Device::disconnect() { //called in object's destructor LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); - LOG(std::string(__FUNCTION__) + std::string(m_model==DeviceModel::PRO?"PRO":"STORAGE"), Loglevel::DEBUG_L2); + return _disconnect(); +} + +bool Device::_disconnect() { + LOG(std::string(__FUNCTION__) + std::string(m_model == DeviceModel::PRO ? "PRO" : "STORAGE"), Loglevel::DEBUG_L2); LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); LOG(std::string("Disconnection success: ") + std::to_string(mp_devhandle == nullptr), Loglevel::DEBUG_L2); @@ -41,14 +49,21 @@ bool Device::disconnect() { hid_close(mp_devhandle); mp_devhandle = nullptr; - //FIXME hidexit should not be called if some devices are still active - use static active devices counter - // hid_exit(); + if (instances_count == 1){ + LOG(std::string("Calling hid_exit"), Loglevel::DEBUG_L2); + hid_exit(); + } return true; } + bool Device::connect() { LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard lock(mex_dev_com); - LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); + return _connect(); +} + +bool Device::_connect() { + LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); // hid_init(); // done automatically on hid_open mp_devhandle = hid_open(m_vid, m_pid, nullptr); @@ -67,8 +82,16 @@ int Device::send(const void *packet) { throw DeviceNotConnected("Attempted HID send on an invalid descriptor."); } - return (hid_send_feature_report( - mp_devhandle, (const unsigned char *)(packet), HID_REPORT_SIZE)); + int send_feature_report = -1; + + for (int i = 0; i < 3 && send_feature_report < 0; ++i) { + send_feature_report = hid_send_feature_report( + mp_devhandle, (const unsigned char *)(packet), HID_REPORT_SIZE); + if (send_feature_report < 0) _reconnect(); + //add thread sleep? + LOG(std::string("Sending attempt: ")+std::to_string(i) + " / 3" , Loglevel::DEBUG_L2); + } + return send_feature_report; } int Device::recv(void *packet) { @@ -138,6 +161,23 @@ void Device::show_stats() { LOG(s, Loglevel::DEBUG_L2); } +void Device::_reconnect() { + if (mex_dev_com.try_lock()){ + throw std::runtime_error("mutex should be locked before entering this function"); + } + LOG(__FUNCTION__, Loglevel::DEBUG_L2); + ++m_counters.low_level_reconnect; + _disconnect(); + _connect(); + +} + +Device::~Device() { + show_stats(); + disconnect(); + instances_count--; +} + Stick10::Stick10(): Device(0x20a0, 0x4108, DeviceModel::PRO, 100ms, 5, 100ms) {} @@ -167,7 +207,9 @@ std::string Device::ErrorCounters::get_as_string() { p(CRC_other_than_awaited); p(wrong_CRC); ss << "), "; + p(low_level_reconnect); p(sending_error); p(receiving_error); return ss.str(); } +#undef p \ No newline at end of file diff --git a/include/device.h b/include/device.h index 5d7ee12..7b300e5 100644 --- a/include/device.h +++ b/include/device.h @@ -50,6 +50,7 @@ public: cnt busy_progressbar; cnt command_result_not_equal_0_recv; cnt communication_successful; + cnt low_level_reconnect; std::string get_as_string(); } m_counters = {}; @@ -59,7 +60,7 @@ public: const milliseconds send_receive_delay, const int retry_receiving_count, const milliseconds retry_timeout); - virtual ~Device(){show_stats(); disconnect();} + virtual ~Device(); // lack of device is not actually an error, // so it doesn't throw @@ -97,6 +98,9 @@ public: DeviceModel get_device_model() const {return m_model;} private: std::atomic last_command_status; + void _reconnect(); + bool _connect(); + bool _disconnect(); protected: const uint16_t m_vid; @@ -115,6 +119,8 @@ protected: std::atomicmp_devhandle; + + static std::atomic_int instances_count; }; class Stick10 : public Device { -- cgit v1.2.3 From 7ab1b59b13477310d0ff631dd9e6686d6ebf4e91 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 28 Feb 2017 22:41:27 +0100 Subject: Remove checking for mutex being locked Signed-off-by: Szczepan Zalega --- device.cc | 4 ---- 1 file changed, 4 deletions(-) diff --git a/device.cc b/device.cc index 44ec5c3..940a654 100644 --- a/device.cc +++ b/device.cc @@ -162,14 +162,10 @@ void Device::show_stats() { } void Device::_reconnect() { - if (mex_dev_com.try_lock()){ - throw std::runtime_error("mutex should be locked before entering this function"); - } LOG(__FUNCTION__, Loglevel::DEBUG_L2); ++m_counters.low_level_reconnect; _disconnect(); _connect(); - } Device::~Device() { -- cgit v1.2.3 From 29375e7953041766de7c44ea5574cf80d5916e41 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 28 Feb 2017 22:50:45 +0100 Subject: Do reconnect also on receiving failure Signed-off-by: Szczepan Zalega --- device.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/device.cc b/device.cc index 940a654..ddbfe85 100644 --- a/device.cc +++ b/device.cc @@ -130,6 +130,7 @@ int Device::recv(void *packet) { Loglevel::DEBUG); break; } + _reconnect(); LOG("Retrying... " + std::to_string(retry_count), Loglevel::DEBUG); std::this_thread::sleep_for(m_retry_timeout); -- cgit v1.2.3 From e4ff28a31b0cfd1821d0a7418aba5f71a1cffb8c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 28 Feb 2017 22:55:16 +0100 Subject: Remove obsolete comments Signed-off-by: Szczepan Zalega --- device.cc | 3 --- 1 file changed, 3 deletions(-) diff --git a/device.cc b/device.cc index ddbfe85..35e7a78 100644 --- a/device.cc +++ b/device.cc @@ -107,13 +107,10 @@ int Device::recv(void *packet) { throw DeviceNotConnected("Attempted HID receive on an invalid descriptor."); } - // FIXME extract error handling and repeating to parent function in - // device_proto:192 for (;;) { status = (hid_get_feature_report(mp_devhandle, (unsigned char *)(packet), HID_REPORT_SIZE)); - // FIXME handle getting libhid error message somewhere else auto pwherr = hid_error(mp_devhandle); std::wstring wherr = (pwherr != nullptr) ? pwherr : L"No error message"; std::string herr(wherr.begin(), wherr.end()); -- cgit v1.2.3 From 097c9ecf42d2724a074ea9e0d317ed5f38b5ca37 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Mar 2017 13:47:52 +0100 Subject: Prefer to use log-enabled library in tests Signed-off-by: Szczepan Zalega --- unittest/conftest.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/unittest/conftest.py b/unittest/conftest.py index f43f153..67b45aa 100644 --- a/unittest/conftest.py +++ b/unittest/conftest.py @@ -29,7 +29,23 @@ def C(request): print(declaration) ffi.cdef(declaration, override=True) - C = ffi.dlopen("../build/libnitrokey.so") + C = None + import os, sys + path_build = os.path.join("..", "build") + paths = [ os.path.join(path_build,"libnitrokey-log.so"), + os.path.join(path_build,"libnitrokey.so")] + for p in paths: + print p + if os.path.exists(p): + C = ffi.dlopen(p) + break + else: + print("File does not exist: " + p) + print("Trying another") + if not C: + print("No library file found") + sys.exit(1) + C.NK_set_debug(False) nk_login = C.NK_login_auto() if nk_login != 1: -- cgit v1.2.3 From f7101225f26176f62ef3df48bd20d43521210987 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Mar 2017 13:49:13 +0100 Subject: Update encrypted volume test. Use random password. Randomizing password to ensure correctness of setting up hidden volume in current iteration Signed-off-by: Szczepan Zalega --- unittest/test_storage.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/unittest/test_storage.py b/unittest/test_storage.py index 9c01382..da7c9a3 100644 --- a/unittest/test_storage.py +++ b/unittest/test_storage.py @@ -58,10 +58,10 @@ def test_encrypted_volume_unlock_hidden(C): assert C.NK_unlock_hidden_volume(hidden_volume_password) == DeviceErrorCode.STATUS_OK -@pytest.mark.skip(reason='hangs device, to report') -def test_encrypted_volume_setup_multiple_hidden(C): - skip_if_device_version_lower_than({'S': 43}) - hidden_volume_password = 'hiddenpassword' +def test_encrypted_volume_setup_multiple_hidden_lock(C): + import random + skip_if_device_version_lower_than({'S': 45}) #hangs device on lower version + hidden_volume_password = 'hiddenpassword' + str(random.randint(0,100)) p = lambda i: hidden_volume_password + str(i) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK -- cgit v1.2.3 From 9e659919a4b2da8855a1c7ec83edb685e6fec663 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Mar 2017 15:43:28 +0100 Subject: Authenticate before factory reset so the command will not timeout To investigate later Signed-off-by: Szczepan Zalega --- unittest/test_pro.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/unittest/test_pro.py b/unittest/test_pro.py index 0ad42e1..67fc585 100644 --- a/unittest/test_pro.py +++ b/unittest/test_pro.py @@ -147,6 +147,9 @@ def test_regenerate_aes_key(C): def test_enable_password_safe_after_factory_reset(C): assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + if is_storage(C): + # for some reason storage likes to be authenticated before reset (to investigate) + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_factory_reset(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK wait(10) if is_storage(C): -- cgit v1.2.3 From 1b1a3211faa806d656b0ebb50864348c595857ed Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 6 Mar 2017 15:43:52 +0100 Subject: Correct comments and fix firmware version requirements Signed-off-by: Szczepan Zalega --- unittest/test_pro.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/unittest/test_pro.py b/unittest/test_pro.py index 67fc585..0140994 100644 --- a/unittest/test_pro.py +++ b/unittest/test_pro.py @@ -58,6 +58,7 @@ def test_write_all_password_safe_slots_and_read_10_times(C): @pytest.mark.slowtest +@pytest.mark.xfail(reason="This test should be run directly after test_write_all_password_safe_slots_and_read_10_times") def test_read_all_password_safe_slots_10_times(C): def fill(s, wid): assert wid >= len(s) @@ -591,7 +592,7 @@ def test_OTP_secret_started_from_null(C, secret): skip_if_device_version_lower_than({'S': 43, 'P': 8}) if len(secret) > 40: # feature: 320 bit long secret handling - skip_if_device_version_lower_than({'S': 44, 'P': 8}) + skip_if_device_version_lower_than({'P': 8}) oath = pytest.importorskip("oath") lib_at = lambda t: oath.hotp(secret, t, format='dec6') @@ -685,8 +686,9 @@ def test_TOTP_secrets(C, secret): ''' skip_if_device_version_lower_than({'S': 44, 'P': 8}) - if is_pro_rtm_07(C) and len(secret)>20*2: #*2 since secret is in hex - pytest.skip("Secret lengths over 20 bytes are not supported by NK Pro 0.7 ") + if len(secret)>20*2: #*2 since secret is in hex + # pytest.skip("Secret lengths over 20 bytes are not supported by NK Pro 0.7 and NK Storage") + skip_if_device_version_lower_than({'P': 8}) slot_number = 0 time = 0 period = 30 @@ -764,7 +766,7 @@ def test_edit_OTP_slot(C): """ should change slots counter and name without changing its secret (using null secret for second update) """ - # counter does not reset under Storage v0.43 + # counter is not getting updated under Storage v0.43 - #TOREPORT skip_if_device_version_lower_than({'S': 44, 'P': 7}) secret = RFC_SECRET -- cgit v1.2.3 From 257062b9a5130cf25dfd26d4ec93880abde1c9ce Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 7 Mar 2017 11:37:41 +0100 Subject: Check for null device reference in case of failed reconnection Signed-off-by: Szczepan Zalega --- device.cc | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/device.cc b/device.cc index 35e7a78..9a64813 100644 --- a/device.cc +++ b/device.cc @@ -77,14 +77,13 @@ int Device::send(const void *packet) { std::lock_guard lock(mex_dev_com); LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2); - if (mp_devhandle == nullptr) { - LOG(std::string("Connection fail") , Loglevel::DEBUG_L2); - throw DeviceNotConnected("Attempted HID send on an invalid descriptor."); - } - int send_feature_report = -1; for (int i = 0; i < 3 && send_feature_report < 0; ++i) { + if (mp_devhandle == nullptr) { + LOG(std::string("Connection fail") , Loglevel::DEBUG_L2); + throw DeviceNotConnected("Attempted HID send on an invalid descriptor."); + } send_feature_report = hid_send_feature_report( mp_devhandle, (const unsigned char *)(packet), HID_REPORT_SIZE); if (send_feature_report < 0) _reconnect(); @@ -101,13 +100,12 @@ int Device::recv(void *packet) { int status; int retry_count = 0; - - if (mp_devhandle == nullptr){ - LOG(std::string("Connection fail") , Loglevel::DEBUG_L2); - throw DeviceNotConnected("Attempted HID receive on an invalid descriptor."); - } - for (;;) { + if (mp_devhandle == nullptr){ + LOG(std::string("Connection fail") , Loglevel::DEBUG_L2); + throw DeviceNotConnected("Attempted HID receive on an invalid descriptor."); + } + status = (hid_get_feature_report(mp_devhandle, (unsigned char *)(packet), HID_REPORT_SIZE)); -- cgit v1.2.3 From 7132b01a499568c21a7ec64b9c58672541bbb7f6 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 7 Mar 2017 16:57:47 +0100 Subject: Handle enabling update mode on Storage device Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 4 ++++ include/NitrokeyManager.h | 1 + 2 files changed, 5 insertions(+) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 4a4f1d9..630a4e4 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -735,6 +735,10 @@ namespace nitrokey{ misc::execute_password_command(device, admin_pin); } + void NitrokeyManager::enable_firmware_update(const char* firmware_pin) { + misc::execute_password_command(device, firmware_pin); + } + void NitrokeyManager::clear_new_sd_card_warning(const char* admin_pin) { misc::execute_password_command(device, admin_pin); } diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index d49941e..71ac6fa 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -101,6 +101,7 @@ namespace nitrokey { void set_unencrypted_read_write(const char *user_pin); void export_firmware(const char *admin_pin); + void enable_firmware_update(const char *firmware_pin); void clear_new_sd_card_warning(const char *admin_pin); -- cgit v1.2.3 From 019d86a056ecb036da243a3304a3220b15e0bfd5 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 7 Mar 2017 17:31:46 +0100 Subject: Add TODO comment Signed-off-by: Szczepan Zalega --- include/device_proto.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/device_proto.h b/include/device_proto.h index ea8f136..1eb637f 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -370,7 +370,7 @@ namespace nitrokey { if (!resp.isValid()) throw std::runtime_error("Invalid incoming packet"); if (receiving_retry_counter <= 0) - throw std::runtime_error( + throw std::runtime_error( //TODO change to other kind to handle correctly by caller, communication exception? "Maximum receiving_retry_counter count reached for receiving response from the device!"); dev->m_counters.communication_successful++; -- cgit v1.2.3 From a3303c491a6f3b9980a91cabe81d5fb643ec8d9a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 9 Mar 2017 12:07:27 +0100 Subject: Set turbo mode Signed-off-by: Szczepan Zalega --- device.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/device.cc b/device.cc index 9a64813..66877da 100644 --- a/device.cc +++ b/device.cc @@ -176,7 +176,7 @@ Stick10::Stick10(): Stick20::Stick20(): - Device(0x20a0, 0x4109, DeviceModel::STORAGE, 200ms, 5, 200ms) + Device(0x20a0, 0x4109, DeviceModel::STORAGE, 20ms, 20, 20ms) {} #include -- cgit v1.2.3 From a9c42dea301329136f663ebc9482a1d38feada29 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 9 Mar 2017 17:33:56 +0100 Subject: Allow to check is current device visible to the OS Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 8 ++++++++ include/NitrokeyManager.h | 4 +++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 630a4e4..140d4d3 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -129,7 +129,15 @@ namespace nitrokey{ } } return false; + } + + bool NitrokeyManager::could_current_device_be_enumerated() { + std::lock_guard lock(mex_dev_com); + if (device != nullptr) { + return device->could_be_enumerated(); } + return false; + } void NitrokeyManager::set_debug(bool state) { if (state){ diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 71ac6fa..4f11314 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -44,7 +44,9 @@ namespace nitrokey { bool connect(); bool disconnect(); bool is_connected() throw() ; - DeviceModel get_connected_device_model() const; + bool could_current_device_be_enumerated(); + + DeviceModel get_connected_device_model() const; void set_debug(bool state); stick10::GetStatus::ResponsePayload get_status(); string get_status_as_string(); -- cgit v1.2.3 From 6c2e2c8177ff6bf5731ea25f3211fc6d889628d6 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 9 Mar 2017 17:35:39 +0100 Subject: Use own exception types instead of general runtime_error Signed-off-by: Szczepan Zalega --- include/device_proto.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/device_proto.h b/include/device_proto.h index 1eb637f..f1f52d6 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -239,7 +239,7 @@ namespace nitrokey { LOG("Outgoing HID packet:", Loglevel::DEBUG); LOG(static_cast(outp), Loglevel::DEBUG); - if (!outp.isValid()) throw std::runtime_error("Invalid outgoing packet"); + if (!outp.isValid()) throw DeviceSendingFailure("Invalid outgoing packet"); bool successful_communication = false; int receiving_retry_counter = 0; @@ -368,9 +368,9 @@ namespace nitrokey { resp.command_id, resp.device_status, resp.storage_status.progress_bar_value); } - if (!resp.isValid()) throw std::runtime_error("Invalid incoming packet"); + if (!resp.isValid()) throw DeviceReceivingFailure("Invalid incoming packet"); if (receiving_retry_counter <= 0) - throw std::runtime_error( //TODO change to other kind to handle correctly by caller, communication exception? + throw DeviceReceivingFailure( "Maximum receiving_retry_counter count reached for receiving response from the device!"); dev->m_counters.communication_successful++; -- cgit v1.2.3 From 077aa887ba94e93006feadc28a06c13c829d318a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 9 Mar 2017 17:36:39 +0100 Subject: Dynamically increase delay between retries on busy status Signed-off-by: Szczepan Zalega --- include/device_proto.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/include/device_proto.h b/include/device_proto.h index f1f52d6..b137689 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -261,6 +261,8 @@ namespace nitrokey { // FIXME make checks done in device:recv here receiving_retry_counter = dev->get_retry_receiving_count(); + int busy_counter = 0; + auto retry_timeout = dev->get_retry_timeout(); while (receiving_retry_counter-- > 0) { dev->m_counters.recv_executed++; status = dev->recv(&resp); @@ -302,16 +304,17 @@ namespace nitrokey { break; } if (resp.device_status == static_cast(stick10::device_status::busy)) { - static int busy_counter = 0; dev->m_counters.busy++; if (busy_counter++<10) { receiving_retry_counter++; LOG("Status busy, not decreasing receiving_retry_counter counter: " + std::to_string(receiving_retry_counter), Loglevel::DEBUG_L2); } else { + retry_timeout *= 2; busy_counter = 0; LOG("Status busy, decreasing receiving_retry_counter counter: " + - std::to_string(receiving_retry_counter), Loglevel::DEBUG); + std::to_string(receiving_retry_counter) + ", current delay:" + + std::to_string(retry_timeout.count()), Loglevel::DEBUG); } } if (resp.device_status == static_cast(stick10::device_status::busy) && @@ -335,7 +338,7 @@ namespace nitrokey { LOG("Invalid incoming HID packet:", Loglevel::DEBUG_L2); LOG(static_cast(resp), Loglevel::DEBUG_L2); dev->m_counters.total_retries++; - std::this_thread::sleep_for(dev->get_retry_timeout()); + std::this_thread::sleep_for(retry_timeout); continue; } if (successful_communication) break; -- cgit v1.2.3 From aa9baa019bb53d83625e0a296efc744ef351fd45 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 11 Mar 2017 13:47:41 +0100 Subject: Add tested Travis build configuration. Set proper hidapi url. Signed-off-by: Szczepan Zalega --- .gitmodules | 2 +- .travis.yml | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ CMakeLists.txt | 2 +- 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 .travis.yml diff --git a/.gitmodules b/.gitmodules index 4c898f5..1656b22 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,4 +6,4 @@ url = https://github.com/pybind/pybind11.git [submodule "hidapi"] path = hidapi - url = git@github.com:szszszsz/hidapi.git + url = https://github.com/szszszsz/hidapi.git diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..ba4465b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,58 @@ +language: generic +sudo: false +os: osx +env: CF= + +matrix: + include: +# - osx_image: xcode7.3 #default +# before_install: &brew +# - brew update +# - brew install hidapi + - osx_image: xcode6.4 + - osx_image: xcode8.2 + - os: linux + dist: trusty + env: COMPILER_NAME=gcc CXX=g++-5 CC=gcc-5 CF=-DCOMPILE_TESTS=ON + addons: + apt: + packages: + - cmake + - libhidapi-dev + - g++-5 + sources: &sources + - ubuntu-toolchain-r-test + - os: linux + dist: trusty + env: COMPILER_NAME=gcc CXX=g++-6 CC=gcc-6 CF=-DCOMPILE_TESTS=ON + addons: + apt: + packages: + - cmake + - libhidapi-dev + - g++-6 + sources: *sources + - os: linux + dist: trusty + env: COMPILER_NAME=clang CXX=clang++-3.8 CC=clang-3.8 CF=-DCOMPILE_TESTS=ON + addons: + apt: + packages: + - cmake + - libhidapi-dev + - g++-5 + - clang-3.8 + sources: *sources + + +install: + - mkdir -p build + - cd build +# - export CXXFLAGS="${CXX_FLAGS} -Wall -Wextra -Werror" # TODO enable when fixed + - ${CXX} --version || true + - cmake --version + - cmake .. ${CF} + +script: + - make -j2 +# - make test # TODO add library device-less tests \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 46f5bee..46405a9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.1) IF (UNIX) OPTION(USE_CLANG "Use CLang" FALSE) IF(USE_CLANG) -- cgit v1.2.3 From 9cfce3cf6b531b01296dbebc1cc7844c1e049478 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 11 Mar 2017 13:48:02 +0100 Subject: Fix compilation warnings Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 4 ++-- NK_C_API.h | 4 ++-- unittest/test_C_API.cpp | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index 05102cc..262a0a4 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -279,14 +279,14 @@ NK_C_API int NK_totp_get_time(){ }); } -NK_C_API int NK_change_admin_PIN(char *current_PIN, char *new_PIN){ +NK_C_API int NK_change_admin_PIN(const char *current_PIN, const char *new_PIN){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->change_admin_PIN(current_PIN, new_PIN); }); } -NK_C_API int NK_change_user_PIN(char *current_PIN, char *new_PIN){ +NK_C_API int NK_change_user_PIN(const char *current_PIN, const char *new_PIN){ auto m = NitrokeyManager::instance(); return get_without_result([&](){ m->change_user_PIN(current_PIN, new_PIN); diff --git a/NK_C_API.h b/NK_C_API.h index dd31287..f52034a 100644 --- a/NK_C_API.h +++ b/NK_C_API.h @@ -244,7 +244,7 @@ NK_C_API int NK_totp_get_time(); * @param new_PIN char[25](Pro) new PIN * @return command processing error code */ -NK_C_API int NK_change_admin_PIN(char *current_PIN, char *new_PIN); +NK_C_API int NK_change_admin_PIN(const char *current_PIN, const char *new_PIN); /** * Change user PIN @@ -252,7 +252,7 @@ NK_C_API int NK_change_admin_PIN(char *current_PIN, char *new_PIN); * @param new_PIN char[25](Pro) new PIN * @return command processing error code */ -NK_C_API int NK_change_user_PIN(char *current_PIN, char *new_PIN); +NK_C_API int NK_change_user_PIN(const char *current_PIN, const char *new_PIN); /** diff --git a/unittest/test_C_API.cpp b/unittest/test_C_API.cpp index 37d3c7f..160145b 100644 --- a/unittest/test_C_API.cpp +++ b/unittest/test_C_API.cpp @@ -24,8 +24,8 @@ TEST_CASE("Check retry count", "[BASIC]") { } TEST_CASE("Check long strings", "[STANDARD]") { - char* longPin = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - char *pin = "123123123"; + const char* longPin = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const char* pin = "123123123"; auto result = NK_change_user_PIN(longPin, pin); REQUIRE(result == TOO_LONG_STRING); result = NK_change_user_PIN(pin, longPin); -- cgit v1.2.3 From ac6b9c18ef55f4cd36e85069cf0cf82c14e04404 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 11 Mar 2017 16:53:44 +0100 Subject: Cleanup modules Remove unused PyBind11 Update hidapi git path Signed-off-by: Szczepan Zalega --- .gitmodules | 5 +---- python_bindings/pybind11 | 1 - 2 files changed, 1 insertion(+), 5 deletions(-) delete mode 160000 python_bindings/pybind11 diff --git a/.gitmodules b/.gitmodules index 1656b22..4608496 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ [submodule "unittest/Catch"] path = unittest/Catch url = https://github.com/philsquared/Catch.git -[submodule "pybind11"] - path = python_bindings/pybind11 - url = https://github.com/pybind/pybind11.git [submodule "hidapi"] path = hidapi - url = https://github.com/szszszsz/hidapi.git + url = https://github.com/Nitrokey/hidapi.git diff --git a/python_bindings/pybind11 b/python_bindings/pybind11 deleted file mode 160000 index 1f66a58..0000000 --- a/python_bindings/pybind11 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1f66a584278dfd1ad88be19d5e4996302793a191 -- cgit v1.2.3