From 89076a0c44dd12a73060dbfda419c20c4ce5285a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 18:12:37 +0200 Subject: Migrate commands to new format Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 134 +++++++++++++++++++++------------------------ unittest/test2.cc | 83 ++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+), 71 deletions(-) create mode 100644 unittest/test2.cc diff --git a/include/stick20_commands.h b/include/stick20_commands.h index f4e7500..8e758d4 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -82,68 +82,67 @@ namespace stick20 { CommandTransaction; }; -class EnableEncryptedPartition : semantics::non_constructible { +class EnableEncryptedPartition : Command{ public: struct CommandPayload { uint8_t password[30]; // TODO check w/ firmware }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class DisableEncryptedPartition : semantics::non_constructible { +class DisableEncryptedPartition : Command{ public: - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class EnableHiddenEncryptedPartition : semantics::non_constructible { +class EnableHiddenEncryptedPartition :Command{ public: struct CommandPayload { uint8_t password[30]; // TODO check w/ firmware }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class DisableHiddenEncryptedPartition : semantics::non_constructible { +class DisableHiddenEncryptedPartition :Command{ public: - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class EnableFirmwareUpdate : semantics::non_constructible { +class EnableFirmwareUpdate :Command{ public: struct CommandPayload { uint8_t password[30]; // TODO check w/ firmware }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class UpdatePassword : semantics::non_constructible { +class UpdatePassword :Command{ public: struct CommandPayload { uint8_t old_password[15]; uint8_t new_password[15]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class ExportFirmware : semantics::non_constructible { +class ExportFirmware :Command{ public: struct CommandPayload { uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; class CreateNewKeys : Command { @@ -166,50 +165,47 @@ class ExportFirmware : semantics::non_constructible { }; -class FillSDCardWithRandomChars : semantics::non_constructible { +class FillSDCardWithRandomChars :Command{ public: struct CommandPayload { uint8_t volume_flag; uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SetupHiddenVolume : semantics::non_constructible { +class SetupHiddenVolume :Command{ public: - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendPasswordMatrix : semantics::non_constructible { +class SendPasswordMatrix :Command{ public: - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendPasswordMatrixPinData : semantics::non_constructible { +class SendPasswordMatrixPinData :Command{ public: struct CommandPayload { uint8_t pin_data[30]; // TODO how long actually can it be? }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendPasswordMatrixSetup : semantics::non_constructible { +class SendPasswordMatrixSetup :Command{ public: struct CommandPayload { uint8_t setup_data[30]; // TODO how long actually can it be? }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; #define d(x) ss << " "#x":\t" << (int)x << std::endl; @@ -246,95 +242,91 @@ class SendPasswordMatrixSetup : semantics::non_constructible { }; -class SendPassword : semantics::non_constructible { +class SendPassword :Command{ public: struct CommandPayload { uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendNewPassword : semantics::non_constructible { +class SendNewPassword :Command{ public: struct CommandPayload { uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; // TODO fix original nomenclature -class SendSetReadonlyToUncryptedVolume : semantics::non_constructible { +class SendSetReadonlyToUncryptedVolume :Command{ public: struct CommandPayload { uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendSetReadwriteToUncryptedVolume : semantics::non_constructible { +class SendSetReadwriteToUncryptedVolume :Command{ public: struct CommandPayload { uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendClearNewSdCardFound : semantics::non_constructible { +class SendClearNewSdCardFound :Command{ public: struct CommandPayload { uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendStartup : semantics::non_constructible { +class SendStartup :Command{ public: struct CommandPayload { uint64_t localtime; // POSIX }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class SendHiddenVolumeSetup : semantics::non_constructible { +class SendHiddenVolumeSetup :Command{ public: struct CommandPayload { // TODO HiddenVolumeSetup_tst type }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class LockFirmware : semantics::non_constructible { +class LockFirmware :Command{ public: struct CommandPayload { uint8_t password[30]; }; - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; -class ProductionTest : semantics::non_constructible { +class ProductionTest :Command{ public: - typedef Transaction CommandTransaction; + typedef Transaction + CommandTransaction; }; } } diff --git a/unittest/test2.cc b/unittest/test2.cc new file mode 100644 index 0000000..6744b45 --- /dev/null +++ b/unittest/test2.cc @@ -0,0 +1,83 @@ +#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() +#include "catch.hpp" + +#include +#include +#include "device_proto.h" +#include "log.h" +#include "stick10_commands.h" + +using namespace std; +using namespace nitrokey::device; +using namespace nitrokey::proto::stick10; +using namespace nitrokey::log; +using namespace nitrokey::misc; + + +std::string getSlotName(Stick10 &stick, int slotNo) { + auto slot_req = get_payload(); + slot_req.slot_number = slotNo; + auto slot = ReadSlot::CommandTransaction::run(stick, slot_req); + std::string sName(reinterpret_cast(slot.data().slot_name)); + return sName; +} + +TEST_CASE("Slot names are correct", "[slotNames]") { + Stick10 stick; + bool connected = stick.connect(); + REQUIRE(connected == true); + + Log::instance().set_loglevel(Loglevel::DEBUG); + + auto resp = GetStatus::CommandTransaction::run(stick); + + auto authreq = get_payload(); + strcpy((char *)(authreq.card_password), "12345678"); + FirstAuthenticate::CommandTransaction::run(stick, authreq); + + { + auto authreq = get_payload(); + strcpy((char *)(authreq.user_password), "123456"); + EnablePasswordSafe::CommandTransaction::run(stick, authreq); + } + + //assuming these values were set earlier, thus failing on normal use + REQUIRE(getSlotName(stick, 0x20) == std::string("1")); + REQUIRE(getSlotName(stick, 0x21) == std::string("slot2")); + + { + auto resp = GetPasswordRetryCount::CommandTransaction::run(stick); + REQUIRE(resp.data().password_retry_count == 3); + } + { + auto resp = GetUserPasswordRetryCount::CommandTransaction::run(stick); + REQUIRE(resp.data().password_retry_count == 3); + } + + { + auto slot = get_payload(); + slot.slot_number = 0; + auto resp2 = GetPasswordSafeSlotName::CommandTransaction::run(stick, slot); + std::string sName(reinterpret_cast(resp2.data().slot_name)); + REQUIRE(sName == std::string("web1")); + } + + { + auto slot = get_payload(); + slot.slot_number = 0; + auto resp2 = + GetPasswordSafeSlotPassword::CommandTransaction::run(stick, slot); + std::string sName(reinterpret_cast(resp2.data().slot_password)); + REQUIRE(sName == std::string("pass1")); + } + + { + auto slot = get_payload(); + slot.slot_number = 0; + auto resp2 = GetPasswordSafeSlotLogin::CommandTransaction::run(stick, slot); + std::string sName(reinterpret_cast(resp2.data().slot_login)); + REQUIRE(sName == std::string("login1")); + } + + stick.disconnect(); +} -- cgit v1.2.3 From 3f7aaa09e8f83b68aac29693b536b2d1e6619d83 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 18:13:03 +0200 Subject: Code reformat Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 634 +++++++++++++++++++++++---------------------- 1 file changed, 322 insertions(+), 312 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 8e758d4..86ac053 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -1,5 +1,6 @@ #ifndef STICK20_COMMANDS_H #define STICK20_COMMANDS_H + #include "inttypes.h" #include "command.h" #include @@ -8,328 +9,337 @@ namespace nitrokey { -namespace proto { + namespace proto { /* * STICK20 protocol command ids * a superset (almost) of STICK10 */ -namespace stick20 { - - enum class PasswordKind : uint8_t { - User = 'P', - Admin = 'A' - }; - - class ChangeAdminUserPin20Current : Command { - public: - struct CommandPayload { - uint8_t kind; - uint8_t old_pin[20]; - std::string dissect() const { - std::stringstream ss; - ss << " old_pin:\t" << old_pin<< std::endl; - return ss.str(); - } - void set_kind(PasswordKind k){ - kind = (uint8_t)k; - } - } __packed; - - typedef Transaction - CommandTransaction; - }; - - - class ChangeAdminUserPin20New : Command { - public: - - struct CommandPayload { - uint8_t kind; - uint8_t new_pin[20]; - std::string dissect() const { - std::stringstream ss; - ss << " new_pin:\t" << new_pin<< std::endl; - return ss.str(); - } - void set_kind(PasswordKind k){ - kind = (uint8_t)k; - } - - } __packed; - - typedef Transaction - CommandTransaction; - }; - - - class UnlockUserPassword : Command { - public: - struct CommandPayload { - uint8_t kind; - uint8_t user_new_password[20]; - std::string dissect() const { - std::stringstream ss; - ss << " user_new_password:\t" << user_new_password<< std::endl; - return ss.str(); - } - void set_kind(PasswordKind k){ - kind = (uint8_t)k; - } - } __packed; - - typedef Transaction - CommandTransaction; - }; - -class EnableEncryptedPartition : Command{ - public: - struct CommandPayload { - uint8_t password[30]; // TODO check w/ firmware - }; - - typedef Transaction - CommandTransaction; -}; - -class DisableEncryptedPartition : Command{ - public: - typedef Transaction - CommandTransaction; -}; - -class EnableHiddenEncryptedPartition :Command{ - public: - struct CommandPayload { - uint8_t password[30]; // TODO check w/ firmware - }; - - typedef Transaction - CommandTransaction; -}; - -class DisableHiddenEncryptedPartition :Command{ - public: - typedef Transaction - CommandTransaction; -}; - -class EnableFirmwareUpdate :Command{ - public: - struct CommandPayload { - uint8_t password[30]; // TODO check w/ firmware - }; - - typedef Transaction - CommandTransaction; -}; - -class UpdatePassword :Command{ - public: - struct CommandPayload { - uint8_t old_password[15]; - uint8_t new_password[15]; - }; - - typedef Transaction - CommandTransaction; -}; - -class ExportFirmware :Command{ - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; - - class CreateNewKeys : Command { - public: - struct CommandPayload { - uint8_t kind; - uint8_t admin_password[30]; //CS20_MAX_PASSWORD_LEN - std::string dissect() const { - std::stringstream ss; - ss << " admin_password:\t" << admin_password<< std::endl; - return ss.str(); - } - void setKindPrefixed(){ - kind = 'P'; - } - } __packed; - - typedef Transaction - CommandTransaction; - }; - - -class FillSDCardWithRandomChars :Command{ - public: - struct CommandPayload { - uint8_t volume_flag; - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; - -class SetupHiddenVolume :Command{ - public: - typedef Transaction - CommandTransaction; -}; - -class SendPasswordMatrix :Command{ - public: - typedef Transaction - CommandTransaction; -}; - -class SendPasswordMatrixPinData :Command{ - public: - struct CommandPayload { - uint8_t pin_data[30]; // TODO how long actually can it be? - }; - - typedef Transaction - CommandTransaction; -}; - -class SendPasswordMatrixSetup :Command{ - public: - struct CommandPayload { - uint8_t setup_data[30]; // TODO how long actually can it be? - }; - - typedef Transaction - CommandTransaction; -}; + namespace stick20 { + + enum class PasswordKind : uint8_t { + User = 'P', + Admin = 'A' + }; + + class ChangeAdminUserPin20Current : Command { + public: + struct CommandPayload { + uint8_t kind; + uint8_t old_pin[20]; + + std::string dissect() const { + std::stringstream ss; + ss << " old_pin:\t" << old_pin << std::endl; + return ss.str(); + } + + void set_kind(PasswordKind k) { + kind = (uint8_t) k; + } + } __packed; + + typedef Transaction + CommandTransaction; + }; + + + class ChangeAdminUserPin20New : Command { + public: + + struct CommandPayload { + uint8_t kind; + uint8_t new_pin[20]; + + std::string dissect() const { + std::stringstream ss; + ss << " new_pin:\t" << new_pin << std::endl; + return ss.str(); + } + + void set_kind(PasswordKind k) { + kind = (uint8_t) k; + } + + } __packed; + + typedef Transaction + CommandTransaction; + }; + + + class UnlockUserPassword : Command { + public: + struct CommandPayload { + uint8_t kind; + uint8_t user_new_password[20]; + + std::string dissect() const { + std::stringstream ss; + ss << " user_new_password:\t" << user_new_password << std::endl; + return ss.str(); + } + + void set_kind(PasswordKind k) { + kind = (uint8_t) k; + } + } __packed; + + typedef Transaction + CommandTransaction; + }; + + class EnableEncryptedPartition : Command { + public: + struct CommandPayload { + uint8_t password[30]; // TODO check w/ firmware + }; + + typedef Transaction + CommandTransaction; + }; + + class DisableEncryptedPartition : Command { + public: + typedef Transaction + CommandTransaction; + }; + + class EnableHiddenEncryptedPartition : Command { + public: + struct CommandPayload { + uint8_t password[30]; // TODO check w/ firmware + }; + + typedef Transaction + CommandTransaction; + }; + + class DisableHiddenEncryptedPartition : Command { + public: + typedef Transaction + CommandTransaction; + }; + + class EnableFirmwareUpdate : Command { + public: + struct CommandPayload { + uint8_t password[30]; // TODO check w/ firmware + }; + + typedef Transaction + CommandTransaction; + }; + + class UpdatePassword : Command { + public: + struct CommandPayload { + uint8_t old_password[15]; + uint8_t new_password[15]; + }; + + typedef Transaction + CommandTransaction; + }; + + class ExportFirmware : Command { + public: + struct CommandPayload { + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; + + class CreateNewKeys : Command { + public: + struct CommandPayload { + uint8_t kind; + uint8_t admin_password[30]; //CS20_MAX_PASSWORD_LEN + std::string dissect() const { + std::stringstream ss; + ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } + + void setKindPrefixed() { + kind = 'P'; + } + } __packed; + + typedef Transaction + CommandTransaction; + }; + + + class FillSDCardWithRandomChars : Command { + public: + struct CommandPayload { + uint8_t volume_flag; + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; + + class SetupHiddenVolume : Command { + public: + typedef Transaction + CommandTransaction; + }; + + class SendPasswordMatrix : Command { + public: + typedef Transaction + CommandTransaction; + }; + + class SendPasswordMatrixPinData : Command { + public: + struct CommandPayload { + uint8_t pin_data[30]; // TODO how long actually can it be? + }; + + typedef Transaction + CommandTransaction; + }; + + class SendPasswordMatrixSetup : Command { + public: + struct CommandPayload { + uint8_t setup_data[30]; // TODO how long actually can it be? + }; + + typedef Transaction + CommandTransaction; + }; #define d(x) ss << " "#x":\t" << (int)x << std::endl; - class GetDeviceStatus : Command { - public: - static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 20 +1; - static const int payload_absolute_begin = 8; - static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; - struct ResponsePayload { - uint8_t _padding[padding_size]; //TODO confirm padding in Storage firmware - //data starts from 21st byte of packet -> 13th byte of payload - uint8_t command_counter; - uint8_t last_command; - uint8_t status; - uint8_t progress_bar_value; - bool isValid() const { return true; } - - std::string dissect() const { - std::stringstream ss; - d(command_counter); - d(last_command); - d(status); - d(progress_bar_value); - ss << "_padding:\t" - << ::nitrokey::misc::hexdump((const char *)(_padding), - sizeof _padding); - return ss.str(); - } - } __packed; - - typedef Transaction - CommandTransaction; - }; - - -class SendPassword :Command{ - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; - -class SendNewPassword :Command{ - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; + class GetDeviceStatus : Command { + public: + static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 20 + 1; + static const int payload_absolute_begin = 8; + static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; + + struct ResponsePayload { + uint8_t _padding[padding_size]; //TODO confirm padding in Storage firmware + //data starts from 21st byte of packet -> 13th byte of payload + uint8_t command_counter; + uint8_t last_command; + uint8_t status; + uint8_t progress_bar_value; + + bool isValid() const { return true; } + + std::string dissect() const { + std::stringstream ss; + d(command_counter); + d(last_command); + d(status); + d(progress_bar_value); + ss << "_padding:\t" + << ::nitrokey::misc::hexdump((const char *) (_padding), + sizeof _padding); + return ss.str(); + } + } __packed; + + typedef Transaction + CommandTransaction; + }; + + + class SendPassword : Command { + public: + struct CommandPayload { + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; + + class SendNewPassword : Command { + public: + struct CommandPayload { + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; // TODO fix original nomenclature -class SendSetReadonlyToUncryptedVolume :Command{ - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; - -class SendSetReadwriteToUncryptedVolume :Command{ - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; - -class SendClearNewSdCardFound :Command{ - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; - -class SendStartup :Command{ - public: - struct CommandPayload { - uint64_t localtime; // POSIX - }; - - typedef Transaction - CommandTransaction; -}; - -class SendHiddenVolumeSetup :Command{ - public: - struct CommandPayload { - // TODO HiddenVolumeSetup_tst type - }; - - typedef Transaction - CommandTransaction; -}; - -class LockFirmware :Command{ - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; -}; - -class ProductionTest :Command{ - public: - typedef Transaction - CommandTransaction; -}; -} -} + class SendSetReadonlyToUncryptedVolume : Command { + public: + struct CommandPayload { + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; + + class SendSetReadwriteToUncryptedVolume : Command { + public: + struct CommandPayload { + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; + + class SendClearNewSdCardFound : Command { + public: + struct CommandPayload { + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; + + class SendStartup : Command { + public: + struct CommandPayload { + uint64_t localtime; // POSIX + }; + + typedef Transaction + CommandTransaction; + }; + + class SendHiddenVolumeSetup : Command { + public: + struct CommandPayload { + // TODO HiddenVolumeSetup_tst type + }; + + typedef Transaction + CommandTransaction; + }; + + class LockFirmware : Command { + public: + struct CommandPayload { + uint8_t password[30]; + }; + + typedef Transaction + CommandTransaction; + }; + + class ProductionTest : Command { + public: + typedef Transaction + CommandTransaction; + }; + } + } } #endif -- cgit v1.2.3 From 323cb033d330129f12ddc19ed96a264e1becf8bb Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 18:14:24 +0200 Subject: Remove password matrix commands Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 86ac053..40352a3 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -190,32 +190,6 @@ namespace nitrokey { CommandTransaction; }; - class SendPasswordMatrix : Command { - public: - typedef Transaction - CommandTransaction; - }; - - class SendPasswordMatrixPinData : Command { - public: - struct CommandPayload { - uint8_t pin_data[30]; // TODO how long actually can it be? - }; - - typedef Transaction - CommandTransaction; - }; - - class SendPasswordMatrixSetup : Command { - public: - struct CommandPayload { - uint8_t setup_data[30]; // TODO how long actually can it be? - }; - - typedef Transaction - CommandTransaction; - }; - #define d(x) ss << " "#x":\t" << (int)x << std::endl; class GetDeviceStatus : Command { -- cgit v1.2.3 From c07390ce32506e009ebf44c2ecc8190d21abd530 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 18:15:46 +0200 Subject: Remove already implemented commands Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 40352a3..e57932d 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -226,26 +226,6 @@ namespace nitrokey { }; - class SendPassword : Command { - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; - }; - - class SendNewPassword : Command { - public: - struct CommandPayload { - uint8_t password[30]; - }; - - typedef Transaction - CommandTransaction; - }; - // TODO fix original nomenclature class SendSetReadonlyToUncryptedVolume : Command { public: -- cgit v1.2.3 From 3601f5f97fb64357d9d9221acbd356eec4dbc67a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 18:20:43 +0200 Subject: Add dissection template to commands Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index e57932d..b685055 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -93,6 +93,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; // TODO check w/ firmware + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -109,6 +114,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; // TODO check w/ firmware + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -125,6 +135,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; // TODO check w/ firmware + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -136,6 +151,11 @@ namespace nitrokey { struct CommandPayload { uint8_t old_password[15]; uint8_t new_password[15]; + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -146,6 +166,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -178,6 +203,11 @@ namespace nitrokey { struct CommandPayload { uint8_t volume_flag; uint8_t password[30]; + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -231,6 +261,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -241,6 +276,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -251,6 +291,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -261,6 +306,11 @@ namespace nitrokey { public: struct CommandPayload { uint64_t localtime; // POSIX + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -271,6 +321,11 @@ namespace nitrokey { public: struct CommandPayload { // TODO HiddenVolumeSetup_tst type + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction @@ -281,6 +336,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t password[30]; + std::string dissect() const { + std::stringstream ss; +// ss << " admin_password:\t" << admin_password << std::endl; + return ss.str(); + } }; typedef Transaction -- cgit v1.2.3 From b0e14aeb25e8d5d799b685bdc844b87617d97c80 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 18:59:12 +0200 Subject: Add strcpyT to misc.h Signed-off-by: Szczepan Zalega --- include/misc.h | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/include/misc.h b/include/misc.h index 5fcd16d..48d6a83 100644 --- a/include/misc.h +++ b/include/misc.h @@ -3,11 +3,32 @@ #include #include #include +#include +#include "log.h" +#include "LibraryException.h" namespace nitrokey { namespace misc { -template + template + void strcpyT(T& dest, const char* src){ + + if (src == nullptr) +// throw EmptySourceStringException(slot_number); + return; + const size_t s_dest = sizeof dest; + nitrokey::log::Log::instance()(std::string("strcpyT sizes dest src ") + +std::to_string(s_dest)+ " " + +std::to_string(strlen(src))+ " " + ,nitrokey::log::Loglevel::DEBUG); + if (strlen(src) > s_dest){ + throw TooLongStringException(strlen(src), s_dest, src); + } + strncpy((char*) &dest, src, s_dest); + } + + + template typename T::CommandPayload get_payload(){ //Create, initialize and return by value command payload typename T::CommandPayload st; -- cgit v1.2.3 From 3a856bcfaac6490426f03f0ac149ef5445c5c36f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 18:59:30 +0200 Subject: General password based command Signed-off-by: Szczepan Zalega --- include/command.h | 55 ++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/include/command.h b/include/command.h index 715902d..7f723e5 100644 --- a/include/command.h +++ b/include/command.h @@ -5,19 +5,48 @@ #include "cxx_semantics.h" namespace nitrokey { -namespace proto { - -template -class Command : semantics::non_constructible { - public: - constexpr static CommandID command_id() { return cmd_id; } - - template - static std::string dissect(const T &) { - return std::string("Payload dissection is unavailable"); - } -}; -} + namespace proto { + + template + class Command : semantics::non_constructible { + public: + constexpr static CommandID command_id() { return cmd_id; } + + template + static std::string dissect(const T &) { + return std::string("Payload dissection is unavailable"); + } + }; + +#define print_to_ss(x) ( ss << " #x:\t" << (x) << std::endl ); + + template + class PasswordCommand : public Command { + public: + struct CommandPayload { + uint8_t kind; + uint8_t password[20]; + + std::string dissect() const { + std::stringstream ss; + print_to_ss( kind ); + print_to_ss(password); + return ss.str(); + } + void set_kind_admin() { + kind = (uint8_t) 'A'; + } + void set_kind_user() { + kind = (uint8_t) 'P'; + } + + } __packed; + + typedef Transaction::command_id(), struct CommandPayload, struct EmptyPayload> + CommandTransaction; + + }; + } } #endif -- cgit v1.2.3 From 24f140f34c9c90be54165802edb80fce3408ffa3 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 19:01:13 +0200 Subject: First template based password commands. Initial dissect support for commands Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 49 ++++++++++++++++++++-------------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index b685055..5ee16de 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -15,6 +15,7 @@ namespace nitrokey { * STICK20 protocol command ids * a superset (almost) of STICK10 */ +#define print_to_ss(x) ( ss << " #x:\t" << (x) << std::endl ); namespace stick20 { enum class PasswordKind : uint8_t { @@ -30,6 +31,7 @@ namespace nitrokey { std::string dissect() const { std::stringstream ss; + print_to_ss( kind ); ss << " old_pin:\t" << old_pin << std::endl; return ss.str(); } @@ -53,6 +55,7 @@ namespace nitrokey { std::string dissect() const { std::stringstream ss; + print_to_ss( kind ); ss << " new_pin:\t" << new_pin << std::endl; return ss.str(); } @@ -76,6 +79,7 @@ namespace nitrokey { std::string dissect() const { std::stringstream ss; + print_to_ss( kind ); ss << " user_new_password:\t" << user_new_password << std::endl; return ss.str(); } @@ -89,26 +93,8 @@ namespace nitrokey { CommandTransaction; }; - class EnableEncryptedPartition : Command { - public: - struct CommandPayload { - uint8_t password[30]; // TODO check w/ firmware - std::string dissect() const { - std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; - - class DisableEncryptedPartition : Command { - public: - typedef Transaction - CommandTransaction; - }; + class EnableEncryptedPartition : public PasswordCommand {}; + class DisableEncryptedPartition : public PasswordCommand {}; class EnableHiddenEncryptedPartition : Command { public: @@ -116,7 +102,7 @@ namespace nitrokey { uint8_t password[30]; // TODO check w/ firmware std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( password ); return ss.str(); } }; @@ -137,7 +123,7 @@ namespace nitrokey { uint8_t password[30]; // TODO check w/ firmware std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( password ); return ss.str(); } }; @@ -153,7 +139,8 @@ namespace nitrokey { uint8_t new_password[15]; std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( old_password ); + print_to_ss( new_password ); return ss.str(); } }; @@ -168,7 +155,7 @@ namespace nitrokey { uint8_t password[30]; std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( password ); return ss.str(); } }; @@ -184,6 +171,7 @@ namespace nitrokey { uint8_t admin_password[30]; //CS20_MAX_PASSWORD_LEN std::string dissect() const { std::stringstream ss; + print_to_ss( kind ); ss << " admin_password:\t" << admin_password << std::endl; return ss.str(); } @@ -205,7 +193,8 @@ namespace nitrokey { uint8_t password[30]; std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( (int)volume_flag ); + print_to_ss( password ); return ss.str(); } }; @@ -255,6 +244,8 @@ namespace nitrokey { CommandTransaction; }; +#undef d + // TODO fix original nomenclature class SendSetReadonlyToUncryptedVolume : Command { @@ -263,7 +254,7 @@ namespace nitrokey { uint8_t password[30]; std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( password ); return ss.str(); } }; @@ -278,7 +269,7 @@ namespace nitrokey { uint8_t password[30]; std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( password ); return ss.str(); } }; @@ -293,7 +284,7 @@ namespace nitrokey { uint8_t password[30]; std::string dissect() const { std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; + print_to_ss( password ); return ss.str(); } }; @@ -356,4 +347,6 @@ namespace nitrokey { } } +#undef print_to_ss + #endif -- cgit v1.2.3 From 27355f0dd8eb11fe1a0d41bd05d3c7dcb74341d8 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 19:02:16 +0200 Subject: C++ tests for Storage commands Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 4 ++- unittest/test2.cc | 75 ++++++++++++------------------------------------------- 2 files changed, 19 insertions(+), 60 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index eedfd35..8f57fa7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,6 +30,8 @@ set(SOURCE_FILES NitrokeyManager.cc NK_C_API.cc include/CommandFailedException.h include/LibraryException.h unittest/test_C_API.cpp - unittest/catch_main.cpp) + unittest/catch_main.cpp + unittest/test2.cc + ) add_executable(libnitrokey ${SOURCE_FILES}) \ No newline at end of file diff --git a/unittest/test2.cc b/unittest/test2.cc index 6744b45..dfc4182 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -3,80 +3,37 @@ #include #include +#include #include "device_proto.h" #include "log.h" -#include "stick10_commands.h" +//#include "stick10_commands.h" +#include "stick20_commands.h" using namespace std; using namespace nitrokey::device; -using namespace nitrokey::proto::stick10; +using namespace nitrokey::proto::stick20; using namespace nitrokey::log; using namespace nitrokey::misc; -std::string getSlotName(Stick10 &stick, int slotNo) { - auto slot_req = get_payload(); - slot_req.slot_number = slotNo; - auto slot = ReadSlot::CommandTransaction::run(stick, slot_req); - std::string sName(reinterpret_cast(slot.data().slot_name)); - return sName; -} - -TEST_CASE("Slot names are correct", "[slotNames]") { - Stick10 stick; +TEST_CASE("test", "[test]") { + Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); - Log::instance().set_loglevel(Loglevel::DEBUG); - - auto resp = GetStatus::CommandTransaction::run(stick); - - auto authreq = get_payload(); - strcpy((char *)(authreq.card_password), "12345678"); - FirstAuthenticate::CommandTransaction::run(stick, authreq); - - { - auto authreq = get_payload(); - strcpy((char *)(authreq.user_password), "123456"); - EnablePasswordSafe::CommandTransaction::run(stick, authreq); - } - - //assuming these values were set earlier, thus failing on normal use - REQUIRE(getSlotName(stick, 0x20) == std::string("1")); - REQUIRE(getSlotName(stick, 0x21) == std::string("slot2")); - - { - auto resp = GetPasswordRetryCount::CommandTransaction::run(stick); - REQUIRE(resp.data().password_retry_count == 3); - } - { - auto resp = GetUserPasswordRetryCount::CommandTransaction::run(stick); - REQUIRE(resp.data().password_retry_count == 3); - } + Log::instance().set_loglevel(Loglevel::DEBUG_L2); { - auto slot = get_payload(); - slot.slot_number = 0; - auto resp2 = GetPasswordSafeSlotName::CommandTransaction::run(stick, slot); - std::string sName(reinterpret_cast(resp2.data().slot_name)); - REQUIRE(sName == std::string("web1")); + auto p = get_payload(); + p.set_kind_user(); + strcpyT(p.password, "123456"); + EnableEncryptedPartition::CommandTransaction::run(stick, p); } - - { - auto slot = get_payload(); - slot.slot_number = 0; - auto resp2 = - GetPasswordSafeSlotPassword::CommandTransaction::run(stick, slot); - std::string sName(reinterpret_cast(resp2.data().slot_password)); - REQUIRE(sName == std::string("pass1")); - } - - { - auto slot = get_payload(); - slot.slot_number = 0; - auto resp2 = GetPasswordSafeSlotLogin::CommandTransaction::run(stick, slot); - std::string sName(reinterpret_cast(resp2.data().slot_login)); - REQUIRE(sName == std::string("login1")); + { + auto p = get_payload(); + p.set_kind_user(); + strcpyT(p.password, "123456"); + DisableEncryptedPartition::CommandTransaction::run(stick, p); } stick.disconnect(); -- cgit v1.2.3 From acf8adf7d6920e702cbd2f256ab312f80b781001 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 19:30:42 +0200 Subject: Enable hidden encrypted partition Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 5ee16de..34dda60 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -95,21 +95,7 @@ namespace nitrokey { class EnableEncryptedPartition : public PasswordCommand {}; class DisableEncryptedPartition : public PasswordCommand {}; - - class EnableHiddenEncryptedPartition : Command { - public: - struct CommandPayload { - uint8_t password[30]; // TODO check w/ firmware - std::string dissect() const { - std::stringstream ss; - print_to_ss( password ); - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; + class EnableHiddenEncryptedPartition : public PasswordCommand {}; class DisableHiddenEncryptedPartition : Command { public: -- cgit v1.2.3 From 2e131cfb2b79f3b1d4406ed1d57f22e6421bbaca Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 19:31:13 +0200 Subject: Make device slower for now for easier debugging Signed-off-by: Szczepan Zalega --- device.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/device.cc b/device.cc index 8b40984..8c3c799 100644 --- a/device.cc +++ b/device.cc @@ -95,8 +95,8 @@ Stick10::Stick10() { Stick20::Stick20() { m_vid = 0x20a0; m_pid = 0x4109; - m_retry_timeout = 20ms; + m_retry_timeout = 200ms; m_model = DeviceModel::STORAGE; - m_send_receive_delay = 20ms; + m_send_receive_delay = 200ms; m_retry_receiving_count = 40; } -- cgit v1.2.3 From 3b0452c05b84ede5a2085aee4a550a2a63ccdb65 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 19:31:59 +0200 Subject: C++ tests update Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index dfc4182..b328c37 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -11,6 +11,7 @@ using namespace std; using namespace nitrokey::device; +using namespace nitrokey::proto; using namespace nitrokey::proto::stick20; using namespace nitrokey::log; using namespace nitrokey::misc; @@ -23,17 +24,31 @@ TEST_CASE("test", "[test]") { Log::instance().set_loglevel(Loglevel::DEBUG_L2); + stick10::LockDevice::CommandTransaction::run(stick); +// { +// auto p = get_payload(); +// p.set_kind_user(); +// strcpyT(p.password, "123456"); +// EnableEncryptedPartition::CommandTransaction::run(stick, p); +// } +// { +// auto p = get_payload(); +// p.set_kind_user(); +// strcpyT(p.password, "123456"); +// DisableEncryptedPartition::CommandTransaction::run(stick, p); +// } + { auto p = get_payload(); p.set_kind_user(); strcpyT(p.password, "123456"); EnableEncryptedPartition::CommandTransaction::run(stick, p); } - { - auto p = get_payload(); + { + auto p = get_payload(); p.set_kind_user(); - strcpyT(p.password, "123456"); - DisableEncryptedPartition::CommandTransaction::run(stick, p); + strcpyT(p.password, "123123123"); + EnableHiddenEncryptedPartition::CommandTransaction::run(stick, p); } stick.disconnect(); -- cgit v1.2.3 From d8a6073f6118062266df8ef77c5a7969a9ed8be7 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Sat, 22 Oct 2016 19:35:26 +0200 Subject: C++ tests update (2) - wait before lock Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/unittest/test2.cc b/unittest/test2.cc index b328c37..79417c6 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -50,6 +50,8 @@ TEST_CASE("test", "[test]") { strcpyT(p.password, "123123123"); EnableHiddenEncryptedPartition::CommandTransaction::run(stick, p); } + this_thread::sleep_for(1000ms); + stick10::LockDevice::CommandTransaction::run(stick); stick.disconnect(); } -- cgit v1.2.3 From 9f0e18f1a91a768717481dbf6b88eedd066a46c9 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 14:42:03 +0200 Subject: Another set of Storage password-only commands Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 118 +++------------------------------------------ 1 file changed, 8 insertions(+), 110 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 34dda60..75bce1c 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -96,27 +96,8 @@ namespace nitrokey { class EnableEncryptedPartition : public PasswordCommand {}; class DisableEncryptedPartition : public PasswordCommand {}; class EnableHiddenEncryptedPartition : public PasswordCommand {}; - - class DisableHiddenEncryptedPartition : Command { - public: - typedef Transaction - CommandTransaction; - }; - - class EnableFirmwareUpdate : Command { - public: - struct CommandPayload { - uint8_t password[30]; // TODO check w/ firmware - std::string dissect() const { - std::stringstream ss; - print_to_ss( password ); - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; + class DisableHiddenEncryptedPartition : public PasswordCommand {}; + class EnableFirmwareUpdate : public PasswordCommand {}; class UpdatePassword : Command { public: @@ -135,20 +116,7 @@ namespace nitrokey { CommandTransaction; }; - class ExportFirmware : Command { - public: - struct CommandPayload { - uint8_t password[30]; - std::string dissect() const { - std::stringstream ss; - print_to_ss( password ); - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; + class ExportFirmware : public PasswordCommand {}; class CreateNewKeys : Command { public: @@ -171,23 +139,7 @@ namespace nitrokey { CommandTransaction; }; - - class FillSDCardWithRandomChars : Command { - public: - struct CommandPayload { - uint8_t volume_flag; - uint8_t password[30]; - std::string dissect() const { - std::stringstream ss; - print_to_ss( (int)volume_flag ); - print_to_ss( password ); - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; + class FillSDCardWithRandomChars : public PasswordCommand {}; class SetupHiddenVolume : Command { public: @@ -234,50 +186,9 @@ namespace nitrokey { // TODO fix original nomenclature - class SendSetReadonlyToUncryptedVolume : Command { - public: - struct CommandPayload { - uint8_t password[30]; - std::string dissect() const { - std::stringstream ss; - print_to_ss( password ); - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; - - class SendSetReadwriteToUncryptedVolume : Command { - public: - struct CommandPayload { - uint8_t password[30]; - std::string dissect() const { - std::stringstream ss; - print_to_ss( password ); - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; - - class SendClearNewSdCardFound : Command { - public: - struct CommandPayload { - uint8_t password[30]; - std::string dissect() const { - std::stringstream ss; - print_to_ss( password ); - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; + class SendSetReadonlyToUncryptedVolume : public PasswordCommand {}; + class SendSetReadwriteToUncryptedVolume : public PasswordCommand {}; + class SendClearNewSdCardFound : public PasswordCommand {}; class SendStartup : Command { public: @@ -309,20 +220,7 @@ namespace nitrokey { CommandTransaction; }; - class LockFirmware : Command { - public: - struct CommandPayload { - uint8_t password[30]; - std::string dissect() const { - std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; - return ss.str(); - } - }; - - typedef Transaction - CommandTransaction; - }; + class LockFirmware : public PasswordCommand {}; class ProductionTest : Command { public: -- cgit v1.2.3 From 24dc03cac985dd76b72f3b1982b3d1ff4535c676 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 14:42:49 +0200 Subject: Build properly subtasks in parallel Signed-off-by: Szczepan Zalega --- Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index cf0cf0c..977eae6 100644 --- a/Makefile +++ b/Makefile @@ -30,14 +30,14 @@ $(BUILD)/%.o: %.cc $(DEPENDS) clean: rm -f $(OBJ) rm -f $(BUILD)/libnitrokey.so - make -C unittest clean + ${MAKE} -C unittest clean mrproper: clean rm -f $(BUILD)/*.d - make -C unittest mrproper + ${MAKE} -C unittest mrproper unittest: $(BUILD)/libnitrokey.so - make -C unittest + ${MAKE} -C unittest cd unittest/build && ln -fs ../../build/libnitrokey.so . .PHONY: all clean mrproper unittest -- cgit v1.2.3 From ec8b19e231390e25860218000d77d622d94782c7 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 14:44:38 +0200 Subject: Remove obsolete macro Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 75bce1c..b3dbacf 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -147,7 +147,6 @@ namespace nitrokey { CommandTransaction; }; -#define d(x) ss << " "#x":\t" << (int)x << std::endl; class GetDeviceStatus : Command { public: @@ -167,10 +166,10 @@ namespace nitrokey { std::string dissect() const { std::stringstream ss; - d(command_counter); - d(last_command); - d(status); - d(progress_bar_value); + print_to_ss((int)command_counter); + print_to_ss((int)last_command); + print_to_ss((int)status); + print_to_ss((int)progress_bar_value); ss << "_padding:\t" << ::nitrokey::misc::hexdump((const char *) (_padding), sizeof _padding); @@ -182,8 +181,6 @@ namespace nitrokey { CommandTransaction; }; -#undef d - // TODO fix original nomenclature class SendSetReadonlyToUncryptedVolume : public PasswordCommand {}; -- cgit v1.2.3 From 9a56e6c27104ead60a89c403e77494bfcfea563f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 14:52:10 +0200 Subject: Remove static keyword from CommandID dissection Signed-off-by: Szczepan Zalega --- include/command.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/command.h b/include/command.h index 7f723e5..6e3525e 100644 --- a/include/command.h +++ b/include/command.h @@ -13,7 +13,7 @@ namespace nitrokey { constexpr static CommandID command_id() { return cmd_id; } template - static std::string dissect(const T &) { + std::string dissect(const T &) { return std::string("Payload dissection is unavailable"); } }; -- cgit v1.2.3 From 536d2b40239cbff94d7e562a0c0c9cf4f462576f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 14:52:53 +0200 Subject: Test: let device rest after enabling encrypted partition Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/unittest/test2.cc b/unittest/test2.cc index 79417c6..883e37b 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -44,6 +44,7 @@ TEST_CASE("test", "[test]") { strcpyT(p.password, "123456"); EnableEncryptedPartition::CommandTransaction::run(stick, p); } + this_thread::sleep_for(1000ms); { auto p = get_payload(); p.set_kind_user(); -- cgit v1.2.3 From 116523fbee311aa7af5151d1a601c8a0f11965e9 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 15:15:04 +0200 Subject: Test: reduced code bloat Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 38 +++++++++++++------------------------- 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index 883e37b..503ab49 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -17,6 +17,15 @@ using namespace nitrokey::log; using namespace nitrokey::misc; +template +void execute_password_command(Device &stick, const char *password) { + auto p = get_payload(); + p.set_kind_user(); + strcpyT(p.password, password); + CMDTYPE::CommandTransaction::run(stick, p); +} + + TEST_CASE("test", "[test]") { Stick20 stick; bool connected = stick.connect(); @@ -25,32 +34,11 @@ TEST_CASE("test", "[test]") { Log::instance().set_loglevel(Loglevel::DEBUG_L2); stick10::LockDevice::CommandTransaction::run(stick); -// { -// auto p = get_payload(); -// p.set_kind_user(); -// strcpyT(p.password, "123456"); -// EnableEncryptedPartition::CommandTransaction::run(stick, p); -// } -// { -// auto p = get_payload(); -// p.set_kind_user(); -// strcpyT(p.password, "123456"); -// DisableEncryptedPartition::CommandTransaction::run(stick, p); -// } - - { - auto p = get_payload(); - p.set_kind_user(); - strcpyT(p.password, "123456"); - EnableEncryptedPartition::CommandTransaction::run(stick, p); - } +// execute_password_command(stick, "123456"); +// execute_password_command(stick, "123456"); + execute_password_command(stick, "123456"); this_thread::sleep_for(1000ms); - { - auto p = get_payload(); - p.set_kind_user(); - strcpyT(p.password, "123123123"); - EnableHiddenEncryptedPartition::CommandTransaction::run(stick, p); - } + execute_password_command(stick, "123123123"); this_thread::sleep_for(1000ms); stick10::LockDevice::CommandTransaction::run(stick); -- cgit v1.2.3 From 003189e780af8208f243bbd312df5f5295015eb1 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 15:50:15 +0200 Subject: Test: check more commands Add delay after each command by default. Check EnableHiddenEncryptedPartition more than once. Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index 503ab49..61fb502 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -18,11 +18,16 @@ using namespace nitrokey::misc; template -void execute_password_command(Device &stick, const char *password) { +void execute_password_command(Device &stick, const char *password, const char kind = 'P') { auto p = get_payload(); - p.set_kind_user(); + if (kind == 'P'){ + p.set_kind_user(); + } else { + p.set_kind_admin(); + } strcpyT(p.password, password); CMDTYPE::CommandTransaction::run(stick, p); + this_thread::sleep_for(1000ms); } @@ -36,10 +41,33 @@ TEST_CASE("test", "[test]") { stick10::LockDevice::CommandTransaction::run(stick); // execute_password_command(stick, "123456"); // execute_password_command(stick, "123456"); - execute_password_command(stick, "123456"); this_thread::sleep_for(1000ms); - execute_password_command(stick, "123123123"); + execute_password_command(stick, "123456"); + this_thread::sleep_for(4000ms); + bool passed = false; + for(int i=0; i<5; i++){ + try { + execute_password_command(stick, "123123123"); + CHECK(true); + passed=true; + break; + } + catch (CommandFailedException &e){ + this_thread::sleep_for(2000ms); + } + } + if(!passed){ + CHECK(false); + } + + execute_password_command(stick, "123123123"); + execute_password_command(stick, "123456"); + execute_password_command(stick, "123456"); + execute_password_command(stick, "12345678", 'A'); this_thread::sleep_for(1000ms); +// execute_password_command(stick, "123123123"); +// execute_password_command(stick, "123123123"); //FIRMWARE PIN + stick10::LockDevice::CommandTransaction::run(stick); stick.disconnect(); -- cgit v1.2.3 From 6eca4d657aafddcb9685df4b599a8913ac075b3a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 15:52:57 +0200 Subject: Disable warnings about GNU extension during C++ tests compilation Signed-off-by: Szczepan Zalega --- unittest/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unittest/Makefile b/unittest/Makefile index 9e8fbc1..dbd003e 100644 --- a/unittest/Makefile +++ b/unittest/Makefile @@ -8,7 +8,7 @@ LIB = -L../build LDLIBS = -lnitrokey BUILD = build -CXXFLAGS = -std=c++14 -fPIC +CXXFLAGS = -std=c++14 -fPIC -Wno-gnu-variable-sized-type-not-at-end CXXSOURCES = $(wildcard *.cc) TARGETS = $(CXXSOURCES:%.cc=$(BUILD)/%) -- cgit v1.2.3 From 33a2d790e0a68d243bc1d9e9f75590b141d85c7f Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 16:19:00 +0200 Subject: Fix printing macro Signed-off-by: Szczepan Zalega --- include/command.h | 3 ++- include/stick20_commands.h | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/include/command.h b/include/command.h index 6e3525e..5ac1d7f 100644 --- a/include/command.h +++ b/include/command.h @@ -18,7 +18,7 @@ namespace nitrokey { } }; -#define print_to_ss(x) ( ss << " #x:\t" << (x) << std::endl ); +#define print_to_ss(x) ( ss << " " << (#x) <<":\t" << (x) << std::endl ); template class PasswordCommand : public Command { @@ -48,5 +48,6 @@ namespace nitrokey { }; } } +#undef print_to_ss #endif diff --git a/include/stick20_commands.h b/include/stick20_commands.h index b3dbacf..5679681 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -15,7 +15,7 @@ namespace nitrokey { * STICK20 protocol command ids * a superset (almost) of STICK10 */ -#define print_to_ss(x) ( ss << " #x:\t" << (x) << std::endl ); +#define print_to_ss(x) ( ss << " " << (#x) <<":\t" << (x) << std::endl ); namespace stick20 { enum class PasswordKind : uint8_t { -- cgit v1.2.3 From 29974c0d51f099af9869e49597f77936fc069376 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 16:19:50 +0200 Subject: Test: another commands Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index 61fb502..91982c9 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -65,8 +65,12 @@ TEST_CASE("test", "[test]") { execute_password_command(stick, "123456"); execute_password_command(stick, "12345678", 'A'); this_thread::sleep_for(1000ms); -// execute_password_command(stick, "123123123"); -// execute_password_command(stick, "123123123"); //FIRMWARE PIN +// execute_password_command(stick, "123123123"); //CAUTION +// execute_password_command(stick, "123123123"); //CAUTION FIRMWARE PIN + + execute_password_command(stick, "12345678", 'A'); +// execute_password_command(stick, "12345678", 'A'); + stick10::LockDevice::CommandTransaction::run(stick); -- cgit v1.2.3 From 8f70b382067c932232dbf3966d8859266986004d Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 17:40:50 +0200 Subject: Try to disconnect when destroying device Signed-off-by: Szczepan Zalega --- include/device.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/device.h b/include/device.h index 34b7a5b..3f18921 100644 --- a/include/device.h +++ b/include/device.h @@ -21,6 +21,7 @@ class Device { public: Device(); + virtual ~Device(){disconnect();} // lack of device is not actually an error, // so it doesn't throw -- cgit v1.2.3 From d02c321effbc8b1ae6e8e54f93df53d57ab0d7e1 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 24 Oct 2016 17:52:15 +0200 Subject: Test: check device status. Use automatic disconnection. Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index 91982c9..9739217 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -64,6 +64,7 @@ TEST_CASE("test", "[test]") { execute_password_command(stick, "123456"); execute_password_command(stick, "123456"); execute_password_command(stick, "12345678", 'A'); + stick20::GetDeviceStatus::CommandTransaction::run(stick); this_thread::sleep_for(1000ms); // execute_password_command(stick, "123123123"); //CAUTION // execute_password_command(stick, "123123123"); //CAUTION FIRMWARE PIN @@ -71,8 +72,5 @@ TEST_CASE("test", "[test]") { execute_password_command(stick, "12345678", 'A'); // execute_password_command(stick, "12345678", 'A'); - stick10::LockDevice::CommandTransaction::run(stick); - - stick.disconnect(); } -- cgit v1.2.3 From 385d33bb4c8bb7fe604f5e0acc8aeca5f2146fae Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 25 Oct 2016 18:40:30 +0200 Subject: Handle busy_progressbar device status Signed-off-by: Szczepan Zalega --- CMakeLists.txt | 1 + include/LongOperationInProgressException.h | 28 ++++++++++++++++++++++++++++ include/device_proto.h | 21 +++++++++++++++++++-- 3 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 include/LongOperationInProgressException.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f57fa7..e9cd54f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,6 +32,7 @@ set(SOURCE_FILES unittest/test_C_API.cpp unittest/catch_main.cpp unittest/test2.cc + include/LongOperationInProgressException.h ) add_executable(libnitrokey ${SOURCE_FILES}) \ No newline at end of file diff --git a/include/LongOperationInProgressException.h b/include/LongOperationInProgressException.h new file mode 100644 index 0000000..673a218 --- /dev/null +++ b/include/LongOperationInProgressException.h @@ -0,0 +1,28 @@ +// +// Created by sz on 24.10.16. +// + +#ifndef LIBNITROKEY_LONGOPERATIONINPROGRESSEXCEPTION_H +#define LIBNITROKEY_LONGOPERATIONINPROGRESSEXCEPTION_H + + +class LongOperationInProgressException : public std::exception { + +public: + unsigned char progress_bar_value; + unsigned char command_id; + + LongOperationInProgressException(unsigned char _command_id, unsigned char _progress_bar_value) { + command_id = _command_id; + progress_bar_value = _progress_bar_value; + nitrokey::log::Log::instance()( + std::string("LongOperationInProgressException, progress bar status: ")+ + std::to_string(progress_bar_value), nitrokey::log::Loglevel::DEBUG); + } + virtual const char *what() const throw() { + return "Device returned busy status with long operation in progress"; + } +}; + + +#endif //LIBNITROKEY_LONGOPERATIONINPROGRESSEXCEPTION_H diff --git a/include/device_proto.h b/include/device_proto.h index cde1d51..037451a 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -16,6 +16,7 @@ #include "command_id.h" #include "dissect.h" #include "CommandFailedException.h" +#include "LongOperationInProgressException.h" #define STICK20_UPDATE_MODE_VID 0x03EB #define STICK20_UPDATE_MODE_PID 0x2FF1 @@ -216,6 +217,7 @@ namespace nitrokey { if (!outp.isValid()) throw std::runtime_error("Invalid outgoing packet"); + bool successful_communication = false; int receiving_retry_counter = 0; int sending_retry_counter = dev.get_retry_sending_count(); while (sending_retry_counter-- > 0) { @@ -263,12 +265,21 @@ 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; if (resp.device_status == static_cast(stick10::device_status::ok) && - resp.last_command_crc == outp.crc && resp.isValid()) break; + resp.last_command_crc == outp.crc && resp.isValid()){ + successful_communication = true; + 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); } + if (resp.device_status == static_cast(stick10::device_status::busy) && + static_cast(resp.storage_status.device_status) + == stick20::device_status::busy_progressbar){ + successful_communication = true; + break; + } Log::instance()(std::string("Retry status - dev status, equal crc, correct CRC: ") + std::to_string(resp.device_status) + " " + std::to_string(resp.last_command_crc == outp.crc) + @@ -282,7 +293,7 @@ namespace nitrokey { std::this_thread::sleep_for(dev.get_retry_timeout()); continue; } - if (resp.device_status == 0 && resp.last_command_crc == outp.crc) break; + 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), Loglevel::DEBUG); @@ -297,6 +308,12 @@ namespace nitrokey { std::string("Device error while executing command ") + std::to_string(status)); + if (resp.device_status == static_cast(stick10::device_status::busy) && + static_cast(resp.storage_status.device_status) + == stick20::device_status::busy_progressbar){ + throw LongOperationInProgressException(resp.command_id, resp.storage_status.progress_bar_value); + } + 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), -- cgit v1.2.3 From b0412c73b8ff129183f570a4eed72bdafd9f55d3 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 25 Oct 2016 18:41:59 +0200 Subject: Handle FillSDCardWithRandomChars command and test it Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 38 +++++++++++++++++++++++++++++++++++++- unittest/test2.cc | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 5679681..a335809 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -139,7 +139,43 @@ namespace nitrokey { CommandTransaction; }; - class FillSDCardWithRandomChars : public PasswordCommand {}; +// class FillSDCardWithRandomChars : public PasswordCommand {}; + + + class FillSDCardWithRandomChars : Command { + public: + enum class ChosenVolumes : uint8_t { + all_volumes = 0, + encrypted_volume = 1 + }; + + struct CommandPayload { + uint8_t volume_flag; + uint8_t kind; + uint8_t password[20]; + + std::string dissect() const { + std::stringstream ss; + print_to_ss( (int) volume_flag ); + print_to_ss( kind ); + print_to_ss(password); + return ss.str(); + } + void set_kind_user() { + kind = (uint8_t) 'P'; + } + void set_defaults(){ + set_kind_user(); + volume_flag = static_cast(ChosenVolumes::encrypted_volume); + } + + } __packed; + + typedef Transaction::command_id(), + struct CommandPayload, struct EmptyPayload> + CommandTransaction; + }; + class SetupHiddenVolume : Command { public: diff --git a/unittest/test2.cc b/unittest/test2.cc index 9739217..3cfc5c1 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -31,6 +31,40 @@ void execute_password_command(Device &stick, const char *password, const char ki } +TEST_CASE("long operation test", "[test_long]") { + Stick20 stick; + bool connected = stick.connect(); + REQUIRE(connected == true); + Log::instance().set_loglevel(Loglevel::DEBUG_L2); + try{ +// execute_password_command(stick, "12345678", 'P'); + auto p = get_payload(); + p.set_defaults(); + strcpyT(p.password, "12345678"); + FillSDCardWithRandomChars::CommandTransaction::run(stick, p); + this_thread::sleep_for(1000ms); + + CHECK(false); + } + catch (LongOperationInProgressException &progressException){ + CHECK(true); + } + + + for (int i = 0; i < 30; ++i) { + try { + stick10::GetStatus::CommandTransaction::run(stick); + } + catch (LongOperationInProgressException &progressException){ + CHECK((int)progressException.progress_bar_value>=0); + CAPTURE((int)progressException.progress_bar_value); + this_thread::sleep_for(2000ms); + } + + } + +} + TEST_CASE("test", "[test]") { Stick20 stick; bool connected = stick.connect(); -- cgit v1.2.3 From 6ddbb5199dce36bbb3e40d4aca5f65593f0d7e84 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 27 Oct 2016 19:36:42 +0200 Subject: Import command ids defined as macro to test local enum Signed-off-by: Szczepan Zalega --- unittest/test_command_ids_header.h | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 unittest/test_command_ids_header.h diff --git a/unittest/test_command_ids_header.h b/unittest/test_command_ids_header.h new file mode 100644 index 0000000..cd55c8a --- /dev/null +++ b/unittest/test_command_ids_header.h @@ -0,0 +1,41 @@ +#ifndef LIBNITROKEY_TEST_COMMAND_IDS_HEADER_H_H +#define LIBNITROKEY_TEST_COMMAND_IDS_HEADER_H_H + +#define STICK20_CMD_START_VALUE 0x20 +#define STICK20_CMD_ENABLE_CRYPTED_PARI (STICK20_CMD_START_VALUE + 0) +#define STICK20_CMD_DISABLE_CRYPTED_PARI (STICK20_CMD_START_VALUE + 1) +#define STICK20_CMD_ENABLE_HIDDEN_CRYPTED_PARI (STICK20_CMD_START_VALUE + 2) +#define STICK20_CMD_DISABLE_HIDDEN_CRYPTED_PARI (STICK20_CMD_START_VALUE + 3) +#define STICK20_CMD_ENABLE_FIRMWARE_UPDATE (STICK20_CMD_START_VALUE + 4) +#define STICK20_CMD_EXPORT_FIRMWARE_TO_FILE (STICK20_CMD_START_VALUE + 5) +#define STICK20_CMD_GENERATE_NEW_KEYS (STICK20_CMD_START_VALUE + 6) +#define STICK20_CMD_FILL_SD_CARD_WITH_RANDOM_CHARS (STICK20_CMD_START_VALUE + 7) + +#define STICK20_CMD_WRITE_STATUS_DATA (STICK20_CMD_START_VALUE + 8) +#define STICK20_CMD_ENABLE_READONLY_UNCRYPTED_LUN (STICK20_CMD_START_VALUE + 9) +#define STICK20_CMD_ENABLE_READWRITE_UNCRYPTED_LUN (STICK20_CMD_START_VALUE + 10) + +#define STICK20_CMD_SEND_PASSWORD_MATRIX (STICK20_CMD_START_VALUE + 11) +#define STICK20_CMD_SEND_PASSWORD_MATRIX_PINDATA (STICK20_CMD_START_VALUE + 12) +#define STICK20_CMD_SEND_PASSWORD_MATRIX_SETUP (STICK20_CMD_START_VALUE + 13) + +#define STICK20_CMD_GET_DEVICE_STATUS (STICK20_CMD_START_VALUE + 14) +#define STICK20_CMD_SEND_DEVICE_STATUS (STICK20_CMD_START_VALUE + 15) + +#define STICK20_CMD_SEND_HIDDEN_VOLUME_PASSWORD (STICK20_CMD_START_VALUE + 16) +#define STICK20_CMD_SEND_HIDDEN_VOLUME_SETUP (STICK20_CMD_START_VALUE + 17) +#define STICK20_CMD_SEND_PASSWORD (STICK20_CMD_START_VALUE + 18) +#define STICK20_CMD_SEND_NEW_PASSWORD (STICK20_CMD_START_VALUE + 19) +#define STICK20_CMD_CLEAR_NEW_SD_CARD_FOUND (STICK20_CMD_START_VALUE + 20) + +#define STICK20_CMD_SEND_STARTUP (STICK20_CMD_START_VALUE + 21) +#define STICK20_CMD_SEND_CLEAR_STICK_KEYS_NOT_INITIATED (STICK20_CMD_START_VALUE + 22) +#define STICK20_CMD_SEND_LOCK_STICK_HARDWARE (STICK20_CMD_START_VALUE + 23) + +#define STICK20_CMD_PRODUCTION_TEST (STICK20_CMD_START_VALUE + 24) +#define STICK20_CMD_SEND_DEBUG_DATA (STICK20_CMD_START_VALUE + 25) + +#define STICK20_CMD_CHANGE_UPDATE_PIN (STICK20_CMD_START_VALUE + 26) + + +#endif //LIBNITROKEY_TEST_COMMAND_IDS_HEADER_H_H -- cgit v1.2.3 From e828759986f3c9633fb0177bf446752480a66adf Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 27 Oct 2016 19:40:57 +0200 Subject: Set commands enum values by hand for greater verbosity Signed-off-by: Szczepan Zalega --- include/command_id.h | 52 ++++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/include/command_id.h b/include/command_id.h index 8148cc1..76c7132 100644 --- a/include/command_id.h +++ b/include/command_id.h @@ -70,39 +70,39 @@ enum class CommandID : uint8_t { STICK20_CMD_SEND_NEW_PASSWORD = stick20::CMD_START_VALUE + 19, ENABLE_CRYPTED_PARI = 0x20, - DISABLE_CRYPTED_PARI, - ENABLE_HIDDEN_CRYPTED_PARI, - DISABLE_HIDDEN_CRYPTED_PARI, - ENABLE_FIRMWARE_UPDATE, - EXPORT_FIRMWARE_TO_FILE, - GENERATE_NEW_KEYS, - FILL_SD_CARD_WITH_RANDOM_CHARS, + DISABLE_CRYPTED_PARI = 0x20 + 1, + ENABLE_HIDDEN_CRYPTED_PARI = 0x20 + 2, + DISABLE_HIDDEN_CRYPTED_PARI = 0x20 + 3, + ENABLE_FIRMWARE_UPDATE = 0x20 + 4, + EXPORT_FIRMWARE_TO_FILE = 0x20 + 5, + GENERATE_NEW_KEYS = 0x20 + 6, + FILL_SD_CARD_WITH_RANDOM_CHARS = 0x20 + 7, - WRITE_STATUS_DATA, - ENABLE_READONLY_UNCRYPTED_LUN, - ENABLE_READWRITE_UNCRYPTED_LUN, + WRITE_STATUS_DATA = 0x20 + 8, + ENABLE_READONLY_UNCRYPTED_LUN = 0x20 + 9, + ENABLE_READWRITE_UNCRYPTED_LUN = 0x20 + 10, - SEND_PASSWORD_MATRIX, - SEND_PASSWORD_MATRIX_PINDATA, - SEND_PASSWORD_MATRIX_SETUP, + SEND_PASSWORD_MATRIX = 0x20 + 11, + SEND_PASSWORD_MATRIX_PINDATA = 0x20 + 12, + SEND_PASSWORD_MATRIX_SETUP = 0x20 + 13, - GET_DEVICE_STATUS, - SEND_DEVICE_STATUS, + GET_DEVICE_STATUS = 0x20 + 14, + SEND_DEVICE_STATUS = 0x20 + 15, - SEND_HIDDEN_VOLUME_PASSWORD, - SEND_HIDDEN_VOLUME_SETUP, - SEND_PASSWORD, - SEND_NEW_PASSWORD, - CLEAR_NEW_SD_CARD_FOUND, + SEND_HIDDEN_VOLUME_PASSWORD = 0x20 + 16, + SEND_HIDDEN_VOLUME_SETUP = 0x20 + 17, + SEND_PASSWORD = 0x20 + 18, + SEND_NEW_PASSWORD = 0x20 + 19, + CLEAR_NEW_SD_CARD_FOUND = 0x20 + 20, - SEND_STARTUP, - SEND_CLEAR_STICK_KEYS_NOT_INITIATED, - SEND_LOCK_STICK_HARDWARE, + SEND_STARTUP = 0x20 + 21, + SEND_CLEAR_STICK_KEYS_NOT_INITIATED = 0x20 + 22, + SEND_LOCK_STICK_HARDWARE = 0x20 + 23, - PRODUCTION_TEST, - SEND_DEBUG_DATA, + PRODUCTION_TEST = 0x20 + 24, + SEND_DEBUG_DATA = 0x20 + 25, - CHANGE_UPDATE_PIN, + CHANGE_UPDATE_PIN = 0x20 + 26, GET_PW_SAFE_SLOT_STATUS = 0x60, GET_PW_SAFE_SLOT_NAME = 0x61, -- cgit v1.2.3 From a4d93360a600d5361a825c5270cb313202e1f318 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 27 Oct 2016 19:42:17 +0200 Subject: Fix naming for change password commands ids Signed-off-by: Szczepan Zalega --- include/command_id.h | 3 --- include/stick20_commands.h | 4 ++-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/include/command_id.h b/include/command_id.h index 76c7132..aa65dd3 100644 --- a/include/command_id.h +++ b/include/command_id.h @@ -66,9 +66,6 @@ enum class CommandID : uint8_t { CHANGE_USER_PIN = 0x14, CHANGE_ADMIN_PIN = 0x15, - STICK20_CMD_SEND_PASSWORD = stick20::CMD_START_VALUE + 18, - STICK20_CMD_SEND_NEW_PASSWORD = stick20::CMD_START_VALUE + 19, - ENABLE_CRYPTED_PARI = 0x20, DISABLE_CRYPTED_PARI = 0x20 + 1, ENABLE_HIDDEN_CRYPTED_PARI = 0x20 + 2, diff --git a/include/stick20_commands.h b/include/stick20_commands.h index a335809..7b69ec6 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -23,7 +23,7 @@ namespace nitrokey { Admin = 'A' }; - class ChangeAdminUserPin20Current : Command { + class ChangeAdminUserPin20Current : Command { public: struct CommandPayload { uint8_t kind; @@ -46,7 +46,7 @@ namespace nitrokey { }; - class ChangeAdminUserPin20New : Command { + class ChangeAdminUserPin20New : Command { public: struct CommandPayload { -- cgit v1.2.3 From b727d90d4e599762ff3eebff2349ae0fed1e0743 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 27 Oct 2016 20:10:22 +0200 Subject: Support Storage status commands: SendStartup ProductionTest Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 170 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 133 insertions(+), 37 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 7b69ec6..4bbb8c0 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -177,35 +177,78 @@ namespace nitrokey { }; - class SetupHiddenVolume : Command { - public: - typedef Transaction - CommandTransaction; - }; - class GetDeviceStatus : Command { + class SendStartup : Command { public: - static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 20 + 1; + struct CommandPayload { + uint64_t localtime; // POSIX seconds from epoch start, supports until year 2106 + std::string dissect() const { + std::stringstream ss; + print_to_ss( localtime ); + return ss.str(); + } + void set_defaults(){ + localtime = + std::chrono::duration_cast ( + std::chrono::system_clock::now().time_since_epoch()).count(); + } + }__packed; + + static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; static const int payload_absolute_begin = 8; static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; struct ResponsePayload { - uint8_t _padding[padding_size]; //TODO confirm padding in Storage firmware - //data starts from 21st byte of packet -> 13th byte of payload - uint8_t command_counter; - uint8_t last_command; - uint8_t status; - uint8_t progress_bar_value; + uint8_t _padding[padding_size]; + + uint8_t SendCounter_u8; + uint8_t SendDataType_u8; + uint8_t FollowBytesFlag_u8; + uint8_t SendSize_u8; + + uint16_t MagicNumber_StickConfig_u16; + uint8_t ReadWriteFlagUncryptedVolume_u8; + uint8_t ReadWriteFlagCryptedVolume_u8; + uint8_t VersionInfo_au8[4]; + uint8_t ReadWriteFlagHiddenVolume_u8; + uint8_t FirmwareLocked_u8; + uint8_t NewSDCardFound_u8; + uint8_t SDFillWithRandomChars_u8; + uint32_t ActiveSD_CardID_u32; + uint8_t VolumeActiceFlag_u8; + uint8_t NewSmartCardFound_u8; + uint8_t UserPwRetryCount; + uint8_t AdminPwRetryCount; + uint32_t ActiveSmartCardID_u32; + uint8_t StickKeysNotInitiated; bool isValid() const { return true; } std::string dissect() const { std::stringstream ss; - print_to_ss((int)command_counter); - print_to_ss((int)last_command); - print_to_ss((int)status); - print_to_ss((int)progress_bar_value); + + print_to_ss((int) SendCounter_u8 ); + print_to_ss((int) SendDataType_u8 ); + print_to_ss((int) FollowBytesFlag_u8 ); + print_to_ss((int) SendSize_u8 ); + + print_to_ss( MagicNumber_StickConfig_u16 ); + print_to_ss((int) ReadWriteFlagUncryptedVolume_u8 ); + print_to_ss((int) ReadWriteFlagCryptedVolume_u8 ); + print_to_ss((int) VersionInfo_au8[1] ); + print_to_ss((int) VersionInfo_au8[3] ); + print_to_ss((int) ReadWriteFlagHiddenVolume_u8 ); + print_to_ss((int) FirmwareLocked_u8 ); + print_to_ss((int) NewSDCardFound_u8 ); + print_to_ss((int) SDFillWithRandomChars_u8 ); + print_to_ss( ActiveSD_CardID_u32 ); + print_to_ss((int) VolumeActiceFlag_u8 ); + print_to_ss((int) NewSmartCardFound_u8 ); + print_to_ss((int) UserPwRetryCount ); + print_to_ss((int) AdminPwRetryCount ); + print_to_ss( ActiveSmartCardID_u32 ); + print_to_ss((int) StickKeysNotInitiated ); ss << "_padding:\t" << ::nitrokey::misc::hexdump((const char *) (_padding), sizeof _padding); @@ -213,7 +256,7 @@ namespace nitrokey { } } __packed; - typedef Transaction + typedef Transaction CommandTransaction; }; @@ -223,41 +266,94 @@ namespace nitrokey { class SendSetReadwriteToUncryptedVolume : public PasswordCommand {}; class SendClearNewSdCardFound : public PasswordCommand {}; - class SendStartup : Command { + class GetDeviceStatus : Command { public: - struct CommandPayload { - uint64_t localtime; // POSIX - std::string dissect() const { - std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; - return ss.str(); - } - }; - typedef Transaction + typedef Transaction CommandTransaction; }; - class SendHiddenVolumeSetup : Command { + class SendHiddenVolumePassword : public PasswordCommand {}; + + class SetupHiddenVolume : Command { public: + constexpr static int MAX_HIDDEN_VOLUME_PASSOWORD_SIZE = 20; struct CommandPayload { - // TODO HiddenVolumeSetup_tst type - std::string dissect() const { - std::stringstream ss; -// ss << " admin_password:\t" << admin_password << std::endl; - return ss.str(); - } - }; + uint8_t SlotNr_u8; + uint8_t StartBlockPercent_u8; + uint8_t EndBlockPercent_u8; + uint8_t HiddenVolumePassword_au8[MAX_HIDDEN_VOLUME_PASSOWORD_SIZE + 1]; + }__packed; typedef Transaction CommandTransaction; }; + class LockFirmware : public PasswordCommand {}; class ProductionTest : Command { public: - typedef Transaction + static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; + static const int payload_absolute_begin = 8; + static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; + + struct ResponsePayload { + uint8_t _padding[padding_size]; + + uint8_t SendCounter_u8; + uint8_t SendDataType_u8; + uint8_t FollowBytesFlag_u8; + uint8_t SendSize_u8; + + uint8_t FirmwareVersion_au8[2]; // 2 byte // 2 + uint8_t FirmwareVersionInternal_u8; // 1 byte // 3 + uint8_t SD_Card_Size_u8; // 1 byte // 4 + uint32_t CPU_CardID_u32; // 4 byte // 8 + uint32_t SmartCardID_u32; // 4 byte // 12 + uint32_t SD_CardID_u32; // 4 byte // 16 + uint8_t SC_UserPwRetryCount; // User PIN retry count 1 byte // 17 + uint8_t SC_AdminPwRetryCount; // Admin PIN retry count 1 byte // 18 + uint8_t SD_Card_ManufacturingYear_u8; // 1 byte // 19 + uint8_t SD_Card_ManufacturingMonth_u8; // 1 byte // 20 + uint16_t SD_Card_OEM_u16; // 2 byte // 22 + uint16_t SD_WriteSpeed_u16; // in kbyte / sec 2 byte // 24 + uint8_t SD_Card_Manufacturer_u8; // 1 byte // 25 + + bool isValid() const { return true; } + + std::string dissect() const { + std::stringstream ss; + + print_to_ss((int) SendCounter_u8); + print_to_ss((int) SendDataType_u8); + print_to_ss((int) FollowBytesFlag_u8); + print_to_ss((int) SendSize_u8); + + print_to_ss((int) FirmwareVersion_au8[0]); + print_to_ss((int) FirmwareVersion_au8[1]); + print_to_ss((int) FirmwareVersionInternal_u8); + print_to_ss((int) SD_Card_Size_u8); + print_to_ss( CPU_CardID_u32); + print_to_ss( SmartCardID_u32); + print_to_ss( SD_CardID_u32); + print_to_ss((int) SC_UserPwRetryCount); + print_to_ss((int) SC_AdminPwRetryCount); + print_to_ss((int) SD_Card_ManufacturingYear_u8); + print_to_ss((int) SD_Card_ManufacturingMonth_u8); + print_to_ss( SD_Card_OEM_u16); + print_to_ss( SD_WriteSpeed_u16); + print_to_ss((int) SD_Card_Manufacturer_u8); + + ss << "_padding:\t" + << ::nitrokey::misc::hexdump((const char *) (_padding), + sizeof _padding); + return ss.str(); + } + + } __packed; + + typedef Transaction CommandTransaction; }; } -- cgit v1.2.3 From d7ee36dfdfc5a896f5ef7d04b7f1f70f05256ebc Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 27 Oct 2016 20:23:04 +0200 Subject: Test command ids correctness and getting device status Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index 3cfc5c1..8e3dacc 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -65,7 +65,68 @@ TEST_CASE("long operation test", "[test_long]") { } -TEST_CASE("test", "[test]") { + +#include "test_command_ids_header.h" + +TEST_CASE("test device commands ids", "[fast]") { + +// REQUIRE(STICK20_CMD_START_VALUE == static_cast(CommandID::START_VALUE)); + REQUIRE(STICK20_CMD_ENABLE_CRYPTED_PARI == static_cast(CommandID::ENABLE_CRYPTED_PARI)); + REQUIRE(STICK20_CMD_DISABLE_CRYPTED_PARI == static_cast(CommandID::DISABLE_CRYPTED_PARI)); + REQUIRE(STICK20_CMD_ENABLE_HIDDEN_CRYPTED_PARI == static_cast(CommandID::ENABLE_HIDDEN_CRYPTED_PARI)); + REQUIRE(STICK20_CMD_DISABLE_HIDDEN_CRYPTED_PARI == static_cast(CommandID::DISABLE_HIDDEN_CRYPTED_PARI)); + REQUIRE(STICK20_CMD_ENABLE_FIRMWARE_UPDATE == static_cast(CommandID::ENABLE_FIRMWARE_UPDATE)); + REQUIRE(STICK20_CMD_EXPORT_FIRMWARE_TO_FILE == static_cast(CommandID::EXPORT_FIRMWARE_TO_FILE)); + REQUIRE(STICK20_CMD_GENERATE_NEW_KEYS == static_cast(CommandID::GENERATE_NEW_KEYS)); + REQUIRE(STICK20_CMD_FILL_SD_CARD_WITH_RANDOM_CHARS == static_cast(CommandID::FILL_SD_CARD_WITH_RANDOM_CHARS)); + + REQUIRE(STICK20_CMD_WRITE_STATUS_DATA == static_cast(CommandID::WRITE_STATUS_DATA)); + REQUIRE(STICK20_CMD_ENABLE_READONLY_UNCRYPTED_LUN == static_cast(CommandID::ENABLE_READONLY_UNCRYPTED_LUN)); + REQUIRE(STICK20_CMD_ENABLE_READWRITE_UNCRYPTED_LUN == static_cast(CommandID::ENABLE_READWRITE_UNCRYPTED_LUN)); + + REQUIRE(STICK20_CMD_SEND_PASSWORD_MATRIX == static_cast(CommandID::SEND_PASSWORD_MATRIX)); + REQUIRE(STICK20_CMD_SEND_PASSWORD_MATRIX_PINDATA == static_cast(CommandID::SEND_PASSWORD_MATRIX_PINDATA)); + REQUIRE(STICK20_CMD_SEND_PASSWORD_MATRIX_SETUP == static_cast(CommandID::SEND_PASSWORD_MATRIX_SETUP)); + + REQUIRE(STICK20_CMD_GET_DEVICE_STATUS == static_cast(CommandID::GET_DEVICE_STATUS)); + REQUIRE(STICK20_CMD_SEND_DEVICE_STATUS == static_cast(CommandID::SEND_DEVICE_STATUS)); + + REQUIRE(STICK20_CMD_SEND_HIDDEN_VOLUME_PASSWORD == static_cast(CommandID::SEND_HIDDEN_VOLUME_PASSWORD)); + REQUIRE(STICK20_CMD_SEND_HIDDEN_VOLUME_SETUP == static_cast(CommandID::SEND_HIDDEN_VOLUME_SETUP)); + REQUIRE(STICK20_CMD_SEND_PASSWORD == static_cast(CommandID::SEND_PASSWORD)); + REQUIRE(STICK20_CMD_SEND_NEW_PASSWORD == static_cast(CommandID::SEND_NEW_PASSWORD)); + REQUIRE(STICK20_CMD_CLEAR_NEW_SD_CARD_FOUND == static_cast(CommandID::CLEAR_NEW_SD_CARD_FOUND)); + + REQUIRE(STICK20_CMD_SEND_STARTUP == static_cast(CommandID::SEND_STARTUP)); + REQUIRE(STICK20_CMD_SEND_CLEAR_STICK_KEYS_NOT_INITIATED == static_cast(CommandID::SEND_CLEAR_STICK_KEYS_NOT_INITIATED)); + REQUIRE(STICK20_CMD_SEND_LOCK_STICK_HARDWARE == static_cast(CommandID::SEND_LOCK_STICK_HARDWARE)); + + REQUIRE(STICK20_CMD_PRODUCTION_TEST == static_cast(CommandID::PRODUCTION_TEST)); + REQUIRE(STICK20_CMD_SEND_DEBUG_DATA == static_cast(CommandID::SEND_DEBUG_DATA)); + + REQUIRE(STICK20_CMD_CHANGE_UPDATE_PIN == static_cast(CommandID::CHANGE_UPDATE_PIN)); + +} + +TEST_CASE("test device internal status with various commands", "[fast]") { + Stick20 stick; + bool connected = stick.connect(); + REQUIRE(connected == true); + + Log::instance().set_loglevel(Loglevel::DEBUG_L2); + auto p = get_payload(); + p.set_defaults(); + auto device_status = stick20::SendStartup::CommandTransaction::run(stick, p); + REQUIRE(device_status.data().AdminPwRetryCount == 3); + REQUIRE(device_status.data().UserPwRetryCount == 3); + REQUIRE(device_status.data().ActiveSmartCardID_u32 != 0); + + auto production_status = stick20::ProductionTest::CommandTransaction::run(stick); + REQUIRE(production_status.data().SD_Card_Size_u8 == 8); + REQUIRE(production_status.data().SD_CardID_u32 != 0); +} + +TEST_CASE("general test", "[test]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); -- cgit v1.2.3 From d58f3fd3bb6df5d3f46e3c4c3b719174e31b7201 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 27 Oct 2016 21:14:17 +0200 Subject: Support for setting hidden volume and test for it Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 19 +++++++++++++++++-- unittest/test2.cc | 20 ++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 4bbb8c0..a1e65c2 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -282,8 +282,23 @@ namespace nitrokey { uint8_t SlotNr_u8; uint8_t StartBlockPercent_u8; uint8_t EndBlockPercent_u8; - uint8_t HiddenVolumePassword_au8[MAX_HIDDEN_VOLUME_PASSOWORD_SIZE + 1]; - }__packed; + uint8_t HiddenVolumePassword_au8[MAX_HIDDEN_VOLUME_PASSOWORD_SIZE + 1]; //last char is a null terminator TODO check if it's needed + std::string dissect() const { + std::stringstream ss; + print_to_ss((int) SlotNr_u8); + print_to_ss((int) StartBlockPercent_u8); + print_to_ss((int) EndBlockPercent_u8); + ss << " HiddenVolumePassword_au8:\t" + << HiddenVolumePassword_au8 << std::endl; + return ss.str(); + } + + void set_defaults(){ + SlotNr_u8 = 0; + StartBlockPercent_u8 = 70; + EndBlockPercent_u8 = 90; + } + } __packed; typedef Transaction CommandTransaction; diff --git a/unittest/test2.cc b/unittest/test2.cc index 8e3dacc..d79042a 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -126,6 +126,26 @@ TEST_CASE("test device internal status with various commands", "[fast]") { REQUIRE(production_status.data().SD_CardID_u32 != 0); } +TEST_CASE("setup hidden volume test", "[hidden]") { + Stick20 stick; + bool connected = stick.connect(); + REQUIRE(connected == true); + Log::instance().set_loglevel(Loglevel::DEBUG_L2); + stick10::LockDevice::CommandTransaction::run(stick); + this_thread::sleep_for(2000ms); + + execute_password_command(stick, "123456"); + + auto p = get_payload(); + p.set_defaults(); + auto hidden_volume_password = "123123123"; + strcpyT(p.HiddenVolumePassword_au8, hidden_volume_password); + stick20::SetupHiddenVolume::CommandTransaction::run(stick, p); + this_thread::sleep_for(2000ms); + + execute_password_command(stick, hidden_volume_password); +} + TEST_CASE("general test", "[test]") { Stick20 stick; bool connected = stick.connect(); -- cgit v1.2.3 From 9772055e79da77c6ec9ea6992cc77891efc1265a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 11:31:16 +0200 Subject: Test multiple hidden volumes with different passwords and locations Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/unittest/test2.cc b/unittest/test2.cc index d79042a..21122ef 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -146,6 +146,38 @@ TEST_CASE("setup hidden volume test", "[hidden]") { execute_password_command(stick, hidden_volume_password); } +TEST_CASE("setup multiple hidden volumes", "[hidden2]") { + Stick20 stick; + bool connected = stick.connect(); + REQUIRE(connected == true); + Log::instance().set_loglevel(Loglevel::DEBUG_L2); + + auto user_pin = "123456"; + stick10::LockDevice::CommandTransaction::run(stick); + this_thread::sleep_for(2000ms); + execute_password_command(stick, user_pin); + + constexpr int volume_count = 4; + for (int i = 0; i < volume_count; ++i) { + auto p = get_payload(); + p.SlotNr_u8 = i; + p.StartBlockPercent_u8 = 20 + 10*i; + p.EndBlockPercent_u8 = p.StartBlockPercent_u8+i+1; + auto hidden_volume_password = std::string("123123123")+std::to_string(i); + strcpyT(p.HiddenVolumePassword_au8, hidden_volume_password.c_str()); + stick20::SetupHiddenVolume::CommandTransaction::run(stick, p); + this_thread::sleep_for(2000ms); + } + + + for (int i = 0; i < volume_count; ++i) { + execute_password_command(stick, user_pin); + auto hidden_volume_password = std::string("123123123")+std::to_string(i); + execute_password_command(stick, hidden_volume_password.c_str()); + this_thread::sleep_for(2000ms); + } +} + TEST_CASE("general test", "[test]") { Stick20 stick; bool connected = stick.connect(); -- cgit v1.2.3 From e262c978f4cb8b448087102b68bbdcc731a090a0 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 11:47:06 +0200 Subject: Print ascii representation of dump in hexdump Signed-off-by: Szczepan Zalega --- misc.cc | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/misc.cc b/misc.cc index 9b339cd..c9d38cb 100644 --- a/misc.cc +++ b/misc.cc @@ -34,6 +34,7 @@ std::vector hex_string_to_byte(const char* hexString){ return data; }; +#include std::string hexdump(const char *p, size_t size, bool print_header) { std::stringstream out; char formatbuf[128]; @@ -45,9 +46,23 @@ std::string hexdump(const char *p, size_t size, bool print_header) { out << formatbuf; } - for (const char *le = p + 16; p < le && p < pend; p++) { - snprintf(formatbuf, 128, "%02x ", uint8_t(*p)); - out << formatbuf; + const char* pp = p; + for (const char *le = p + 16; p < le; p++) { + if (p < pend){ + snprintf(formatbuf, 128, "%02x ", uint8_t(*p)); + out << formatbuf; + } else { + out << "-- "; + } + + } + 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; } -- cgit v1.2.3 From 3b1926164b2e0eb91cf3a7e9c854cca85f7d4c8e Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 14:33:25 +0200 Subject: Support for changing firmware update password and test Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 12 +++++++----- unittest/test2.cc | 25 ++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index a1e65c2..676b3df 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -99,15 +99,17 @@ namespace nitrokey { class DisableHiddenEncryptedPartition : public PasswordCommand {}; class EnableFirmwareUpdate : public PasswordCommand {}; - class UpdatePassword : Command { + class ChangeUpdatePassword : Command { public: struct CommandPayload { - uint8_t old_password[15]; - uint8_t new_password[15]; + uint8_t __gap; + uint8_t current_update_password[20]; + uint8_t __gap2; + uint8_t new_update_password[20]; std::string dissect() const { std::stringstream ss; - print_to_ss( old_password ); - print_to_ss( new_password ); + print_to_ss( current_update_password ); + print_to_ss( new_update_password ); return ss.str(); } }; diff --git a/unittest/test2.cc b/unittest/test2.cc index 21122ef..8db91b7 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -178,7 +178,30 @@ TEST_CASE("setup multiple hidden volumes", "[hidden2]") { } } -TEST_CASE("general test", "[test]") { +//in case of a bug this could change update PIN to some unexpected value +// - please save log with packet dump if this test will not pass +TEST_CASE("update password change", "[dangerous]") { + Stick20 stick; + bool connected = stick.connect(); + REQUIRE(connected == true); + Log::instance().set_loglevel(Loglevel::DEBUG_L2); + + auto pass1 = "12345678"; + auto pass2 = "12345678901234567890"; + + auto data = { + make_pair(pass1, pass2), + make_pair(pass2, pass1), + }; + for (auto && password: data) { + auto p = get_payload(); + strcpyT(p.current_update_password, password.first); + strcpyT(p.new_update_password, password.second); + stick20::ChangeUpdatePassword::CommandTransaction::run(stick, p); + } +} + + TEST_CASE("general test", "[test]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); -- cgit v1.2.3 From e45e2f03cf40b5826632ab95cbc79c487249897a Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 14:34:25 +0200 Subject: Mark unused commands and remove obsolete code Signed-off-by: Szczepan Zalega --- include/command_id.h | 8 ++++---- include/stick20_commands.h | 3 --- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/include/command_id.h b/include/command_id.h index aa65dd3..9cace2f 100644 --- a/include/command_id.h +++ b/include/command_id.h @@ -79,14 +79,14 @@ enum class CommandID : uint8_t { ENABLE_READONLY_UNCRYPTED_LUN = 0x20 + 9, ENABLE_READWRITE_UNCRYPTED_LUN = 0x20 + 10, - SEND_PASSWORD_MATRIX = 0x20 + 11, - SEND_PASSWORD_MATRIX_PINDATA = 0x20 + 12, - SEND_PASSWORD_MATRIX_SETUP = 0x20 + 13, + SEND_PASSWORD_MATRIX = 0x20 + 11, //@unused + SEND_PASSWORD_MATRIX_PINDATA = 0x20 + 12, //@unused + SEND_PASSWORD_MATRIX_SETUP = 0x20 + 13, //@unused GET_DEVICE_STATUS = 0x20 + 14, SEND_DEVICE_STATUS = 0x20 + 15, - SEND_HIDDEN_VOLUME_PASSWORD = 0x20 + 16, + SEND_HIDDEN_VOLUME_PASSWORD = 0x20 + 16, //@unused SEND_HIDDEN_VOLUME_SETUP = 0x20 + 17, SEND_PASSWORD = 0x20 + 18, SEND_NEW_PASSWORD = 0x20 + 19, diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 676b3df..237118d 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -141,8 +141,6 @@ namespace nitrokey { CommandTransaction; }; -// class FillSDCardWithRandomChars : public PasswordCommand {}; - class FillSDCardWithRandomChars : Command { public: @@ -275,7 +273,6 @@ namespace nitrokey { CommandTransaction; }; - class SendHiddenVolumePassword : public PasswordCommand {}; class SetupHiddenVolume : Command { public: -- cgit v1.2.3 From 6343eea03980627cb763de777af6b316130bdf43 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 14:55:56 +0200 Subject: Support getting SD card occupancy and test Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 21 +++++++++++++++++++++ unittest/test2.cc | 6 ++++++ 2 files changed, 27 insertions(+) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 237118d..42f46ad 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -273,6 +273,27 @@ namespace nitrokey { CommandTransaction; }; + class GetSDCardOccupancy : Command { + public: + struct ResponsePayload { + uint8_t WriteLevelMin; + uint8_t WriteLevelMax; + uint8_t ReadLevelMin; + uint8_t ReadLevelMax; + std::string dissect() const { + std::stringstream ss; + print_to_ss((int) WriteLevelMin); + print_to_ss((int) WriteLevelMax); + print_to_ss((int) ReadLevelMin); + print_to_ss((int) ReadLevelMax); + return ss.str(); + } + } __packed; + + typedef Transaction + CommandTransaction; + }; + class SetupHiddenVolume : Command { public: diff --git a/unittest/test2.cc b/unittest/test2.cc index 8db91b7..f5d2b28 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -124,6 +124,12 @@ TEST_CASE("test device internal status with various commands", "[fast]") { auto production_status = stick20::ProductionTest::CommandTransaction::run(stick); REQUIRE(production_status.data().SD_Card_Size_u8 == 8); REQUIRE(production_status.data().SD_CardID_u32 != 0); + + auto sdcard_occupancy = stick20::GetSDCardOccupancy::CommandTransaction::run(stick); + REQUIRE((int) sdcard_occupancy.data().ReadLevelMin >= 0); + REQUIRE((int) sdcard_occupancy.data().ReadLevelMax <= 100); + REQUIRE((int) sdcard_occupancy.data().WriteLevelMin >= 0); + REQUIRE((int) sdcard_occupancy.data().WriteLevelMax <= 100); } TEST_CASE("setup hidden volume test", "[hidden]") { -- cgit v1.2.3 From ce30b49b4d50f2eff39a40ddd0c02ad96b78654c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 16:29:55 +0200 Subject: Make packet variables' names more clear General fixes Remove default values from hidden volume setup command rename password -> pin Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 6 +++--- include/stick20_commands.h | 31 ++++++++++++------------------- unittest/test2.cc | 6 ++++-- 3 files changed, 19 insertions(+), 24 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 4c2c834..8bc0e38 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -420,7 +420,7 @@ namespace nitrokey{ } case DeviceModel::STORAGE : { auto p = get_payload(); - strcpyT(p.admin_password, admin_password); + strcpyT(p.admin_pin, admin_password); p.setKindPrefixed(); stick20::CreateNewKeys::CommandTransaction::run(*device, p); break; @@ -448,10 +448,10 @@ namespace nitrokey{ p2.set_kind(PasswordKind::Admin); strcpyT(p2.old_pin, admin_password); ChangeAdminUserPin20Current::CommandTransaction::run(*device, p2); - auto p3 = get_payload(); + auto p3 = get_payload(); p3.set_kind(PasswordKind::Admin); strcpyT(p3.user_new_password, new_user_password); - stick20::UnlockUserPassword::CommandTransaction::run(*device, p3); + stick20::UnlockUserPin::CommandTransaction::run(*device, p3); break; } } diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 42f46ad..31d7b13 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -71,7 +71,7 @@ namespace nitrokey { }; - class UnlockUserPassword : Command { + class UnlockUserPin : Command { public: struct CommandPayload { uint8_t kind; @@ -124,11 +124,11 @@ namespace nitrokey { public: struct CommandPayload { uint8_t kind; - uint8_t admin_password[30]; //CS20_MAX_PASSWORD_LEN + uint8_t admin_pin[30]; //CS20_MAX_PASSWORD_LEN std::string dissect() const { std::stringstream ss; print_to_ss( kind ); - ss << " admin_password:\t" << admin_password << std::endl; + ss << " admin_pin:\t" << admin_pin << std::endl; return ss.str(); } @@ -152,13 +152,13 @@ namespace nitrokey { struct CommandPayload { uint8_t volume_flag; uint8_t kind; - uint8_t password[20]; + uint8_t admin_pin[20]; std::string dissect() const { std::stringstream ss; print_to_ss( (int) volume_flag ); print_to_ss( kind ); - print_to_ss(password); + print_to_ss(admin_pin); return ss.str(); } void set_kind_user() { @@ -297,27 +297,20 @@ namespace nitrokey { class SetupHiddenVolume : Command { public: - constexpr static int MAX_HIDDEN_VOLUME_PASSOWORD_SIZE = 20; + constexpr static int MAX_HIDDEN_VOLUME_PASSWORD_SIZE = 20; struct CommandPayload { uint8_t SlotNr_u8; uint8_t StartBlockPercent_u8; uint8_t EndBlockPercent_u8; - uint8_t HiddenVolumePassword_au8[MAX_HIDDEN_VOLUME_PASSOWORD_SIZE + 1]; //last char is a null terminator TODO check if it's needed + uint8_t HiddenVolumePassword_au8[MAX_HIDDEN_VOLUME_PASSWORD_SIZE]; std::string dissect() const { std::stringstream ss; print_to_ss((int) SlotNr_u8); print_to_ss((int) StartBlockPercent_u8); print_to_ss((int) EndBlockPercent_u8); - ss << " HiddenVolumePassword_au8:\t" - << HiddenVolumePassword_au8 << std::endl; + print_to_ss(HiddenVolumePassword_au8); return ss.str(); } - - void set_defaults(){ - SlotNr_u8 = 0; - StartBlockPercent_u8 = 70; - EndBlockPercent_u8 = 90; - } } __packed; typedef Transaction @@ -329,9 +322,9 @@ namespace nitrokey { class ProductionTest : Command { public: - static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; - static const int payload_absolute_begin = 8; - static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; + static constexpr int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; + static constexpr int payload_absolute_begin = 8; + static constexpr int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; struct ResponsePayload { uint8_t _padding[padding_size]; @@ -380,7 +373,7 @@ namespace nitrokey { print_to_ss( SD_WriteSpeed_u16); print_to_ss((int) SD_Card_Manufacturer_u8); - ss << "_padding:\t" + ss << "_padding:" << std::endl << ::nitrokey::misc::hexdump((const char *) (_padding), sizeof _padding); return ss.str(); diff --git a/unittest/test2.cc b/unittest/test2.cc index f5d2b28..9aaef3f 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -40,7 +40,7 @@ TEST_CASE("long operation test", "[test_long]") { // execute_password_command(stick, "12345678", 'P'); auto p = get_payload(); p.set_defaults(); - strcpyT(p.password, "12345678"); + strcpyT(p.admin_pin, "12345678"); FillSDCardWithRandomChars::CommandTransaction::run(stick, p); this_thread::sleep_for(1000ms); @@ -143,7 +143,9 @@ TEST_CASE("setup hidden volume test", "[hidden]") { execute_password_command(stick, "123456"); auto p = get_payload(); - p.set_defaults(); + p.SlotNr_u8 = 0; + p.StartBlockPercent_u8 = 70; + p.EndBlockPercent_u8 = 90; auto hidden_volume_password = "123123123"; strcpyT(p.HiddenVolumePassword_au8, hidden_volume_password); stick20::SetupHiddenVolume::CommandTransaction::run(stick, p); -- cgit v1.2.3 From 6af0fa2c553ca1a31da63b7164b53defe11172df Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 19:07:51 +0200 Subject: Tests refactoring - replace magic values with constants Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index 9aaef3f..94a0dd3 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -1,4 +1,8 @@ #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"; + #include "catch.hpp" #include @@ -37,10 +41,9 @@ TEST_CASE("long operation test", "[test_long]") { REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG_L2); try{ -// execute_password_command(stick, "12345678", 'P'); auto p = get_payload(); p.set_defaults(); - strcpyT(p.admin_pin, "12345678"); + strcpyT(p.admin_pin, default_admin_pin); FillSDCardWithRandomChars::CommandTransaction::run(stick, p); this_thread::sleep_for(1000ms); @@ -140,7 +143,8 @@ TEST_CASE("setup hidden volume test", "[hidden]") { stick10::LockDevice::CommandTransaction::run(stick); this_thread::sleep_for(2000ms); - execute_password_command(stick, "123456"); + auto user_pin = default_user_pin; + execute_password_command(stick, user_pin); auto p = get_payload(); p.SlotNr_u8 = 0; @@ -160,7 +164,7 @@ TEST_CASE("setup multiple hidden volumes", "[hidden2]") { REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG_L2); - auto user_pin = "123456"; + auto user_pin = default_user_pin; stick10::LockDevice::CommandTransaction::run(stick); this_thread::sleep_for(2000ms); execute_password_command(stick, user_pin); @@ -194,7 +198,7 @@ TEST_CASE("update password change", "[dangerous]") { REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG_L2); - auto pass1 = "12345678"; + auto pass1 = default_admin_pin; auto pass2 = "12345678901234567890"; auto data = { @@ -220,7 +224,7 @@ TEST_CASE("update password change", "[dangerous]") { // execute_password_command(stick, "123456"); // execute_password_command(stick, "123456"); this_thread::sleep_for(1000ms); - execute_password_command(stick, "123456"); + execute_password_command(stick, default_user_pin); this_thread::sleep_for(4000ms); bool passed = false; for(int i=0; i<5; i++){ @@ -239,9 +243,11 @@ TEST_CASE("update password change", "[dangerous]") { } execute_password_command(stick, "123123123"); - execute_password_command(stick, "123456"); - execute_password_command(stick, "123456"); - execute_password_command(stick, "12345678", 'A'); + + + execute_password_command(stick, default_user_pin); + execute_password_command(stick, default_user_pin); + execute_password_command(stick, default_admin_pin, 'A'); stick20::GetDeviceStatus::CommandTransaction::run(stick); this_thread::sleep_for(1000ms); // execute_password_command(stick, "123123123"); //CAUTION -- cgit v1.2.3 From 4200d7428ac200fd7c0fb57e67aed9f492bfb3d5 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Fri, 28 Oct 2016 20:04:14 +0200 Subject: Tests: skip long and dangerous tests remove hidden volume test from general test Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 42 ++++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index 94a0dd3..e4edf87 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -1,6 +1,6 @@ #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() -static const char *const default_admin_pin = "12345678"; +static const char *const default_admin_pin = "12345678"; static const char *const default_user_pin = "123456"; #include "catch.hpp" @@ -34,8 +34,19 @@ void execute_password_command(Device &stick, const char *password, const char ki this_thread::sleep_for(1000ms); } +/** + * fail on purpose (will result in failed test) + * disable from running unwillingly + */ +void SKIP_TEST() { + CAPTURE("Failing current test to SKIP it"); + REQUIRE(false); +} + TEST_CASE("long operation test", "[test_long]") { + SKIP_TEST(); + Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); @@ -158,7 +169,7 @@ TEST_CASE("setup hidden volume test", "[hidden]") { execute_password_command(stick, hidden_volume_password); } -TEST_CASE("setup multiple hidden volumes", "[hidden2]") { +TEST_CASE("setup multiple hidden volumes", "[hidden]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); @@ -190,9 +201,12 @@ TEST_CASE("setup multiple hidden volumes", "[hidden2]") { } } + //in case of a bug this could change update PIN to some unexpected value // - please save log with packet dump if this test will not pass TEST_CASE("update password change", "[dangerous]") { + SKIP_TEST(); + Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); @@ -213,7 +227,7 @@ TEST_CASE("update password change", "[dangerous]") { } } - TEST_CASE("general test", "[test]") { +TEST_CASE("general test", "[test]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); @@ -223,27 +237,7 @@ TEST_CASE("update password change", "[dangerous]") { stick10::LockDevice::CommandTransaction::run(stick); // execute_password_command(stick, "123456"); // execute_password_command(stick, "123456"); - this_thread::sleep_for(1000ms); - execute_password_command(stick, default_user_pin); - this_thread::sleep_for(4000ms); - bool passed = false; - for(int i=0; i<5; i++){ - try { - execute_password_command(stick, "123123123"); - CHECK(true); - passed=true; - break; - } - catch (CommandFailedException &e){ - this_thread::sleep_for(2000ms); - } - } - if(!passed){ - CHECK(false); - } - - execute_password_command(stick, "123123123"); - +// execute_password_command(stick, "123123123"); execute_password_command(stick, default_user_pin); execute_password_command(stick, default_user_pin); -- cgit v1.2.3 From 90e3e144728114189b5b33b4763b07e871b2e66c Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 16:33:40 +0100 Subject: Describe commands and mark unused Signed-off-by: Szczepan Zalega --- include/command_id.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/include/command_id.h b/include/command_id.h index 9cace2f..a3806f0 100644 --- a/include/command_id.h +++ b/include/command_id.h @@ -67,15 +67,15 @@ enum class CommandID : uint8_t { CHANGE_ADMIN_PIN = 0x15, ENABLE_CRYPTED_PARI = 0x20, - DISABLE_CRYPTED_PARI = 0x20 + 1, + DISABLE_CRYPTED_PARI = 0x20 + 1, //@unused ENABLE_HIDDEN_CRYPTED_PARI = 0x20 + 2, - DISABLE_HIDDEN_CRYPTED_PARI = 0x20 + 3, - ENABLE_FIRMWARE_UPDATE = 0x20 + 4, + DISABLE_HIDDEN_CRYPTED_PARI = 0x20 + 3, //@unused + ENABLE_FIRMWARE_UPDATE = 0x20 + 4, //enables update mode EXPORT_FIRMWARE_TO_FILE = 0x20 + 5, GENERATE_NEW_KEYS = 0x20 + 6, FILL_SD_CARD_WITH_RANDOM_CHARS = 0x20 + 7, - WRITE_STATUS_DATA = 0x20 + 8, + WRITE_STATUS_DATA = 0x20 + 8, //@unused ENABLE_READONLY_UNCRYPTED_LUN = 0x20 + 9, ENABLE_READWRITE_UNCRYPTED_LUN = 0x20 + 10, @@ -94,10 +94,10 @@ enum class CommandID : uint8_t { SEND_STARTUP = 0x20 + 21, SEND_CLEAR_STICK_KEYS_NOT_INITIATED = 0x20 + 22, - SEND_LOCK_STICK_HARDWARE = 0x20 + 23, + SEND_LOCK_STICK_HARDWARE = 0x20 + 23, //locks firmware upgrade PRODUCTION_TEST = 0x20 + 24, - SEND_DEBUG_DATA = 0x20 + 25, + SEND_DEBUG_DATA = 0x20 + 25, //@unused CHANGE_UPDATE_PIN = 0x20 + 26, @@ -109,8 +109,8 @@ enum class CommandID : uint8_t { SET_PW_SAFE_SLOT_DATA_2 = 0x65, PW_SAFE_ERASE_SLOT = 0x66, PW_SAFE_ENABLE = 0x67, - PW_SAFE_INIT_KEY = 0x68, - PW_SAFE_SEND_DATA = 0x69, + PW_SAFE_INIT_KEY = 0x68, //@unused + PW_SAFE_SEND_DATA = 0x69, //@unused SD_CARD_HIGH_WATERMARK = 0x70, DETECT_SC_AES = 0x6a, NEW_AES_KEY = 0x6b -- cgit v1.2.3 From 8b49ee9e25efbca9d0d51fcc8be17fd115fc78fd Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 16:56:40 +0100 Subject: Define configuration response packet separately Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 44 ++++++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 31d7b13..5c2d97e 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -178,23 +178,7 @@ namespace nitrokey { - - class SendStartup : Command { - public: - struct CommandPayload { - uint64_t localtime; // POSIX seconds from epoch start, supports until year 2106 - std::string dissect() const { - std::stringstream ss; - print_to_ss( localtime ); - return ss.str(); - } - void set_defaults(){ - localtime = - std::chrono::duration_cast ( - std::chrono::system_clock::now().time_since_epoch()).count(); - } - }__packed; - + namespace DeviceConfigurationResponsePacket{ static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; static const int payload_absolute_begin = 8; static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; @@ -249,14 +233,33 @@ namespace nitrokey { print_to_ss((int) AdminPwRetryCount ); print_to_ss( ActiveSmartCardID_u32 ); print_to_ss((int) StickKeysNotInitiated ); - ss << "_padding:\t" + ss << "_padding:" << std::endl << ::nitrokey::misc::hexdump((const char *) (_padding), sizeof _padding); return ss.str(); } } __packed; + } + + class SendStartup : Command { + public: + struct CommandPayload { + uint64_t localtime; // POSIX seconds from epoch start, supports until year 2106 + std::string dissect() const { + std::stringstream ss; + print_to_ss( localtime ); + return ss.str(); + } + void set_defaults(){ + localtime = + std::chrono::duration_cast ( + std::chrono::system_clock::now().time_since_epoch()).count(); + } + }__packed; + + using ResponsePayload = DeviceConfigurationResponsePacket::ResponsePayload; - typedef Transaction + typedef Transaction CommandTransaction; }; @@ -268,8 +271,9 @@ namespace nitrokey { class GetDeviceStatus : Command { public: + using ResponsePayload = DeviceConfigurationResponsePacket::ResponsePayload; - typedef Transaction + typedef Transaction CommandTransaction; }; -- cgit v1.2.3 From 9ad4796130a4ce192420563bb601468ffc292df9 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 17:48:18 +0100 Subject: Code refactoring - unify password only commands Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 12 +++---- include/command.h | 25 +++++++++++++-- include/stick20_commands.h | 78 ++++------------------------------------------ 3 files changed, 35 insertions(+), 80 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 8bc0e38..eb34ef2 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -304,10 +304,10 @@ namespace nitrokey{ case DeviceModel::STORAGE: { auto p = get_payload(); - strcpyT(p.old_pin, current_PIN); + strcpyT(p.password, current_PIN); p.set_kind(StoKind); auto p2 = get_payload(); - strcpyT(p2.new_pin, new_PIN); + strcpyT(p2.password, new_PIN); p2.set_kind(StoKind); ChangeAdminUserPin20Current::CommandTransaction::run(*device, p); ChangeAdminUserPin20New::CommandTransaction::run(*device, p2); @@ -445,12 +445,12 @@ namespace nitrokey{ } case DeviceModel::STORAGE : { auto p2 = get_payload(); - p2.set_kind(PasswordKind::Admin); - strcpyT(p2.old_pin, admin_password); + p2.set_defaults(); + strcpyT(p2.password, admin_password); ChangeAdminUserPin20Current::CommandTransaction::run(*device, p2); auto p3 = get_payload(); - p3.set_kind(PasswordKind::Admin); - strcpyT(p3.user_new_password, new_user_password); + p3.set_defaults(); + strcpyT(p3.password, new_user_password); stick20::UnlockUserPin::CommandTransaction::run(*device, p3); break; } diff --git a/include/command.h b/include/command.h index 5ac1d7f..badf068 100644 --- a/include/command.h +++ b/include/command.h @@ -19,13 +19,18 @@ namespace nitrokey { }; #define print_to_ss(x) ( ss << " " << (#x) <<":\t" << (x) << std::endl ); +namespace stick20{ + enum class PasswordKind : uint8_t { + User = 'P', + Admin = 'A' + }; - template + template class PasswordCommand : public Command { public: struct CommandPayload { uint8_t kind; - uint8_t password[20]; + uint8_t password[password_length]; std::string dissect() const { std::stringstream ss; @@ -40,6 +45,21 @@ namespace nitrokey { kind = (uint8_t) 'P'; } + void set_defaults(){ + set_kind(Tpassword_kind); + } + + void set_kind(PasswordKind password_kind){ + switch (password_kind){ + case PasswordKind::Admin: + set_kind_admin(); + break; + case PasswordKind::User: + set_kind_user(); + break; + } + }; + } __packed; typedef Transaction::command_id(), struct CommandPayload, struct EmptyPayload> @@ -47,6 +67,7 @@ namespace nitrokey { }; } + } } #undef print_to_ss diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 5c2d97e..a51d1ca 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -18,80 +18,14 @@ namespace nitrokey { #define print_to_ss(x) ( ss << " " << (#x) <<":\t" << (x) << std::endl ); namespace stick20 { - enum class PasswordKind : uint8_t { - User = 'P', - Admin = 'A' - }; - - class ChangeAdminUserPin20Current : Command { - public: - struct CommandPayload { - uint8_t kind; - uint8_t old_pin[20]; - - std::string dissect() const { - std::stringstream ss; - print_to_ss( kind ); - ss << " old_pin:\t" << old_pin << std::endl; - return ss.str(); - } - - void set_kind(PasswordKind k) { - kind = (uint8_t) k; - } - } __packed; - - typedef Transaction - CommandTransaction; - }; - - - class ChangeAdminUserPin20New : Command { - public: - - struct CommandPayload { - uint8_t kind; - uint8_t new_pin[20]; - - std::string dissect() const { - std::stringstream ss; - print_to_ss( kind ); - ss << " new_pin:\t" << new_pin << std::endl; - return ss.str(); - } - - void set_kind(PasswordKind k) { - kind = (uint8_t) k; - } - - } __packed; - - typedef Transaction - CommandTransaction; - }; - class UnlockUserPin : Command { - public: - struct CommandPayload { - uint8_t kind; - uint8_t user_new_password[20]; - - std::string dissect() const { - std::stringstream ss; - print_to_ss( kind ); - ss << " user_new_password:\t" << user_new_password << std::endl; - return ss.str(); - } - - void set_kind(PasswordKind k) { - kind = (uint8_t) k; - } - } __packed; - - typedef Transaction - CommandTransaction; - }; + class ChangeAdminUserPin20Current : + public PasswordCommand {}; + class ChangeAdminUserPin20New : + public PasswordCommand {}; + class UnlockUserPin : + public PasswordCommand {}; class EnableEncryptedPartition : public PasswordCommand {}; class DisableEncryptedPartition : public PasswordCommand {}; -- cgit v1.2.3 From 98b27cb58b12f699b5c11f88d55c3e3f70ed2063 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 18:02:55 +0100 Subject: Code refactoring - unify password only commands (2) Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 4 ++-- include/command.h | 9 ++++++++- include/stick20_commands.h | 24 ++---------------------- 3 files changed, 12 insertions(+), 25 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index eb34ef2..f0099da 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -420,8 +420,8 @@ namespace nitrokey{ } case DeviceModel::STORAGE : { auto p = get_payload(); - strcpyT(p.admin_pin, admin_password); - p.setKindPrefixed(); + strcpyT(p.password, admin_password); + p.set_defaults(); stick20::CreateNewKeys::CommandTransaction::run(*device, p); break; } diff --git a/include/command.h b/include/command.h index badf068..0a875e4 100644 --- a/include/command.h +++ b/include/command.h @@ -22,7 +22,8 @@ namespace nitrokey { namespace stick20{ enum class PasswordKind : uint8_t { User = 'P', - Admin = 'A' + Admin = 'A', + AdminPrefixed }; template @@ -41,6 +42,9 @@ namespace stick20{ void set_kind_admin() { kind = (uint8_t) 'A'; } + void set_kind_admin_prefixed() { + kind = (uint8_t) 'P'; + } void set_kind_user() { kind = (uint8_t) 'P'; } @@ -57,6 +61,9 @@ namespace stick20{ case PasswordKind::User: set_kind_user(); break; + case PasswordKind::AdminPrefixed: + set_kind_admin_prefixed(); + break; } }; diff --git a/include/stick20_commands.h b/include/stick20_commands.h index a51d1ca..d7d89cf 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -18,8 +18,6 @@ namespace nitrokey { #define print_to_ss(x) ( ss << " " << (#x) <<":\t" << (x) << std::endl ); namespace stick20 { - - class ChangeAdminUserPin20Current : public PasswordCommand {}; class ChangeAdminUserPin20New : @@ -54,26 +52,8 @@ namespace nitrokey { class ExportFirmware : public PasswordCommand {}; - class CreateNewKeys : Command { - public: - struct CommandPayload { - uint8_t kind; - uint8_t admin_pin[30]; //CS20_MAX_PASSWORD_LEN - std::string dissect() const { - std::stringstream ss; - print_to_ss( kind ); - ss << " admin_pin:\t" << admin_pin << std::endl; - return ss.str(); - } - - void setKindPrefixed() { - kind = 'P'; - } - } __packed; - - typedef Transaction - CommandTransaction; - }; + class CreateNewKeys : + public PasswordCommand {}; class FillSDCardWithRandomChars : Command { -- cgit v1.2.3 From b540266c4ce17b640724bc09275e45e15a53d707 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 18:19:54 +0100 Subject: Transmission data for 2.0 commands move to separate struct Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 67 +++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 36 deletions(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index d7d89cf..f816868 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -90,20 +90,37 @@ namespace nitrokey { CommandTransaction; }; - + namespace StorageCommandResponsePayload{ + static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; + static const int payload_absolute_begin = 8; + static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; + struct TransmissionData{ + uint8_t _padding[padding_size]; + + uint8_t SendCounter_u8; + uint8_t SendDataType_u8; + uint8_t FollowBytesFlag_u8; + uint8_t SendSize_u8; + + std::string dissect() const { + std::stringstream ss; + ss << "_padding:" << std::endl + << ::nitrokey::misc::hexdump((const char *) (_padding), + sizeof _padding); + print_to_ss((int) SendCounter_u8); + print_to_ss((int) SendDataType_u8); + print_to_ss((int) FollowBytesFlag_u8); + print_to_ss((int) SendSize_u8); + return ss.str(); + } + + } __packed; + } namespace DeviceConfigurationResponsePacket{ - static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; - static const int payload_absolute_begin = 8; - static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; struct ResponsePayload { - uint8_t _padding[padding_size]; - - uint8_t SendCounter_u8; - uint8_t SendDataType_u8; - uint8_t FollowBytesFlag_u8; - uint8_t SendSize_u8; + StorageCommandResponsePayload::TransmissionData transmission_data; uint16_t MagicNumber_StickConfig_u16; uint8_t ReadWriteFlagUncryptedVolume_u8; @@ -126,11 +143,7 @@ namespace nitrokey { std::string dissect() const { std::stringstream ss; - print_to_ss((int) SendCounter_u8 ); - print_to_ss((int) SendDataType_u8 ); - print_to_ss((int) FollowBytesFlag_u8 ); - print_to_ss((int) SendSize_u8 ); - + print_to_ss(transmission_data.dissect()); print_to_ss( MagicNumber_StickConfig_u16 ); print_to_ss((int) ReadWriteFlagUncryptedVolume_u8 ); print_to_ss((int) ReadWriteFlagCryptedVolume_u8 ); @@ -147,9 +160,7 @@ namespace nitrokey { print_to_ss((int) AdminPwRetryCount ); print_to_ss( ActiveSmartCardID_u32 ); print_to_ss((int) StickKeysNotInitiated ); - ss << "_padding:" << std::endl - << ::nitrokey::misc::hexdump((const char *) (_padding), - sizeof _padding); + return ss.str(); } } __packed; @@ -240,17 +251,9 @@ namespace nitrokey { class ProductionTest : Command { public: - static constexpr int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; - static constexpr int payload_absolute_begin = 8; - static constexpr int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; - struct ResponsePayload { - uint8_t _padding[padding_size]; - uint8_t SendCounter_u8; - uint8_t SendDataType_u8; - uint8_t FollowBytesFlag_u8; - uint8_t SendSize_u8; + StorageCommandResponsePayload::TransmissionData transmission_data; uint8_t FirmwareVersion_au8[2]; // 2 byte // 2 uint8_t FirmwareVersionInternal_u8; // 1 byte // 3 @@ -271,11 +274,7 @@ namespace nitrokey { std::string dissect() const { std::stringstream ss; - print_to_ss((int) SendCounter_u8); - print_to_ss((int) SendDataType_u8); - print_to_ss((int) FollowBytesFlag_u8); - print_to_ss((int) SendSize_u8); - + print_to_ss(transmission_data.dissect()); print_to_ss((int) FirmwareVersion_au8[0]); print_to_ss((int) FirmwareVersion_au8[1]); print_to_ss((int) FirmwareVersionInternal_u8); @@ -290,10 +289,6 @@ namespace nitrokey { print_to_ss( SD_Card_OEM_u16); print_to_ss( SD_WriteSpeed_u16); print_to_ss((int) SD_Card_Manufacturer_u8); - - ss << "_padding:" << std::endl - << ::nitrokey::misc::hexdump((const char *) (_padding), - sizeof _padding); return ss.str(); } -- cgit v1.2.3 From ca130e790ecc4e4502eb39e1ab550348eae9bc54 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 18:40:48 +0100 Subject: Code refactoring - named magic numbers Signed-off-by: Szczepan Zalega --- include/device_proto.h | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/include/device_proto.h b/include/device_proto.h index 037451a..6bcbcb0 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -92,22 +92,29 @@ namespace nitrokey { */ template struct DeviceResponse { + static constexpr auto storage_status_absolute_address = 21; //magic number from firmware + static constexpr auto header_size = 8; //from _zero to last_command_status inclusive + static constexpr auto footer_size = 4; //crc + static constexpr auto boiler_size = header_size + footer_size; + uint8_t _zero; uint8_t device_status; uint8_t command_id; // originally last_command_type uint32_t last_command_crc; uint8_t last_command_status; + union { - uint8_t _padding[HID_REPORT_SIZE - 12]; + uint8_t _padding[HID_REPORT_SIZE - boiler_size]; ResponsePayload payload; struct { - uint8_t _storage_status_padding[20 - 8 + 1]; //starts on 20th byte minus already 8 used + zero byte + uint8_t _storage_status_padding[storage_status_absolute_address - header_size]; uint8_t command_counter; uint8_t command_id; uint8_t device_status; //@see stick20::device_status uint8_t progress_bar_value; } __packed storage_status; } __packed; + uint32_t crc; void initialize() { bzero(this, sizeof *this); } @@ -120,9 +127,7 @@ namespace nitrokey { } void update_CRC() { crc = calculate_CRC(); } - bool isCRCcorrect() const { return crc == calculate_CRC(); } - bool isValid() const { // return !_zero && payload.isValid() && isCRCcorrect() && // command_id == (uint8_t)(cmd_id); -- cgit v1.2.3 From c346ff180244de682e78f49783eab9b296c79de6 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 19:03:30 +0100 Subject: Code refactoring - named magic numbers (2) Signed-off-by: Szczepan Zalega --- include/device_proto.h | 19 +++++++++++++------ include/stick20_commands.h | 6 +++--- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/include/device_proto.h b/include/device_proto.h index 6bcbcb0..187d25c 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -90,12 +90,19 @@ namespace nitrokey { * command_id member in incoming HIDReport structure carries the command * type last used. */ - template - struct DeviceResponse { - static constexpr auto storage_status_absolute_address = 21; //magic number from firmware + namespace DeviceResponseConstants{ + //magic numbers from firmware + static constexpr auto storage_status_absolute_address = 21; + static constexpr auto storage_data_absolute_address = storage_status_absolute_address + 5; static constexpr auto header_size = 8; //from _zero to last_command_status inclusive static constexpr auto footer_size = 4; //crc - static constexpr auto boiler_size = header_size + footer_size; + static constexpr auto wrapping_size = header_size + footer_size; + } + + template + struct DeviceResponse { + static constexpr auto storage_status_padding_size = + DeviceResponseConstants::storage_status_absolute_address - DeviceResponseConstants::header_size; uint8_t _zero; uint8_t device_status; @@ -104,10 +111,10 @@ namespace nitrokey { uint8_t last_command_status; union { - uint8_t _padding[HID_REPORT_SIZE - boiler_size]; + uint8_t _padding[HID_REPORT_SIZE - DeviceResponseConstants::wrapping_size]; ResponsePayload payload; struct { - uint8_t _storage_status_padding[storage_status_absolute_address - header_size]; + uint8_t _storage_status_padding[storage_status_padding_size]; uint8_t command_counter; uint8_t command_id; uint8_t device_status; //@see stick20::device_status diff --git a/include/stick20_commands.h b/include/stick20_commands.h index f816868..139dc63 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -91,9 +91,9 @@ namespace nitrokey { }; namespace StorageCommandResponsePayload{ - static const int OUTPUT_CMD_RESULT_STICK20_STATUS_START = 25 + 1; - static const int payload_absolute_begin = 8; - static const int padding_size = OUTPUT_CMD_RESULT_STICK20_STATUS_START - payload_absolute_begin; + using namespace DeviceResponseConstants; + static constexpr auto padding_size = + storage_data_absolute_address - header_size; struct TransmissionData{ uint8_t _padding[padding_size]; -- cgit v1.2.3 From 266b57dfe7b36799243816b7af22f3dd69b0d197 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 19:07:34 +0100 Subject: Disable locking firmware command for now Signed-off-by: Szczepan Zalega --- include/stick20_commands.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/stick20_commands.h b/include/stick20_commands.h index 139dc63..1af9da3 100644 --- a/include/stick20_commands.h +++ b/include/stick20_commands.h @@ -247,7 +247,8 @@ namespace nitrokey { }; - class LockFirmware : public PasswordCommand {}; +//disable this command for now +// class LockFirmware : public PasswordCommand {}; class ProductionTest : Command { public: -- cgit v1.2.3 From 103f71bb4e06132e70eb26fc2f1c5ca560068107 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 20:47:23 +0100 Subject: Tests reorganization (Python) Signed-off-by: Szczepan Zalega --- unittest/conftest.py | 42 +++ unittest/constants.py | 30 +++ unittest/misc.py | 40 +++ unittest/test_bindings.py | 654 ---------------------------------------------- unittest/test_library.py | 67 +++++ unittest/test_pro.py | 488 ++++++++++++++++++++++++++++++++++ unittest/test_storage.py | 7 + 7 files changed, 674 insertions(+), 654 deletions(-) create mode 100644 unittest/conftest.py create mode 100644 unittest/constants.py create mode 100644 unittest/misc.py delete mode 100644 unittest/test_bindings.py create mode 100644 unittest/test_library.py create mode 100644 unittest/test_pro.py create mode 100644 unittest/test_storage.py diff --git a/unittest/conftest.py b/unittest/conftest.py new file mode 100644 index 0000000..68227d5 --- /dev/null +++ b/unittest/conftest.py @@ -0,0 +1,42 @@ +import pytest + +from misc import ffi + +@pytest.fixture(scope="module") +def C(request): + fp = '../NK_C_API.h' + + declarations = [] + with open(fp, 'r') as f: + declarations = f.readlines() + + a = iter(declarations) + for declaration in a: + if declaration.startswith('extern') and not '"C"' in declaration: + declaration = declaration.replace('extern', '').strip() + while not ';' in declaration: + declaration += (next(a)).strip() + print(declaration) + ffi.cdef(declaration, override=True) + + C = ffi.dlopen("../build/libnitrokey.so") + C.NK_set_debug(False) + nk_login = C.NK_login_auto() + if nk_login != 1: + print('No devices detected!') + assert nk_login == 1 # returns 0 if not connected or wrong model or 1 when connected + + # assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + # assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK + + # C.NK_status() + + def fin(): + print('\nFinishing connection to device') + C.NK_logout() + print('Finished') + + request.addfinalizer(fin) + C.NK_set_debug(True) + + return C diff --git a/unittest/constants.py b/unittest/constants.py new file mode 100644 index 0000000..e3caae3 --- /dev/null +++ b/unittest/constants.py @@ -0,0 +1,30 @@ +from enum import Enum +from misc import to_hex + +RFC_SECRET_HR = '12345678901234567890' +RFC_SECRET = to_hex(RFC_SECRET_HR) # '12345678901234567890' + + +# print( repr((RFC_SECRET, RFC_SECRET_, len(RFC_SECRET))) ) + +class DefaultPasswords(Enum): + ADMIN = '12345678' + USER = '123456' + ADMIN_TEMP = '123123123' + USER_TEMP = '234234234' + + +class DeviceErrorCode(Enum): + STATUS_OK = 0 + NOT_PROGRAMMED = 3 + WRONG_PASSWORD = 4 + STATUS_NOT_AUTHORIZED = 5 + STATUS_AES_DEC_FAILED = 0xa + + +class LibraryErrors(Enum): + TOO_LONG_STRING = 200 + INVALID_SLOT = 201 + INVALID_HEX_STRING = 202 + TARGET_BUFFER_SIZE_SMALLER_THAN_SOURCE = 203 + diff --git a/unittest/misc.py b/unittest/misc.py new file mode 100644 index 0000000..b45436d --- /dev/null +++ b/unittest/misc.py @@ -0,0 +1,40 @@ +import cffi + +ffi = cffi.FFI() +gs = ffi.string + + +def to_hex(s): + return "".join("{:02x}".format(ord(c)) for c in s) + + +def wait(t): + import time + msg = 'Waiting for %d seconds' % t + print(msg.center(40, '=')) + time.sleep(t) + + +def cast_pointer_to_tuple(obj, typen, len): + # usage: + # config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) + return tuple(ffi.cast("%s [%d]" % (typen, len), obj)[0:len]) + +def get_firmware_version_from_status(C): + status = gs(C.NK_status()) + status = [s if 'firmware_version' in s else '' for s in status.split('\n')] + firmware = status[0].split(':')[1] + return firmware + + +def is_pro_rtm_07(C): + firmware = get_firmware_version_from_status(C) + return '07 00' in firmware + + +def is_storage(C): + """ + exact firmware storage is sent by other function + """ + firmware = get_firmware_version_from_status(C) + return '01 00' in firmware \ No newline at end of file diff --git a/unittest/test_bindings.py b/unittest/test_bindings.py deleted file mode 100644 index f7ade46..0000000 --- a/unittest/test_bindings.py +++ /dev/null @@ -1,654 +0,0 @@ -import pytest -import cffi -from enum import Enum - -ffi = cffi.FFI() -gs = ffi.string - - -def to_hex(s): - return "".join("{:02x}".format(ord(c)) for c in s) - - -def wait(t): - import time - msg = 'Waiting for %d seconds' % t - print(msg.center(40, '=')) - time.sleep(t) - - -RFC_SECRET_HR = '12345678901234567890' -RFC_SECRET = to_hex(RFC_SECRET_HR) # '12345678901234567890' - - -# print( repr((RFC_SECRET, RFC_SECRET_, len(RFC_SECRET))) ) - -class DefaultPasswords(Enum): - ADMIN = '12345678' - USER = '123456' - ADMIN_TEMP = '123123123' - USER_TEMP = '234234234' - - -class DeviceErrorCode(Enum): - STATUS_OK = 0 - NOT_PROGRAMMED = 3 - WRONG_PASSWORD = 4 - STATUS_NOT_AUTHORIZED = 5 - STATUS_AES_DEC_FAILED = 0xa - - -class LibraryErrors(Enum): - TOO_LONG_STRING = 200 - INVALID_SLOT = 201 - INVALID_HEX_STRING = 202 - TARGET_BUFFER_SIZE_SMALLER_THAN_SOURCE = 203 - - -@pytest.fixture(scope="module") -def C(request): - fp = '../NK_C_API.h' - - declarations = [] - with open(fp, 'r') as f: - declarations = f.readlines() - - a = iter(declarations) - for declaration in a: - if declaration.startswith('extern') and not '"C"' in declaration: - declaration = declaration.replace('extern', '').strip() - while not ';' in declaration: - declaration += (next(a)).strip() - print(declaration) - ffi.cdef(declaration) - - C = ffi.dlopen("../build/libnitrokey.so") - C.NK_set_debug(False) - nk_login = C.NK_login_auto() - if nk_login != 1: - print('No devices detected!') - assert nk_login == 1 # returns 0 if not connected or wrong model or 1 when connected - - # assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - # assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK - - # C.NK_status() - - def fin(): - print('\nFinishing connection to device') - C.NK_logout() - print('Finished') - - request.addfinalizer(fin) - C.NK_set_debug(True) - - return C - - -def get_firmware_version_from_status(C): - status = gs(C.NK_status()) - status = [s if 'firmware_version' in s else '' for s in status.split('\n')] - firmware = status[0].split(':')[1] - return firmware - - -def is_pro_rtm_07(C): - firmware = get_firmware_version_from_status(C) - return '07 00' in firmware - - -def is_storage(C): - """ - exact firmware storage is sent by other function - """ - firmware = get_firmware_version_from_status(C) - return '01 00' in firmware - - -def test_enable_password_safe(C): - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - assert C.NK_enable_password_safe('wrong_password') == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - - -def test_write_password_safe_slot(C): - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - assert C.NK_write_password_safe_slot(0, 'slotname1', 'login1', 'pass1') == DeviceErrorCode.STATUS_NOT_AUTHORIZED - 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 - - -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 - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - assert gs(C.NK_get_password_safe_slot_name(0)) == '' - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED - - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert gs(C.NK_get_password_safe_slot_name(0)) == 'slotname1' - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - - -def test_get_password_safe_slot_login_password(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 - slot_login = C.NK_get_password_safe_slot_login(0) - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - assert gs(slot_login) == 'login1' - slot_password = gs(C.NK_get_password_safe_slot_password(0)) - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - assert slot_password == 'pass1' - - -def test_erase_password_safe_slot(C): - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert C.NK_erase_password_safe_slot(0) == DeviceErrorCode.STATUS_OK - assert gs(C.NK_get_password_safe_slot_name(0)) == '' - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK # TODO CHECK shouldn't this be DeviceErrorCode.NOT_PROGRAMMED ? - - -def test_password_safe_slot_status(C): - C.NK_set_debug(True) - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert C.NK_erase_password_safe_slot(0) == DeviceErrorCode.STATUS_OK - assert C.NK_write_password_safe_slot(1, 'slotname2', 'login2', 'pass2') == DeviceErrorCode.STATUS_OK - safe_slot_status = C.NK_get_password_safe_slot_status() - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - is_slot_programmed = list(ffi.cast("uint8_t [16]", safe_slot_status)[0:16]) - print((is_slot_programmed, len(is_slot_programmed))) - assert is_slot_programmed[0] == 0 - assert is_slot_programmed[1] == 1 - - -def test_issue_device_locks_on_second_key_generation_in_sequence(C): - if is_pro_rtm_07(C): - pytest.skip("issue to register: device locks up " - "after below commands sequence (reinsertion fixes), skipping for now") - assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - - -def test_regenerate_aes_key(C): - C.NK_set_debug(True) - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - - -@pytest.mark.xfail(reason="NK Pro firmware bug: regenerating AES key command not always results in cleared slot data") -def test_destroy_password_safe(C): - """ - Sometimes fails on NK Pro - slot name is not cleared ergo key generation has not succeed despite the success result - returned from the device - """ - C.NK_set_debug(True) - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - # write password safe slot - assert C.NK_write_password_safe_slot(0, 'slotname1', 'login1', 'pass1') == DeviceErrorCode.STATUS_OK - # read slot - assert gs(C.NK_get_password_safe_slot_name(0)) == 'slotname1' - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - slot_login = C.NK_get_password_safe_slot_login(0) - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - assert gs(slot_login) == 'login1' - # destroy password safe by regenerating aes key - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - - assert gs(C.NK_get_password_safe_slot_name(0)) != 'slotname1' - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - - # check was slot status cleared - safe_slot_status = C.NK_get_password_safe_slot_status() - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - is_slot_programmed = list(ffi.cast("uint8_t [16]", safe_slot_status)[0:16]) - assert is_slot_programmed[0] == 0 - - -def test_is_AES_supported(C): - if is_storage(C): - pytest.skip("Storage does not implement this command") - assert C.NK_is_AES_supported('wrong password') != 1 - assert C.NK_get_last_command_status() == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_is_AES_supported(DefaultPasswords.USER) == 1 - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - - -def test_admin_PIN_change(C): - new_password = '123123123' - assert C.NK_change_admin_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_change_admin_PIN(DefaultPasswords.ADMIN, new_password) == DeviceErrorCode.STATUS_OK - assert C.NK_change_admin_PIN(new_password, DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - - -def test_user_PIN_change(C): - new_password = '123123123' - assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_change_user_PIN(DefaultPasswords.USER, new_password) == DeviceErrorCode.STATUS_OK - assert C.NK_change_user_PIN(new_password, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - - -def test_too_long_strings(C): - new_password = '123123123' - long_string = 'a' * 100 - assert C.NK_change_user_PIN(long_string, new_password) == LibraryErrors.TOO_LONG_STRING - assert C.NK_change_user_PIN(new_password, long_string) == LibraryErrors.TOO_LONG_STRING - assert C.NK_change_admin_PIN(long_string, new_password) == LibraryErrors.TOO_LONG_STRING - assert C.NK_change_admin_PIN(new_password, long_string) == LibraryErrors.TOO_LONG_STRING - assert C.NK_first_authenticate(long_string, DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TOO_LONG_STRING - assert C.NK_erase_totp_slot(0, long_string) == LibraryErrors.TOO_LONG_STRING - digits = False - assert C.NK_write_hotp_slot(1, long_string, RFC_SECRET, 0, digits, False, False, "", - DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TOO_LONG_STRING - assert C.NK_write_hotp_slot(1, 'long_test', RFC_SECRET, 0, digits, False, False, "", - long_string) == LibraryErrors.TOO_LONG_STRING - assert C.NK_get_hotp_code_PIN(0, long_string) == 0 - assert C.NK_get_last_command_status() == LibraryErrors.TOO_LONG_STRING - - -def test_invalid_slot(C): - invalid_slot = 255 - assert C.NK_erase_totp_slot(invalid_slot, 'some password') == LibraryErrors.INVALID_SLOT - assert C.NK_write_hotp_slot(invalid_slot, 'long_test', RFC_SECRET, 0, False, False, False, "", - 'aaa') == LibraryErrors.INVALID_SLOT - assert C.NK_get_hotp_code_PIN(invalid_slot, 'some password') == 0 - assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT - assert C.NK_erase_password_safe_slot(invalid_slot) == LibraryErrors.INVALID_SLOT - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert gs(C.NK_get_password_safe_slot_name(invalid_slot)) == '' - assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT - assert gs(C.NK_get_password_safe_slot_login(invalid_slot)) == '' - assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT - - -def test_admin_retry_counts(C): - default_admin_retry_count = 3 - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - assert C.NK_get_admin_retry_count() == default_admin_retry_count - assert C.NK_change_admin_PIN('wrong_password', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_get_admin_retry_count() == default_admin_retry_count - 1 - assert C.NK_change_admin_PIN(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - assert C.NK_get_admin_retry_count() == default_admin_retry_count - - -def test_user_retry_counts_change_PIN(C): - assert C.NK_change_user_PIN(DefaultPasswords.USER, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - wrong_password = 'wrong_password' - default_user_retry_count = 3 - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - assert C.NK_get_user_retry_count() == default_user_retry_count - assert C.NK_change_user_PIN(wrong_password, wrong_password) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_get_user_retry_count() == default_user_retry_count - 1 - assert C.NK_change_user_PIN(DefaultPasswords.USER, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert C.NK_get_user_retry_count() == default_user_retry_count - -def test_user_retry_counts_PWSafe(C): - default_user_retry_count = 3 - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - assert C.NK_get_user_retry_count() == default_user_retry_count - assert C.NK_enable_password_safe('wrong_password') == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_get_user_retry_count() == default_user_retry_count - 1 - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert C.NK_get_user_retry_count() == default_user_retry_count - - -def test_unlock_user_password(C): - C.NK_set_debug(True) - default_user_retry_count = 3 - default_admin_retry_count = 3 - new_password = '123123123' - assert C.NK_get_user_retry_count() == default_user_retry_count - assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_get_user_retry_count() == default_user_retry_count - 3 - assert C.NK_get_admin_retry_count() == default_admin_retry_count - - assert C.NK_unlock_user_password('wrong password', DefaultPasswords.USER) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_get_admin_retry_count() == default_admin_retry_count - 1 - assert C.NK_unlock_user_password(DefaultPasswords.ADMIN, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert C.NK_get_user_retry_count() == default_user_retry_count - assert C.NK_get_admin_retry_count() == default_admin_retry_count - - -def test_admin_auth(C): - assert C.NK_first_authenticate('wrong_password', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - - -def test_user_auth(C): - assert C.NK_user_authenticate('wrong_password', DefaultPasswords.USER_TEMP) == DeviceErrorCode.WRONG_PASSWORD - assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK - - -def check_HOTP_RFC_codes(C, func, prep=None, use_8_digits=False): - """ - # https://tools.ietf.org/html/rfc4226#page-32 - """ - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_hotp_slot(1, 'python_test', RFC_SECRET, 0, use_8_digits, False, False, "", - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - test_data = [ - 1284755224, 1094287082, 137359152, 1726969429, 1640338314, 868254676, 1918287922, 82162583, 673399871, - 645520489, - ] - for code in test_data: - if prep: - prep() - r = func(1) - code = str(code)[-8:] if use_8_digits else str(code)[-6:] - assert int(code) == r - - -@pytest.mark.parametrize("use_8_digits", [False, True, ]) -@pytest.mark.parametrize("use_pin_protection", [False, True, ]) -def test_HOTP_RFC_use8digits_usepin(C, use_8_digits, use_pin_protection): - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - if use_pin_protection: - check_HOTP_RFC_codes(C, - lambda x: C.NK_get_hotp_code_PIN(x, DefaultPasswords.USER_TEMP), - lambda: C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP), - use_8_digits=use_8_digits) - else: - check_HOTP_RFC_codes(C, C.NK_get_hotp_code, use_8_digits=use_8_digits) - - -def test_HOTP_token(C): - """ - Check HOTP routine with written token ID to slot. - """ - use_pin_protection = False - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - token_ID = "AAV100000022" - assert C.NK_write_hotp_slot(1, 'python_test', RFC_SECRET, 0, False, False, True, token_ID, - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - for i in range(5): - hotp_code = C.NK_get_hotp_code(1) - assert hotp_code != 0 - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - -def test_HOTP_counters(C): - """ - # https://tools.ietf.org/html/rfc4226#page-32 - """ - use_pin_protection = False - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - use_8_digits = True - HOTP_test_data = [ - 1284755224, 1094287082, 137359152, 1726969429, 1640338314, - 868254676, 1918287922, 82162583, 673399871, 645520489, - ] - slot_number = 1 - for counter, code in enumerate(HOTP_test_data): - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_hotp_slot(slot_number, 'python_test', RFC_SECRET, counter, use_8_digits, False, False, "", - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - r = C.NK_get_hotp_code(slot_number) - code = str(code)[-8:] if use_8_digits else str(code)[-6:] - assert int(code) == r - - -INT32_MAX = 2 ** 31 - 1 -def test_HOTP_64bit_counter(C): - if is_storage(C): - pytest.xfail('bug in NK Storage HOTP firmware - counter is set with a 8 digits string, ' - 'however int32max takes 10 digits to be written') - oath = pytest.importorskip("oath") - lib_at = lambda t: oath.hotp(RFC_SECRET, t, format='dec6') - PIN_protection = False - use_8_digits = False - slot_number = 1 - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - dev_res = [] - lib_res = [] - for t in range(INT32_MAX - 5, INT32_MAX + 5, 1): - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_hotp_slot(slot_number, 'python_test', RFC_SECRET, t, use_8_digits, False, False, "", - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - code_device = str(C.NK_get_hotp_code(slot_number)) - dev_res += (t, code_device) - lib_res += (t, lib_at(t)) - assert dev_res == lib_res - - -def test_TOTP_64bit_time(C): - if is_storage(C): - pytest.xfail('bug in NK Storage TOTP firmware') - oath = pytest.importorskip("oath") - T = 1 - lib_at = lambda t: oath.totp(RFC_SECRET, t=t) - PIN_protection = False - slot_number = 1 - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_totp_slot(slot_number, 'python_test', RFC_SECRET, 30, False, False, False, "", - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - dev_res = [] - lib_res = [] - for t in range(INT32_MAX - 5, INT32_MAX + 5, 1): - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_totp_set_time(t) == DeviceErrorCode.STATUS_OK - code_device = str((C.NK_get_totp_code(slot_number, T, 0, 30))) - dev_res += (t, code_device) - lib_res += (t, lib_at(t)) - assert dev_res == lib_res - - -@pytest.mark.xfail(reason="NK Pro: possible firmware bug or communication issue: set time command not always changes the time on stick thus failing this test, " - "this does not influence normal use since setting time is not done every TOTP code request" - "Rarely fail occurs on NK Storage") -@pytest.mark.parametrize("PIN_protection", [False, True, ]) -def test_TOTP_RFC_usepin(C, PIN_protection): - slot_number = 1 - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - # test according to https://tools.ietf.org/html/rfc6238#appendix-B - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_totp_slot(slot_number, 'python_test', RFC_SECRET, 30, True, False, False, "", - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - - get_func = None - if PIN_protection: - get_func = lambda x, y, z, r: C.NK_get_totp_code_PIN(x, y, z, r, DefaultPasswords.USER_TEMP) - else: - get_func = C.NK_get_totp_code - - # Mode: Sha1, time step X=30 - test_data = [ - #Time T (hex) TOTP - (59, 0x1, 94287082), - (1111111109, 0x00000000023523EC, 7081804), - (1111111111, 0x00000000023523ED, 14050471), - (1234567890, 0x000000000273EF07, 89005924), - (2000000000, 0x0000000003F940AA, 69279037), - # (20000000000, 0x0000000027BC86AA, 65353130), # 64bit is also checked in other test - ] - responses = [] - data = [] - correct = 0 - for t, T, expected_code in test_data: - if PIN_protection: - C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_totp_set_time(t) == DeviceErrorCode.STATUS_OK - code_from_device = get_func(slot_number, T, 0, 30) # FIXME T is not changing the outcome - data += [ (t, expected_code) ] - responses += [ (t, code_from_device) ] - correct += expected_code == code_from_device - assert data == responses or correct == len(test_data) - -def test_get_slot_names(C): - C.NK_set_debug(True) - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_erase_totp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - # erasing slot invalidates temporary password, so requesting authentication - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_erase_hotp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - - for i in range(15): - name = ffi.string(C.NK_get_totp_slot_name(i)) - if name == '': - assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED - for i in range(3): - name = ffi.string(C.NK_get_hotp_slot_name(i)) - if name == '': - assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED - - -def test_get_OTP_codes(C): - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - for i in range(15): - code = C.NK_get_totp_code(i, 0, 0, 0) - if code == 0: - assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED - - for i in range(3): - code = C.NK_get_hotp_code(i) - if code == 0: - assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED - - -def test_get_OTP_code_from_not_programmed_slot(C): - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_erase_hotp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_erase_totp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - - code = C.NK_get_hotp_code(0) - assert code == 0 - assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED - - code = C.NK_get_totp_code(0, 0, 0, 0) - assert code == 0 - assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED - - -def test_get_code_user_authorize(C): - C.NK_set_debug(True) - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_totp_slot(0, 'python_otp_auth', RFC_SECRET, 30, True, False, False, "", - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - # enable PIN protection of OTP codes with write_config - # TODO create convinience function on C API side to enable/disable OTP USER_PIN protection - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - code = C.NK_get_totp_code(0, 0, 0, 0) - assert code == 0 - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED - # disable PIN protection with write_config - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - code = C.NK_get_totp_code(0, 0, 0, 0) - assert code != 0 - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - - -def cast_pointer_to_tuple(obj, typen, len): - # usage: - # config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) - return tuple(ffi.cast("%s [%d]" % (typen, len), obj)[0:len]) - - -def test_read_write_config(C): - C.NK_set_debug(True) - - # let's set sample config with pin protection and disabled scrolllock - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(0, 1, 2, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - config_raw_data = C.NK_read_config() - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) - assert config == (0, 1, 2, True, False) - - # restore defaults and check - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - config_raw_data = C.NK_read_config() - assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK - config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) - assert config == (255, 255, 255, False, True) - - -def test_factory_reset(C): - if is_storage(C): - pytest.skip('Recovery not implemented for NK Storage') - C.NK_set_debug(True) - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_write_hotp_slot(1, 'python_test', RFC_SECRET, 0, False, False, False, "", - DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_get_hotp_code(1) == 755224 - assert C.NK_factory_reset(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - wait(10) - assert C.NK_get_hotp_code(1) != 287082 - assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED - # restore AES key - assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK - assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK - assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK - assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK - - -@pytest.mark.skip(reason='Experimental') -def test_clear(C): - d = 'asdasdasd' - print(d) - C.clear_password(d) - print(d) - - -def test_get_status(C): - status = C.NK_status() - s = gs(status) - assert len(s) > 0 - - -def test_get_serial_number(C): - sn = C.NK_device_serial_number() - sn = gs(sn) - assert len(sn) > 0 - print(('Serial number of the device: ', sn)) - - -@pytest.mark.parametrize("invalid_hex_string", - ['text', '00 ', '0xff', 'zzzzzzzzzzzz', 'fff', '', 'f' * 257, 'f' * 258]) -def test_invalid_secret_hex_string_for_OTP_write(C, invalid_hex_string): - """ - Tests for invalid secret hex string during writing to OTP slot. Invalid strings are not hexadecimal number, - empty or longer than 255 characters. - """ - assert C.NK_write_hotp_slot(1, 'slot_name', invalid_hex_string, 0, True, False, False, '', - DefaultPasswords.ADMIN_TEMP) == LibraryErrors.INVALID_HEX_STRING - assert C.NK_write_totp_slot(1, 'python_test', invalid_hex_string, 30, True, False, False, "", - DefaultPasswords.ADMIN_TEMP) == LibraryErrors.INVALID_HEX_STRING - - -def test_warning_binary_bigger_than_secret_buffer(C): - invalid_hex_string = to_hex('1234567890') * 3 - assert C.NK_write_hotp_slot(1, 'slot_name', invalid_hex_string, 0, True, False, False, '', - DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TARGET_BUFFER_SIZE_SMALLER_THAN_SOURCE - - -@pytest.mark.xfail(reason="TODO") -def test_OTP_secret_started_from_null(C): - assert False diff --git a/unittest/test_library.py b/unittest/test_library.py new file mode 100644 index 0000000..d0eef80 --- /dev/null +++ b/unittest/test_library.py @@ -0,0 +1,67 @@ +import pytest + +from misc import ffi, gs, to_hex +from constants import DefaultPasswords, DeviceErrorCode, RFC_SECRET, LibraryErrors + +def test_too_long_strings(C): + new_password = '123123123' + long_string = 'a' * 100 + assert C.NK_change_user_PIN(long_string, new_password) == LibraryErrors.TOO_LONG_STRING + assert C.NK_change_user_PIN(new_password, long_string) == LibraryErrors.TOO_LONG_STRING + assert C.NK_change_admin_PIN(long_string, new_password) == LibraryErrors.TOO_LONG_STRING + assert C.NK_change_admin_PIN(new_password, long_string) == LibraryErrors.TOO_LONG_STRING + assert C.NK_first_authenticate(long_string, DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TOO_LONG_STRING + assert C.NK_erase_totp_slot(0, long_string) == LibraryErrors.TOO_LONG_STRING + digits = False + assert C.NK_write_hotp_slot(1, long_string, RFC_SECRET, 0, digits, False, False, "", + DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TOO_LONG_STRING + assert C.NK_write_hotp_slot(1, 'long_test', RFC_SECRET, 0, digits, False, False, "", + long_string) == LibraryErrors.TOO_LONG_STRING + assert C.NK_get_hotp_code_PIN(0, long_string) == 0 + assert C.NK_get_last_command_status() == LibraryErrors.TOO_LONG_STRING + + +def test_invalid_slot(C): + invalid_slot = 255 + assert C.NK_erase_totp_slot(invalid_slot, 'some password') == LibraryErrors.INVALID_SLOT + assert C.NK_write_hotp_slot(invalid_slot, 'long_test', RFC_SECRET, 0, False, False, False, "", + 'aaa') == LibraryErrors.INVALID_SLOT + assert C.NK_get_hotp_code_PIN(invalid_slot, 'some password') == 0 + assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT + assert C.NK_erase_password_safe_slot(invalid_slot) == LibraryErrors.INVALID_SLOT + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert gs(C.NK_get_password_safe_slot_name(invalid_slot)) == '' + assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT + assert gs(C.NK_get_password_safe_slot_login(invalid_slot)) == '' + assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT + +@pytest.mark.parametrize("invalid_hex_string", + ['text', '00 ', '0xff', 'zzzzzzzzzzzz', 'fff', '', 'f' * 257, 'f' * 258]) +def test_invalid_secret_hex_string_for_OTP_write(C, invalid_hex_string): + """ + Tests for invalid secret hex string during writing to OTP slot. Invalid strings are not hexadecimal number, + empty or longer than 255 characters. + """ + assert C.NK_write_hotp_slot(1, 'slot_name', invalid_hex_string, 0, True, False, False, '', + DefaultPasswords.ADMIN_TEMP) == LibraryErrors.INVALID_HEX_STRING + assert C.NK_write_totp_slot(1, 'python_test', invalid_hex_string, 30, True, False, False, "", + DefaultPasswords.ADMIN_TEMP) == LibraryErrors.INVALID_HEX_STRING + + +def test_warning_binary_bigger_than_secret_buffer(C): + invalid_hex_string = to_hex('1234567890') * 3 + assert C.NK_write_hotp_slot(1, 'slot_name', invalid_hex_string, 0, True, False, False, '', + DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TARGET_BUFFER_SIZE_SMALLER_THAN_SOURCE + + +@pytest.mark.xfail(reason="TODO") +def test_OTP_secret_started_from_null(C): + assert False + + +@pytest.mark.skip(reason='Experimental') +def test_clear(C): + d = 'asdasdasd' + print(d) + C.clear_password(d) + print(d) \ No newline at end of file diff --git a/unittest/test_pro.py b/unittest/test_pro.py new file mode 100644 index 0000000..6ab2af9 --- /dev/null +++ b/unittest/test_pro.py @@ -0,0 +1,488 @@ +import pytest + +from constants import DefaultPasswords, DeviceErrorCode, RFC_SECRET +from misc import ffi, gs, wait, cast_pointer_to_tuple +from misc import is_pro_rtm_07, is_storage + +def test_enable_password_safe(C): + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_enable_password_safe('wrong_password') == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + +def test_write_password_safe_slot(C): + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_write_password_safe_slot(0, 'slotname1', 'login1', 'pass1') == DeviceErrorCode.STATUS_NOT_AUTHORIZED + 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 + + +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 + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert gs(C.NK_get_password_safe_slot_name(0)) == '' + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED + + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert gs(C.NK_get_password_safe_slot_name(0)) == 'slotname1' + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + + +def test_get_password_safe_slot_login_password(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 + slot_login = C.NK_get_password_safe_slot_login(0) + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + assert gs(slot_login) == 'login1' + slot_password = gs(C.NK_get_password_safe_slot_password(0)) + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + assert slot_password == 'pass1' + + +def test_erase_password_safe_slot(C): + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_erase_password_safe_slot(0) == DeviceErrorCode.STATUS_OK + assert gs(C.NK_get_password_safe_slot_name(0)) == '' + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK # TODO CHECK shouldn't this be DeviceErrorCode.NOT_PROGRAMMED ? + + +def test_password_safe_slot_status(C): + C.NK_set_debug(True) + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_erase_password_safe_slot(0) == DeviceErrorCode.STATUS_OK + assert C.NK_write_password_safe_slot(1, 'slotname2', 'login2', 'pass2') == DeviceErrorCode.STATUS_OK + safe_slot_status = C.NK_get_password_safe_slot_status() + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + is_slot_programmed = list(ffi.cast("uint8_t [16]", safe_slot_status)[0:16]) + print((is_slot_programmed, len(is_slot_programmed))) + assert is_slot_programmed[0] == 0 + assert is_slot_programmed[1] == 1 + + +def test_issue_device_locks_on_second_key_generation_in_sequence(C): + if is_pro_rtm_07(C): + pytest.skip("issue to register: device locks up " + "after below commands sequence (reinsertion fixes), skipping for now") + assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + + +def test_regenerate_aes_key(C): + C.NK_set_debug(True) + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + +@pytest.mark.xfail(reason="NK Pro firmware bug: regenerating AES key command not always results in cleared slot data") +def test_destroy_password_safe(C): + """ + Sometimes fails on NK Pro - slot name is not cleared ergo key generation has not succeed despite the success result + returned from the device + """ + C.NK_set_debug(True) + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + # write password safe slot + assert C.NK_write_password_safe_slot(0, 'slotname1', 'login1', 'pass1') == DeviceErrorCode.STATUS_OK + # read slot + assert gs(C.NK_get_password_safe_slot_name(0)) == 'slotname1' + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + slot_login = C.NK_get_password_safe_slot_login(0) + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + assert gs(slot_login) == 'login1' + # destroy password safe by regenerating aes key + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + assert gs(C.NK_get_password_safe_slot_name(0)) != 'slotname1' + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + + # check was slot status cleared + safe_slot_status = C.NK_get_password_safe_slot_status() + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + is_slot_programmed = list(ffi.cast("uint8_t [16]", safe_slot_status)[0:16]) + assert is_slot_programmed[0] == 0 + + +def test_is_AES_supported(C): + if is_storage(C): + pytest.skip("Storage does not implement this command") + assert C.NK_is_AES_supported('wrong password') != 1 + assert C.NK_get_last_command_status() == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_is_AES_supported(DefaultPasswords.USER) == 1 + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + + +def test_admin_PIN_change(C): + new_password = '123123123' + assert C.NK_change_admin_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_change_admin_PIN(DefaultPasswords.ADMIN, new_password) == DeviceErrorCode.STATUS_OK + assert C.NK_change_admin_PIN(new_password, DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + + +def test_user_PIN_change(C): + new_password = '123123123' + assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_change_user_PIN(DefaultPasswords.USER, new_password) == DeviceErrorCode.STATUS_OK + assert C.NK_change_user_PIN(new_password, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + +def test_admin_retry_counts(C): + default_admin_retry_count = 3 + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_get_admin_retry_count() == default_admin_retry_count + assert C.NK_change_admin_PIN('wrong_password', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_get_admin_retry_count() == default_admin_retry_count - 1 + assert C.NK_change_admin_PIN(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + assert C.NK_get_admin_retry_count() == default_admin_retry_count + + +def test_user_retry_counts_change_PIN(C): + assert C.NK_change_user_PIN(DefaultPasswords.USER, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + wrong_password = 'wrong_password' + default_user_retry_count = 3 + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_get_user_retry_count() == default_user_retry_count + assert C.NK_change_user_PIN(wrong_password, wrong_password) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_get_user_retry_count() == default_user_retry_count - 1 + assert C.NK_change_user_PIN(DefaultPasswords.USER, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_get_user_retry_count() == default_user_retry_count + +def test_user_retry_counts_PWSafe(C): + default_user_retry_count = 3 + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_get_user_retry_count() == default_user_retry_count + assert C.NK_enable_password_safe('wrong_password') == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_get_user_retry_count() == default_user_retry_count - 1 + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_get_user_retry_count() == default_user_retry_count + + +def test_unlock_user_password(C): + C.NK_set_debug(True) + default_user_retry_count = 3 + default_admin_retry_count = 3 + new_password = '123123123' + assert C.NK_get_user_retry_count() == default_user_retry_count + assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_change_user_PIN('wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_get_user_retry_count() == default_user_retry_count - 3 + assert C.NK_get_admin_retry_count() == default_admin_retry_count + + assert C.NK_unlock_user_password('wrong password', DefaultPasswords.USER) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_get_admin_retry_count() == default_admin_retry_count - 1 + assert C.NK_unlock_user_password(DefaultPasswords.ADMIN, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_get_user_retry_count() == default_user_retry_count + assert C.NK_get_admin_retry_count() == default_admin_retry_count + + +def test_admin_auth(C): + assert C.NK_first_authenticate('wrong_password', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + + +def test_user_auth(C): + assert C.NK_user_authenticate('wrong_password', DefaultPasswords.USER_TEMP) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK + + +def check_HOTP_RFC_codes(C, func, prep=None, use_8_digits=False): + """ + # https://tools.ietf.org/html/rfc4226#page-32 + """ + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_hotp_slot(1, 'python_test', RFC_SECRET, 0, use_8_digits, False, False, "", + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + test_data = [ + 1284755224, 1094287082, 137359152, 1726969429, 1640338314, 868254676, 1918287922, 82162583, 673399871, + 645520489, + ] + for code in test_data: + if prep: + prep() + r = func(1) + code = str(code)[-8:] if use_8_digits else str(code)[-6:] + assert int(code) == r + + +@pytest.mark.parametrize("use_8_digits", [False, True, ]) +@pytest.mark.parametrize("use_pin_protection", [False, True, ]) +def test_HOTP_RFC_use8digits_usepin(C, use_8_digits, use_pin_protection): + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + if use_pin_protection: + check_HOTP_RFC_codes(C, + lambda x: C.NK_get_hotp_code_PIN(x, DefaultPasswords.USER_TEMP), + lambda: C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP), + use_8_digits=use_8_digits) + else: + check_HOTP_RFC_codes(C, C.NK_get_hotp_code, use_8_digits=use_8_digits) + + +def test_HOTP_token(C): + """ + Check HOTP routine with written token ID to slot. + """ + use_pin_protection = False + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + token_ID = "AAV100000022" + assert C.NK_write_hotp_slot(1, 'python_test', RFC_SECRET, 0, False, False, True, token_ID, + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + for i in range(5): + hotp_code = C.NK_get_hotp_code(1) + assert hotp_code != 0 + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + +def test_HOTP_counters(C): + """ + # https://tools.ietf.org/html/rfc4226#page-32 + """ + use_pin_protection = False + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + use_8_digits = True + HOTP_test_data = [ + 1284755224, 1094287082, 137359152, 1726969429, 1640338314, + 868254676, 1918287922, 82162583, 673399871, 645520489, + ] + slot_number = 1 + for counter, code in enumerate(HOTP_test_data): + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_hotp_slot(slot_number, 'python_test', RFC_SECRET, counter, use_8_digits, False, False, "", + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + r = C.NK_get_hotp_code(slot_number) + code = str(code)[-8:] if use_8_digits else str(code)[-6:] + assert int(code) == r + + +INT32_MAX = 2 ** 31 - 1 +def test_HOTP_64bit_counter(C): + if is_storage(C): + pytest.xfail('bug in NK Storage HOTP firmware - counter is set with a 8 digits string, ' + 'however int32max takes 10 digits to be written') + oath = pytest.importorskip("oath") + lib_at = lambda t: oath.hotp(RFC_SECRET, t, format='dec6') + PIN_protection = False + use_8_digits = False + slot_number = 1 + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + dev_res = [] + lib_res = [] + for t in range(INT32_MAX - 5, INT32_MAX + 5, 1): + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_hotp_slot(slot_number, 'python_test', RFC_SECRET, t, use_8_digits, False, False, "", + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + code_device = str(C.NK_get_hotp_code(slot_number)) + dev_res += (t, code_device) + lib_res += (t, lib_at(t)) + assert dev_res == lib_res + + +def test_TOTP_64bit_time(C): + if is_storage(C): + pytest.xfail('bug in NK Storage TOTP firmware') + oath = pytest.importorskip("oath") + T = 1 + lib_at = lambda t: oath.totp(RFC_SECRET, t=t) + PIN_protection = False + slot_number = 1 + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_totp_slot(slot_number, 'python_test', RFC_SECRET, 30, False, False, False, "", + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + dev_res = [] + lib_res = [] + for t in range(INT32_MAX - 5, INT32_MAX + 5, 1): + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_totp_set_time(t) == DeviceErrorCode.STATUS_OK + code_device = str((C.NK_get_totp_code(slot_number, T, 0, 30))) + dev_res += (t, code_device) + lib_res += (t, lib_at(t)) + assert dev_res == lib_res + + +@pytest.mark.xfail(reason="NK Pro: possible firmware bug or communication issue: set time command not always changes the time on stick thus failing this test, " + "this does not influence normal use since setting time is not done every TOTP code request" + "Rarely fail occurs on NK Storage") +@pytest.mark.parametrize("PIN_protection", [False, True, ]) +def test_TOTP_RFC_usepin(C, PIN_protection): + slot_number = 1 + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + # test according to https://tools.ietf.org/html/rfc6238#appendix-B + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_totp_slot(slot_number, 'python_test', RFC_SECRET, 30, True, False, False, "", + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + + get_func = None + if PIN_protection: + get_func = lambda x, y, z, r: C.NK_get_totp_code_PIN(x, y, z, r, DefaultPasswords.USER_TEMP) + else: + get_func = C.NK_get_totp_code + + # Mode: Sha1, time step X=30 + test_data = [ + #Time T (hex) TOTP + (59, 0x1, 94287082), + (1111111109, 0x00000000023523EC, 7081804), + (1111111111, 0x00000000023523ED, 14050471), + (1234567890, 0x000000000273EF07, 89005924), + (2000000000, 0x0000000003F940AA, 69279037), + # (20000000000, 0x0000000027BC86AA, 65353130), # 64bit is also checked in other test + ] + responses = [] + data = [] + correct = 0 + for t, T, expected_code in test_data: + if PIN_protection: + C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_totp_set_time(t) == DeviceErrorCode.STATUS_OK + code_from_device = get_func(slot_number, T, 0, 30) # FIXME T is not changing the outcome + data += [ (t, expected_code) ] + responses += [ (t, code_from_device) ] + correct += expected_code == code_from_device + assert data == responses or correct == len(test_data) + +def test_get_slot_names(C): + C.NK_set_debug(True) + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_erase_totp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + # erasing slot invalidates temporary password, so requesting authentication + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_erase_hotp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + + for i in range(15): + name = ffi.string(C.NK_get_totp_slot_name(i)) + if name == '': + assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED + for i in range(3): + name = ffi.string(C.NK_get_hotp_slot_name(i)) + if name == '': + assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED + + +def test_get_OTP_codes(C): + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + for i in range(15): + code = C.NK_get_totp_code(i, 0, 0, 0) + if code == 0: + assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED + + for i in range(3): + code = C.NK_get_hotp_code(i) + if code == 0: + assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED + + +def test_get_OTP_code_from_not_programmed_slot(C): + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_erase_hotp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_erase_totp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + + code = C.NK_get_hotp_code(0) + assert code == 0 + assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED + + code = C.NK_get_totp_code(0, 0, 0, 0) + assert code == 0 + assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED + + +def test_get_code_user_authorize(C): + C.NK_set_debug(True) + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_totp_slot(0, 'python_otp_auth', RFC_SECRET, 30, True, False, False, "", + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + # enable PIN protection of OTP codes with write_config + # TODO create convinience function on C API side to enable/disable OTP USER_PIN protection + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + code = C.NK_get_totp_code(0, 0, 0, 0) + assert code == 0 + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED + # disable PIN protection with write_config + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + code = C.NK_get_totp_code(0, 0, 0, 0) + assert code != 0 + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + + +def cast_pointer_to_tuple(obj, typen, len): + # usage: + # config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) + return tuple(ffi.cast("%s [%d]" % (typen, len), obj)[0:len]) + + +def test_read_write_config(C): + C.NK_set_debug(True) + + # let's set sample config with pin protection and disabled scrolllock + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(0, 1, 2, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + config_raw_data = C.NK_read_config() + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) + assert config == (0, 1, 2, True, False) + + # restore defaults and check + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + config_raw_data = C.NK_read_config() + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) + assert config == (255, 255, 255, False, True) + + +def test_factory_reset(C): + if is_storage(C): + pytest.skip('Recovery not implemented for NK Storage') + C.NK_set_debug(True) + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_write_hotp_slot(1, 'python_test', RFC_SECRET, 0, False, False, False, "", + DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_get_hotp_code(1) == 755224 + assert C.NK_factory_reset(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + wait(10) + assert C.NK_get_hotp_code(1) != 287082 + assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED + # restore AES key + assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + + +def test_get_status(C): + status = C.NK_status() + s = gs(status) + assert len(s) > 0 + + +def test_get_serial_number(C): + sn = C.NK_device_serial_number() + sn = gs(sn) + assert len(sn) > 0 + print(('Serial number of the device: ', sn)) diff --git a/unittest/test_storage.py b/unittest/test_storage.py new file mode 100644 index 0000000..d6cc558 --- /dev/null +++ b/unittest/test_storage.py @@ -0,0 +1,7 @@ +import pytest + +from misc import ffi, gs, wait, cast_pointer_to_tuple +from constants import DefaultPasswords, DeviceErrorCode, RFC_SECRET, LibraryErrors + + + -- cgit v1.2.3 From d03e9fda2fc5c9d5f97e396c65190ab750863e36 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Mon, 31 Oct 2016 20:50:48 +0100 Subject: .gitignore update Signed-off-by: Szczepan Zalega --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index 1a8accf..47b7703 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,9 @@ *.sw* *.log *.o +unittest/build/ +*.pyc +core +.cache/ +.idea/ +CMakeFiles/ -- cgit v1.2.3 From 3a81030c744fae5d31f21d728a6b2f616637e550 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 2 Nov 2016 21:50:28 +0100 Subject: Set default debug level to DEBUG Signed-off-by: Szczepan Zalega --- NitrokeyManager.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index f0099da..606c4fb 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -16,7 +16,7 @@ namespace nitrokey{ nitrokey::log::Log::instance()(std::string("strcpyT sizes dest src ") +std::to_string(s_dest)+ " " +std::to_string(strlen(src))+ " " - ,nitrokey::log::Loglevel::DEBUG); + ,nitrokey::log::Loglevel::DEBUG_L2); if (strlen(src) > s_dest){ throw TooLongStringException(strlen(src), s_dest, src); } @@ -94,7 +94,7 @@ namespace nitrokey{ void NitrokeyManager::set_debug(bool state) { if (state){ - Log::instance().set_loglevel(Loglevel::DEBUG_L2); + Log::instance().set_loglevel(Loglevel::DEBUG); } else { Log::instance().set_loglevel(Loglevel::ERROR); } -- cgit v1.2.3 From e4cb016284e27c92090868119277091d122114f5 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 2 Nov 2016 21:51:21 +0100 Subject: Helper for running simple, password only commands for Storage Signed-off-by: Szczepan Zalega --- include/misc.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/include/misc.h b/include/misc.h index 48d6a83..5158de0 100644 --- a/include/misc.h +++ b/include/misc.h @@ -36,6 +36,13 @@ typename T::CommandPayload get_payload(){ return st; } + template + void execute_password_command(Tdev &stick, const char *password) { + auto p = get_payload(); + p.set_defaults(); + strcpyT(p.password, password); + CMDTYPE::CommandTransaction::run(stick, p); + } std::string hexdump(const char *p, size_t size, bool print_header=true); uint32_t stm_crc32(const uint8_t *data, size_t size); -- cgit v1.2.3 From 0a15620115f4f6d56ec99777e1996497d7175bc2 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 2 Nov 2016 21:52:09 +0100 Subject: Decrease debug log output in c++ tests Signed-off-by: Szczepan Zalega --- unittest/test2.cc | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/unittest/test2.cc b/unittest/test2.cc index e4edf87..00e70e3 100644 --- a/unittest/test2.cc +++ b/unittest/test2.cc @@ -50,7 +50,7 @@ TEST_CASE("long operation test", "[test_long]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); - Log::instance().set_loglevel(Loglevel::DEBUG_L2); + Log::instance().set_loglevel(Loglevel::DEBUG); try{ auto p = get_payload(); p.set_defaults(); @@ -127,8 +127,8 @@ TEST_CASE("test device internal status with various commands", "[fast]") { bool connected = stick.connect(); REQUIRE(connected == true); - Log::instance().set_loglevel(Loglevel::DEBUG_L2); - auto p = get_payload(); + Log::instance().set_loglevel(Loglevel::DEBUG); + auto p = get_payload(); p.set_defaults(); auto device_status = stick20::SendStartup::CommandTransaction::run(stick, p); REQUIRE(device_status.data().AdminPwRetryCount == 3); @@ -150,7 +150,7 @@ TEST_CASE("setup hidden volume test", "[hidden]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); - Log::instance().set_loglevel(Loglevel::DEBUG_L2); + Log::instance().set_loglevel(Loglevel::DEBUG); stick10::LockDevice::CommandTransaction::run(stick); this_thread::sleep_for(2000ms); @@ -173,7 +173,7 @@ TEST_CASE("setup multiple hidden volumes", "[hidden]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); - Log::instance().set_loglevel(Loglevel::DEBUG_L2); + Log::instance().set_loglevel(Loglevel::DEBUG); auto user_pin = default_user_pin; stick10::LockDevice::CommandTransaction::run(stick); @@ -210,7 +210,7 @@ TEST_CASE("update password change", "[dangerous]") { Stick20 stick; bool connected = stick.connect(); REQUIRE(connected == true); - Log::instance().set_loglevel(Loglevel::DEBUG_L2); + Log::instance().set_loglevel(Loglevel::DEBUG); auto pass1 = default_admin_pin; auto pass2 = "12345678901234567890"; @@ -232,7 +232,7 @@ TEST_CASE("general test", "[test]") { bool connected = stick.connect(); REQUIRE(connected == true); - Log::instance().set_loglevel(Loglevel::DEBUG_L2); + Log::instance().set_loglevel(Loglevel::DEBUG); stick10::LockDevice::CommandTransaction::run(stick); // execute_password_command(stick, "123456"); -- cgit v1.2.3 From 7d943d3e8717ba47af4b53787cc4c29ad6ee2f90 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Wed, 2 Nov 2016 21:52:40 +0100 Subject: Python bindings and tests for most of Storage functionality Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 90 ++++++++++++++++++++++++++++++++++++++++++++++ NK_C_API.h | 17 +++++++++ NitrokeyManager.cc | 79 +++++++++++++++++++++++++++++++++++++++- include/NitrokeyManager.h | 25 ++++++++++++- unittest/constants.py | 2 ++ unittest/test_storage.py | 91 +++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 302 insertions(+), 2 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index 7110fca..fc6d3c5 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -375,5 +375,95 @@ extern int NK_login_auto() { }); } +// storage commands + +extern 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){ + 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){ + auto m = NitrokeyManager::instance(); + return get_without_result([&](){ + m->unlock_hidden_volume(hidden_volume_password); + }); +} + +extern int NK_create_hidden_volume(int slot_nr, int start_percent, int end_percent, + const char* hidden_volume_password){ + auto m = NitrokeyManager::instance(); + return get_without_result([&](){ + m->create_hidden_volume( slot_nr, start_percent, end_percent, + hidden_volume_password); + }); +} + +extern 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){ + auto m = NitrokeyManager::instance(); + return get_without_result([&](){ + m->set_unencrypted_read_write(user_pin); + }); +} + +extern 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) { + 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) { + 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, + const char* new_update_password) { + auto m = NitrokeyManager::instance(); + return get_without_result([&](){ + m->change_update_password(current_update_password, new_update_password); + }); +} + +extern const char* NK_get_status_storage() { + auto m = NitrokeyManager::instance(); + return get_with_string_result([&](){ + return m->get_status_storage(); + }); +} + +extern const char* NK_get_SD_usage_data() { + auto m = NitrokeyManager::instance(); + return get_with_string_result([&](){ + return m->get_SD_usage_data(); + }); +} + + } diff --git a/NK_C_API.h b/NK_C_API.h index 728824d..e5b414c 100644 --- a/NK_C_API.h +++ b/NK_C_API.h @@ -324,6 +324,23 @@ extern int NK_erase_password_safe_slot(uint8_t slot_number); */ extern int NK_is_AES_supported(const char *user_password); + +extern int NK_send_startup(uint64_t seconds_from_epoch); +extern int NK_unlock_encrypted_volume(const char* user_pin); +extern int NK_unlock_hidden_volume(const char* hidden_volume_password); +extern int NK_create_hidden_volume(int slot_nr, int start_percent, int end_percent, + const char* hidden_volume_password); +extern int NK_set_unencrypted_read_only(const char* user_pin); +extern int NK_set_unencrypted_read_write(const char* user_pin); +extern int NK_export_firmware(const char* admin_pin) ; +extern int NK_clear_new_sd_card_warning(const char* admin_pin) ; +extern int NK_fill_SD_card_with_random_data(const char* admin_pin) ; +extern int NK_change_update_password(const char* current_update_password, + const char* new_update_password); +extern const char* NK_get_status_storage(); +extern const char* NK_get_SD_usage_data(); + + } diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 606c4fb..49b34c4 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -3,6 +3,7 @@ #include "include/NitrokeyManager.h" #include "include/LibraryException.h" #include +#include "include/misc.h" namespace nitrokey{ @@ -486,4 +487,80 @@ namespace nitrokey{ return true; } -} + //storage commands + + /** + * TODO rename to set_time ? + * TODO check what exactly this one is doing + * @param seconds_from_epoch + */ + void NitrokeyManager::send_startup(uint64_t seconds_from_epoch){ + auto p = get_payload(); +// p.set_defaults(); + p.localtime = seconds_from_epoch; + //auto device_status = + stick20::SendStartup::CommandTransaction::run(*device, p); + } + + void NitrokeyManager::unlock_encrypted_volume(const char* 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); + } + + //TODO check is encrypted volume unlocked before execution + //if not return library exception + void NitrokeyManager::create_hidden_volume(int slot_nr, int start_percent, int end_percent, + const char* hidden_volume_password) { + auto p = get_payload(); + p.SlotNr_u8 = slot_nr; + p.StartBlockPercent_u8 = start_percent; + p.EndBlockPercent_u8 = end_percent; + strcpyT(p.HiddenVolumePassword_au8, hidden_volume_password); + stick20::SetupHiddenVolume::CommandTransaction::run(*device, p); + } + + void NitrokeyManager::set_unencrypted_read_only(const char* 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); + } + + void NitrokeyManager::export_firmware(const char* 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); + } + + 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); + } + + 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); + } + + const char * NitrokeyManager::get_status_storage(){ + auto p = stick20::GetDeviceStatus::CommandTransaction::run(*device); + return strdup(p.data().dissect().c_str()); + } + + const char * NitrokeyManager::get_SD_usage_data(){ + 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 52c18d7..7a3ffcc 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -82,6 +82,30 @@ namespace nitrokey { bool is_AES_supported(const char *user_password); + void unlock_encrypted_volume(const char *user_password); + + void unlock_hidden_volume(const char *hidden_volume_password); + + void set_unencrypted_read_only(const char *user_pin); + + void set_unencrypted_read_write(const char *user_pin); + + void export_firmware(const char *admin_pin); + + void clear_new_sd_card_warning(const char *admin_pin); + + void fill_SD_card_with_random_data(const char *admin_pin); + + void change_update_password(const char *current_update_password, const char *new_update_password); + + void create_hidden_volume(int slot_nr, int start_percent, int end_percent, const char *hidden_volume_password); + + void send_startup(uint64_t seconds_from_epoch); + + const char * get_status_storage(); + + const char *get_SD_usage_data(); + ~NitrokeyManager(); private: NitrokeyManager(); @@ -101,7 +125,6 @@ namespace nitrokey { template void change_PIN_general(char *current_PIN, char *new_PIN); - }; } diff --git a/unittest/constants.py b/unittest/constants.py index e3caae3..258619e 100644 --- a/unittest/constants.py +++ b/unittest/constants.py @@ -12,6 +12,8 @@ class DefaultPasswords(Enum): USER = '123456' ADMIN_TEMP = '123123123' USER_TEMP = '234234234' + UPDATE = '12345678' + UPDATE_TEMP = '123update123' class DeviceErrorCode(Enum): diff --git a/unittest/test_storage.py b/unittest/test_storage.py index d6cc558..b02b1eb 100644 --- a/unittest/test_storage.py +++ b/unittest/test_storage.py @@ -3,5 +3,96 @@ import pytest from misc import ffi, gs, wait, cast_pointer_to_tuple from constants import DefaultPasswords, DeviceErrorCode, RFC_SECRET, LibraryErrors +import pprint +pprint = pprint.PrettyPrinter(indent=4).pprint +def get_dict_from_dissect(status): + x = [] + for s in status.split('\n'): + try: + if not ':' in s: continue + ss = s.replace('\t', '').replace(' (int) ', '').split(':') + if not len(ss) == 2: continue + x.append(ss) + except: + pass + d = {k.strip(): v.strip() for k, v in x} + return d + + +def test_get_status_storage(C): + status_pointer = C.NK_get_status_storage() + status_string = gs(status_pointer) + status_dict = get_dict_from_dissect(status_string) + default_admin_password_retry_count = 3 + assert int(status_dict['AdminPwRetryCount']) == default_admin_password_retry_count + + +def test_sd_card_usage(C): + data_pointer = C.NK_get_SD_usage_data() + data_string = gs(data_pointer) + assert len(data_string) > 0 + data_dict = get_dict_from_dissect(data_string) + assert int(data_dict['WriteLevelMax']) <= 100 + + +def test_encrypted_volume_unlock(C): + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + +def test_encrypted_volume_unlock_hidden(C): + hidden_volume_password = 'hiddenpassword' + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + 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 + + +def test_encrypted_volume_setup_multiple_hidden(C): + 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(4): + assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i) ) == DeviceErrorCode.STATUS_OK + for i in range(4): + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK + + +def test_unencrypted_volume_set_read_only(C): + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_set_unencrypted_read_only(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + +def test_unencrypted_volume_set_read_write(C): + assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK + assert C.NK_set_unencrypted_read_write(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK + + +def test_export_firmware(C): + assert C.NK_export_firmware(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + + +def test_clear_new_sd_card_notification(C): + assert C.NK_clear_new_sd_card_warning(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + + +@pytest.mark.skip +def test_fill_SD_card(C): + assert C.NK_fill_SD_card_with_random_data(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + + +def test_change_update_password(C): + wrong_password = 'aaaaaaaaaaa' + assert C.NK_change_update_password(wrong_password, DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.WRONG_PASSWORD + assert C.NK_change_update_password(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.STATUS_OK + assert C.NK_change_update_password(DefaultPasswords.UPDATE_TEMP, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK + + +def test_send_startup(C): + time_seconds_from_epoch = 0 # FIXME set proper date + assert C.NK_send_startup(time_seconds_from_epoch) == DeviceErrorCode.STATUS_OK -- cgit v1.2.3 From 130a33311567a1f0f6a9a2d8707bff20a558eb20 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 3 Nov 2016 13:45:53 +0100 Subject: Treat LongOperationException as CommandFailed and handle it transparently Signed-off-by: Szczepan Zalega --- include/LongOperationInProgressException.h | 10 +++++----- include/device_proto.h | 15 ++++++++------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/include/LongOperationInProgressException.h b/include/LongOperationInProgressException.h index 673a218..7f182b0 100644 --- a/include/LongOperationInProgressException.h +++ b/include/LongOperationInProgressException.h @@ -5,16 +5,16 @@ #ifndef LIBNITROKEY_LONGOPERATIONINPROGRESSEXCEPTION_H #define LIBNITROKEY_LONGOPERATIONINPROGRESSEXCEPTION_H +#include "CommandFailedException.h" -class LongOperationInProgressException : public std::exception { +class LongOperationInProgressException : public CommandFailedException { public: unsigned char progress_bar_value; - unsigned char command_id; - LongOperationInProgressException(unsigned char _command_id, unsigned char _progress_bar_value) { - command_id = _command_id; - progress_bar_value = _progress_bar_value; + 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()( 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 187d25c..0953566 100644 --- a/include/device_proto.h +++ b/include/device_proto.h @@ -316,21 +316,22 @@ namespace nitrokey { clear_packet(outp); if (status <= 0) - throw std::runtime_error( + throw std::runtime_error( //FIXME replace with CriticalErrorException std::string("Device error while executing command ") + std::to_string(status)); - if (resp.device_status == static_cast(stick10::device_status::busy) && - static_cast(resp.storage_status.device_status) - == stick20::device_status::busy_progressbar){ - throw LongOperationInProgressException(resp.command_id, resp.storage_status.progress_bar_value); - } - 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), Loglevel::DEBUG); + if (resp.device_status == static_cast(stick10::device_status::busy) && + static_cast(resp.storage_status.device_status) + == stick20::device_status::busy_progressbar){ + throw LongOperationInProgressException( + resp.command_id, resp.device_status, resp.storage_status.progress_bar_value); + } + if (!resp.isValid()) throw std::runtime_error("Invalid incoming packet"); if (receiving_retry_counter <= 0) throw std::runtime_error( -- cgit v1.2.3 From fe36daa38ab1995c8c7fc6470d06b8595efd2385 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 3 Nov 2016 13:51:59 +0100 Subject: Tests: remake fill SD card test. Get progress bar value when busy. Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 7 +++++++ NK_C_API.h | 1 + NitrokeyManager.cc | 9 +++++++++ include/NitrokeyManager.h | 2 ++ unittest/constants.py | 1 + unittest/test_storage.py | 15 ++++++++++++++- 6 files changed, 34 insertions(+), 1 deletion(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index fc6d3c5..2a28ede 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -464,6 +464,13 @@ extern const char* NK_get_SD_usage_data() { }); } +extern int NK_get_progress_bar_value() { + auto m = NitrokeyManager::instance(); + return get_with_result([&](){ + return m->get_progress_bar_value(); + }); +} + } diff --git a/NK_C_API.h b/NK_C_API.h index e5b414c..b71aeb8 100644 --- a/NK_C_API.h +++ b/NK_C_API.h @@ -339,6 +339,7 @@ extern int NK_change_update_password(const char* current_update_password, const char* new_update_password); extern const char* NK_get_status_storage(); extern const char* NK_get_SD_usage_data(); +extern int NK_get_progress_bar_value(); } diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index 49b34c4..fdf1e05 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -562,5 +562,14 @@ namespace nitrokey{ return strdup(p.data().dissect().c_str()); } + int NitrokeyManager::get_progress_bar_value(){ + try{ + stick20::GetDeviceStatus::CommandTransaction::run(*device); + return -1; + } + catch (LongOperationInProgressException &e){ + return e.progress_bar_value; + } + } } diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 7a3ffcc..2d5859f 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -106,6 +106,8 @@ namespace nitrokey { const char *get_SD_usage_data(); + int get_progress_bar_value(); + ~NitrokeyManager(); private: NitrokeyManager(); diff --git a/unittest/constants.py b/unittest/constants.py index 258619e..78a219b 100644 --- a/unittest/constants.py +++ b/unittest/constants.py @@ -18,6 +18,7 @@ class DefaultPasswords(Enum): class DeviceErrorCode(Enum): STATUS_OK = 0 + BUSY = 1 # busy or busy progressbar in place of wrong_CRC status NOT_PROGRAMMED = 3 WRONG_PASSWORD = 4 STATUS_NOT_AUTHORIZED = 5 diff --git a/unittest/test_storage.py b/unittest/test_storage.py index b02b1eb..600faf2 100644 --- a/unittest/test_storage.py +++ b/unittest/test_storage.py @@ -83,7 +83,20 @@ def test_clear_new_sd_card_notification(C): @pytest.mark.skip def test_fill_SD_card(C): - assert C.NK_fill_SD_card_with_random_data(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK + status = C.NK_fill_SD_card_with_random_data(DefaultPasswords.ADMIN) + assert status == DeviceErrorCode.STATUS_OK or status == DeviceErrorCode.BUSY + while 1: + value = C.NK_get_progress_bar_value() + if value == -1: break + assert 0 <= value <= 100 + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK + wait(5) + + +def test_get_busy_progress_on_idle(C): + value = C.NK_get_progress_bar_value() + assert value == -1 + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK def test_change_update_password(C): -- cgit v1.2.3 From 8cb4f03c841e7035af1893f260db5690cf6b4aa5 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 3 Nov 2016 17:02:02 +0100 Subject: Document Storage methods in C API Use uint8_t instead of int where appropriate Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 4 +- NK_C_API.h | 113 ++++++++++++++++++++++++++++++++++++++++++++-- NitrokeyManager.cc | 9 +--- include/NitrokeyManager.h | 3 +- 4 files changed, 115 insertions(+), 14 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index 2a28ede..aeb6920 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -398,8 +398,8 @@ extern int NK_unlock_hidden_volume(const char* hidden_volume_password){ }); } -extern int NK_create_hidden_volume(int slot_nr, int start_percent, int end_percent, - const char* hidden_volume_password){ +extern 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([&](){ m->create_hidden_volume( slot_nr, start_percent, end_percent, diff --git a/NK_C_API.h b/NK_C_API.h index b71aeb8..2d958d6 100644 --- a/NK_C_API.h +++ b/NK_C_API.h @@ -325,22 +325,127 @@ extern int NK_erase_password_safe_slot(uint8_t slot_number); extern int NK_is_AES_supported(const char *user_password); + + + +/** + * This command is typically run to initiate + * communication with the device (altough not required). + * It sets time on device and returns its current status + * - a combination of set_time and get_status_storage commands + * Storage only + * @param seconds_from_epoch date and time expressed in seconds + */ extern int NK_send_startup(uint64_t seconds_from_epoch); + +/** + * Unlock encrypted volume. + * Storage only + * @param user_pin user pin 20 characters + * @return command processing error code + */ extern int NK_unlock_encrypted_volume(const char* user_pin); + +/** + * Unlock hidden volume and lock encrypted volume. + * Requires encrypted volume to be unlocked. + * Storage only + * @param hidden_volume_password 20 characters + * @return command processing error code + */ extern int NK_unlock_hidden_volume(const char* hidden_volume_password); -extern int NK_create_hidden_volume(int slot_nr, int start_percent, int end_percent, - const char* hidden_volume_password); + +/** + * Create hidden volume. + * Requires encrypted volume to be unlocked. + * Storage only + * @param slot_nr slot number in range 0-3 + * @param start_percent volume begin expressed in percent of total available storage, int in range 0-99 + * @param end_percent volume end expressed in percent of total available storage, int in range 1-100 + * @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, + const char *hidden_volume_password); + +/** + * Make unencrypted volume read-only. + * Device hides unencrypted volume for a second therefore make sure + * buffers are flushed before running. + * Storage only + * @param user_pin 20 characters + * @return command processing error code + */ extern int NK_set_unencrypted_read_only(const char* user_pin); + +/** + * Make unencrypted volume read-write. + * Device hides unencrypted volume for a second therefore make sure + * buffers are flushed before running. + * Storage only + * @param user_pin 20 characters + * @return command processing error code + */ extern int NK_set_unencrypted_read_write(const char* user_pin); + +/** + * Exports device's firmware to unencrypted volume. + * Storage only + * @param admin_pin 20 characters + * @return command processing error code + */ extern int NK_export_firmware(const char* admin_pin) ; + +/** + * Clear new SD card notification. It is set after factory reset. + * Storage only + * @param admin_pin 20 characters + * @return command processing error code + */ extern int NK_clear_new_sd_card_warning(const char* admin_pin) ; + +/** + * Fill SD card with random data. + * Should be done on first stick initialization after creating keys. + * Storage only + * @param admin_pin 20 characters + * @return command processing error code + */ extern int NK_fill_SD_card_with_random_data(const char* admin_pin) ; + +/** + * Change update password. + * Update password is used for entering update mode, where firmware + * could be uploaded using dfu-programmer or other means. + * Storage only + * @param current_update_password 20 characters + * @param new_update_password 20 characters + * @return command processing error code + */ extern int NK_change_update_password(const char* current_update_password, - const char* new_update_password); + const char* new_update_password); + +/** + * Get Storage stick status as string. + * Storage only + * @return string with devices attributes + */ extern const char* NK_get_status_storage(); + +/** + * Get SD card usage attributes as string. + * Usable during hidden volumes creation. + * Storage only + * @return string with SD card usage attributes + */ extern const char* NK_get_SD_usage_data(); -extern int NK_get_progress_bar_value(); +/** + * 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(); } diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index fdf1e05..bba06a3 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -489,11 +489,6 @@ namespace nitrokey{ //storage commands - /** - * TODO rename to set_time ? - * TODO check what exactly this one is doing - * @param seconds_from_epoch - */ void NitrokeyManager::send_startup(uint64_t seconds_from_epoch){ auto p = get_payload(); // p.set_defaults(); @@ -512,8 +507,8 @@ namespace nitrokey{ //TODO check is encrypted volume unlocked before execution //if not return library exception - void NitrokeyManager::create_hidden_volume(int slot_nr, int start_percent, int end_percent, - const char* hidden_volume_password) { + void NitrokeyManager::create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent, + const char *hidden_volume_password) { auto p = get_payload(); p.SlotNr_u8 = slot_nr; p.StartBlockPercent_u8 = start_percent; diff --git a/include/NitrokeyManager.h b/include/NitrokeyManager.h index 2d5859f..11c2be4 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -98,7 +98,8 @@ namespace nitrokey { void change_update_password(const char *current_update_password, const char *new_update_password); - void create_hidden_volume(int slot_nr, int start_percent, int end_percent, const char *hidden_volume_password); + void create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent, + const char *hidden_volume_password); void send_startup(uint64_t seconds_from_epoch); -- cgit v1.2.3 From 8d4bff3590191e369be02bbe0fbf858ab8930f52 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 3 Nov 2016 18:21:40 +0100 Subject: Skip hanging tests Signed-off-by: Szczepan Zalega --- unittest/test_storage.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unittest/test_storage.py b/unittest/test_storage.py index 600faf2..e7e0bda 100644 --- a/unittest/test_storage.py +++ b/unittest/test_storage.py @@ -49,7 +49,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): hidden_volume_password = 'hiddenpassword' p = lambda i: hidden_volume_password + str(i) -- cgit v1.2.3 From cdd16f3f184b2745094da39de3f815aea6633fdb Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Thu, 3 Nov 2016 18:22:02 +0100 Subject: Rename methods in API to make string return more obvious Signed-off-by: Szczepan Zalega --- NK_C_API.cc | 8 ++++---- NK_C_API.h | 4 ++-- NitrokeyManager.cc | 7 +++---- include/NitrokeyManager.h | 4 ++-- unittest/test_storage.py | 7 +++++-- 5 files changed, 16 insertions(+), 14 deletions(-) diff --git a/NK_C_API.cc b/NK_C_API.cc index aeb6920..d42840b 100644 --- a/NK_C_API.cc +++ b/NK_C_API.cc @@ -450,17 +450,17 @@ extern int NK_change_update_password(const char* current_update_password, }); } -extern const char* NK_get_status_storage() { +extern const char* NK_get_status_storage_as_string() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ - return m->get_status_storage(); + return m->get_status_storage_as_string(); }); } -extern const char* NK_get_SD_usage_data() { +extern const char* NK_get_SD_usage_data_as_string() { auto m = NitrokeyManager::instance(); return get_with_string_result([&](){ - return m->get_SD_usage_data(); + return m->get_SD_usage_data_as_string(); }); } diff --git a/NK_C_API.h b/NK_C_API.h index 2d958d6..a446a62 100644 --- a/NK_C_API.h +++ b/NK_C_API.h @@ -430,7 +430,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(); +extern const char* NK_get_status_storage_as_string(); /** * Get SD card usage attributes as string. @@ -438,7 +438,7 @@ extern const char* NK_get_status_storage(); * Storage only * @return string with SD card usage attributes */ -extern const char* NK_get_SD_usage_data(); +extern const char* NK_get_SD_usage_data_as_string(); /** * Get progress value of current long operation. diff --git a/NitrokeyManager.cc b/NitrokeyManager.cc index bba06a3..20f4f14 100644 --- a/NitrokeyManager.cc +++ b/NitrokeyManager.cc @@ -491,9 +491,8 @@ namespace nitrokey{ void NitrokeyManager::send_startup(uint64_t seconds_from_epoch){ auto p = get_payload(); -// p.set_defaults(); +// p.set_defaults(); //set current time p.localtime = seconds_from_epoch; - //auto device_status = stick20::SendStartup::CommandTransaction::run(*device, p); } @@ -547,12 +546,12 @@ namespace nitrokey{ stick20::ChangeUpdatePassword::CommandTransaction::run(*device, p); } - const char * NitrokeyManager::get_status_storage(){ + const char * NitrokeyManager::get_status_storage_as_string(){ auto p = stick20::GetDeviceStatus::CommandTransaction::run(*device); return strdup(p.data().dissect().c_str()); } - const char * NitrokeyManager::get_SD_usage_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 11c2be4..60fa753 100644 --- a/include/NitrokeyManager.h +++ b/include/NitrokeyManager.h @@ -103,9 +103,9 @@ namespace nitrokey { void send_startup(uint64_t seconds_from_epoch); - const char * get_status_storage(); + const char * get_status_storage_as_string(); - const char *get_SD_usage_data(); + const char *get_SD_usage_data_as_string(); int get_progress_bar_value(); diff --git a/unittest/test_storage.py b/unittest/test_storage.py index e7e0bda..01276ce 100644 --- a/unittest/test_storage.py +++ b/unittest/test_storage.py @@ -22,15 +22,18 @@ def get_dict_from_dissect(status): def test_get_status_storage(C): - status_pointer = C.NK_get_status_storage() + status_pointer = C.NK_get_status_storage_as_string() + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK status_string = gs(status_pointer) + assert len(status_string) > 0 status_dict = get_dict_from_dissect(status_string) default_admin_password_retry_count = 3 assert int(status_dict['AdminPwRetryCount']) == default_admin_password_retry_count def test_sd_card_usage(C): - data_pointer = C.NK_get_SD_usage_data() + data_pointer = C.NK_get_SD_usage_data_as_string() + assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK data_string = gs(data_pointer) assert len(data_string) > 0 data_dict = get_dict_from_dissect(data_string) -- cgit v1.2.3