aboutsummaryrefslogtreecommitdiff
path: root/libnitrokey-v3.6
diff options
context:
space:
mode:
Diffstat (limited to 'libnitrokey-v3.6')
-rw-r--r--libnitrokey-v3.6/DeviceCommunicationExceptions.cpp24
-rw-r--r--libnitrokey-v3.6/LICENSE166
-rw-r--r--libnitrokey-v3.6/NK_C_API.cc959
-rw-r--r--libnitrokey-v3.6/NK_C_API.h1090
-rw-r--r--libnitrokey-v3.6/NitrokeyManager.cc1233
-rw-r--r--libnitrokey-v3.6/README.md374
-rw-r--r--libnitrokey-v3.6/command_id.cc191
-rw-r--r--libnitrokey-v3.6/device.cc391
-rw-r--r--libnitrokey-v3.6/libnitrokey/CommandFailedException.h76
-rw-r--r--libnitrokey-v3.6/libnitrokey/DeviceCommunicationExceptions.h73
-rw-r--r--libnitrokey-v3.6/libnitrokey/LibraryException.h118
-rw-r--r--libnitrokey-v3.6/libnitrokey/LongOperationInProgressException.h45
-rw-r--r--libnitrokey-v3.6/libnitrokey/NitrokeyManager.h311
-rw-r--r--libnitrokey-v3.6/libnitrokey/command.h112
-rw-r--r--libnitrokey-v3.6/libnitrokey/command_id.h156
-rw-r--r--libnitrokey-v3.6/libnitrokey/cxx_semantics.h44
-rw-r--r--libnitrokey-v3.6/libnitrokey/deprecated.h35
-rw-r--r--libnitrokey-v3.6/libnitrokey/device.h240
-rw-r--r--libnitrokey-v3.6/libnitrokey/device_proto.h491
-rw-r--r--libnitrokey-v3.6/libnitrokey/dissect.h145
-rw-r--r--libnitrokey-v3.6/libnitrokey/hidapi/hidapi.h391
-rw-r--r--libnitrokey-v3.6/libnitrokey/log.h110
-rw-r--r--libnitrokey-v3.6/libnitrokey/misc.h121
-rw-r--r--libnitrokey-v3.6/libnitrokey/stick10_commands.h929
-rw-r--r--libnitrokey-v3.6/libnitrokey/stick10_commands_0.8.h348
-rw-r--r--libnitrokey-v3.6/libnitrokey/stick20_commands.h394
-rw-r--r--libnitrokey-v3.6/libnitrokey/version.h33
-rw-r--r--libnitrokey-v3.6/log.cc103
-rw-r--r--libnitrokey-v3.6/misc.cc123
-rw-r--r--libnitrokey-v3.6/version.cc37
-rw-r--r--libnitrokey-v3.6/version.cc.in37
31 files changed, 8900 insertions, 0 deletions
diff --git a/libnitrokey-v3.6/DeviceCommunicationExceptions.cpp b/libnitrokey-v3.6/DeviceCommunicationExceptions.cpp
new file mode 100644
index 0000000..4d62aad
--- /dev/null
+++ b/libnitrokey-v3.6/DeviceCommunicationExceptions.cpp
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include "DeviceCommunicationExceptions.h"
+
+std::atomic_int DeviceCommunicationException::occurred {0};
diff --git a/libnitrokey-v3.6/LICENSE b/libnitrokey-v3.6/LICENSE
new file mode 100644
index 0000000..341c30b
--- /dev/null
+++ b/libnitrokey-v3.6/LICENSE
@@ -0,0 +1,166 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
+
diff --git a/libnitrokey-v3.6/NK_C_API.cc b/libnitrokey-v3.6/NK_C_API.cc
new file mode 100644
index 0000000..c84e402
--- /dev/null
+++ b/libnitrokey-v3.6/NK_C_API.cc
@@ -0,0 +1,959 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include "NK_C_API.h"
+#include <iostream>
+#include <tuple>
+#include "libnitrokey/NitrokeyManager.h"
+#include <cstring>
+#include "libnitrokey/LibraryException.h"
+#include "libnitrokey/cxx_semantics.h"
+#include "libnitrokey/stick20_commands.h"
+#include "libnitrokey/device_proto.h"
+#include "libnitrokey/version.h"
+
+#ifdef _MSC_VER
+#ifdef _WIN32
+#pragma message "Using own strndup"
+char * strndup(const char* str, size_t maxlen) {
+ size_t len = strnlen(str, maxlen);
+ char* dup = (char *)malloc(len + 1);
+ memcpy(dup, str, len);
+ dup[len] = 0;
+ return dup;
+}
+#endif
+#endif
+
+using namespace nitrokey;
+
+const uint8_t NK_PWS_SLOT_COUNT = PWS_SLOT_COUNT;
+static uint8_t NK_last_command_status = 0;
+static const int max_string_field_length = 100;
+
+template <typename T>
+T* duplicate_vector_and_clear(std::vector<T> &v){
+ auto d = new T[v.size()];
+ std::copy(v.begin(), v.end(), d);
+ std::fill(v.begin(), v.end(), 0);
+ return d;
+}
+
+template <typename R, typename T>
+std::tuple<int, R> get_with_status(T func, R fallback) {
+ NK_last_command_status = 0;
+ try {
+ return std::make_tuple(0, func());
+ }
+ catch (CommandFailedException & commandFailedException){
+ NK_last_command_status = commandFailedException.last_command_status;
+ }
+ catch (LibraryException & libraryException){
+ NK_last_command_status = libraryException.exception_id();
+ }
+ catch (const DeviceCommunicationException &deviceException){
+ NK_last_command_status = 256-deviceException.getType();
+ }
+ return std::make_tuple(NK_last_command_status, fallback);
+}
+
+template <typename T>
+uint8_t * get_with_array_result(T func){
+ return std::get<1>(get_with_status<uint8_t*>(func, nullptr));
+}
+
+template <typename T>
+char* get_with_string_result(T func){
+ auto result = std::get<1>(get_with_status<char*>(func, nullptr));
+ if (result == nullptr) {
+ return strndup("", MAXIMUM_STR_REPLY_LENGTH);
+ }
+ return result;
+}
+
+template <typename T>
+auto get_with_result(T func){
+ return std::get<1>(get_with_status(func, static_cast<decltype(func())>(0)));
+}
+
+template <typename T>
+uint8_t get_without_result(T func){
+ NK_last_command_status = 0;
+ try {
+ func();
+ return 0;
+ }
+ catch (CommandFailedException & commandFailedException){
+ NK_last_command_status = commandFailedException.last_command_status;
+ }
+ catch (LibraryException & libraryException){
+ NK_last_command_status = libraryException.exception_id();
+ }
+ catch (const InvalidCRCReceived &invalidCRCException){
+ ;
+ }
+ catch (const DeviceCommunicationException &deviceException){
+ NK_last_command_status = 256-deviceException.getType();
+ }
+ return NK_last_command_status;
+}
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ NK_C_API uint8_t NK_get_last_command_status() {
+ auto _copy = NK_last_command_status;
+ NK_last_command_status = 0;
+ return _copy;
+ }
+
+ NK_C_API int NK_login(const char *device_model) {
+ auto m = NitrokeyManager::instance();
+ try {
+ NK_last_command_status = 0;
+ return m->connect(device_model);
+ }
+ catch (CommandFailedException & commandFailedException) {
+ NK_last_command_status = commandFailedException.last_command_status;
+ return commandFailedException.last_command_status;
+ }
+ catch (const DeviceCommunicationException &deviceException){
+ NK_last_command_status = 256-deviceException.getType();
+ cerr << deviceException.what() << endl;
+ return 0;
+ }
+ catch (std::runtime_error &e) {
+ cerr << e.what() << endl;
+ return 0;
+ }
+ return 0;
+ }
+
+ NK_C_API int NK_login_enum(NK_device_model device_model) {
+ const char *model_string;
+ switch (device_model) {
+ case NK_PRO:
+ model_string = "P";
+ break;
+ case NK_STORAGE:
+ model_string = "S";
+ break;
+ case NK_LIBREM:
+ model_string = "L";
+ break;
+ case NK_DISCONNECTED:
+ default:
+ /* no such enum value -- return error code */
+ return 0;
+ }
+ return NK_login(model_string);
+ }
+
+ NK_C_API int NK_logout() {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->disconnect();
+ });
+ }
+
+ NK_C_API int NK_first_authenticate(const char* admin_password, const char* admin_temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ return m->first_authenticate(admin_password, admin_temporary_password);
+ });
+ }
+
+
+ NK_C_API int NK_user_authenticate(const char* user_password, const char* user_temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->user_authenticate(user_password, user_temporary_password);
+ });
+ }
+
+ NK_C_API int NK_factory_reset(const char* admin_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->factory_reset(admin_password);
+ });
+ }
+ NK_C_API int NK_build_aes_key(const char* admin_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->build_aes_key(admin_password);
+ });
+ }
+
+ NK_C_API int NK_unlock_user_password(const char *admin_password, const char *new_user_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->unlock_user_password(admin_password, new_user_password);
+ });
+ }
+
+ NK_C_API int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock, bool enable_user_password,
+ bool delete_user_password,
+ const char *admin_temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ return m->write_config(numlock, capslock, scrolllock, enable_user_password, delete_user_password, admin_temporary_password);
+ });
+ }
+
+ NK_C_API int NK_write_config_struct(struct NK_config config,
+ const char *admin_temporary_password) {
+ return NK_write_config(config.numlock, config.capslock, config.scrolllock, config.enable_user_password,
+ config.disable_user_password, admin_temporary_password);
+ }
+
+
+ NK_C_API uint8_t* NK_read_config() {
+ auto m = NitrokeyManager::instance();
+ return get_with_array_result([&]() {
+ auto v = m->read_config();
+ return duplicate_vector_and_clear(v);
+ });
+ }
+
+ NK_C_API void NK_free_config(uint8_t* config) {
+ delete[] config;
+ }
+
+ NK_C_API int NK_read_config_struct(struct NK_config* out) {
+ if (out == nullptr) {
+ return -1;
+ }
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ auto v = m->read_config();
+ out->numlock = v[0];
+ out->capslock = v[1];
+ out->scrolllock = v[2];
+ out->enable_user_password = v[3];
+ out->disable_user_password = v[4];
+ });
+ }
+
+
+ NK_C_API enum NK_device_model NK_get_device_model() {
+ auto m = NitrokeyManager::instance();
+ try {
+ auto model = m->get_connected_device_model();
+ switch (model) {
+ case DeviceModel::PRO:
+ return NK_PRO;
+ case DeviceModel::STORAGE:
+ return NK_STORAGE;
+ case DeviceModel::LIBREM:
+ return NK_LIBREM;
+ default:
+ /* unknown or not connected device */
+ return NK_device_model::NK_DISCONNECTED;
+ }
+ } catch (const DeviceNotConnected& e) {
+ return NK_device_model::NK_DISCONNECTED;
+ }
+}
+
+
+ void clear_string(std::string &s) {
+ std::fill(s.begin(), s.end(), ' ');
+ }
+
+
+ NK_C_API char * NK_status() {
+ return NK_get_status_as_string();
+ }
+
+ NK_C_API char * NK_get_status_as_string() {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ string && s = m->get_status_as_string();
+ char * rs = strndup(s.c_str(), MAXIMUM_STR_REPLY_LENGTH);
+ clear_string(s);
+ return rs;
+ });
+ }
+
+ NK_C_API int NK_get_status(struct NK_status* out) {
+ if (out == nullptr) {
+ return -1;
+ }
+ auto m = NitrokeyManager::instance();
+ auto result = get_with_status([&]() {
+ return m->get_status();
+ }, proto::stick10::GetStatus::ResponsePayload());
+ auto error_code = std::get<0>(result);
+ if (error_code != 0) {
+ return error_code;
+ }
+
+ auto status = std::get<1>(result);
+ out->firmware_version_major = status.firmware_version_st.major;
+ out->firmware_version_minor = status.firmware_version_st.minor;
+ out->serial_number_smart_card = status.card_serial_u32;
+ out->config_numlock = status.numlock;
+ out->config_capslock = status.capslock;
+ out->config_scrolllock = status.scrolllock;
+ out->otp_user_password = status.enable_user_password != 0;
+ return 0;
+ }
+
+ NK_C_API char * NK_device_serial_number() {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ string && s = m->get_serial_number();
+ char * rs = strndup(s.c_str(), max_string_field_length);
+ clear_string(s);
+ return rs;
+ });
+ }
+
+ NK_C_API uint32_t NK_device_serial_number_as_u32() {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->get_serial_number_as_u32();
+ });
+ }
+
+ NK_C_API char * NK_get_hotp_code(uint8_t slot_number) {
+ return NK_get_hotp_code_PIN(slot_number, "");
+ }
+
+ NK_C_API char * NK_get_hotp_code_PIN(uint8_t slot_number, const char *user_temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ string && s = m->get_HOTP_code(slot_number, user_temporary_password);
+ char * rs = strndup(s.c_str(), max_string_field_length);
+ clear_string(s);
+ return rs;
+ });
+ }
+
+ NK_C_API char * NK_get_totp_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time,
+ uint8_t last_interval) {
+ return NK_get_totp_code_PIN(slot_number, challenge, last_totp_time, last_interval, "");
+ }
+
+ NK_C_API char * NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time,
+ uint8_t last_interval, const char *user_temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ string && s = m->get_TOTP_code(slot_number, challenge, last_totp_time, last_interval, user_temporary_password);
+ char * rs = strndup(s.c_str(), max_string_field_length);
+ clear_string(s);
+ return rs;
+ });
+ }
+
+ NK_C_API int NK_erase_hotp_slot(uint8_t slot_number, const char *temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&] {
+ m->erase_hotp_slot(slot_number, temporary_password);
+ });
+ }
+
+ NK_C_API int NK_erase_totp_slot(uint8_t slot_number, const char *temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&] {
+ m->erase_totp_slot(slot_number, temporary_password);
+ });
+ }
+
+ NK_C_API int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&] {
+ m->write_HOTP_slot(slot_number, slot_name, secret, hotp_counter, use_8_digits, use_enter, use_tokenID, token_ID,
+ temporary_password);
+ });
+ }
+
+ NK_C_API int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&] {
+ m->write_TOTP_slot(slot_number, slot_name, secret, time_window, use_8_digits, use_enter, use_tokenID, token_ID,
+ temporary_password);
+ });
+ }
+
+ NK_C_API char* NK_get_totp_slot_name(uint8_t slot_number) {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ const auto slot_name = m->get_totp_slot_name(slot_number);
+ return slot_name;
+ });
+ }
+ NK_C_API char* NK_get_hotp_slot_name(uint8_t slot_number) {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ const auto slot_name = m->get_hotp_slot_name(slot_number);
+ return slot_name;
+ });
+ }
+
+ NK_C_API void NK_set_debug(bool state) {
+ auto m = NitrokeyManager::instance();
+ m->set_debug(state);
+ }
+
+
+ NK_C_API void NK_set_debug_level(const int level) {
+ auto m = NitrokeyManager::instance();
+ m->set_loglevel(level);
+ }
+
+ NK_C_API unsigned int NK_get_major_library_version() {
+ return get_major_library_version();
+ }
+
+ NK_C_API unsigned int NK_get_minor_library_version() {
+ return get_minor_library_version();
+ }
+
+ NK_C_API const char* NK_get_library_version() {
+ return get_library_version();
+ }
+
+ NK_C_API int NK_totp_set_time(uint64_t time) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_time(time);
+ });
+ }
+
+ NK_C_API int NK_totp_set_time_soft(uint64_t time) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_time_soft(time);
+ });
+ }
+
+ NK_C_API int NK_totp_get_time() {
+ return 0;
+ }
+
+ NK_C_API int NK_change_admin_PIN(const char *current_PIN, const char *new_PIN) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->change_admin_PIN(current_PIN, new_PIN);
+ });
+ }
+
+ NK_C_API int NK_change_user_PIN(const char *current_PIN, const char *new_PIN) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->change_user_PIN(current_PIN, new_PIN);
+ });
+ }
+
+ NK_C_API int NK_enable_password_safe(const char *user_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->enable_password_safe(user_pin);
+ });
+ }
+ NK_C_API uint8_t * NK_get_password_safe_slot_status() {
+ auto m = NitrokeyManager::instance();
+ return get_with_array_result([&]() {
+ auto slot_status = m->get_password_safe_slot_status();
+ return duplicate_vector_and_clear(slot_status);
+ });
+
+ }
+
+ NK_C_API void NK_free_password_safe_slot_status(uint8_t* status) {
+ delete[] status;
+ }
+
+ NK_C_API uint8_t NK_get_user_retry_count() {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->get_user_retry_count();
+ });
+ }
+
+ NK_C_API uint8_t NK_get_admin_retry_count() {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->get_admin_retry_count();
+ });
+ }
+
+ NK_C_API int NK_lock_device() {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->lock_device();
+ });
+ }
+
+ NK_C_API char *NK_get_password_safe_slot_name(uint8_t slot_number) {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ return m->get_password_safe_slot_name(slot_number);
+ });
+ }
+
+ NK_C_API char *NK_get_password_safe_slot_login(uint8_t slot_number) {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ return m->get_password_safe_slot_login(slot_number);
+ });
+ }
+ NK_C_API char *NK_get_password_safe_slot_password(uint8_t slot_number) {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ return m->get_password_safe_slot_password(slot_number);
+ });
+ }
+ NK_C_API int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login,
+ const char *slot_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->write_password_safe_slot(slot_number, slot_name, slot_login, slot_password);
+ });
+ }
+
+ NK_C_API int NK_erase_password_safe_slot(uint8_t slot_number) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->erase_password_safe_slot(slot_number);
+ });
+ }
+
+ NK_C_API int NK_is_AES_supported(const char *user_password) {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return (uint8_t)m->is_AES_supported(user_password);
+ });
+ }
+
+ NK_C_API int NK_login_auto() {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return (uint8_t)m->connect();
+ });
+ }
+
+ // storage commands
+
+ NK_C_API int NK_send_startup(uint64_t seconds_from_epoch) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->send_startup(seconds_from_epoch);
+ });
+ }
+
+ NK_C_API int NK_unlock_encrypted_volume(const char* user_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->unlock_encrypted_volume(user_pin);
+ });
+ }
+
+ NK_C_API int NK_lock_encrypted_volume() {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->lock_encrypted_volume();
+ });
+ }
+
+ NK_C_API int NK_unlock_hidden_volume(const char* hidden_volume_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->unlock_hidden_volume(hidden_volume_password);
+ });
+ }
+
+ NK_C_API int NK_lock_hidden_volume() {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->lock_hidden_volume();
+ });
+ }
+
+ NK_C_API int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent,
+ const char *hidden_volume_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->create_hidden_volume(slot_nr, start_percent, end_percent,
+ hidden_volume_password);
+ });
+ }
+
+ // deprecated, noop on v0.51 and older (excl. v0.49)
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+ NK_C_API int NK_set_unencrypted_read_only(const char *user_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_unencrypted_read_only(user_pin);
+ });
+ }
+
+ // deprecated, noop on v0.51 and older (excl. v0.49)
+ NK_C_API int NK_set_unencrypted_read_write(const char *user_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_unencrypted_read_write(user_pin);
+ });
+ }
+#pragma GCC diagnostic pop
+
+ NK_C_API int NK_set_unencrypted_read_only_admin(const char *admin_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_unencrypted_read_only_admin(admin_pin);
+ });
+ }
+
+ NK_C_API int NK_set_unencrypted_read_write_admin(const char *admin_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_unencrypted_read_write_admin(admin_pin);
+ });
+ }
+
+ NK_C_API int NK_set_encrypted_read_only(const char* admin_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_encrypted_volume_read_only(admin_pin);
+ });
+ }
+
+ NK_C_API int NK_set_encrypted_read_write(const char* admin_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->set_encrypted_volume_read_write(admin_pin);
+ });
+ }
+
+ NK_C_API int NK_export_firmware(const char* admin_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->export_firmware(admin_pin);
+ });
+ }
+
+ NK_C_API int NK_clear_new_sd_card_warning(const char* admin_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->clear_new_sd_card_warning(admin_pin);
+ });
+ }
+
+ NK_C_API int NK_fill_SD_card_with_random_data(const char* admin_pin) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->fill_SD_card_with_random_data(admin_pin);
+ });
+ }
+
+ NK_C_API int NK_change_update_password(const char* current_update_password,
+ const char* new_update_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->change_update_password(current_update_password, new_update_password);
+ });
+ }
+
+ NK_C_API int NK_enable_firmware_update(const char* update_password){
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->enable_firmware_update(update_password);
+ });
+ }
+
+ NK_C_API char* NK_get_status_storage_as_string() {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ return m->get_status_storage_as_string();
+ });
+ }
+
+ NK_C_API int NK_get_status_storage(NK_storage_status* out) {
+ if (out == nullptr) {
+ return -1;
+ }
+ auto m = NitrokeyManager::instance();
+ auto result = get_with_status([&]() {
+ return m->get_status_storage();
+ }, proto::stick20::DeviceConfigurationResponsePacket::ResponsePayload());
+ auto error_code = std::get<0>(result);
+ if (error_code != 0) {
+ return error_code;
+ }
+
+ auto status = std::get<1>(result);
+ out->unencrypted_volume_read_only = status.ReadWriteFlagUncryptedVolume_u8 != 0;
+ out->unencrypted_volume_active = status.VolumeActiceFlag_st.unencrypted;
+ out->encrypted_volume_read_only = status.ReadWriteFlagCryptedVolume_u8 != 0;
+ out->encrypted_volume_active = status.VolumeActiceFlag_st.encrypted;
+ out->hidden_volume_read_only = status.ReadWriteFlagHiddenVolume_u8 != 0;
+ out->hidden_volume_active = status.VolumeActiceFlag_st.hidden;
+ out->firmware_version_major = status.versionInfo.major;
+ out->firmware_version_minor = status.versionInfo.minor;
+ out->firmware_locked = status.FirmwareLocked_u8 != 0;
+ out->serial_number_sd_card = status.ActiveSD_CardID_u32;
+ out->serial_number_smart_card = status.ActiveSmartCardID_u32;
+ out->user_retry_count = status.UserPwRetryCount;
+ out->admin_retry_count = status.AdminPwRetryCount;
+ out->new_sd_card_found = status.NewSDCardFound_st.NewCard;
+ out->filled_with_random = (status.SDFillWithRandomChars_u8 & 0x01) != 0;
+ out->stick_initialized = status.StickKeysNotInitiated == 0;
+ return 0;
+ }
+
+ NK_C_API int NK_get_storage_production_info(NK_storage_ProductionTest * out){
+ if (out == nullptr) {
+ return -1;
+ }
+ auto m = NitrokeyManager::instance();
+ auto result = get_with_status([&]() {
+ return m->production_info();
+ }, proto::stick20::ProductionTest::ResponsePayload());
+
+ auto error_code = std::get<0>(result);
+ if (error_code != 0) {
+ return error_code;
+ }
+
+ stick20::ProductionTest::ResponsePayload status = std::get<1>(result);
+ // Cannot use memcpy without declaring C API struct packed
+ // (which is not parsed by Python's CFFI apparently), hence the manual way.
+#define a(x) out->x = status.x;
+ a(FirmwareVersion_au8[0]);
+ a(FirmwareVersion_au8[1]);
+ a(FirmwareVersionInternal_u8);
+ a(SD_Card_Size_u8);
+ a(CPU_CardID_u32);
+ a(SmartCardID_u32);
+ a(SD_CardID_u32);
+ a(SC_UserPwRetryCount);
+ a(SC_AdminPwRetryCount);
+ a(SD_Card_ManufacturingYear_u8);
+ a(SD_Card_ManufacturingMonth_u8);
+ a(SD_Card_OEM_u16);
+ a(SD_WriteSpeed_u16);
+ a(SD_Card_Manufacturer_u8);
+#undef a
+ return 0;
+ }
+
+ NK_C_API int NK_get_SD_usage_data(struct NK_SD_usage_data* out) {
+ if (out == nullptr)
+ return -1;
+ auto m = NitrokeyManager::instance();
+ auto result = get_with_status([&]() {
+ return m->get_SD_usage_data();
+ }, std::make_pair<uint8_t, uint8_t>(0, 0));
+ auto error_code = std::get<0>(result);
+ if (error_code != 0)
+ return error_code;
+
+ auto data = std::get<1>(result);
+ out->write_level_min = std::get<0>(data);
+ out->write_level_max = std::get<1>(data);
+
+ return 0;
+ }
+
+NK_C_API char* NK_get_SD_usage_data_as_string() {
+ auto m = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ return m->get_SD_usage_data_as_string();
+ });
+ }
+
+ NK_C_API int NK_get_progress_bar_value() {
+ auto m = NitrokeyManager::instance();
+ return std::get<1>(get_with_status([&]() {
+ return m->get_progress_bar_value();
+ }, -2));
+ }
+
+ NK_C_API uint8_t NK_get_major_firmware_version() {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->get_major_firmware_version();
+ });
+ }
+
+ NK_C_API uint8_t NK_get_minor_firmware_version() {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->get_minor_firmware_version();
+ });
+ }
+
+ NK_C_API int NK_set_unencrypted_volume_rorw_pin_type_user() {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->set_unencrypted_volume_rorw_pin_type_user() ? 1 : 0;
+ });
+ }
+
+ NK_C_API char* NK_list_devices_by_cpuID() {
+ auto nm = NitrokeyManager::instance();
+ return get_with_string_result([&]() {
+ auto v = nm->list_devices_by_cpuID();
+ std::string res;
+ for (const auto a : v){
+ res += a+";";
+ }
+ if (res.size()>0) res.pop_back(); // remove last delimiter char
+ return strndup(res.c_str(), MAXIMUM_STR_REPLY_LENGTH);
+ });
+ }
+
+ bool copy_device_info(const DeviceInfo& source, NK_device_info* target) {
+ switch (source.m_deviceModel) {
+ case DeviceModel::PRO:
+ target->model = NK_PRO;
+ break;
+ case DeviceModel::STORAGE:
+ target->model = NK_STORAGE;
+ break;
+ case DeviceModel::LIBREM:
+ target->model = NK_LIBREM;
+ break;
+ default:
+ return false;
+ }
+
+ target->path = strndup(source.m_path.c_str(), MAXIMUM_STR_REPLY_LENGTH);
+ target->serial_number = strndup(source.m_serialNumber.c_str(), MAXIMUM_STR_REPLY_LENGTH);
+ target->next = nullptr;
+
+ return target->path && target->serial_number;
+ }
+
+ NK_C_API struct NK_device_info* NK_list_devices() {
+ auto nm = NitrokeyManager::instance();
+ return get_with_result([&]() -> NK_device_info* {
+ auto v = nm->list_devices();
+ if (v.empty())
+ return nullptr;
+
+ auto result = new NK_device_info();
+ auto ptr = result;
+ auto first = v.begin();
+ if (!copy_device_info(*first, ptr)) {
+ NK_free_device_info(result);
+ return nullptr;
+ }
+ v.erase(first);
+
+ for (auto& info : v) {
+ ptr->next = new NK_device_info();
+ ptr = ptr->next;
+
+ if (!copy_device_info(info, ptr)) {
+ NK_free_device_info(result);
+ return nullptr;
+ }
+ }
+ return result;
+ });
+ }
+
+ NK_C_API void NK_free_device_info(struct NK_device_info* device_info) {
+ if (!device_info)
+ return;
+
+ if (device_info->next)
+ NK_free_device_info(device_info->next);
+
+ free(device_info->path);
+ free(device_info->serial_number);
+ delete device_info;
+ }
+
+ NK_C_API int NK_connect_with_ID(const char* id) {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->connect_with_ID(id) ? 1 : 0;
+ });
+ }
+
+ NK_C_API int NK_connect_with_path(const char* path) {
+ auto m = NitrokeyManager::instance();
+ return get_with_result([&]() {
+ return m->connect_with_path(path) ? 1 : 0;
+ });
+ }
+
+
+ NK_C_API int NK_wink() {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ return m->wink();
+ });
+ }
+
+ NK_C_API int NK_enable_firmware_update_pro(const char* update_password){
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->enable_firmware_update_pro(update_password);
+ });
+}
+
+ NK_C_API int NK_change_firmware_password_pro(const char *current_firmware_password, const char *new_firmware_password) {
+ auto m = NitrokeyManager::instance();
+ return get_without_result([&]() {
+ m->change_firmware_update_password_pro(current_firmware_password,
+ new_firmware_password);
+ });
+ }
+
+
+ NK_C_API int NK_read_HOTP_slot(const uint8_t slot_num, struct ReadSlot_t* out){
+ if (out == nullptr)
+ return -1;
+ auto m = NitrokeyManager::instance();
+ auto result = get_with_status([&]() {
+ return m->get_HOTP_slot_data(slot_num);
+ }, stick10::ReadSlot::ResponsePayload() );
+ auto error_code = std::get<0>(result);
+ if (error_code != 0) {
+ return error_code;
+ }
+#define a(x) out->x = read_slot.x
+ stick10::ReadSlot::ResponsePayload read_slot = std::get<1>(result);
+ a(_slot_config);
+ a(slot_counter);
+#undef a
+#define m(x) memmove(out->x, read_slot.x, sizeof(read_slot.x))
+ m(slot_name);
+ m(slot_token_id);
+#undef m
+ return 0;
+}
+
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/libnitrokey-v3.6/NK_C_API.h b/libnitrokey-v3.6/NK_C_API.h
new file mode 100644
index 0000000..68fb56c
--- /dev/null
+++ b/libnitrokey-v3.6/NK_C_API.h
@@ -0,0 +1,1090 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef LIBNITROKEY_NK_C_API_H
+#define LIBNITROKEY_NK_C_API_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "deprecated.h"
+
+#ifdef _MSC_VER
+#define NK_C_API __declspec(dllexport)
+#else
+#define NK_C_API
+#endif
+
+/**
+ * \file
+ *
+ * C API for libnitrokey
+ *
+ * \mainpage
+ *
+ * **libnitrokey** provides access to Nitrokey Pro and Nitrokey Storage devices.
+ * This documentation describes libnitrokey’s C API. For a list of the
+ * available functions, see the NK_C_API.h file.
+ *
+ * \section getting_started Example
+ *
+ * \code{.c}
+ * #include <stdio.h>
+ * #include <stdlib.h>
+ * #include <libnitrokey/NK_C_API.h>
+ *
+ * int main(void)
+ * {
+ * if (NK_login_auto() != 1) {
+ * fprintf(stderr, "No Nitrokey found.\n");
+ * return 1;
+ * }
+ *
+ * NK_device_model model = NK_get_device_model();
+ * printf("Connected to ");
+ * switch (model) {
+ * case NK_PRO:
+ * printf("a Nitrokey Pro");
+ * break;
+ * case NK_STORAGE:
+ * printf("a Nitrokey Storage");
+ * break;
+ * case NK_LIBREM:
+ * printf("a Librem Key");
+ * break;
+ * default:
+ * printf("an unsupported Nitrokey");
+ * break;
+ * }
+ *
+ * char* serial_number = NK_device_serial_number();
+ * if (serial_number)
+ * printf(" with serial number %s\n", serial_number);
+ * else
+ * printf(" -- could not query serial number!\n");
+ * free(serial_number);
+ *
+ * NK_logout();
+ * return 0;
+ * }
+ * \endcode
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ /**
+ * The number of slots in the password safe.
+ */
+ extern const uint8_t NK_PWS_SLOT_COUNT;
+
+ static const int MAXIMUM_STR_REPLY_LENGTH = 8192;
+
+ /**
+ * The Nitrokey device models supported by the API.
+ */
+ enum NK_device_model {
+ /**
+ * Use, if no supported device is connected
+ */
+ NK_DISCONNECTED = 0,
+ /**
+ * Nitrokey Pro.
+ */
+ NK_PRO = 1,
+ /**
+ * Nitrokey Storage.
+ */
+ NK_STORAGE = 2,
+ /**
+ * Librem Key.
+ */
+ NK_LIBREM = 3
+ };
+
+ /**
+ * The connection info for a Nitrokey device as a linked list.
+ */
+ struct NK_device_info {
+ /**
+ * The model of the Nitrokey device.
+ */
+ enum NK_device_model model;
+ /**
+ * The USB device path for NK_connect_with_path.
+ */
+ char* path;
+ /**
+ * The serial number.
+ */
+ char* serial_number;
+ /**
+ * The pointer to the next element of the linked list or null
+ * if this is the last element in the list.
+ */
+ struct NK_device_info* next;
+ };
+
+ /**
+ * Stores the common device status for all Nitrokey devices.
+ */
+ struct NK_status {
+ /**
+ * The major firmware version, e. g. 0 in v0.40.
+ */
+ uint8_t firmware_version_major;
+ /**
+ * The minor firmware version, e. g. 40 in v0.40.
+ */
+ uint8_t firmware_version_minor;
+ /**
+ * The serial number of the smart card.
+ */
+ uint32_t serial_number_smart_card;
+ /**
+ * The HOTP slot to generate a password from if the numlock
+ * key is pressed twice (slot 0-1, or any other value to
+ * disable the function).
+ */
+ uint8_t config_numlock;
+ /**
+ * The HOTP slot to generate a password from if the capslock
+ * key is pressed twice (slot 0-1, or any other value to
+ * disable the function).
+ */
+ uint8_t config_capslock;
+ /**
+ * The HOTP slot to generate a password from if the scrolllock
+ * key is pressed twice (slot 0-1, or any other value to
+ * disable the function).
+ */
+ uint8_t config_scrolllock;
+ /**
+ * Indicates whether the user password is required to generate
+ * an OTP value.
+ */
+ bool otp_user_password;
+ };
+
+ /**
+ * Stores the status of a Storage device.
+ */
+ struct NK_storage_status {
+ /**
+ * Indicates whether the unencrypted volume is read-only.
+ */
+ bool unencrypted_volume_read_only;
+ /**
+ * Indicates whether the unencrypted volume is active.
+ */
+ bool unencrypted_volume_active;
+ /**
+ * Indicates whether the encrypted volume is read-only.
+ */
+ bool encrypted_volume_read_only;
+ /**
+ * Indicates whether the encrypted volume is active.
+ */
+ bool encrypted_volume_active;
+ /**
+ * Indicates whether the hidden volume is read-only.
+ */
+ bool hidden_volume_read_only;
+ /**
+ * Indicates whether the hidden volume is active.
+ */
+ bool hidden_volume_active;
+ /**
+ * The major firmware version, e. g. 0 in v0.40.
+ */
+ uint8_t firmware_version_major;
+ /**
+ * The minor firmware version, e. g. 40 in v0.40.
+ */
+ uint8_t firmware_version_minor;
+ /**
+ * Indicates whether the firmware is locked.
+ */
+ bool firmware_locked;
+ /**
+ * The serial number of the SD card in the Storage stick.
+ */
+ uint32_t serial_number_sd_card;
+ /**
+ * The serial number of the smart card in the Storage stick.
+ */
+ uint32_t serial_number_smart_card;
+ /**
+ * The number of remaining login attempts for the user PIN.
+ */
+ uint8_t user_retry_count;
+ /**
+ * The number of remaining login attempts for the admin PIN.
+ */
+ uint8_t admin_retry_count;
+ /**
+ * Indicates whether a new SD card was found.
+ */
+ bool new_sd_card_found;
+ /**
+ * Indicates whether the SD card is filled with random characters.
+ */
+ bool filled_with_random;
+ /**
+ * Indicates whether the stick has been initialized by generating
+ * the AES keys.
+ */
+ bool stick_initialized;
+ };
+
+ /**
+ * Data about the usage of the SD card.
+ */
+ struct NK_SD_usage_data {
+ /**
+ * The minimum write level, as a percentage of the total card
+ * size.
+ */
+ uint8_t write_level_min;
+ /**
+ * The maximum write level, as a percentage of the total card
+ * size.
+ */
+ uint8_t write_level_max;
+ };
+
+ /**
+ * The general configuration of a Nitrokey device.
+ */
+ struct NK_config {
+ /**
+ * value in range [0-1] to send HOTP code from slot 'numlock' after double pressing numlock
+ * or outside the range to disable this function
+ */
+ uint8_t numlock;
+ /**
+ * similar to numlock but with capslock
+ */
+ uint8_t capslock;
+ /**
+ * similar to numlock but with scrolllock
+ */
+ uint8_t scrolllock;
+ /**
+ * True to enable OTP PIN protection (require PIN each OTP code request)
+ */
+ bool enable_user_password;
+ /**
+ * Unused.
+ */
+ bool disable_user_password;
+ };
+
+ struct NK_storage_ProductionTest{
+ uint8_t FirmwareVersion_au8[2];
+ uint8_t FirmwareVersionInternal_u8;
+ uint8_t SD_Card_Size_u8;
+ uint32_t CPU_CardID_u32;
+ uint32_t SmartCardID_u32;
+ uint32_t SD_CardID_u32;
+ uint8_t SC_UserPwRetryCount;
+ uint8_t SC_AdminPwRetryCount;
+ uint8_t SD_Card_ManufacturingYear_u8;
+ uint8_t SD_Card_ManufacturingMonth_u8;
+ uint16_t SD_Card_OEM_u16;
+ uint16_t SD_WriteSpeed_u16;
+ uint8_t SD_Card_Manufacturer_u8;
+ };
+
+ NK_C_API int NK_get_storage_production_info(struct NK_storage_ProductionTest * out);
+
+
+/**
+ * Set debug level of messages written on stderr
+ * @param state state=True - most messages, state=False - only errors level
+ */
+ NK_C_API void NK_set_debug(bool state);
+
+ /**
+ * Set debug level of messages written on stderr
+ * @param level (int) 0-lowest verbosity, 5-highest verbosity
+ */
+ NK_C_API void NK_set_debug_level(const int level);
+
+ /**
+ * Get the major library version, e. g. the 3 in v3.2.
+ * @return the major library version
+ */
+ NK_C_API unsigned int NK_get_major_library_version();
+
+ /**
+ * Get the minor library version, e. g. the 2 in v3.2.
+ * @return the minor library version
+ */
+ NK_C_API unsigned int NK_get_minor_library_version();
+
+ /**
+ * Get the library version as a string. This is the output of
+ * `git describe --always` at compile time, for example "v3.3" or
+ * "v3.3-19-gaee920b".
+ * The return value is a string literal and must not be freed.
+ * @return the library version as a string
+ */
+ NK_C_API const char* NK_get_library_version();
+
+ /**
+ * Connect to device of given model. Currently library can be connected only to one device at once.
+ * @param device_model char 'S': Nitrokey Storage, 'P': Nitrokey Pro
+ * @return 1 if connected, 0 if wrong model or cannot connect
+ */
+ NK_C_API int NK_login(const char *device_model);
+
+ /**
+ * Connect to device of given model. Currently library can be connected only to one device at once.
+ * @param device_model NK_device_model: NK_PRO: Nitrokey Pro, NK_STORAGE: Nitrokey Storage, NK_LIBREM: Librem Key
+ * @return 1 if connected, 0 if wrong model or cannot connect
+ */
+ NK_C_API int NK_login_enum(enum NK_device_model device_model);
+
+ /**
+ * Connect to first available device, starting checking from Pro 1st to Storage 2nd.
+ * @return 1 if connected, 0 if wrong model or cannot connect
+ */
+ NK_C_API int NK_login_auto();
+
+ /**
+ * Disconnect from the device.
+ * @return command processing error code
+ */
+ NK_C_API int NK_logout();
+
+ /**
+ * Query the model of the connected device.
+ * Returns the model of the connected device or NK_DISCONNECTED.
+ *
+ * @return true if a device is connected and the out argument has been set
+ */
+ NK_C_API enum NK_device_model NK_get_device_model();
+
+ /**
+ * Return the debug status string. Debug purposes. This function is
+ * deprecated in favor of NK_get_status_as_string.
+ * @return string representation of the status or an empty string
+ * if the command failed
+ */
+ DEPRECATED
+ NK_C_API char * NK_status();
+
+ /**
+ * Return the debug status string. Debug purposes.
+ * @return string representation of the status or an empty string
+ * if the command failed
+ */
+ NK_C_API char * NK_get_status_as_string();
+
+ /**
+ * Get the stick status common to all Nitrokey devices and return the
+ * command processing error code. If the code is zero, i. e. the
+ * command was successful, the storage status is written to the output
+ * pointer's target. The output pointer must not be null.
+ *
+ * @param out the output pointer for the status
+ * @return command processing error code
+ */
+ NK_C_API int NK_get_status(struct NK_status* out);
+
+ /**
+ * Return the device's serial number string in hex.
+ * @return string device's serial number in hex
+ */
+ NK_C_API char * NK_device_serial_number();
+
+ /**
+ * Return the device's serial number string as an integer. Use
+ * NK_last_command_status to check for an error if this function
+ * returns zero.
+ * @return device's serial number as an integer
+ */
+ NK_C_API uint32_t NK_device_serial_number_as_u32();
+
+ /**
+ * Get last command processing status. Useful for commands which returns the results of their own and could not return
+ * an error code.
+ * @return previous command processing error code
+ */
+ NK_C_API uint8_t NK_get_last_command_status();
+
+ /**
+ * Lock device - cancel any user device unlocking.
+ * @return command processing error code
+ */
+ NK_C_API int NK_lock_device();
+
+ /**
+ * Authenticates the user on USER privilages with user_password and sets user's temporary password on device to user_temporary_password.
+ * @param user_password char[25] current user password
+ * @param user_temporary_password char[25] user temporary password to be set on device for further communication (authentication command)
+ * @return command processing error code
+ */
+ NK_C_API int NK_user_authenticate(const char* user_password, const char* user_temporary_password);
+
+ /**
+ * Authenticates the user on ADMIN privilages with admin_password and sets user's temporary password on device to admin_temporary_password.
+ * @param admin_password char[25] current administrator PIN
+ * @param admin_temporary_password char[25] admin temporary password to be set on device for further communication (authentication command)
+ * @return command processing error code
+ */
+ NK_C_API int NK_first_authenticate(const char* admin_password, const char* admin_temporary_password);
+
+ /**
+ * Execute a factory reset.
+ * @param admin_password char[20] current administrator PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_factory_reset(const char* admin_password);
+
+ /**
+ * Generates AES key on the device
+ * @param admin_password char[20] current administrator PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_build_aes_key(const char* admin_password);
+
+ /**
+ * Unlock user PIN locked after 3 incorrect codes tries.
+ * @param admin_password char[20] current administrator PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_unlock_user_password(const char *admin_password, const char *new_user_password);
+
+ /**
+ * Write general config to the device
+ * @param numlock set value in range [0-1] to send HOTP code from slot 'numlock' after double pressing numlock
+ * or outside the range to disable this function
+ * @param capslock similar to numlock but with capslock
+ * @param scrolllock similar to numlock but with scrolllock
+ * @param enable_user_password set True to enable OTP PIN protection (require PIN each OTP code request)
+ * @param delete_user_password (unused)
+ * @param admin_temporary_password current admin temporary password
+ * @return command processing error code
+ */
+ NK_C_API int NK_write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock,
+ bool enable_user_password, bool delete_user_password, const char *admin_temporary_password);
+
+ /**
+ * Write general config to the device
+ * @param config the configuration data
+ * @param admin_temporary_password current admin temporary password
+ * @return command processing error code
+ */
+ NK_C_API int NK_write_config_struct(struct NK_config config, const char *admin_temporary_password);
+
+ /**
+ * Get currently set config - status of function Numlock/Capslock/Scrollock OTP sending and is enabled PIN protected OTP
+ * The return value must be freed using NK_free_config.
+ * @see NK_write_config
+ * @return uint8_t general_config[5]:
+ * uint8_t numlock;
+ uint8_t capslock;
+ uint8_t scrolllock;
+ uint8_t enable_user_password;
+ uint8_t delete_user_password;
+
+ */
+ NK_C_API uint8_t* NK_read_config();
+
+ /**
+ * Free a value returned by NK_read_config. May be called with a NULL
+ * argument.
+ */
+ NK_C_API void NK_free_config(uint8_t* config);
+
+ /**
+ * Get currently set config and write it to the given pointer.
+ * @see NK_read_config
+ * @see NK_write_config_struct
+ * @param out a pointer to the struct that should be written to
+ * @return command processing error code
+ */
+ NK_C_API int NK_read_config_struct(struct NK_config* out);
+
+ //OTP
+
+ /**
+ * Get name of given TOTP slot
+ * @param slot_number TOTP slot number, slot_number<15
+ * @return char[20] the name of the slot
+ */
+ NK_C_API char * NK_get_totp_slot_name(uint8_t slot_number);
+
+ /**
+ *
+ * @param slot_number HOTP slot number, slot_number<3
+ * @return char[20] the name of the slot
+ */
+ NK_C_API char * NK_get_hotp_slot_name(uint8_t slot_number);
+
+ /**
+ * Erase HOTP slot data from the device
+ * @param slot_number HOTP slot number, slot_number<3
+ * @param temporary_password admin temporary password
+ * @return command processing error code
+ */
+ NK_C_API int NK_erase_hotp_slot(uint8_t slot_number, const char *temporary_password);
+
+ /**
+ * Erase TOTP slot data from the device
+ * @param slot_number TOTP slot number, slot_number<15
+ * @param temporary_password admin temporary password
+ * @return command processing error code
+ */
+ NK_C_API int NK_erase_totp_slot(uint8_t slot_number, const char *temporary_password);
+
+ /**
+ * Write HOTP slot data to the device
+ * @param slot_number HOTP slot number, slot_number<3, 0-numbered
+ * @param slot_name char[15] desired slot name. C string (requires ending '\0'; 16 bytes).
+ * @param secret char[40] 160-bit or 320-bit (currently Pro v0.8 only) secret as a hex string. C string (requires ending '\0'; 41 bytes).
+ * See NitrokeyManager::is_320_OTP_secret_supported.
+ * @param hotp_counter uint32_t starting value of HOTP counter
+ * @param use_8_digits should returned codes be 6 (false) or 8 digits (true)
+ * @param use_enter press ENTER key after sending OTP code using double-pressed scroll/num/capslock
+ * @param use_tokenID @see token_ID
+ * @param token_ID @see https://openauthentication.org/token-specs/, 'Class A' section
+ * @param temporary_password char[25] admin temporary password
+ * @return command processing error code
+ */
+ NK_C_API int NK_write_hotp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password);
+
+ /**
+ * Write TOTP slot data to the device
+ * @param slot_number TOTP slot number, slot_number<15, 0-numbered
+ * @param slot_name char[15] desired slot name. C string (requires ending '\0'; 16 bytes).
+ * @param secret char[40] 160-bit or 320-bit (currently Pro v0.8 only) secret as a hex string. C string (requires ending '\0'; 41 bytes).
+ * See NitrokeyManager::is_320_OTP_secret_supported.
+ * @param time_window uint16_t time window for this TOTP
+ * @param use_8_digits should returned codes be 6 (false) or 8 digits (true)
+ * @param use_enter press ENTER key after sending OTP code using double-pressed scroll/num/capslock
+ * @param use_tokenID @see token_ID
+ * @param token_ID @see https://openauthentication.org/token-specs/, 'Class A' section
+ * @param temporary_password char[20] admin temporary password
+ * @return command processing error code
+ */
+ NK_C_API int NK_write_totp_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password);
+
+ /**
+ * Get HOTP code from the device
+ * @param slot_number HOTP slot number, slot_number<3
+ * @return HOTP code
+ */
+ NK_C_API char * NK_get_hotp_code(uint8_t slot_number);
+
+ /**
+ * Get HOTP code from the device (PIN protected)
+ * @param slot_number HOTP slot number, slot_number<3
+ * @param user_temporary_password char[25] user temporary password if PIN protected OTP codes are enabled,
+ * otherwise should be set to empty string - ''
+ * @return HOTP code
+ */
+ NK_C_API char * NK_get_hotp_code_PIN(uint8_t slot_number, const char *user_temporary_password);
+
+ /**
+ * Get TOTP code from the device
+ * @param slot_number TOTP slot number, slot_number<15
+ * @param challenge TOTP challenge -- unused
+ * @param last_totp_time last time -- unused
+ * @param last_interval last interval --unused
+ * @return TOTP code
+ */
+ NK_C_API char * NK_get_totp_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time,
+ uint8_t last_interval);
+
+ /**
+ * Get TOTP code from the device (PIN protected)
+ * @param slot_number TOTP slot number, slot_number<15
+ * @param challenge TOTP challenge -- unused
+ * @param last_totp_time last time -- unused
+ * @param last_interval last interval -- unused
+ * @param user_temporary_password char[25] user temporary password if PIN protected OTP codes are enabled,
+ * otherwise should be set to empty string - ''
+ * @return TOTP code
+ */
+ NK_C_API char * NK_get_totp_code_PIN(uint8_t slot_number, uint64_t challenge,
+ uint64_t last_totp_time, uint8_t last_interval,
+ const char *user_temporary_password);
+
+ /**
+ * Set time on the device (for TOTP requests)
+ * @param time seconds in unix epoch (from 01.01.1970)
+ * @return command processing error code
+ */
+ NK_C_API int NK_totp_set_time(uint64_t time);
+
+ /**
+ * Set the device time used for TOTP to the given time. Contrary to
+ * {@code set_time(uint64_t)}, this command fails if {@code old_time}
+ * &gt; {@code time} or if {@code old_time} is zero (where {@code
+ * old_time} is the current time on the device).
+ *
+ * @param time new device time as Unix timestamp (seconds since
+ * 1970-01-01)
+ * @return command processing error code
+ */
+ NK_C_API int NK_totp_set_time_soft(uint64_t time);
+
+ // NK_totp_get_time is deprecated -- use NK_totp_set_time_soft instead
+ DEPRECATED
+ NK_C_API int NK_totp_get_time();
+
+ //passwords
+ /**
+ * Change administrator PIN
+ * @param current_PIN char[25] current PIN
+ * @param new_PIN char[25] new PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_change_admin_PIN(const char *current_PIN, const char *new_PIN);
+
+ /**
+ * Change user PIN
+ * @param current_PIN char[25] current PIN
+ * @param new_PIN char[25] new PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_change_user_PIN(const char *current_PIN, const char *new_PIN);
+
+
+ /**
+ * Get retry count of user PIN
+ * @return user PIN retry count
+ */
+ NK_C_API uint8_t NK_get_user_retry_count();
+
+ /**
+ * Get retry count of admin PIN
+ * @return admin PIN retry count
+ */
+ NK_C_API uint8_t NK_get_admin_retry_count();
+ //password safe
+
+ /**
+ * Enable password safe access
+ * @param user_pin char[30] current user PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_enable_password_safe(const char *user_pin);
+
+ /**
+ * Get password safe slots' status
+ * The return value must be freed using NK_free_password_safe_slot_status.
+ * @return uint8_t[16] slot statuses - each byte represents one slot with 0 (not programmed) and 1 (programmed)
+ */
+ NK_C_API uint8_t * NK_get_password_safe_slot_status();
+
+ /**
+ * Free a value returned by NK_get_password_safe_slot_status. May be
+ * called with a NULL argument.
+ */
+ NK_C_API void NK_free_password_safe_slot_status(uint8_t* status);
+
+ /**
+ * Get password safe slot name
+ * @param slot_number password safe slot number, slot_number<16
+ * @return slot name
+ */
+ NK_C_API char *NK_get_password_safe_slot_name(uint8_t slot_number);
+
+ /**
+ * Get password safe slot login
+ * @param slot_number password safe slot number, slot_number<16
+ * @return login from the PWS slot
+ */
+ NK_C_API char *NK_get_password_safe_slot_login(uint8_t slot_number);
+
+ /**
+ * Get the password safe slot password
+ * @param slot_number password safe slot number, slot_number<16
+ * @return password from the PWS slot
+ */
+ NK_C_API char *NK_get_password_safe_slot_password(uint8_t slot_number);
+
+ /**
+ * Write password safe data to the slot
+ * @param slot_number password safe slot number, slot_number<16
+ * @param slot_name char[11] name of the slot
+ * @param slot_login char[32] login string
+ * @param slot_password char[20] password string
+ * @return command processing error code
+ */
+ NK_C_API int NK_write_password_safe_slot(uint8_t slot_number, const char *slot_name,
+ const char *slot_login, const char *slot_password);
+
+ /**
+ * Erase the password safe slot from the device
+ * @param slot_number password safe slot number, slot_number<16
+ * @return command processing error code
+ */
+ NK_C_API int NK_erase_password_safe_slot(uint8_t slot_number);
+
+ /**
+ * Check whether AES is supported by the device
+ * @return 0 for no and 1 for yes
+ */
+ NK_C_API int NK_is_AES_supported(const char *user_password);
+
+ /**
+ * Get device's major firmware version
+ * @return major part of the version number (e.g. 0 from 0.48, 0 from 0.7 etc.)
+ */
+ NK_C_API uint8_t NK_get_major_firmware_version();
+
+ /**
+ * Get device's minor firmware version
+ * @return minor part of the version number (e.g. 7 from 0.7, 48 from 0.48 etc.)
+ */
+ NK_C_API uint8_t NK_get_minor_firmware_version();
+
+ /**
+ * Function to determine unencrypted volume PIN type
+ * @param minor_firmware_version
+ * @return Returns 1, if set unencrypted volume ro/rw pin type is User, 0 otherwise.
+ */
+ NK_C_API int NK_set_unencrypted_volume_rorw_pin_type_user();
+
+
+ /**
+ * 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
+ */
+ NK_C_API 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
+ */
+ NK_C_API int NK_unlock_encrypted_volume(const char* user_pin);
+
+ /**
+ * Locks encrypted volume
+ * @return command processing error code
+ */
+ NK_C_API int NK_lock_encrypted_volume();
+
+ /**
+ * Unlock hidden volume and lock encrypted volume.
+ * Requires encrypted volume to be unlocked.
+ * Storage only
+ * @param hidden_volume_password 20 characters
+ * @return command processing error code
+ */
+ NK_C_API int NK_unlock_hidden_volume(const char* hidden_volume_password);
+
+ /**
+ * Locks hidden volume
+ * @return command processing error code
+ */
+ NK_C_API int NK_lock_hidden_volume();
+
+ /**
+ * Create hidden volume.
+ * 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
+ */
+ NK_C_API int NK_create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent,
+ const char *hidden_volume_password);
+
+ /**
+ * Make unencrypted volume read-only.
+ * Device hides unencrypted volume for a second therefore make sure
+ * buffers are flushed before running.
+ * Does nothing if firmware version is not matched
+ * Firmware range: Storage v0.50, v0.48 and below
+ * Storage only
+ * @param user_pin 20 characters User PIN
+ * @return command processing error code
+ */
+ //[[deprecated("Use NK_set_unencrypted_read_only_admin instead")]]
+ DEPRECATED
+ NK_C_API 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.
+ * Does nothing if firmware version is not matched
+ * Firmware range: Storage v0.50, v0.48 and below
+ * Storage only
+ * @param user_pin 20 characters User PIN
+ * @return command processing error code
+ */
+ //[[deprecated("Use NK_set_unencrypted_read_write_admin instead")]]
+ DEPRECATED
+ NK_C_API int NK_set_unencrypted_read_write(const char *user_pin);
+
+ /**
+ * Make unencrypted volume read-only.
+ * Device hides unencrypted volume for a second therefore make sure
+ * buffers are flushed before running.
+ * Does nothing if firmware version is not matched
+ * Firmware range: Storage v0.49, v0.51+
+ * Storage only
+ * @param admin_pin 20 characters Admin PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_set_unencrypted_read_only_admin(const char* admin_pin);
+
+ /**
+ * Make unencrypted volume read-write.
+ * Device hides unencrypted volume for a second therefore make sure
+ * buffers are flushed before running.
+ * Does nothing if firmware version is not matched
+ * Firmware range: Storage v0.49, v0.51+
+ * Storage only
+ * @param admin_pin 20 characters Admin PIN
+ * @return command processing error code
+ */
+ NK_C_API int NK_set_unencrypted_read_write_admin(const char* admin_pin);
+
+ /**
+ * Make encrypted volume read-only.
+ * Device hides encrypted volume for a second therefore make sure
+ * buffers are flushed before running.
+ * Firmware range: v0.49 only, future (see firmware release notes)
+ * Storage only
+ * @param admin_pin 20 characters
+ * @return command processing error code
+ */
+ NK_C_API int NK_set_encrypted_read_only(const char* admin_pin);
+
+ /**
+ * Make encrypted volume read-write.
+ * Device hides encrypted volume for a second therefore make sure
+ * buffers are flushed before running.
+ * Firmware range: v0.49 only, future (see firmware release notes)
+ * Storage only
+ * @param admin_pin 20 characters
+ * @return command processing error code
+ */
+ NK_C_API int NK_set_encrypted_read_write(const char* admin_pin);
+
+ /**
+ * Exports device's firmware to unencrypted volume.
+ * Storage only
+ * @param admin_pin 20 characters
+ * @return command processing error code
+ */
+ NK_C_API 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
+ */
+ NK_C_API 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
+ */
+ NK_C_API 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
+ */
+ NK_C_API int NK_change_update_password(const char* current_update_password,
+ const char* new_update_password);
+
+ /**
+ * Enter update mode. Needs update password.
+ * When device is in update mode it no longer accepts any HID commands until
+ * firmware is launched (regardless of being updated or not).
+ * Smartcard (through CCID interface) and its all volumes are not visible as well.
+ * Its VID and PID are changed to factory-default (03eb:2ff1 Atmel Corp.)
+ * to be detected by flashing software. Result of this command can be reversed
+ * by using 'launch' command.
+ * For dfu-programmer it would be: 'dfu-programmer at32uc3a3256s launch'.
+ * Storage only
+ * @param update_password 20 characters
+ * @return command processing error code
+ */
+ NK_C_API int NK_enable_firmware_update(const char* update_password);
+
+ /**
+ * Get Storage stick status as string.
+ * Storage only
+ * @return string with devices attributes
+ */
+ NK_C_API char* NK_get_status_storage_as_string();
+
+ /**
+ * Get the Storage stick status and return the command processing
+ * error code. If the code is zero, i. e. the command was successful,
+ * the storage status is written to the output pointer's target.
+ * The output pointer must not be null.
+ *
+ * @param out the output pointer for the storage status
+ * @return command processing error code
+ */
+ NK_C_API int NK_get_status_storage(struct NK_storage_status* out);
+
+ /**
+ * Get SD card usage attributes. Usable during hidden volumes creation.
+ * If the command was successful (return value 0), the usage data is
+ * written to the output pointer’s target. The output pointer must
+ * not be null.
+ * Storage only
+ * @param out the output pointer for the usage data
+ * @return command processing error code
+ */
+ NK_C_API int NK_get_SD_usage_data(struct NK_SD_usage_data* out);
+
+ /**
+ * Get SD card usage attributes as string.
+ * Usable during hidden volumes creation.
+ * Storage only
+ * @return string with SD card usage attributes
+ */
+ NK_C_API char* NK_get_SD_usage_data_as_string();
+
+ /**
+ * Get progress value of current long operation.
+ * Storage only
+ * @return int in range 0-100 or -1 if device is not busy or -2 if an
+ * error occured
+ */
+ NK_C_API int NK_get_progress_bar_value();
+
+/**
+ * Returns a list of connected devices' id's, delimited by ';' character. Empty string is returned on no device found.
+ * Each ID could consist of:
+ * 1. SC_id:SD_id_p_path (about 40 bytes)
+ * 2. path (about 10 bytes)
+ * where 'path' is USB path (bus:num), 'SC_id' is smartcard ID, 'SD_id' is storage card ID and
+ * '_p_' and ':' are field delimiters.
+ * Case 2 (USB path only) is used, when the device cannot be asked about its status data (e.g. during a long operation,
+ * like clearing SD card.
+ * Internally connects to all available devices and creates a map between ids and connection objects.
+ * Side effects: changes active device to last detected Storage device.
+ * Storage only
+ * @example Example of returned data: '00005d19:dacc2cb4_p_0001:0010:02;000037c7:4cf12445_p_0001:000f:02;0001:000c:02'
+ * @return string delimited id's of connected devices
+ */
+ NK_C_API char* NK_list_devices_by_cpuID();
+
+ /**
+ * Returns a linked list of all connected devices, or null if no devices
+ * are connected or an error occured. The linked list must be freed by
+ * calling NK_free_device_info.
+ * @return a linked list of all connected devices
+ */
+ NK_C_API struct NK_device_info* NK_list_devices();
+
+ /**
+ * Free a linked list returned by NK_list_devices.
+ * @param the linked list to free or null
+ */
+ NK_C_API void NK_free_device_info(struct NK_device_info* device_info);
+
+/**
+ * Connects to the device with given ID. ID's list could be created with NK_list_devices_by_cpuID.
+ * Requires calling to NK_list_devices_by_cpuID first. Connecting to arbitrary ID/USB path is not handled.
+ * On connection requests status from device and disconnects it / removes from map on connection failure.
+ * Storage only
+ * @param id Target device ID (example: '00005d19:dacc2cb4_p_0001:0010:02')
+ * @return 1 on successful connection, 0 otherwise
+ */
+ NK_C_API int NK_connect_with_ID(const char* id);
+
+ /**
+ * Connects to a device with the given path. The path is a USB device
+ * path as returned by hidapi.
+ * @param path the device path
+ * @return 1 on successful connection, 0 otherwise
+ */
+ NK_C_API int NK_connect_with_path(const char* path);
+
+ /**
+ * Blink red and green LED alternatively and infinitely (until device is reconnected).
+ * @return command processing error code
+ */
+ NK_C_API int NK_wink();
+
+
+ /**
+ * Enable update mode on Nitrokey Pro.
+ * Supported from v0.11.
+ * @param update_password 20 bytes update password
+ * @return command processing error code
+ */
+ NK_C_API int NK_enable_firmware_update_pro(const char* update_password);
+
+ /**
+ * Change update-mode password on Nitrokey Pro.
+ * Supported from v0.11.
+ * @param current_firmware_password 20 bytes update password
+ * @param new_firmware_password 20 bytes update password
+ * @return command processing error code
+ */
+ NK_C_API int NK_change_firmware_password_pro(const char *current_firmware_password, const char *new_firmware_password);
+
+
+// as in ReadSlot::ResponsePayload
+struct ReadSlot_t {
+ uint8_t slot_name[15];
+ uint8_t _slot_config;
+ uint8_t slot_token_id[13];
+ uint64_t slot_counter;
+};
+
+
+NK_C_API int NK_read_HOTP_slot(const uint8_t slot_num, struct ReadSlot_t* out);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //LIBNITROKEY_NK_C_API_H
diff --git a/libnitrokey-v3.6/NitrokeyManager.cc b/libnitrokey-v3.6/NitrokeyManager.cc
new file mode 100644
index 0000000..329d155
--- /dev/null
+++ b/libnitrokey-v3.6/NitrokeyManager.cc
@@ -0,0 +1,1233 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include <cstring>
+#include <iostream>
+#include "libnitrokey/NitrokeyManager.h"
+#include "libnitrokey/LibraryException.h"
+#include <algorithm>
+#include <unordered_map>
+#include <stick20_commands.h>
+#include "libnitrokey/misc.h"
+#include <mutex>
+#include "libnitrokey/cxx_semantics.h"
+#include "libnitrokey/misc.h"
+#include <functional>
+#include <stick10_commands.h>
+
+std::mutex nitrokey::proto::send_receive_mtx;
+
+namespace nitrokey{
+
+ std::mutex mex_dev_com_manager;
+
+#ifndef strndup
+#ifdef _WIN32
+#pragma message "Using own strndup"
+char * strndup(const char* str, size_t maxlen){
+ size_t len = strnlen(str, maxlen);
+ char* dup = (char *) malloc(len + 1);
+ memcpy(dup, str, len);
+ dup[len] = 0;
+ return dup;
+}
+#endif
+#endif
+
+using nitrokey::misc::strcpyT;
+
+ template <typename T>
+ typename T::CommandPayload get_payload(){
+ //Create, initialize and return by value command payload
+ typename T::CommandPayload st;
+ bzero(&st, sizeof(st));
+ return st;
+ }
+
+
+ // package type to auth, auth type [Authorize,UserAuthorize]
+ template <typename S, typename A, typename T>
+ void NitrokeyManager::authorize_packet(T &package, const char *admin_temporary_password, shared_ptr<Device> device){
+ if (!is_authorization_command_supported()){
+ LOG("Authorization command not supported, skipping", Loglevel::WARNING);
+ }
+ auto auth = get_payload<A>();
+ strcpyT(auth.temporary_password, admin_temporary_password);
+ auth.crc_to_authorize = S::CommandTransaction::getCRC(package);
+ A::CommandTransaction::run(device, auth);
+ }
+
+ shared_ptr <NitrokeyManager> NitrokeyManager::_instance = nullptr;
+
+ NitrokeyManager::NitrokeyManager() : device(nullptr)
+ {
+ set_debug(false);
+ }
+ NitrokeyManager::~NitrokeyManager() {
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+
+ for (auto d : connected_devices){
+ if (d.second == nullptr) continue;
+ d.second->disconnect();
+ connected_devices[d.first] = nullptr;
+ }
+ }
+
+ bool NitrokeyManager::set_current_device_speed(int retry_delay, int send_receive_delay){
+ if (retry_delay < 20 || send_receive_delay < 20){
+ LOG("Delay set too low: " + to_string(retry_delay) +" "+ to_string(send_receive_delay), Loglevel::WARNING);
+ return false;
+ }
+
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+ if(device == nullptr) {
+ return false;
+ }
+ device->set_receiving_delay(std::chrono::duration<int, std::milli>(send_receive_delay));
+ device->set_retry_delay(std::chrono::duration<int, std::milli>(retry_delay));
+ return true;
+ }
+
+ std::vector<DeviceInfo> NitrokeyManager::list_devices(){
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+
+ return Device::enumerate();
+ }
+
+ std::vector<std::string> NitrokeyManager::list_devices_by_cpuID(){
+ using misc::toHex;
+ //disconnect default device
+ disconnect();
+
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+ LOGD1("Disconnecting registered devices");
+ for (auto & kv : connected_devices_byID){
+ if (kv.second != nullptr)
+ kv.second->disconnect();
+ }
+ connected_devices_byID.clear();
+
+ LOGD1("Enumerating devices");
+ std::vector<std::string> res;
+ const auto v = Device::enumerate();
+ LOGD1("Discovering IDs");
+ for (auto & i: v){
+ if (i.m_deviceModel != DeviceModel::STORAGE)
+ continue;
+ auto p = i.m_path;
+ auto d = make_shared<Stick20>();
+ LOGD1( std::string("Found: ") + p );
+ d->set_path(p);
+ try{
+ if (d->connect()){
+ device = d;
+ std::string id;
+ try {
+ const auto status = get_status_storage();
+ const auto sc_id = toHex(status.ActiveSmartCardID_u32);
+ const auto sd_id = toHex(status.ActiveSD_CardID_u32);
+ id += sc_id + ":" + sd_id;
+ id += "_p_" + p;
+ }
+ catch (const LongOperationInProgressException &e) {
+ LOGD1(std::string("Long operation in progress, setting ID to: ") + p);
+ id = p;
+ }
+
+ connected_devices_byID[id] = d;
+ res.push_back(id);
+ LOGD1( std::string("Found: ") + p + " => " + id);
+ } else{
+ LOGD1( std::string("Could not connect to: ") + p);
+ }
+ }
+ catch (const DeviceCommunicationException &e){
+ LOGD1( std::string("Exception encountered: ") + p);
+ }
+ }
+ return res;
+ }
+
+ bool NitrokeyManager::connect_with_ID(const std::string id) {
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+
+ auto position = connected_devices_byID.find(id);
+ if (position == connected_devices_byID.end()) {
+ LOGD1(std::string("Could not find device ")+id + ". Refresh devices list with list_devices_by_cpuID().");
+ return false;
+ }
+
+ auto d = connected_devices_byID[id];
+ device = d;
+ current_device_id = id;
+
+ //validate connection
+ try{
+ get_status();
+ }
+ catch (const LongOperationInProgressException &){
+ //ignore
+ }
+ catch (const DeviceCommunicationException &){
+ d->disconnect();
+ current_device_id = "";
+ connected_devices_byID[id] = nullptr;
+ connected_devices_byID.erase(position);
+ return false;
+ }
+ nitrokey::log::Log::setPrefix(id);
+ LOGD1("Device successfully changed");
+ return true;
+ }
+
+ /**
+ * Connects device to path.
+ * Assumes devices are not being disconnected and caches connections (param cache_connections).
+ * @param path os-dependent device path
+ * @return false, when could not connect, true otherwise
+ */
+ bool NitrokeyManager::connect_with_path(std::string path) {
+ const bool cache_connections = false;
+
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+
+ if (cache_connections){
+ if(connected_devices.find(path) != connected_devices.end()
+ && connected_devices[path] != nullptr) {
+ device = connected_devices[path];
+ return true;
+ }
+ }
+
+ auto vendor_id = NITROKEY_VID;
+ auto info_ptr = hid_enumerate(vendor_id, 0);
+ if (!info_ptr) {
+ vendor_id = PURISM_VID;
+ info_ptr = hid_enumerate(vendor_id, 0);
+ }
+ auto first_info_ptr = info_ptr;
+ if (!info_ptr)
+ return false;
+
+ misc::Option<DeviceModel> model;
+ while (info_ptr && !model.has_value()) {
+ if (path == std::string(info_ptr->path)) {
+ model = product_id_to_model(info_ptr->vendor_id, info_ptr->product_id);
+ }
+ info_ptr = info_ptr->next;
+ }
+ hid_free_enumeration(first_info_ptr);
+
+ if (!model.has_value())
+ return false;
+
+ auto p = Device::create(model.value());
+ if (!p)
+ return false;
+ p->set_path(path);
+
+ if(!p->connect()) return false;
+
+ if(cache_connections){
+ connected_devices [path] = p;
+ }
+
+ device = p; //previous device will be disconnected automatically
+ current_device_id = path;
+ nitrokey::log::Log::setPrefix(path);
+ LOGD1("Device successfully changed");
+ return true;
+ }
+
+ bool NitrokeyManager::connect() {
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+ vector< shared_ptr<Device> > devices = { make_shared<Stick10>(), make_shared<Stick20>(),
+ make_shared<LibremKey>() };
+ bool connected = false;
+ for( auto & d : devices ){
+ if (d->connect()){
+ device = std::shared_ptr<Device>(d);
+ connected = true;
+ }
+ }
+ return connected;
+ }
+
+
+ void NitrokeyManager::set_log_function(std::function<void(std::string)> log_function){
+ static nitrokey::log::FunctionalLogHandler handler(log_function);
+ nitrokey::log::Log::instance().set_handler(&handler);
+ }
+
+ bool NitrokeyManager::set_default_commands_delay(int delay){
+ if (delay < 20){
+ LOG("Delay set too low: " + to_string(delay), Loglevel::WARNING);
+ return false;
+ }
+ Device::set_default_device_speed(delay);
+ return true;
+ }
+
+ bool NitrokeyManager::connect(const char *device_model) {
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+ LOG(__FUNCTION__, nitrokey::log::Loglevel::DEBUG_L2);
+ switch (device_model[0]){
+ case 'P':
+ device = make_shared<Stick10>();
+ break;
+ case 'S':
+ device = make_shared<Stick20>();
+ break;
+ case 'L':
+ device = make_shared<LibremKey>();
+ break;
+ default:
+ throw std::runtime_error("Unknown model");
+ }
+ return device->connect();
+ }
+
+ bool NitrokeyManager::connect(device::DeviceModel device_model) {
+ const char *model_string;
+ switch (device_model) {
+ case device::DeviceModel::PRO:
+ model_string = "P";
+ break;
+ case device::DeviceModel::STORAGE:
+ model_string = "S";
+ break;
+ case device::DeviceModel::LIBREM:
+ model_string = "L";
+ break;
+ default:
+ throw std::runtime_error("Unknown model");
+ }
+ return connect(model_string);
+ }
+
+ shared_ptr<NitrokeyManager> NitrokeyManager::instance() {
+ static std::mutex mutex;
+ std::lock_guard<std::mutex> lock(mutex);
+ if (_instance == nullptr){
+ _instance = make_shared<NitrokeyManager>();
+ }
+ return _instance;
+ }
+
+
+
+ bool NitrokeyManager::disconnect() {
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+ return _disconnect_no_lock();
+ }
+
+ bool NitrokeyManager::_disconnect_no_lock() {
+ //do not use directly without locked mutex,
+ //used by could_be_enumerated, disconnect
+ if (device == nullptr){
+ return false;
+ }
+ const auto res = device->disconnect();
+ device = nullptr;
+ return res;
+ }
+
+ bool NitrokeyManager::is_connected() throw(){
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+ if(device != nullptr){
+ auto connected = device->could_be_enumerated();
+ if(connected){
+ return true;
+ } else {
+ _disconnect_no_lock();
+ return false;
+ }
+ }
+ return false;
+ }
+
+ bool NitrokeyManager::could_current_device_be_enumerated() {
+ std::lock_guard<std::mutex> lock(mex_dev_com_manager);
+ if (device != nullptr) {
+ return device->could_be_enumerated();
+ }
+ return false;
+ }
+
+ void NitrokeyManager::set_loglevel(int loglevel) {
+ loglevel = max(loglevel, static_cast<int>(Loglevel::ERROR));
+ loglevel = min(loglevel, static_cast<int>(Loglevel::DEBUG_L2));
+ Log::instance().set_loglevel(static_cast<Loglevel>(loglevel));
+ }
+
+ void NitrokeyManager::set_loglevel(Loglevel loglevel) {
+ Log::instance().set_loglevel(loglevel);
+ }
+
+ void NitrokeyManager::set_debug(bool state) {
+ if (state){
+ Log::instance().set_loglevel(Loglevel::DEBUG);
+ } else {
+ Log::instance().set_loglevel(Loglevel::ERROR);
+ }
+ }
+
+
+ string NitrokeyManager::get_serial_number() {
+ try {
+ auto serial_number = this->get_serial_number_as_u32();
+ if (serial_number == 0) {
+ return "NA";
+ } else {
+ return nitrokey::misc::toHex(serial_number);
+ }
+ } catch (DeviceNotConnected& e) {
+ return "";
+ }
+ }
+
+ uint32_t NitrokeyManager::get_serial_number_as_u32() {
+ if (device == nullptr) { throw DeviceNotConnected("device not connected"); }
+ switch (device->get_device_model()) {
+ case DeviceModel::LIBREM:
+ case DeviceModel::PRO: {
+ auto response = GetStatus::CommandTransaction::run(device);
+ return response.data().card_serial_u32;
+ }
+ break;
+
+ case DeviceModel::STORAGE:
+ {
+ auto response = stick20::GetDeviceStatus::CommandTransaction::run(device);
+ return response.data().ActiveSmartCardID_u32;
+ }
+ break;
+ }
+ return 0;
+ }
+
+ stick10::GetStatus::ResponsePayload NitrokeyManager::get_status(){
+ try{
+ auto response = GetStatus::CommandTransaction::run(device);
+ return response.data();
+ }
+ catch (DeviceSendingFailure &e){
+// disconnect();
+ throw;
+ }
+ }
+
+ string NitrokeyManager::get_status_as_string() {
+ auto response = GetStatus::CommandTransaction::run(device);
+ return response.data().dissect();
+ }
+
+ string getFilledOTPCode(uint32_t code, bool use_8_digits){
+ stringstream s;
+ s << std::right << std::setw(use_8_digits ? 8 : 6) << std::setfill('0') << code;
+ return s.str();
+ }
+
+ string NitrokeyManager::get_HOTP_code(uint8_t slot_number, const char *user_temporary_password) {
+ if (!is_valid_hotp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+
+ if (is_authorization_command_supported()){
+ auto gh = get_payload<GetHOTP>();
+ gh.slot_number = get_internal_slot_number_for_hotp(slot_number);
+ if(user_temporary_password != nullptr && strlen(user_temporary_password)!=0){ //FIXME use string instead of strlen
+ authorize_packet<GetHOTP, UserAuthorize>(gh, user_temporary_password, device);
+ }
+ auto resp = GetHOTP::CommandTransaction::run(device, gh);
+ return getFilledOTPCode(resp.data().code, resp.data().use_8_digits);
+ } else {
+ auto gh = get_payload<stick10_08::GetHOTP>();
+ gh.slot_number = get_internal_slot_number_for_hotp(slot_number);
+ if(user_temporary_password != nullptr && strlen(user_temporary_password)!=0) {
+ strcpyT(gh.temporary_user_password, user_temporary_password);
+ }
+ auto resp = stick10_08::GetHOTP::CommandTransaction::run(device, gh);
+ return getFilledOTPCode(resp.data().code, resp.data().use_8_digits);
+ }
+ return "";
+ }
+
+ bool NitrokeyManager::is_internal_hotp_slot_number(uint8_t slot_number) const { return slot_number < 0x20; }
+ bool NitrokeyManager::is_valid_hotp_slot_number(uint8_t slot_number) const { return slot_number < 3; }
+ bool NitrokeyManager::is_valid_totp_slot_number(uint8_t slot_number) const { return slot_number < 0x10-1; } //15
+ uint8_t NitrokeyManager::get_internal_slot_number_for_totp(uint8_t slot_number) const { return (uint8_t) (0x20 + slot_number); }
+ uint8_t NitrokeyManager::get_internal_slot_number_for_hotp(uint8_t slot_number) const { return (uint8_t) (0x10 + slot_number); }
+
+
+
+ string NitrokeyManager::get_TOTP_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time,
+ uint8_t last_interval,
+ const char *user_temporary_password) {
+ if(!is_valid_totp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ slot_number = get_internal_slot_number_for_totp(slot_number);
+
+ if (is_authorization_command_supported()){
+ auto gt = get_payload<GetTOTP>();
+ gt.slot_number = slot_number;
+ gt.challenge = challenge;
+ gt.last_interval = last_interval;
+ gt.last_totp_time = last_totp_time;
+
+ if(user_temporary_password != nullptr && strlen(user_temporary_password)!=0){ //FIXME use string instead of strlen
+ authorize_packet<GetTOTP, UserAuthorize>(gt, user_temporary_password, device);
+ }
+ auto resp = GetTOTP::CommandTransaction::run(device, gt);
+ return getFilledOTPCode(resp.data().code, resp.data().use_8_digits);
+ } else {
+ auto gt = get_payload<stick10_08::GetTOTP>();
+ strcpyT(gt.temporary_user_password, user_temporary_password);
+ gt.slot_number = slot_number;
+ auto resp = stick10_08::GetTOTP::CommandTransaction::run(device, gt);
+ return getFilledOTPCode(resp.data().code, resp.data().use_8_digits);
+ }
+ return "";
+ }
+
+ bool NitrokeyManager::erase_slot(uint8_t slot_number, const char *temporary_password) {
+ if (is_authorization_command_supported()){
+ auto p = get_payload<EraseSlot>();
+ p.slot_number = slot_number;
+ authorize_packet<EraseSlot, Authorize>(p, temporary_password, device);
+ auto resp = EraseSlot::CommandTransaction::run(device,p);
+ } else {
+ auto p = get_payload<stick10_08::EraseSlot>();
+ p.slot_number = slot_number;
+ strcpyT(p.temporary_admin_password, temporary_password);
+ auto resp = stick10_08::EraseSlot::CommandTransaction::run(device,p);
+ }
+ return true;
+ }
+
+ bool NitrokeyManager::erase_hotp_slot(uint8_t slot_number, const char *temporary_password) {
+ if (!is_valid_hotp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ slot_number = get_internal_slot_number_for_hotp(slot_number);
+ return erase_slot(slot_number, temporary_password);
+ }
+
+ bool NitrokeyManager::erase_totp_slot(uint8_t slot_number, const char *temporary_password) {
+ if (!is_valid_totp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ slot_number = get_internal_slot_number_for_totp(slot_number);
+ return erase_slot(slot_number, temporary_password);
+ }
+
+ template <typename T, typename U>
+ void vector_copy_ranged(T& dest, std::vector<U> &vec, size_t begin, size_t elements_to_copy){
+ const size_t d_size = sizeof(dest);
+ if(d_size < elements_to_copy){
+ throw TargetBufferSmallerThanSource(elements_to_copy, d_size);
+ }
+ std::fill(dest, dest+d_size, 0);
+ std::copy(vec.begin() + begin, vec.begin() +begin + elements_to_copy, dest);
+ }
+
+ template <typename T, typename U>
+ void vector_copy(T& dest, std::vector<U> &vec){
+ const size_t d_size = sizeof(dest);
+ if(d_size < vec.size()){
+ throw TargetBufferSmallerThanSource(vec.size(), d_size);
+ }
+ std::fill(dest, dest+d_size, 0);
+ std::copy(vec.begin(), vec.end(), dest);
+ }
+
+ bool NitrokeyManager::write_HOTP_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password) {
+ if (!is_valid_hotp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+
+ int internal_slot_number = get_internal_slot_number_for_hotp(slot_number);
+ if (is_authorization_command_supported()){
+ write_HOTP_slot_authorize(internal_slot_number, slot_name, secret, hotp_counter, use_8_digits, use_enter, use_tokenID,
+ token_ID, temporary_password);
+ } else {
+ write_OTP_slot_no_authorize(internal_slot_number, slot_name, secret, hotp_counter, use_8_digits, use_enter, use_tokenID,
+ token_ID, temporary_password);
+ }
+ return true;
+ }
+
+ void NitrokeyManager::write_HOTP_slot_authorize(uint8_t slot_number, const char *slot_name, const char *secret,
+ uint64_t hotp_counter, bool use_8_digits, bool use_enter,
+ bool use_tokenID, const char *token_ID, const char *temporary_password) {
+ auto payload = get_payload<WriteToHOTPSlot>();
+ payload.slot_number = slot_number;
+ auto secret_bin = misc::hex_string_to_byte(secret);
+ vector_copy(payload.slot_secret, secret_bin);
+ strcpyT(payload.slot_name, slot_name);
+ strcpyT(payload.slot_token_id, token_ID);
+ switch (device->get_device_model() ){
+ case DeviceModel::LIBREM:
+ case DeviceModel::PRO: {
+ payload.slot_counter = hotp_counter;
+ break;
+ }
+ case DeviceModel::STORAGE: {
+ string counter = to_string(hotp_counter);
+ strcpyT(payload.slot_counter_s, counter.c_str());
+ break;
+ }
+ default:
+ LOG(string(__FILE__) + to_string(__LINE__) +
+ string(__FUNCTION__) + string(" Unhandled device model for HOTP")
+ , Loglevel::DEBUG);
+ break;
+ }
+ payload.use_8_digits = use_8_digits;
+ payload.use_enter = use_enter;
+ payload.use_tokenID = use_tokenID;
+
+ authorize_packet<WriteToHOTPSlot, Authorize>(payload, temporary_password, device);
+
+ auto resp = WriteToHOTPSlot::CommandTransaction::run(device, payload);
+ }
+
+ bool NitrokeyManager::write_TOTP_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password) {
+ if (!is_valid_totp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ int internal_slot_number = get_internal_slot_number_for_totp(slot_number);
+
+ if (is_authorization_command_supported()){
+ write_TOTP_slot_authorize(internal_slot_number, slot_name, secret, time_window, use_8_digits, use_enter, use_tokenID,
+ token_ID, temporary_password);
+ } else {
+ write_OTP_slot_no_authorize(internal_slot_number, slot_name, secret, time_window, use_8_digits, use_enter, use_tokenID,
+ token_ID, temporary_password);
+ }
+
+ return true;
+ }
+
+ void NitrokeyManager::write_OTP_slot_no_authorize(uint8_t internal_slot_number, const char *slot_name,
+ const char *secret,
+ uint64_t counter_or_interval, bool use_8_digits, bool use_enter,
+ bool use_tokenID, const char *token_ID,
+ const char *temporary_password) const {
+
+ auto payload2 = get_payload<stick10_08::SendOTPData>();
+ strcpyT(payload2.temporary_admin_password, temporary_password);
+ strcpyT(payload2.data, slot_name);
+ payload2.setTypeName();
+ stick10_08::SendOTPData::CommandTransaction::run(device, payload2);
+
+ payload2.setTypeSecret();
+ payload2.id = 0;
+ auto secret_bin = misc::hex_string_to_byte(secret);
+ auto remaining_secret_length = secret_bin.size();
+ const auto maximum_OTP_secret_size = 40;
+ if(remaining_secret_length > maximum_OTP_secret_size){
+ throw TargetBufferSmallerThanSource(remaining_secret_length, maximum_OTP_secret_size);
+ }
+
+ while (remaining_secret_length>0){
+ const auto bytesToCopy = std::min(sizeof(payload2.data), remaining_secret_length);
+ const auto start = secret_bin.size() - remaining_secret_length;
+ memset(payload2.data, 0, sizeof(payload2.data));
+ vector_copy_ranged(payload2.data, secret_bin, start, bytesToCopy);
+ stick10_08::SendOTPData::CommandTransaction::run(device, payload2);
+ remaining_secret_length -= bytesToCopy;
+ payload2.id++;
+ }
+
+ auto payload = get_payload<stick10_08::WriteToOTPSlot>();
+ strcpyT(payload.temporary_admin_password, temporary_password);
+ strcpyT(payload.slot_token_id, token_ID);
+ payload.use_8_digits = use_8_digits;
+ payload.use_enter = use_enter;
+ payload.use_tokenID = use_tokenID;
+ payload.slot_counter_or_interval = counter_or_interval;
+ payload.slot_number = internal_slot_number;
+ stick10_08::WriteToOTPSlot::CommandTransaction::run(device, payload);
+ }
+
+ void NitrokeyManager::write_TOTP_slot_authorize(uint8_t slot_number, const char *slot_name, const char *secret,
+ uint16_t time_window, bool use_8_digits, bool use_enter,
+ bool use_tokenID, const char *token_ID, const char *temporary_password) {
+ auto payload = get_payload<WriteToTOTPSlot>();
+ payload.slot_number = slot_number;
+ auto secret_bin = misc::hex_string_to_byte(secret);
+ vector_copy(payload.slot_secret, secret_bin);
+ strcpyT(payload.slot_name, slot_name);
+ strcpyT(payload.slot_token_id, token_ID);
+ payload.slot_interval = time_window; //FIXME naming
+ payload.use_8_digits = use_8_digits;
+ payload.use_enter = use_enter;
+ payload.use_tokenID = use_tokenID;
+
+ authorize_packet<WriteToTOTPSlot, Authorize>(payload, temporary_password, device);
+
+ auto resp = WriteToTOTPSlot::CommandTransaction::run(device, payload);
+ }
+
+ char * NitrokeyManager::get_totp_slot_name(uint8_t slot_number) {
+ if (!is_valid_totp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ slot_number = get_internal_slot_number_for_totp(slot_number);
+ return get_slot_name(slot_number);
+ }
+ char * NitrokeyManager::get_hotp_slot_name(uint8_t slot_number) {
+ if (!is_valid_hotp_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ slot_number = get_internal_slot_number_for_hotp(slot_number);
+ return get_slot_name(slot_number);
+ }
+
+ static const int max_string_field_length = 2*1024; //storage's status string is ~1k
+
+ char * NitrokeyManager::get_slot_name(uint8_t slot_number) {
+ auto payload = get_payload<GetSlotName>();
+ payload.slot_number = slot_number;
+ auto resp = GetSlotName::CommandTransaction::run(device, payload);
+ return strndup((const char *) resp.data().slot_name, max_string_field_length);
+ }
+
+ bool NitrokeyManager::first_authenticate(const char *pin, const char *temporary_password) {
+ auto authreq = get_payload<FirstAuthenticate>();
+ strcpyT(authreq.card_password, pin);
+ strcpyT(authreq.temporary_password, temporary_password);
+ FirstAuthenticate::CommandTransaction::run(device, authreq);
+ return true;
+ }
+
+ bool NitrokeyManager::set_time(uint64_t time) {
+ auto p = get_payload<SetTime>();
+ p.reset = 1;
+ p.time = time;
+ SetTime::CommandTransaction::run(device, p);
+ return false;
+ }
+
+ void NitrokeyManager::set_time_soft(uint64_t time) {
+ auto p = get_payload<SetTime>();
+ p.reset = 0;
+ p.time = time;
+ SetTime::CommandTransaction::run(device, p);
+ }
+
+ bool NitrokeyManager::get_time(uint64_t time) {
+ set_time_soft(time);
+ return true;
+ }
+
+ void NitrokeyManager::change_user_PIN(const char *current_PIN, const char *new_PIN) {
+ change_PIN_general<ChangeUserPin, PasswordKind::User>(current_PIN, new_PIN);
+ }
+
+ void NitrokeyManager::change_admin_PIN(const char *current_PIN, const char *new_PIN) {
+ change_PIN_general<ChangeAdminPin, PasswordKind::Admin>(current_PIN, new_PIN);
+ }
+
+ template <typename ProCommand, PasswordKind StoKind>
+ void NitrokeyManager::change_PIN_general(const char *current_PIN, const char *new_PIN) {
+ switch (device->get_device_model()){
+ case DeviceModel::LIBREM:
+ case DeviceModel::PRO:
+ {
+ auto p = get_payload<ProCommand>();
+ strcpyT(p.old_pin, current_PIN);
+ strcpyT(p.new_pin, new_PIN);
+ ProCommand::CommandTransaction::run(device, p);
+ }
+ break;
+ //in Storage change admin/user pin is divided to two commands with 20 chars field len
+ case DeviceModel::STORAGE:
+ {
+ auto p = get_payload<ChangeAdminUserPin20Current>();
+ strcpyT(p.password, current_PIN);
+ p.set_kind(StoKind);
+ auto p2 = get_payload<ChangeAdminUserPin20New>();
+ strcpyT(p2.password, new_PIN);
+ p2.set_kind(StoKind);
+ ChangeAdminUserPin20Current::CommandTransaction::run(device, p);
+ ChangeAdminUserPin20New::CommandTransaction::run(device, p2);
+ }
+ break;
+ }
+
+ }
+
+ void NitrokeyManager::enable_password_safe(const char *user_pin) {
+ //The following command will cancel enabling PWS if it is not supported
+ auto a = get_payload<IsAESSupported>();
+ strcpyT(a.user_password, user_pin);
+ IsAESSupported::CommandTransaction::run(device, a);
+
+ auto p = get_payload<EnablePasswordSafe>();
+ strcpyT(p.user_password, user_pin);
+ EnablePasswordSafe::CommandTransaction::run(device, p);
+ }
+
+ vector <uint8_t> NitrokeyManager::get_password_safe_slot_status() {
+ auto responsePayload = GetPasswordSafeSlotStatus::CommandTransaction::run(device);
+ vector<uint8_t> v = vector<uint8_t>(responsePayload.data().password_safe_status,
+ responsePayload.data().password_safe_status
+ + sizeof(responsePayload.data().password_safe_status));
+ return v;
+ }
+
+ uint8_t NitrokeyManager::get_user_retry_count() {
+ if(device->get_device_model() == DeviceModel::STORAGE){
+ stick20::GetDeviceStatus::CommandTransaction::run(device);
+ }
+ auto response = GetUserPasswordRetryCount::CommandTransaction::run(device);
+ return response.data().password_retry_count;
+ }
+
+ uint8_t NitrokeyManager::get_admin_retry_count() {
+ if(device->get_device_model() == DeviceModel::STORAGE){
+ stick20::GetDeviceStatus::CommandTransaction::run(device);
+ }
+ auto response = GetPasswordRetryCount::CommandTransaction::run(device);
+ return response.data().password_retry_count;
+ }
+
+ void NitrokeyManager::lock_device() {
+ LockDevice::CommandTransaction::run(device);
+ }
+
+ char * NitrokeyManager::get_password_safe_slot_name(uint8_t slot_number) {
+ if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ auto p = get_payload<GetPasswordSafeSlotName>();
+ p.slot_number = slot_number;
+ auto response = GetPasswordSafeSlotName::CommandTransaction::run(device, p);
+ return strndup((const char *) response.data().slot_name, max_string_field_length);
+ }
+
+ bool NitrokeyManager::is_valid_password_safe_slot_number(uint8_t slot_number) const { return slot_number < 16; }
+
+ char * NitrokeyManager::get_password_safe_slot_login(uint8_t slot_number) {
+ if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ auto p = get_payload<GetPasswordSafeSlotLogin>();
+ p.slot_number = slot_number;
+ auto response = GetPasswordSafeSlotLogin::CommandTransaction::run(device, p);
+ return strndup((const char *) response.data().slot_login, max_string_field_length);
+ }
+
+ char * NitrokeyManager::get_password_safe_slot_password(uint8_t slot_number) {
+ if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ auto p = get_payload<GetPasswordSafeSlotPassword>();
+ p.slot_number = slot_number;
+ auto response = GetPasswordSafeSlotPassword::CommandTransaction::run(device, p);
+ return strndup((const char *) response.data().slot_password, max_string_field_length); //FIXME use secure way
+ }
+
+ void NitrokeyManager::write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login,
+ const char *slot_password) {
+ if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ auto p = get_payload<SetPasswordSafeSlotData>();
+ p.slot_number = slot_number;
+ strcpyT(p.slot_name, slot_name);
+ strcpyT(p.slot_password, slot_password);
+ SetPasswordSafeSlotData::CommandTransaction::run(device, p);
+
+ auto p2 = get_payload<SetPasswordSafeSlotData2>();
+ p2.slot_number = slot_number;
+ strcpyT(p2.slot_login_name, slot_login);
+ SetPasswordSafeSlotData2::CommandTransaction::run(device, p2);
+ }
+
+ void NitrokeyManager::erase_password_safe_slot(uint8_t slot_number) {
+ if (!is_valid_password_safe_slot_number(slot_number)) throw InvalidSlotException(slot_number);
+ auto p = get_payload<ErasePasswordSafeSlot>();
+ p.slot_number = slot_number;
+ ErasePasswordSafeSlot::CommandTransaction::run(device, p);
+ }
+
+ void NitrokeyManager::user_authenticate(const char *user_password, const char *temporary_password) {
+ auto p = get_payload<UserAuthenticate>();
+ strcpyT(p.card_password, user_password);
+ strcpyT(p.temporary_password, temporary_password);
+ UserAuthenticate::CommandTransaction::run(device, p);
+ }
+
+ void NitrokeyManager::build_aes_key(const char *admin_password) {
+ switch (device->get_device_model()) {
+ case DeviceModel::LIBREM:
+ case DeviceModel::PRO: {
+ auto p = get_payload<BuildAESKey>();
+ strcpyT(p.admin_password, admin_password);
+ BuildAESKey::CommandTransaction::run(device, p);
+ break;
+ }
+ case DeviceModel::STORAGE : {
+ auto p = get_payload<stick20::CreateNewKeys>();
+ strcpyT(p.password, admin_password);
+ p.set_defaults();
+ stick20::CreateNewKeys::CommandTransaction::run(device, p);
+ break;
+ }
+ }
+ }
+
+ void NitrokeyManager::factory_reset(const char *admin_password) {
+ auto p = get_payload<FactoryReset>();
+ strcpyT(p.admin_password, admin_password);
+ FactoryReset::CommandTransaction::run(device, p);
+ }
+
+ void NitrokeyManager::unlock_user_password(const char *admin_password, const char *new_user_password) {
+ switch (device->get_device_model()){
+ case DeviceModel::LIBREM:
+ case DeviceModel::PRO: {
+ auto p = get_payload<stick10::UnlockUserPassword>();
+ strcpyT(p.admin_password, admin_password);
+ strcpyT(p.user_new_password, new_user_password);
+ stick10::UnlockUserPassword::CommandTransaction::run(device, p);
+ break;
+ }
+ case DeviceModel::STORAGE : {
+ auto p2 = get_payload<ChangeAdminUserPin20Current>();
+ p2.set_defaults();
+ strcpyT(p2.password, admin_password);
+ ChangeAdminUserPin20Current::CommandTransaction::run(device, p2);
+ auto p3 = get_payload<stick20::UnlockUserPin>();
+ p3.set_defaults();
+ strcpyT(p3.password, new_user_password);
+ stick20::UnlockUserPin::CommandTransaction::run(device, p3);
+ break;
+ }
+ }
+ }
+
+
+ void NitrokeyManager::write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock, bool enable_user_password,
+ bool delete_user_password, const char *admin_temporary_password) {
+ auto p = get_payload<stick10_08::WriteGeneralConfig>();
+ p.numlock = numlock;
+ p.capslock = capslock;
+ p.scrolllock = scrolllock;
+ p.enable_user_password = static_cast<uint8_t>(enable_user_password ? 1 : 0);
+ p.delete_user_password = static_cast<uint8_t>(delete_user_password ? 1 : 0);
+ if (is_authorization_command_supported()){
+ authorize_packet<stick10_08::WriteGeneralConfig, Authorize>(p, admin_temporary_password, device);
+ } else {
+ strcpyT(p.temporary_admin_password, admin_temporary_password);
+ }
+ stick10_08::WriteGeneralConfig::CommandTransaction::run(device, p);
+ }
+
+ vector<uint8_t> NitrokeyManager::read_config() {
+ auto responsePayload = GetStatus::CommandTransaction::run(device);
+ vector<uint8_t> v = vector<uint8_t>(responsePayload.data().general_config,
+ responsePayload.data().general_config+sizeof(responsePayload.data().general_config));
+ return v;
+ }
+
+ bool NitrokeyManager::is_authorization_command_supported(){
+ //authorization command is supported for versions equal or below:
+ auto m = std::unordered_map<DeviceModel , int, EnumClassHash>({
+ {DeviceModel::PRO, 7},
+ {DeviceModel::LIBREM, 7},
+ {DeviceModel::STORAGE, 53},
+ });
+ return get_minor_firmware_version() <= m[device->get_device_model()];
+ }
+
+ bool NitrokeyManager::is_320_OTP_secret_supported(){
+ // 320 bit OTP secret is supported by version bigger or equal to:
+ auto m = std::unordered_map<DeviceModel , int, EnumClassHash>({
+ {DeviceModel::PRO, 8},
+ {DeviceModel::LIBREM, 8},
+ {DeviceModel::STORAGE, 54},
+ });
+ return get_minor_firmware_version() >= m[device->get_device_model()];
+ }
+
+ DeviceModel NitrokeyManager::get_connected_device_model() const{
+ if (device == nullptr){
+ throw DeviceNotConnected("device not connected");
+ }
+ return device->get_device_model();
+ }
+
+ bool NitrokeyManager::is_smartcard_in_use(){
+ try{
+ stick20::CheckSmartcardUsage::CommandTransaction::run(device);
+ }
+ catch(const CommandFailedException & e){
+ return e.reason_smartcard_busy();
+ }
+ return false;
+ }
+
+ uint8_t NitrokeyManager::get_minor_firmware_version(){
+ switch(device->get_device_model()){
+ case DeviceModel::LIBREM:
+ case DeviceModel::PRO:{
+ auto status_p = GetStatus::CommandTransaction::run(device);
+ return status_p.data().firmware_version_st.minor; //7 or 8
+ }
+ case DeviceModel::STORAGE:{
+ auto status = stick20::GetDeviceStatus::CommandTransaction::run(device);
+ auto test_firmware = status.data().versionInfo.build_iteration != 0;
+ if (test_firmware)
+ LOG("Development firmware detected. Increasing minor version number.", nitrokey::log::Loglevel::WARNING);
+ return status.data().versionInfo.minor + (test_firmware? 1 : 0);
+ }
+ }
+ return 0;
+ }
+ uint8_t NitrokeyManager::get_major_firmware_version(){
+ switch(device->get_device_model()){
+ case DeviceModel::LIBREM:
+ case DeviceModel::PRO:{
+ auto status_p = GetStatus::CommandTransaction::run(device);
+ return status_p.data().firmware_version_st.major; //0
+ }
+ case DeviceModel::STORAGE:{
+ auto status = stick20::GetDeviceStatus::CommandTransaction::run(device);
+ return status.data().versionInfo.major;
+ }
+ }
+ return 0;
+ }
+
+ bool NitrokeyManager::is_AES_supported(const char *user_password) {
+ auto a = get_payload<IsAESSupported>();
+ strcpyT(a.user_password, user_password);
+ IsAESSupported::CommandTransaction::run(device, a);
+ return true;
+ }
+
+ //storage commands
+
+ void NitrokeyManager::send_startup(uint64_t seconds_from_epoch){
+ auto p = get_payload<stick20::SendStartup>();
+// p.set_defaults(); //set current time
+ p.localtime = seconds_from_epoch;
+ stick20::SendStartup::CommandTransaction::run(device, p);
+ }
+
+ void NitrokeyManager::unlock_encrypted_volume(const char* user_pin){
+ misc::execute_password_command<stick20::EnableEncryptedPartition>(device, user_pin);
+ }
+
+ void NitrokeyManager::unlock_hidden_volume(const char* hidden_volume_password) {
+ misc::execute_password_command<stick20::EnableHiddenEncryptedPartition>(device, hidden_volume_password);
+ }
+
+ void NitrokeyManager::set_encrypted_volume_read_only(const char* admin_pin) {
+ misc::execute_password_command<stick20::SetEncryptedVolumeReadOnly>(device, admin_pin);
+ }
+
+ void NitrokeyManager::set_encrypted_volume_read_write(const char* admin_pin) {
+ misc::execute_password_command<stick20::SetEncryptedVolumeReadWrite>(device, admin_pin);
+ }
+
+ //TODO check is encrypted volume unlocked before execution
+ //if not return library exception
+ 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<stick20::SetupHiddenVolume>();
+ 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_admin(const char* admin_pin) {
+ //from v0.49, v0.52+ it needs Admin PIN
+ if (set_unencrypted_volume_rorw_pin_type_user()){
+ LOG("set_unencrypted_read_only_admin is not supported for this version of Storage device. "
+ "Please update firmware to v0.52+. Doing nothing.", nitrokey::log::Loglevel::WARNING);
+ return;
+ }
+ misc::execute_password_command<stick20::SetUnencryptedVolumeReadOnlyAdmin>(device, admin_pin);
+ }
+
+ void NitrokeyManager::set_unencrypted_read_only(const char *user_pin) {
+ //until v0.48 (incl. v0.50 and v0.51) User PIN was sufficient
+ LOG("set_unencrypted_read_only is deprecated. Use set_unencrypted_read_only_admin instead.",
+ nitrokey::log::Loglevel::WARNING);
+ if (!set_unencrypted_volume_rorw_pin_type_user()){
+ LOG("set_unencrypted_read_only is not supported for this version of Storage device. Doing nothing.",
+ nitrokey::log::Loglevel::WARNING);
+ return;
+ }
+ misc::execute_password_command<stick20::SendSetReadonlyToUncryptedVolume>(device, user_pin);
+ }
+
+ void NitrokeyManager::set_unencrypted_read_write_admin(const char* admin_pin) {
+ //from v0.49, v0.52+ it needs Admin PIN
+ if (set_unencrypted_volume_rorw_pin_type_user()){
+ LOG("set_unencrypted_read_write_admin is not supported for this version of Storage device. "
+ "Please update firmware to v0.52+. Doing nothing.", nitrokey::log::Loglevel::WARNING);
+ return;
+ }
+ misc::execute_password_command<stick20::SetUnencryptedVolumeReadWriteAdmin>(device, admin_pin);
+ }
+
+ void NitrokeyManager::set_unencrypted_read_write(const char *user_pin) {
+ //until v0.48 (incl. v0.50 and v0.51) User PIN was sufficient
+ LOG("set_unencrypted_read_write is deprecated. Use set_unencrypted_read_write_admin instead.",
+ nitrokey::log::Loglevel::WARNING);
+ if (!set_unencrypted_volume_rorw_pin_type_user()){
+ LOG("set_unencrypted_read_write is not supported for this version of Storage device. Doing nothing.",
+ nitrokey::log::Loglevel::WARNING);
+ return;
+ }
+ misc::execute_password_command<stick20::SendSetReadwriteToUncryptedVolume>(device, user_pin);
+ }
+
+ bool NitrokeyManager::set_unencrypted_volume_rorw_pin_type_user(){
+ auto minor_firmware_version = get_minor_firmware_version();
+ return minor_firmware_version <= 48 || minor_firmware_version == 50 || minor_firmware_version == 51;
+ }
+
+ void NitrokeyManager::export_firmware(const char* admin_pin) {
+ misc::execute_password_command<stick20::ExportFirmware>(device, admin_pin);
+ }
+
+ void NitrokeyManager::enable_firmware_update(const char* firmware_pin) {
+ misc::execute_password_command<stick20::EnableFirmwareUpdate>(device, firmware_pin);
+ }
+
+ void NitrokeyManager::clear_new_sd_card_warning(const char* admin_pin) {
+ misc::execute_password_command<stick20::SendClearNewSdCardFound>(device, admin_pin);
+ }
+
+ void NitrokeyManager::fill_SD_card_with_random_data(const char* admin_pin) {
+ auto p = get_payload<stick20::FillSDCardWithRandomChars>();
+ 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<stick20::ChangeUpdatePassword>();
+ strcpyT(p.current_update_password, current_update_password);
+ strcpyT(p.new_update_password, new_update_password);
+ stick20::ChangeUpdatePassword::CommandTransaction::run(device, p);
+ }
+
+ char * NitrokeyManager::get_status_storage_as_string(){
+ auto p = stick20::GetDeviceStatus::CommandTransaction::run(device);
+ return strndup(p.data().dissect().c_str(), max_string_field_length);
+ }
+
+ stick20::DeviceConfigurationResponsePacket::ResponsePayload NitrokeyManager::get_status_storage(){
+ auto p = stick20::GetDeviceStatus::CommandTransaction::run(device);
+ return p.data();
+ }
+
+ char * NitrokeyManager::get_SD_usage_data_as_string(){
+ auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(device);
+ return strndup(p.data().dissect().c_str(), max_string_field_length);
+ }
+
+ std::pair<uint8_t,uint8_t> NitrokeyManager::get_SD_usage_data(){
+ auto p = stick20::GetSDCardOccupancy::CommandTransaction::run(device);
+ return std::make_pair(p.data().WriteLevelMin, p.data().WriteLevelMax);
+ }
+
+ int NitrokeyManager::get_progress_bar_value(){
+ try{
+ stick20::GetDeviceStatus::CommandTransaction::run(device);
+ return -1;
+ }
+ catch (LongOperationInProgressException &e){
+ return e.progress_bar_value;
+ }
+ }
+
+ string NitrokeyManager::get_TOTP_code(uint8_t slot_number, const char *user_temporary_password) {
+ return get_TOTP_code(slot_number, 0, 0, 0, user_temporary_password);
+ }
+
+ /**
+ * Returns ReadSlot structure, describing OTP slot configuration. Always return binary counter -
+ * does the necessary conversion, if needed, to unify the behavior across Pro and Storage.
+ * @private For internal use only
+ * @param slot_number which OTP slot to use (usual format)
+ * @return ReadSlot structure
+ */
+ stick10::ReadSlot::ResponsePayload NitrokeyManager::get_OTP_slot_data(const uint8_t slot_number) {
+ auto p = get_payload<stick10::ReadSlot>();
+ p.slot_number = slot_number;
+ p.data_format = stick10::ReadSlot::CounterFormat::BINARY; // ignored for devices other than Storage v0.54+
+ auto data = stick10::ReadSlot::CommandTransaction::run(device, p);
+
+ auto &payload = data.data();
+
+ // if fw <=v0.53 and asked binary - do the conversion from ASCII
+ if (device->get_device_model() == DeviceModel::STORAGE && get_minor_firmware_version() <= 53
+ && is_internal_hotp_slot_number(slot_number))
+ {
+ //convert counter from string to ull
+ auto counter_s = std::string(payload.slot_counter_s, payload.slot_counter_s + sizeof(payload.slot_counter_s));
+ payload.slot_counter = std::stoull(counter_s);
+ }
+
+ return payload;
+ }
+
+ stick10::ReadSlot::ResponsePayload NitrokeyManager::get_TOTP_slot_data(const uint8_t slot_number) {
+ return get_OTP_slot_data(get_internal_slot_number_for_totp(slot_number));
+ }
+
+ stick10::ReadSlot::ResponsePayload NitrokeyManager::get_HOTP_slot_data(const uint8_t slot_number) {
+ return get_OTP_slot_data(get_internal_slot_number_for_hotp(slot_number));
+ }
+
+ void NitrokeyManager::lock_encrypted_volume() {
+ misc::execute_password_command<stick20::DisableEncryptedPartition>(device, "");
+ }
+
+ void NitrokeyManager::lock_hidden_volume() {
+ misc::execute_password_command<stick20::DisableHiddenEncryptedPartition>(device, "");
+ }
+
+ uint8_t NitrokeyManager::get_SD_card_size() {
+ auto data = stick20::ProductionTest::CommandTransaction::run(device);
+ return data.data().SD_Card_Size_u8;
+ }
+
+ const string NitrokeyManager::get_current_device_id() const {
+ return current_device_id;
+ }
+
+ void NitrokeyManager::wink(){
+ stick20::Wink::CommandTransaction::run(device);
+ };
+
+ stick20::ProductionTest::ResponsePayload NitrokeyManager::production_info(){
+ auto data = stick20::ProductionTest::CommandTransaction::run(device);
+ return data.data();
+ };
+
+ void NitrokeyManager::enable_firmware_update_pro(const char *firmware_pin) {
+ auto p = get_payload<FirmwareUpdate>();
+ strcpyT(p.firmware_password, firmware_pin);
+ FirmwareUpdate::CommandTransaction::run(device, p);
+ }
+
+ void
+ NitrokeyManager::change_firmware_update_password_pro(const char *firmware_pin_current, const char *firmware_pin_new) {
+ auto p = get_payload<FirmwarePasswordChange>();
+ strcpyT(p.firmware_password_current, firmware_pin_current);
+ strcpyT(p.firmware_password_new, firmware_pin_new);
+ FirmwarePasswordChange::CommandTransaction::run(device, p);
+ }
+
+}
diff --git a/libnitrokey-v3.6/README.md b/libnitrokey-v3.6/README.md
new file mode 100644
index 0000000..aa5ca1a
--- /dev/null
+++ b/libnitrokey-v3.6/README.md
@@ -0,0 +1,374 @@
+[![Build Status](https://travis-ci.org/Nitrokey/libnitrokey.svg?branch=master)](https://travis-ci.org/Nitrokey/libnitrokey)
+[![Waffle.io - Columns and their card count](https://badge.waffle.io/Nitrokey/libnitrokey.svg?columns=ready,in%20progress,test,waiting%20for%20feedback)](https://waffle.io/Nitrokey/libnitrokey)
+
+# libnitrokey
+libnitrokey is a project to communicate with Nitrokey Pro and Storage devices in a clean and easy manner. Written in C++14, testable with `py.test` and `Catch` frameworks, with C API, Python access (through CFFI and C API, in future with Pybind11).
+
+The development of this project is aimed to make it itself a living documentation of communication protocol between host and the Nitrokey stick devices. The command packets' format is described here: [Pro v0.7](libnitrokey/stick10_commands.h), [Pro v0.8](libnitrokey/stick10_commands_0.8.h), [Storage](libnitrokey/stick20_commands.h). Handling and additional operations are described here: [NitrokeyManager.cc](NitrokeyManager.cc).
+
+A C++14 complying compiler is required due to heavy use of variable templates. For feature support tables please check [table 1](https://gcc.gnu.org/projects/cxx-status.html#cxx14) or [table 2](http://en.cppreference.com/w/cpp/compiler_support).
+
+libnitrokey is developed and tested with the latest compilers: g++ 6.2, clang 3.8. We use Travis CI to test builds also on g++ 5.4 and under OSX compilers starting up from xcode 8.2 environment.
+
+## Getting sources
+This repository uses `git submodules`.
+To clone please use git's `--recursive` option like in:
+```bash
+git clone --recursive https://github.com/Nitrokey/libnitrokey.git
+```
+or for already cloned repository:
+```bash
+git clone https://github.com/Nitrokey/libnitrokey.git
+cd libnitrokey
+git submodule update --init --recursive
+```
+
+## Dependencies
+Following libraries are needed to use libnitrokey on Linux (names of the packages on Ubuntu):
+- libhidapi-dev [(HID API)](http://www.signal11.us/oss/hidapi/)
+- libusb-1.0-0-dev
+
+
+## Compilation
+libnitrokey uses CMake as its main build system. As a secondary option it offers building through Qt's qMake.
+### Qt
+A Qt's .pro project file is provided for direct compilation and for inclusion to other projects.
+Using it directly is not recommended due to lack of dependencies check and not implemented library versioning.
+Compilation is tested with Qt 5.6 and greater.
+
+Quick start example:
+```bash
+mkdir -p build
+cd build
+qmake ..
+make -j2
+```
+
+### Windows and Visual Studio 2017
+Lately Visual Studio has started handling CMake files directly. After opening the project's directory it should recognize it and initialize build system. Afterwards please run:
+1. `CMake -> Cache -> View Cache CMakeLists.txt -> CMakeLists.txt` to edit settings
+2. `CMake -> Build All` to build
+
+It is possible too to use CMake GUI directly with its settings editor.
+
+### CMake
+To compile please run following sequence of commands:
+```bash
+# assuming current dir is ./libnitrokey/
+mkdir -p build
+cd build
+cmake .. <OPTIONS>
+make -j2
+```
+
+By default (with empty `<OPTIONS>` string) this will create in `build/` directory a shared library (.so, .dll or .dynlib). If you wish to build static version you can use as `<OPTIONS>` string `-DBUILD_SHARED_LIBS=OFF`.
+
+All options could be listed with `cmake .. -L` or instead `cmake` a `ccmake ..` tool could be used for configuration (where `..` is the path to directory with `CMakeLists.txt` file). `ccmake` shows also description of the build parameters.
+
+If you have trouble compiling or running the library you can check [.travis.yml](.travis.yml) file for configuration details. This file is used by Travis CI service to make test builds on OSX and Ubuntu 14.04.
+
+Other build options (all take either `ON` or `OFF`):
+* ADD_ASAN - add tests for memory leaks and out-of-bounds access
+* ADD_TSAN - add tests for threads race, needs USE_CLANG
+* COMPILE_TESTS - compile C++ tests
+* COMPILE_OFFLINE_TESTS - compile C++ tests, that do not require any device to be connected
+* LOG_VOLATILE_DATA (default: OFF) - include secrets in log (PWS passwords, PINs etc)
+* NO_LOG (default: OFF) - do not compile LOG statements - will make library smaller, but without any diagnostic messages
+
+
+### Meson
+It is possible to use Meson and Ninja to build the project as well (currently available only `master` branch).
+Please run:
+```
+meson builddir <OPTIONS>
+meson configure builddir # to show available build flags
+ninja -C builddir
+```
+
+# Using libnitrokey with Python
+To use libnitrokey with Python a [CFFI](http://cffi.readthedocs.io/en/latest/overview.html) library is required (either 2.7+ or 3.0+). It can be installed with:
+```bash
+pip install --user cffi # for python 2.x
+pip3 install cffi # for python 3.x
+```
+## Python2
+Just import it, read the C API header and it is done! You have access to the library. Here is an example (in Python 2) printing HOTP code for Pro or Storage device, assuming it is run in root directory [(full example)](python_bindings_example.py):
+```python
+#!/usr/bin/env python2
+import cffi
+
+ffi = cffi.FFI()
+get_string = ffi.string
+
+def get_library():
+ fp = 'NK_C_API.h' # path to C API header
+
+ declarations = []
+ with open(fp, 'r') as f:
+ declarations = f.readlines()
+
+ cnt = 0
+ a = iter(declarations)
+ for declaration in a:
+ if declaration.strip().startswith('NK_C_API'):
+ declaration = declaration.replace('NK_C_API', '').strip()
+ while ';' not in declaration:
+ declaration += (next(a)).strip()
+ # print(declaration)
+ ffi.cdef(declaration, override=True)
+ cnt +=1
+ print('Imported {} declarations'.format(cnt))
+
+
+ C = None
+ import os, sys
+ path_build = os.path.join(".", "build")
+ paths = [
+ os.environ.get('LIBNK_PATH', None),
+ os.path.join(path_build,"libnitrokey.so"),
+ os.path.join(path_build,"libnitrokey.dylib"),
+ os.path.join(path_build,"libnitrokey.dll"),
+ os.path.join(path_build,"nitrokey.dll"),
+ ]
+ for p in paths:
+ if not p: continue
+ print("Trying " +p)
+ p = os.path.abspath(p)
+ if os.path.exists(p):
+ print("Found: "+p)
+ C = ffi.dlopen(p)
+ break
+ else:
+ print("File does not exist: " + p)
+ if not C:
+ print("No library file found")
+ sys.exit(1)
+
+ return C
+
+
+def get_hotp_code(lib, i):
+ return lib.NK_get_hotp_code(i)
+
+
+libnitrokey = get_library()
+libnitrokey.NK_set_debug(False) # do not show debug messages (log library only)
+
+hotp_slot_code = get_hotp_code(libnitrokey, 1)
+print('Getting HOTP code from Nitrokey device: ')
+print(hotp_slot_code)
+libnitrokey.NK_logout() # disconnect device
+```
+In case no devices are connected, a friendly message will be printed.
+All available functions for C and Python are listed in [NK_C_API.h](NK_C_API.h). Please check `Documentation` section below.
+
+## Python3
+Just import it, read the C API header and it is done! You have access to the library. Here is an example (in Python 3) printing HOTP code for Pro or Storage device, assuming it is run in root directory [(full example)](python3_bindings_example.py):
+```python
+#!/usr/bin/env python3
+import cffi
+
+ffi = cffi.FFI()
+get_string = ffi.string
+
+def get_library():
+ fp = 'NK_C_API.h' # path to C API header
+
+ declarations = []
+ with open(fp, 'r') as f:
+ declarations = f.readlines()
+
+ cnt = 0
+ a = iter(declarations)
+ for declaration in a:
+ if declaration.strip().startswith('NK_C_API'):
+ declaration = declaration.replace('NK_C_API', '').strip()
+ while ';' not in declaration:
+ declaration += (next(a)).strip()
+ # print(declaration)
+ ffi.cdef(declaration, override=True)
+ cnt +=1
+ print('Imported {} declarations'.format(cnt))
+
+
+ C = None
+ import os, sys
+ path_build = os.path.join(".", "build")
+ paths = [
+ os.environ.get('LIBNK_PATH', None),
+ os.path.join(path_build,"libnitrokey.so"),
+ os.path.join(path_build,"libnitrokey.dylib"),
+ os.path.join(path_build,"libnitrokey.dll"),
+ os.path.join(path_build,"nitrokey.dll"),
+ ]
+ for p in paths:
+ if not p: continue
+ print("Trying " +p)
+ p = os.path.abspath(p)
+ if os.path.exists(p):
+ print("Found: "+p)
+ C = ffi.dlopen(p)
+ break
+ else:
+ print("File does not exist: " + p)
+ if not C:
+ print("No library file found")
+ sys.exit(1)
+
+ return C
+
+
+def get_hotp_code(lib, i):
+ return lib.NK_get_hotp_code(i)
+
+def connect_device(lib):
+ # lib.NK_login('S'.encode('ascii')) # connect only to Nitrokey Storage device
+ # lib.NK_login('P'.encode('ascii')) # connect only to Nitrokey Pro device
+ device_connected = lib.NK_login_auto() # connect to any Nitrokey Stick
+ if device_connected:
+ print('Connected to Nitrokey device!')
+ else:
+ print('Could not connect to Nitrokey device!')
+ exit()
+
+libnitrokey = get_library()
+libnitrokey.NK_set_debug(False) # do not show debug messages (log library only)
+
+connect_device(libnitrokey)
+
+hotp_slot_code = get_hotp_code(libnitrokey, 1)
+print('Getting HOTP code from Nitrokey device: ')
+print(ffi.string(hotp_slot_code).decode('ascii'))
+libnitrokey.NK_logout() # disconnect device
+```
+
+In case no devices are connected, a friendly message will be printed.
+All available functions for C and Python are listed in [NK_C_API.h](NK_C_API.h). Please check `Documentation` section below.
+
+## Documentation
+The documentation of C API is included in the sources (can be generated with `make doc` if Doxygen is installed).
+Please check [NK_C_API.h](NK_C_API.h) (C API) for high level commands and [libnitrokey/NitrokeyManager.h](libnitrokey/NitrokeyManager.h) (C++ API). All devices' commands are listed along with packet format in [libnitrokey/stick10_commands.h](libnitrokey/stick10_commands.h) and [libnitrokey/stick20_commands.h](libnitrokey/stick20_commands.h) respectively for Nitrokey Pro and Nitrokey Storage products.
+
+# Tests
+**Warning!** Most of the tests will overwrite user data. The only user-data safe tests are specified in `unittest/test_safe.cpp` (see *C++ tests* chapter).
+
+**Warning!** Before you run unittests please change both your Admin and User PINs on your Nitrostick to defaults (`12345678` and `123456` respectively), or change the values in tests source code. If you do not change them, the tests might lock your device temporarily. If it's too late already, you can reset your Nitrokey using instructions from [homepage](https://www.nitrokey.com/de/documentation/how-reset-nitrokey).
+
+## Python tests
+libnitrokey has a great suite of tests written in Python 3 under the path: [unittest/test_*.py](https://github.com/Nitrokey/libnitrokey/tree/master/unittest):
+* `test_pro.py` - contains tests of OTP, Password Safe and PIN control functionality. Could be run on both Pro and Storage devices.
+* `test_storage.py` - contains tests of Encrypted Volumes functionality. Could be run only on Storage.
+
+The tests themselves show how to handle common requests to device.
+Before running please install all required libraries with:
+```bash
+cd unittest
+pip install --user -r requirements.txt
+```
+or use Python's environment managing tool like [pipenv](https://pipenv.readthedocs.io/en/latest/) or `virtualenv`.
+
+
+To run them please execute:
+```bash
+# substitute <dev> with either 'pro' or 'storage'
+py.test -v test_<dev>.py
+# more specific use - run tests containing in name <test_name> 5 times:
+py.test -v test_<dev>.py -k <test_name> --count 5
+
+```
+For additional documentation please check the following for [py.test installation](http://doc.pytest.org/en/latest/getting-started.html). For better coverage [randomly plugin](https://pypi.python.org/pypi/pytest-randomly) is installed - it randomizes the test order allowing to detect unseen dependencies between the tests.
+
+## C++ tests
+There are also some unit tests implemented in C++, placed in unittest directory. The only user-data safe online test set here is [test_safe.cpp](https://github.com/Nitrokey/libnitrokey/blob/master/unittest/test_safe.cpp), which tries to connect to the device, and collect its status data. Example run for Storage:
+```text
+# Storage device inserted, firmware version v0.53
+$ ./test_safe
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] => GET_DEVICE_STATUS
+..
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] <= GET_DEVICE_STATUS 0 1
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] => GET_PASSWORD_RETRY_COUNT
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] <= GET_PASSWORD_RETRY_COUNT 0 0
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] => GET_DEVICE_STATUS
+..
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] <= GET_DEVICE_STATUS 0 1
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] => GET_USER_PASSWORD_RETRY_COUNT
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] <= GET_USER_PASSWORD_RETRY_COUNT 0 0
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] => GET_DEVICE_STATUS
+...
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] <= GET_DEVICE_STATUS 0 1
+ transmission_data.dissect(): _padding:
+0000 00 00 00 00 00 00 00 00 00 00 00 00 00 05 2e 01 ................
+0010 00 00 -- -- -- -- -- -- -- -- -- -- -- -- -- -- ..
+ (int) SendCounter_u8: 0
+ (int) SendDataType_u8: 3
+ (int) FollowBytesFlag_u8: 0
+ (int) SendSize_u8: 28
+
+ MagicNumber_StickConfig_u16: 13080
+ (int) ReadWriteFlagUncryptedVolume_u8: 1
+ (int) ReadWriteFlagCryptedVolume_u8: 0
+ (int) ReadWriteFlagHiddenVolume_u8: 0
+ (int) versionInfo.major: 0
+ (int) versionInfo.minor: 53
+ (int) versionInfo.build_iteration: 0
+ (int) FirmwareLocked_u8: 0
+ (int) NewSDCardFound_u8: 1
+ (int) NewSDCardFound_st.NewCard: 1
+ (int) NewSDCardFound_st.Counter: 0
+ (int) SDFillWithRandomChars_u8: 1
+ ActiveSD_CardID_u32: 3670817656
+ (int) VolumeActiceFlag_u8: 1
+ (int) VolumeActiceFlag_st.unencrypted: 1
+ (int) VolumeActiceFlag_st.encrypted: 0
+ (int) VolumeActiceFlag_st.hidden: 0
+ (int) NewSmartCardFound_u8: 0
+ (int) UserPwRetryCount: 3
+ (int) AdminPwRetryCount: 3
+ ActiveSmartCardID_u32: 24122
+ (int) StickKeysNotInitiated: 0
+
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] => GET_DEVICE_STATUS
+..
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] <= GET_DEVICE_STATUS 0 1
+00005e3a
+[Wed Jan 2 13:31:17 2019][DEBUG_L1] => GET_DEVICE_STATUS
+....
+[Wed Jan 2 13:31:18 2019][DEBUG_L1] <= GET_DEVICE_STATUS 0 1
+[Wed Jan 2 13:31:18 2019][DEBUG_L1] => GET_DEVICE_STATUS
+...
+[Wed Jan 2 13:31:18 2019][DEBUG_L1] <= GET_DEVICE_STATUS 0 1
+===============================================================================
+All tests passed (18 assertions in 6 test cases)
+```
+Test's execution configuration and verbosity could be manipulated - please see `./test_safe --help` for details.
+
+The other tests sets are not written as extensively as Python tests and are rather more a C++ low level interface check used during the library development, using either low-level components, C API from `NK_C_API.cc`, or C++ API from `NitrokeyManager.cc`. Some of them are: [test_HOTP.cc](https://github.com/Nitrokey/libnitrokey/blob/master/unittest/test_HOTP.cc),
+[test1.cc](https://github.com/Nitrokey/libnitrokey/blob/master/unittest/test1.cc). See more in [unittest](https://github.com/Nitrokey/libnitrokey/tree/master/unittest) directory.
+
+**Note: these are not device model agnostic, and will most probably destroy your data on the device.**
+
+
+Unit tests were checked on Ubuntu 16.04/16.10/17.04. To run them just execute binaries built in `./libnitrokey/build` dir, after enabling them by passing `-DCOMPILE_TESTS=ON` option to `cmake` - e.g.: `cmake .. -DCOMPILE_TESTS=ON && make`.
+
+
+The documentation of how it works could be found in nitrokey-app project's README on Github:
+[Nitrokey-app - internals](https://github.com/Nitrokey/nitrokey-app/blob/master/README.md#internals).
+
+To peek/debug communication with device running nitrokey-app (0.x branch) in debug mode (`-d` switch) and checking the logs
+(right click on tray icon and then 'Debug') might be helpful. Latest Nitrokey App (1.x branch) uses libnitrokey to communicate with device. Once run with `--dl 3` (3 or higher; range 0-5) it will print all communication to the console. Additionally crosschecking with
+firmware code should show how things works:
+[report_protocol.c](https://github.com/Nitrokey/nitrokey-pro-firmware/blob/master/src/keyboard/report_protocol.c)
+(for Nitrokey Pro, for Storage similarly).
+
+# Known issues / tasks
+* Currently only one device can be connected at a time (experimental work could be found in `wip-multiple_devices` branch),
+* C++ API needs some reorganization to C++ objects (instead of pointers to byte arrays). This will be also preparing for integration with Pybind11,
+* Fix compilation warnings.
+
+Other tasks might be listed either in [TODO](TODO) file or on project's issues page.
+
+# License
+This project is licensed under LGPL version 3. License text could be found under [LICENSE](LICENSE) file.
+
+# Roadmap
+To check what issues will be fixed and when please check [milestones](https://github.com/Nitrokey/libnitrokey/milestones) page.
diff --git a/libnitrokey-v3.6/command_id.cc b/libnitrokey-v3.6/command_id.cc
new file mode 100644
index 0000000..90f300f
--- /dev/null
+++ b/libnitrokey-v3.6/command_id.cc
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include <assert.h>
+#include "command_id.h"
+
+namespace nitrokey {
+namespace proto {
+
+const char *commandid_to_string(CommandID id) {
+#ifdef NO_LOG
+ return "";
+#endif
+ switch (id) {
+ case CommandID::GET_STATUS:
+ return "GET_STATUS";
+ case CommandID::WRITE_TO_SLOT:
+ return "WRITE_TO_SLOT";
+ case CommandID::READ_SLOT_NAME:
+ return "READ_SLOT_NAME";
+ case CommandID::READ_SLOT:
+ return "READ_SLOT";
+ case CommandID::GET_CODE:
+ return "GET_CODE";
+ case CommandID::WRITE_CONFIG:
+ return "WRITE_CONFIG";
+ case CommandID::ERASE_SLOT:
+ return "ERASE_SLOT";
+ case CommandID::FIRST_AUTHENTICATE:
+ return "FIRST_AUTHENTICATE";
+ case CommandID::AUTHORIZE:
+ return "AUTHORIZE";
+ case CommandID::GET_PASSWORD_RETRY_COUNT:
+ return "GET_PASSWORD_RETRY_COUNT";
+ case CommandID::CLEAR_WARNING:
+ return "CLEAR_WARNING";
+ case CommandID::SET_TIME:
+ return "SET_TIME";
+ case CommandID::TEST_COUNTER:
+ return "TEST_COUNTER";
+ case CommandID::TEST_TIME:
+ return "TEST_TIME";
+ case CommandID::USER_AUTHENTICATE:
+ return "USER_AUTHENTICATE";
+ case CommandID::GET_USER_PASSWORD_RETRY_COUNT:
+ return "GET_USER_PASSWORD_RETRY_COUNT";
+ case CommandID::USER_AUTHORIZE:
+ return "USER_AUTHORIZE";
+ case CommandID::UNLOCK_USER_PASSWORD:
+ return "UNLOCK_USER_PASSWORD";
+ case CommandID::LOCK_DEVICE:
+ return "LOCK_DEVICE";
+ case CommandID::FACTORY_RESET:
+ return "FACTORY_RESET";
+ case CommandID::CHANGE_USER_PIN:
+ return "CHANGE_USER_PIN";
+ case CommandID::CHANGE_ADMIN_PIN:
+ return "CHANGE_ADMIN_PIN";
+ case CommandID::FIRMWARE_UPDATE:
+ return "FIRMWARE_UPDATE";
+ case CommandID::FIRMWARE_PASSWORD_CHANGE:
+ return "FIRMWARE_PASSWORD_CHANGE";
+
+ case CommandID::ENABLE_CRYPTED_PARI:
+ return "ENABLE_CRYPTED_PARI";
+ case CommandID::DISABLE_CRYPTED_PARI:
+ return "DISABLE_CRYPTED_PARI";
+ case CommandID::ENABLE_HIDDEN_CRYPTED_PARI:
+ return "ENABLE_HIDDEN_CRYPTED_PARI";
+ case CommandID::DISABLE_HIDDEN_CRYPTED_PARI:
+ return "DISABLE_HIDDEN_CRYPTED_PARI";
+ case CommandID::ENABLE_FIRMWARE_UPDATE:
+ return "ENABLE_FIRMWARE_UPDATE";
+ case CommandID::EXPORT_FIRMWARE_TO_FILE:
+ return "EXPORT_FIRMWARE_TO_FILE";
+ case CommandID::GENERATE_NEW_KEYS:
+ return "GENERATE_NEW_KEYS";
+ case CommandID::FILL_SD_CARD_WITH_RANDOM_CHARS:
+ return "FILL_SD_CARD_WITH_RANDOM_CHARS";
+
+ case CommandID::WRITE_STATUS_DATA:
+ return "WRITE_STATUS_DATA";
+ case CommandID::ENABLE_READONLY_UNCRYPTED_LUN:
+ return "ENABLE_READONLY_UNCRYPTED_LUN";
+ case CommandID::ENABLE_READWRITE_UNCRYPTED_LUN:
+ return "ENABLE_READWRITE_UNCRYPTED_LUN";
+
+ case CommandID::SEND_PASSWORD_MATRIX:
+ return "SEND_PASSWORD_MATRIX";
+ case CommandID::SEND_PASSWORD_MATRIX_PINDATA:
+ return "SEND_PASSWORD_MATRIX_PINDATA";
+ case CommandID::SEND_PASSWORD_MATRIX_SETUP:
+ return "SEND_PASSWORD_MATRIX_SETUP";
+
+ case CommandID::GET_DEVICE_STATUS:
+ return "GET_DEVICE_STATUS";
+ case CommandID::SEND_DEVICE_STATUS:
+ return "SEND_DEVICE_STATUS";
+
+ case CommandID::SEND_HIDDEN_VOLUME_PASSWORD:
+ return "SEND_HIDDEN_VOLUME_PASSWORD";
+ case CommandID::SEND_HIDDEN_VOLUME_SETUP:
+ return "SEND_HIDDEN_VOLUME_SETUP";
+ case CommandID::SEND_PASSWORD:
+ return "SEND_PASSWORD";
+ case CommandID::SEND_NEW_PASSWORD:
+ return "SEND_NEW_PASSWORD";
+ case CommandID::CLEAR_NEW_SD_CARD_FOUND:
+ return "CLEAR_NEW_SD_CARD_FOUND";
+
+ case CommandID::SEND_STARTUP:
+ return "SEND_STARTUP";
+ case CommandID::SEND_CLEAR_STICK_KEYS_NOT_INITIATED:
+ return "SEND_CLEAR_STICK_KEYS_NOT_INITIATED";
+ case CommandID::SEND_LOCK_STICK_HARDWARE:
+ return "SEND_LOCK_STICK_HARDWARE";
+
+ case CommandID::PRODUCTION_TEST:
+ return "PRODUCTION_TEST";
+ case CommandID::SEND_DEBUG_DATA:
+ return "SEND_DEBUG_DATA";
+
+ case CommandID::CHANGE_UPDATE_PIN:
+ return "CHANGE_UPDATE_PIN";
+
+ case CommandID::ENABLE_ADMIN_READONLY_UNCRYPTED_LUN:
+ return "ENABLE_ADMIN_READONLY_UNCRYPTED_LUN";
+ case CommandID::ENABLE_ADMIN_READWRITE_UNCRYPTED_LUN:
+ return "ENABLE_ADMIN_READWRITE_UNCRYPTED_LUN";
+ case CommandID::ENABLE_ADMIN_READONLY_ENCRYPTED_LUN:
+ return "ENABLE_ADMIN_READONLY_ENCRYPTED_LUN";
+ case CommandID::ENABLE_ADMIN_READWRITE_ENCRYPTED_LUN:
+ return "ENABLE_ADMIN_READWRITE_ENCRYPTED_LUN";
+ case CommandID::CHECK_SMARTCARD_USAGE:
+ return "CHECK_SMARTCARD_USAGE";
+
+ case CommandID::GET_PW_SAFE_SLOT_STATUS:
+ return "GET_PW_SAFE_SLOT_STATUS";
+ case CommandID::GET_PW_SAFE_SLOT_NAME:
+ return "GET_PW_SAFE_SLOT_NAME";
+ case CommandID::GET_PW_SAFE_SLOT_PASSWORD:
+ return "GET_PW_SAFE_SLOT_PASSWORD";
+ case CommandID::GET_PW_SAFE_SLOT_LOGINNAME:
+ return "GET_PW_SAFE_SLOT_LOGINNAME";
+ case CommandID::SET_PW_SAFE_SLOT_DATA_1:
+ return "SET_PW_SAFE_SLOT_DATA_1";
+ case CommandID::SET_PW_SAFE_SLOT_DATA_2:
+ return "SET_PW_SAFE_SLOT_DATA_2";
+ case CommandID::PW_SAFE_ERASE_SLOT:
+ return "PW_SAFE_ERASE_SLOT";
+ case CommandID::PW_SAFE_ENABLE:
+ return "PW_SAFE_ENABLE";
+ case CommandID::PW_SAFE_INIT_KEY:
+ return "PW_SAFE_INIT_KEY";
+ case CommandID::PW_SAFE_SEND_DATA:
+ return "PW_SAFE_SEND_DATA";
+ case CommandID::SD_CARD_HIGH_WATERMARK:
+ return "SD_CARD_HIGH_WATERMARK";
+ case CommandID::DETECT_SC_AES:
+ return "DETECT_SC_AES";
+ case CommandID::NEW_AES_KEY:
+ return "NEW_AES_KEY";
+ case CommandID::WRITE_TO_SLOT_2:
+ return "WRITE_TO_SLOT_2";
+ case CommandID::SEND_OTP_DATA:
+ return "SEND_OTP_DATA";
+ case CommandID::WINK:
+ return "WINK";
+ }
+ return "UNKNOWN";
+}
+}
+}
diff --git a/libnitrokey-v3.6/device.cc b/libnitrokey-v3.6/device.cc
new file mode 100644
index 0000000..1204c1e
--- /dev/null
+++ b/libnitrokey-v3.6/device.cc
@@ -0,0 +1,391 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include <chrono>
+#include <codecvt>
+#include <iostream>
+#include <locale>
+#include <thread>
+#include <cstddef>
+#include <stdexcept>
+#include "hidapi/hidapi.h"
+#include "libnitrokey/misc.h"
+#include "libnitrokey/device.h"
+#include "libnitrokey/log.h"
+#include <mutex>
+#include "DeviceCommunicationExceptions.h"
+#include "device.h"
+
+std::mutex mex_dev_com;
+
+using namespace nitrokey::device;
+using namespace nitrokey::log;
+using namespace nitrokey::misc;
+using namespace std::chrono;
+
+const uint16_t nitrokey::device::NITROKEY_VID = 0x20a0;
+const uint16_t nitrokey::device::NITROKEY_PRO_PID = 0x4108;
+const uint16_t nitrokey::device::NITROKEY_STORAGE_PID = 0x4109;
+
+const uint16_t nitrokey::device::PURISM_VID = 0x316d;
+const uint16_t nitrokey::device::LIBREM_KEY_PID = 0x4c4b;
+
+Option<DeviceModel> nitrokey::device::product_id_to_model(uint16_t product_id) {
+ return product_id_to_model(NITROKEY_VID, product_id);
+}
+
+Option<DeviceModel> nitrokey::device::product_id_to_model(uint16_t vendor_id, uint16_t product_id) {
+ switch (vendor_id) {
+ case NITROKEY_VID:
+ switch (product_id) {
+ case NITROKEY_PRO_PID:
+ return DeviceModel::PRO;
+ case NITROKEY_STORAGE_PID:
+ return DeviceModel::STORAGE;
+ default:
+ return {};
+ }
+ case PURISM_VID:
+ switch (product_id) {
+ case LIBREM_KEY_PID:
+ return DeviceModel::LIBREM;
+ default:
+ return {};
+ }
+ default:
+ return {};
+ }
+}
+
+std::atomic_int Device::instances_count{0};
+std::chrono::milliseconds Device::default_delay {0} ;
+
+std::ostream& nitrokey::device::operator<<(std::ostream& stream, DeviceModel model) {
+ switch (model) {
+ case DeviceModel::PRO:
+ stream << "Pro";
+ break;
+ case DeviceModel::STORAGE:
+ stream << "Storage";
+ break;
+ case DeviceModel::LIBREM:
+ stream << "Librem";
+ break;
+ default:
+ stream << "Unknown";
+ break;
+ }
+ return stream;
+}
+
+Device::Device(const uint16_t vid, const uint16_t pid, const DeviceModel model,
+ const milliseconds send_receive_delay, const int retry_receiving_count,
+ const milliseconds retry_timeout)
+ :
+ last_command_status(0),
+ m_vid(vid),
+ m_pid(pid),
+ m_model(model),
+ m_retry_sending_count(1),
+ m_retry_receiving_count(retry_receiving_count),
+ m_retry_timeout(retry_timeout),
+ m_send_receive_delay(send_receive_delay),
+ mp_devhandle(nullptr)
+{
+ instances_count++;
+}
+
+bool Device::disconnect() {
+ //called in object's destructor
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+ std::lock_guard<std::mutex> lock(mex_dev_com);
+ return _disconnect();
+}
+
+bool Device::_disconnect() {
+ LOG(std::string(__FUNCTION__) +
+ std::string(m_model == DeviceModel::PRO ? "PRO" : (m_model == DeviceModel::STORAGE ? "STORAGE" : "LIBREM")),
+ Loglevel::DEBUG_L2);
+ LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2);
+
+ if(mp_devhandle == nullptr) {
+ LOG(std::string("Disconnection: handle already freed: ") + std::to_string(mp_devhandle == nullptr) + " ("+m_path+")", Loglevel::DEBUG_L1);
+ return false;
+ }
+
+ hid_close(mp_devhandle);
+ mp_devhandle = nullptr;
+#ifndef __APPLE__
+ if (instances_count == 1){
+ LOG(std::string("Calling hid_exit"), Loglevel::DEBUG_L2);
+ hid_exit();
+ }
+#endif
+ return true;
+}
+
+bool Device::connect() {
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+ std::lock_guard<std::mutex> lock(mex_dev_com);
+ return _connect();
+}
+
+bool Device::_connect() {
+ LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2);
+
+// hid_init(); // done automatically on hid_open
+ if (m_path.empty()){
+ mp_devhandle = hid_open(m_vid, m_pid, nullptr);
+ } else {
+ mp_devhandle = hid_open_path(m_path.c_str());
+ }
+ const bool success = mp_devhandle != nullptr;
+ LOG(std::string("Connection success: ") + std::to_string(success) + " ("+m_path+")", Loglevel::DEBUG_L1);
+ return success;
+}
+
+void Device::set_path(const std::string path){
+ m_path = path;
+}
+
+int Device::send(const void *packet) {
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+ std::lock_guard<std::mutex> lock(mex_dev_com);
+ LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2);
+
+ int send_feature_report = -1;
+
+ for (int i = 0; i < 3 && send_feature_report < 0; ++i) {
+ if (mp_devhandle == nullptr) {
+ LOG(std::string("Connection fail") , Loglevel::DEBUG_L2);
+ throw DeviceNotConnected("Attempted HID send on an invalid descriptor.");
+ }
+ send_feature_report = hid_send_feature_report(
+ mp_devhandle, (const unsigned char *)(packet), HID_REPORT_SIZE);
+ if (send_feature_report < 0) _reconnect();
+ //add thread sleep?
+ LOG(std::string("Sending attempt: ")+std::to_string(i+1) + " / 3" , Loglevel::DEBUG_L2);
+ }
+ return send_feature_report;
+}
+
+int Device::recv(void *packet) {
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+ std::lock_guard<std::mutex> lock(mex_dev_com);
+ LOG(std::string(__FUNCTION__) + std::string(" *IN* "), Loglevel::DEBUG_L2);
+ int status;
+ int retry_count = 0;
+
+ for (;;) {
+ if (mp_devhandle == nullptr){
+ LOG(std::string("Connection fail") , Loglevel::DEBUG_L2);
+ throw DeviceNotConnected("Attempted HID receive on an invalid descriptor.");
+ }
+
+ status = (hid_get_feature_report(mp_devhandle, (unsigned char *)(packet),
+ HID_REPORT_SIZE));
+
+ auto pwherr = hid_error(mp_devhandle);
+ std::wstring wherr = (pwherr != nullptr) ? pwherr : L"No error message";
+ std::string herr(wherr.begin(), wherr.end());
+ LOG(std::string("libhid error message: ") + herr,
+ Loglevel::DEBUG_L2);
+
+ if (status > 0) break; // success
+ if (retry_count++ >= m_retry_receiving_count) {
+ LOG(
+ "Maximum retry count reached: " + std::to_string(retry_count),
+ Loglevel::WARNING);
+ LOG(
+ std::string("Counter stats: ") + m_counters.get_as_string(),
+ Loglevel::DEBUG);
+ break;
+ }
+ _reconnect();
+ LOG("Retrying... " + std::to_string(retry_count),
+ Loglevel::DEBUG);
+ std::this_thread::sleep_for(m_retry_timeout);
+ }
+
+ return status;
+}
+
+namespace {
+ void add_vendor_devices(std::vector<DeviceInfo>& res, uint16_t vendor_id){
+ auto pInfo = hid_enumerate(vendor_id, 0);
+ auto pInfo_ = pInfo;
+ while (pInfo != nullptr){
+ if (pInfo->path == nullptr || pInfo->serial_number == nullptr) {
+ continue;
+ }
+ auto deviceModel = product_id_to_model(vendor_id, pInfo->product_id);
+ if (deviceModel.has_value()) {
+ std::string path(pInfo->path);
+ std::wstring serialNumberW(pInfo->serial_number);
+ std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
+ std::string serialNumber = converter.to_bytes(serialNumberW);
+ DeviceInfo info = { deviceModel.value(), path, serialNumber };
+ res.push_back(info);
+ }
+ pInfo = pInfo->next;
+ }
+
+ if (pInfo_ != nullptr){
+ hid_free_enumeration(pInfo_);
+ }
+ }
+}
+
+std::vector<DeviceInfo> Device::enumerate(){
+ std::vector<DeviceInfo> res;
+ ::add_vendor_devices(res, NITROKEY_VID);
+ ::add_vendor_devices(res, PURISM_VID);
+ return res;
+}
+
+std::shared_ptr<Device> Device::create(DeviceModel model) {
+ switch (model) {
+ case DeviceModel::PRO:
+ return std::make_shared<Stick10>();
+ case DeviceModel::STORAGE:
+ return std::make_shared<Stick20>();
+ case DeviceModel::LIBREM:
+ return std::make_shared<LibremKey>();
+ default:
+ return {};
+ }
+}
+
+bool Device::could_be_enumerated() {
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+ std::lock_guard<std::mutex> lock(mex_dev_com);
+ if (mp_devhandle==nullptr){
+ return false;
+ }
+#ifndef __APPLE__
+ auto pInfo = hid_enumerate(m_vid, m_pid);
+ if (pInfo != nullptr){
+ hid_free_enumeration(pInfo);
+ return true;
+ }
+ return false;
+#else
+// alternative for OSX
+ unsigned char buf[1];
+ return hid_read_timeout(mp_devhandle, buf, sizeof(buf), 20) != -1;
+#endif
+}
+
+void Device::show_stats() {
+ auto s = m_counters.get_as_string();
+ LOG(s, Loglevel::DEBUG_L2);
+}
+
+void Device::_reconnect() {
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+ ++m_counters.low_level_reconnect;
+ _disconnect();
+ _connect();
+}
+
+Device::~Device() {
+ show_stats();
+ disconnect();
+ instances_count--;
+}
+
+void Device::set_default_device_speed(int delay) {
+ default_delay = std::chrono::duration<int, std::milli>(delay);
+}
+
+
+void Device::set_receiving_delay(const std::chrono::milliseconds delay){
+ std::lock_guard<std::mutex> lock(mex_dev_com);
+ m_send_receive_delay = delay;
+}
+
+void Device::set_retry_delay(const std::chrono::milliseconds delay){
+ std::lock_guard<std::mutex> lock(mex_dev_com);
+ m_retry_timeout = delay;
+}
+
+Stick10::Stick10():
+ Device(NITROKEY_VID, NITROKEY_PRO_PID, DeviceModel::PRO, 100ms, 5, 100ms)
+ {
+ setDefaultDelay();
+ }
+
+
+Stick20::Stick20():
+ Device(NITROKEY_VID, NITROKEY_STORAGE_PID, DeviceModel::STORAGE, 40ms, 55, 40ms)
+ {
+ setDefaultDelay();
+ }
+
+
+LibremKey::LibremKey():
+ Device(PURISM_VID, LIBREM_KEY_PID, DeviceModel::LIBREM, 100ms, 5, 100ms)
+ {
+ setDefaultDelay();
+ }
+
+#include <sstream>
+#define p(x) ss << #x << " " << x << ", ";
+std::string Device::ErrorCounters::get_as_string() {
+#ifdef NO_LOG
+ return "";
+#endif
+
+ std::stringstream ss;
+ p(total_comm_runs);
+ p(communication_successful);
+ ss << "(";
+ p(command_successful_recv);
+ p(command_result_not_equal_0_recv);
+ ss << "), ";
+ p(sends_executed);
+ p(recv_executed);
+ p(successful_storage_commands);
+ p(total_retries);
+ ss << "(";
+ p(busy);
+ p(busy_progressbar);
+ p(CRC_other_than_awaited);
+ p(wrong_CRC);
+ ss << "), ";
+ p(low_level_reconnect);
+ p(sending_error);
+ p(receiving_error);
+ return ss.str();
+}
+
+void Device::setDefaultDelay() {
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+
+ auto count = default_delay.count();
+ if (count != 0){
+ LOG("Setting default delay to " + std::to_string(count), Loglevel::DEBUG_L2);
+ m_retry_timeout = default_delay;
+ m_send_receive_delay = default_delay;
+ }
+}
+
+#undef p
diff --git a/libnitrokey-v3.6/libnitrokey/CommandFailedException.h b/libnitrokey-v3.6/libnitrokey/CommandFailedException.h
new file mode 100644
index 0000000..32bd6b7
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/CommandFailedException.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef LIBNITROKEY_COMMANDFAILEDEXCEPTION_H
+#define LIBNITROKEY_COMMANDFAILEDEXCEPTION_H
+
+#include <exception>
+#include <cstdint>
+#include "log.h"
+#include "command_id.h"
+
+using cs = nitrokey::proto::stick10::command_status;
+using cs2 = nitrokey::proto::stick20::device_status;
+
+class CommandFailedException : public std::exception {
+public:
+ const uint8_t last_command_id;
+ const uint8_t last_command_status;
+
+ CommandFailedException(uint8_t last_command_id, uint8_t last_command_status) :
+ last_command_id(last_command_id),
+ last_command_status(last_command_status){
+ LOG(std::string("CommandFailedException, status: ")+ std::to_string(last_command_status), nitrokey::log::Loglevel::DEBUG);
+ }
+
+ virtual const char *what() const throw() {
+ return "Command execution has failed on device";
+ }
+
+
+ bool reason_timestamp_warning() const throw(){
+ return last_command_status == static_cast<uint8_t>(cs::timestamp_warning);
+ }
+
+ bool reason_AES_not_initialized() const throw(){
+ return last_command_status == static_cast<uint8_t>(cs::AES_dec_failed);
+ }
+
+ bool reason_not_authorized() const throw(){
+ return last_command_status == static_cast<uint8_t>(cs::not_authorized);
+ }
+
+ bool reason_slot_not_programmed() const throw(){
+ return last_command_status == static_cast<uint8_t>(cs::slot_not_programmed);
+ }
+
+ bool reason_wrong_password() const throw(){
+ return last_command_status == static_cast<uint8_t>(cs::wrong_password);
+ }
+
+ bool reason_smartcard_busy() const throw(){
+ return last_command_status == static_cast<uint8_t>(cs2::smartcard_error);
+ }
+
+};
+
+
+#endif //LIBNITROKEY_COMMANDFAILEDEXCEPTION_H
diff --git a/libnitrokey-v3.6/libnitrokey/DeviceCommunicationExceptions.h b/libnitrokey-v3.6/libnitrokey/DeviceCommunicationExceptions.h
new file mode 100644
index 0000000..f710d0b
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/DeviceCommunicationExceptions.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+
+#ifndef LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H
+#define LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H
+
+#include <atomic>
+#include <exception>
+#include <stdexcept>
+#include <string>
+
+
+class DeviceCommunicationException: public std::runtime_error
+{
+ std::string message;
+ static std::atomic_int occurred;
+public:
+ DeviceCommunicationException(std::string _msg): std::runtime_error(_msg), message(_msg){
+ ++occurred;
+ }
+ uint8_t getType() const {return 1;};
+// virtual const char* what() const throw() override {
+// return message.c_str();
+// }
+ static bool has_occurred(){ return occurred > 0; };
+ static void reset_occurred_flag(){ occurred = 0; };
+};
+
+class DeviceNotConnected: public DeviceCommunicationException {
+public:
+ DeviceNotConnected(std::string msg) : DeviceCommunicationException(msg){}
+ uint8_t getType() const {return 2;};
+};
+
+class DeviceSendingFailure: public DeviceCommunicationException {
+public:
+ DeviceSendingFailure(std::string msg) : DeviceCommunicationException(msg){}
+ uint8_t getType() const {return 3;};
+};
+
+class DeviceReceivingFailure: public DeviceCommunicationException {
+public:
+ DeviceReceivingFailure(std::string msg) : DeviceCommunicationException(msg){}
+ uint8_t getType() const {return 4;};
+};
+
+class InvalidCRCReceived: public DeviceReceivingFailure {
+public:
+ InvalidCRCReceived(std::string msg) : DeviceReceivingFailure(msg){}
+ uint8_t getType() const {return 5;};
+};
+
+
+#endif //LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H
diff --git a/libnitrokey-v3.6/libnitrokey/LibraryException.h b/libnitrokey-v3.6/libnitrokey/LibraryException.h
new file mode 100644
index 0000000..3b9d177
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/LibraryException.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef LIBNITROKEY_LIBRARYEXCEPTION_H
+#define LIBNITROKEY_LIBRARYEXCEPTION_H
+
+#include <exception>
+#include <cstdint>
+#include <string>
+#include "log.h"
+
+class LibraryException: std::exception {
+public:
+ virtual uint8_t exception_id()= 0;
+};
+
+class TargetBufferSmallerThanSource: public LibraryException {
+public:
+ virtual uint8_t exception_id() override {
+ return 203;
+ }
+
+public:
+ size_t source_size;
+ size_t target_size;
+
+ TargetBufferSmallerThanSource(
+ size_t source_size, size_t target_size
+ ) : source_size(source_size), target_size(target_size) {}
+
+ virtual const char *what() const throw() override {
+ std::string s = " ";
+ auto ts = [](size_t x){ return std::to_string(x); };
+ std::string msg = std::string("Target buffer size is smaller than source: [source size, buffer size]")
+ +s+ ts(source_size) +s+ ts(target_size);
+ return msg.c_str();
+ }
+
+};
+
+class InvalidHexString : public LibraryException {
+public:
+ virtual uint8_t exception_id() override {
+ return 202;
+ }
+
+public:
+ uint8_t invalid_char;
+
+ InvalidHexString (uint8_t invalid_char) : invalid_char( invalid_char) {}
+
+ virtual const char *what() const throw() override {
+ return "Invalid character in hex string";
+ }
+
+};
+
+class InvalidSlotException : public LibraryException {
+public:
+ virtual uint8_t exception_id() override {
+ return 201;
+ }
+
+public:
+ uint8_t slot_selected;
+
+ InvalidSlotException(uint8_t slot_selected) : slot_selected(slot_selected) {}
+
+ virtual const char *what() const throw() override {
+ return "Wrong slot selected";
+ }
+
+};
+
+
+
+class TooLongStringException : public LibraryException {
+public:
+ virtual uint8_t exception_id() override {
+ return 200;
+ }
+
+ std::size_t size_source;
+ std::size_t size_destination;
+ std::string message;
+
+ TooLongStringException(size_t size_source, size_t size_destination, const std::string &message = "") : size_source(
+ size_source), size_destination(size_destination), message(message) {
+ LOG(std::string("TooLongStringException, size diff: ")+ std::to_string(size_source-size_destination), nitrokey::log::Loglevel::DEBUG);
+
+ }
+
+ virtual const char *what() const throw() override {
+ //TODO add sizes and message data to final message
+ return "Too long string has been supplied as an argument";
+ }
+
+};
+
+#endif //LIBNITROKEY_LIBRARYEXCEPTION_H
diff --git a/libnitrokey-v3.6/libnitrokey/LongOperationInProgressException.h b/libnitrokey-v3.6/libnitrokey/LongOperationInProgressException.h
new file mode 100644
index 0000000..865d6b5
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/LongOperationInProgressException.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef LIBNITROKEY_LONGOPERATIONINPROGRESSEXCEPTION_H
+#define LIBNITROKEY_LONGOPERATIONINPROGRESSEXCEPTION_H
+
+#include "CommandFailedException.h"
+
+class LongOperationInProgressException : public CommandFailedException {
+
+public:
+ unsigned char 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){
+ LOG(
+ 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/libnitrokey-v3.6/libnitrokey/NitrokeyManager.h b/libnitrokey-v3.6/libnitrokey/NitrokeyManager.h
new file mode 100644
index 0000000..cb7cfce
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/NitrokeyManager.h
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef LIBNITROKEY_NITROKEYMANAGER_H
+#define LIBNITROKEY_NITROKEYMANAGER_H
+
+#include "device.h"
+#include "log.h"
+#include "device_proto.h"
+#include "stick10_commands.h"
+#include "stick10_commands_0.8.h"
+#include "stick20_commands.h"
+#include <vector>
+#include <memory>
+#include <unordered_map>
+
+namespace nitrokey {
+ using namespace nitrokey::device;
+ using namespace std;
+ using namespace nitrokey::proto::stick10;
+ using namespace nitrokey::proto::stick20;
+ using namespace nitrokey::proto;
+ using namespace nitrokey::log;
+
+
+#ifdef __WIN32
+char * strndup(const char* str, size_t maxlen);
+#endif
+
+ class NitrokeyManager {
+ public:
+ static shared_ptr <NitrokeyManager> instance();
+
+ bool first_authenticate(const char *pin, const char *temporary_password);
+ bool write_HOTP_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password);
+ bool write_TOTP_slot(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password);
+ string get_HOTP_code(uint8_t slot_number, const char *user_temporary_password);
+ string get_TOTP_code(uint8_t slot_number, uint64_t challenge, uint64_t last_totp_time,
+ uint8_t last_interval,
+ const char *user_temporary_password);
+ string get_TOTP_code(uint8_t slot_number, const char *user_temporary_password);
+ stick10::ReadSlot::ResponsePayload get_TOTP_slot_data(const uint8_t slot_number);
+ stick10::ReadSlot::ResponsePayload get_HOTP_slot_data(const uint8_t slot_number);
+
+ bool set_time(uint64_t time);
+ /**
+ * Set the device time used for TOTP to the given time. Contrary to
+ * {@code set_time(uint64_t)}, this command fails if {@code old_time}
+ * &gt; {@code time} or if {@code old_time} is zero (where {@code
+ * old_time} is the current time on the device).
+ *
+ * @param time new device time as Unix timestamp (seconds since
+ * 1970-01-01)
+ */
+ void set_time_soft(uint64_t time);
+
+ [[deprecated("get_time is deprecated -- use set_time_soft instead")]]
+ bool get_time(uint64_t time = 0);
+ bool erase_totp_slot(uint8_t slot_number, const char *temporary_password);
+ bool erase_hotp_slot(uint8_t slot_number, const char *temporary_password);
+ std::vector<DeviceInfo> list_devices();
+ std::vector<std::string> list_devices_by_cpuID();
+
+ /**
+ * Connect to the device using unique smartcard:datacard id.
+ * Needs list_device_by_cpuID() run first
+ * @param id Current ID of the target device
+ * @return true on success, false on failure
+ */
+ bool connect_with_ID(const std::string id);
+ bool connect_with_path (std::string path);
+ bool connect(const char *device_model);
+ bool connect(device::DeviceModel device_model);
+ bool connect();
+ bool disconnect();
+ bool is_connected() throw() ;
+ bool could_current_device_be_enumerated();
+ bool set_default_commands_delay(int delay);
+
+ DeviceModel get_connected_device_model() const;
+ void set_debug(bool state);
+ stick10::GetStatus::ResponsePayload get_status();
+ string get_status_as_string();
+ string get_serial_number();
+ uint32_t get_serial_number_as_u32();
+
+ char * get_totp_slot_name(uint8_t slot_number);
+ char * get_hotp_slot_name(uint8_t slot_number);
+
+ void change_user_PIN(const char *current_PIN, const char *new_PIN);
+ void change_admin_PIN(const char *current_PIN, const char *new_PIN);
+
+ void enable_password_safe(const char *user_pin);
+
+ vector <uint8_t> get_password_safe_slot_status();
+
+ uint8_t get_admin_retry_count();
+ uint8_t get_user_retry_count();
+
+ void lock_device();
+
+ char * get_password_safe_slot_name(uint8_t slot_number);
+ char * get_password_safe_slot_password(uint8_t slot_number);
+ char * get_password_safe_slot_login(uint8_t slot_number);
+
+ void
+ write_password_safe_slot(uint8_t slot_number, const char *slot_name, const char *slot_login,
+ const char *slot_password);
+
+ void erase_password_safe_slot(uint8_t slot_number);
+
+ void user_authenticate(const char *user_password, const char *temporary_password);
+
+ void factory_reset(const char *admin_password);
+
+ void build_aes_key(const char *admin_password);
+
+ void unlock_user_password(const char *admin_password, const char *new_user_password);
+
+ void write_config(uint8_t numlock, uint8_t capslock, uint8_t scrolllock, bool enable_user_password,
+ bool delete_user_password, const char *admin_temporary_password);
+
+ vector<uint8_t> read_config();
+
+ bool is_AES_supported(const char *user_password);
+
+ void unlock_encrypted_volume(const char *user_password);
+ void lock_encrypted_volume();
+
+ void unlock_hidden_volume(const char *hidden_volume_password);
+ void lock_hidden_volume();
+
+ /**
+ * Sets unencrypted volume read-only.
+ * Works until v0.48 (incl. v0.50), where User PIN was sufficient
+ * Does nothing otherwise.
+ * @param user_pin User PIN
+ */
+ [[deprecated("Use set_unencrypted_read_only_admin instead.")]]
+ void set_unencrypted_read_only(const char *user_pin);
+
+ /**
+ * Sets unencrypted volume read-only.
+ * Works from v0.49 (except v0.50) accepts Admin PIN
+ * Does nothing otherwise.
+ * @param admin_pin Admin PIN
+ */
+ void set_unencrypted_read_only_admin(const char *admin_pin);
+
+ /**
+ * Sets unencrypted volume read-write.
+ * Works until v0.48 (incl. v0.50), where User PIN was sufficient
+ * Does nothing otherwise.
+ * @param user_pin User PIN
+ */
+ [[deprecated("Use set_unencrypted_read_write_admin instead")]]
+ void set_unencrypted_read_write(const char *user_pin);
+
+ /**
+ * Sets unencrypted volume read-write.
+ * Works from v0.49 (except v0.50) accepts Admin PIN
+ * Does nothing otherwise.
+ * @param admin_pin Admin PIN
+ */
+ void set_unencrypted_read_write_admin(const char *admin_pin);
+
+ void export_firmware(const char *admin_pin);
+ void enable_firmware_update(const char *firmware_pin);
+
+ void clear_new_sd_card_warning(const char *admin_pin);
+
+ void fill_SD_card_with_random_data(const char *admin_pin);
+
+ uint8_t get_SD_card_size();
+
+ void change_update_password(const char *current_update_password, const char *new_update_password);
+
+ void create_hidden_volume(uint8_t slot_nr, uint8_t start_percent, uint8_t end_percent,
+ const char *hidden_volume_password);
+
+ void send_startup(uint64_t seconds_from_epoch);
+
+ char * get_status_storage_as_string();
+ stick20::DeviceConfigurationResponsePacket::ResponsePayload get_status_storage();
+
+ char * get_SD_usage_data_as_string();
+ std::pair<uint8_t,uint8_t> get_SD_usage_data();
+
+
+ int get_progress_bar_value();
+
+ ~NitrokeyManager();
+ bool is_authorization_command_supported();
+ bool is_320_OTP_secret_supported();
+
+
+ template <typename S, typename A, typename T>
+ void authorize_packet(T &package, const char *admin_temporary_password, shared_ptr<Device> device);
+ uint8_t get_minor_firmware_version();
+
+ explicit NitrokeyManager();
+ void set_log_function(std::function<void(std::string)> log_function);
+ private:
+
+ static shared_ptr <NitrokeyManager> _instance;
+ std::shared_ptr<Device> device;
+ std::string current_device_id;
+ public:
+ const string get_current_device_id() const;
+
+ private:
+ std::unordered_map<std::string, shared_ptr<Device> > connected_devices;
+ std::unordered_map<std::string, shared_ptr<Device> > connected_devices_byID;
+
+
+ stick10::ReadSlot::ResponsePayload get_OTP_slot_data(const uint8_t slot_number);
+ bool is_valid_hotp_slot_number(uint8_t slot_number) const;
+ bool is_valid_totp_slot_number(uint8_t slot_number) const;
+ bool is_valid_password_safe_slot_number(uint8_t slot_number) const;
+ uint8_t get_internal_slot_number_for_hotp(uint8_t slot_number) const;
+ uint8_t get_internal_slot_number_for_totp(uint8_t slot_number) const;
+ bool erase_slot(uint8_t slot_number, const char *temporary_password);
+ char * get_slot_name(uint8_t slot_number);
+
+ template <typename ProCommand, PasswordKind StoKind>
+ void change_PIN_general(const char *current_PIN, const char *new_PIN);
+
+ void write_HOTP_slot_authorize(uint8_t slot_number, const char *slot_name, const char *secret, uint64_t hotp_counter,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password);
+
+ void write_TOTP_slot_authorize(uint8_t slot_number, const char *slot_name, const char *secret, uint16_t time_window,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password);
+
+ void write_OTP_slot_no_authorize(uint8_t internal_slot_number, const char *slot_name, const char *secret,
+ uint64_t counter_or_interval,
+ bool use_8_digits, bool use_enter, bool use_tokenID, const char *token_ID,
+ const char *temporary_password) const;
+ bool _disconnect_no_lock();
+
+ public:
+ bool set_current_device_speed(int retry_delay, int send_receive_delay);
+ void set_loglevel(Loglevel loglevel);
+
+ void set_loglevel(int loglevel);
+
+ /**
+ * Sets encrypted volume read-only.
+ * Supported from future versions of Storage.
+ * @param admin_pin Admin PIN
+ */
+ void set_encrypted_volume_read_only(const char *admin_pin);
+
+ /**
+ * Sets encrypted volume read-write.
+ * Supported from future versions of Storage.
+ * @param admin_pin Admin PIN
+ */
+ void set_encrypted_volume_read_write(const char *admin_pin);
+
+ uint8_t get_major_firmware_version();
+
+ bool is_smartcard_in_use();
+
+ /**
+ * Function to determine unencrypted volume PIN type
+ * @param minor_firmware_version
+ * @return Returns true, if set unencrypted volume ro/rw pin type is User, false otherwise.
+ */
+ bool set_unencrypted_volume_rorw_pin_type_user();
+
+ /**
+ * Blink red and green LED alternatively and infinitely (until device is reconnected).
+ */
+ void wink();
+
+ stick20::ProductionTest::ResponsePayload production_info();
+
+ void enable_firmware_update_pro(const char *firmware_pin);
+
+ void change_firmware_update_password_pro(const char *firmware_pin_current, const char *firmware_pin_new);
+ bool is_internal_hotp_slot_number(uint8_t slot_number) const;
+ };
+}
+
+
+
+#endif //LIBNITROKEY_NITROKEYMANAGER_H
diff --git a/libnitrokey-v3.6/libnitrokey/command.h b/libnitrokey-v3.6/libnitrokey/command.h
new file mode 100644
index 0000000..6852bf0
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/command.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef COMMAND_H
+#define COMMAND_H
+#include <string>
+#include "command_id.h"
+#include "cxx_semantics.h"
+
+#define print_to_ss(x) ( ss << " " << (#x) <<":\t" << (x) << std::endl );
+#ifdef LOG_VOLATILE_DATA
+#define print_to_ss_volatile(x) print_to_ss(x);
+#else
+#define print_to_ss_volatile(x) ( ss << " " << (#x) <<":\t" << "***********" << std::endl );
+#endif
+#define hexdump_to_ss(x) (ss << #x":\n"\
+ << ::nitrokey::misc::hexdump((const uint8_t *) (&x), sizeof x, false));
+
+namespace nitrokey {
+ namespace proto {
+
+ template<CommandID cmd_id>
+ class Command : semantics::non_constructible {
+ public:
+ constexpr static CommandID command_id() { return cmd_id; }
+
+ template<typename T>
+ std::string dissect(const T &) {
+ return std::string("Payload dissection is unavailable");
+ }
+ };
+
+namespace stick20{
+ enum class PasswordKind : uint8_t {
+ User = 'P',
+ Admin = 'A',
+ AdminPrefixed
+ };
+
+ template<CommandID cmd_id, PasswordKind Tpassword_kind = PasswordKind::User, int password_length = 20>
+ class PasswordCommand : public Command<cmd_id> {
+ constexpr static CommandID _command_id() { return cmd_id; }
+ public:
+ struct CommandPayload {
+ uint8_t kind;
+ uint8_t password[password_length];
+
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss( kind );
+ print_to_ss_volatile(password);
+ return ss.str();
+ }
+ 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';
+ }
+
+ 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;
+ case PasswordKind::AdminPrefixed:
+ set_kind_admin_prefixed();
+ break;
+ }
+ };
+
+ } __packed;
+
+ //typedef Transaction<Command<cmd_id>::command_id(), struct CommandPayload, struct EmptyPayload>
+ // CommandTransaction;
+ using CommandTransaction = Transaction<cmd_id, CommandPayload, EmptyPayload>;
+ //using CommandTransaction = Transaction<_command_id(), CommandPayload, EmptyPayload>;
+
+ };
+ }
+ }
+}
+
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/command_id.h b/libnitrokey-v3.6/libnitrokey/command_id.h
new file mode 100644
index 0000000..ee6726c
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/command_id.h
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef COMMAND_ID_H
+#define COMMAND_ID_H
+#include <stdint.h>
+
+namespace nitrokey {
+namespace proto {
+ namespace stick20 {
+ enum class device_status : uint8_t {
+ idle = 0,
+ ok,
+ busy,
+ wrong_password,
+ busy_progressbar,
+ password_matrix_ready,
+ no_user_password_unlock, // FIXME: translate on receive to command status error (fix in firmware?)
+ smartcard_error,
+ security_bit_active
+ };
+ const int CMD_START_VALUE = 0x20;
+ const int CMD_END_VALUE = 0x60;
+ }
+ namespace stick10 {
+ enum class command_status : uint8_t {
+ ok = 0,
+ wrong_CRC,
+ wrong_slot,
+ slot_not_programmed,
+ wrong_password = 4,
+ not_authorized,
+ timestamp_warning,
+ no_name_error,
+ not_supported,
+ unknown_command,
+ AES_dec_failed
+ };
+ enum class device_status : uint8_t {
+ ok = 0,
+ busy = 1,
+ error,
+ received_report,
+ };
+ }
+
+
+enum class CommandID : uint8_t {
+ GET_STATUS = 0x00,
+ WRITE_TO_SLOT = 0x01,
+ READ_SLOT_NAME = 0x02,
+ READ_SLOT = 0x03,
+ GET_CODE = 0x04,
+ WRITE_CONFIG = 0x05,
+ ERASE_SLOT = 0x06,
+ FIRST_AUTHENTICATE = 0x07,
+ AUTHORIZE = 0x08,
+ GET_PASSWORD_RETRY_COUNT = 0x09,
+ CLEAR_WARNING = 0x0A,
+ SET_TIME = 0x0B,
+ TEST_COUNTER = 0x0C,
+ TEST_TIME = 0x0D,
+ USER_AUTHENTICATE = 0x0E,
+ GET_USER_PASSWORD_RETRY_COUNT = 0x0F,
+ USER_AUTHORIZE = 0x10,
+ UNLOCK_USER_PASSWORD = 0x11,
+ LOCK_DEVICE = 0x12,
+ FACTORY_RESET = 0x13,
+ CHANGE_USER_PIN = 0x14,
+ CHANGE_ADMIN_PIN = 0x15,
+ WRITE_TO_SLOT_2 = 0x16,
+ SEND_OTP_DATA = 0x17,
+ FIRMWARE_UPDATE = 0x19,
+ FIRMWARE_PASSWORD_CHANGE = 0x1A,
+
+ ENABLE_CRYPTED_PARI = 0x20,
+ DISABLE_CRYPTED_PARI = 0x20 + 1,
+ ENABLE_HIDDEN_CRYPTED_PARI = 0x20 + 2,
+ DISABLE_HIDDEN_CRYPTED_PARI = 0x20 + 3,
+ ENABLE_FIRMWARE_UPDATE = 0x20 + 4, //enables update mode
+ EXPORT_FIRMWARE_TO_FILE = 0x20 + 5,
+ GENERATE_NEW_KEYS = 0x20 + 6,
+ FILL_SD_CARD_WITH_RANDOM_CHARS = 0x20 + 7,
+
+ WRITE_STATUS_DATA = 0x20 + 8, //@unused
+ ENABLE_READONLY_UNCRYPTED_LUN = 0x20 + 9,
+ ENABLE_READWRITE_UNCRYPTED_LUN = 0x20 + 10,
+
+ 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, //@unused
+ SEND_HIDDEN_VOLUME_SETUP = 0x20 + 17,
+ SEND_PASSWORD = 0x20 + 18,
+ SEND_NEW_PASSWORD = 0x20 + 19,
+ CLEAR_NEW_SD_CARD_FOUND = 0x20 + 20,
+
+ SEND_STARTUP = 0x20 + 21,
+ SEND_CLEAR_STICK_KEYS_NOT_INITIATED = 0x20 + 22,
+ SEND_LOCK_STICK_HARDWARE = 0x20 + 23, //locks firmware upgrade
+
+ PRODUCTION_TEST = 0x20 + 24,
+ SEND_DEBUG_DATA = 0x20 + 25, //@unused
+
+ CHANGE_UPDATE_PIN = 0x20 + 26,
+
+ //added in v0.48.5
+ ENABLE_ADMIN_READONLY_UNCRYPTED_LUN = 0x20 + 28,
+ ENABLE_ADMIN_READWRITE_UNCRYPTED_LUN = 0x20 + 29,
+ ENABLE_ADMIN_READONLY_ENCRYPTED_LUN = 0x20 + 30,
+ ENABLE_ADMIN_READWRITE_ENCRYPTED_LUN = 0x20 + 31,
+ CHECK_SMARTCARD_USAGE = 0x20 + 32,
+ //v0.52+
+ WINK = 0x20 + 33,
+
+ GET_PW_SAFE_SLOT_STATUS = 0x60,
+ GET_PW_SAFE_SLOT_NAME = 0x61,
+ GET_PW_SAFE_SLOT_PASSWORD = 0x62,
+ GET_PW_SAFE_SLOT_LOGINNAME = 0x63,
+ SET_PW_SAFE_SLOT_DATA_1 = 0x64,
+ SET_PW_SAFE_SLOT_DATA_2 = 0x65,
+ PW_SAFE_ERASE_SLOT = 0x66,
+ PW_SAFE_ENABLE = 0x67,
+ 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
+};
+
+const char *commandid_to_string(CommandID id);
+}
+}
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/cxx_semantics.h b/libnitrokey-v3.6/libnitrokey/cxx_semantics.h
new file mode 100644
index 0000000..36ed142
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/cxx_semantics.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef CXX_SEMANTICS_H
+#define CXX_SEMANTICS_H
+
+#ifndef _MSC_VER
+#define __packed __attribute__((__packed__))
+#else
+#define __packed
+#endif
+
+#ifdef _MSC_VER
+#define strdup _strdup
+#endif
+
+/*
+ * There's no need to include Boost for a simple subset this project needs.
+ */
+namespace semantics {
+class non_constructible {
+ non_constructible() {}
+};
+}
+
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/deprecated.h b/libnitrokey-v3.6/libnitrokey/deprecated.h
new file mode 100644
index 0000000..5a83288
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/deprecated.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+
+#ifndef LIBNITROKEY_DEPRECATED_H
+#define LIBNITROKEY_DEPRECATED_H
+
+#if defined(__GNUC__) || defined(__clang__)
+#define DEPRECATED __attribute__((deprecated))
+#elif defined(_MSC_VER)
+#define DEPRECATED __declspec(deprecated)
+#else
+#pragma message("WARNING: DEPRECATED macro is not defined for this compiler")
+#define DEPRECATED
+#endif
+
+#endif //LIBNITROKEY_DEPRECATED_H
diff --git a/libnitrokey-v3.6/libnitrokey/device.h b/libnitrokey-v3.6/libnitrokey/device.h
new file mode 100644
index 0000000..917e0d0
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/device.h
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef DEVICE_H
+#define DEVICE_H
+#include <chrono>
+#include "hidapi/hidapi.h"
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <ostream>
+#include <vector>
+#include "misc.h"
+
+#define HID_REPORT_SIZE 65
+
+#include <atomic>
+
+namespace nitrokey {
+namespace device {
+ using namespace std::chrono_literals;
+ using std::chrono::milliseconds;
+
+ struct EnumClassHash
+ {
+ template <typename T>
+ std::size_t operator()(T t) const
+ {
+ return static_cast<std::size_t>(t);
+ }
+ };
+
+enum class DeviceModel{
+ PRO,
+ STORAGE,
+ LIBREM
+};
+
+std::ostream& operator<<(std::ostream& stream, DeviceModel model);
+
+/**
+ * The USB vendor ID for Nitrokey devices.
+ */
+extern const uint16_t NITROKEY_VID;
+/**
+ * The USB product ID for the Nitrokey Pro.
+ */
+extern const uint16_t NITROKEY_PRO_PID;
+/**
+ * The USB product ID for the Nitrokey Storage.
+ */
+extern const uint16_t NITROKEY_STORAGE_PID;
+/**
+ * The USB vendor ID for Purism devices.
+ */
+extern const uint16_t PURISM_VID;
+/**
+ * The USB product ID for the Librem Key.
+ */
+extern const uint16_t LIBREM_KEY_PID;
+
+/**
+ * Convert the given USB product ID to a Nitrokey model. If there is no model
+ * with that ID, return an absent value.
+ */
+misc::Option<DeviceModel> product_id_to_model(uint16_t product_id);
+misc::Option<DeviceModel> product_id_to_model(uint16_t vendor_id, uint16_t product_id);
+
+/**
+ * Information about a connected device.
+ *
+ * This struct contains the information about a connected device returned by
+ * hidapi when enumerating the connected devices.
+ */
+struct DeviceInfo {
+ /**
+ * The model of the connected device.
+ */
+ DeviceModel m_deviceModel;
+ /**
+ * The USB connection path for the device.
+ */
+ std::string m_path;
+ /**
+ * The serial number of the device.
+ */
+ std::string m_serialNumber;
+};
+
+#include <atomic>
+
+class Device {
+
+public:
+
+ struct ErrorCounters{
+ using cnt = std::atomic_int;
+ cnt wrong_CRC;
+ cnt CRC_other_than_awaited;
+ cnt busy;
+ cnt total_retries;
+ cnt sending_error;
+ cnt receiving_error;
+ cnt total_comm_runs;
+ cnt successful_storage_commands;
+ cnt command_successful_recv;
+ cnt recv_executed;
+ cnt sends_executed;
+ cnt busy_progressbar;
+ cnt command_result_not_equal_0_recv;
+ cnt communication_successful;
+ cnt low_level_reconnect;
+ std::string get_as_string();
+
+ } m_counters = {};
+
+
+ Device(const uint16_t vid, const uint16_t pid, const DeviceModel model,
+ const milliseconds send_receive_delay, const int retry_receiving_count,
+ const milliseconds retry_timeout);
+
+ virtual ~Device();
+
+ // lack of device is not actually an error,
+ // so it doesn't throw
+ virtual bool connect();
+ virtual bool disconnect();
+
+ /*
+ * Sends packet of HID_REPORT_SIZE.
+ */
+ virtual int send(const void *packet);
+
+ /*
+ * Gets packet of HID_REPORT_SIZE.
+ * Can sleep. See below.
+ */
+ virtual int recv(void *packet);
+
+ /***
+ * Returns true if some device is visible by OS with given VID and PID
+ * whether the device is connected through HID API or not.
+ * @return true if visible by OS
+ */
+ bool could_be_enumerated();
+ /**
+ * Returns a vector with all connected Nitrokey devices.
+ *
+ * @return information about all connected devices
+ */
+ static std::vector<DeviceInfo> enumerate();
+
+ /**
+ * Create a Device of the given model.
+ */
+ static std::shared_ptr<Device> create(DeviceModel model);
+
+
+ void show_stats();
+// ErrorCounters get_stats(){ return m_counters; }
+ int get_retry_receiving_count() const { return m_retry_receiving_count; };
+ int get_retry_sending_count() const { return m_retry_sending_count; };
+ std::chrono::milliseconds get_retry_timeout() const { return m_retry_timeout; };
+ std::chrono::milliseconds get_send_receive_delay() const {return m_send_receive_delay;}
+
+ int get_last_command_status() {int a = std::atomic_exchange(&last_command_status, static_cast<uint8_t>(0)); return a;};
+ void set_last_command_status(uint8_t _err) { last_command_status = _err;} ;
+ bool last_command_sucessfull() const {return last_command_status == 0;};
+ DeviceModel get_device_model() const {return m_model;}
+ void set_receiving_delay(std::chrono::milliseconds delay);
+ void set_retry_delay(std::chrono::milliseconds delay);
+ static void set_default_device_speed(int delay);
+ void setDefaultDelay();
+ void set_path(const std::string path);
+
+
+ private:
+ std::atomic<uint8_t> last_command_status;
+ void _reconnect();
+ bool _connect();
+ bool _disconnect();
+
+protected:
+ const uint16_t m_vid;
+ const uint16_t m_pid;
+ const DeviceModel m_model;
+
+ /*
+ * While the project uses Signal11 portable HIDAPI
+ * library, there's no way of doing it asynchronously,
+ * hence polling.
+ */
+ const int m_retry_sending_count;
+ const int m_retry_receiving_count;
+ std::chrono::milliseconds m_retry_timeout;
+ std::chrono::milliseconds m_send_receive_delay;
+ std::atomic<hid_device *>mp_devhandle;
+ std::string m_path;
+
+ static std::atomic_int instances_count;
+ static std::chrono::milliseconds default_delay ;
+};
+
+class Stick10 : public Device {
+ public:
+ Stick10();
+
+};
+
+class Stick20 : public Device {
+ public:
+ Stick20();
+};
+
+class LibremKey : public Device {
+ public:
+ LibremKey();
+};
+
+}
+}
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/device_proto.h b/libnitrokey-v3.6/libnitrokey/device_proto.h
new file mode 100644
index 0000000..6ffe5fb
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/device_proto.h
@@ -0,0 +1,491 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef DEVICE_PROTO_H
+#define DEVICE_PROTO_H
+
+#include <utility>
+#include <thread>
+#include <type_traits>
+#include <stdexcept>
+#include <string>
+// a local version for compatibility with Windows
+#include <stdint.h>
+#include "cxx_semantics.h"
+#include "device.h"
+#include "misc.h"
+#include "log.h"
+#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
+
+#define PAYLOAD_SIZE 53
+#define PWS_SLOT_COUNT 16
+#define PWS_SLOTNAME_LENGTH 11
+#define PWS_PASSWORD_LENGTH 20
+#define PWS_LOGINNAME_LENGTH 32
+
+#define PWS_SEND_PASSWORD 0
+#define PWS_SEND_LOGINNAME 1
+#define PWS_SEND_TAB 2
+#define PWS_SEND_CR 3
+
+#include <mutex>
+#include "DeviceCommunicationExceptions.h"
+#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
+
+namespace nitrokey {
+ namespace proto {
+ extern std::mutex send_receive_mtx;
+
+
+/*
+ * POD types for HID proto commands
+ * Instances are meant to be __packed.
+ *
+ * TODO (future) support for Big Endian
+ */
+#pragma pack (push,1)
+/*
+ * Every packet is a USB HID report (check USB spec)
+ */
+ template<CommandID cmd_id, typename Payload>
+ struct HIDReport {
+ uint8_t _zero;
+ CommandID command_id; // uint8_t
+ union {
+ uint8_t _padding[HID_REPORT_SIZE - 6];
+ Payload payload;
+ } __packed;
+ uint32_t crc;
+
+ // POD types can't have non-default constructors
+ // used in Transaction<>::run()
+ void initialize() {
+ bzero(this, sizeof *this);
+ command_id = cmd_id;
+ }
+
+ uint32_t calculate_CRC() const {
+ // w/o leading zero, a part of each HID packet
+ // w/o 4-byte crc
+ return misc::stm_crc32((const uint8_t *) (this) + 1,
+ (size_t) (HID_REPORT_SIZE - 5));
+ }
+
+ void update_CRC() { crc = calculate_CRC(); }
+
+ bool isCRCcorrect() const { return crc == calculate_CRC(); }
+
+ bool isValid() const {
+ return true;
+ // return !_zero && payload.isValid() && isCRCcorrect();
+ }
+
+ operator std::string() const {
+ // Packet type is known upfront in normal operation.
+ // Can't be used to dissect random packets.
+ return QueryDissector<cmd_id, decltype(*this)>::dissect(*this);
+ }
+ } __packed;
+
+/*
+ * Response payload (the parametrized type inside struct HIDReport)
+ *
+ * command_id member in incoming HIDReport structure carries the command
+ * type last used.
+ */
+ 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 wrapping_size = header_size + footer_size;
+ }
+
+ template<CommandID cmd_id, typename ResponsePayload>
+ struct DeviceResponse {
+ static constexpr auto storage_status_padding_size =
+ DeviceResponseConstants::storage_status_absolute_address - DeviceResponseConstants::header_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 - DeviceResponseConstants::wrapping_size];
+ ResponsePayload payload;
+ struct {
+ 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
+ uint8_t progress_bar_value;
+ } __packed storage_status;
+ } __packed;
+
+ uint32_t crc;
+
+ void initialize() { bzero(this, sizeof *this); }
+
+ uint32_t calculate_CRC() const {
+ // w/o leading zero, a part of each HID packet
+ // w/o 4-byte crc
+ return misc::stm_crc32((const uint8_t *) (this) + 1,
+ (size_t) (HID_REPORT_SIZE - 5));
+ }
+
+ 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);
+ return crc != 0;
+ }
+
+ operator std::string() const {
+ return ResponseDissector<cmd_id, decltype(*this)>::dissect(*this);
+ }
+ } __packed;
+
+ struct EmptyPayload {
+ bool isValid() const { return true; }
+
+ std::string dissect() const { return std::string("Empty Payload."); }
+ } __packed;
+
+ template<typename command_packet, typename response_payload>
+ class ClearingProxy {
+ public:
+ ClearingProxy(command_packet &p) {
+ packet = p;
+ bzero(&p, sizeof(p));
+ }
+
+ ~ClearingProxy() {
+ bzero(&packet, sizeof(packet));
+ }
+
+ response_payload &data() {
+ return packet.payload;
+ }
+
+ command_packet packet;
+ };
+
+ template<CommandID cmd_id, typename command_payload, typename response_payload>
+ class Transaction : semantics::non_constructible {
+ public:
+ // Types declared in command class scope can't be reached from there.
+ typedef command_payload CommandPayload;
+ typedef response_payload ResponsePayload;
+
+
+ typedef struct HIDReport<cmd_id, CommandPayload> OutgoingPacket;
+ typedef struct DeviceResponse<cmd_id, ResponsePayload> ResponsePacket;
+#pragma pack (pop)
+
+ static_assert(std::is_pod<OutgoingPacket>::value,
+ "outgoingpacket must be a pod type");
+ static_assert(std::is_pod<ResponsePacket>::value,
+ "ResponsePacket must be a POD type");
+ static_assert(sizeof(OutgoingPacket) == HID_REPORT_SIZE,
+ "OutgoingPacket type is not the right size");
+ static_assert(sizeof(ResponsePacket) == HID_REPORT_SIZE,
+ "ResponsePacket type is not the right size");
+
+ static uint32_t getCRC(
+ const command_payload &payload) {
+ OutgoingPacket outp;
+ outp.initialize();
+ outp.payload = payload;
+ outp.update_CRC();
+ return outp.crc;
+ }
+
+ template<typename T>
+ static void clear_packet(T &st) {
+ bzero(&st, sizeof(st));
+ }
+
+ static ClearingProxy<ResponsePacket, response_payload> run(std::shared_ptr<device::Device> dev,
+ const command_payload &payload) {
+ using namespace ::nitrokey::device;
+ using namespace ::nitrokey::log;
+ using namespace std::chrono_literals;
+
+ std::lock_guard<std::mutex> guard(send_receive_mtx);
+
+ LOG(__FUNCTION__, Loglevel::DEBUG_L2);
+
+ if (dev == nullptr){
+ LOG(std::string("Throw: Device not initialized"), Loglevel::DEBUG_L1);
+ throw DeviceNotConnected("Device not initialized");
+ }
+ dev->m_counters.total_comm_runs++;
+
+ int status = 0;
+ OutgoingPacket outp;
+ ResponsePacket resp;
+
+ // POD types can't have non-default constructors
+ outp.initialize();
+ resp.initialize();
+
+ outp.payload = payload;
+ outp.update_CRC();
+
+ LOG("-------------------", Loglevel::DEBUG);
+ LOG("Outgoing HID packet:", Loglevel::DEBUG);
+ LOG(static_cast<std::string>(outp), Loglevel::DEBUG);
+ LOG(std::string("=> ") + std::string(commandid_to_string(static_cast<CommandID>(outp.command_id))), Loglevel::DEBUG_L1);
+
+
+ if (!outp.isValid()) {
+ LOG(std::string("Throw: Invalid outgoing packet"), Loglevel::DEBUG_L1);
+ throw DeviceSendingFailure("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) {
+ dev->m_counters.sends_executed++;
+ status = dev->send(&outp);
+ if (status <= 0){
+ //FIXME early disconnection not yet working properly
+// LOG("Encountered communication error, disconnecting device", Loglevel::DEBUG_L2);
+// dev->disconnect();
+ dev->m_counters.sending_error++;
+ LOG(std::string("Throw: Device error while sending command "), Loglevel::DEBUG_L1);
+ throw DeviceSendingFailure(
+ std::string("Device error while sending command ") +
+ std::to_string(status));
+ }
+
+ std::this_thread::sleep_for(dev->get_send_receive_delay());
+
+ // FIXME make checks done in device:recv here
+ receiving_retry_counter = dev->get_retry_receiving_count();
+ int busy_counter = 0;
+ auto retry_timeout = dev->get_retry_timeout();
+ while (receiving_retry_counter-- > 0) {
+ dev->m_counters.recv_executed++;
+ status = dev->recv(&resp);
+
+ if (dev->get_device_model() == DeviceModel::STORAGE &&
+ resp.command_id >= stick20::CMD_START_VALUE &&
+ resp.command_id < stick20::CMD_END_VALUE ) {
+ LOG(std::string("Detected storage device cmd, status: ") +
+ std::to_string(resp.storage_status.device_status), Loglevel::DEBUG_L2);
+
+ resp.last_command_status = static_cast<uint8_t>(stick10::command_status::ok);
+ switch (static_cast<stick20::device_status>(resp.storage_status.device_status)) {
+ case stick20::device_status::idle :
+ case stick20::device_status::ok:
+ resp.device_status = static_cast<uint8_t>(stick10::device_status::ok);
+ break;
+ case stick20::device_status::busy:
+ case stick20::device_status::busy_progressbar: //TODO this will be modified later for getting progressbar status
+ resp.device_status = static_cast<uint8_t>(stick10::device_status::busy);
+ break;
+ case stick20::device_status::wrong_password:
+ resp.last_command_status = static_cast<uint8_t>(stick10::command_status::wrong_password);
+ resp.device_status = static_cast<uint8_t>(stick10::device_status::ok);
+ break;
+ case stick20::device_status::no_user_password_unlock:
+ resp.last_command_status = static_cast<uint8_t>(stick10::command_status::AES_dec_failed);
+ resp.device_status = static_cast<uint8_t>(stick10::device_status::ok);
+ break;
+ default:
+ LOG(std::string("Unknown storage device status, cannot translate: ") +
+ std::to_string(resp.storage_status.device_status), Loglevel::DEBUG);
+ resp.device_status = resp.storage_status.device_status;
+ break;
+ };
+ }
+
+ //Some of the commands return wrong CRC, for now skip checking it (TODO list and report)
+ //if (resp.device_status == 0 && resp.last_command_crc == outp.crc && resp.isCRCcorrect()) break;
+ auto CRC_equal_awaited = true; // resp.last_command_crc == outp.crc;
+ if (resp.device_status == static_cast<uint8_t>(stick10::device_status::ok) &&
+ CRC_equal_awaited && resp.isValid()){
+ successful_communication = true;
+ break;
+ }
+ if (resp.device_status == static_cast<uint8_t>(stick10::device_status::busy)) {
+ dev->m_counters.busy++;
+
+ if (busy_counter++<10) {
+ receiving_retry_counter++;
+ LOG("Status busy, not decreasing receiving_retry_counter counter: " +
+ std::to_string(receiving_retry_counter), Loglevel::DEBUG_L2);
+ } else {
+ retry_timeout *= 2;
+ retry_timeout = std::min(retry_timeout, 300ms);
+ busy_counter = 0;
+ LOG("Status busy, decreasing receiving_retry_counter counter: " +
+ std::to_string(receiving_retry_counter) + ", current delay:"
+ + std::to_string(retry_timeout.count()), Loglevel::DEBUG);
+ LOG(std::string("Busy retry: status ")
+ + std::to_string(resp.storage_status.device_status)
+ + ", "
+ + std::to_string(retry_timeout.count())
+ + "ms, counter "
+ + std::to_string(receiving_retry_counter)
+ + ", progress: "
+ + std::to_string(resp.storage_status.progress_bar_value)
+ , Loglevel::DEBUG_L1);
+ }
+ }
+ if (resp.device_status == static_cast<uint8_t>(stick10::device_status::busy) &&
+ static_cast<stick20::device_status>(resp.storage_status.device_status)
+ == stick20::device_status::busy_progressbar){
+ successful_communication = true;
+ break;
+ }
+ LOG(std::string("Retry status - dev status, awaited cmd crc, correct packet CRC: ")
+ + std::to_string(resp.device_status) +
+ " " + std::to_string(CRC_equal_awaited) +
+ " " + std::to_string(resp.isCRCcorrect()), Loglevel::DEBUG_L2);
+
+ if (!resp.isCRCcorrect()) dev->m_counters.wrong_CRC++;
+ if (!CRC_equal_awaited) dev->m_counters.CRC_other_than_awaited++;
+
+
+ LOG(
+ "Device is not ready or received packet's last CRC is not equal to sent CRC packet, retrying...",
+ Loglevel::DEBUG_L2);
+ LOG("Invalid incoming HID packet:", Loglevel::DEBUG_L2);
+ LOG(static_cast<std::string>(resp), Loglevel::DEBUG_L2);
+ dev->m_counters.total_retries++;
+ LOG(".", Loglevel::DEBUG_L1);
+ std::this_thread::sleep_for(retry_timeout);
+ continue;
+ }
+ if (successful_communication) break;
+ LOG(std::string("Resending (outer loop) "), Loglevel::DEBUG_L2);
+ LOG(std::string("sending_retry_counter count: ") + std::to_string(sending_retry_counter),
+ Loglevel::DEBUG);
+ }
+
+ if(resp.last_command_crc != outp.crc){
+ LOG(std::string("Accepting response with CRC other than expected ")
+ + "Command ID: " + std::to_string(resp.command_id) + " " +
+ commandid_to_string(static_cast<CommandID>(resp.command_id)) + " "
+ + "Reported by response and expected: " + std::to_string(resp.last_command_crc) + "!=" + std::to_string(outp.crc),
+ Loglevel::WARNING
+ );
+ }
+
+ dev->set_last_command_status(resp.last_command_status); // FIXME should be handled on device.recv
+
+ clear_packet(outp);
+
+
+ if (status <= 0) {
+ dev->m_counters.receiving_error++;
+ LOG(std::string("Throw: Device error while executing command "), Loglevel::DEBUG_L1);
+ throw DeviceReceivingFailure( //FIXME replace with CriticalErrorException
+ std::string("Device error while executing command ") +
+ std::to_string(status));
+ }
+
+ LOG(std::string("<= ") +
+ std::string(
+ commandid_to_string(static_cast<CommandID>(resp.command_id))
+ + std::string(" ")
+ + std::to_string(resp.device_status)
+ + std::string(" ")
+ + std::to_string(resp.storage_status.device_status)
+// + std::to_string( status_translate_command(resp.storage_status.device_status))
+ ), Loglevel::DEBUG_L1);
+
+ LOG("Incoming HID packet:", Loglevel::DEBUG);
+ LOG(static_cast<std::string>(resp), Loglevel::DEBUG);
+ if (dev->get_retry_receiving_count() - receiving_retry_counter > 2) {
+ LOG(std::string("Packet received with receiving_retry_counter count: ") +
+ std::to_string(receiving_retry_counter),
+ Loglevel::DEBUG_L1);
+ }
+
+ if (resp.device_status == static_cast<uint8_t>(stick10::device_status::busy) &&
+ static_cast<stick20::device_status>(resp.storage_status.device_status)
+ == stick20::device_status::busy_progressbar){
+ dev->m_counters.busy_progressbar++;
+ LOG(std::string("Throw: Long operation in progress exception"), Loglevel::DEBUG_L1);
+ throw LongOperationInProgressException(
+ resp.command_id, resp.device_status, resp.storage_status.progress_bar_value);
+ }
+
+ if (!resp.isValid()) {
+ LOG(std::string("Throw: Invalid incoming packet"), Loglevel::DEBUG_L1);
+ throw InvalidCRCReceived("Invalid incoming packet");
+ }
+ if (receiving_retry_counter <= 0){
+ LOG(std::string("Throw: \"Maximum receiving_retry_counter count reached for receiving response from the device!\""
+ + std::to_string(receiving_retry_counter)), Loglevel::DEBUG_L1);
+ throw DeviceReceivingFailure(
+ "Maximum receiving_retry_counter count reached for receiving response from the device!");
+ }
+ dev->m_counters.communication_successful++;
+
+ if (resp.last_command_status != static_cast<uint8_t>(stick10::command_status::ok)){
+ dev->m_counters.command_result_not_equal_0_recv++;
+ LOG(std::string("Throw: CommandFailedException ") + std::to_string(resp.last_command_status), Loglevel::DEBUG_L1);
+ throw CommandFailedException(resp.command_id, resp.last_command_status);
+ }
+
+ dev->m_counters.command_successful_recv++;
+
+ if (dev->get_device_model() == DeviceModel::STORAGE &&
+ resp.command_id >= stick20::CMD_START_VALUE &&
+ resp.command_id < stick20::CMD_END_VALUE ) {
+ dev->m_counters.successful_storage_commands++;
+ }
+
+ if (!resp.isCRCcorrect())
+ LOG(std::string("Accepting response from device with invalid CRC. ")
+ + "Command ID: " + std::to_string(resp.command_id) + " " +
+ commandid_to_string(static_cast<CommandID>(resp.command_id)) + " "
+ + "Reported and calculated: " + std::to_string(resp.crc) + "!=" + std::to_string(resp.calculate_CRC()),
+ Loglevel::WARNING
+ );
+
+ // See: DeviceResponse
+ return resp;
+ }
+
+ static ClearingProxy<ResponsePacket, response_payload> run(std::shared_ptr<device::Device> dev) {
+ command_payload empty_payload;
+ return run(dev, empty_payload);
+ }
+ };
+ }
+}
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/dissect.h b/libnitrokey-v3.6/libnitrokey/dissect.h
new file mode 100644
index 0000000..690b5b7
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/dissect.h
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+/*
+ * Protocol packet dissection
+ */
+#ifndef DISSECT_H
+#define DISSECT_H
+#include <string>
+#include <sstream>
+#include <iomanip>
+#include "misc.h"
+#include "cxx_semantics.h"
+#include "command_id.h"
+#include "device_proto.h"
+
+namespace nitrokey {
+namespace proto {
+
+template <CommandID id, class HIDPacket>
+class QueryDissector : semantics::non_constructible {
+ public:
+ static std::string dissect(const HIDPacket &pod) {
+ std::stringstream out;
+
+#ifdef LOG_VOLATILE_DATA
+ out << "Raw HID packet:" << std::endl;
+ out << ::nitrokey::misc::hexdump((const uint8_t *)(&pod), sizeof pod);
+#endif
+
+ out << "Contents:" << std::endl;
+ out << "Command ID:\t" << commandid_to_string((CommandID)(pod.command_id))
+ << std::endl;
+ out << "CRC:\t"
+ << std::hex << std::setw(2) << std::setfill('0')
+ << pod.crc << std::endl;
+
+ out << "Payload:" << std::endl;
+ out << pod.payload.dissect();
+ return out.str();
+ }
+};
+
+
+
+
+template <CommandID id, class HIDPacket>
+class ResponseDissector : semantics::non_constructible {
+ public:
+ static std::string status_translate_device(int status){
+ auto enum_status = static_cast<proto::stick10::device_status>(status);
+ switch (enum_status){
+ case stick10::device_status::ok: return "OK";
+ case stick10::device_status::busy: return "BUSY";
+ case stick10::device_status::error: return "ERROR";
+ case stick10::device_status::received_report: return "RECEIVED_REPORT";
+ }
+ return std::string("UNKNOWN: ") + std::to_string(status);
+ }
+
+ static std::string to_upper(std::string str){
+ for (auto & c: str) c = toupper(c);
+ return str;
+ }
+ static std::string status_translate_command(int status){
+ auto enum_status = static_cast<proto::stick10::command_status >(status);
+ switch (enum_status) {
+#define p(X) case X: return to_upper(std::string(#X));
+ p(stick10::command_status::ok)
+ p(stick10::command_status::wrong_CRC)
+ p(stick10::command_status::wrong_slot)
+ p(stick10::command_status::slot_not_programmed)
+ p(stick10::command_status::wrong_password)
+ p(stick10::command_status::not_authorized)
+ p(stick10::command_status::timestamp_warning)
+ p(stick10::command_status::no_name_error)
+ p(stick10::command_status::not_supported)
+ p(stick10::command_status::unknown_command)
+ p(stick10::command_status::AES_dec_failed)
+#undef p
+ }
+ return std::string("UNKNOWN: ") + std::to_string(status);
+ }
+
+ static std::string dissect(const HIDPacket &pod) {
+ std::stringstream out;
+
+ // FIXME use values from firmware (possibly generate separate
+ // header automatically)
+
+#ifdef LOG_VOLATILE_DATA
+ out << "Raw HID packet:" << std::endl;
+ out << ::nitrokey::misc::hexdump((const uint8_t *)(&pod), sizeof pod);
+#endif
+
+ out << "Device status:\t" << pod.device_status + 0 << " "
+ << status_translate_device(pod.device_status) << std::endl;
+ out << "Command ID:\t" << commandid_to_string((CommandID)(pod.command_id)) << " hex: " << std::hex << (int)pod.command_id
+ << std::endl;
+ out << "Last command CRC:\t"
+ << std::hex << std::setw(2) << std::setfill('0')
+ << pod.last_command_crc << std::endl;
+ out << "Last command status:\t" << pod.last_command_status + 0 << " "
+ << status_translate_command(pod.last_command_status) << std::endl;
+ out << "CRC:\t"
+ << std::hex << std::setw(2) << std::setfill('0')
+ << pod.crc << std::endl;
+ if((int)pod.command_id == pod.storage_status.command_id){
+ out << "Storage stick status (where applicable):" << std::endl;
+#define d(x) out << " "#x": \t"<< std::hex << std::setw(2) \
+ << std::setfill('0')<< static_cast<int>(x) << std::endl;
+ d(pod.storage_status.command_counter);
+ d(pod.storage_status.command_id);
+ d(pod.storage_status.device_status);
+ d(pod.storage_status.progress_bar_value);
+#undef d
+ }
+
+ out << "Payload:" << std::endl;
+ out << pod.payload.dissect();
+ return out.str();
+ }
+};
+}
+}
+
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/hidapi/hidapi.h b/libnitrokey-v3.6/libnitrokey/hidapi/hidapi.h
new file mode 100644
index 0000000..e5bc2dc
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/hidapi/hidapi.h
@@ -0,0 +1,391 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 8/22/2009
+
+ Copyright 2009, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+/** @file
+ * @defgroup API hidapi API
+ */
+
+#ifndef HIDAPI_H__
+#define HIDAPI_H__
+
+#include <wchar.h>
+
+#ifdef _WIN32
+ #define HID_API_EXPORT __declspec(dllexport)
+ #define HID_API_CALL
+#else
+ #define HID_API_EXPORT /**< API export macro */
+ #define HID_API_CALL /**< API call macro */
+#endif
+
+#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ struct hid_device_;
+ typedef struct hid_device_ hid_device; /**< opaque hidapi structure */
+
+ /** hidapi info structure */
+ struct hid_device_info {
+ /** Platform-specific device path */
+ char *path;
+ /** Device Vendor ID */
+ unsigned short vendor_id;
+ /** Device Product ID */
+ unsigned short product_id;
+ /** Serial Number */
+ wchar_t *serial_number;
+ /** Device Release Number in binary-coded decimal,
+ also known as Device Version Number */
+ unsigned short release_number;
+ /** Manufacturer String */
+ wchar_t *manufacturer_string;
+ /** Product string */
+ wchar_t *product_string;
+ /** Usage Page for this Device/Interface
+ (Windows/Mac only). */
+ unsigned short usage_page;
+ /** Usage for this Device/Interface
+ (Windows/Mac only).*/
+ unsigned short usage;
+ /** The USB interface which this logical device
+ represents. Valid on both Linux implementations
+ in all cases, and valid on the Windows implementation
+ only if the device contains more than one interface. */
+ int interface_number;
+
+ /** Pointer to the next device */
+ struct hid_device_info *next;
+ };
+
+
+ /** @brief Initialize the HIDAPI library.
+
+ This function initializes the HIDAPI library. Calling it is not
+ strictly necessary, as it will be called automatically by
+ hid_enumerate() and any of the hid_open_*() functions if it is
+ needed. This function should be called at the beginning of
+ execution however, if there is a chance of HIDAPI handles
+ being opened by different threads simultaneously.
+
+ @ingroup API
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_init(void);
+
+ /** @brief Finalize the HIDAPI library.
+
+ This function frees all of the static data associated with
+ HIDAPI. It should be called at the end of execution to avoid
+ memory leaks.
+
+ @ingroup API
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_exit(void);
+
+ /** @brief Enumerate the HID Devices.
+
+ This function returns a linked list of all the HID devices
+ attached to the system which match vendor_id and product_id.
+ If @p vendor_id is set to 0 then any vendor matches.
+ If @p product_id is set to 0 then any product matches.
+ If @p vendor_id and @p product_id are both set to 0, then
+ all HID devices will be returned.
+
+ @ingroup API
+ @param vendor_id The Vendor ID (VID) of the types of device
+ to open.
+ @param product_id The Product ID (PID) of the types of
+ device to open.
+
+ @returns
+ This function returns a pointer to a linked list of type
+ struct #hid_device, containing information about the HID devices
+ attached to the system, or NULL in the case of failure. Free
+ this linked list by calling hid_free_enumeration().
+ */
+ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);
+
+ /** @brief Free an enumeration Linked List
+
+ This function frees a linked list created by hid_enumerate().
+
+ @ingroup API
+ @param devs Pointer to a list of struct_device returned from
+ hid_enumerate().
+ */
+ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs);
+
+ /** @brief Open a HID device using a Vendor ID (VID), Product ID
+ (PID) and optionally a serial number.
+
+ If @p serial_number is NULL, the first device with the
+ specified VID and PID is opened.
+
+ @ingroup API
+ @param vendor_id The Vendor ID (VID) of the device to open.
+ @param product_id The Product ID (PID) of the device to open.
+ @param serial_number The Serial Number of the device to open
+ (Optionally NULL).
+
+ @returns
+ This function returns a pointer to a #hid_device object on
+ success or NULL on failure.
+ */
+ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number);
+
+ /** @brief Open a HID device by its path name.
+
+ The path name be determined by calling hid_enumerate(), or a
+ platform-specific path name can be used (eg: /dev/hidraw0 on
+ Linux).
+
+ @ingroup API
+ @param path The path name of the device to open
+
+ @returns
+ This function returns a pointer to a #hid_device object on
+ success or NULL on failure.
+ */
+ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path);
+
+ /** @brief Write an Output report to a HID device.
+
+ The first byte of @p data[] must contain the Report ID. For
+ devices which only support a single report, this must be set
+ to 0x0. The remaining bytes contain the report data. Since
+ the Report ID is mandatory, calls to hid_write() will always
+ contain one more byte than the report contains. For example,
+ if a hid report is 16 bytes long, 17 bytes must be passed to
+ hid_write(), the Report ID (or 0x0, for devices with a
+ single report), followed by the report data (16 bytes). In
+ this example, the length passed in would be 17.
+
+ hid_write() will send the data on the first OUT endpoint, if
+ one exists. If it does not, it will send the data through
+ the Control Endpoint (Endpoint 0).
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data The data to send, including the report number as
+ the first byte.
+ @param length The length in bytes of the data to send.
+
+ @returns
+ This function returns the actual number of bytes written and
+ -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);
+
+ /** @brief Read an Input report from a HID device with timeout.
+
+ Input reports are returned
+ to the host through the INTERRUPT IN endpoint. The first byte will
+ contain the Report number if the device uses numbered reports.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into.
+ @param length The number of bytes to read. For devices with
+ multiple reports, make sure to read an extra byte for
+ the report number.
+ @param milliseconds timeout in milliseconds or -1 for blocking wait.
+
+ @returns
+ This function returns the actual number of bytes read and
+ -1 on error. If no packet was available to be read within
+ the timeout period, this function returns 0.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds);
+
+ /** @brief Read an Input report from a HID device.
+
+ Input reports are returned
+ to the host through the INTERRUPT IN endpoint. The first byte will
+ contain the Report number if the device uses numbered reports.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into.
+ @param length The number of bytes to read. For devices with
+ multiple reports, make sure to read an extra byte for
+ the report number.
+
+ @returns
+ This function returns the actual number of bytes read and
+ -1 on error. If no packet was available to be read and
+ the handle is in non-blocking mode, this function returns 0.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);
+
+ /** @brief Set the device handle to be non-blocking.
+
+ In non-blocking mode calls to hid_read() will return
+ immediately with a value of 0 if there is no data to be
+ read. In blocking mode, hid_read() will wait (block) until
+ there is data to read before returning.
+
+ Nonblocking can be turned on and off at any time.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param nonblock enable or not the nonblocking reads
+ - 1 to enable nonblocking
+ - 0 to disable nonblocking.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock);
+
+ /** @brief Send a Feature report to the device.
+
+ Feature reports are sent over the Control endpoint as a
+ Set_Report transfer. The first byte of @p data[] must
+ contain the Report ID. For devices which only support a
+ single report, this must be set to 0x0. The remaining bytes
+ contain the report data. Since the Report ID is mandatory,
+ calls to hid_send_feature_report() will always contain one
+ more byte than the report contains. For example, if a hid
+ report is 16 bytes long, 17 bytes must be passed to
+ hid_send_feature_report(): the Report ID (or 0x0, for
+ devices which do not use numbered reports), followed by the
+ report data (16 bytes). In this example, the length passed
+ in would be 17.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data The data to send, including the report number as
+ the first byte.
+ @param length The length in bytes of the data to send, including
+ the report number.
+
+ @returns
+ This function returns the actual number of bytes written and
+ -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length);
+
+ /** @brief Get a feature report from a HID device.
+
+ Set the first byte of @p data[] to the Report ID of the
+ report to be read. Make sure to allow space for this
+ extra byte in @p data[]. Upon return, the first byte will
+ still contain the Report ID, and the report data will
+ start in data[1].
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into, including
+ the Report ID. Set the first byte of @p data[] to the
+ Report ID of the report to be read, or set it to zero
+ if your device does not use numbered reports.
+ @param length The number of bytes to read, including an
+ extra byte for the report ID. The buffer can be longer
+ than the actual report.
+
+ @returns
+ This function returns the number of bytes read plus
+ one for the report ID (which is still in the first
+ byte), or -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length);
+
+ /** @brief Close a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ */
+ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device);
+
+ /** @brief Get The Manufacturer String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get The Product String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get The Serial Number String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get a string from a HID device, based on its string index.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string_index The index of the string to get.
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen);
+
+ /** @brief Get a string describing the last error which occurred.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+
+ @returns
+ This function returns a string containing the last error
+ which occurred or NULL if none has occurred.
+ */
+ HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/libnitrokey-v3.6/libnitrokey/log.h b/libnitrokey-v3.6/libnitrokey/log.h
new file mode 100644
index 0000000..eade68f
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/log.h
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef LOG_H
+#define LOG_H
+
+#include <string>
+#include <functional>
+
+namespace nitrokey {
+ namespace log {
+
+//for MSVC
+#ifdef ERROR
+#undef ERROR
+#endif
+
+
+ enum class Loglevel : int {
+ ERROR,
+ WARNING,
+ INFO,
+ DEBUG_L1,
+ DEBUG,
+ DEBUG_L2
+ };
+
+ class LogHandler {
+ public:
+ virtual void print(const std::string &, Loglevel lvl) = 0;
+ virtual ~LogHandler() = default;
+ protected:
+ std::string loglevel_to_str(Loglevel);
+ std::string format_message_to_string(const std::string &str, const Loglevel &lvl);
+
+ };
+
+ class StdlogHandler : public LogHandler {
+ public:
+ virtual void print(const std::string &, Loglevel lvl);
+ };
+
+ class FunctionalLogHandler : public LogHandler {
+ using log_function_type = std::function<void(std::string)>;
+ log_function_type log_function;
+ public:
+ FunctionalLogHandler(log_function_type _log_function);
+ virtual void print(const std::string &, Loglevel lvl);
+
+ };
+
+ extern StdlogHandler stdlog_handler;
+
+ class Log {
+ public:
+ Log() : mp_loghandler(&stdlog_handler), m_loglevel(Loglevel::WARNING) {}
+
+ static Log &instance() {
+ if (mp_instance == nullptr) mp_instance = new Log;
+ return *mp_instance;
+ }
+
+ void operator()(const std::string &, Loglevel);
+ void set_loglevel(Loglevel lvl) { m_loglevel = lvl; }
+ void set_handler(LogHandler *handler) { mp_loghandler = handler; }
+
+ private:
+ LogHandler *mp_loghandler;
+ Loglevel m_loglevel;
+ static std::string prefix;
+ public:
+ static void setPrefix(std::string prefix = std::string());
+
+ private:
+
+ static Log *mp_instance;
+ };
+ }
+}
+
+
+#ifdef NO_LOG
+#define LOG(string, level) while(false){}
+#define LOGD(string) while(false){}
+#define LOGD1(string) while(false){}
+#else
+#define LOG(string, level) nitrokey::log::Log::instance()((string), (level))
+#define LOGD1(string) nitrokey::log::Log::instance()((string), (nitrokey::log::Loglevel::DEBUG_L1))
+#define LOGD(string) nitrokey::log::Log::instance()((string), (nitrokey::log::Loglevel::DEBUG_L2))
+#endif
+
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/misc.h b/libnitrokey-v3.6/libnitrokey/misc.h
new file mode 100644
index 0000000..a9c4672
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/misc.h
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+
+#ifndef MISC_H
+#define MISC_H
+#include <stdio.h>
+#include <string>
+#include <vector>
+#include <string.h>
+#include "log.h"
+#include "LibraryException.h"
+#include <sstream>
+#include <stdexcept>
+#include <iomanip>
+
+
+namespace nitrokey {
+namespace misc {
+
+/**
+ * Simple replacement for std::optional (C++17).
+ */
+template<typename T>
+class Option {
+public:
+ Option() : m_hasValue(false), m_value() {}
+ Option(T value) : m_hasValue(true), m_value(value) {}
+
+ bool has_value() const {
+ return m_hasValue;
+ }
+ T value() const {
+ if (!m_hasValue) {
+ throw std::logic_error("Called Option::value without value");
+ }
+ return m_value;
+ }
+
+private:
+ bool m_hasValue;
+ T m_value;
+};
+
+ template<typename T>
+ std::string toHex(T value){
+ using namespace std;
+ std::ostringstream oss;
+ oss << std::hex << std::setw(sizeof(value)*2) << std::setfill('0') << value;
+ return oss.str();
+ }
+
+#define FIELD_WIDTH_MAX (100)
+ /**
+ * Copies string from pointer to fixed size C-style array. Src needs to be a valid C-string - eg. ended with '\0'.
+ * Throws when source is bigger than destination.
+ * @tparam T type of destination array
+ * @param dest fixed size destination array
+ * @param src pointer to source c-style valid string
+ */
+ template <typename T>
+ void strcpyT(T& dest, const char* src){
+
+ if (src == nullptr)
+// throw EmptySourceStringException(slot_number);
+ return;
+ const size_t s_dest = sizeof dest;
+ const size_t src_strlen = strnlen(src, FIELD_WIDTH_MAX);
+ LOG(std::string("strcpyT sizes dest src ")
+ + std::to_string(s_dest) + " "
+ + std::to_string(src_strlen) + " "
+ , nitrokey::log::Loglevel::DEBUG_L2);
+ if (src_strlen > s_dest){
+ throw TooLongStringException(src_strlen, s_dest, src);
+ }
+ strncpy((char*) &dest, src, s_dest);
+ }
+
+#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
+ template <typename T>
+typename T::CommandPayload get_payload(){
+ //Create, initialize and return by value command payload
+ typename T::CommandPayload st;
+ bzero(&st, sizeof(st));
+ return st;
+}
+
+ template<typename CMDTYPE, typename Tdev>
+ void execute_password_command(Tdev &stick, const char *password) {
+ auto p = get_payload<CMDTYPE>();
+ p.set_defaults();
+ strcpyT(p.password, password);
+ CMDTYPE::CommandTransaction::run(stick, p);
+ }
+
+ std::string hexdump(const uint8_t *p, size_t size, bool print_header=true, bool print_ascii=true,
+ bool print_empty=true);
+ uint32_t stm_crc32(const uint8_t *data, size_t size);
+ std::vector<uint8_t> hex_string_to_byte(const char* hexString);
+}
+}
+
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/stick10_commands.h b/libnitrokey-v3.6/libnitrokey/stick10_commands.h
new file mode 100644
index 0000000..5e8a5aa
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/stick10_commands.h
@@ -0,0 +1,929 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef STICK10_COMMANDS_H
+#define STICK10_COMMANDS_H
+
+#include <bitset>
+#include <iomanip>
+#include <string>
+#include <sstream>
+#include <stdint.h>
+#include "device_proto.h"
+#include "command.h"
+
+#pragma pack (push,1)
+
+namespace nitrokey {
+namespace proto {
+
+
+
+/*
+ * Stick10 protocol definition
+ */
+namespace stick10 {
+class GetSlotName : public Command<CommandID::READ_SLOT_NAME> {
+ public:
+ // reachable as a typedef in Transaction
+ struct CommandPayload {
+ uint8_t slot_number;
+
+ bool isValid() const { return slot_number<0x10+3; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ uint8_t slot_name[15];
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(slot_name);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload,
+ struct ResponsePayload> CommandTransaction;
+};
+
+class EraseSlot : Command<CommandID::ERASE_SLOT> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class SetTime : Command<CommandID::SET_TIME> {
+ public:
+ struct CommandPayload {
+ uint8_t reset; // 0 - get time, 1 - set time
+ uint64_t time; // posix time
+
+ bool isValid() const { return reset && reset != 1; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "reset:\t" << (int)(reset) << std::endl;
+ ss << "time:\t" << (time) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+
+class WriteToHOTPSlot : Command<CommandID::WRITE_TO_SLOT> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint8_t slot_name[15];
+ uint8_t slot_secret[20];
+ union{
+ uint8_t _slot_config;
+ struct{
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ union{
+ uint8_t slot_token_id[13]; /** OATH Token Identifier */
+ struct{ /** @see https://openauthentication.org/token-specs/ */
+ uint8_t omp[2];
+ uint8_t tt[2];
+ uint8_t mui[8];
+ uint8_t keyboard_layout; //disabled feature in nitroapp as of 20160805
+ } slot_token_fields;
+ };
+ union{
+ uint64_t slot_counter;
+ uint8_t slot_counter_s[8];
+ } __packed;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ print_to_ss_volatile(slot_name);
+ print_to_ss_volatile(slot_secret);
+ ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl;
+ ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl;
+ ss << "\tuse_enter(1):\t" << use_enter << std::endl;
+ ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl;
+
+ ss << "slot_token_id:\t";
+ for (auto i : slot_token_id)
+ ss << std::hex << std::setw(2) << std::setfill('0')<< (int) i << " " ;
+ ss << std::endl;
+ ss << "slot_counter:\t[" << (int)slot_counter << "]\t"
+ << ::nitrokey::misc::hexdump((const uint8_t *)(&slot_counter), sizeof slot_counter, false);
+
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class WriteToTOTPSlot : Command<CommandID::WRITE_TO_SLOT> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint8_t slot_name[15];
+ uint8_t slot_secret[20];
+ union{
+ uint8_t _slot_config;
+ struct{
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ union{
+ uint8_t slot_token_id[13]; /** OATH Token Identifier */
+ struct{ /** @see https://openauthentication.org/token-specs/ */
+ uint8_t omp[2];
+ uint8_t tt[2];
+ uint8_t mui[8];
+ uint8_t keyboard_layout; //disabled feature in nitroapp as of 20160805
+ } slot_token_fields;
+ };
+ uint16_t slot_interval;
+
+ bool isValid() const { return !(slot_number & 0xF0); } //TODO check
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ print_to_ss_volatile(slot_name);
+ print_to_ss_volatile(slot_secret);
+ ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl;
+ ss << "slot_token_id:\t";
+ for (auto i : slot_token_id)
+ ss << std::hex << std::setw(2) << std::setfill('0')<< (int) i << " " ;
+ ss << std::endl;
+ ss << "slot_interval:\t" << (int)slot_interval << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class GetTOTP : Command<CommandID::GET_CODE> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint64_t challenge;
+ uint64_t last_totp_time;
+ uint8_t last_interval;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ ss << "challenge:\t" << (challenge) << std::endl;
+ ss << "last_totp_time:\t" << (last_totp_time) << std::endl;
+ ss << "last_interval:\t" << (int)(last_interval) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ union {
+ uint8_t whole_response[18]; //14 bytes reserved for config, but used only 1
+ struct {
+ uint32_t code;
+ union{
+ uint8_t _slot_config;
+ struct{
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ } __packed ;
+ } __packed ;
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "code:\t" << (code) << std::endl;
+ ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl;
+ ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl;
+ ss << "\tuse_enter(1):\t" << use_enter << std::endl;
+ ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct ResponsePayload>
+ CommandTransaction;
+};
+
+class GetHOTP : Command<CommandID::GET_CODE> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+
+ bool isValid() const { return (slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ union {
+ uint8_t whole_response[18]; //14 bytes reserved for config, but used only 1
+ struct {
+ uint32_t code;
+ union{
+ uint8_t _slot_config;
+ struct{
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ } __packed;
+ } __packed;
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "code:\t" << (code) << std::endl;
+ ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl;
+ ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl;
+ ss << "\tuse_enter(1):\t" << use_enter << std::endl;
+ ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct ResponsePayload>
+ CommandTransaction;
+};
+
+class ReadSlot : Command<CommandID::READ_SLOT> {
+ public:
+ enum class CounterFormat {
+ ASCII = 0,
+ BINARY = 1,
+ };
+ struct CommandPayload {
+ uint8_t slot_number;
+ CounterFormat data_format; //Storage v0.54+ only: slot_counter value format: 0 - in ascii, 1 - binary
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ uint8_t slot_name[15];
+ union{
+ uint8_t _slot_config;
+ struct{
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ union{
+ uint8_t slot_token_id[13]; /** OATH Token Identifier */
+ struct{ /** @see https://openauthentication.org/token-specs/ */
+ uint8_t omp[2];
+ uint8_t tt[2];
+ uint8_t mui[8];
+ uint8_t keyboard_layout; //disabled feature in nitroapp as of 20160805
+ } slot_token_fields;
+ };
+ union{
+ uint64_t slot_counter;
+ uint8_t slot_counter_s[8];
+ } __packed;
+
+ bool isValid() const { return true; }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(slot_name);
+ ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl;
+ ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl;
+ ss << "\tuse_enter(1):\t" << use_enter << std::endl;
+ ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl;
+
+ ss << "slot_token_id:\t";
+ for (auto i : slot_token_id)
+ ss << std::hex << std::setw(2) << std::setfill('0')<< (int) i << " " ;
+ ss << std::endl;
+ ss << "slot_counter:\t[" << (int)slot_counter << "]\t"
+ << ::nitrokey::misc::hexdump((const uint8_t *)(&slot_counter), sizeof slot_counter, false);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload,
+ struct ResponsePayload> CommandTransaction;
+};
+
+class GetStatus : Command<CommandID::GET_STATUS> {
+ public:
+ struct ResponsePayload {
+ union {
+ uint16_t firmware_version;
+ struct {
+ uint8_t minor;
+ uint8_t major;
+ } firmware_version_st;
+ };
+ union{
+ uint8_t card_serial[4];
+ uint32_t card_serial_u32;
+ } __packed;
+ union {
+ uint8_t general_config[5];
+ struct{
+ uint8_t numlock; /** 0-1: HOTP slot number from which the code will be get on double press, other value - function disabled */
+ uint8_t capslock; /** same as numlock */
+ uint8_t scrolllock; /** same as numlock */
+ uint8_t enable_user_password;
+ uint8_t delete_user_password; /* unused */
+ } __packed;
+ } __packed;
+
+ static constexpr uint8_t special_HOTP_slots = 2;
+ bool isValid() const { return numlock < special_HOTP_slots && capslock < special_HOTP_slots
+ && scrolllock < special_HOTP_slots && enable_user_password < 2; }
+
+ std::string get_card_serial_hex() const {
+ return nitrokey::misc::toHex(card_serial_u32);
+ }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "firmware_version:\t"
+ << "[" << firmware_version << "]" << "\t"
+ << ::nitrokey::misc::hexdump(
+ (const uint8_t *)(&firmware_version), sizeof firmware_version, false);
+ ss << "card_serial_u32:\t" << std::hex << card_serial_u32 << std::endl;
+ ss << "card_serial:\t"
+ << ::nitrokey::misc::hexdump((const uint8_t *)(card_serial),
+ sizeof card_serial, false);
+ ss << "general_config:\t"
+ << ::nitrokey::misc::hexdump((const uint8_t *)(general_config),
+ sizeof general_config, false);
+ ss << "numlock:\t" << (int)numlock << std::endl;
+ ss << "capslock:\t" << (int)capslock << std::endl;
+ ss << "scrolllock:\t" << (int)scrolllock << std::endl;
+ ss << "enable_user_password:\t" << (bool) enable_user_password << std::endl;
+ ss << "delete_user_password:\t" << (bool) delete_user_password << std::endl;
+
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct EmptyPayload, struct ResponsePayload>
+ CommandTransaction;
+};
+
+class GetPasswordRetryCount : Command<CommandID::GET_PASSWORD_RETRY_COUNT> {
+ public:
+ struct ResponsePayload {
+ uint8_t password_retry_count;
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " password_retry_count\t" << (int)password_retry_count << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct EmptyPayload, struct ResponsePayload>
+ CommandTransaction;
+};
+
+class GetUserPasswordRetryCount
+ : Command<CommandID::GET_USER_PASSWORD_RETRY_COUNT> {
+ public:
+ struct ResponsePayload {
+ uint8_t password_retry_count;
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " password_retry_count\t" << (int)password_retry_count << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct EmptyPayload, struct ResponsePayload>
+ CommandTransaction;
+};
+
+ template <typename T, typename Q, int N>
+ void write_array(T &ss, Q (&arr)[N]){
+ for (int i=0; i<N; i++){
+ ss << std::hex << std::setfill('0') << std::setw(2) << (int)arr[i] << " ";
+ }
+ ss << std::endl;
+ };
+
+
+class GetPasswordSafeSlotStatus : Command<CommandID::GET_PW_SAFE_SLOT_STATUS> {
+ public:
+ struct ResponsePayload {
+ uint8_t password_safe_status[PWS_SLOT_COUNT];
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "password_safe_status\t";
+ write_array(ss, password_safe_status);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct EmptyPayload, struct ResponsePayload>
+ CommandTransaction;
+};
+
+class GetPasswordSafeSlotName : Command<CommandID::GET_PW_SAFE_SLOT_NAME> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number\t" << (int)slot_number << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ uint8_t slot_name[PWS_SLOTNAME_LENGTH];
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(slot_name);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload,
+ struct ResponsePayload> CommandTransaction;
+};
+
+class GetPasswordSafeSlotPassword
+ : Command<CommandID::GET_PW_SAFE_SLOT_PASSWORD> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " slot_number\t" << (int)slot_number << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ uint8_t slot_password[PWS_PASSWORD_LENGTH];
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(slot_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload,
+ struct ResponsePayload> CommandTransaction;
+};
+
+class GetPasswordSafeSlotLogin
+ : Command<CommandID::GET_PW_SAFE_SLOT_LOGINNAME> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " slot_number\t" << (int)slot_number << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ uint8_t slot_login[PWS_LOGINNAME_LENGTH];
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(slot_login);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload,
+ struct ResponsePayload> CommandTransaction;
+};
+
+class SetPasswordSafeSlotData : Command<CommandID::SET_PW_SAFE_SLOT_DATA_1> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint8_t slot_name[PWS_SLOTNAME_LENGTH];
+ uint8_t slot_password[PWS_PASSWORD_LENGTH];
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " slot_number\t" << (int)slot_number << std::endl;
+ print_to_ss_volatile(slot_name);
+ print_to_ss_volatile(slot_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class SetPasswordSafeSlotData2 : Command<CommandID::SET_PW_SAFE_SLOT_DATA_2> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint8_t slot_login_name[PWS_LOGINNAME_LENGTH];
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " slot_number\t" << (int)slot_number << std::endl;
+ print_to_ss_volatile(slot_login_name);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class ErasePasswordSafeSlot : Command<CommandID::PW_SAFE_ERASE_SLOT> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " slot_number\t" << (int)slot_number << std::endl;
+ return ss.str();
+ }
+
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class EnablePasswordSafe : Command<CommandID::PW_SAFE_ENABLE> {
+ public:
+ struct CommandPayload {
+ uint8_t user_password[30];
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(user_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class PasswordSafeInitKey : Command<CommandID::PW_SAFE_INIT_KEY> {
+ /**
+ * never used in Nitrokey App
+ */
+ public:
+ typedef Transaction<command_id(), struct EmptyPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class PasswordSafeSendSlotViaHID : Command<CommandID::PW_SAFE_SEND_DATA> {
+ /**
+ * never used in Nitrokey App
+ */
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint8_t slot_kind;
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+// TODO "Device::passwordSafeSendSlotDataViaHID"
+
+class WriteGeneralConfig : Command<CommandID::WRITE_CONFIG> {
+ public:
+ struct CommandPayload {
+ union{
+ uint8_t config[5];
+ struct{
+ uint8_t numlock; /** 0-1: HOTP slot number from which the code will be get on double press, other value - function disabled */
+ uint8_t capslock; /** same as numlock */
+ uint8_t scrolllock; /** same as numlock */
+ uint8_t enable_user_password;
+ uint8_t delete_user_password;
+ };
+ };
+ bool isValid() const { return numlock < 2 && capslock < 2 && scrolllock < 2 && enable_user_password < 2; }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "numlock:\t" << (int)numlock << std::endl;
+ ss << "capslock:\t" << (int)capslock << std::endl;
+ ss << "scrolllock:\t" << (int)scrolllock << std::endl;
+ ss << "enable_user_password:\t" << (bool) enable_user_password << std::endl;
+ ss << "delete_user_password:\t" << (bool) delete_user_password << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class FirstAuthenticate : Command<CommandID::FIRST_AUTHENTICATE> {
+ public:
+ struct CommandPayload {
+ uint8_t card_password[25];
+ uint8_t temporary_password[25];
+
+ bool isValid() const { return true; }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(card_password);
+ hexdump_to_ss(temporary_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class UserAuthenticate : Command<CommandID::USER_AUTHENTICATE> {
+ public:
+ struct CommandPayload {
+ uint8_t card_password[25];
+ uint8_t temporary_password[25];
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(card_password);
+ hexdump_to_ss(temporary_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class Authorize : Command<CommandID::AUTHORIZE> {
+ public:
+ struct CommandPayload {
+ uint32_t crc_to_authorize;
+ uint8_t temporary_password[25];
+
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " crc_to_authorize:\t" << std::hex << std::setw(2) << std::setfill('0') << crc_to_authorize<< std::endl;
+ hexdump_to_ss(temporary_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class UserAuthorize : Command<CommandID::USER_AUTHORIZE> {
+ public:
+ struct CommandPayload {
+ uint32_t crc_to_authorize;
+ uint8_t temporary_password[25];
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << " crc_to_authorize:\t" << crc_to_authorize<< std::endl;
+ hexdump_to_ss(temporary_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class UnlockUserPassword : Command<CommandID::UNLOCK_USER_PASSWORD> {
+ public:
+ struct CommandPayload {
+ uint8_t admin_password[25];
+ uint8_t user_new_password[25];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(admin_password);
+ print_to_ss_volatile(user_new_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class ChangeUserPin : Command<CommandID::CHANGE_USER_PIN> {
+ public:
+ struct CommandPayload {
+ uint8_t old_pin[25];
+ uint8_t new_pin[25];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(old_pin);
+ print_to_ss_volatile(new_pin);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class IsAESSupported : Command<CommandID::DETECT_SC_AES> {
+ public:
+ struct CommandPayload {
+ uint8_t user_password[20];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(user_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+
+class ChangeAdminPin : Command<CommandID::CHANGE_ADMIN_PIN> {
+ public:
+ struct CommandPayload {
+ uint8_t old_pin[25];
+ uint8_t new_pin[25];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(old_pin);
+ print_to_ss_volatile(new_pin);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class LockDevice : Command<CommandID::LOCK_DEVICE> {
+ public:
+ typedef Transaction<command_id(), struct EmptyPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class FactoryReset : Command<CommandID::FACTORY_RESET> {
+ public:
+ struct CommandPayload {
+ uint8_t admin_password[20];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(admin_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+};
+
+class BuildAESKey : Command<CommandID::NEW_AES_KEY> {
+ public:
+ struct CommandPayload {
+ uint8_t admin_password[20];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(admin_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+
+};
+
+class FirmwareUpdate : Command<CommandID::FIRMWARE_UPDATE> {
+public:
+ struct CommandPayload {
+ uint8_t firmware_password[20];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(firmware_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+
+};
+
+class FirmwarePasswordChange : Command<CommandID::FIRMWARE_PASSWORD_CHANGE> {
+public:
+ struct CommandPayload {
+ uint8_t firmware_password_current[20];
+ uint8_t firmware_password_new[20];
+ std::string dissect() const {
+ std::stringstream ss;
+ print_to_ss_volatile(firmware_password_current);
+ print_to_ss_volatile(firmware_password_new);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+
+};
+
+
+}
+}
+}
+#pragma pack (pop)
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/stick10_commands_0.8.h b/libnitrokey-v3.6/libnitrokey/stick10_commands_0.8.h
new file mode 100644
index 0000000..9477890
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/stick10_commands_0.8.h
@@ -0,0 +1,348 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+
+#ifndef LIBNITROKEY_STICK10_COMMANDS_0_8_H
+#define LIBNITROKEY_STICK10_COMMANDS_0_8_H
+
+#include <bitset>
+#include <iomanip>
+#include <string>
+#include <sstream>
+#include <cstdint>
+#include "command.h"
+#include "device_proto.h"
+#include "stick10_commands.h"
+
+#pragma pack (push,1)
+
+
+namespace nitrokey {
+ namespace proto {
+
+/*
+ * Stick10 protocol definition
+ */
+ namespace stick10_08 {
+ using stick10::FirstAuthenticate;
+ using stick10::UserAuthenticate;
+ using stick10::SetTime;
+ using stick10::GetStatus;
+ using stick10::BuildAESKey;
+ using stick10::ChangeAdminPin;
+ using stick10::ChangeUserPin;
+ using stick10::EnablePasswordSafe;
+ using stick10::ErasePasswordSafeSlot;
+ using stick10::FactoryReset;
+ using stick10::GetPasswordRetryCount;
+ using stick10::GetUserPasswordRetryCount;
+ using stick10::GetPasswordSafeSlotLogin;
+ using stick10::GetPasswordSafeSlotName;
+ using stick10::GetPasswordSafeSlotPassword;
+ using stick10::GetPasswordSafeSlotStatus;
+ using stick10::GetSlotName;
+ using stick10::IsAESSupported;
+ using stick10::LockDevice;
+ using stick10::PasswordSafeInitKey;
+ using stick10::PasswordSafeSendSlotViaHID;
+ using stick10::SetPasswordSafeSlotData;
+ using stick10::SetPasswordSafeSlotData2;
+ using stick10::UnlockUserPassword;
+ using stick10::ReadSlot;
+
+ class EraseSlot : Command<CommandID::ERASE_SLOT> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint8_t temporary_admin_password[25];
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ hexdump_to_ss(temporary_admin_password);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+ };
+
+ class SendOTPData : Command<CommandID::SEND_OTP_DATA> {
+ //admin auth
+ public:
+ struct CommandPayload {
+ uint8_t temporary_admin_password[25];
+ uint8_t type; //S-secret, N-name
+ uint8_t id; //multiple reports for values longer than 30 bytes
+ uint8_t data[30]; //data, does not need null termination
+
+ bool isValid() const { return true; }
+
+ void setTypeName(){
+ type = 'N';
+ }
+ void setTypeSecret(){
+ type = 'S';
+ }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ hexdump_to_ss(temporary_admin_password);
+ ss << "type:\t" << type << std::endl;
+ ss << "id:\t" << (int)id << std::endl;
+#ifdef LOG_VOLATILE_DATA
+ ss << "data:" << std::endl
+ << ::nitrokey::misc::hexdump((const uint8_t *) (&data), sizeof data);
+#else
+ ss << " Volatile data not logged" << std::endl;
+#endif
+ return ss.str();
+ }
+ } __packed;
+
+
+ struct ResponsePayload {
+ union {
+ uint8_t data[40];
+ } __packed;
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+#ifdef LOG_VOLATILE_DATA
+ ss << "data:" << std::endl
+ << ::nitrokey::misc::hexdump((const uint8_t *) (&data), sizeof data);
+#else
+ ss << " Volatile data not logged" << std::endl;
+#endif
+ return ss.str();
+ }
+ } __packed;
+
+
+ typedef Transaction<command_id(), struct CommandPayload, struct ResponsePayload>
+ CommandTransaction;
+ };
+
+ class WriteToOTPSlot : Command<CommandID::WRITE_TO_SLOT> {
+ //admin auth
+ public:
+ struct CommandPayload {
+ uint8_t temporary_admin_password[25];
+ uint8_t slot_number;
+ union {
+ uint64_t slot_counter_or_interval;
+ uint8_t slot_counter_s[8];
+ } __packed;
+ union {
+ uint8_t _slot_config;
+ struct {
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ union {
+ uint8_t slot_token_id[13]; /** OATH Token Identifier */
+ struct { /** @see https://openauthentication.org/token-specs/ */
+ uint8_t omp[2];
+ uint8_t tt[2];
+ uint8_t mui[8];
+ uint8_t keyboard_layout; //disabled feature in nitroapp as of 20160805
+ } slot_token_fields;
+ };
+
+ bool isValid() const { return true; }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ hexdump_to_ss(temporary_admin_password);
+ ss << "slot_config:\t" << std::bitset<8>((int) _slot_config) << std::endl;
+ ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl;
+ ss << "\tuse_enter(1):\t" << use_enter << std::endl;
+ ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl;
+ ss << "slot_number:\t" << (int) (slot_number) << std::endl;
+ ss << "slot_counter_or_interval:\t[" << (int) slot_counter_or_interval << "]\t"
+ << ::nitrokey::misc::hexdump((const uint8_t *) (&slot_counter_or_interval), sizeof slot_counter_or_interval, false);
+
+ ss << "slot_token_id:\t";
+ for (auto i : slot_token_id)
+ ss << std::hex << std::setw(2) << std::setfill('0') << (int) i << " ";
+ ss << std::endl;
+
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+ };
+
+ class GetHOTP : Command<CommandID::GET_CODE> {
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ struct {
+ uint64_t challenge; //@unused
+ uint64_t last_totp_time; //@unused
+ uint8_t last_interval; //@unused
+ } __packed _unused;
+ uint8_t temporary_user_password[25];
+
+ bool isValid() const { return (slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ hexdump_to_ss(temporary_user_password);
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ union {
+ uint8_t whole_response[18]; //14 bytes reserved for config, but used only 1
+ struct {
+ uint32_t code;
+ union{
+ uint8_t _slot_config;
+ struct{
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ } __packed;
+ } __packed;
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "code:\t" << (code) << std::endl;
+ ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl;
+ ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl;
+ ss << "\tuse_enter(1):\t" << use_enter << std::endl;
+ ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct ResponsePayload>
+ CommandTransaction;
+ };
+
+
+ class GetTOTP : Command<CommandID::GET_CODE> {
+ //user auth
+ public:
+ struct CommandPayload {
+ uint8_t slot_number;
+ uint64_t challenge; //@unused
+ uint64_t last_totp_time; //@unused
+ uint8_t last_interval; //@unused
+ uint8_t temporary_user_password[25];
+
+ bool isValid() const { return !(slot_number & 0xF0); }
+ std::string dissect() const {
+ std::stringstream ss;
+ hexdump_to_ss(temporary_user_password);
+ ss << "slot_number:\t" << (int)(slot_number) << std::endl;
+ ss << "challenge:\t" << (challenge) << std::endl;
+ ss << "last_totp_time:\t" << (last_totp_time) << std::endl;
+ ss << "last_interval:\t" << (int)(last_interval) << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ struct ResponsePayload {
+ union {
+ uint8_t whole_response[18]; //14 bytes reserved for config, but used only 1
+ struct {
+ uint32_t code;
+ union{
+ uint8_t _slot_config;
+ struct{
+ bool use_8_digits : 1;
+ bool use_enter : 1;
+ bool use_tokenID : 1;
+ };
+ };
+ } __packed ;
+ } __packed ;
+
+ bool isValid() const { return true; }
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "code:\t" << (code) << std::endl;
+ ss << "slot_config:\t" << std::bitset<8>((int)_slot_config) << std::endl;
+ ss << "\tuse_8_digits(0):\t" << use_8_digits << std::endl;
+ ss << "\tuse_enter(1):\t" << use_enter << std::endl;
+ ss << "\tuse_tokenID(2):\t" << use_tokenID << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct ResponsePayload>
+ CommandTransaction;
+ };
+
+
+ class WriteGeneralConfig : Command<CommandID::WRITE_CONFIG> {
+ //admin auth
+ public:
+ struct CommandPayload {
+ union{
+ uint8_t config[5];
+ struct{
+ uint8_t numlock; /** 0-1: HOTP slot number from which the code will be get on double press, other value - function disabled */
+ uint8_t capslock; /** same as numlock */
+ uint8_t scrolllock; /** same as numlock */
+ uint8_t enable_user_password;
+ uint8_t delete_user_password;
+ };
+ };
+ uint8_t temporary_admin_password[25];
+
+ static constexpr uint8_t special_HOTP_slots = 3;
+ bool isValid() const { return numlock < special_HOTP_slots && capslock < special_HOTP_slots
+ && scrolllock < special_HOTP_slots && enable_user_password < 2; }
+
+ std::string dissect() const {
+ std::stringstream ss;
+ ss << "numlock:\t" << (int)numlock << std::endl;
+ ss << "capslock:\t" << (int)capslock << std::endl;
+ ss << "scrolllock:\t" << (int)scrolllock << std::endl;
+ ss << "enable_user_password:\t" << (bool) enable_user_password << std::endl;
+ ss << "delete_user_password:\t" << (bool) delete_user_password << std::endl;
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+ };
+ }
+ }
+}
+#pragma pack (pop)
+
+#endif //LIBNITROKEY_STICK10_COMMANDS_0_8_H
diff --git a/libnitrokey-v3.6/libnitrokey/stick20_commands.h b/libnitrokey-v3.6/libnitrokey/stick20_commands.h
new file mode 100644
index 0000000..7efa1b6
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/stick20_commands.h
@@ -0,0 +1,394 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef STICK20_COMMANDS_H
+#define STICK20_COMMANDS_H
+
+
+
+#include <cstdint>
+#include "command.h"
+#include <string>
+#include <sstream>
+#include "device_proto.h"
+
+#pragma pack (push,1)
+
+namespace nitrokey {
+ namespace proto {
+
+/*
+* STICK20 protocol command ids
+* a superset (almost) of STICK10
+*/
+
+ namespace stick20 {
+
+ class ChangeAdminUserPin20Current :
+ public PasswordCommand<CommandID::SEND_PASSWORD, PasswordKind::Admin> {};
+ class ChangeAdminUserPin20New :
+ public PasswordCommand<CommandID::SEND_NEW_PASSWORD, PasswordKind::Admin> {};
+ class UnlockUserPin :
+ public PasswordCommand<CommandID::UNLOCK_USER_PASSWORD, PasswordKind::Admin> {};
+
+ class EnableEncryptedPartition : public PasswordCommand<CommandID::ENABLE_CRYPTED_PARI> {};
+ class EnableHiddenEncryptedPartition : public PasswordCommand<CommandID::ENABLE_HIDDEN_CRYPTED_PARI> {};
+
+ class SetUnencryptedVolumeReadOnlyAdmin :
+ public PasswordCommand<CommandID::ENABLE_ADMIN_READONLY_UNCRYPTED_LUN, PasswordKind::Admin> {};
+ class SetUnencryptedVolumeReadWriteAdmin :
+ public PasswordCommand<CommandID::ENABLE_ADMIN_READWRITE_UNCRYPTED_LUN, PasswordKind::Admin> {};
+ class SetEncryptedVolumeReadOnly :
+ public PasswordCommand<CommandID::ENABLE_ADMIN_READONLY_ENCRYPTED_LUN, PasswordKind::Admin> {};
+ class SetEncryptedVolumeReadWrite :
+ public PasswordCommand<CommandID::ENABLE_ADMIN_READWRITE_ENCRYPTED_LUN, PasswordKind::Admin> {};
+
+ //FIXME the volume disabling commands do not need password
+ class DisableEncryptedPartition : public PasswordCommand<CommandID::DISABLE_CRYPTED_PARI> {};
+ class DisableHiddenEncryptedPartition : public PasswordCommand<CommandID::DISABLE_HIDDEN_CRYPTED_PARI> {};
+
+ class EnableFirmwareUpdate : public PasswordCommand<CommandID::ENABLE_FIRMWARE_UPDATE> {};
+
+ class ChangeUpdatePassword : Command<CommandID::CHANGE_UPDATE_PIN> {
+ public:
+ struct CommandPayload {
+ 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_volatile( current_update_password );
+ print_to_ss_volatile( new_update_password );
+ return ss.str();
+ }
+ };
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+ };
+
+ class ExportFirmware : public PasswordCommand<CommandID::EXPORT_FIRMWARE_TO_FILE> {};
+
+ class CreateNewKeys :
+ public PasswordCommand<CommandID::GENERATE_NEW_KEYS, PasswordKind::AdminPrefixed, 30> {};
+
+
+ class FillSDCardWithRandomChars : Command<CommandID::FILL_SD_CARD_WITH_RANDOM_CHARS> {
+ public:
+ enum class ChosenVolumes : uint8_t {
+ all_volumes = 0,
+ encrypted_volume = 1
+ };
+
+ struct CommandPayload {
+ uint8_t volume_flag;
+ uint8_t kind;
+ 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_volatile(admin_pin);
+ return ss.str();
+ }
+ void set_kind_user() {
+ kind = (uint8_t) 'P';
+ }
+ void set_defaults(){
+ set_kind_user();
+ volume_flag = static_cast<uint8_t>(ChosenVolumes::encrypted_volume);
+ }
+
+ } __packed;
+
+ typedef Transaction<Command<CommandID::FILL_SD_CARD_WITH_RANDOM_CHARS>::command_id(),
+ struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+ };
+
+ namespace StorageCommandResponsePayload{
+ using namespace DeviceResponseConstants;
+ static constexpr auto padding_size =
+ storage_data_absolute_address - header_size;
+ 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 uint8_t *) (_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{
+
+ struct ResponsePayload {
+ StorageCommandResponsePayload::TransmissionData transmission_data;
+
+ uint16_t MagicNumber_StickConfig_u16;
+ /**
+ * READ_WRITE_ACTIVE = ReadWriteFlagUncryptedVolume_u8 == 0;
+ */
+ uint8_t ReadWriteFlagUncryptedVolume_u8;
+ uint8_t ReadWriteFlagCryptedVolume_u8;
+
+ union{
+ uint8_t VersionInfo_au8[4];
+ struct {
+ uint8_t major;
+ uint8_t minor;
+ uint8_t _reserved2;
+ uint8_t build_iteration;
+ } __packed versionInfo;
+ } __packed;
+
+ uint8_t ReadWriteFlagHiddenVolume_u8;
+ uint8_t FirmwareLocked_u8;
+
+ union{
+ uint8_t NewSDCardFound_u8;
+ struct {
+ bool NewCard :1;
+ uint8_t Counter :7;
+ } __packed NewSDCardFound_st;
+ } __packed;
+
+ /**
+ * SD card FILLED with random chars
+ */
+ uint8_t SDFillWithRandomChars_u8;
+ uint32_t ActiveSD_CardID_u32;
+ union{
+ uint8_t VolumeActiceFlag_u8;
+ struct {
+ bool unencrypted :1;
+ bool encrypted :1;
+ bool hidden :1;
+ } __packed VolumeActiceFlag_st;
+ } __packed;
+ uint8_t NewSmartCardFound_u8;
+ uint8_t UserPwRetryCount;
+ uint8_t AdminPwRetryCount;
+ uint32_t ActiveSmartCardID_u32;
+ uint8_t StickKeysNotInitiated;
+
+ bool isValid() const { return true; }
+
+ std::string dissect() const {
+ std::stringstream ss;
+
+ print_to_ss(transmission_data.dissect());
+ print_to_ss( MagicNumber_StickConfig_u16 );
+ print_to_ss((int) ReadWriteFlagUncryptedVolume_u8 );
+ print_to_ss((int) ReadWriteFlagCryptedVolume_u8 );
+ print_to_ss((int) ReadWriteFlagHiddenVolume_u8 );
+ print_to_ss((int) versionInfo.major );
+ print_to_ss((int) versionInfo.minor );
+ print_to_ss((int) versionInfo.build_iteration );
+ print_to_ss((int) FirmwareLocked_u8 );
+ print_to_ss((int) NewSDCardFound_u8 );
+ print_to_ss((int) NewSDCardFound_st.NewCard );
+ print_to_ss((int) NewSDCardFound_st.Counter );
+ print_to_ss((int) SDFillWithRandomChars_u8 );
+ print_to_ss( ActiveSD_CardID_u32 );
+ print_to_ss((int) VolumeActiceFlag_u8 );
+ print_to_ss((int) VolumeActiceFlag_st.unencrypted );
+ print_to_ss((int) VolumeActiceFlag_st.encrypted );
+ print_to_ss((int) VolumeActiceFlag_st.hidden);
+ 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 );
+
+ return ss.str();
+ }
+ } __packed;
+ }
+
+ class SendStartup : Command<CommandID::SEND_STARTUP> {
+ 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::seconds> (
+ std::chrono::system_clock::now().time_since_epoch()).count();
+ }
+ }__packed;
+
+ using ResponsePayload = DeviceConfigurationResponsePacket::ResponsePayload;
+
+ typedef Transaction<command_id(), struct CommandPayload, ResponsePayload>
+ CommandTransaction;
+ };
+
+
+// TODO fix original nomenclature
+ class SendSetReadonlyToUncryptedVolume : public PasswordCommand<CommandID::ENABLE_READONLY_UNCRYPTED_LUN> {};
+ class SendSetReadwriteToUncryptedVolume : public PasswordCommand<CommandID::ENABLE_READWRITE_UNCRYPTED_LUN> {};
+ class SendClearNewSdCardFound : public PasswordCommand<CommandID::CLEAR_NEW_SD_CARD_FOUND> {};
+
+ class GetDeviceStatus : Command<CommandID::GET_DEVICE_STATUS> {
+ public:
+ using ResponsePayload = DeviceConfigurationResponsePacket::ResponsePayload;
+
+ typedef Transaction<command_id(), struct EmptyPayload, ResponsePayload>
+ CommandTransaction;
+ };
+
+ class Wink : Command<CommandID::WINK> {
+ public:
+ typedef Transaction<command_id(), struct EmptyPayload, struct EmptyPayload>
+ CommandTransaction;
+ };
+
+ class CheckSmartcardUsage : Command<CommandID::CHECK_SMARTCARD_USAGE> {
+ public:
+ typedef Transaction<command_id(), struct EmptyPayload, EmptyPayload>
+ CommandTransaction;
+ };
+
+ class GetSDCardOccupancy : Command<CommandID::SD_CARD_HIGH_WATERMARK> {
+ 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<command_id(), struct EmptyPayload, struct ResponsePayload>
+ CommandTransaction;
+ };
+
+
+ class SetupHiddenVolume : Command<CommandID::SEND_HIDDEN_VOLUME_SETUP> {
+ public:
+ 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_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);
+ print_to_ss_volatile(HiddenVolumePassword_au8);
+ return ss.str();
+ }
+ } __packed;
+
+ typedef Transaction<command_id(), struct CommandPayload, struct EmptyPayload>
+ CommandTransaction;
+ };
+
+
+//disable this command for now
+// class LockFirmware : public PasswordCommand<CommandID::SEND_LOCK_STICK_HARDWARE> {};
+
+ class ProductionTest : Command<CommandID::PRODUCTION_TEST> {
+ public:
+ struct ResponsePayload {
+
+ StorageCommandResponsePayload::TransmissionData transmission_data;
+
+ 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(transmission_data.dissect());
+ 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);
+ return ss.str();
+ }
+
+ } __packed;
+
+ typedef Transaction<command_id(), struct EmptyPayload, struct ResponsePayload>
+ CommandTransaction;
+ };
+
+ }
+ }
+}
+
+#undef print_to_ss
+#pragma pack (pop)
+
+#endif
diff --git a/libnitrokey-v3.6/libnitrokey/version.h b/libnitrokey-v3.6/libnitrokey/version.h
new file mode 100644
index 0000000..6547af0
--- /dev/null
+++ b/libnitrokey-v3.6/libnitrokey/version.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#ifndef LIBNITROKEY_VERSION_H
+#define LIBNITROKEY_VERSION_H
+
+namespace nitrokey {
+ unsigned int get_major_library_version();
+
+ unsigned int get_minor_library_version();
+
+ const char* get_library_version();
+}
+
+#endif
diff --git a/libnitrokey-v3.6/log.cc b/libnitrokey-v3.6/log.cc
new file mode 100644
index 0000000..06acee7
--- /dev/null
+++ b/libnitrokey-v3.6/log.cc
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include "log.h"
+#include <iostream>
+#include <ctime>
+#include <iomanip>
+
+#include <sstream>
+
+namespace nitrokey {
+ namespace log {
+
+ Log *Log::mp_instance = nullptr;
+ StdlogHandler stdlog_handler;
+
+ std::string Log::prefix = "";
+
+
+ std::string LogHandler::loglevel_to_str(Loglevel lvl) {
+ switch (lvl) {
+ case Loglevel::DEBUG_L1:
+ return std::string("DEBUG_L1");
+ case Loglevel::DEBUG_L2:
+ return std::string("DEBUG_L2");
+ case Loglevel::DEBUG:
+ return std::string("DEBUG");
+ case Loglevel::INFO:
+ return std::string("INFO");
+ case Loglevel::WARNING:
+ return std::string("WARNING");
+ case Loglevel::ERROR:
+ return std::string("ERROR");
+ }
+ return std::string("");
+ }
+
+ void Log::operator()(const std::string &logstr, Loglevel lvl) {
+ if (mp_loghandler != nullptr){
+ if ((int) lvl <= (int) m_loglevel) mp_loghandler->print(prefix+logstr, lvl);
+ }
+ }
+
+ void Log::setPrefix(const std::string prefix) {
+ if (!prefix.empty()){
+ Log::prefix = "["+prefix+"]";
+ } else {
+ Log::prefix = "";
+ }
+ }
+
+ void StdlogHandler::print(const std::string &str, Loglevel lvl) {
+ std::string s = format_message_to_string(str, lvl);
+ std::clog << s;
+ }
+
+ void FunctionalLogHandler::print(const std::string &str, Loglevel lvl) {
+ std::string s = format_message_to_string(str, lvl);
+ log_function(s);
+ }
+
+ std::string LogHandler::format_message_to_string(const std::string &str, const Loglevel &lvl) {
+ static bool last_short = false;
+ if (str.length() == 1){
+ last_short = true;
+ return str;
+ }
+ time_t t = time(nullptr);
+ tm tm = *localtime(&t);
+
+ std::stringstream s;
+ s
+ << (last_short? "\n" : "")
+ << "[" << std::put_time(&tm, "%c") << "]"
+ << "[" << loglevel_to_str(lvl) << "]\t"
+ << str << std::endl;
+ last_short = false;
+ return s.str();
+ }
+
+ FunctionalLogHandler::FunctionalLogHandler(log_function_type _log_function) {
+ log_function = _log_function;
+ }
+ }
+}
diff --git a/libnitrokey-v3.6/misc.cc b/libnitrokey-v3.6/misc.cc
new file mode 100644
index 0000000..59185f3
--- /dev/null
+++ b/libnitrokey-v3.6/misc.cc
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2015-2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include <sstream>
+#include <string>
+#include "misc.h"
+#include "inttypes.h"
+#include <cstdlib>
+#include <cstring>
+#include "LibraryException.h"
+#include <vector>
+
+namespace nitrokey {
+namespace misc {
+
+
+
+::std::vector<uint8_t> hex_string_to_byte(const char* hexString){
+ const size_t big_string_size = 257; //arbitrary 'big' number
+ const size_t s_size = strnlen(hexString, big_string_size);
+ const size_t d_size = s_size/2;
+ if (s_size%2!=0 || s_size>=big_string_size){
+ throw InvalidHexString(0);
+ }
+ auto data = ::std::vector<uint8_t>();
+ data.reserve(d_size);
+
+ char buf[3];
+ buf[2] = '\0';
+ for(size_t i=0; i<s_size; i++){
+
+ char c = hexString[i];
+ bool char_from_range = (('0' <= c && c <='9') || ('A' <= c && c <= 'F') || ('a' <= c && c<= 'f'));
+ if (!char_from_range){
+ throw InvalidHexString(c);
+ }
+ buf[i%2] = c;
+ if (i%2==1){
+ data.push_back( strtoul(buf, NULL, 16) & 0xFF );
+ }
+ }
+ return data;
+};
+
+#include <cctype>
+::std::string hexdump(const uint8_t *p, size_t size, bool print_header,
+ bool print_ascii, bool print_empty) {
+ ::std::stringstream out;
+ char formatbuf[128];
+ const uint8_t *pstart = p;
+
+ for (const uint8_t *pend = p + size; p < pend;) {
+ if (print_header){
+ snprintf(formatbuf, 128, "%04x\t", static_cast<int> (p - pstart));
+ out << formatbuf;
+ }
+
+ const uint8_t* pp = p;
+ for (const uint8_t *le = p + 16; p < le; p++) {
+ if (p < pend){
+ snprintf(formatbuf, 128, "%02x ", uint8_t(*p));
+ out << formatbuf;
+ } else {
+ if(print_empty)
+ out << "-- ";
+ }
+
+ }
+ if(print_ascii){
+ out << " ";
+ for (const uint8_t *le = pp + 16; pp < le && pp < pend; pp++) {
+ if (std::isgraph(*pp))
+ out << uint8_t(*pp);
+ else
+ out << '.';
+ }
+ }
+ out << ::std::endl;
+ }
+ return out.str();
+}
+
+static uint32_t _crc32(uint32_t crc, uint32_t data) {
+ int i;
+ crc = crc ^ data;
+
+ for (i = 0; i < 32; i++) {
+ if (crc & 0x80000000)
+ crc = (crc << 1) ^ 0x04C11DB7; // polynomial used in STM32
+ else
+ crc = (crc << 1);
+ }
+
+ return crc;
+}
+
+uint32_t stm_crc32(const uint8_t *data, size_t size) {
+ uint32_t crc = 0xffffffff;
+ const uint32_t *pend = (const uint32_t *)(data + size);
+ for (const uint32_t *p = (const uint32_t *)(data); p < pend; p++)
+ crc = _crc32(crc, *p);
+ return crc;
+}
+}
+}
diff --git a/libnitrokey-v3.6/version.cc b/libnitrokey-v3.6/version.cc
new file mode 100644
index 0000000..dfdc802
--- /dev/null
+++ b/libnitrokey-v3.6/version.cc
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include "version.h"
+
+namespace nitrokey {
+ unsigned int get_major_library_version() {
+ return 3;
+ }
+
+ unsigned int get_minor_library_version() {
+ return 0;
+ }
+
+ const char* get_library_version() {
+ return "unknown";
+ }
+}
+
diff --git a/libnitrokey-v3.6/version.cc.in b/libnitrokey-v3.6/version.cc.in
new file mode 100644
index 0000000..0eae647
--- /dev/null
+++ b/libnitrokey-v3.6/version.cc.in
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2018 Nitrokey UG
+ *
+ * This file is part of libnitrokey.
+ *
+ * libnitrokey is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * libnitrokey is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with libnitrokey. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: LGPL-3.0
+ */
+
+#include "version.h"
+
+namespace nitrokey {
+ unsigned int get_major_library_version() {
+ return @PROJECT_VERSION_MAJOR@;
+ }
+
+ unsigned int get_minor_library_version() {
+ return @PROJECT_VERSION_MINOR@;
+ }
+
+ const char* get_library_version() {
+ return "@PROJECT_VERSION_GIT@";
+ }
+}
+