pax_global_header00006660000000000000000000000064142322342140014507gustar00rootroot0000000000000052 comment=7c31c2f071c01b17fc6d832ee21e5b4d67081f76 libnitrokey-3.7/000077500000000000000000000000001423223421400137135ustar00rootroot00000000000000libnitrokey-3.7/.gitignore000066400000000000000000000001511423223421400157000ustar00rootroot00000000000000*.sw* *.log *.o build unittest/build/ unittest/.pytest_cache/ *.pyc core .cache/ .idea/ CMakeFiles/ /.vs libnitrokey-3.7/.gitlab-ci.yml000066400000000000000000000043201423223421400163460ustar00rootroot00000000000000include: 'https://raw.githubusercontent.com/Nitrokey/common-ci-jobs/master/common_jobs.yml' stages: - pull-github - fetch - build - deploy variables: #Repo for shared scripts (pull.sh release.sh, nightly_upload.sh): GIT_STRATEGY: clone #This seems to have no effect also set in webinterface GIT_DEPTH: 0 #This seems to have no effect also set in webinterface GIT_SUBMODULE_STRATEGY: recursive #This seems to have no effect also set in webinterfac SCRIPTS_REPO: git@git.dotplex.com:nitrokey/gitlab-ci.git REPO_USER: nitrokey REPO_NAME: libnitrokey MAIN_BRANCH: master COMMON_PULL: "true" COMMON_UPLOAD_NIGHTLY: "true" COMMON_GITHUB_RELEASE: "true" COMMON_UPLOAD_FILES: "false" fetch-and-package: image: registry.git.dotplex.com/nitrokey/libnitrokey/libnitrokey-bionic-gcc8:latest rules: - if: '$CI_PIPELINE_SOURCE == "push"' - if: '$CI_PIPELINE_SOURCE == "schedule"' - if: '$CI_PIPELINE_SOURCE == "web"' tags: - docker stage: fetch script: - ci-script/package.sh after_script: - wget $icon_server/checkmark/$CI_COMMIT_REF_NAME/$CI_COMMIT_SHA/$CI_JOB_NAME/$CI_JOB_STATUS/${CI_JOB_URL#*/*/*/} artifacts: paths: - artifacts - libnitrokey-source-metadata expire_in: 2 weeks .build: rules: - if: '$CI_PIPELINE_SOURCE == "push"' - if: '$CI_PIPELINE_SOURCE == "schedule"' - if: '$CI_PIPELINE_SOURCE == "web"' tags: - docker stage: build script: - ci-script/build.sh after_script: - wget $icon_server/checkmark/$CI_COMMIT_REF_NAME/$CI_COMMIT_SHA/$CI_JOB_NAME/$CI_JOB_STATUS/${CI_JOB_URL#*/*/*/} build-bionic-gcc8: extends: .build image: registry.git.dotplex.com/nitrokey/libnitrokey/libnitrokey-bionic-gcc8:latest build-bionic-gcc7: extends: .build image: registry.git.dotplex.com/nitrokey/libnitrokey/libnitrokey-bionic-gcc7:latest build-bionic-gcc6: extends: .build image: registry.git.dotplex.com/nitrokey/libnitrokey/libnitrokey-bionic-gcc6:latest build-bionic-gcc5: extends: .build image: registry.git.dotplex.com/nitrokey/libnitrokey/libnitrokey-bionic-gcc5:latest build-bionic-llvm7: extends: .build image: registry.git.dotplex.com/nitrokey/libnitrokey/libnitrokey-bionic-llvm7:latest libnitrokey-3.7/.gitmodules000066400000000000000000000002641423223421400160720ustar00rootroot00000000000000[submodule "unittest/Catch"] path = unittest/Catch url = https://github.com/catchorg/Catch2.git [submodule "hidapi"] path = hidapi url = https://github.com/Nitrokey/hidapi.git libnitrokey-3.7/.idea/000077500000000000000000000000001423223421400146735ustar00rootroot00000000000000libnitrokey-3.7/.idea/codeStyleSettings.xml000066400000000000000000000042251423223421400210740ustar00rootroot00000000000000 libnitrokey-3.7/.idea/dictionaries/000077500000000000000000000000001423223421400173505ustar00rootroot00000000000000libnitrokey-3.7/.idea/dictionaries/sz.xml000066400000000000000000000002661423223421400205320ustar00rootroot00000000000000 loglevel nitrokey totp libnitrokey-3.7/.idea/vcs.xml000066400000000000000000000004621423223421400162120ustar00rootroot00000000000000 libnitrokey-3.7/.travis.yml000066400000000000000000000045501423223421400160300ustar00rootroot00000000000000language: generic os: osx env: global: - CF="-DCOMPILE_OFFLINE_TESTS=1 -DERROR_ON_WARNING=ON" jobs: include: - osx_image: xcode11.5 - osx_image: xcode9.1 - os: linux dist: trusty env: COMPILER_NAME=gcc CXX=g++-5 CC=gcc-5 addons: apt: packages: - cmake - libhidapi-dev - g++-5 sources: &sources - ubuntu-toolchain-r-test - os: linux dist: trusty env: COMPILER_NAME=gcc CXX=g++-7 CC=gcc-7 addons: apt: packages: - cmake - libhidapi-dev - g++-7 sources: *sources - os: linux dist: bionic env: COMPILER_NAME=gcc CXX=g++-10 CC=gcc-10 addons: apt: packages: - cmake - libhidapi-dev - g++-10 - python3 - python3-pip - meson - ninja-build sources: *sources script: - make -j2 - ctest -VV - mkdir install && make install DESTDIR=install - cd ../ - python3 -m pip install -r unittest/requirements.txt --user - cd unittest && python3 -m pytest -sv test_offline.py - cd ../ - mkdir -p build-meson && meson build-meson - cd build-meson && ninja - env DESTDIR=install ninja install - os: linux dist: trusty env: COMPILER_NAME=clang CXX=clang++-3.8 CC=clang-3.8 addons: apt: packages: - cmake - libhidapi-dev - g++-5 - clang-3.8 sources: *sources - os: linux dist: bionic env: COMPILER_NAME=clang CXX=clang++-6.0 CC=clang-6.0 addons: apt: packages: - cmake - libhidapi-dev - clang-6.0 sources: *sources - os: linux dist: bionic env: COMPILER_NAME=clang CXX=clang++-9 CC=clang-9 addons: apt: packages: - cmake - libhidapi-dev - clang-9 sources: *sources install: - mkdir -p build - cd build # - export CXXFLAGS="${CXX_FLAGS} -Wall -Wextra -Werror" # TODO enable when fixed - ${CXX} --version || true - cmake --version - cmake .. ${CF} script: - make -j2 - ctest -VV - mkdir install && make install DESTDIR=installlibnitrokey-3.7/CHANGELOG.md000066400000000000000000000142141423223421400155260ustar00rootroot00000000000000# Change Log ## [v3.2](https://github.com/Nitrokey/libnitrokey/tree/v3.2) (2018-01-16) [Full Changelog](https://github.com/Nitrokey/libnitrokey/compare/v3.1...v3.2) **Closed issues:** - Communication exceptions are not catched in C API [\#89](https://github.com/Nitrokey/libnitrokey/issues/89) - Devices are not detected under Windows [\#88](https://github.com/Nitrokey/libnitrokey/issues/88) - Python bindings example is not working [\#82](https://github.com/Nitrokey/libnitrokey/issues/82) - Missing NK\_C\_API.h in install includes [\#77](https://github.com/Nitrokey/libnitrokey/issues/77) - Handle time-taking commands [\#67](https://github.com/Nitrokey/libnitrokey/issues/67) ## [v3.1](https://github.com/Nitrokey/libnitrokey/tree/v3.1) (2017-10-11) [Full Changelog](https://github.com/Nitrokey/libnitrokey/compare/v3.0...v3.1) ## [v3.0](https://github.com/Nitrokey/libnitrokey/tree/v3.0) (2017-10-07) [Full Changelog](https://github.com/Nitrokey/libnitrokey/compare/v2.0...v3.0) **Implemented enhancements:** - Support for NK Pro 0.8 [\#51](https://github.com/Nitrokey/libnitrokey/issues/51) **Closed issues:** - tests are failing [\#71](https://github.com/Nitrokey/libnitrokey/issues/71) - cmake doesn't install any headers [\#70](https://github.com/Nitrokey/libnitrokey/issues/70) - SONAME versioning [\#69](https://github.com/Nitrokey/libnitrokey/issues/69) - Read slot returns invalid counter value for Storage [\#59](https://github.com/Nitrokey/libnitrokey/issues/59) - Return OTP codes as strings [\#57](https://github.com/Nitrokey/libnitrokey/issues/57) - Fix compilation warnings [\#56](https://github.com/Nitrokey/libnitrokey/issues/56) - Add Travis support [\#48](https://github.com/Nitrokey/libnitrokey/issues/48) - Correct get\_time [\#27](https://github.com/Nitrokey/libnitrokey/issues/27) - Move from Makefile to CMake [\#18](https://github.com/Nitrokey/libnitrokey/issues/18) ## [v2.0](https://github.com/Nitrokey/libnitrokey/tree/v2.0) (2016-12-12) [Full Changelog](https://github.com/Nitrokey/libnitrokey/compare/v1.0...v2.0) **Implemented enhancements:** - Support for Nitrokey Storage - Nitrokey Storage commands [\#14](https://github.com/Nitrokey/libnitrokey/issues/14) - Support for Nitrokey Storage - Nitrokey Pro commands [\#13](https://github.com/Nitrokey/libnitrokey/issues/13) **Fixed bugs:** - Fails to compile on ubuntu 16.04 [\#46](https://github.com/Nitrokey/libnitrokey/issues/46) - C++ tests do not compile [\#45](https://github.com/Nitrokey/libnitrokey/issues/45) - HOTP counter values limited to 8bit [\#44](https://github.com/Nitrokey/libnitrokey/issues/44) - Device is not released after library function disconnect call [\#43](https://github.com/Nitrokey/libnitrokey/issues/43) **Closed issues:** - Compilation error on G++6 \(flexible array member\) [\#49](https://github.com/Nitrokey/libnitrokey/issues/49) - No library function for getting device's serial number [\#33](https://github.com/Nitrokey/libnitrokey/issues/33) - Pass binary data \(OTP secrets\) coded as hex values [\#31](https://github.com/Nitrokey/libnitrokey/issues/31) - set\_time not always work [\#29](https://github.com/Nitrokey/libnitrokey/issues/29) **Merged pull requests:** - Support for Nitrokey Pro 0.8 [\#53](https://github.com/Nitrokey/libnitrokey/pull/53) ([szszszsz](https://github.com/szszszsz)) - Support Nitrokey Storage [\#52](https://github.com/Nitrokey/libnitrokey/pull/52) ([szszszsz](https://github.com/szszszsz)) - Fix compilation G++6 error [\#50](https://github.com/Nitrokey/libnitrokey/pull/50) ([szszszsz](https://github.com/szszszsz)) - Fix compilation warning and error under G++ [\#47](https://github.com/Nitrokey/libnitrokey/pull/47) ([szszszsz](https://github.com/szszszsz)) - Support Pro stick commands on Storage device [\#42](https://github.com/Nitrokey/libnitrokey/pull/42) ([szszszsz](https://github.com/szszszsz)) - Readme update - dependencies, compilers, format [\#40](https://github.com/Nitrokey/libnitrokey/pull/40) ([szszszsz](https://github.com/szszszsz)) - Issue 31 secret as hex [\#36](https://github.com/Nitrokey/libnitrokey/pull/36) ([szszszsz](https://github.com/szszszsz)) - Function for getting device's serial number in hex. Fixes \#33 [\#34](https://github.com/Nitrokey/libnitrokey/pull/34) ([szszszsz](https://github.com/szszszsz)) ## [v1.0](https://github.com/Nitrokey/libnitrokey/tree/v1.0) (2016-08-09) [Full Changelog](https://github.com/Nitrokey/libnitrokey/compare/v0.9...v1.0) **Closed issues:** - Automatically detect any connected stick [\#22](https://github.com/Nitrokey/libnitrokey/issues/22) - Security check [\#20](https://github.com/Nitrokey/libnitrokey/issues/20) - Show friendly message when no device is connected and do not abort [\#17](https://github.com/Nitrokey/libnitrokey/issues/17) - Fix PIN protected OTP for Pro [\#15](https://github.com/Nitrokey/libnitrokey/issues/15) ## [v0.9](https://github.com/Nitrokey/libnitrokey/tree/v0.9) (2016-08-05) [Full Changelog](https://github.com/Nitrokey/libnitrokey/compare/v0.8...v0.9) **Closed issues:** - Add README [\#6](https://github.com/Nitrokey/libnitrokey/issues/6) - Support configs for OTP slots [\#19](https://github.com/Nitrokey/libnitrokey/issues/19) - Cover remaining Nitrokey Pro commands in lib and tests [\#16](https://github.com/Nitrokey/libnitrokey/issues/16) **Merged pull requests:** - waffle.io Badge [\#21](https://github.com/Nitrokey/libnitrokey/pull/21) ([waffle-iron](https://github.com/waffle-iron)) ## [v0.8](https://github.com/Nitrokey/libnitrokey/tree/v0.8) (2016-08-02) **Implemented enhancements:** - Change license to LGPLv3 [\#1](https://github.com/Nitrokey/libnitrokey/issues/1) **Closed issues:** - Python wrapper for OTP and PINs [\#12](https://github.com/Nitrokey/libnitrokey/issues/12) - Fails to built with default setting on ubuntu 14.04 [\#11](https://github.com/Nitrokey/libnitrokey/issues/11) - Check why packet buffers are not zeroed [\#8](https://github.com/Nitrokey/libnitrokey/issues/8) **Merged pull requests:** - Reset the HOTP counter [\#9](https://github.com/Nitrokey/libnitrokey/pull/9) ([cornelinux](https://github.com/cornelinux)) \* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*libnitrokey-3.7/CMakeLists.txt000066400000000000000000000220041423223421400164510ustar00rootroot00000000000000# https://cmake.org/pipermail/cmake/2011-May/044166.html IF(NOT DEFINED CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS) SET(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS ON) ENDIF() cmake_minimum_required(VERSION 3.1) IF (UNIX) OPTION(ADD_ASAN "Use ASAN to show memory issues" FALSE) OPTION(ADD_TSAN "Use TSAN to show thread issues" FALSE) IF(ADD_ASAN) SET(EXTRA_LIBS ${EXTRA_LIBS} asan ) ADD_COMPILE_OPTIONS(-fsanitize=address -fno-omit-frame-pointer) ENDIF() IF(ADD_TSAN) SET(EXTRA_LIBS ${EXTRA_LIBS} tsan ) SET(USE_CLANG TRUE) ADD_COMPILE_OPTIONS(-fsanitize=thread -fno-omit-frame-pointer -fPIC -g) #use with clang ENDIF() IF(ADD_TSAN AND ADD_ASAN) message(FATAL_ERROR "TSAN and ASAN cannot be used at the same time") ENDIF() ENDIF() project(libnitrokey LANGUAGES C CXX VERSION 3.7.0) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) include(GNUInstallDirs) IF (NOT CMAKE_BUILD_TYPE) IF(APPLE) # Issues occur when build with enabled optimizations set(CMAKE_BUILD_TYPE Debug) ELSE() set(CMAKE_BUILD_TYPE RelWithDebInfo) ENDIF() ENDIF() MESSAGE("${PROJECT_NAME}: Build type: ${CMAKE_BUILD_TYPE}") include_directories(hidapi) include_directories(libnitrokey) set(SOURCE_FILES libnitrokey/command.h libnitrokey/command_id.h libnitrokey/cxx_semantics.h libnitrokey/device.h libnitrokey/device_proto.h libnitrokey/dissect.h libnitrokey/log.h libnitrokey/misc.h libnitrokey/NitrokeyManager.h libnitrokey/stick10_commands.h libnitrokey/stick20_commands.h libnitrokey/CommandFailedException.h libnitrokey/LibraryException.h libnitrokey/LongOperationInProgressException.h libnitrokey/stick10_commands_0.8.h command_id.cc device.cc log.cc misc.cc NitrokeyManager.cc NK_C_API.h NK_C_API.cc DeviceCommunicationExceptions.cpp ${CMAKE_CURRENT_BINARY_DIR}/version.cc ) set(BUILD_SHARED_LIBS ON CACHE BOOL "Build all libraries as shared") add_library(nitrokey ${SOURCE_FILES}) set(HIDAPI_LIBUSB_NAME hidapi-libusb) IF(APPLE) include_directories(hidapi/hidapi) add_library(hidapi-libusb STATIC hidapi/mac/hid.c ) target_link_libraries(hidapi-libusb "-framework CoreFoundation" "-framework IOKit") target_link_libraries(nitrokey hidapi-libusb) ELSEIF(UNIX) # add_library(hidapi-libusb STATIC hidapi/libusb/hid.c ) find_package(PkgConfig) IF(${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") pkg_search_module(HIDAPI_LIBUSB REQUIRED hidapi) set(HIDAPI_LIBUSB_NAME hidapi) ELSE() pkg_search_module(HIDAPI_LIBUSB REQUIRED hidapi-libusb) ENDIF() target_compile_options(nitrokey PRIVATE ${HIDAPI_LIBUSB_CFLAGS}) target_link_libraries(nitrokey ${HIDAPI_LIBUSB_LDFLAGS}) ELSEIF(WIN32) include_directories(hidapi/hidapi) add_library(hidapi-libusb STATIC hidapi/windows/hid.c ) target_link_libraries(hidapi-libusb setupapi) target_link_libraries(nitrokey hidapi-libusb) ENDIF() set_target_properties(nitrokey PROPERTIES VERSION ${libnitrokey_VERSION} SOVERSION ${libnitrokey_VERSION_MAJOR}) OPTION(ERROR_ON_WARNING "Stop compilation on warning found (not supported for MSVC)" OFF) if (NOT MSVC) set(COMPILE_FLAGS "-Wall -Wno-unused-function -Wcast-qual -Woverloaded-virtual -Wsign-compare -Wformat -Wformat-security") IF(NOT APPLE) if (ERROR_ON_WARNING) set(COMPILE_FLAGS "${COMPILE_FLAGS} -Werror") endif() ENDIF() SET_TARGET_PROPERTIES(nitrokey PROPERTIES COMPILE_FLAGS ${COMPILE_FLAGS} ) endif() OPTION(NO_LOG "Compile without logging functionality and its strings (decreases size)" OFF) IF (NO_LOG) SET_TARGET_PROPERTIES(nitrokey PROPERTIES COMPILE_DEFINITIONS "NO_LOG") ENDIF() OPTION(LOG_VOLATILE_DATA "Log volatile data (debug)" OFF) IF (LOG_VOLATILE_DATA) SET_TARGET_PROPERTIES(nitrokey PROPERTIES COMPILE_DEFINITIONS "LOG_VOLATILE_DATA") ENDIF() OPTION(ADD_GIT_INFO "Add information about source code version from Git repository" TRUE) # generate version.h IF(ADD_GIT_INFO) execute_process( COMMAND git describe --always --abbrev=4 HEAD WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} RESULT_VARIABLE PROJECT_VERSION_GIT_RETURN_CODE OUTPUT_VARIABLE PROJECT_VERSION_GIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) ENDIF() # the version.h generation logic is tricky in a number of ways: # 1. git describe on a release tarball will always fail with # a non-zero return code, usually 128 # 2. If git is not installed, PROJECT_VERSION_GIT_RETURN_CODE # will contain the string 'No such file or directory' # Hence fallback to PROJECT_VERSION when the return code is NOT 0. IF((NOT ${ADD_GIT_INFO}) OR (NOT ${PROJECT_VERSION_GIT_RETURN_CODE} STREQUAL "0")) MESSAGE(STATUS "Setting fallback Git library version") SET(PROJECT_VERSION_GIT "v${PROJECT_VERSION}") ENDIF() MESSAGE(STATUS "Setting Git library version to: " ${PROJECT_VERSION_GIT} ) configure_file("version.cc.in" "version.cc" @ONLY) file(GLOB LIB_INCLUDES "libnitrokey/*.h" "NK_C_API.h") install (FILES ${LIB_INCLUDES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}) install (TARGETS nitrokey DESTINATION ${CMAKE_INSTALL_LIBDIR}) IF(NOT WIN32) # Install Nitrokey udev rules IF(NOT DEFINED CMAKE_INSTALL_UDEVRULESDIR) set(PKG_GET_UDEV_DIR ${PKG_CONFIG_EXECUTABLE} --variable=udevdir udev) execute_process(COMMAND ${PKG_GET_UDEV_DIR} RESULT_VARIABLE ERR OUTPUT_VARIABLE CMAKE_INSTALL_UDEVRULESDIR OUTPUT_STRIP_TRAILING_WHITESPACE) IF(${ERR}) set(CMAKE_INSTALL_UDEVRULESDIR "lib/udev/rules.d") ELSE() set(CMAKE_INSTALL_UDEVRULESDIR "${CMAKE_INSTALL_UDEVRULESDIR}/rules.d") ENDIF() string(REGEX REPLACE "^/" "" CMAKE_INSTALL_UDEVRULESDIR "${CMAKE_INSTALL_UDEVRULESDIR}") string(REGEX REPLACE "^usr/" "" CMAKE_INSTALL_UDEVRULESDIR "${CMAKE_INSTALL_UDEVRULESDIR}") # usual prefix is usr/local message(STATUS "Setting udev rules dir to ${CMAKE_INSTALL_UDEVRULESDIR}") ENDIF() install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/41-nitrokey.rules DESTINATION ${CMAKE_INSTALL_UDEVRULESDIR} ) ENDIF() # configure and install pkg-config file configure_file(${CMAKE_CURRENT_SOURCE_DIR}/libnitrokey.pc.in ${CMAKE_CURRENT_BINARY_DIR}/libnitrokey-1.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libnitrokey-1.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) OPTION(COMPILE_TESTS "Compile tests" FALSE) OPTION(COMPILE_OFFLINE_TESTS "Compile offline tests" FALSE) IF(COMPILE_OFFLINE_TESTS OR COMPILE_TESTS) find_package(PkgConfig) IF(PKG_CONFIG_FOUND) pkg_check_modules(CATCH2 catch2) ENDIF() if (CATCH2_FOUND) message(STATUS "Found system Catch2, not using bundled version") add_compile_options(${CATCH2_CFLAGS}) ELSE() message(STATUS "Did NOT find system Catch2, instead using bundled version") include_directories(unittest/Catch/single_include) ENDIF() add_library(catch STATIC unittest/catch_main.cpp ) ENDIF() IF(COMPILE_OFFLINE_TESTS) add_executable (test_offline unittest/test_offline.cc) target_link_libraries (test_offline ${EXTRA_LIBS} nitrokey catch) SET_TARGET_PROPERTIES(test_offline PROPERTIES COMPILE_FLAGS ${COMPILE_FLAGS} ) #run with 'make test' or 'ctest' include (CTest) add_test (runs test_offline) add_executable(test_minimal unittest/test_minimal.c) target_link_libraries(test_minimal ${EXTRA_LIBS} nitrokey) add_test(minimal test_minimal) ENDIF() IF (COMPILE_TESTS) #needs connected Pro/Storage devices for success #WARNING: it may delete data on the device SET(TESTS unittest/test_C_API.cpp unittest/test2.cc unittest/test3.cc unittest/test_HOTP.cc unittest/test1.cc unittest/test_issues.cc unittest/test_memory.c unittest/test_multiple_devices.cc unittest/test_strdup.cpp unittest/test_safe.cpp ) foreach(testsourcefile ${TESTS} ) get_filename_component(testname ${testsourcefile} NAME_WE ) add_executable(${testname} ${testsourcefile} ) target_link_libraries(${testname} ${EXTRA_LIBS} nitrokey catch ) SET_TARGET_PROPERTIES(${testname} PROPERTIES COMPILE_FLAGS ${COMPILE_FLAGS} ) endforeach(testsourcefile) ENDIF() #SET(CPACK_GENERATOR # "DEB;RPM") # build a CPack driven installer package include (InstallRequiredSystemLibraries) set (CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") set (CPACK_PACKAGE_VERSION "${PROJECT_VERSION}") include (CPack) # Build Doxygen documentation for the C API find_package(Doxygen) if (DOXYGEN_FOUND) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) add_custom_target(doc ${DOXYGEN_EXECUTABLE} Doxyfile WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Generating C API documentation with Doxygen" VERBATIM) endif(DOXYGEN_FOUND) libnitrokey-3.7/CMakeSettings.json000066400000000000000000000025221423223421400173100ustar00rootroot00000000000000{ // See https://go.microsoft.com//fwlink//?linkid=834763 for more information about this file. "configurations": [ { "name": "x86-Debug", "generator": "Visual Studio 15 2017", "configurationType" : "Debug", "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "-m -v:minimal" }, { "name": "x86-Release", "generator": "Visual Studio 15 2017", "configurationType" : "Release", "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "-m -v:minimal" }, { "name": "x64-Debug", "generator": "Visual Studio 15 2017 Win64", "configurationType" : "Debug", "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "-m -v:minimal" }, { "name": "x64-Release", "generator": "Visual Studio 15 2017 Win64", "configurationType" : "Release", "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "-m -v:minimal" } ] }libnitrokey-3.7/DeviceCommunicationExceptions.cpp000066400000000000000000000015501423223421400224070ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "DeviceCommunicationExceptions.h" std::atomic_int DeviceCommunicationException::occurred {0}; libnitrokey-3.7/Doxyfile.in000066400000000000000000000013371423223421400160320ustar00rootroot00000000000000# For better readability, the documentation and default settings are removed # from this file. For more information on the Doxygen configuration, generate # a new Doxyfile using `doxygen -g` or have a look at the Doxygen manual at # http://www.doxygen.nl/manual/config.html # # This file is processed by CMake. To generate the documentation, run `make # doc` in the build directory. PROJECT_NAME = "@CMAKE_PROJECT_NAME@" PROJECT_NUMBER = "@PROJECT_VERSION@" PROJECT_BRIEF = OUTPUT_DIRECTORY = doc STRIP_FROM_PATH = @CMAKE_CURRENT_SOURCE_DIR@ JAVADOC_AUTOBRIEF = YES OPTIMIZE_OUTPUT_FOR_C = YES WARN_NO_PARAMDOC = YES INPUT = @CMAKE_CURRENT_SOURCE_DIR@/NK_C_API.h libnitrokey-3.7/LICENSE000066400000000000000000000167441423223421400147340ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. libnitrokey-3.7/NK_C_API.cc000066400000000000000000000710741423223421400154760ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "NK_C_API.h" #include #include #include "libnitrokey/NitrokeyManager.h" #include #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 T* duplicate_vector_and_clear(std::vector &v){ auto d = new T[v.size()]; std::copy(v.begin(), v.end(), d); std::fill(v.begin(), v.end(), 0); return d; } template std::tuple 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 uint8_t * get_with_array_result(T func){ return std::get<1>(get_with_status(func, nullptr)); } template char* get_with_string_result(T func){ auto result = std::get<1>(get_with_status(func, nullptr)); if (result == nullptr) { return strndup("", MAXIMUM_STR_REPLY_LENGTH); } return result; } template auto get_with_result(T func){ return std::get<1>(get_with_status(func, static_cast(0))); } template 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 void NK_set_log_function(NK_log_function fn) { auto m = NitrokeyManager::instance(); std::function log_function = [fn](auto s, auto lvl) { fn(static_cast(lvl), s.c_str()); }; m->set_log_function_raw(log_function); } 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(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_get_random(const uint8_t len, struct GetRandom_t *out){ if (out == nullptr) return -1; auto m = NitrokeyManager::instance(); auto result = get_with_status([&]() { return m->get_random_pro(len); }, stick10::GetRandom::ResponsePayload()); auto error_code = std::get<0>(result); if (error_code != 0) { return error_code; } auto data = std::get<1>(result); memmove(out, reinterpret_cast(&data), sizeof(struct GetRandom_t)); return 0; } 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 libnitrokey-3.7/NK_C_API.h000066400000000000000000001070621423223421400153350ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef LIBNITROKEY_NK_C_API_H #define LIBNITROKEY_NK_C_API_H #include #include #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 * #include * #include * * 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); /** * Callback function for NK_set_log_function. The first argument is * the log level (0 = Error, 1 = Warn, 2 = Info, 3 = DebugL1, * 4 = Debug, 5 = DebugL2) and the second argument is the log message. */ NK_C_API typedef void (*NK_log_function)(int, const char*); /** * Set a custom log function. * * The log function is called for every log message that matches the * log level settings (see NK_set_debug and NK_set_debug_level). */ NK_C_API void NK_set_log_function(NK_log_function fn); /** * 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} * > {@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; }; struct GetRandom_t { uint8_t op_success; uint8_t size_effective; uint8_t data[51]; }; NK_C_API int NK_get_random(const uint8_t len, struct GetRandom_t *out); 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 libnitrokey-3.7/NitrokeyManager.cc000066400000000000000000001456231423223421400173340ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include #include #include "libnitrokey/NitrokeyManager.h" #include "libnitrokey/LibraryException.h" #include #include #include #include "libnitrokey/misc.h" #include #include "libnitrokey/cxx_semantics.h" #include "libnitrokey/misc.h" #include #include 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::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 void NitrokeyManager::authorize_packet(T &package, const char *admin_temporary_password, shared_ptr device){ if (!is_authorization_command_supported()){ LOG("Authorization command not supported, skipping", Loglevel::WARNING); } auto auth = get_payload(); strcpyT(auth.temporary_password, admin_temporary_password); auth.crc_to_authorize = S::CommandTransaction::getCRC(package); A::CommandTransaction::run(device, auth); } shared_ptr NitrokeyManager::_instance = nullptr; NitrokeyManager::NitrokeyManager() : device(nullptr) { set_debug(false); } NitrokeyManager::~NitrokeyManager() { std::lock_guard 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 lock(mex_dev_com_manager); if(device == nullptr) { return false; } device->set_receiving_delay(std::chrono::duration(send_receive_delay)); device->set_retry_delay(std::chrono::duration(retry_delay)); return true; } std::vector NitrokeyManager::list_devices(){ std::lock_guard lock(mex_dev_com_manager); return Device::enumerate(); } std::vector NitrokeyManager::list_devices_by_cpuID(){ using misc::toHex; //disconnect default device disconnect(); std::lock_guard 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 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(); 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 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 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_ids = { NITROKEY_VID, PURISM_VID }; for (auto vendor_id : vendor_ids) { auto info_ptr = hid_enumerate(vendor_id, 0); if (!info_ptr) { continue; } auto first_info_ptr = info_ptr; misc::Option 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()) continue; auto p = Device::create(model.value()); if (!p) continue; p->set_path(path); if(!p->connect()) continue; 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; } return false; } bool NitrokeyManager::connect() { std::lock_guard lock(mex_dev_com_manager); vector< shared_ptr > devices = { make_shared(), make_shared(), make_shared() }; bool connected = false; for( auto & d : devices ){ if (d->connect()){ device = std::shared_ptr(d); connected = true; } } return connected; } void NitrokeyManager::set_log_function(std::function log_function){ // FIXME use move and pass to log handler, instead of keeping here static variable static nitrokey::log::FunctionalLogHandler handler(log_function); nitrokey::log::Log::instance().set_handler(&handler); } void NitrokeyManager::set_log_function_raw(std::function log_function) { // FIXME use move and pass to log handler, instead of keeping here static variable static nitrokey::log::RawFunctionalLogHandler 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 lock(mex_dev_com_manager); LOG(__FUNCTION__, nitrokey::log::Loglevel::DEBUG_L2); switch (device_model[0]){ case 'P': device = make_shared(); break; case 'S': device = make_shared(); break; case 'L': device = make_shared(); 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::instance() { static std::mutex mutex; std::lock_guard lock(mutex); if (_instance == nullptr){ _instance = make_shared(); } return _instance; } bool NitrokeyManager::disconnect() { std::lock_guard 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 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 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(Loglevel::ERROR)); loglevel = min(loglevel, static_cast(Loglevel::DEBUG_L2)); Log::instance().set_loglevel(static_cast(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(); 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(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(); 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(); 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(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(); 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(); p.slot_number = slot_number; authorize_packet(p, temporary_password, device); auto resp = EraseSlot::CommandTransaction::run(device,p); } else { auto p = get_payload(); p.slot_number = slot_number; strcpyT(p.temporary_admin_password, temporary_password); auto resp = stick10_08::EraseSlot::CommandTransaction::run(device,p); } 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 void vector_copy_ranged(T& dest, std::vector &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 void vector_copy(T& dest, std::vector &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) { if (device == nullptr) { throw DeviceNotConnected("device not connected"); } auto payload = get_payload(); 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(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(); 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(); 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(); 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(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(); 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(); 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(); 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(); 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(current_PIN, new_PIN); } void NitrokeyManager::change_admin_PIN(const char *current_PIN, const char *new_PIN) { change_PIN_general(current_PIN, new_PIN); } template void NitrokeyManager::change_PIN_general(const char *current_PIN, const char *new_PIN) { if (device == nullptr) { throw DeviceNotConnected("device not connected"); } switch (device->get_device_model()){ case DeviceModel::LIBREM: case DeviceModel::PRO: { auto p = get_payload(); 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(); strcpyT(p.password, current_PIN); p.set_kind(StoKind); auto p2 = get_payload(); 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(); strcpyT(a.user_password, user_pin); IsAESSupported::CommandTransaction::run(device, a); auto p = get_payload(); strcpyT(p.user_password, user_pin); EnablePasswordSafe::CommandTransaction::run(device, p); } vector NitrokeyManager::get_password_safe_slot_status() { auto responsePayload = GetPasswordSafeSlotStatus::CommandTransaction::run(device); vector v = vector(responsePayload.data().password_safe_status, responsePayload.data().password_safe_status + sizeof(responsePayload.data().password_safe_status)); return v; } uint8_t NitrokeyManager::get_user_retry_count() { if (device == nullptr) { throw DeviceNotConnected("device not connected"); } 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 == nullptr) { throw DeviceNotConnected("device not connected"); } 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(); 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(); 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(); 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(); 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(); 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(); 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(); 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) { if (device == nullptr) { throw DeviceNotConnected("device not connected"); } switch (device->get_device_model()) { case DeviceModel::LIBREM: case DeviceModel::PRO: { auto p = get_payload(); strcpyT(p.admin_password, admin_password); BuildAESKey::CommandTransaction::run(device, p); break; } case DeviceModel::STORAGE : { auto p = get_payload(); strcpyT(p.password, admin_password); p.set_defaults(); stick20::CreateNewKeys::CommandTransaction::run(device, p); break; } } } void NitrokeyManager::factory_reset(const char *admin_password) { auto p = get_payload(); 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) { if (device == nullptr) { throw DeviceNotConnected("device not connected"); } switch (device->get_device_model()){ case DeviceModel::LIBREM: case DeviceModel::PRO: { auto p = get_payload(); 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(); p2.set_defaults(); strcpyT(p2.password, admin_password); ChangeAdminUserPin20Current::CommandTransaction::run(device, p2); auto p3 = get_payload(); 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(); p.numlock = numlock; p.capslock = capslock; p.scrolllock = scrolllock; p.enable_user_password = static_cast(enable_user_password ? 1 : 0); p.delete_user_password = static_cast(delete_user_password ? 1 : 0); if (is_authorization_command_supported()){ authorize_packet(p, admin_temporary_password, device); } else { strcpyT(p.temporary_admin_password, admin_temporary_password); } stick10_08::WriteGeneralConfig::CommandTransaction::run(device, p); } vector NitrokeyManager::read_config() { auto responsePayload = GetStatus::CommandTransaction::run(device); vector v = vector(responsePayload.data().general_config, responsePayload.data().general_config+sizeof(responsePayload.data().general_config)); return v; } bool NitrokeyManager::is_authorization_command_supported(){ if (device == nullptr) { throw DeviceNotConnected("device not connected"); } //authorization command is supported for versions equal or below: auto m = std::unordered_map({ {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(){ if (device == nullptr) { throw DeviceNotConnected("device not connected"); } // 320 bit OTP secret is supported by version bigger or equal to: auto m = std::unordered_map({ {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(){ if (device == nullptr) { throw DeviceNotConnected("device not connected"); } 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(){ if (device == nullptr) { throw DeviceNotConnected("device not connected"); } 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(); 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(); // 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(device, user_pin); } void NitrokeyManager::unlock_hidden_volume(const char* hidden_volume_password) { misc::execute_password_command(device, hidden_volume_password); } void NitrokeyManager::set_encrypted_volume_read_only(const char* admin_pin) { misc::execute_password_command(device, admin_pin); } void NitrokeyManager::set_encrypted_volume_read_write(const char* admin_pin) { misc::execute_password_command(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(); 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(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(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(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(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(device, admin_pin); } void NitrokeyManager::enable_firmware_update(const char* firmware_pin) { misc::execute_password_command(device, firmware_pin); } void NitrokeyManager::clear_new_sd_card_warning(const char* admin_pin) { misc::execute_password_command(device, admin_pin); } void NitrokeyManager::fill_SD_card_with_random_data(const char* admin_pin) { auto p = get_payload(); p.set_defaults(); strcpyT(p.admin_pin, admin_pin); stick20::FillSDCardWithRandomChars::CommandTransaction::run(device, p); } void NitrokeyManager::change_update_password(const char* current_update_password, const char* new_update_password) { auto p = get_payload(); strcpyT(p.current_update_password, current_update_password); strcpyT(p.new_update_password, new_update_password); stick20::ChangeUpdatePassword::CommandTransaction::run(device, p); } 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 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) { if (device == nullptr) { throw DeviceNotConnected("device not connected"); } auto p = get_payload(); 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(device, ""); } void NitrokeyManager::lock_hidden_volume() { misc::execute_password_command(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(); strcpyT(p.firmware_password, firmware_pin); FirmwareUpdate::CommandTransaction::run(device, p); } GetRandom::ResponsePayload NitrokeyManager::get_random_pro(uint8_t size_requested) { auto p = get_payload(); p.size_requested = size_requested; auto data = GetRandom::CommandTransaction::run(device, p); return data.data(); } void NitrokeyManager::change_firmware_update_password_pro(const char *firmware_pin_current, const char *firmware_pin_new) { auto p = get_payload(); strcpyT(p.firmware_password_current, firmware_pin_current); strcpyT(p.firmware_password_new, firmware_pin_new); FirmwarePasswordChange::CommandTransaction::run(device, p); } } libnitrokey-3.7/README.md000066400000000000000000000420631423223421400151770ustar00rootroot00000000000000[![Build Status](https://travis-ci.org/Nitrokey/libnitrokey.svg?branch=master)](https://travis-ci.org/Nitrokey/libnitrokey) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FNitrokey%2Flibnitrokey.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2FNitrokey%2Flibnitrokey?ref=badge_shield) # 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 a variety of compilers, starting from g++ 6.2 and clang 3.8. We use Travis CI to test builds also on g++ 5.4 and under OSX compilers starting up from xcode 9 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 .. make -j2 ``` By default (with empty `` 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 `` 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 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):
Code snippet (click to show) ```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):
Code snippet (click to show) ```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 with either 'pro' or 'storage' py.test -v test_.py # more specific use - run tests containing in name 5 times: py.test -v test_.py -k --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:
Log (click to show) ```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. libnitrokey-3.7/TODO000066400000000000000000000000731423223421400144030ustar00rootroot00000000000000use strings instead of char* and vectors instead of others libnitrokey-3.7/ci-script/000077500000000000000000000000001423223421400156105ustar00rootroot00000000000000libnitrokey-3.7/ci-script/build.sh000077500000000000000000000016511423223421400172510ustar00rootroot00000000000000#!/bin/bash set -exuo pipefail export . ./libnitrokey-source-metadata/metadata tar xf artifacts/${LIBNITROKEY_BUILD_OUTNAME}.tar.gz pushd ${LIBNITROKEY_BUILD_OUTNAME} pip3 install --user -r unittest/requirements.txt ## This is quite sketchy but will work for now - we're using a tarball prepared by git archive, so we can't pull submodules. ## Instead, we download the Catch2 header manually. The version is hardcoded, which is bad. ## TODO: figure out a better way to handle that ## One possibility is to install Catch2 system-wide on builder images. mkdir -p unittest/Catch/single_include/catch2 curl -L -o unittest/Catch/single_include/catch2/catch.hpp https://github.com/catchorg/Catch2/releases/download/v2.3.0/catch.hpp mkdir build mkdir install pushd build cmake .. -DERROR_ON_WARNING=OFF -DCOMPILE_TESTS=ON make -j2 ctest -VV make install DESTDIR=../install popd pushd unittest python3 -m pytest -sv test_offline.py popd libnitrokey-3.7/ci-script/package.sh000077500000000000000000000020621423223421400175420ustar00rootroot00000000000000#!/bin/bash set -exuo pipefail export mkdir -p artifacts OUTDIR="$(realpath artifacts)" BASENAME="libnitrokey" #pushd libnitrokey VERSION="$(git describe --abbrev=0)" BUILD="${VERSION}.${CI_COMMIT_SHORT_SHA}" DATE="$(date -Iseconds)" case "${CI_PIPELINE_SOURCE}" in push) OUTNAME="${BASENAME}-${BUILD}" ;; schedule) OUTNAME="${BASENAME}-${DATE}" ;; web) OUTNAME="${BASENAME}-${VERSION}" ;; esac git archive --format tar --prefix ${OUTNAME}/ ${CI_COMMIT_SHA} | gzip > ${OUTDIR}/${OUTNAME}.tar.gz echo size: gzip -l ${OUTDIR}/${OUTNAME}.tar.gz echo "LIBNITROKEY_BUILD_VERSION=\"${VERSION}\"" >> ./metadata echo "LIBNITROKEY_BUILD_ID=\"${BUILD}\"" >> ./metadata echo "LIBNITROKEY_BUILD_DATE=\"${DATE}\"" >> ./metadata echo "LIBNITROKEY_BUILD_TYPE=\"${CI_PIPELINE_SOURCE}\"" >> ./metadata echo "LIBNITROKEY_BUILD_OUTNAME=\"${OUTNAME}\"" >> ./metadata cat ./metadata pwd ls mkdir -p libnitrokey-source-metadata mv metadata libnitrokey-source-metadata/ cat libnitrokey-source-metadata/metadata pushd ${OUTDIR} sha256sum *.tar.gz > SHA256SUM popd libnitrokey-3.7/command_id.cc000066400000000000000000000147321423223421400163230ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include #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"; case CommandID::GET_RANDOM: return "GET_RANDOM"; } return "UNKNOWN"; } } } libnitrokey-3.7/data/000077500000000000000000000000001423223421400146245ustar00rootroot00000000000000libnitrokey-3.7/data/41-nitrokey.rules000066400000000000000000000054441423223421400177750ustar00rootroot00000000000000# # Copyright (c) 2015-2019 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 . # # SPDX-License-Identifier: LGPL-3.0 # # Here rules in new style should be provided. Matching devices should be tagged with 'uaccess'. # File prefix number should be lower than 73, to be correctly processed by the Udev. # Recommended udev version: >= 188. # ACTION!="add|change", GOTO="u2f_end" # Nitrokey U2F KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="2581", ATTRS{idProduct}=="f1d0", TAG+="uaccess" # Nitrokey FIDO U2F KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="4287", TAG+="uaccess" # Nitrokey FIDO2 KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42b1", TAG+="uaccess" # Nitrokey 3 NFC KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42b2", TAG+="uaccess" # Nitrokey 3 NFC Bootloader KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42dd", TAG+="uaccess" LABEL="u2f_end" SUBSYSTEM!="usb", GOTO="gnupg_rules_end" ACTION!="add", GOTO="gnupg_rules_end" # USB SmartCard Readers ## Crypto Stick 1.2 ATTR{idVendor}=="20a0", ATTR{idProduct}=="4107", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", TAG+="uaccess" ## Nitrokey Pro ATTR{idVendor}=="20a0", ATTR{idProduct}=="4108", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", TAG+="uaccess" ## Nitrokey Pro Bootloader ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42b4", TAG+="uaccess" ## Nitrokey Storage ATTR{idVendor}=="20a0", ATTR{idProduct}=="4109", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", TAG+="uaccess" ## Nitrokey Storage Bootloader ATTR{idVendor}=="03eb", ATTR{idProduct}=="2ff1", TAG+="uaccess" ## Nitrokey Start ATTR{idVendor}=="20a0", ATTR{idProduct}=="4211", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", TAG+="uaccess" ## Nitrokey HSM ATTR{idVendor}=="20a0", ATTR{idProduct}=="4230", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", TAG+="uaccess" LABEL="gnupg_rules_end" # Nitrokey Storage dev Entry KERNEL=="sd?1", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="4109", SYMLINK+="nitrospace" libnitrokey-3.7/data/41-nitrokey_old.rules000066400000000000000000000057731423223421400206400ustar00rootroot00000000000000# # Copyright (c) 2015-2019 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 . # # SPDX-License-Identifier: LGPL-3.0 # # Here rules in old style should be provided. Matching devices should be added to 'plugdev' group, # and with mode set to "0660". # File prefix number should be lower than 73, to be correctly processed by the Udev. # Recommended udev version: < 188. # ACTION!="add|change", GOTO="u2f_end" # Nitrokey U2F KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="2581", ATTRS{idProduct}=="f1d0", MODE="0660", GROUP+="plugdev" # Nitrokey FIDO U2F KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="4287", MODE="0660", GROUP+="plugdev" # Nitrokey FIDO2 KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42b1", MODE="0660", GROUP+="plugdev" # Nitrokey 3 NFC KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42b2", MODE="0660", GROUP+="plugdev" # Nitrokey 3 NFC Bootloader KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42dd", MODE="0660", GROUP+="plugdev" LABEL="u2f_end" SUBSYSTEM!="usb", GOTO="gnupg_rules_end" ACTION!="add", GOTO="gnupg_rules_end" # USB SmartCard Readers ## Crypto Stick 1.2 ATTR{idVendor}=="20a0", ATTR{idProduct}=="4107", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", MODE="0660", GROUP+="plugdev" ## Nitrokey Pro ATTR{idVendor}=="20a0", ATTR{idProduct}=="4108", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", MODE="0660", GROUP+="plugdev" ## Nitrokey Pro Bootloader ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="42b4", MODE="0660", GROUP+="plugdev" ## Nitrokey Storage ATTR{idVendor}=="20a0", ATTR{idProduct}=="4109", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", MODE="0660", GROUP+="plugdev" ## Nitrokey Storage Bootloader ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2ff1", MODE="0660", GROUP+="plugdev" ## Nitrokey Start ATTR{idVendor}=="20a0", ATTR{idProduct}=="4211", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", MODE="0660", GROUP+="plugdev" ## Nitrokey HSM ATTR{idVendor}=="20a0", ATTR{idProduct}=="4230", ENV{ID_SMARTCARD_READER}="1", ENV{ID_SMARTCARD_READER_DRIVER}="gnupg", MODE="0660", GROUP+="plugdev" LABEL="gnupg_rules_end" # Nitrokey Storage dev Entry KERNEL=="sd?1", ATTRS{idVendor}=="20a0", ATTRS{idProduct}=="4109", SYMLINK+="nitrospace" libnitrokey-3.7/device.cc000066400000000000000000000252141423223421400154650ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include #include #include #include #include #include #include #include "hidapi/hidapi.h" #include "libnitrokey/misc.h" #include "libnitrokey/device.h" #include "libnitrokey/log.h" #include #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 nitrokey::device::product_id_to_model(uint16_t product_id) { return product_id_to_model(NITROKEY_VID, product_id); } Option 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 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 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 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 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& 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) { pInfo = pInfo->next; 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> 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 Device::enumerate(){ std::vector res; ::add_vendor_devices(res, NITROKEY_VID); ::add_vendor_devices(res, PURISM_VID); return res; } std::shared_ptr Device::create(DeviceModel model) { switch (model) { case DeviceModel::PRO: return std::make_shared(); case DeviceModel::STORAGE: return std::make_shared(); case DeviceModel::LIBREM: return std::make_shared(); default: return {}; } } bool Device::could_be_enumerated() { LOG(__FUNCTION__, Loglevel::DEBUG_L2); std::lock_guard 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(delay); } void Device::set_receiving_delay(const std::chrono::milliseconds delay){ std::lock_guard lock(mex_dev_com); m_send_receive_delay = delay; } void Device::set_retry_delay(const std::chrono::milliseconds delay){ std::lock_guard lock(mex_dev_com); m_retry_timeout = delay; } Stick10::Stick10(): Device(NITROKEY_VID, NITROKEY_PRO_PID, DeviceModel::PRO, 100ms, 15, 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, 15, 100ms) { setDefaultDelay(); } #include #define p(x) ss << #x << " " << x << ", "; std::string Device::ErrorCounters::get_as_string() { #ifdef NO_LOG return ""; #endif if (total_comm_runs == 0) { return "Statistics: no connection run"; } 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 libnitrokey-3.7/hidapi/000077500000000000000000000000001423223421400151515ustar00rootroot00000000000000libnitrokey-3.7/libnitrokey.pc.in000066400000000000000000000004551423223421400172030ustar00rootroot00000000000000libdir=@CMAKE_INSTALL_FULL_LIBDIR@ includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: libnitrokey Description: Library for communicating with Nitrokey in a clean and easy manner Version: @libnitrokey_VERSION@ Requires.private: @HIDAPI_LIBUSB_NAME@ Libs: -L${libdir} -lnitrokey Cflags: -I${includedir} libnitrokey-3.7/libnitrokey.pro000066400000000000000000000060161423223421400167730ustar00rootroot00000000000000# Created by and for Qt Creator. This file was created for editing the project sources only. # You may attempt to use it for building too, by modifying this file here. CONFIG += c++14 shared debug TEMPLATE = lib TARGET = nitrokey VERSION = 3.7.0 LIBNK_VERSION_MAJOR = 3 LIBNK_VERSION_MINOR = 7 QMAKE_TARGET_COMPANY = Nitrokey QMAKE_TARGET_PRODUCT = libnitrokey QMAKE_TARGET_DESCRIPTION = Communicate with Nitrokey stick devices in a clean and easy manner QMAKE_TARGET_COPYRIGHT = Copyright (c) 2015-2022 Nitrokey Gmbh HEADERS = \ $$PWD/hidapi/hidapi/hidapi.h \ $$PWD/libnitrokey/command.h \ $$PWD/libnitrokey/command_id.h \ $$PWD/libnitrokey/CommandFailedException.h \ $$PWD/libnitrokey/cxx_semantics.h \ $$PWD/libnitrokey/device.h \ $$PWD/libnitrokey/device_proto.h \ $$PWD/libnitrokey/DeviceCommunicationExceptions.h \ $$PWD/libnitrokey/dissect.h \ $$PWD/libnitrokey/LibraryException.h \ $$PWD/libnitrokey/log.h \ $$PWD/libnitrokey/version.h \ $$PWD/libnitrokey/LongOperationInProgressException.h \ $$PWD/libnitrokey/misc.h \ $$PWD/libnitrokey/NitrokeyManager.h \ $$PWD/libnitrokey/stick10_commands.h \ $$PWD/libnitrokey/stick10_commands_0.8.h \ $$PWD/libnitrokey/stick20_commands.h \ $$PWD/NK_C_API.h SOURCES = \ $$PWD/command_id.cc \ $$PWD/device.cc \ $$PWD/DeviceCommunicationExceptions.cpp \ $$PWD/log.cc \ $$PWD/version.cc \ $$PWD/misc.cc \ $$PWD/NitrokeyManager.cc \ $$PWD/NK_C_API.cc tests { SOURCES += \ $$PWD/unittest/catch_main.cpp \ $$PWD/unittest/test.cc \ $$PWD/unittest/test2.cc \ $$PWD/unittest/test3.cc \ $$PWD/unittest/test_C_API.cpp \ $$PWD/unittest/test_HOTP.cc } unix:!macx{ # SOURCES += $$PWD/hidapi/linux/hid.c LIBS += -lhidapi-libusb } macx{ SOURCES += $$PWD/hidapi/mac/hid.c LIBS+= -framework IOKit -framework CoreFoundation } win32 { SOURCES += $$PWD/hidapi/windows/hid.c LIBS += -lsetupapi } INCLUDEPATH = \ $$PWD/. \ $$PWD/hidapi/hidapi \ $$PWD/libnitrokey \ $$PWD/libnitrokey/hidapi \ $$PWD/unittest \ $$PWD/unittest/Catch/single_include unix:!macx{ # Install rules for QMake (CMake is preffered though) udevrules.path = $$system(pkg-config --variable=udevdir udev) isEmpty(udevrules.path){ udevrules.path = "/lib/udev/" message("Could not detect path for udev rules - setting default: " $$udevrules.path) } udevrules.path = $$udevrules.path"/rules.d" udevrules.files = $$PWD/"data/41-nitrokey.rules" message ($$udevrules.files) INSTALLS +=udevrules headers.files = $$HEADERS headers.path = /usr/local/include/libnitrokey/ INSTALLS += headers libbin.path = /usr/local/lib INSTALLS += libbin } DEFINES += LIBNK_GIT_VERSION=\"\\\"$$system(git describe --abbrev=4 --always)\\\"\" LIBNK_VERSION="\\\"$${VERSION}\\\"" DEFINES += LIBNK_VERSION_MAJOR=$${LIBNK_VERSION_MAJOR} LIBNK_VERSION_MINOR=$${LIBNK_VERSION_MINOR} message($$DEFINES) libnitrokey-3.7/libnitrokey/000077500000000000000000000000001423223421400162465ustar00rootroot00000000000000libnitrokey-3.7/libnitrokey/CommandFailedException.h000066400000000000000000000046651423223421400227740ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef LIBNITROKEY_COMMANDFAILEDEXCEPTION_H #define LIBNITROKEY_COMMANDFAILEDEXCEPTION_H #include #include #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(cs::timestamp_warning); } bool reason_AES_not_initialized() const throw(){ return last_command_status == static_cast(cs::AES_dec_failed); } bool reason_not_authorized() const throw(){ return last_command_status == static_cast(cs::not_authorized); } bool reason_slot_not_programmed() const throw(){ return last_command_status == static_cast(cs::slot_not_programmed); } bool reason_wrong_password() const throw(){ return last_command_status == static_cast(cs::wrong_password); } bool reason_smartcard_busy() const throw(){ return last_command_status == static_cast(cs2::smartcard_error); } }; #endif //LIBNITROKEY_COMMANDFAILEDEXCEPTION_H libnitrokey-3.7/libnitrokey/DeviceCommunicationExceptions.h000066400000000000000000000043401423223421400244070ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H #define LIBNITROKEY_DEVICECOMMUNICATIONEXCEPTIONS_H #include #include #include #include class DeviceCommunicationException: public std::runtime_error { std::string message; static std::atomic_int occurred; public: explicit DeviceCommunicationException(const 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 libnitrokey-3.7/libnitrokey/LibraryException.h000066400000000000000000000062711423223421400217100ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef LIBNITROKEY_LIBRARYEXCEPTION_H #define LIBNITROKEY_LIBRARYEXCEPTION_H #include #include #include #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 libnitrokey-3.7/libnitrokey/LongOperationInProgressException.h000066400000000000000000000031631423223421400250750ustar00rootroot00000000000000/* * 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 . * * 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 libnitrokey-3.7/libnitrokey/NitrokeyManager.h000066400000000000000000000305541423223421400215250ustar00rootroot00000000000000/* * 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 . * * 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 #include #include 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 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} * > {@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 list_devices(); std::vector 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 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 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 get_SD_usage_data(); int get_progress_bar_value(); virtual ~NitrokeyManager(); bool is_authorization_command_supported(); bool is_320_OTP_secret_supported(); template void authorize_packet(T &package, const char *admin_temporary_password, shared_ptr device); uint8_t get_minor_firmware_version(); explicit NitrokeyManager(); void set_log_function(std::function log_function); void set_log_function_raw(std::function log_function); private: static shared_ptr _instance; std::shared_ptr device; std::string current_device_id; public: const string get_current_device_id() const; private: std::unordered_map > connected_devices; std::unordered_map > 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 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; GetRandom::ResponsePayload get_random_pro(uint8_t size_requested); }; } #endif //LIBNITROKEY_NITROKEYMANAGER_H libnitrokey-3.7/libnitrokey/command.h000066400000000000000000000072711423223421400200440ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef COMMAND_H #define COMMAND_H #include #include "command_id.h" #include "cxx_semantics.h" #define print_to_ss(x) ( ss << " " << (#x) <<":\t" << (x) << std::endl ); #define print_to_ss_int(x) ( ss << " " << (#x) <<":\t" << (int)(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 class Command : semantics::non_constructible { public: constexpr static CommandID command_id() { return cmd_id; } template 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 class PasswordCommand : public Command { 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_id(), struct CommandPayload, struct EmptyPayload> // CommandTransaction; using CommandTransaction = Transaction; //using CommandTransaction = Transaction<_command_id(), CommandPayload, EmptyPayload>; }; } } } #endif libnitrokey-3.7/libnitrokey/command_id.h000066400000000000000000000104771423223421400205220ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef COMMAND_ID_H #define COMMAND_ID_H #include 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, GET_RANDOM = 0x1B, 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 libnitrokey-3.7/libnitrokey/cxx_semantics.h000066400000000000000000000021471423223421400212730ustar00rootroot00000000000000/* * 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 . * * 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 libnitrokey-3.7/libnitrokey/deprecated.h000066400000000000000000000021551423223421400205220ustar00rootroot00000000000000/* * 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 . * * 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 libnitrokey-3.7/libnitrokey/device.h000066400000000000000000000137311423223421400176630ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef DEVICE_H #define DEVICE_H #include #include "hidapi/hidapi.h" #include #include #include #include #include #include "misc.h" #define HID_REPORT_SIZE 65 #include namespace nitrokey { namespace device { using namespace std::chrono_literals; using std::chrono::milliseconds; struct EnumClassHash { template std::size_t operator()(T t) const { return static_cast(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 product_id_to_model(uint16_t product_id); misc::Option 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 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 bool connect(); 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 enumerate(); /** * Create a Device of the given model. */ static std::shared_ptr 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(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 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::atomicmp_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 libnitrokey-3.7/libnitrokey/device_proto.h000066400000000000000000000522441423223421400211100ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef DEVICE_PROTO_H #define DEVICE_PROTO_H #include #include #include #include #include // a local version for compatibility with Windows #include #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 #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 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::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 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::dissect(*this); } } __packed; struct EmptyPayload { bool isValid() const { return true; } std::string dissect() const { return std::string("Empty Payload."); } } __packed; template class ClearingProxy { public: ClearingProxy(command_packet &p) { packet = p; bzero(&p, sizeof(p)); } virtual ~ClearingProxy() { bzero(&packet, sizeof(packet)); } response_payload &data() { return packet.payload; } command_packet packet; }; template 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 OutgoingPacket; typedef struct DeviceResponse ResponsePacket; #pragma pack (pop) static_assert(std::is_pod::value, "outgoingpacket must be a pod type"); static_assert(std::is_pod::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 static void clear_packet(T &st) { bzero(&st, sizeof(st)); } static ClearingProxy run(std::shared_ptr dev, const command_payload &payload) { using namespace ::nitrokey::device; using namespace ::nitrokey::log; using namespace std::chrono_literals; std::lock_guard guard(send_receive_mtx); LOG(__FUNCTION__, Loglevel::DEBUG_L2); if (dev == nullptr){ LOG(std::string("Connection not established yet"), Loglevel::DEBUG_L2); 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(outp), Loglevel::DEBUG); LOG(std::string("=> ") + std::string(commandid_to_string(static_cast(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(stick10::command_status::ok); switch (static_cast(resp.storage_status.device_status)) { case stick20::device_status::idle : case stick20::device_status::ok: resp.device_status = static_cast(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(stick10::device_status::busy); break; case stick20::device_status::wrong_password: resp.last_command_status = static_cast(stick10::command_status::wrong_password); resp.device_status = static_cast(stick10::device_status::ok); break; case stick20::device_status::no_user_password_unlock: resp.last_command_status = static_cast(stick10::command_status::AES_dec_failed); resp.device_status = static_cast(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(stick10::device_status::ok) && CRC_equal_awaited && resp.isValid()){ successful_communication = true; break; } if (resp.device_status == static_cast(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(stick10::device_status::busy) && static_cast(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(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(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(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(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(stick10::device_status::busy) && static_cast(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(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(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 run(std::shared_ptr dev) { command_payload empty_payload; return run(dev, empty_payload); } }; } } #endif libnitrokey-3.7/libnitrokey/dissect.h000066400000000000000000000114071423223421400200600ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ /* * Protocol packet dissection */ #ifndef DISSECT_H #define DISSECT_H #include #include #include #include "misc.h" #include "cxx_semantics.h" #include "command_id.h" #include "device_proto.h" namespace nitrokey { namespace proto { template 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 class ResponseDissector : semantics::non_constructible { public: static std::string status_translate_device(int status){ auto enum_status = static_cast(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(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(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 libnitrokey-3.7/libnitrokey/hidapi/000077500000000000000000000000001423223421400175045ustar00rootroot00000000000000libnitrokey-3.7/libnitrokey/hidapi/hidapi.h000066400000000000000000000330561423223421400211220ustar00rootroot00000000000000/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software 8/22/2009 Copyright 2009, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: http://github.com/signal11/hidapi . ********************************************************/ /** @file * @defgroup API hidapi API */ #ifndef HIDAPI_H__ #define HIDAPI_H__ #include #ifdef _WIN32 #define HID_API_EXPORT __declspec(dllexport) #define HID_API_CALL #else #define HID_API_EXPORT /**< API export macro */ #define HID_API_CALL /**< API call macro */ #endif #define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/ #ifdef __cplusplus extern "C" { #endif struct hid_device_; typedef struct hid_device_ hid_device; /**< opaque hidapi structure */ /** hidapi info structure */ struct hid_device_info { /** Platform-specific device path */ char *path; /** Device Vendor ID */ unsigned short vendor_id; /** Device Product ID */ unsigned short product_id; /** Serial Number */ wchar_t *serial_number; /** Device Release Number in binary-coded decimal, also known as Device Version Number */ unsigned short release_number; /** Manufacturer String */ wchar_t *manufacturer_string; /** Product string */ wchar_t *product_string; /** Usage Page for this Device/Interface (Windows/Mac only). */ unsigned short usage_page; /** Usage for this Device/Interface (Windows/Mac only).*/ unsigned short usage; /** The USB interface which this logical device represents. Valid on both Linux implementations in all cases, and valid on the Windows implementation only if the device contains more than one interface. */ int interface_number; /** Pointer to the next device */ struct hid_device_info *next; }; /** @brief Initialize the HIDAPI library. This function initializes the HIDAPI library. Calling it is not strictly necessary, as it will be called automatically by hid_enumerate() and any of the hid_open_*() functions if it is needed. This function should be called at the beginning of execution however, if there is a chance of HIDAPI handles being opened by different threads simultaneously. @ingroup API @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_init(void); /** @brief Finalize the HIDAPI library. This function frees all of the static data associated with HIDAPI. It should be called at the end of execution to avoid memory leaks. @ingroup API @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_exit(void); /** @brief Enumerate the HID Devices. This function returns a linked list of all the HID devices attached to the system which match vendor_id and product_id. If @p vendor_id is set to 0 then any vendor matches. If @p product_id is set to 0 then any product matches. If @p vendor_id and @p product_id are both set to 0, then all HID devices will be returned. @ingroup API @param vendor_id The Vendor ID (VID) of the types of device to open. @param product_id The Product ID (PID) of the types of device to open. @returns This function returns a pointer to a linked list of type struct #hid_device, containing information about the HID devices attached to the system, or NULL in the case of failure. Free this linked list by calling hid_free_enumeration(). */ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id); /** @brief Free an enumeration Linked List This function frees a linked list created by hid_enumerate(). @ingroup API @param devs Pointer to a list of struct_device returned from hid_enumerate(). */ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs); /** @brief Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number. If @p serial_number is NULL, the first device with the specified VID and PID is opened. @ingroup API @param vendor_id The Vendor ID (VID) of the device to open. @param product_id The Product ID (PID) of the device to open. @param serial_number The Serial Number of the device to open (Optionally NULL). @returns This function returns a pointer to a #hid_device object on success or NULL on failure. */ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); /** @brief Open a HID device by its path name. The path name be determined by calling hid_enumerate(), or a platform-specific path name can be used (eg: /dev/hidraw0 on Linux). @ingroup API @param path The path name of the device to open @returns This function returns a pointer to a #hid_device object on success or NULL on failure. */ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path); /** @brief Write an Output report to a HID device. The first byte of @p data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to hid_write() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_write(), the Report ID (or 0x0, for devices with a single report), followed by the report data (16 bytes). In this example, the length passed in would be 17. hid_write() will send the data on the first OUT endpoint, if one exists. If it does not, it will send the data through the Control Endpoint (Endpoint 0). @ingroup API @param device A device handle returned from hid_open(). @param data The data to send, including the report number as the first byte. @param length The length in bytes of the data to send. @returns This function returns the actual number of bytes written and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length); /** @brief Read an Input report from a HID device with timeout. Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number if the device uses numbered reports. @ingroup API @param device A device handle returned from hid_open(). @param data A buffer to put the read data into. @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. @param milliseconds timeout in milliseconds or -1 for blocking wait. @returns This function returns the actual number of bytes read and -1 on error. If no packet was available to be read within the timeout period, this function returns 0. */ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds); /** @brief Read an Input report from a HID device. Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number if the device uses numbered reports. @ingroup API @param device A device handle returned from hid_open(). @param data A buffer to put the read data into. @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. @returns This function returns the actual number of bytes read and -1 on error. If no packet was available to be read and the handle is in non-blocking mode, this function returns 0. */ int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length); /** @brief Set the device handle to be non-blocking. In non-blocking mode calls to hid_read() will return immediately with a value of 0 if there is no data to be read. In blocking mode, hid_read() will wait (block) until there is data to read before returning. Nonblocking can be turned on and off at any time. @ingroup API @param device A device handle returned from hid_open(). @param nonblock enable or not the nonblocking reads - 1 to enable nonblocking - 0 to disable nonblocking. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock); /** @brief Send a Feature report to the device. Feature reports are sent over the Control endpoint as a Set_Report transfer. The first byte of @p data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to hid_send_feature_report() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_send_feature_report(): the Report ID (or 0x0, for devices which do not use numbered reports), followed by the report data (16 bytes). In this example, the length passed in would be 17. @ingroup API @param device A device handle returned from hid_open(). @param data The data to send, including the report number as the first byte. @param length The length in bytes of the data to send, including the report number. @returns This function returns the actual number of bytes written and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length); /** @brief Get a feature report from a HID device. Set the first byte of @p data[] to the Report ID of the report to be read. Make sure to allow space for this extra byte in @p data[]. Upon return, the first byte will still contain the Report ID, and the report data will start in data[1]. @ingroup API @param device A device handle returned from hid_open(). @param data A buffer to put the read data into, including the Report ID. Set the first byte of @p data[] to the Report ID of the report to be read, or set it to zero if your device does not use numbered reports. @param length The number of bytes to read, including an extra byte for the report ID. The buffer can be longer than the actual report. @returns This function returns the number of bytes read plus one for the report ID (which is still in the first byte), or -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length); /** @brief Close a HID device. @ingroup API @param device A device handle returned from hid_open(). */ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device); /** @brief Get The Manufacturer String from a HID device. @ingroup API @param device A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen); /** @brief Get The Product String from a HID device. @ingroup API @param device A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen); /** @brief Get The Serial Number String from a HID device. @ingroup API @param device A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen); /** @brief Get a string from a HID device, based on its string index. @ingroup API @param device A device handle returned from hid_open(). @param string_index The index of the string to get. @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen); /** @brief Get a string describing the last error which occurred. @ingroup API @param device A device handle returned from hid_open(). @returns This function returns a string containing the last error which occurred or NULL if none has occurred. */ HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device); #ifdef __cplusplus } #endif #endif libnitrokey-3.7/libnitrokey/log.h000066400000000000000000000062431423223421400172050ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef LOG_H #define LOG_H #include #include 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; log_function_type log_function; public: FunctionalLogHandler(log_function_type _log_function); virtual void print(const std::string &, Loglevel lvl); }; class RawFunctionalLogHandler : public LogHandler { using log_function_type = std::function; log_function_type log_function; public: RawFunctionalLogHandler(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 libnitrokey-3.7/libnitrokey/misc.h000066400000000000000000000067241423223421400173630ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef MISC_H #define MISC_H #include #include #include #include #include "log.h" #include "LibraryException.h" #include #include #include namespace nitrokey { namespace misc { /** * Simple replacement for std::optional (C++17). */ template 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 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 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::CommandPayload get_payload(){ //Create, initialize and return by value command payload typename T::CommandPayload st; bzero(&st, sizeof(st)); return st; } template void execute_password_command(Tdev &stick, const char *password) { auto p = get_payload(); p.set_defaults(); strcpyT(p.password, password); CMDTYPE::CommandTransaction::run(stick, p); } std::string hexdump(const 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 hex_string_to_byte(const char* hexString); } } #endif libnitrokey-3.7/libnitrokey/stick10_commands.h000066400000000000000000000677411423223421400215750ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef STICK10_COMMANDS_H #define STICK10_COMMANDS_H #include #include #include #include #include #include "device_proto.h" #include "command.h" #pragma pack (push,1) namespace nitrokey { namespace proto { /* * Stick10 protocol definition */ namespace stick10 { class GetSlotName : public Command { 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 CommandTransaction; }; class EraseSlot : Command { 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 CommandTransaction; }; class SetTime : Command { 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 CommandTransaction; }; class WriteToHOTPSlot : Command { 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 CommandTransaction; }; class WriteToTOTPSlot : Command { 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 CommandTransaction; }; class GetTOTP : Command { 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 CommandTransaction; }; class GetHOTP : Command { 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 CommandTransaction; }; class ReadSlot : Command { 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 CommandTransaction; }; class GetStatus : Command { 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 CommandTransaction; }; class GetPasswordRetryCount : Command { 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 CommandTransaction; }; class GetUserPasswordRetryCount : Command { 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 CommandTransaction; }; template void write_array(T &ss, Q (&arr)[N]){ for (int i=0; i { 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 CommandTransaction; }; class GetPasswordSafeSlotName : Command { 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 CommandTransaction; }; class GetPasswordSafeSlotPassword : Command { 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 CommandTransaction; }; class GetPasswordSafeSlotLogin : Command { 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 CommandTransaction; }; class SetPasswordSafeSlotData : Command { 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 CommandTransaction; }; class SetPasswordSafeSlotData2 : Command { 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 CommandTransaction; }; class ErasePasswordSafeSlot : Command { 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 CommandTransaction; }; class EnablePasswordSafe : Command { 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 CommandTransaction; }; class PasswordSafeInitKey : Command { /** * never used in Nitrokey App */ public: typedef Transaction CommandTransaction; }; class PasswordSafeSendSlotViaHID : Command { /** * 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 CommandTransaction; }; // TODO "Device::passwordSafeSendSlotDataViaHID" class WriteGeneralConfig : Command { 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 CommandTransaction; }; class FirstAuthenticate : Command { 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 CommandTransaction; }; class UserAuthenticate : Command { 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 CommandTransaction; }; class Authorize : Command { 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 CommandTransaction; }; class UserAuthorize : Command { 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 CommandTransaction; }; class UnlockUserPassword : Command { 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 CommandTransaction; }; class ChangeUserPin : Command { 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 CommandTransaction; }; class IsAESSupported : Command { 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 CommandTransaction; }; class ChangeAdminPin : Command { 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 CommandTransaction; }; class LockDevice : Command { public: typedef Transaction CommandTransaction; }; class FactoryReset : Command { 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 CommandTransaction; }; class BuildAESKey : Command { 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 CommandTransaction; }; class GetRandom : Command { public: static const int DATA_SIZE_MAX = 64 - 13; struct CommandPayload { uint8_t size_requested; bool isValid() const { return size_requested < DATA_SIZE_MAX; } std::string dissect() const { std::stringstream ss; print_to_ss_int(size_requested); return ss.str(); } } __packed; struct ResponsePayload { uint8_t op_success; uint8_t size_effective; uint8_t data[DATA_SIZE_MAX]; bool isValid() const { return true; } std::string dissect() const { std::stringstream ss; print_to_ss_int(op_success); print_to_ss_int(size_effective); hexdump_to_ss(data); return ss.str(); } } __packed; typedef Transaction CommandTransaction; }; class FirmwareUpdate : Command { 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 CommandTransaction; }; class FirmwarePasswordChange : Command { 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 CommandTransaction; }; } } } #pragma pack (pop) #endif libnitrokey-3.7/libnitrokey/stick10_commands_0.8.h000066400000000000000000000343541423223421400221540ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef LIBNITROKEY_STICK10_COMMANDS_0_8_H #define LIBNITROKEY_STICK10_COMMANDS_0_8_H #include #include #include #include #include #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 { 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 CommandTransaction; }; class SendOTPData : Command { //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 CommandTransaction; }; class WriteToOTPSlot : Command { //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 CommandTransaction; }; class GetHOTP : Command { 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 CommandTransaction; }; class GetTOTP : Command { //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 CommandTransaction; }; class WriteGeneralConfig : Command { //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 CommandTransaction; }; } } } #pragma pack (pop) #endif //LIBNITROKEY_STICK10_COMMANDS_0_8_H libnitrokey-3.7/libnitrokey/stick20_commands.h000066400000000000000000000407271423223421400215710ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef STICK20_COMMANDS_H #define STICK20_COMMANDS_H #include #include "command.h" #include #include #include "device_proto.h" #pragma pack (push,1) namespace nitrokey { namespace proto { /* * STICK20 protocol command ids * a superset (almost) of STICK10 */ namespace stick20 { class ChangeAdminUserPin20Current : public PasswordCommand {}; class ChangeAdminUserPin20New : public PasswordCommand {}; class UnlockUserPin : public PasswordCommand {}; class EnableEncryptedPartition : public PasswordCommand {}; class EnableHiddenEncryptedPartition : public PasswordCommand {}; class SetUnencryptedVolumeReadOnlyAdmin : public PasswordCommand {}; class SetUnencryptedVolumeReadWriteAdmin : public PasswordCommand {}; class SetEncryptedVolumeReadOnly : public PasswordCommand {}; class SetEncryptedVolumeReadWrite : public PasswordCommand {}; //FIXME the volume disabling commands do not need password class DisableEncryptedPartition : public PasswordCommand {}; class DisableHiddenEncryptedPartition : public PasswordCommand {}; class EnableFirmwareUpdate : public PasswordCommand {}; class ChangeUpdatePassword : Command { 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 CommandTransaction; }; class ExportFirmware : public PasswordCommand {}; class CreateNewKeys : public PasswordCommand {}; class FillSDCardWithRandomChars : Command { public: enum class ChosenVolumes : uint8_t { all_volumes = 0, encrypted_volume = 1 }; struct CommandPayload { uint8_t volume_flag; uint8_t kind; uint8_t 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(ChosenVolumes::encrypted_volume); } } __packed; typedef Transaction::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 { public: struct CommandPayload { uint64_t localtime; // POSIX seconds from epoch start, supports until year 2106 std::string dissect() const { std::stringstream ss; print_to_ss( localtime ); return ss.str(); } void set_defaults(){ localtime = std::chrono::duration_cast ( std::chrono::system_clock::now().time_since_epoch()).count(); } }__packed; using ResponsePayload = DeviceConfigurationResponsePacket::ResponsePayload; typedef Transaction CommandTransaction; }; // TODO fix original nomenclature class SendSetReadonlyToUncryptedVolume : public PasswordCommand {}; class SendSetReadwriteToUncryptedVolume : public PasswordCommand {}; class SendClearNewSdCardFound : public PasswordCommand {}; class GetDeviceStatus : Command { public: using ResponsePayload = DeviceConfigurationResponsePacket::ResponsePayload; typedef Transaction CommandTransaction; }; class Wink : Command { public: typedef Transaction CommandTransaction; }; class CheckSmartcardUsage : Command { public: typedef Transaction CommandTransaction; }; class GetSDCardOccupancy : Command { public: struct ResponsePayload { uint8_t WriteLevelMin; uint8_t WriteLevelMax; uint8_t ReadLevelMin; uint8_t ReadLevelMax; std::string dissect() const { std::stringstream ss; print_to_ss((int) WriteLevelMin); print_to_ss((int) WriteLevelMax); print_to_ss((int) ReadLevelMin); print_to_ss((int) ReadLevelMax); return ss.str(); } } __packed; typedef Transaction CommandTransaction; }; class SetupHiddenVolume : Command { public: 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 CommandTransaction; }; //disable this command for now // class LockFirmware : public PasswordCommand {}; class ProductionTest : Command { 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 CommandTransaction; }; } } } #undef print_to_ss #pragma pack (pop) #endif libnitrokey-3.7/libnitrokey/version.h000066400000000000000000000017341423223421400201110ustar00rootroot00000000000000/* * 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 . * * 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 libnitrokey-3.7/log.cc000066400000000000000000000063741423223421400150150ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "log.h" #include #include #include #include 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){ // FIXME crashes on exit because static object under mp_loghandler is not valid anymore, see NitrokeyManager::set_log_function 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); } void RawFunctionalLogHandler::print(const std::string &str, Loglevel lvl) { log_function(str, lvl); } 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; } RawFunctionalLogHandler::RawFunctionalLogHandler(log_function_type _log_function) { log_function = _log_function; } } } libnitrokey-3.7/meson.build000066400000000000000000000112451423223421400160600ustar00rootroot00000000000000project( 'libnitrokey', 'cpp', version : '3.7.0', license : 'LGPL-3.0+', default_options : [ 'cpp_std=c++14' ], meson_version : '>= 0.48.0', ) cxx = meson.get_compiler('cpp') host_system = host_machine.system() pkg = import('pkgconfig') common_flags = [ '-Wno-unused-function', '-Wcast-qual', ] test_cxxflags = common_flags + [ '-Woverloaded-virtual', ] test_cflags = common_flags add_project_arguments(cxx.get_supported_arguments(test_cxxflags), language : 'cpp') if get_option('offline-tests') add_languages('c', required: get_option('offline-tests')) c = meson.get_compiler('c') add_project_arguments(c.get_supported_arguments(test_cflags), language : 'c') endif if target_machine.system() == 'freebsd' dep_hidapi = dependency('hidapi') else dep_hidapi = dependency('hidapi-libusb') endif inc_libnitrokey = include_directories('libnitrokey') libnitrokey_args = [] if not get_option('log') libnitrokey_args += ['-DNO_LOG'] endif if get_option('log-volatile-data') libnitrokey_args += ['-DLOG_VOLATILE_DATA'] endif version_array = meson.project_version().split('.') version_major = version_array[0].to_int() version_minor = version_array[1].to_int() version_data = configuration_data() version_data.set('PROJECT_VERSION_MAJOR', version_major) version_data.set('PROJECT_VERSION_MINOR', version_minor) # We don't want to substitute it by noop version_data.set('PROJECT_VERSION_GIT', '@VCS_TAG@') version_cc_in = configure_file( input : 'version.cc.in', output : 'version.cc.in', configuration : version_data, ) version_cc = vcs_tag( input : version_cc_in, output : 'version.cc', fallback : 'v@0@'.format(meson.project_version()), ) libnitrokey = library( 'nitrokey', sources : [ 'command_id.cc', 'device.cc', 'log.cc', version_cc, 'misc.cc', 'NitrokeyManager.cc', 'NK_C_API.cc', 'DeviceCommunicationExceptions.cpp', ], include_directories : [ inc_libnitrokey, ], dependencies : [ dep_hidapi, ], cpp_args : libnitrokey_args, version : meson.project_version(), install : true, ) install_headers( 'libnitrokey/CommandFailedException.h', 'libnitrokey/command.h', 'libnitrokey/command_id.h', 'libnitrokey/cxx_semantics.h', 'libnitrokey/DeviceCommunicationExceptions.h', 'libnitrokey/device.h', 'libnitrokey/device_proto.h', 'libnitrokey/dissect.h', 'libnitrokey/LibraryException.h', 'libnitrokey/log.h', 'libnitrokey/LongOperationInProgressException.h', 'libnitrokey/misc.h', 'libnitrokey/version.h', 'libnitrokey/NitrokeyManager.h', 'libnitrokey/stick10_commands_0.8.h', 'libnitrokey/stick10_commands.h', 'libnitrokey/stick20_commands.h', subdir : meson.project_name(), ) ext_libnitrokey = declare_dependency( link_with : libnitrokey, include_directories : inc_libnitrokey, ) pkg.generate( name : meson.project_name(), filebase : 'libnitrokey-1', libraries : libnitrokey, version : meson.project_version(), requires_private : dep_hidapi.name(), description : 'Library for communicating with Nitrokey in a clean and easy manner', install : true, ) if target_machine.system() == 'freebsd' dep_udev = dependency('libudev') else dep_udev = dependency('udev') endif install_data( 'data/41-nitrokey.rules', install_dir : '@0@/rules.d'.format(dep_udev.get_pkgconfig_variable('udevdir')), ) if get_option('tests') or get_option('offline-tests') dep_catch = dependency('catch2', version : '>=2.3.0', required : false) if not dep_catch.found() dep_catch = declare_dependency( include_directories : include_directories('unittest/Catch/single_include') ) endif _catch = static_library( 'catch', sources : [ 'unittest/catch_main.cpp', ], dependencies : [ dep_catch, ], ) _dep_catch = declare_dependency( link_with : _catch, dependencies : dep_catch, ) endif tests = [] if get_option('offline-tests') tests += [ ['test_offline', 'test_offline.cc'], ['test_minimal', 'test_minimal.c'], ] endif if get_option('tests') tests += [ ['test_C_API', 'test_C_API.cpp'], ['test1', 'test1.cc'], ['test2', 'test2.cc'], ['test3', 'test3.cc'], ['test_HOTP', 'test_HOTP.cc'], ['test_memory', 'test_memory.c'], ['test_issues', 'test_issues.cc'], ['test_multiple_devices', 'test_multiple_devices.cc'], ['test_strdup', 'test_strdup.cpp'], ['test_safe', 'test_safe.cpp'], ] endif foreach tst : tests test( tst[0], executable( tst[0], sources : 'unittest/@0@'.format(tst[1]), dependencies : [ ext_libnitrokey, _dep_catch, ], ) ) endforeach libnitrokey-3.7/meson_options.txt000066400000000000000000000006121423223421400173470ustar00rootroot00000000000000option('log', type : 'boolean', value : true, description : 'Logging functionality') option('log-volatile-data', type : 'boolean', value : false, description : 'Log volatile data (debug)') option('tests', type : 'boolean', value : false, description : 'Compile tests (needs connected PRO device)') option('offline-tests', type : 'boolean', value : false, description : 'Compile offline tests') libnitrokey-3.7/misc.cc000066400000000000000000000063101423223421400151550ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include #include #include "misc.h" #include "inttypes.h" #include #include #include "LibraryException.h" #include namespace nitrokey { namespace misc { ::std::vector 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(); data.reserve(d_size); char buf[3]; buf[2] = '\0'; for(size_t i=0; i ::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 (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; } } } libnitrokey-3.7/python3_bindings_example.py000066400000000000000000000126341423223421400212670ustar00rootroot00000000000000#!/usr/bin/env python3 """ 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 . SPDX-License-Identifier: LGPL-3.0 """ import cffi from enum import Enum """ This example will print 10 HOTP codes from just written HOTP#2 slot. For more examples of use please refer to unittest/test_*.py files. """ ffi = cffi.FFI() get_string = ffi.string class DeviceErrorCode(Enum): STATUS_OK = 0 NOT_PROGRAMMED = 3 WRONG_PASSWORD = 4 STATUS_NOT_AUTHORIZED = 5 STATUS_AES_DEC_FAILED = 0xa 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") print("Please set the path using LIBNK_PATH environment variable to existing library or compile it (see " "README.md for details)") sys.exit(1) return C def get_hotp_code(lib, i): return get_string(lib.NK_get_hotp_code(i)) def to_hex(ss): return ''.join([ format(ord(s),'02x') for s in ss ]) print('Warning!') print('This example will change your configuration on inserted stick and overwrite your HOTP#2 slot.') print('Please write "continue" to continue or any other string to quit') a = input() if not a == 'continue': exit() ADMIN = input('Please enter your admin PIN (empty string uses 12345678) ') ADMIN = ADMIN or '12345678' # use default if empty string show_log = input('Should log messages be shown (please write "yes" to enable; this will make harder reading script output) ') == 'yes' libnitrokey = get_library() if show_log: log_level = input('Please select verbosity level (0-5, 2 is library default, 3 will be selected on empty input) ') log_level = log_level or '3' log_level = int(log_level) libnitrokey.NK_set_debug_level(log_level) else: libnitrokey.NK_set_debug_level(2) ADMIN_TEMP = '123123123' RFC_SECRET = to_hex('12345678901234567890') # libnitrokey.NK_login('S') # connect only to Nitrokey Storage device # libnitrokey.NK_login('P') # connect only to Nitrokey Pro device device_connected = libnitrokey.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() use_8_digits = True pin_correct = libnitrokey.NK_first_authenticate(ADMIN.encode('ascii'), ADMIN_TEMP.encode('ascii')) == DeviceErrorCode.STATUS_OK.value if pin_correct: print('Your PIN is correct!') else: print('Your PIN is not correct! Please try again. Please be careful to not lock your stick!') retry_count_left = libnitrokey.NK_get_admin_retry_count() print('Retry count left: %d' % retry_count_left ) exit() # For function parameters documentation please check NK_C_API.h assert libnitrokey.NK_write_config(255, 255, 255, False, True, ADMIN_TEMP.encode('ascii')) == DeviceErrorCode.STATUS_OK.value libnitrokey.NK_first_authenticate(ADMIN.encode('ascii'), ADMIN_TEMP.encode('ascii')) libnitrokey.NK_write_hotp_slot(1, 'python_test'.encode('ascii'), RFC_SECRET.encode('ascii'), 0, use_8_digits, False, False, "".encode('ascii'), ADMIN_TEMP.encode('ascii')) # RFC test according to: https://tools.ietf.org/html/rfc4226#page-32 test_data = [ 1284755224, 1094287082, 137359152, 1726969429, 1640338314, 868254676, 1918287922, 82162583, 673399871, 645520489, ] print('Getting HOTP code from Nitrokey Stick (RFC test, 8 digits): ') for i in range(10): hotp_slot_1_code = get_hotp_code(libnitrokey, 1) correct_str = "correct!" if hotp_slot_1_code.decode('ascii') == str(test_data[i])[-8:] else "not correct" print('%d: %s, should be %s -> %s' % (i, hotp_slot_1_code.decode('ascii'), str(test_data[i])[-8:], correct_str)) libnitrokey.NK_logout() # disconnect device libnitrokey-3.7/python_bindings_example.py000077500000000000000000000123571423223421400212110ustar00rootroot00000000000000#!/usr/bin/env python2 """ 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 . SPDX-License-Identifier: LGPL-3.0 """ import cffi from enum import Enum """ This example will print 10 HOTP codes from just written HOTP#2 slot. For more examples of use please refer to unittest/test_*.py files. """ ffi = cffi.FFI() get_string = ffi.string class DeviceErrorCode(Enum): STATUS_OK = 0 NOT_PROGRAMMED = 3 WRONG_PASSWORD = 4 STATUS_NOT_AUTHORIZED = 5 STATUS_AES_DEC_FAILED = 0xa 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") print("Please set the path using LIBNK_PATH environment variable to existing library or compile it (see " "README.md for details)") sys.exit(1) return C def get_hotp_code(lib, i): return get_string(lib.NK_get_hotp_code(i)) def to_hex(ss): return ''.join([ format(ord(s),'02x') for s in ss ]) print('Warning!') print('This example will change your configuration on inserted stick and overwrite your HOTP#2 slot.') print('Please write "continue" to continue or any other string to quit') a = raw_input() if not a == 'continue': exit() ADMIN = raw_input('Please enter your admin PIN (empty string uses 12345678) ') ADMIN = ADMIN or '12345678' # use default if empty string show_log = raw_input('Should log messages be shown (please write "yes" to enable; this will make harder reading script output) ') == 'yes' libnitrokey = get_library() if show_log: log_level = raw_input('Please select verbosity level (0-5, 2 is library default, 3 will be selected on empty input) ') log_level = log_level or '3' log_level = int(log_level) libnitrokey.NK_set_debug_level(log_level) else: libnitrokey.NK_set_debug_level(2) ADMIN_TEMP = '123123123' RFC_SECRET = to_hex('12345678901234567890') # libnitrokey.NK_login('S') # connect only to Nitrokey Storage device # libnitrokey.NK_login('P') # connect only to Nitrokey Pro device device_connected = libnitrokey.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() use_8_digits = True pin_correct = libnitrokey.NK_first_authenticate(ADMIN, ADMIN_TEMP) == DeviceErrorCode.STATUS_OK if pin_correct: print('Your PIN is correct!') else: print('Your PIN is not correct! Please try again. Please be careful to not lock your stick!') retry_count_left = libnitrokey.NK_get_admin_retry_count() print('Retry count left: %d' % retry_count_left ) exit() # For function parameters documentation please check NK_C_API.h assert libnitrokey.NK_write_config(255, 255, 255, False, True, ADMIN_TEMP) == DeviceErrorCode.STATUS_OK libnitrokey.NK_first_authenticate(ADMIN, ADMIN_TEMP) libnitrokey.NK_write_hotp_slot(1, 'python_test', RFC_SECRET, 0, use_8_digits, False, False, "", ADMIN_TEMP) # RFC test according to: https://tools.ietf.org/html/rfc4226#page-32 test_data = [ 1284755224, 1094287082, 137359152, 1726969429, 1640338314, 868254676, 1918287922, 82162583, 673399871, 645520489, ] print('Getting HOTP code from Nitrokey Stick (RFC test, 8 digits): ') for i in range(10): hotp_slot_1_code = get_hotp_code(libnitrokey, 1) correct_str = "correct!" if hotp_slot_1_code == str(test_data[i])[-8:] else "not correct" print('%d: %s, should be %s -> %s' % (i, hotp_slot_1_code, str(test_data[i])[-8:], correct_str)) libnitrokey.NK_logout() # disconnect device libnitrokey-3.7/unittest/000077500000000000000000000000001423223421400155725ustar00rootroot00000000000000libnitrokey-3.7/unittest/Catch/000077500000000000000000000000001423223421400166145ustar00rootroot00000000000000libnitrokey-3.7/unittest/build/000077500000000000000000000000001423223421400166715ustar00rootroot00000000000000libnitrokey-3.7/unittest/build/libnitrokey.so000077700000000000000000000000001423223421400262052../../build/libnitrokey.soustar00rootroot00000000000000libnitrokey-3.7/unittest/build/run.sh000077500000000000000000000000361423223421400200330ustar00rootroot00000000000000LD_LIBRARY_PATH=. ./test_HOTP libnitrokey-3.7/unittest/catch_main.cpp000066400000000000000000000015361423223421400203710ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #include "catch2/catch.hpp"libnitrokey-3.7/unittest/conftest.py000066400000000000000000000134321423223421400177740ustar00rootroot00000000000000""" Copyright (c) 2015-2019 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 . SPDX-License-Identifier: LGPL-3.0 """ import pytest import os, sys from misc import ffi, gs device_type = None from logging import getLogger, basicConfig, DEBUG basicConfig(format='* %(relativeCreated)6d %(filename)s:%(lineno)d %(message)s',level=DEBUG) log = getLogger('conftest') print = log.debug def get_device_type(): return device_type def skip_if_device_version_lower_than(allowed_devices): global device_type model, version = device_type infinite_version_number = 999 if allowed_devices.get(model, infinite_version_number) > version: pytest.skip('This device model is not applicable to run this test') class AtrrCallProx(object): def __init__(self, C, name): self.C = C self.name = name def __call__(self, *args, **kwargs): print('Calling {}{}'.format(self.name, args)) res = self.C(*args, **kwargs) res_s = res try: res_s = '{} => '.format(res) + '{}'.format(gs(res)) except Exception as e: pass print('Result of {}: {}'.format(self.name, res_s)) return res class AttrProxy(object): def __init__(self, C, name): self.C = C self.name = name def __getattr__(self, attr): return AtrrCallProx(getattr(self.C, attr), attr) @pytest.fixture(scope="module") def C_offline(request=None): print("Getting library without initializing connection") return get_library(request, allow_offline=True) @pytest.fixture(scope="session") def C(request=None): import platform print(f"Python version: {platform.python_version()}") print(f"OS: {platform.system()} {platform.release()} {platform.version()}") print("Getting library with connection initialized") return get_library(request) def get_library(request, allow_offline=False): library_read_declarations() C = library_open_lib() C.NK_set_debug_level(int(os.environ.get('LIBNK_DEBUG', 2))) nk_login = C.NK_login_auto() if nk_login != 1: print('No devices detected!') if not allow_offline: assert nk_login != 0 # returns 0 if not connected or wrong model or 1 when connected global device_type firmware_version = C.NK_get_minor_firmware_version() model = C.NK_get_device_model() model = 'P' if model == 1 else 'S' if model == 2 else 'U' device_type = (model, firmware_version) print('Connected library: {}'.format(gs(C.NK_get_library_version()))) print('Connected device: {} {}'.format(model, firmware_version)) # assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK # assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK # C.NK_status() def fin(): print('\nFinishing connection to device') C.NK_logout() print('Finished') if request: request.addfinalizer(fin) # C.NK_set_debug(True) C.NK_set_debug_level(int(os.environ.get('LIBNK_DEBUG', 3))) return AttrProxy(C, "libnitrokey C") def library_open_lib(): C = None 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 library_read_declarations(): fp = '../NK_C_API.h' 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') \ or declaration.strip().startswith('struct'): declaration = declaration.replace('NK_C_API', '').strip() while ');' not in declaration and '};' not in declaration: declaration += (next(a)).strip() + '\n' ffi.cdef(declaration, override=True) cnt += 1 print('Imported {} declarations'.format(cnt)) def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) parser.addoption("--run-skipped", action="store_true", help="run the tests skipped by default, e.g. adding side effects") def pytest_runtest_setup(item): if 'skip_by_default' in item.keywords and not item.config.getoption("--run-skipped"): pytest.skip("need --run-skipped option to run this test") def pytest_configure(config): config.addinivalue_line("markers", "slow: mark test as slow to run") def library_device_reconnect(C): C.NK_logout() C = library_open_lib() C.NK_logout() assert C.NK_login_auto() == 1, 'Device not found' return Clibnitrokey-3.7/unittest/constants.py000066400000000000000000000052531423223421400201650ustar00rootroot00000000000000""" 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 . SPDX-License-Identifier: LGPL-3.0 """ from enum import Enum from sys import stderr from misc import to_hex, bb from conftest import print RFC_SECRET_HR = '12345678901234567890' RFC_SECRET = to_hex(RFC_SECRET_HR) # '31323334353637383930...' bbRFC_SECRET = bb(RFC_SECRET) # print( repr((RFC_SECRET, RFC_SECRET_, len(RFC_SECRET))) ) class DefaultPasswords: ADMIN = b'12345678' USER = b'123456' ADMIN_TEMP = b'123123123' USER_TEMP = b'234234234' UPDATE = b'12345678' UPDATE_TEMP = b'123update123' UPDATE_LONG = b'1234567890'*2 UPDATE_TOO_LONG = UPDATE_LONG + b'x' UPDATE_TOO_SHORT = UPDATE_LONG[:7] class DeviceErrorCode(Enum): STATUS_OK = 0 BUSY = 1 # busy or busy progressbar in place of wrong_CRC status NOT_PROGRAMMED = 3 WRONG_PASSWORD = 4 STATUS_NOT_AUTHORIZED = 5 STATUS_AES_DEC_FAILED = 10 STATUS_WRONG_SLOT = 2 STATUS_TIMESTAMP_WARNING = 6 STATUS_NO_NAME_ERROR = 7 STATUS_NOT_SUPPORTED = 8 STATUS_UNKNOWN_COMMAND = 9 STATUS_AES_CREATE_KEY_FAILED = 11 STATUS_ERROR_CHANGING_USER_PASSWORD = 12 STATUS_ERROR_CHANGING_ADMIN_PASSWORD = 13 STATUS_ERROR_UNBLOCKING_PIN = 14 STATUS_UNKNOWN_ERROR = 100 STATUS_DISCONNECTED = 255 def __eq__(self, other): other_name = 'Unknown' try: other_name = str(DeviceErrorCode(other).name) except: pass result = self.value == other print(f'Returned {other_name}, expected {self.name} => {result}') return result class LibraryErrors(Enum): TOO_LONG_STRING = 200 INVALID_SLOT = 201 INVALID_HEX_STRING = 202 TARGET_BUFFER_SIZE_SMALLER_THAN_SOURCE = 203 def __eq__(self, other): other_name = 'Unknown' try: other_name = str(LibraryErrors(other).name) except: pass result = self.value == other print(f'Returned {other_name}, expected {self.name} => {result}') return result HOTP_slot_count = 3 TOTP_slot_count = 15 PWS_SLOT_COUNT = 16 libnitrokey-3.7/unittest/helpers.py000066400000000000000000000036521423223421400176140ustar00rootroot00000000000000from constants import DeviceErrorCode, PWS_SLOT_COUNT, DefaultPasswords from misc import gs, bb def helper_fill(str_to_fill, target_width): assert target_width >= len(str_to_fill) numbers = '1234567890' * 4 str_to_fill += numbers[:target_width - len(str_to_fill)] assert len(str_to_fill) == target_width return bb(str_to_fill) def helper_PWS_get_pass(suffix): return helper_fill('pass' + suffix, 20) def helper_PWS_get_loginname(suffix): return helper_fill('login' + suffix, 32) def helper_PWS_get_slotname(suffix): return helper_fill('slotname' + suffix, 11) def helper_check_device_for_data(C): assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(0, PWS_SLOT_COUNT): iss = str(i) assert gs(C.NK_get_password_safe_slot_name(i)) == helper_PWS_get_slotname(iss) assert gs(C.NK_get_password_safe_slot_login(i)) == helper_PWS_get_loginname(iss) assert gs(C.NK_get_password_safe_slot_password(i)) == helper_PWS_get_pass(iss) return True def helper_populate_device(C): # FIXME use object with random data, and check against it # FIXME generate OTP as well, and check codes against its secrets assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK res = C.NK_enable_password_safe(DefaultPasswords.USER) if res != DeviceErrorCode.STATUS_OK: assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(0, PWS_SLOT_COUNT): iss = str(i) assert C.NK_write_password_safe_slot(i, helper_PWS_get_slotname(iss), helper_PWS_get_loginname(iss), helper_PWS_get_pass(iss)) == DeviceErrorCode.STATUS_OK return True libnitrokey-3.7/unittest/libnk-tool.py000077500000000000000000000023011423223421400202150ustar00rootroot00000000000000#!/usr/bin/env python3 """ Copyright (c) 2015-2019 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 . SPDX-License-Identifier: LGPL-3.0 """ import click from conftest import get_library, get_device_type from constants import DefaultPasswords, DeviceErrorCode @click.group() def cli(): pass @click.command() def update(): libnk = get_library(None) device_type = get_device_type() print(device_type) assert device_type[0] == 'S' assert libnk.NK_enable_firmware_update(DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK cli.add_command(update) if __name__ == '__main__': cli() libnitrokey-3.7/unittest/misc.py000066400000000000000000000036511423223421400171040ustar00rootroot00000000000000""" 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 . SPDX-License-Identifier: LGPL-3.0 """ import cffi ffi = cffi.FFI() gs = ffi.string def to_hex(s): return "".join("{:02x}".format(ord(c)) for c in s) def wait(t): import time msg = 'Waiting for %d seconds' % t print(msg.center(40, '=')) time.sleep(t) def cast_pointer_to_tuple(obj, typen, len): # usage: # config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) return tuple(ffi.cast("%s [%d]" % (typen, len), obj)[0:len]) def get_devices_firmware_version(C): firmware = C.NK_get_minor_firmware_version() return firmware def is_pro_rtm_07(C): firmware = get_devices_firmware_version(C) return firmware == 7 def is_pro_rtm_08(C): firmware = get_devices_firmware_version(C) return firmware in [8,9] def is_storage(C): """ exact firmware storage is sent by other function """ # TODO identify connected device directly firmware = get_devices_firmware_version(C) return firmware >= 45 def is_long_OTP_secret_handled(C): return is_pro_rtm_08(C) or is_storage(C) and get_devices_firmware_version(C) >= 54 def has_binary_counter(C): return (not is_storage(C)) or (is_storage(C) and get_devices_firmware_version(C) >= 54) def bb(x): return bytes(x, encoding='ascii')libnitrokey-3.7/unittest/pyproject.toml000066400000000000000000000005661423223421400205150ustar00rootroot00000000000000[tool.pytest.ini_options] markers = [ "slow: marks tests as slow (deselect with '-m \"not slow\"')", "serial", "aes", "encrypted", "factory_reset", "firmware", "hidden", "info", "lock_device", "other", "otp", "pin", "PWS", "skip", "skip_by_default", "slowtest", "status", "unencrypted", "update", ]libnitrokey-3.7/unittest/requirements.txt000066400000000000000000000000771423223421400210620ustar00rootroot00000000000000cffi pytest pytest-repeat pytest-randomly tqdm oath hypothesis libnitrokey-3.7/unittest/setup_python_dependencies.sh000066400000000000000000000000641423223421400233750ustar00rootroot00000000000000#!/bin/bash pip install -r requirements.txt --user libnitrokey-3.7/unittest/test1.cc000066400000000000000000000064701423223421400171500ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "catch2/catch.hpp" #include #include #include "device_proto.h" #include "log.h" #include "stick10_commands.h" using namespace std; using namespace nitrokey::device; using namespace nitrokey::proto::stick10; using namespace nitrokey::log; using namespace nitrokey::misc; using Dev10 = std::shared_ptr; std::string getSlotName(Dev10 stick, int slotNo) { auto slot_req = get_payload(); slot_req.slot_number = slotNo; auto slot = ReadSlot::CommandTransaction::run(stick, slot_req); std::string sName(reinterpret_cast(slot.data().slot_name)); return sName; } TEST_CASE("Slot names are correct", "[slotNames]") { auto stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); auto resp = GetStatus::CommandTransaction::run(stick); auto authreq = get_payload(); strcpy((char *)(authreq.card_password), "12345678"); FirstAuthenticate::CommandTransaction::run(stick, authreq); { auto authreq = get_payload(); strcpy((char *)(authreq.user_password), "123456"); EnablePasswordSafe::CommandTransaction::run(stick, authreq); } //assuming these values were set earlier, thus failing on normal use REQUIRE(getSlotName(stick, 0x20) == std::string("1")); REQUIRE(getSlotName(stick, 0x21) == std::string("slot2")); { auto resp = GetPasswordRetryCount::CommandTransaction::run(stick); REQUIRE(resp.data().password_retry_count == 3); } { auto resp = GetUserPasswordRetryCount::CommandTransaction::run(stick); REQUIRE(resp.data().password_retry_count == 3); } { auto slot = get_payload(); slot.slot_number = 0; auto resp2 = GetPasswordSafeSlotName::CommandTransaction::run(stick, slot); std::string sName(reinterpret_cast(resp2.data().slot_name)); REQUIRE(sName == std::string("web1")); } { auto slot = get_payload(); slot.slot_number = 0; auto resp2 = GetPasswordSafeSlotPassword::CommandTransaction::run(stick, slot); std::string sName(reinterpret_cast(resp2.data().slot_password)); REQUIRE(sName == std::string("pass1")); } { auto slot = get_payload(); slot.slot_number = 0; auto resp2 = GetPasswordSafeSlotLogin::CommandTransaction::run(stick, slot); std::string sName(reinterpret_cast(resp2.data().slot_login)); REQUIRE(sName == std::string("login1")); } stick->disconnect(); } libnitrokey-3.7/unittest/test2.cc000066400000000000000000000174111423223421400171460ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ static const char *const default_admin_pin = "12345678"; static const char *const default_user_pin = "123456"; #include "catch2/catch.hpp" #include #include #include #include "device_proto.h" #include "log.h" //#include "stick10_commands.h" #include "stick20_commands.h" using namespace std; using namespace nitrokey::device; using namespace nitrokey::proto; using namespace nitrokey::proto::stick20; using namespace nitrokey::log; using namespace nitrokey::misc; #include template void execute_password_command(std::shared_ptr stick, const char *password, const char kind = 'P') { auto p = get_payload(); if (kind == 'P'){ p.set_kind_user(); } else { p.set_kind_admin(); } strcpyT(p.password, password); CMDTYPE::CommandTransaction::run(stick, p); this_thread::sleep_for(1000ms); } /** * fail on purpose (will result in failed test) * disable from running unwillingly */ void SKIP_TEST() { CAPTURE("Failing current test to SKIP it"); REQUIRE(false); } TEST_CASE("long operation test", "[test_long]") { SKIP_TEST(); auto stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); try{ auto p = get_payload(); p.set_defaults(); strcpyT(p.admin_pin, default_admin_pin); FillSDCardWithRandomChars::CommandTransaction::run(stick, p); this_thread::sleep_for(1000ms); CHECK(false); } catch (LongOperationInProgressException &progressException){ CHECK(true); } for (int i = 0; i < 30; ++i) { try { stick10::GetStatus::CommandTransaction::run(stick); } catch (LongOperationInProgressException &progressException){ CHECK((int)progressException.progress_bar_value>=0); CAPTURE((int)progressException.progress_bar_value); this_thread::sleep_for(2000ms); } } } TEST_CASE("test device internal status with various commands", "[fast]") { auto stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); auto p = get_payload(); p.set_defaults(); auto device_status = stick20::SendStartup::CommandTransaction::run(stick, p); REQUIRE(device_status.data().AdminPwRetryCount == 3); REQUIRE(device_status.data().UserPwRetryCount == 3); REQUIRE(device_status.data().ActiveSmartCardID_u32 != 0); auto production_status = stick20::ProductionTest::CommandTransaction::run(stick); REQUIRE(production_status.data().SD_Card_Size_u8 == 8); REQUIRE(production_status.data().SD_CardID_u32 != 0); auto sdcard_occupancy = stick20::GetSDCardOccupancy::CommandTransaction::run(stick); REQUIRE((int) sdcard_occupancy.data().ReadLevelMin >= 0); REQUIRE((int) sdcard_occupancy.data().ReadLevelMax <= 100); REQUIRE((int) sdcard_occupancy.data().WriteLevelMin >= 0); REQUIRE((int) sdcard_occupancy.data().WriteLevelMax <= 100); } TEST_CASE("setup hidden volume test", "[hidden]") { auto stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); stick10::LockDevice::CommandTransaction::run(stick); this_thread::sleep_for(2000ms); auto user_pin = default_user_pin; execute_password_command(stick, user_pin); auto p = get_payload(); p.SlotNr_u8 = 0; p.StartBlockPercent_u8 = 70; p.EndBlockPercent_u8 = 90; auto hidden_volume_password = "123123123"; strcpyT(p.HiddenVolumePassword_au8, hidden_volume_password); stick20::SetupHiddenVolume::CommandTransaction::run(stick, p); this_thread::sleep_for(2000ms); execute_password_command(stick, hidden_volume_password); } TEST_CASE("setup multiple hidden volumes", "[hidden]") { auto stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); auto user_pin = default_user_pin; stick10::LockDevice::CommandTransaction::run(stick); this_thread::sleep_for(2000ms); execute_password_command(stick, user_pin); constexpr int volume_count = 4; for (int i = 0; i < volume_count; ++i) { auto p = get_payload(); p.SlotNr_u8 = i; p.StartBlockPercent_u8 = 20 + 10*i; p.EndBlockPercent_u8 = p.StartBlockPercent_u8+i+1; auto hidden_volume_password = std::string("123123123")+std::to_string(i); strcpyT(p.HiddenVolumePassword_au8, hidden_volume_password.c_str()); stick20::SetupHiddenVolume::CommandTransaction::run(stick, p); this_thread::sleep_for(2000ms); } for (int i = 0; i < volume_count; ++i) { execute_password_command(stick, user_pin); auto hidden_volume_password = std::string("123123123")+std::to_string(i); execute_password_command(stick, hidden_volume_password.c_str()); this_thread::sleep_for(2000ms); } } //in case of a bug this could change update PIN to some unexpected value // - please save log with packet dump if this test will not pass TEST_CASE("update password change", "[dangerous]") { SKIP_TEST(); auto stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); auto pass1 = default_admin_pin; auto pass2 = "12345678901234567890"; auto data = { make_pair(pass1, pass2), make_pair(pass2, pass1), }; for (auto && password: data) { auto p = get_payload(); strcpyT(p.current_update_password, password.first); strcpyT(p.new_update_password, password.second); stick20::ChangeUpdatePassword::CommandTransaction::run(stick, p); } } TEST_CASE("general test", "[test]") { auto stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); stick10::LockDevice::CommandTransaction::run(stick); // execute_password_command(stick, "123456"); // execute_password_command(stick, "123456"); // execute_password_command(stick, "123123123"); execute_password_command(stick, default_user_pin); execute_password_command(stick, default_user_pin); execute_password_command(stick, default_admin_pin, 'A'); stick20::GetDeviceStatus::CommandTransaction::run(stick); this_thread::sleep_for(1000ms); // execute_password_command(stick, "123123123"); //CAUTION // execute_password_command(stick, "123123123"); //CAUTION FIRMWARE PIN execute_password_command(stick, "12345678", 'A'); // execute_password_command(stick, "12345678", 'A'); stick10::LockDevice::CommandTransaction::run(stick); } libnitrokey-3.7/unittest/test3.cc000066400000000000000000000165501423223421400171520ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ static const char *const default_admin_pin = "12345678"; static const char *const default_user_pin = "123456"; const char * temporary_password = "123456789012345678901234"; const char * RFC_SECRET = "12345678901234567890"; #include "catch2/catch.hpp" #include #include #include #include "device_proto.h" #include "log.h" #include "stick10_commands_0.8.h" //#include "stick20_commands.h" using namespace std; using namespace nitrokey::device; using namespace nitrokey::proto; using namespace nitrokey::proto::stick10_08; using namespace nitrokey::log; using namespace nitrokey::misc; using Dev = Stick10; using Dev10 = std::shared_ptr; void connect_and_setup(Dev10 stick) { bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); } void authorize(Dev10 stick) { auto authreq = get_payload(); strcpy((char *) (authreq.card_password), default_admin_pin); strcpy((char *) (authreq.temporary_password), temporary_password); FirstAuthenticate::CommandTransaction::run(stick, authreq); auto user_auth = get_payload(); strcpyT(user_auth.temporary_password, temporary_password); strcpyT(user_auth.card_password, default_user_pin); UserAuthenticate::CommandTransaction::run(stick, user_auth); } TEST_CASE("write slot", "[pronew]"){ auto stick = make_shared(); connect_and_setup(stick); authorize(stick); auto p2 = get_payload(); strcpyT(p2.temporary_admin_password, temporary_password); p2.setTypeName(); strcpyT(p2.data, "test name aaa"); stick10_08::SendOTPData::CommandTransaction::run(stick, p2); p2 = get_payload(); strcpyT(p2.temporary_admin_password, temporary_password); strcpyT(p2.data, RFC_SECRET); p2.setTypeSecret(); stick10_08::SendOTPData::CommandTransaction::run(stick, p2); auto p = get_payload(); strcpyT(p.temporary_admin_password, temporary_password); p.use_8_digits = true; p.slot_number = 0 + 0x10; p.slot_counter_or_interval = 0; stick10_08::WriteToOTPSlot::CommandTransaction::run(stick, p); auto pc = get_payload(); pc.enable_user_password = 0; strcpyT(pc.temporary_admin_password, temporary_password); WriteGeneralConfig::CommandTransaction::run(stick, pc); auto p3 = get_payload(); p3.slot_number = 0 + 0x10; GetHOTP::CommandTransaction::run(stick, p3); } TEST_CASE("erase slot", "[pronew]"){ auto stick = make_shared(); connect_and_setup(stick); authorize(stick); auto p = get_payload(); p.enable_user_password = 0; strcpyT(p.temporary_admin_password, temporary_password); WriteGeneralConfig::CommandTransaction::run(stick, p); auto p3 = get_payload(); p3.slot_number = 0 + 0x10; GetHOTP::CommandTransaction::run(stick, p3); auto erase_payload = get_payload(); erase_payload.slot_number = 0 + 0x10; strcpyT(erase_payload.temporary_admin_password, temporary_password); EraseSlot::CommandTransaction::run(stick, erase_payload); auto p4 = get_payload(); p4.slot_number = 0 + 0x10; REQUIRE_THROWS( GetHOTP::CommandTransaction::run(stick, p4) ); } TEST_CASE("write general config", "[pronew]") { auto stick = make_shared(); connect_and_setup(stick); authorize(stick); auto p = get_payload(); p.enable_user_password = 1; REQUIRE_THROWS( WriteGeneralConfig::CommandTransaction::run(stick, p) ); strcpyT(p.temporary_admin_password, temporary_password); WriteGeneralConfig::CommandTransaction::run(stick, p); } TEST_CASE("authorize user HOTP", "[pronew]") { auto stick = make_shared(); connect_and_setup(stick); authorize(stick); { auto p = get_payload(); p.enable_user_password = 1; strcpyT(p.temporary_admin_password, temporary_password); WriteGeneralConfig::CommandTransaction::run(stick, p); } auto p2 = get_payload(); strcpyT(p2.temporary_admin_password, temporary_password); p2.setTypeName(); strcpyT(p2.data, "test name aaa"); stick10_08::SendOTPData::CommandTransaction::run(stick, p2); p2 = get_payload(); strcpyT(p2.temporary_admin_password, temporary_password); strcpyT(p2.data, RFC_SECRET); p2.setTypeSecret(); stick10_08::SendOTPData::CommandTransaction::run(stick, p2); auto p = get_payload(); strcpyT(p.temporary_admin_password, temporary_password); p.use_8_digits = true; p.slot_number = 0 + 0x10; p.slot_counter_or_interval = 0; stick10_08::WriteToOTPSlot::CommandTransaction::run(stick, p); auto p3 = get_payload(); p3.slot_number = 0 + 0x10; REQUIRE_THROWS( GetHOTP::CommandTransaction::run(stick, p3) ); strcpyT(p3.temporary_user_password, temporary_password); auto code_response = GetHOTP::CommandTransaction::run(stick, p3); REQUIRE(code_response.data().code == 84755224); } TEST_CASE("check firmware version", "[pronew]") { auto stick = make_shared(); connect_and_setup(stick); auto p = GetStatus::CommandTransaction::run(stick); REQUIRE(p.data().firmware_version == 8); } TEST_CASE("authorize user TOTP", "[pronew]") { auto stick = make_shared(); connect_and_setup(stick); authorize(stick); { auto p = get_payload(); p.enable_user_password = 1; strcpyT(p.temporary_admin_password, temporary_password); WriteGeneralConfig::CommandTransaction::run(stick, p); } auto p2 = get_payload(); strcpyT(p2.temporary_admin_password, temporary_password); p2.setTypeName(); strcpyT(p2.data, "test name TOTP"); stick10_08::SendOTPData::CommandTransaction::run(stick, p2); p2 = get_payload(); strcpyT(p2.temporary_admin_password, temporary_password); strcpyT(p2.data, RFC_SECRET); p2.setTypeSecret(); stick10_08::SendOTPData::CommandTransaction::run(stick, p2); auto p = get_payload(); strcpyT(p.temporary_admin_password, temporary_password); p.use_8_digits = true; p.slot_number = 0 + 0x20; p.slot_counter_or_interval = 30; stick10_08::WriteToOTPSlot::CommandTransaction::run(stick, p); auto p_get_totp = get_payload(); p_get_totp.slot_number = 0 + 0x20; REQUIRE_THROWS( GetTOTP::CommandTransaction::run(stick, p_get_totp) ); strcpyT(p_get_totp.temporary_user_password, temporary_password); auto p_set_time = get_payload(); p_set_time.reset = 1; p_set_time.time = 59; SetTime::CommandTransaction::run(stick, p_set_time); auto code = GetTOTP::CommandTransaction::run(stick, p_get_totp); REQUIRE(code.data().code == 94287082); } libnitrokey-3.7/unittest/test_C_API.cpp000066400000000000000000000053151423223421400202140ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ static const int TOO_LONG_STRING = 200; #include "catch2/catch.hpp" #include #include #include "log.h" #include "../NK_C_API.h" int login; TEST_CASE("C API connect", "[BASIC]") { login = NK_login_auto(); REQUIRE(login != 0); NK_logout(); login = NK_login_auto(); REQUIRE(login != 0); NK_logout(); login = NK_login_auto(); REQUIRE(login != 0); } TEST_CASE("Check retry count", "[BASIC]") { REQUIRE(login != 0); NK_set_debug_level(3); REQUIRE(NK_get_admin_retry_count() == 3); REQUIRE(NK_get_user_retry_count() == 3); } TEST_CASE("Check long strings", "[STANDARD]") { REQUIRE(login != 0); const char* longPin = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const char* pin = "123123123"; auto result = NK_change_user_PIN(longPin, pin); REQUIRE(result == TOO_LONG_STRING); result = NK_change_user_PIN(pin, longPin); REQUIRE(result == TOO_LONG_STRING); CAPTURE(result); } #include TEST_CASE("multiple devices with ID", "[BASIC]") { NK_logout(); NK_set_debug_level(3); auto s = NK_list_devices_by_cpuID(); REQUIRE(s!=nullptr); REQUIRE(strnlen(s, 4096) < 4096); REQUIRE(strnlen(s, 4096) > 2*4); std::cout << s << std::endl; char *string, *token; int t; string = strndup(s, 4096); free (static_cast(const_cast(s))); while ((token = strsep(&string, ";")) != nullptr){ if (strnlen(token, 4096) < 3) continue; std::cout << token << " connecting: "; std::cout << (t=NK_connect_with_ID(token)) << std::endl; REQUIRE(t == 1); } free (string); } TEST_CASE("Get device model", "[BASIC]") { NK_logout(); NK_device_model model = NK_get_device_model(); REQUIRE(model == NK_device_model::NK_DISCONNECTED); auto success = NK_login_auto() == 1; REQUIRE(success); model = NK_get_device_model(); REQUIRE(model != NK_device_model::NK_DISCONNECTED); REQUIRE((model == NK_PRO || model == NK_STORAGE)); NK_logout(); } libnitrokey-3.7/unittest/test_HOTP.cc000066400000000000000000000077161423223421400177250ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "catch2/catch.hpp" #include #include "device_proto.h" #include "log.h" #include "stick10_commands.h" #include #include "misc.h" using namespace std; using namespace nitrokey::device; using namespace nitrokey::proto::stick10; using namespace nitrokey::log; using namespace nitrokey::misc; void hexStringToByte(uint8_t data[], const char* hexString){ REQUIRE(strlen(hexString)%2==0); char buf[3]; buf[2] = '\0'; for(size_t i=0; i(slot_secret) ) == 0 ); } TEST_CASE("Test HOTP codes according to RFC", "[HOTP]") { std::shared_ptr stick = make_shared(); bool connected = stick->connect(); REQUIRE(connected == true); Log::instance().set_loglevel(Loglevel::DEBUG); auto resp = GetStatus::CommandTransaction::run(stick); const char * temporary_password = "123456789012345678901234"; { auto authreq = get_payload(); strcpy((char *)(authreq.card_password), "12345678"); strcpy((char *)(authreq.temporary_password), temporary_password); FirstAuthenticate::CommandTransaction::run(stick, authreq); } //test according to https://tools.ietf.org/html/rfc4226#page-32 { auto hwrite = get_payload(); hwrite.slot_number = 0x10; strcpy(reinterpret_cast(hwrite.slot_name), "rfc4226_lib"); //strcpy(reinterpret_cast(hwrite.slot_secret), ""); const char* secretHex = "3132333435363738393031323334353637383930"; hexStringToByte(hwrite.slot_secret, secretHex); //hwrite.slot_config; //TODO check various configs in separate test cases //strcpy(reinterpret_cast(hwrite.slot_token_id), ""); //strcpy(reinterpret_cast(hwrite.slot_counter), ""); //authorize writehotp first { auto auth = get_payload(); strcpy((char *)(auth.temporary_password), temporary_password); auth.crc_to_authorize = WriteToHOTPSlot::CommandTransaction::getCRC(hwrite); Authorize::CommandTransaction::run(stick, auth); } //run hotp command WriteToHOTPSlot::CommandTransaction::run(stick, hwrite); uint32_t codes[] = { 755224, 287082, 359152, 969429, 338314, 254676, 287922, 162583, 399871, 520489 }; for( auto code: codes){ auto gh = get_payload(); gh.slot_number = 0x10; auto resp = GetHOTP::CommandTransaction::run(stick, gh); REQUIRE( resp.data().code == code); } //checking slot programmed before with nitro-app /* for( auto code: codes){ GetHOTP::CommandTransaction::CommandPayload gh; gh.slot_number = 0x12; auto resp = GetHOTP::CommandTransaction::run(stick, gh); REQUIRE( resp.code == code); } */ } stick->disconnect(); } libnitrokey-3.7/unittest/test_command_ids_header.h000066400000000000000000000056011423223421400225710ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #ifndef LIBNITROKEY_TEST_COMMAND_IDS_HEADER_H_H #define LIBNITROKEY_TEST_COMMAND_IDS_HEADER_H_H #define STICK20_CMD_START_VALUE 0x20 #define STICK20_CMD_ENABLE_CRYPTED_PARI (STICK20_CMD_START_VALUE + 0) #define STICK20_CMD_DISABLE_CRYPTED_PARI (STICK20_CMD_START_VALUE + 1) #define STICK20_CMD_ENABLE_HIDDEN_CRYPTED_PARI (STICK20_CMD_START_VALUE + 2) #define STICK20_CMD_DISABLE_HIDDEN_CRYPTED_PARI (STICK20_CMD_START_VALUE + 3) #define STICK20_CMD_ENABLE_FIRMWARE_UPDATE (STICK20_CMD_START_VALUE + 4) #define STICK20_CMD_EXPORT_FIRMWARE_TO_FILE (STICK20_CMD_START_VALUE + 5) #define STICK20_CMD_GENERATE_NEW_KEYS (STICK20_CMD_START_VALUE + 6) #define STICK20_CMD_FILL_SD_CARD_WITH_RANDOM_CHARS (STICK20_CMD_START_VALUE + 7) #define STICK20_CMD_WRITE_STATUS_DATA (STICK20_CMD_START_VALUE + 8) #define STICK20_CMD_ENABLE_READONLY_UNCRYPTED_LUN (STICK20_CMD_START_VALUE + 9) #define STICK20_CMD_ENABLE_READWRITE_UNCRYPTED_LUN (STICK20_CMD_START_VALUE + 10) #define STICK20_CMD_SEND_PASSWORD_MATRIX (STICK20_CMD_START_VALUE + 11) #define STICK20_CMD_SEND_PASSWORD_MATRIX_PINDATA (STICK20_CMD_START_VALUE + 12) #define STICK20_CMD_SEND_PASSWORD_MATRIX_SETUP (STICK20_CMD_START_VALUE + 13) #define STICK20_CMD_GET_DEVICE_STATUS (STICK20_CMD_START_VALUE + 14) #define STICK20_CMD_SEND_DEVICE_STATUS (STICK20_CMD_START_VALUE + 15) #define STICK20_CMD_SEND_HIDDEN_VOLUME_PASSWORD (STICK20_CMD_START_VALUE + 16) #define STICK20_CMD_SEND_HIDDEN_VOLUME_SETUP (STICK20_CMD_START_VALUE + 17) #define STICK20_CMD_SEND_PASSWORD (STICK20_CMD_START_VALUE + 18) #define STICK20_CMD_SEND_NEW_PASSWORD (STICK20_CMD_START_VALUE + 19) #define STICK20_CMD_CLEAR_NEW_SD_CARD_FOUND (STICK20_CMD_START_VALUE + 20) #define STICK20_CMD_SEND_STARTUP (STICK20_CMD_START_VALUE + 21) #define STICK20_CMD_SEND_CLEAR_STICK_KEYS_NOT_INITIATED (STICK20_CMD_START_VALUE + 22) #define STICK20_CMD_SEND_LOCK_STICK_HARDWARE (STICK20_CMD_START_VALUE + 23) #define STICK20_CMD_PRODUCTION_TEST (STICK20_CMD_START_VALUE + 24) #define STICK20_CMD_SEND_DEBUG_DATA (STICK20_CMD_START_VALUE + 25) #define STICK20_CMD_CHANGE_UPDATE_PIN (STICK20_CMD_START_VALUE + 26) #endif //LIBNITROKEY_TEST_COMMAND_IDS_HEADER_H_H libnitrokey-3.7/unittest/test_issues.cc000066400000000000000000000052051423223421400204550ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ const char * const default_admin_pin = "12345678"; const char * const default_user_pin = "123456"; const char * const temporary_password = "123456789012345678901234"; const char * const RFC_SECRET = "12345678901234567890"; const char * const hidden_volume_pass = "123456789012345"; #include "catch2/catch.hpp" #include using namespace std; using namespace nitrokey; bool test_36(){ auto i = NitrokeyManager::instance(); i->set_loglevel(3); REQUIRE(i->connect()); for (int j = 0; j < 200; ++j) { i->get_status(); i->get_status_storage_as_string(); INFO( "Iteration: " << j); } return true; } bool test_31(){ auto i = NitrokeyManager::instance(); i->set_loglevel(3); REQUIRE(i->connect()); // i->unlock_encrypted_volume(default_user_pin); // i->create_hidden_volume(0, 70, 80, hidden_volume_pass); // i->lock_device(); try{ i->get_password_safe_slot_status(); } catch (...){ //pass } i->get_status_storage(); i->get_admin_retry_count(); i->get_status_storage(); i->get_user_retry_count(); i->unlock_encrypted_volume(default_user_pin); i->get_status_storage(); i->get_password_safe_slot_status(); i->get_status_storage(); i->get_user_retry_count(); i->get_password_safe_slot_status(); i->get_status(); i->get_status_storage(); i->get_admin_retry_count(); i->get_status(); i->get_user_retry_count(); i->unlock_hidden_volume(hidden_volume_pass); i->get_status_storage(); i->get_password_safe_slot_status(); return true; } TEST_CASE("issue 31", "[issue]"){ { auto i = NitrokeyManager::instance(); i->set_loglevel(4); REQUIRE(i->connect()); i->unlock_encrypted_volume(default_user_pin); i->create_hidden_volume(0, 70, 80, hidden_volume_pass); i->lock_device(); } for(int i=0; i<20; i++){ REQUIRE(test_31()); } } TEST_CASE("issue 36", "[issue]"){ REQUIRE(test_36()); } libnitrokey-3.7/unittest/test_issues.py000066400000000000000000000075551423223421400205320ustar00rootroot00000000000000from enum import Enum import pytest from conftest import skip_if_device_version_lower_than from constants import DefaultPasswords, DeviceErrorCode from misc import gs, ffi from test_pro import check_HOTP_RFC_codes, test_random def test_destroy_encrypted_data_leaves_OTP_intact(C): """ Make sure AES key regeneration will not remove OTP records. Test for Nitrokey Storage. Details: https://github.com/Nitrokey/libnitrokey/issues/199 """ skip_if_device_version_lower_than({'S': 55}) assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK # write password safe slot assert C.NK_write_password_safe_slot(0, b'slotname1', b'login1', b'pass1') == DeviceErrorCode.STATUS_OK # read slot assert gs(C.NK_get_password_safe_slot_name(0)) == b'slotname1' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK slot_login = C.NK_get_password_safe_slot_login(0) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert gs(slot_login) == b'login1' # write OTP use_8_digits = False use_pin_protection = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK check_HOTP_RFC_codes(C, lambda x: gs(C.NK_get_hotp_code(x)), use_8_digits=use_8_digits) # confirm OTP assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_hotp_slot_name(1)) == b'python_test' # destroy password safe by regenerating aes key assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_password_safe_slot_name(0)) != b'slotname1' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK # confirm OTP assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_hotp_slot_name(1)) == b'python_test' class Modes(Enum): EmptyBody = 0 FactoryResetWithAES = 1 FactoryReset = 2 AESGeneration = 3 @pytest.mark.firmware @pytest.mark.factory_reset @pytest.mark.parametrize("mode", map(Modes, reversed(range(4)))) def test_pro_factory_reset_breaks_update_password(C, mode: Modes): from test_pro_bootloader import test_bootloader_password_change_pro, test_bootloader_password_change_pro_length from test_pro import test_factory_reset skip_if_device_version_lower_than({'P': 14}) func = { Modes.EmptyBody: lambda: True, Modes.FactoryResetWithAES: lambda: test_factory_reset(C) or True, Modes.FactoryReset: lambda: C.NK_factory_reset(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK, Modes.AESGeneration: lambda: C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK, } def boot_test(C): test_bootloader_password_change_pro(C) # test_bootloader_password_change_pro_length(C) def random(C): data = ffi.new('struct GetRandom_t *') req_count = 50 res = C.NK_get_random(req_count, data) assert res == DeviceErrorCode.STATUS_OK assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert data.op_success == 1 assert data.size_effective == req_count random(C) boot_test(C) random(C) func[mode]() random(C) # fails here boot_test(C) random(C) libnitrokey-3.7/unittest/test_library.py000066400000000000000000000112211423223421400206440ustar00rootroot00000000000000""" 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 . SPDX-License-Identifier: LGPL-3.0 """ import pytest from misc import ffi, gs, to_hex, is_pro_rtm_07, is_long_OTP_secret_handled from constants import DefaultPasswords, DeviceErrorCode, RFC_SECRET, LibraryErrors, bbRFC_SECRET def test_too_long_strings(C): new_password = b'123123123' long_string = b'a' * 100 assert C.NK_change_user_PIN(long_string, new_password) == LibraryErrors.TOO_LONG_STRING assert C.NK_change_user_PIN(new_password, long_string) == LibraryErrors.TOO_LONG_STRING assert C.NK_change_admin_PIN(long_string, new_password) == LibraryErrors.TOO_LONG_STRING assert C.NK_change_admin_PIN(new_password, long_string) == LibraryErrors.TOO_LONG_STRING assert C.NK_first_authenticate(long_string, DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TOO_LONG_STRING assert C.NK_erase_totp_slot(0, long_string) == LibraryErrors.TOO_LONG_STRING digits = False assert C.NK_write_hotp_slot(1, long_string, bbRFC_SECRET, 0, digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TOO_LONG_STRING assert C.NK_write_hotp_slot(1, b'long_test', bbRFC_SECRET, 0, digits, False, False, b"", long_string) == LibraryErrors.TOO_LONG_STRING assert gs(C.NK_get_hotp_code_PIN(0, long_string)) == b"" assert C.NK_get_last_command_status() == LibraryErrors.TOO_LONG_STRING assert C.NK_change_firmware_password_pro(long_string, long_string) == LibraryErrors.TOO_LONG_STRING assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, long_string) == LibraryErrors.TOO_LONG_STRING def test_invalid_slot(C): invalid_slot = 255 assert C.NK_erase_totp_slot(invalid_slot, b'some password') == LibraryErrors.INVALID_SLOT assert C.NK_write_hotp_slot(invalid_slot, b'long_test', bbRFC_SECRET, 0, False, False, False, b"", b'aaa') == LibraryErrors.INVALID_SLOT assert gs(C.NK_get_hotp_code_PIN(invalid_slot, b'some password')) == b"" assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT assert C.NK_erase_password_safe_slot(invalid_slot) == LibraryErrors.INVALID_SLOT assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_password_safe_slot_name(invalid_slot)) == b'' assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT assert gs(C.NK_get_password_safe_slot_login(invalid_slot)) == b'' assert C.NK_get_last_command_status() == LibraryErrors.INVALID_SLOT @pytest.mark.parametrize("invalid_hex_string", ['text', '00 ', '0xff', 'zzzzzzzzzzzz', 'fff', 'f' * 257, 'f' * 258]) def test_invalid_secret_hex_string_for_OTP_write(C, invalid_hex_string): """ Tests for invalid secret hex string during writing to OTP slot. Invalid strings are not hexadecimal number, empty or longer than 255 characters. """ invalid_hex_string = invalid_hex_string.encode('ascii') assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(1, b'slot_name', invalid_hex_string, 0, True, False, False, b'', DefaultPasswords.ADMIN_TEMP) == LibraryErrors.INVALID_HEX_STRING assert C.NK_write_totp_slot(1, b'python_test', invalid_hex_string, 30, True, False, False, b"", DefaultPasswords.ADMIN_TEMP) == LibraryErrors.INVALID_HEX_STRING def test_warning_binary_bigger_than_secret_buffer(C): invalid_hex_string = to_hex('1234567890') * 3 invalid_hex_string = invalid_hex_string.encode('ascii') if is_long_OTP_secret_handled(C): invalid_hex_string *= 2 assert C.NK_write_hotp_slot(1, b'slot_name', invalid_hex_string, 0, True, False, False, b'', DefaultPasswords.ADMIN_TEMP) == LibraryErrors.TARGET_BUFFER_SIZE_SMALLER_THAN_SOURCE @pytest.mark.skip(reason='Experimental') def test_clear(C): d = 'asdasdasd' print(d) C.clear_password(d) print(d)libnitrokey-3.7/unittest/test_memory.c000066400000000000000000000031661423223421400203130ustar00rootroot00000000000000/* * Copyright (c) 2020 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include #include "../NK_C_API.h" // This test should be run with valgrind to make sure that there are no // memory leaks in the tested functions: // valgrind ./test_memory int main() { int result = NK_login_auto(); if (result != 1) return 1; int retry_count = NK_get_admin_retry_count(); if (retry_count != 3) return 1; retry_count = NK_get_user_retry_count(); if (retry_count != 3) return 1; enum NK_device_model model = NK_get_device_model(); if (model != NK_PRO && model != NK_STORAGE) return 1; uint8_t *config = NK_read_config(); if (config == NULL) return 1; NK_free_config(config); result = NK_enable_password_safe("123456"); if (result != 0) return 1; uint8_t *slot_status = NK_get_password_safe_slot_status(); if (slot_status == NULL) { return 1; } NK_free_password_safe_slot_status(slot_status); NK_logout(); return 0; } libnitrokey-3.7/unittest/test_minimal.c000066400000000000000000000016731423223421400204320ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "../NK_C_API.h" // This test is only intended to make sure that the C API header can be // compiled by a C compiler. (All other tests are written in C++.) int main() { return 0; } libnitrokey-3.7/unittest/test_multiple.py000066400000000000000000000056701423223421400210460ustar00rootroot00000000000000""" Copyright (c) 2017-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 . SPDX-License-Identifier: LGPL-3.0 """ import pprint from time import sleep import pytest from collections import defaultdict from tqdm import tqdm from conftest import skip_if_device_version_lower_than from constants import DefaultPasswords, DeviceErrorCode from misc import gs, wait, ffi, bb pprint = pprint.PrettyPrinter(indent=4).pprint @pytest.mark.other @pytest.mark.info def test_list_devices(C): infos = C.NK_list_devices() assert infos != ffi.NULL C.NK_free_device_info(infos) @pytest.mark.other @pytest.mark.info def test_connect_with_path(C): ids = gs(C.NK_list_devices_by_cpuID()) # NK_list_devices_by_cpuID already opened the devices, so we have to close # them before trying to reconnect assert C.NK_logout() == 0 devices_list = ids.split(b';') for value in devices_list: parts = value.split(b'_p_') assert len(parts) < 3 if len(parts) == 2: path = parts[1] else: path = parts[0] assert C.NK_connect_with_path(path) == 1 @pytest.mark.other @pytest.mark.info def test_get_status_storage_multiple(C): ids = gs(C.NK_list_devices_by_cpuID()) print(ids) devices_list = ids.split(b';') # # for s in devices_list: # res = C.NK_connect_with_ID(s) # assert res == 1 # # st = gs(C.NK_get_status_storage_as_string()) # # print(len(st)) # C.NK_lock_device() # for s in devices_list: res = C.NK_connect_with_ID(s) assert res == 1 v = C.NK_fill_SD_card_with_random_data(b'12345678') # print(v) devices_count = len(devices_list) assert devices_count != 0 b = 0 last_b = 0 with tqdm(total=devices_count*100) as pbar: while b/devices_count < 100: pbar.update(b - last_b) b = defaultdict (lambda: 0) ids = gs(C.NK_list_devices_by_cpuID()) devices_list = ids.split(b';') devices_count = len(devices_list) for s in devices_list: res = C.NK_connect_with_ID(s) if res != 1: continue b[s] += C.NK_get_progress_bar_value() print(b) b = sum(b.values()) print('{}: {}'.format(b, int(b/devices_count) * '=')) sleep(5) libnitrokey-3.7/unittest/test_multiple_devices.cc000066400000000000000000000172151423223421400225030ustar00rootroot00000000000000/* * Copyright (c) 2017-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 . * * SPDX-License-Identifier: LGPL-3.0 */ static const char *const default_admin_pin = "12345678"; static const char *const default_user_pin = "123456"; const char * temporary_password = "123456789012345678901234"; const char * RFC_SECRET = "12345678901234567890"; #include "catch2/catch.hpp" #include #include #include #include "../NK_C_API.h" using namespace nitrokey; TEST_CASE("List devices", "[BASIC]") { auto v = Device::enumerate(); REQUIRE(v.size() > 0); for (auto i : v){ auto d = Device::create(i.m_deviceModel); if (!d) { std::cout << "Could not create device with model " << i.m_deviceModel << "\n"; continue; } std::cout << i.m_deviceModel << " " << i.m_path << " " << i.m_serialNumber << " |"; d->set_path(i.m_path); d->connect(); auto res = GetStatus::CommandTransaction::run(d); std::cout << " " << res.data().card_serial_u32 << " " << res.data().get_card_serial_hex() << std::endl; d->disconnect(); } } TEST_CASE("List Storage devices", "[BASIC]") { shared_ptr d = make_shared(); auto v = Device::enumerate(); REQUIRE(v.size() > 0); for (auto i : v){ if (i.m_deviceModel != DeviceModel::STORAGE) continue; auto a = i.m_path; std::cout << a; d->set_path(a); d->connect(); auto res = GetStatus::CommandTransaction::run(d); auto res2 = GetDeviceStatus::CommandTransaction::run(d); std::cout << " " << res.data().card_serial_u32 << " " << res.data().get_card_serial_hex() << " " << std::to_string(res2.data().versionInfo.minor) << std::endl; d->disconnect(); } } TEST_CASE("Regenerate AES keys", "[BASIC]") { shared_ptr d = make_shared(); auto v = Device::enumerate(); REQUIRE(v.size() > 0); std::vector> devices; for (auto i : v){ if (i.m_deviceModel != DeviceModel::STORAGE) continue; auto a = i.m_path; std::cout << a << endl; d = make_shared(); d->set_path(a); d->connect(); devices.push_back(d); } for (auto d : devices){ auto res2 = GetDeviceStatus::CommandTransaction::run(d); std::cout << std::to_string(res2.data().versionInfo.minor) << std::endl; // nitrokey::proto::stick20::CreateNewKeys::CommandPayload p; // p.set_defaults(); // memcpy(p.password, "12345678", 8); // auto res3 = nitrokey::proto::stick20::CreateNewKeys::CommandTransaction::run(d, p); } for (auto d : devices){ //TODO watch out for multiple hid_exit calls d->disconnect(); } } TEST_CASE("Use C API", "[BASIC]") { auto ptr = NK_list_devices(); auto first_ptr = ptr; REQUIRE(ptr != nullptr); while (ptr) { std::cout << "Connect with: " << ptr->model << " " << ptr->path << " " << ptr->serial_number << " | " << NK_connect_with_path(ptr->path) << " | "; auto status = NK_get_status_as_string(); std::cout << status << std::endl; free(status); ptr = ptr->next; } NK_free_device_info(first_ptr); } TEST_CASE("Use API", "[BASIC]") { auto nm = NitrokeyManager::instance(); nm->set_loglevel(2); auto v = nm->list_devices(); REQUIRE(v.size() > 0); for (auto i : v) { std::cout << "Connect with: " << i.m_deviceModel << " " << i.m_path << " " << i.m_serialNumber << " | " << std::boolalpha << nm->connect_with_path(i.m_path) << " |"; try { auto status = nm->get_status(); std::cout << " " << status.card_serial_u32 << " " << status.get_card_serial_hex() << std::endl; } catch (const LongOperationInProgressException &e) { std::cout << "long operation in progress on " << i.m_path << " " << std::to_string(e.progress_bar_value) << std::endl; } } } TEST_CASE("Use Storage API", "[BASIC]") { auto nm = NitrokeyManager::instance(); nm->set_loglevel(2); auto v = nm->list_devices(); REQUIRE(v.size() > 0); for (int i=0; i<10; i++){ for (auto i : v) { if (i.m_deviceModel != DeviceModel::STORAGE) continue; auto a = i.m_path; std::cout <<"Connect with: " << a << " " << std::boolalpha << nm->connect_with_path(a) << " "; try{ auto status_storage = nm->get_status_storage(); std::cout << status_storage.ActiveSmartCardID_u32 << " " << status_storage.ActiveSD_CardID_u32 << std::endl; // nm->fill_SD_card_with_random_data("12345678"); } catch (const LongOperationInProgressException &e){ std::cout << "long operation in progress on " << a << " " << std::to_string(e.progress_bar_value) << std::endl; // this_thread::sleep_for(1000ms); } } std::cout <<"Iteration: " << i << std::endl; } } TEST_CASE("Use API ID", "[BASIC]") { auto nm = NitrokeyManager::instance(); nm->set_loglevel(2); auto v = nm->list_devices_by_cpuID(); REQUIRE(v.size() > 0); //no refresh - should not reconnect to new devices // Scenario: // 1. Run test // 2. Remove one of the devices and reinsert it after a while // 3. Device should not be reconnected and test should not crash // 4. Remove all devices - test should continue for (int j = 0; j < 100; j++) { for (auto i : v) { if (!nm->connect_with_ID(i)) continue; int retry_count = 99; try { retry_count = nm->get_admin_retry_count(); std::cout << j << " " << i << " " << to_string(retry_count) << std::endl; } catch (...) { retry_count = 99; //pass } } } std::cout << "finished" << std::endl; } TEST_CASE("Use API ID refresh", "[BASIC]") { auto nm = NitrokeyManager::instance(); nm->set_loglevel(2); //refresh in each iteration - should reconnect to new devices // Scenario: // 1. Run test // 2. Remove one of the devices and reinsert it after a while // 3. Device should be reconnected for(int j=0; j<100; j++) { auto v = nm->list_devices_by_cpuID(); REQUIRE(v.size() > 0); for (auto i : v) { nm->connect_with_ID(i); int retry_count = 99; try { retry_count = nm->get_admin_retry_count(); std::cout << j <<" " << i << " " << to_string(retry_count) << std::endl; } catch (...){ retry_count = 99; //pass } } } std::cout << "finished" << std::endl; } libnitrokey-3.7/unittest/test_offline.cc000066400000000000000000000174511423223421400205720ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "catch2/catch.hpp" #include #include #include #include #include "../NK_C_API.h" using namespace nitrokey::proto; using namespace nitrokey::device; using namespace std; using namespace nitrokey; //This test suite assumes no Pro or Storage devices are connected TEST_CASE("Return false on no device connected", "[fast]") { INFO("This test case assumes no Pro or Storage devices are connected"); auto stick = make_shared(); bool connected = true; REQUIRE_NOTHROW(connected = stick->connect()); REQUIRE_FALSE(connected); auto stick_pro = make_shared(); REQUIRE_NOTHROW(connected = stick_pro->connect()); REQUIRE_FALSE(connected); auto i = NitrokeyManager::instance(); REQUIRE_NOTHROW(connected = i->connect()); REQUIRE_FALSE(connected); REQUIRE_FALSE(i->is_connected()); REQUIRE_FALSE(i->disconnect()); REQUIRE_FALSE(i->could_current_device_be_enumerated()); int C_connected = 1; REQUIRE_NOTHROW(C_connected = NK_login_auto()); REQUIRE(0 == C_connected); } TEST_CASE("Test C++ side behaviour in offline", "[fast]") { auto i = NitrokeyManager::instance(); string serial_number; REQUIRE_NOTHROW (serial_number = i->get_serial_number()); REQUIRE(serial_number.empty()); REQUIRE_THROWS_AS( i->get_serial_number_as_u32(), DeviceNotConnected ); REQUIRE_THROWS_AS( i->get_status(), DeviceNotConnected ); REQUIRE_THROWS_AS( i->get_HOTP_code(0xFF, ""), InvalidSlotException ); REQUIRE_THROWS_AS( i->get_TOTP_code(0xFF, ""), InvalidSlotException ); REQUIRE_THROWS_AS( i->erase_hotp_slot(0xFF, ""), InvalidSlotException ); REQUIRE_THROWS_AS( i->erase_totp_slot(0xFF, ""), InvalidSlotException ); REQUIRE_THROWS_AS( i->get_totp_slot_name(0xFF), InvalidSlotException ); REQUIRE_THROWS_AS( i->get_hotp_slot_name(0xFF), InvalidSlotException ); REQUIRE_THROWS_AS( i->first_authenticate("123123", "123123"), DeviceNotConnected ); REQUIRE_THROWS_AS( i->get_connected_device_model(), DeviceNotConnected ); REQUIRE_THROWS_AS( i->clear_new_sd_card_warning("123123"), DeviceNotConnected ); } TEST_CASE("Test helper function - hex_string_to_byte", "[fast]") { using namespace nitrokey::misc; std::vector v; REQUIRE_NOTHROW(v = hex_string_to_byte("00112233445566")); const uint8_t test_data[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; REQUIRE(v.size() == sizeof(test_data)); for (size_t i = 0; i < v.size(); ++i) { INFO("Position i: " << i); REQUIRE(v[i] == test_data[i]); } } #include "test_command_ids_header.h" TEST_CASE("Test device commands ids", "[fast]") { // Make sure CommandID values are in sync with firmware's header // REQUIRE(STICK20_CMD_START_VALUE == static_cast(CommandID::START_VALUE)); REQUIRE(STICK20_CMD_ENABLE_CRYPTED_PARI == static_cast(CommandID::ENABLE_CRYPTED_PARI)); REQUIRE(STICK20_CMD_DISABLE_CRYPTED_PARI == static_cast(CommandID::DISABLE_CRYPTED_PARI)); REQUIRE(STICK20_CMD_ENABLE_HIDDEN_CRYPTED_PARI == static_cast(CommandID::ENABLE_HIDDEN_CRYPTED_PARI)); REQUIRE(STICK20_CMD_DISABLE_HIDDEN_CRYPTED_PARI == static_cast(CommandID::DISABLE_HIDDEN_CRYPTED_PARI)); REQUIRE(STICK20_CMD_ENABLE_FIRMWARE_UPDATE == static_cast(CommandID::ENABLE_FIRMWARE_UPDATE)); REQUIRE(STICK20_CMD_EXPORT_FIRMWARE_TO_FILE == static_cast(CommandID::EXPORT_FIRMWARE_TO_FILE)); REQUIRE(STICK20_CMD_GENERATE_NEW_KEYS == static_cast(CommandID::GENERATE_NEW_KEYS)); REQUIRE(STICK20_CMD_FILL_SD_CARD_WITH_RANDOM_CHARS == static_cast(CommandID::FILL_SD_CARD_WITH_RANDOM_CHARS)); REQUIRE(STICK20_CMD_WRITE_STATUS_DATA == static_cast(CommandID::WRITE_STATUS_DATA)); REQUIRE(STICK20_CMD_ENABLE_READONLY_UNCRYPTED_LUN == static_cast(CommandID::ENABLE_READONLY_UNCRYPTED_LUN)); REQUIRE(STICK20_CMD_ENABLE_READWRITE_UNCRYPTED_LUN == static_cast(CommandID::ENABLE_READWRITE_UNCRYPTED_LUN)); REQUIRE(STICK20_CMD_SEND_PASSWORD_MATRIX == static_cast(CommandID::SEND_PASSWORD_MATRIX)); REQUIRE(STICK20_CMD_SEND_PASSWORD_MATRIX_PINDATA == static_cast(CommandID::SEND_PASSWORD_MATRIX_PINDATA)); REQUIRE(STICK20_CMD_SEND_PASSWORD_MATRIX_SETUP == static_cast(CommandID::SEND_PASSWORD_MATRIX_SETUP)); REQUIRE(STICK20_CMD_GET_DEVICE_STATUS == static_cast(CommandID::GET_DEVICE_STATUS)); REQUIRE(STICK20_CMD_SEND_DEVICE_STATUS == static_cast(CommandID::SEND_DEVICE_STATUS)); REQUIRE(STICK20_CMD_SEND_HIDDEN_VOLUME_PASSWORD == static_cast(CommandID::SEND_HIDDEN_VOLUME_PASSWORD)); REQUIRE(STICK20_CMD_SEND_HIDDEN_VOLUME_SETUP == static_cast(CommandID::SEND_HIDDEN_VOLUME_SETUP)); REQUIRE(STICK20_CMD_SEND_PASSWORD == static_cast(CommandID::SEND_PASSWORD)); REQUIRE(STICK20_CMD_SEND_NEW_PASSWORD == static_cast(CommandID::SEND_NEW_PASSWORD)); REQUIRE(STICK20_CMD_CLEAR_NEW_SD_CARD_FOUND == static_cast(CommandID::CLEAR_NEW_SD_CARD_FOUND)); REQUIRE(STICK20_CMD_SEND_STARTUP == static_cast(CommandID::SEND_STARTUP)); REQUIRE(STICK20_CMD_SEND_CLEAR_STICK_KEYS_NOT_INITIATED == static_cast(CommandID::SEND_CLEAR_STICK_KEYS_NOT_INITIATED)); REQUIRE(STICK20_CMD_SEND_LOCK_STICK_HARDWARE == static_cast(CommandID::SEND_LOCK_STICK_HARDWARE)); REQUIRE(STICK20_CMD_PRODUCTION_TEST == static_cast(CommandID::PRODUCTION_TEST)); REQUIRE(STICK20_CMD_SEND_DEBUG_DATA == static_cast(CommandID::SEND_DEBUG_DATA)); REQUIRE(STICK20_CMD_CHANGE_UPDATE_PIN == static_cast(CommandID::CHANGE_UPDATE_PIN)); } #include "version.h" TEST_CASE("Test version getter", "[fast]") { REQUIRE(nitrokey::get_major_library_version() >= 3u); REQUIRE(nitrokey::get_minor_library_version() >= 3u); const char *library_version = nitrokey::get_library_version(); REQUIRE(library_version != nullptr); CAPTURE(library_version); // The library version has to match the pattern returned by git describe: // v. or v.--g, where is the number // of commits since the last tag, and is the hash of the current // commit. (This assumes that all tags have the name v..). // Optional field is allowed as well. INFO("This test will fail, if the full git commit version was not collected during library build."); std::string s = library_version; std::string version("(pre-)?v[0-9]+\\.[0-9]+(\\.[0-9]+)?"); std::string git_suffix("(-[0-9]+)+-g[0-9a-z]+"); std::regex pattern(version + "(" + git_suffix + ")?"); REQUIRE(std::regex_match(s, pattern)); } TEST_CASE("Connect should not return true after the second attempt", "[fast]") { int result = 0; result = NK_login("S"); REQUIRE(result == 0); result = NK_login_auto(); REQUIRE(result == 0); result = NK_logout(); REQUIRE(result == 0); result = NK_logout(); REQUIRE(result == 0); result = NK_login("P"); REQUIRE(result == 0); result = NK_login_auto(); REQUIRE(result == 0); result = NK_logout(); REQUIRE(result == 0); } libnitrokey-3.7/unittest/test_offline.py000066400000000000000000000023111423223421400206220ustar00rootroot00000000000000""" Copyright (c) 2019 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 . SPDX-License-Identifier: LGPL-3.0 """ from misc import gs import re def test_offline(C_offline): C_offline.NK_set_debug(False) C_offline.NK_set_debug_level(4) assert C_offline.NK_get_major_library_version() == 3 assert C_offline.NK_get_minor_library_version() >= 3 assert C_offline.NK_login_auto() == 0 libnk_version = gs(C_offline.NK_get_library_version()) assert libnk_version print(libnk_version) # v3.4.1-29-g1f3d search = re.search(b'v\d\.\d(\.\d)?', libnk_version) assert search is not Nonelibnitrokey-3.7/unittest/test_pro.py000066400000000000000000001511161423223421400200100ustar00rootroot00000000000000""" Copyright (c) 2015-2019 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 . SPDX-License-Identifier: LGPL-3.0 """ import time from binascii import hexlify from math import floor import pytest from conftest import skip_if_device_version_lower_than from constants import DefaultPasswords, DeviceErrorCode, RFC_SECRET, bbRFC_SECRET, HOTP_slot_count, \ TOTP_slot_count from helpers import helper_PWS_get_slotname, helper_PWS_get_loginname, helper_PWS_get_pass from misc import ffi, gs, wait, cast_pointer_to_tuple, has_binary_counter, bb from misc import is_storage @pytest.mark.aes def test_regenerate_aes_key_2(C): test_regenerate_aes_key(C) @pytest.mark.lock_device @pytest.mark.PWS def test_enable_password_safe(C): """ All Password Safe tests depend on AES keys being initialized. They will fail otherwise. """ assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(b'wrong_password') == DeviceErrorCode.WRONG_PASSWORD assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK @pytest.mark.lock_device @pytest.mark.PWS def test_write_password_safe_slot(C): assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_write_password_safe_slot(0, b'slotname1', b'login1', b'pass1') == DeviceErrorCode.STATUS_NOT_AUTHORIZED assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_write_password_safe_slot(0, b'slotname1', b'login1', b'pass1') == DeviceErrorCode.STATUS_OK @pytest.mark.lock_device @pytest.mark.PWS @pytest.mark.slowtest def test_write_all_password_safe_slots_and_read_10_times(C): assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK PWS_slot_count = 16 for i in range(0, PWS_slot_count): iss = str(i) assert C.NK_write_password_safe_slot(i, helper_PWS_get_slotname(iss), helper_PWS_get_loginname(iss), helper_PWS_get_pass(iss)) == DeviceErrorCode.STATUS_OK for j in range(0, 10): for i in range(0, PWS_slot_count): iss = str(i) assert gs(C.NK_get_password_safe_slot_name(i)) == helper_PWS_get_slotname(iss) assert gs(C.NK_get_password_safe_slot_login(i)) == helper_PWS_get_loginname(iss) assert gs(C.NK_get_password_safe_slot_password(i)) == helper_PWS_get_pass(iss) @pytest.mark.lock_device @pytest.mark.PWS @pytest.mark.slowtest @pytest.mark.xfail(reason="This test should be run directly after test_write_all_password_safe_slots_and_read_10_times") def test_read_all_password_safe_slots_10_times(C): assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK PWS_slot_count = 16 for j in range(0, 10): for i in range(0, PWS_slot_count): iss = str(i) assert gs(C.NK_get_password_safe_slot_name(i)) == helper_PWS_get_slotname(iss) assert gs(C.NK_get_password_safe_slot_login(i)) == helper_PWS_get_loginname(iss) assert gs(C.NK_get_password_safe_slot_password(i)) == helper_PWS_get_pass(iss) @pytest.mark.lock_device @pytest.mark.PWS def test_get_password_safe_slot_name(C): assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_write_password_safe_slot(0, b'slotname1', b'login1', b'pass1') == DeviceErrorCode.STATUS_OK assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_password_safe_slot_name(0)) == b'' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_password_safe_slot_name(0)) == b'slotname1' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK @pytest.mark.PWS def test_get_password_safe_slot_login_password(C): assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_write_password_safe_slot(0, b'slotname1', b'login1', b'pass1') == DeviceErrorCode.STATUS_OK slot_login = C.NK_get_password_safe_slot_login(0) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert gs(slot_login) == b'login1' slot_password = gs(C.NK_get_password_safe_slot_password(0)) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert slot_password == b'pass1' @pytest.mark.PWS def test_erase_password_safe_slot(C): assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_erase_password_safe_slot(0) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_password_safe_slot_name(0)) == b'' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK # TODO CHECK shouldn't this be DeviceErrorCode.NOT_PROGRAMMED ? @pytest.mark.PWS def test_password_safe_slot_status(C): assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_erase_password_safe_slot(0) == DeviceErrorCode.STATUS_OK assert C.NK_write_password_safe_slot(1, b'slotname2', b'login2', b'pass2') == DeviceErrorCode.STATUS_OK safe_slot_status = C.NK_get_password_safe_slot_status() assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK is_slot_programmed = list(ffi.cast("uint8_t [16]", safe_slot_status)[0:16]) print((is_slot_programmed, len(is_slot_programmed))) assert is_slot_programmed[0] == 0 assert is_slot_programmed[1] == 1 @pytest.mark.aes def test_issue_device_locks_on_second_key_generation_in_sequence(C): # if is_pro_rtm_07(C) or is_pro_rtm_08(C): pytest.skip("issue to register: device locks up " "after below commands sequence (reinsertion fixes), skipping for now") assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.aes def test_regenerate_aes_key(C): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK @pytest.mark.lock_device @pytest.mark.aes @pytest.mark.factory_reset def test_enable_password_safe_after_factory_reset(C): assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK if is_storage(C): # for some reason storage likes to be authenticated before reset (to investigate) assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_factory_reset(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK wait(10) if is_storage(C): assert C.NK_clear_new_sd_card_warning(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK enable_password_safe_result = C.NK_enable_password_safe(DefaultPasswords.USER) pro_case = enable_password_safe_result in [DeviceErrorCode.STATUS_AES_DEC_FAILED, DeviceErrorCode.STATUS_AES_CREATE_KEY_FAILED] # STATUS_AES_CREATE_KEY_FAILED since v0.14 storage_case = enable_password_safe_result in [DeviceErrorCode.WRONG_PASSWORD, DeviceErrorCode.STATUS_UNKNOWN_ERROR] # UNKNOWN_ERROR since v0.51 assert not is_storage(C) and pro_case \ or is_storage(C) and storage_case C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK @pytest.mark.lock_device @pytest.mark.aes @pytest.mark.xfail(reason="NK Pro firmware bug: regenerating AES key command not always results in cleared slot data") def test_destroy_password_safe(C): """ Sometimes fails on NK Pro - slot name is not cleared ergo key generation has not succeed despite the success result returned from the device """ assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK # write password safe slot assert C.NK_write_password_safe_slot(0, b'slotname1', b'login1', b'pass1') == DeviceErrorCode.STATUS_OK # read slot assert gs(C.NK_get_password_safe_slot_name(0)) == b'slotname1' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK slot_login = C.NK_get_password_safe_slot_login(0) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert gs(slot_login) == b'login1' # destroy password safe by regenerating aes key assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_password_safe_slot_name(0)) != b'slotname1' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK # check was slot status cleared safe_slot_status = C.NK_get_password_safe_slot_status() assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK is_slot_programmed = list(ffi.cast("uint8_t [16]", safe_slot_status)[0:16]) assert is_slot_programmed[0] == 0 @pytest.mark.aes def test_is_AES_supported(C): if is_storage(C): pytest.skip("Storage does not implement this command") assert C.NK_is_AES_supported(b'wrong password') != 1 assert C.NK_get_last_command_status() == DeviceErrorCode.WRONG_PASSWORD assert C.NK_is_AES_supported(DefaultPasswords.USER) == 1 assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK @pytest.mark.pin def test_admin_PIN_change(C): new_password = b'123123123' assert C.NK_change_admin_PIN(b'wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_change_admin_PIN(DefaultPasswords.ADMIN, new_password) == DeviceErrorCode.STATUS_OK assert C.NK_change_admin_PIN(new_password, DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.pin def test_user_PIN_change(C): new_password = b'123123123' assert C.NK_change_user_PIN(b'wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_change_user_PIN(DefaultPasswords.USER, new_password) == DeviceErrorCode.STATUS_OK assert C.NK_change_user_PIN(new_password, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK @pytest.mark.lock_device @pytest.mark.pin def test_admin_retry_counts(C): default_admin_retry_count = 3 assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_get_admin_retry_count() == default_admin_retry_count assert C.NK_change_admin_PIN(b'wrong_password', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_get_admin_retry_count() == default_admin_retry_count - 1 assert C.NK_change_admin_PIN(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_get_admin_retry_count() == default_admin_retry_count @pytest.mark.lock_device @pytest.mark.pin def test_user_retry_counts_change_PIN(C): # TODO can get device with AES key not set, and fail because of that - generate the key or reorder tests assert C.NK_change_user_PIN(DefaultPasswords.USER, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK wrong_password = b'wrong_password' default_user_retry_count = 3 assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_get_user_retry_count() == default_user_retry_count assert C.NK_change_user_PIN(wrong_password, wrong_password) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_get_user_retry_count() == default_user_retry_count - 1 assert C.NK_change_user_PIN(DefaultPasswords.USER, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_get_user_retry_count() == default_user_retry_count @pytest.mark.lock_device @pytest.mark.pin def test_user_retry_counts_PWSafe(C): default_user_retry_count = 3 assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_get_user_retry_count() == default_user_retry_count assert C.NK_enable_password_safe(b'wrong_password') == DeviceErrorCode.WRONG_PASSWORD assert C.NK_get_user_retry_count() == default_user_retry_count - 1 assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_get_user_retry_count() == default_user_retry_count @pytest.mark.pin def test_unlock_user_password(C): default_user_retry_count = 3 default_admin_retry_count = 3 new_password = b'123123123' assert C.NK_get_user_retry_count() == default_user_retry_count assert C.NK_change_user_PIN(b'wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_change_user_PIN(b'wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_change_user_PIN(b'wrong_password', new_password) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_get_user_retry_count() == default_user_retry_count - 3 assert C.NK_get_admin_retry_count() == default_admin_retry_count assert C.NK_unlock_user_password(b'wrong password', DefaultPasswords.USER) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_get_admin_retry_count() == default_admin_retry_count - 1 assert C.NK_unlock_user_password(DefaultPasswords.ADMIN, DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_get_user_retry_count() == default_user_retry_count assert C.NK_get_admin_retry_count() == default_admin_retry_count @pytest.mark.pin def test_admin_auth(C): assert C.NK_first_authenticate(b'wrong_password', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK @pytest.mark.pin def test_user_auth(C): assert C.NK_user_authenticate(b'wrong_password', DefaultPasswords.USER_TEMP) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK @pytest.mark.otp def check_HOTP_RFC_codes(C, func, prep=None, use_8_digits=False): """ # https://tools.ietf.org/html/rfc4226#page-32 """ assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(1, b'python_test', bbRFC_SECRET, 0, use_8_digits, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK test_data = [ 1284755224, 1094287082, 137359152, 1726969429, 1640338314, 868254676, 1918287922, 82162583, 673399871, 645520489, ] for code in test_data: if prep: prep() r = func(1) code = str(code)[-8:] if use_8_digits else str(code)[-6:] assert bb(code) == r @pytest.mark.otp @pytest.mark.parametrize("use_8_digits", [False, True, ]) @pytest.mark.parametrize("use_pin_protection", [False, True, ]) def test_HOTP_RFC_use8digits_usepin(C, use_8_digits, use_pin_protection): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK if use_pin_protection: check_HOTP_RFC_codes(C, lambda x: gs(C.NK_get_hotp_code_PIN(x, DefaultPasswords.USER_TEMP)), lambda: C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP), use_8_digits=use_8_digits) else: check_HOTP_RFC_codes(C, lambda x: gs(C.NK_get_hotp_code(x)), use_8_digits=use_8_digits) @pytest.mark.otp def test_HOTP_token(C): """ Check HOTP routine with written token ID to slot. """ use_pin_protection = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK token_ID = b"AAV100000022" assert C.NK_write_hotp_slot(1, b'python_test', bbRFC_SECRET, 0, False, False, True, token_ID, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK for i in range(5): hotp_code = gs(C.NK_get_hotp_code(1)) assert hotp_code != b'' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK @pytest.mark.otp def test_HOTP_counters(C): """ # https://tools.ietf.org/html/rfc4226#page-32 """ use_pin_protection = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK use_8_digits = True HOTP_test_data = [ 1284755224, 1094287082, 137359152, 1726969429, 1640338314, 868254676, 1918287922, 82162583, 673399871, 645520489, ] slot_number = 1 for counter, code in enumerate(HOTP_test_data): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, b'python_test', bbRFC_SECRET, counter, use_8_digits, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK r = gs(C.NK_get_hotp_code(slot_number)) code = str(code)[-8:] if use_8_digits else str(code)[-6:] assert bb(code) == r INT32_MAX = 2 ** 31 - 1 @pytest.mark.otp def test_HOTP_64bit_counter(C): if not has_binary_counter(C): pytest.xfail('bug in NK Storage HOTP firmware - counter is set with a 8 digits string, ' 'however int32max takes 10 digits to be written') oath = pytest.importorskip("oath") lib_at = lambda t: bb(oath.hotp(RFC_SECRET, t, format='dec6')) PIN_protection = False use_8_digits = False slot_number = 1 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK dev_res = [] lib_res = [] for t in range(INT32_MAX - 5, INT32_MAX + 5, 1): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, b'python_test', bbRFC_SECRET, t, use_8_digits, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code_device = gs(C.NK_get_hotp_code(slot_number)) dev_res += (t, code_device) lib_res += (t, lib_at(t)) assert dev_res == lib_res def helper_set_HOTP_test_slot(C, slot_number): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK slot_name = b'HOTP_test'[:-2] + '{:02}'.format(slot_number).encode() assert C.NK_write_hotp_slot(slot_number, slot_name, bbRFC_SECRET, 0, False, False, True, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK def helper_set_TOTP_test_slot(C, slot_number): PIN_protection = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK slot_name = b'TOTP_test'[:-2] + '{:02}'.format(slot_number).encode() assert C.NK_write_totp_slot(slot_number, slot_name, bbRFC_SECRET, 30, False, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK def helper_set_time_on_device(C, t): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_totp_set_time(t) == DeviceErrorCode.STATUS_OK @pytest.mark.otp @pytest.mark.parametrize("t_values",[ range(INT32_MAX - 5, INT32_MAX + 5, 1), [2**31, 2**32, 2**33, 2**34, 2**40, 2**50, 2**60], pytest.param([2**61-1, 2**62-1, 2**63-1, 2**64-1], marks=pytest.mark.xfail), ]) def test_TOTP_64bit_time(C, t_values): if not has_binary_counter(C): pytest.xfail('bug in NK Storage TOTP firmware') oath = pytest.importorskip("oath") T = 1 slot_number = 1 lib_at = lambda t: bb(oath.totp(RFC_SECRET, t=t)) helper_set_TOTP_test_slot(C, slot_number) dev_res = [] lib_res = [] for t in t_values: helper_set_time_on_device(C, t) code_device = gs((C.NK_get_totp_code(slot_number, T, 0, 30))) dev_res += (t, code_device) lib_res += (t, lib_at(t)) assert dev_res == lib_res @pytest.mark.otp @pytest.mark.xfail(reason="NK Pro: Test fails in 50% of cases due to test vectors set 1 second before interval count change" "Here time is changed on seconds side only and miliseconds part is not being reset apparently" "This results in available time to test of half a second on average, thus 50% failed cases" "With disabled two first test vectors test passess 10/10 times" "Fail may also occurs on NK Storage with lower occurrency since it needs less time to execute " "commands") @pytest.mark.parametrize("PIN_protection", [False, True, ]) def test_TOTP_RFC_usepin(C, PIN_protection): slot_number = 1 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK # test according to https://tools.ietf.org/html/rfc6238#appendix-B assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_totp_slot(slot_number, b'python_test', bbRFC_SECRET, 30, True, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK get_func = None if PIN_protection: get_func = lambda x, y, z, r: gs(C.NK_get_totp_code_PIN(x, y, z, r, DefaultPasswords.USER_TEMP)) else: get_func = lambda x, y, z, r: gs(C.NK_get_totp_code(x, y, z, r)) # Mode: Sha1, time step X=30 test_data = [ #Time T (hex) TOTP (59, 0x1, 94287082), # Warning - test vector time 1 second before interval count changes (1111111109, 0x00000000023523EC, 7081804), # Warning - test vector time 1 second before interval count changes (1111111111, 0x00000000023523ED, 14050471), (1234567890, 0x000000000273EF07, 89005924), (2000000000, 0x0000000003F940AA, 69279037), # (20000000000, 0x0000000027BC86AA, 65353130), # 64bit is also checked in other test ] responses = [] data = [] correct = 0 for t, T, expected_code in test_data: if PIN_protection: C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_totp_set_time(t) == DeviceErrorCode.STATUS_OK code_from_device = get_func(slot_number, T, 0, 30) # FIXME T is not changing the outcome data += [ (t, bb(str(expected_code).zfill(8))) ] responses += [ (t, code_from_device) ] correct += expected_code == code_from_device assert data == responses or correct == len(test_data) @pytest.mark.otp def test_get_slot_names(C): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_erase_totp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK # erasing slot invalidates temporary password, so requesting authentication assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_erase_hotp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK for i in range(TOTP_slot_count): name = ffi.string(C.NK_get_totp_slot_name(i)) if name == '': assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED for i in range(HOTP_slot_count): name = ffi.string(C.NK_get_hotp_slot_name(i)) if name == '': assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED @pytest.mark.otp def test_get_OTP_codes(C): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK for i in range(TOTP_slot_count): code = gs(C.NK_get_totp_code(i, 0, 0, 0)) if code == b'': assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED for i in range(HOTP_slot_count): code = gs(C.NK_get_hotp_code(i)) if code == b'': assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED @pytest.mark.otp def test_get_OTP_code_from_not_programmed_slot(C): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_erase_hotp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_erase_totp_slot(0, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code = gs(C.NK_get_hotp_code(0)) assert code == b'' assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED code = gs(C.NK_get_totp_code(0, 0, 0, 0)) assert code == b'' assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED @pytest.mark.otp def test_get_code_user_authorize(C): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_totp_slot(0, b'python_otp_auth', bbRFC_SECRET, 30, True, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK # enable PIN protection of OTP codes with write_config # TODO create convinience function on C API side to enable/disable OTP USER_PIN protection assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code = gs(C.NK_get_totp_code(0, 0, 0, 0)) assert code == b'' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED # disable PIN protection with write_config assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code = gs(C.NK_get_totp_code(0, 0, 0, 0)) assert code != b'' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK def helper_get_TOTP_code(C,i): code = gs(C.NK_get_totp_code(i, 0, 0, 30)) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert code != b'' return code def helper_get_HOTP_code(C,i): code = gs(C.NK_get_hotp_code(i)) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert code != b'' return code @pytest.mark.otp def test_authorize_issue_admin(C): skip_if_device_version_lower_than({'S': 43, 'P': 9}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(b"wrong pass", b"another temp pass") == DeviceErrorCode.WRONG_PASSWORD assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_NOT_AUTHORIZED assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK @pytest.mark.otp def test_authorize_issue_user(C): skip_if_device_version_lower_than({'S': 43, 'P': 9}) # issue fixed in Pro v0.9, Storage version chosen arbitrary assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_totp_slot(0, b'python_otp_auth', bbRFC_SECRET, 30, True, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK # enable PIN protection of OTP codes with write_config assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK gs(C.NK_get_totp_code(0, 0, 0, 0)) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK gs(C.NK_get_totp_code_PIN(0, 0, 0, 0, DefaultPasswords.USER_TEMP)) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert C.NK_user_authenticate(b"wrong pass", b"another temp pass") == DeviceErrorCode.WRONG_PASSWORD gs(C.NK_get_totp_code_PIN(0, 0, 0, 0, DefaultPasswords.USER_TEMP)) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_NOT_AUTHORIZED assert C.NK_user_authenticate(DefaultPasswords.USER, DefaultPasswords.USER_TEMP) == DeviceErrorCode.STATUS_OK gs(C.NK_get_totp_code_PIN(0, 0, 0, 0, DefaultPasswords.USER_TEMP)) assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK # disable PIN protection with write_config assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code = gs(C.NK_get_totp_code(0, 0, 0, 0)) assert code != b'' assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK def cast_pointer_to_tuple(obj, typen, len): # usage: # config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) return tuple(ffi.cast("%s [%d]" % (typen, len), obj)[0:len]) def test_read_write_config(C): # let's set sample config with pin protection and disabled scrolllock assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(0, 1, 2, True, False, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK config_raw_data = C.NK_read_config() assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) assert config == (0, 1, 2, True, False) # use structs: read I config_st = ffi.new('struct NK_config *') if not config_st: raise Exception("Could not allocate config") assert C.NK_read_config_struct(config_st) == DeviceErrorCode.STATUS_OK assert config_st.numlock == 0 assert config_st.capslock == 1 assert config_st.scrolllock == 2 assert config_st.enable_user_password assert not config_st.disable_user_password # use structs: write config_st.numlock = 0xFF assert C.NK_write_config_struct(config_st[0], DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK # use structs: read II err = C.NK_read_config_struct(config_st) assert err == 0 assert config_st.numlock == 0xFF assert config_st.capslock == 1 assert config_st.scrolllock == 2 assert config_st.enable_user_password assert not config_st.disable_user_password # restore defaults and check assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK config_raw_data = C.NK_read_config() assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK config = cast_pointer_to_tuple(config_raw_data, 'uint8_t', 5) assert config == (255, 255, 255, False, True) @pytest.mark.lock_device @pytest.mark.factory_reset def test_factory_reset(C): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, False, True, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(1, b'python_test', bbRFC_SECRET, 0, False, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_hotp_code(1)) == b"755224" assert C.NK_factory_reset(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK wait(10) assert gs(C.NK_get_hotp_code(1)) != b"287082" assert C.NK_get_last_command_status() == DeviceErrorCode.NOT_PROGRAMMED # restore AES key assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_build_aes_key(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK if is_storage(C): assert C.NK_clear_new_sd_card_warning(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.status def test_get_status_as_string(C): status = C.NK_get_status_as_string() s = gs(status) assert len(s) > 0 @pytest.mark.status def test_get_status(C): status_st = ffi.new('struct NK_status *') if not status_st: raise Exception("Could not allocate status") err = C.NK_get_status(status_st) assert err == 0 assert status_st.firmware_version_major == 0 assert status_st.firmware_version_minor != 0 @pytest.mark.status def test_get_serial_number(C): sn = C.NK_device_serial_number() sn = gs(sn) assert len(sn) > 0 print(('Serial number of the device: ', sn)) @pytest.mark.status def test_get_serial_number_as_u32(C): sn = C.NK_device_serial_number_as_u32() assert sn > 0 print(('Serial number of the device (u32): ', sn)) @pytest.mark.otp @pytest.mark.parametrize("secret", ['000001', '00'*10+'ff', '00'*19+'ff', '000102', '00'*29+'ff', '00'*39+'ff', '002EF43F51AFA97BA2B46418768123C9E1809A5B' ]) def test_OTP_secret_started_from_null(C, secret): """ NK Pro 0.8+, NK Storage 0.43+ """ skip_if_device_version_lower_than({'S': 43, 'P': 8}) if len(secret) > 40: # feature: 320 bit long secret handling skip_if_device_version_lower_than({'P': 8, 'S': 54}) oath = pytest.importorskip("oath") lib_at = lambda t: bb(oath.hotp(secret, t, format='dec6')) PIN_protection = False use_8_digits = False slot_number = 1 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK dev_res = [] lib_res = [] for t in range(1,5): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, b'null_secret', bb(secret), t, use_8_digits, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code_device = gs(C.NK_get_hotp_code(slot_number)) dev_res += (t, code_device) lib_res += (t, lib_at(t)) assert dev_res == lib_res @pytest.mark.otp @pytest.mark.parametrize("counter", [0, 3, 7, 0xffff, 0xffffffff, 0xffffffffffffffff] ) def test_HOTP_slots_read_write_counter(C, counter): """ Write different counters to all HOTP slots, read code and compare with 3rd party :param counter: """ if counter >= 1e7: # Storage v0.53 and below does not handle counters longer than 7 digits skip_if_device_version_lower_than({'P': 7, 'S': 54}) secret = RFC_SECRET oath = pytest.importorskip("oath") lib_at = lambda t: bb(oath.hotp(secret, t, format='dec6')) PIN_protection = False use_8_digits = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK dev_res = [] lib_res = [] for slot_number in range(HOTP_slot_count): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, b'HOTP rw' + bytes(slot_number), bb(secret), counter, use_8_digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code_device = gs(C.NK_get_hotp_code(slot_number)) dev_res += (counter, code_device) lib_res += (counter, lib_at(counter)) assert dev_res == lib_res @pytest.mark.otp @pytest.mark.parametrize("period", [30,60] ) @pytest.mark.parametrize("time", range(21,70,20) ) def test_TOTP_slots_read_write_at_time_period(C, time, period): """ Write to all TOTP slots with specified period, read code at specified time and compare with 3rd party """ secret = RFC_SECRET oath = pytest.importorskip("oath") lib_at = lambda t: bb(oath.totp(RFC_SECRET, t=t, period=period)) PIN_protection = False use_8_digits = False T = 0 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK dev_res = [] lib_res = [] for slot_number in range(TOTP_slot_count): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_totp_slot(slot_number, b'TOTP rw' + bytes(slot_number), bb(secret), period, use_8_digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_totp_set_time(time) == DeviceErrorCode.STATUS_OK code_device = gs(C.NK_get_totp_code(slot_number, T, 0, period)) dev_res += (time, code_device) lib_res += (time, lib_at(time)) assert dev_res == lib_res @pytest.mark.otp @pytest.mark.parametrize("secret", [RFC_SECRET, 2*RFC_SECRET, '12'*10, '12'*30] ) def test_TOTP_secrets(C, secret): ''' NK Pro 0.8+, NK Storage 0.44+ ''' skip_if_device_version_lower_than({'S': 44, 'P': 8}) if len(secret)>20*2: #*2 since secret is in hex # pytest.skip("Secret lengths over 20 bytes are not supported by NK Pro 0.7 and NK Storage v0.53 and older") skip_if_device_version_lower_than({'P': 8, 'S': 54}) slot_number = 0 time = 0 period = 30 oath = pytest.importorskip("oath") lib_at = lambda t: bb(oath.totp(secret, t=t, period=period)) PIN_protection = False use_8_digits = False T = 0 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK dev_res = [] lib_res = [] assert C.NK_write_totp_slot(slot_number, b'secret' + bytes(len(secret)), bb(secret), period, use_8_digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_totp_set_time(time) == DeviceErrorCode.STATUS_OK code_device = gs(C.NK_get_totp_code(slot_number, T, 0, period)) dev_res += (time, code_device) lib_res += (time, lib_at(time)) assert dev_res == lib_res @pytest.mark.otp @pytest.mark.parametrize("secret", [RFC_SECRET, 2*RFC_SECRET, '12'*10, '12'*30] ) def test_HOTP_secrets(C, secret): """ NK Pro 0.8+ feature needed: support for 320bit secrets """ if len(secret)>40: skip_if_device_version_lower_than({'P': 8, 'S': 54}) slot_number = 0 counter = 0 oath = pytest.importorskip("oath") lib_at = lambda t: bb(oath.hotp(secret, counter=t)) PIN_protection = False use_8_digits = False T = 0 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK dev_res = [] lib_res = [] # repeat authentication for Pro 0.7 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, b'secret' + bytes(len(secret)), bb(secret), counter, use_8_digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code_device = gs(C.NK_get_hotp_code(slot_number)) dev_res += (counter, code_device) lib_res += (counter, lib_at(counter)) assert dev_res == lib_res def test_special_double_press(C): """ requires manual check after function run double press each of num-, scroll-, caps-lock and check inserted OTP codes (each 1st should be 755224) on nkpro 0.7 scrolllock should do nothing, on nkpro 0.8+ should return OTP code """ secret = RFC_SECRET counter = 0 PIN_protection = False use_8_digits = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(0, 1, 2, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK for slot_number in range(3): assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, b'double' + bytes(slot_number), bb(secret), counter, use_8_digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK # requires manual check @pytest.mark.otp def test_edit_OTP_slot(C): """ should change slots counter and name without changing its secret (using null secret for second update) """ # counter is not getting updated under Storage v0.43 - #TOREPORT skip_if_device_version_lower_than({'S': 44, 'P': 7}) secret = RFC_SECRET counter = 0 PIN_protection = False use_8_digits = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK slot_number = 0 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK first_name = b'edit slot' assert C.NK_write_hotp_slot(slot_number, first_name, bb(secret), counter, use_8_digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert gs(C.NK_get_hotp_slot_name(slot_number)) == first_name first_code = gs(C.NK_get_hotp_code(slot_number)) changed_name = b'changedname' empty_secret = b'' assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, changed_name, empty_secret, counter, use_8_digits, False, False, b"", DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK second_code = gs(C.NK_get_hotp_code(slot_number)) assert first_code == second_code assert gs(C.NK_get_hotp_slot_name(slot_number)) == changed_name @pytest.mark.otp @pytest.mark.skip @pytest.mark.parametrize("secret", ['31323334353637383930'*2,'31323334353637383930'*4] ) def test_TOTP_codes_from_nitrokeyapp(secret, C): """ Helper test for manual TOTP check of written secret by Nitrokey App Destined to run by hand """ slot_number = 0 PIN_protection = False period = 30 assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, PIN_protection, not PIN_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK code_device = gs(C.NK_get_totp_code(slot_number, 0, 0, period)) oath = pytest.importorskip("oath") lib_at = lambda : bb(oath.totp(secret, period=period)) print (lib_at()) assert lib_at() == code_device def test_get_device_model(C): assert C.NK_get_device_model() != 0 # assert C.NK_get_device_model() != C.NK_DISCONNECTED @pytest.mark.otp @pytest.mark.parametrize('counter_mid', [10**3-1, 10**4-1, 10**7-1, 10**8-10, 2**16, 2**31-1, 2**32-1, 2**33, 2**50, 2**60, 2**63]) # 2**64-1 def test_HOTP_counter_getter(C, counter_mid: int): if len(str(counter_mid)) > 8: skip_if_device_version_lower_than({'S': 54, 'P': 7}) assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK use_pin_protection = False use_8_digits = False assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK read_slot_st = ffi.new('struct ReadSlot_t *') if not read_slot_st: raise Exception("Could not allocate status") slot_number = 1 for counter in range(counter_mid-3, counter_mid+3): # assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(slot_number, b'python_test', bbRFC_SECRET, counter, use_8_digits, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_read_HOTP_slot(slot_number, read_slot_st) == DeviceErrorCode.STATUS_OK assert read_slot_st.slot_counter == counter @pytest.mark.otp def test_edge_OTP_slots(C): # -> shows TOTP15 is not written # -> assuming HOTP1 is written # (optional) Write slot HOTP1 # Write slot TOTP15 # Wait # Read slot TOTP15 details # Read HOTP1 details # returns SLOT_NOT_PROGRAMMED # (next nkapp execution) # -> shows HOTP1 is not written # briefly writing TOTP15 clears HOTP1, and vice versa read_slot_st = ffi.new('struct ReadSlot_t *') if not read_slot_st: raise Exception("Could not allocate status") use_pin_protection = False use_8_digits = False assert C.NK_first_authenticate(DefaultPasswords.ADMIN, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_config(255, 255, 255, use_pin_protection, not use_pin_protection, DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK counter = 0 HOTP_slot_number = 1 -1 TOTP_slot_number = TOTP_slot_count -1 # 0 based assert C.NK_write_totp_slot(TOTP_slot_number, b'python_test', bbRFC_SECRET, 30, False, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_write_hotp_slot(HOTP_slot_number, b'python_test', bbRFC_SECRET, counter, use_8_digits, False, False, b'', DefaultPasswords.ADMIN_TEMP) == DeviceErrorCode.STATUS_OK for i in range(5): code_hotp = gs(C.NK_get_hotp_code(HOTP_slot_number)) assert code_hotp assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert C.NK_read_HOTP_slot(HOTP_slot_number, read_slot_st) == DeviceErrorCode.STATUS_OK assert read_slot_st.slot_counter == (i+1) helper_set_time_on_device(C, 1) code_totp = gs((C.NK_get_totp_code(TOTP_slot_number, 0, 0, 30))) assert code_totp assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK @pytest.mark.otp def test_OTP_all_rw(C): """ Write all OTP slots and read codes from them two times. All generated codes should be the same, which is checked as well. """ for i in range(TOTP_slot_count): helper_set_TOTP_test_slot(C, i) for i in range(HOTP_slot_count): helper_set_HOTP_test_slot(C, i) all_codes = [] for i in range(5): this_loop_codes = [] code_old = b'' helper_set_time_on_device(C, 30*i) for i in range(TOTP_slot_count): code = helper_get_TOTP_code(C, i) if code_old: assert code == code_old code_old = code this_loop_codes.append(('T', i, code)) code_old = b'' for i in range(HOTP_slot_count): code = helper_get_HOTP_code(C, i) if code_old: assert code == code_old code_old = code this_loop_codes.append(('H', i, code)) all_codes.append(this_loop_codes) from pprint import pprint pprint(all_codes) @pytest.mark.parametrize("count",[16, 32, 50, 51]) def test_random(C, count): skip_if_device_version_lower_than({'P': 14, 'S': 99}) data = ffi.new('struct GetRandom_t *') req_count = count res = C.NK_get_random(req_count, data) assert res == DeviceErrorCode.STATUS_OK assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert data.op_success == 1 assert data.size_effective == req_count print(f'{hexlify(bytes(data.data))}') def test_random_collect(C): skip_if_device_version_lower_than({'P': 14, 'S': 99}) collected = b'' data = ffi.new('struct GetRandom_t *') req_count = 50 tic = time.perf_counter() for i in range(1024//req_count+1): res = C.NK_get_random(req_count, data) assert res == DeviceErrorCode.STATUS_OK assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK assert data.op_success == 1 assert data.size_effective == req_count collected += bytes(data.data) toc = time.perf_counter() assert len(collected) > 1024 print(hexlify(collected)) print(f'Time used to collect {len(collected)} bytes: {round(toc-tic,2)} -> {floor(len(collected) / (toc-tic))} Bps') libnitrokey-3.7/unittest/test_pro_bootloader.py000066400000000000000000000104251423223421400222170ustar00rootroot00000000000000import pytest from conftest import skip_if_device_version_lower_than, library_device_reconnect from constants import DefaultPasswords, DeviceErrorCode, LibraryErrors from helpers import helper_populate_device, helper_check_device_for_data @pytest.mark.firmware def test_bootloader_password_change_pro_length(C): skip_if_device_version_lower_than({'P': 11}) # Test whether the correct password is set assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK # Change to the longest possible password assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_LONG) == DeviceErrorCode.STATUS_OK assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE_LONG, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK # Use longer or shorter passwords than possible assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_TOO_LONG) == LibraryErrors.TOO_LONG_STRING assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_TOO_SHORT) == DeviceErrorCode.WRONG_PASSWORD @pytest.mark.firmware def test_bootloader_password_change_pro(C): skip_if_device_version_lower_than({'P': 11}) assert C.NK_change_firmware_password_pro(b'zxcasd', b'zxcasd') == DeviceErrorCode.WRONG_PASSWORD # Revert effects of broken test run, if needed C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE_TEMP, DefaultPasswords.UPDATE) # Change to the same password assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK # Change password assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE_TEMP, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK @pytest.mark.firmware def test_bootloader_run_pro_wrong_password(C): skip_if_device_version_lower_than({'P': 11}) assert C.NK_enable_firmware_update_pro(DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.WRONG_PASSWORD @pytest.mark.skip_by_default @pytest.mark.firmware def test_bootloader_run_pro_real(C): skip_if_device_version_lower_than({'P': 11}) # Not enabled due to lack of side-effect removal at this point assert C.NK_enable_firmware_update_pro(DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_DISCONNECTED @pytest.mark.firmware def test_bootloader_password_change_pro_too_long(C): skip_if_device_version_lower_than({'P': 11}) long_string = b'a' * 100 assert C.NK_change_firmware_password_pro(long_string, long_string) == LibraryErrors.TOO_LONG_STRING assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, long_string) == LibraryErrors.TOO_LONG_STRING @pytest.mark.skip_by_default @pytest.mark.firmware def test_bootloader_data_retention(C): skip_if_device_version_lower_than({'P': 11}) # Not enabled due to lack of side-effect removal at this point assert helper_populate_device(C) assert C.NK_enable_firmware_update_pro(DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_DISCONNECTED input('Please press ENTER after uploading new firmware to the device') C = library_device_reconnect(C) assert helper_check_device_for_data(C) @pytest.mark.firmware def test_factory_reset_does_not_change_update_password(C): """ Check if factory reset changes the update password, which should not happen """ skip_if_device_version_lower_than({'P': 13}) from test_pro import test_factory_reset # Revert effects of a broken test run, if needed C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE_TEMP, DefaultPasswords.UPDATE) # actual test assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.STATUS_OK test_factory_reset(C) assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_change_firmware_password_pro(DefaultPasswords.UPDATE_TEMP, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK libnitrokey-3.7/unittest/test_safe.cpp000066400000000000000000000051441423223421400202570ustar00rootroot00000000000000/* * Copyright (c) 2019 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "catch2/catch.hpp" #include #include #include "log.h" #include "../NK_C_API.h" int login; TEST_CASE("C API connect", "[BASIC]") { INFO("This test set assumes either Pro or Storage device is connected."); INFO("Here should be implemented only tests not changing the device's state, " "and safe to user data."); login = NK_login_auto(); REQUIRE(login != 0); NK_set_debug_level(3); } TEST_CASE("Check retry count", "[BASIC]") { INFO("This test assumes your PINs' attempt counters are set to 3"); REQUIRE(login != 0); REQUIRE(NK_get_admin_retry_count() == 3); REQUIRE(NK_get_user_retry_count() == 3); } void validate_cstring(char *s){ constexpr uint16_t max_length = 8*1024; REQUIRE(s != nullptr); REQUIRE(strnlen(s, max_length) > 0); REQUIRE(strnlen(s, max_length) < max_length); std::cout << s << std::endl; } TEST_CASE("Status command for Pro or Storage", "[BASIC]") { REQUIRE(login != 0); char* s = nullptr; auto const m = NK_get_device_model(); REQUIRE(m != NK_DISCONNECTED); if (m == NK_PRO) s = NK_get_status_as_string(); else if (m == NK_STORAGE){ s = NK_get_status_storage_as_string(); } validate_cstring(s); free(s); s = nullptr; } TEST_CASE("Device serial", "[BASIC]") { REQUIRE(login != 0); char* s = nullptr; s = NK_device_serial_number(); validate_cstring(s); free(s); s = nullptr; } TEST_CASE("Firmware version", "[BASIC]") { REQUIRE(login != 0); // Currently all devices has major version '0' // No firmware ever had a minor equal to '0' REQUIRE(NK_get_major_firmware_version() == 0); REQUIRE(NK_get_minor_firmware_version() != 0); } TEST_CASE("Library version", "[BASIC]") { REQUIRE(NK_get_major_library_version() == 3); REQUIRE(NK_get_minor_library_version() >= 4); } libnitrokey-3.7/unittest/test_storage.py000066400000000000000000000650761423223421400206650ustar00rootroot00000000000000""" Copyright (c) 2015-2019 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 . SPDX-License-Identifier: LGPL-3.0 """ import dataclasses import pprint import secrets from datetime import datetime, timedelta from time import sleep import pytest from hypothesis import given, strategies as st, settings, Verbosity, assume from conftest import skip_if_device_version_lower_than from constants import DefaultPasswords, DeviceErrorCode from misc import gs, wait, ffi, bb pprint = pprint.PrettyPrinter(indent=4).pprint def get_dict_from_dissect(status): x = [] for s in status.split('\n'): try: if not ':' in s: continue ss = s.replace('\t', '').replace(' (int) ', '').split(':') if not len(ss) == 2: continue x.append(ss) except: pass d = {k.strip(): v.strip() for k, v in x} return d def get_status_storage(C): status_pointer = C.NK_get_status_storage_as_string() assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK status_string = gs(status_pointer) assert len(status_string) > 0 status_dict = get_dict_from_dissect(status_string.decode('ascii')) # assert int(status_dict['AdminPwRetryCount']) == default_admin_password_retry_count return status_dict, C.NK_get_last_command_status() @pytest.mark.other @pytest.mark.info def test_get_status_storage(C): skip_if_device_version_lower_than({'S': 43}) status_pointer = C.NK_get_status_storage_as_string() assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK status_string = gs(status_pointer) assert len(status_string) > 0 status_dict = get_dict_from_dissect(status_string.decode('ascii')) default_admin_password_retry_count = 3 assert int(status_dict['AdminPwRetryCount']) == default_admin_password_retry_count print('C.NK_get_major_firmware_version(): {}'.format(C.NK_get_major_firmware_version())) print('C.NK_get_minor_firmware_version(): {}'.format(C.NK_get_minor_firmware_version())) @pytest.mark.other @pytest.mark.info def test_sd_card_usage(C): skip_if_device_version_lower_than({'S': 43}) data_pointer = C.NK_get_SD_usage_data_as_string() assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK data_string = gs(data_pointer) assert len(data_string) > 0 data_dict = get_dict_from_dissect(data_string.decode("ascii")) assert int(data_dict['WriteLevelMax']) <= 100 @pytest.mark.encrypted def test_encrypted_volume_unlock(C): skip_if_device_version_lower_than({'S': 43}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK @pytest.mark.hidden def test_encrypted_volume_unlock_hidden(C): skip_if_device_version_lower_than({'S': 43}) hidden_volume_password = b'hiddenpassword' assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_create_hidden_volume(0, 20, 21, hidden_volume_password) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(hidden_volume_password) == DeviceErrorCode.STATUS_OK @pytest.mark.hidden def test_encrypted_volume_setup_multiple_hidden_lock(C): import random skip_if_device_version_lower_than({'S': 45}) #hangs device on lower version hidden_volume_password = b'hiddenpassword' + bb(str(random.randint(0,100))) p = lambda i: hidden_volume_password + bb(str(i)) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(4): assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i) ) == DeviceErrorCode.STATUS_OK for i in range(4): assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK @pytest.mark.hidden @pytest.mark.parametrize("volumes_to_setup", range(1, 5)) def test_encrypted_volume_setup_multiple_hidden_no_lock_device_volumes(C, volumes_to_setup): skip_if_device_version_lower_than({'S': 43}) hidden_volume_password = b'hiddenpassword' p = lambda i: hidden_volume_password + bb(str(i)) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(volumes_to_setup): assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(volumes_to_setup): assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK # TODO mount and test for files assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK @pytest.mark.hidden @pytest.mark.parametrize("volumes_to_setup", range(1, 5)) def test_encrypted_volume_setup_multiple_hidden_no_lock_device_volumes_unlock_at_once(C, volumes_to_setup): skip_if_device_version_lower_than({'S': 43}) hidden_volume_password = b'hiddenpassword' p = lambda i: hidden_volume_password + bb(str(i)) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(volumes_to_setup): assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(volumes_to_setup): assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK # TODO mount and test for files assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK @pytest.mark.hidden @pytest.mark.parametrize("use_slot", range(4)) def test_encrypted_volume_setup_one_hidden_no_lock_device_slot(C, use_slot): skip_if_device_version_lower_than({'S': 43}) hidden_volume_password = b'hiddenpassword' p = lambda i: hidden_volume_password + bb(str(i)) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK i = use_slot assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for j in range(3): assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK # TODO mount and test for files assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK @pytest.mark.hidden @pytest.mark.PWS def test_password_safe_slot_name_corruption(C): skip_if_device_version_lower_than({'S': 43}) volumes_to_setup = 4 # connected with encrypted volumes, possible also with hidden def fill(s, wid): assert wid >= len(s) numbers = '1234567890' * 4 s += numbers[:wid - len(s)] assert len(s) == wid return bb(s) def get_pass(suffix): return fill('pass' + suffix, 20) def get_loginname(suffix): return fill('login' + suffix, 32) def get_slotname(suffix): return fill('slotname' + suffix, 11) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_enable_password_safe(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK PWS_slot_count = 16 for i in range(0, PWS_slot_count): iss = str(i) assert C.NK_write_password_safe_slot(i, get_slotname(iss), get_loginname(iss), get_pass(iss)) == DeviceErrorCode.STATUS_OK def check_PWS_correctness(C): for i in range(0, PWS_slot_count): iss = str(i) assert gs(C.NK_get_password_safe_slot_name(i)) == get_slotname(iss) assert gs(C.NK_get_password_safe_slot_login(i)) == get_loginname(iss) assert gs(C.NK_get_password_safe_slot_password(i)) == get_pass(iss) hidden_volume_password = b'hiddenpassword' p = lambda i: hidden_volume_password + bb(str(i)) def check_volumes_correctness(C): for i in range(volumes_to_setup): assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK # TODO mount and test for files assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK check_PWS_correctness(C) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(volumes_to_setup): assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK check_volumes_correctness(C) check_PWS_correctness(C) check_volumes_correctness(C) check_PWS_correctness(C) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK check_volumes_correctness(C) check_PWS_correctness(C) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK check_volumes_correctness(C) check_PWS_correctness(C) @pytest.mark.hidden def test_hidden_volume_corruption(C): # bug: this should return error without unlocking encrypted volume each hidden volume lock, but it does not skip_if_device_version_lower_than({'S': 43}) hidden_volume_password = b'hiddenpassword' p = lambda i: hidden_volume_password + bb(str(i)) volumes_to_setup = 4 assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(volumes_to_setup): assert C.NK_create_hidden_volume(i, 20 + i * 10, 20 + i * 10 + i + 1, p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK assert C.NK_lock_encrypted_volume() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(volumes_to_setup): assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK assert C.NK_unlock_hidden_volume(p(i)) == DeviceErrorCode.STATUS_OK wait(2) assert C.NK_lock_hidden_volume() == DeviceErrorCode.STATUS_OK @pytest.mark.unencrypted def test_unencrypted_volume_set_read_only(C): skip_if_device_version_lower_than({'S': 43}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_set_unencrypted_read_only(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK @pytest.mark.unencrypted def test_unencrypted_volume_set_read_write(C): skip_if_device_version_lower_than({'S': 43}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_set_unencrypted_read_write(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK @pytest.mark.unencrypted def test_unencrypted_volume_set_read_only_admin(C): skip_if_device_version_lower_than({'S': 51}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_set_unencrypted_read_only_admin(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.unencrypted def test_unencrypted_volume_set_read_write_admin(C): skip_if_device_version_lower_than({'S': 51}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_set_unencrypted_read_write_admin(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.encrypted @pytest.mark.skip(reason='not supported on recent firmware, except v0.49') def test_encrypted_volume_set_read_only(C): skip_if_device_version_lower_than({'S': 99}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_set_encrypted_read_only(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.encrypted @pytest.mark.skip(reason='not supported on recent firmware, except v0.49') def test_encrypted_volume_set_read_write(C): skip_if_device_version_lower_than({'S': 99}) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_set_encrypted_read_write(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.other def test_export_firmware(C): skip_if_device_version_lower_than({'S': 43}) assert C.NK_export_firmware(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.other def test_clear_new_sd_card_notification(C): skip_if_device_version_lower_than({'S': 43}) assert C.NK_clear_new_sd_card_warning(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK @pytest.mark.encrypted @pytest.mark.slowtest @pytest.mark.skip(reason='long test (about 1h)') def test_fill_SD_card(C): skip_if_device_version_lower_than({'S': 43}) status = C.NK_fill_SD_card_with_random_data(DefaultPasswords.ADMIN) assert status == DeviceErrorCode.STATUS_OK or status == DeviceErrorCode.BUSY while 1: value = C.NK_get_progress_bar_value() if value == -1: break assert 0 <= value <= 100 assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK wait(5) @pytest.mark.other @pytest.mark.info def test_get_busy_progress_on_idle(C): skip_if_device_version_lower_than({'S': 43}) value = C.NK_get_progress_bar_value() assert value == -1 assert C.NK_get_last_command_status() == DeviceErrorCode.STATUS_OK @pytest.mark.update def test_change_update_password(C): skip_if_device_version_lower_than({'S': 43}) wrong_password = b'aaaaaaaaaaa' assert C.NK_change_update_password(wrong_password, DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_change_update_password(DefaultPasswords.UPDATE, DefaultPasswords.UPDATE_TEMP) == DeviceErrorCode.STATUS_OK assert C.NK_enable_firmware_update(DefaultPasswords.UPDATE) == DeviceErrorCode.WRONG_PASSWORD assert C.NK_change_update_password(DefaultPasswords.UPDATE_TEMP, DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK @pytest.mark.skip_by_default @pytest.mark.update def test_enable_firmware_update(C): skip_if_device_version_lower_than({'S': 50}) assert C.NK_enable_firmware_update(DefaultPasswords.UPDATE) == DeviceErrorCode.STATUS_OK @pytest.mark.other def test_send_startup(C): skip_if_device_version_lower_than({'S': 43}) time_seconds_from_epoch = 0 # FIXME set proper date assert C.NK_send_startup(time_seconds_from_epoch) == DeviceErrorCode.STATUS_OK @pytest.mark.other def test_struct_multiline_prodtest(C): info_st = ffi.new('struct NK_storage_ProductionTest *') if info_st is None: raise Exception('Invalid value') err = C.NK_get_storage_production_info(info_st) assert err == 0 assert info_st.SD_Card_ManufacturingYear_u8 != 0 assert info_st.SD_Card_ManufacturingMonth_u8 != 0 assert info_st.SD_Card_Size_u8 != 0 assert info_st.FirmwareVersion_au8[0] == 0 assert info_st.FirmwareVersion_au8[1] >= 50 info = 'CPU:{CPU},SC:{SC},SD:{SD},' \ 'SCM:{SCM},SCO:{SCO},DAT:{DAT},Size:{size},Firmware:{fw} - {fwb}'.format( CPU='0x{:08x}'.format(info_st.CPU_CardID_u32), SC='0x{:08x}'.format(info_st.SmartCardID_u32), SD='0x{:08x}'.format(info_st.SD_CardID_u32), SCM='0x{:02x}'.format(info_st.SD_Card_Manufacturer_u8), SCO='0x{:04x}'.format(info_st.SD_Card_OEM_u16), DAT='20{}.{}'.format(info_st.SD_Card_ManufacturingYear_u8, info_st.SD_Card_ManufacturingMonth_u8), size=info_st.SD_Card_Size_u8, fw='{}.{}'.format(info_st.FirmwareVersion_au8[0], info_st.FirmwareVersion_au8[1]), fwb=info_st.FirmwareVersionInternal_u8 ) print(info) @pytest.mark.skip(reason='additional test') @pytest.mark.other @pytest.mark.firmware def test_export_firmware_extended_fedora29(C): """ Check, whether the firmware file is exported correctly, and in correct size. Apparently, the auto-remounting side effect of the v0.46 change, is disturbing the export process. Unmounting the UV just before the export gives the device 20/20 success rate. Test case for issue https://github.com/Nitrokey/nitrokey-app/issues/399 """ skip_if_device_version_lower_than({'S': 43}) skip_if_not_fedora('Tested on Fedora only. To check on other distros.') from time import sleep import os from os.path import exists as exist import re try: import pyudev as pu import pexpect except: pytest.skip('Skipping due to missing required packages: pyudev and pexpect.') ctx = pu.Context() devices = ctx.list_devices(subsystem='block', ID_VENDOR='Nitrokey') device = None for d in devices: if d.device_type == 'partition': device = '/dev/{}'.format(d.sys_name) break assert device, 'Device could not be found' pexpect.run(f'udisksctl unmount -b {device}').decode() sleep(1) _res = pexpect.run(f'udisksctl mount -b {device}').decode() firmware_abs_path = re.findall('at (/.*)\.', _res) assert firmware_abs_path, 'Cannot get mount point' firmware_abs_path = firmware_abs_path[0] print('path: {}, device: {}'.format(firmware_abs_path, device)) assert firmware_abs_path, 'Cannot get mount point' firmware_abs_path = firmware_abs_path + '/firmware.bin' checks = 0 checks_add = 0 if exist(firmware_abs_path): os.remove(firmware_abs_path) assert not exist(firmware_abs_path) ATTEMPTS = 20 for i in range(ATTEMPTS): # if umount is disabled, success rate is 3/10, enabled: 10/10 pexpect.run(f'udisksctl unmount -b {device}') assert C.NK_export_firmware(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK pexpect.run(f'udisksctl mount -b {device}') sleep(1) firmware_file_exist = exist(firmware_abs_path) if firmware_file_exist: checks += 1 getsize = os.path.getsize(firmware_abs_path) print('Firmware file exist, size: {}'.format(getsize)) checks_add += 1 if getsize >= 100 * 1024 else 0 # checks_add += 1 if os.path.getsize(firmware_abs_path) == 256*1024 else 0 os.remove(firmware_abs_path) assert not exist(firmware_abs_path) print('CHECK {} ; CHECK ADDITIONAL {}'.format(checks, checks_add)) assert checks == ATTEMPTS assert checks_add == checks def skip_if_not_fedora(message:str) -> None: import os from os.path import exists as exist def skip(): pytest.skip(message) os_release_fp = '/etc/os-release' if not exist(os_release_fp): skip() with open(os_release_fp) as f: os_release_lines = f.readlines() if 'Fedora' not in os_release_lines[0]: skip() @pytest.mark.other @pytest.mark.firmware def test_export_firmware_extended_macos(C): """ Check, whether the firmware file is exported correctly, and in correct size. Apparently, the auto-remounting side effect of the v0.46 change, is disturbing the export process. Unmounting the UV just before the export gives the device 20/20 success rate. Test case for issue https://github.com/Nitrokey/nitrokey-app/issues/399 """ skip_if_device_version_lower_than({'S': 43}) skip_if_not_macos('macOS specific test, due to the mount path and command.') import pexpect from time import sleep import os from os.path import exists as exist import plistlib usb_devices = pexpect.run('system_profiler -xml SPUSBDataType') assert b'Nitrokey' in usb_devices, 'No Nitrokey devices connected' usb_devices_parsed = plistlib.loads(usb_devices) assert isinstance(usb_devices_parsed, list), 'usb_devices_parsed has unexpected type' # Try to get all USB devices try: devices = usb_devices_parsed[0]['_items'][0]['_items'] except KeyError: devices = None assert devices is not None, 'could not list USB devices' device_item = None for item in devices: if '_items' in item: # Fix for macOS 10.13.6, Python 3.6.2 item = item['_items'][0] if 'manufacturer' in item and item['manufacturer'] == 'Nitrokey': device_item = item # Try to get first volume of USB device try: volume = device_item['Media'][0]['volumes'][0] except (KeyError, TypeError): volume = None assert volume is not None, 'could not determine volume' assert 'bsd_name' in volume, 'could not get BSD style device name' device = '/dev/' + volume['bsd_name'] pexpect.run(f'diskutil mount {device}') sleep(3) assert 'mount_point' in volume, 'could not get mount point' firmware_abs_path = volume['mount_point'] + '/firmware.bin' checks = 0 print('path: {}, device: {}'.format(firmware_abs_path, device)) checks_add = 0 if exist(firmware_abs_path): os.remove(firmware_abs_path) assert not exist(firmware_abs_path) ATTEMPTS = 20 for i in range(ATTEMPTS): # if umount is disabled, success rate is 3/10, enabled: 10/10 pexpect.run(f'diskutil unmount {device}') assert C.NK_export_firmware(DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK pexpect.run(f'diskutil mount {device}') sleep(1) firmware_file_exist = exist(firmware_abs_path) if firmware_file_exist: checks += 1 getsize = os.path.getsize(firmware_abs_path) print('Firmware file exist, size: {}'.format(getsize)) checks_add += 1 if getsize >= 100 * 1024 else 0 # checks_add += 1 if os.path.getsize(firmware_abs_path) == 256*1024 else 0 os.remove(firmware_abs_path) assert not exist(firmware_abs_path) print('CHECK {} ; CHECK ADDITIONAL {}'.format(checks, checks_add)) assert checks == ATTEMPTS assert checks_add == checks def skip_if_not_macos(message: str) -> None: import platform if platform.system() != 'Darwin': pytest.skip(message) from typing import Callable, Optional def helper_busy_wait(func: Callable, timeout=10) -> DeviceErrorCode: start = datetime.now() res = func() while res == DeviceErrorCode.BUSY: sleep(.5) status_dict, res = get_status_storage(C) print(status_dict) if datetime.now() - start > timedelta(seconds=timeout): print('Timeout, stopping') return res return res def helper_create_hidden_volume(C, slot, begin, end, password_in: Optional[bytes], should_work=True): """ :param password_in: if None, generate randomly per call """ assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK password = password_in if password_in is None: password = secrets.token_hex(5) password = password.encode('ascii') assert not should_work ^ (helper_busy_wait( lambda: C.NK_create_hidden_volume(slot, begin, end, password)) == DeviceErrorCode.STATUS_OK) assert not should_work ^ ( helper_busy_wait(lambda: C.NK_unlock_hidden_volume(password)) == DeviceErrorCode.STATUS_OK) if should_work: assert helper_busy_wait(lambda: C.NK_lock_hidden_volume()) == DeviceErrorCode.STATUS_OK @dataclasses.dataclass class MalformedParams: slot: int begin: int end: int password: Optional[bytes] = None should_work: bool = True def as_list(self): return [self.slot, self.begin, self.end, self.password, self.should_work] @pytest.mark.hidden @pytest.mark.parametrize("args", [ # correct calls MalformedParams(slot=0, begin=1, end=2), MalformedParams(slot=0, begin=0, end=100), MalformedParams(slot=0, begin=99, end=100), MalformedParams(slot=0, begin=0, end=1), MalformedParams(slot=0, begin=0, end=1), # password not empty # password not longer than 20 characters MalformedParams(slot=0, begin=1, end=2, password=b"", should_work=False), MalformedParams(slot=0, begin=1, end=2, password=b"a" * 21, should_work=False), MalformedParams(slot=0, begin=1, end=2, password=b"a" * 20), # slot 0..3 MalformedParams(slot=5, begin=1, end=2, should_work=False), MalformedParams(slot=55, begin=1, end=2, should_work=False), # end 1..100 MalformedParams(slot=0, begin=0, end=101, should_work=False), # begin 0..99 MalformedParams(slot=0, begin=100, end=100, should_work=False), MalformedParams(slot=0, begin=50, end=49, should_work=False), MalformedParams(slot=0, begin=50, end=50, should_work=False), ], ids=str) def test_hidden_volume_malformed_parameters(C, args): skip_if_device_version_lower_than({'S': 56}) helper_create_hidden_volume(C, *args.as_list()) # password=st.text(min_size=10, max_size=20) # disabled to avoid failed tests due to unlocking previously correctly # configured HV with the same password used in failing example @given(slot=st.integers(min_value=0, max_value=3), begin=st.integers(min_value=0, max_value=99), end=st.integers(min_value=1, max_value=100)) @settings(max_examples=15, deadline=timedelta(seconds=10), verbosity=Verbosity.verbose) def test_hypo_hidden_volume_setup(C, slot, begin, end): assume(begin < end) # password = password.encode('utf-8') password = None helper_create_hidden_volume(C, slot, begin, end, password, should_work=True) libnitrokey-3.7/unittest/test_strdup.cpp000066400000000000000000000032531423223421400206610ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ // issue: https://github.com/Nitrokey/libnitrokey/issues/110 // tests according to the issue's author, Robin Krahl (robinkrahl) // suggested run command: valgrind --tool=memcheck --leak-check=full ./test_strdup #include #include #include "../NK_C_API.h" #include "catch2/catch.hpp" static const int SHORT_STRING_LENGTH = 10; TEST_CASE("Test strdup memory free error", "[BASIC]") { NK_set_debug(false); char *c = NK_get_status_as_string(); /* error --> string literal */ REQUIRE(c != nullptr); REQUIRE(strnlen(c, SHORT_STRING_LENGTH) == 0); puts(c); free(c); } TEST_CASE("Test strdup memory leak", "[BASIC]") { NK_set_debug(false); bool connected = NK_login_auto() == 1; if (!connected) return; REQUIRE(connected); char *c = NK_get_status_as_string(); /* no error --> dynamically allocated */ REQUIRE(c != nullptr); REQUIRE(strnlen(c, SHORT_STRING_LENGTH) > 0); puts(c); free(c); } libnitrokey-3.7/version.cc000066400000000000000000000022151423223421400157070ustar00rootroot00000000000000/* * 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 . * * SPDX-License-Identifier: LGPL-3.0 */ #include "version.h" namespace nitrokey { unsigned int get_major_library_version() { #ifdef LIBNK_VERSION_MAJOR return LIBNK_VERSION_MAJOR; #endif return 3; } unsigned int get_minor_library_version() { #ifdef LIBNK_VERSION_MINOR return LIBNK_VERSION_MINOR; #endif return 0; } const char* get_library_version() { return "unknown"; } } libnitrokey-3.7/version.cc.in000066400000000000000000000020731423223421400163160ustar00rootroot00000000000000/* * 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 . * * 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@"; } }