pax_global_header00006660000000000000000000000064152211521050014504gustar00rootroot0000000000000052 comment=3a7fa1a780716534e800ba51f80fe929af77adf7 libcotp-4.2.1/000077500000000000000000000000001522115210500131445ustar00rootroot00000000000000libcotp-4.2.1/.circleci/000077500000000000000000000000001522115210500147775ustar00rootroot00000000000000libcotp-4.2.1/.circleci/config.yml000066400000000000000000000064441522115210500167770ustar00rootroot00000000000000version: 2.0 jobs: debianStable_gcrypt: docker: - image: debian:stable steps: - checkout - run: command: | export DEBIAN_FRONTEND=noninteractive apt update && apt -y install git gcc clang cmake libcriterion-dev libgcrypt20-dev mkdir build && cd "$_" cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_TESTS=ON .. make && make install ./tests/test_base32encode ./tests/test_base32decode ./tests/test_cotp ubuntu2404_gcrypt: docker: - image: ubuntu:24.04 steps: - checkout - run: command: | export DEBIAN_FRONTEND=noninteractive apt update && apt -y install git gcc clang cmake libcriterion-dev libgcrypt20-dev mkdir build && cd "$_" cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_TESTS=ON .. make && make install ./tests/test_base32encode ./tests/test_base32decode ./tests/test_cotp debianStable_openssl: docker: - image: debian:stable steps: - checkout - run: command: | export DEBIAN_FRONTEND=noninteractive apt update && apt -y install git gcc clang cmake libcriterion-dev libssl-dev mkdir build && cd "$_" cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_TESTS=ON -DHMAC_WRAPPER=openssl .. make && make install ./tests/test_base32encode ./tests/test_base32decode ./tests/test_cotp ubuntu2404_openssl: docker: - image: ubuntu:24.04 steps: - checkout - run: command: | export DEBIAN_FRONTEND=noninteractive apt update && apt -y install git gcc clang cmake libcriterion-dev libssl-dev mkdir build && cd "$_" cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_TESTS=ON -DHMAC_WRAPPER=openssl .. make && make install ./tests/test_base32encode ./tests/test_base32decode ./tests/test_cotp debianStable_mbedtls: docker: - image: debian:stable steps: - checkout - run: command: | export DEBIAN_FRONTEND=noninteractive apt update && apt -y install git gcc clang cmake libcriterion-dev libmbedtls-dev mkdir build && cd "$_" cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_TESTS=ON -DHMAC_WRAPPER=mbedtls .. make && make install ./tests/test_base32encode ./tests/test_base32decode ./tests/test_cotp ubuntu2404_mbedtls: docker: - image: ubuntu:24.04 steps: - checkout - run: command: | export DEBIAN_FRONTEND=noninteractive apt update && apt -y install git gcc clang cmake libcriterion-dev libmbedtls-dev mkdir build && cd "$_" cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_TESTS=ON -DHMAC_WRAPPER=mbedtls .. make && make install ./tests/test_base32encode ./tests/test_base32decode ./tests/test_cotp workflows: version: 2 build: jobs: - debianStable_gcrypt - ubuntu2404_gcrypt - debianStable_openssl - ubuntu2404_openssl - debianStable_mbedtls - ubuntu2404_mbedtls libcotp-4.2.1/.github/000077500000000000000000000000001522115210500145045ustar00rootroot00000000000000libcotp-4.2.1/.github/workflows/000077500000000000000000000000001522115210500165415ustar00rootroot00000000000000libcotp-4.2.1/.github/workflows/codeql-analysis.yml000066400000000000000000000025351522115210500223610ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [ master ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] schedule: - cron: '16 8 * * 2' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'cpp' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - name: Checkout repository uses: actions/checkout@v3 - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} - name: Install Dependencies run: | sudo apt update && DEBIAN_FRONTEND=noninteractive sudo apt -y install git gcc cmake libgcrypt20-dev git clone https://github.com/paolostivanin/libbaseencode ./be_dir && cd be_dir mkdir build && cd build cmake -DCMAKE_INSTALL_PREFIX=/usr .. make sudo make install cd ../.. - name: Build run: | mkdir build && cd $_ cmake .. make - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 libcotp-4.2.1/.github/workflows/sanitizers.yml000066400000000000000000000040541522115210500214620ustar00rootroot00000000000000name: Sanitizers on: push: branches: [ master ] pull_request: branches: [ master ] jobs: asan-ubsan: name: ASan+UBSan (${{ matrix.backend }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: backend: [ gcrypt, openssl, mbedtls ] steps: - uses: actions/checkout@v4 - name: Install dependencies run: | sudo apt update sudo DEBIAN_FRONTEND=noninteractive apt -y install \ cmake clang libcriterion-dev \ libgcrypt20-dev libssl-dev libmbedtls-dev - name: Configure run: | mkdir build && cd build CC=clang CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1" \ cmake -DBUILD_TESTS=ON -DCOTP_ENABLE_VALIDATION=ON \ -DHMAC_WRAPPER=${{ matrix.backend }} .. - name: Build run: cmake --build build --parallel - name: Test env: ASAN_OPTIONS: detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 run: ctest --test-dir build --output-on-failure fuzz-smoke: name: Fuzzer smoke (30s each) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: | sudo apt update sudo DEBIAN_FRONTEND=noninteractive apt -y install \ cmake clang libgcrypt20-dev - name: Configure (Clang + libFuzzer + ASan + UBSan) run: | mkdir build && cd build CC=clang cmake -DCOTP_BUILD_FUZZERS=ON .. - name: Build fuzzers run: cmake --build build --parallel --target fuzz_base32_decode fuzz_get_totp_at fuzz_otpauth_uri - name: Smoke run each fuzzer for 30s env: ASAN_OPTIONS: detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 run: | ./build/fuzz/fuzz_base32_decode -max_total_time=30 ./build/fuzz/fuzz_get_totp_at -max_total_time=30 ./build/fuzz/fuzz_otpauth_uri -max_total_time=30 libcotp-4.2.1/.gitignore000066400000000000000000000003301522115210500151300ustar00rootroot00000000000000.idea/ cmake-build-debug/ build/ # Object files *.o *.ko *.obj *.elf # Precompiled Headers *.gch *.pch # Libraries *.lib *.a *.la *.lo # Shared object *.so *.so.* # Executables *.out *.app *.i*86 *.x86_64 *.hex libcotp-4.2.1/CMakeLists.txt000066400000000000000000000140501522115210500157040ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.16) project(cotp VERSION "4.2.1" LANGUAGES "C") # Guard against drift between CMake project version and the COTP_VERSION_STRING macro in cotp.h file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/src/cotp.h" _cotp_hdr_ver REGEX "^#define COTP_VERSION_STRING") string(REGEX MATCH "\"([0-9]+\\.[0-9]+\\.[0-9]+)\"" _ "${_cotp_hdr_ver}") if(NOT "${CMAKE_MATCH_1}" STREQUAL "${PROJECT_VERSION}") message(FATAL_ERROR "cotp.h COTP_VERSION_STRING (${CMAKE_MATCH_1}) does not match project VERSION (${PROJECT_VERSION}). Update both.") endif() set(CMAKE_C_STANDARD 11) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(GNUInstallDirs) include(CMakePackageConfigHelpers) include(CheckFunctionExists) check_function_exists(explicit_bzero HAVE_EXPLICIT_BZERO) find_package(PkgConfig) option(BUILD_SHARED_LIBS "Build libcotp as a shared library" ON) option(BUILD_TESTS "Build base32 and cotp tests" OFF) set(HMAC_WRAPPER "gcrypt" CACHE STRING "Choose between gcrypt (default), openssl or mbedtls for HMAC computation") set_property(CACHE HMAC_WRAPPER PROPERTY STRINGS "gcrypt" "openssl" "mbedtls") if("${HMAC_WRAPPER}" STREQUAL "gcrypt") set(HMAC_SOURCE_FILES src/utils/whmac_gcrypt.c ) set(HASH_SOURCE_FILES src/utils/whash_gcrypt.c ) find_package(Gcrypt 1.8.0 REQUIRED) set(HMAC_INCLUDE_DIR ${GCRYPT_INCLUDE_DIR}) set(HMAC_LIBRARIES ${GCRYPT_LIBRARIES}) message(STATUS "libcotp: HMAC backend set to gcrypt") elseif("${HMAC_WRAPPER}" STREQUAL "openssl") find_package(OpenSSL 3.0.0 REQUIRED) set(HMAC_SOURCE_FILES src/utils/whmac_openssl.c ) set(HASH_SOURCE_FILES src/utils/whash_openssl.c ) set(HMAC_INCLUDE_DIR ${OPENSSL_INCLUDE_DIR}) set(HMAC_LIBRARIES ${OPENSSL_LIBRARIES}) message(STATUS "libcotp: HMAC backend set to openssl") elseif("${HMAC_WRAPPER}" STREQUAL "mbedtls") find_package(MbedTLS REQUIRED) set(HMAC_SOURCE_FILES src/utils/whmac_mbedtls.c ) set(HASH_SOURCE_FILES src/utils/whash_mbedtls.c ) set(HMAC_INCLUDE_DIR ${MBEDTLS_INCLUDE_DIRS}) set(HMAC_LIBRARIES ${MBEDTLS_LIBRARIES}) message(STATUS "libcotp: HMAC backend set to mbedtls") else() message(FATAL_ERROR "libcotp: unknown HMAC_WRAPPER '${HMAC_WRAPPER}'. Choose gcrypt, openssl, or mbedtls.") endif() set(COTP_HEADERS src/cotp.h ) option(COTP_ENABLE_VALIDATION "Enable helper APIs for OTP validation in a time window" OFF) set(SOURCE_FILES src/otp.c src/yaotp.c ${HMAC_SOURCE_FILES} ${HASH_SOURCE_FILES} src/utils/base32.c src/utils/secure_zero.c src/utils/pct.c src/utils/otpauth_uri.c src/utils/yaotp_uri.c src/ctx.c src/strerror.c ) if (COTP_ENABLE_VALIDATION) list(APPEND SOURCE_FILES src/utils/validation.c) endif() add_library(cotp ${SOURCE_FILES}) if (HAVE_EXPLICIT_BZERO) target_compile_definitions(cotp PRIVATE HAVE_EXPLICIT_BZERO) endif() if (COTP_ENABLE_VALIDATION) target_compile_definitions(cotp PUBLIC COTP_ENABLE_VALIDATION) endif() target_link_libraries(cotp PRIVATE ${HMAC_LIBRARIES}) target_include_directories(cotp PUBLIC $ $ PRIVATE ${HMAC_INCLUDE_DIR}) if(NOT MSVC) target_compile_options(cotp PRIVATE -Wall -Wextra -O3 -Wformat=2 -Wmissing-format-attribute -fstack-protector-strong -Wundef -Wmissing-format-attribute -fdiagnostics-color=always -Wstrict-prototypes -Wunreachable-code -Wchar-subscripts -Wwrite-strings -Wpointer-arith -Wbad-function-cast -Wcast-align -Werror=format-security -Werror=implicit-function-declaration -Wno-sign-compare -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 -fvisibility=hidden) endif() if(NOT APPLE AND NOT MSVC) target_link_options(cotp PRIVATE "LINKER:-z,relro,-z,now" "LINKER:-z,noexecstack") endif() set_target_properties(cotp PROPERTIES VERSION ${CMAKE_PROJECT_VERSION} SOVERSION ${CMAKE_PROJECT_VERSION_MAJOR}) if (BUILD_TESTS) enable_testing() add_subdirectory(tests) endif () option(COTP_BUILD_FUZZERS "Build libFuzzer harnesses (requires Clang with -fsanitize=fuzzer)" OFF) if (COTP_BUILD_FUZZERS) add_subdirectory(fuzz) endif () set(COTP_LIB_DIR "${CMAKE_INSTALL_LIBDIR}") set(COTP_INC_DIR "${CMAKE_INSTALL_INCLUDEDIR}") install( TARGETS cotp EXPORT cotpTargets ARCHIVE DESTINATION ${COTP_LIB_DIR} LIBRARY DESTINATION ${COTP_LIB_DIR} COMPONENT library ) install( FILES ${COTP_HEADERS} DESTINATION ${COTP_INC_DIR} ) # CMake package config for find_package(COTP CONFIG) write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/COTPConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion ) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/COTPConfig.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/COTPConfig.cmake" INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/COTP ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/COTPConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/COTPConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/COTP ) install(EXPORT cotpTargets NAMESPACE COTP:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/COTP) if (PkgConfig_FOUND) # Allow adding prefix if CMAKE_INSTALL_INCLUDEDIR not absolute. if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") set(PKGCONFIG_TARGET_INCLUDES "${CMAKE_INSTALL_INCLUDEDIR}") else() set(PKGCONFIG_TARGET_INCLUDES "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") endif() # Allow adding prefix if CMAKE_INSTALL_LIBDIR not absolute. if(IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}") set(PKGCONFIG_TARGET_LIBS "${CMAKE_INSTALL_LIBDIR}") else() set(PKGCONFIG_TARGET_LIBS "\${exec_prefix}/${CMAKE_INSTALL_LIBDIR}") endif() configure_file("cotp.pc.in" "cotp.pc" @ONLY) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/cotp.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig/) endif() libcotp-4.2.1/LICENSE000066400000000000000000000261211522115210500141530ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 Paolo Stivanin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. libcotp-4.2.1/README.md000066400000000000000000000445121522115210500144310ustar00rootroot00000000000000# libcotp Coverity Scan Build Status C library that generates TOTP and HOTP according to [RFC-6238](https://www.rfc-editor.org/rfc/rfc6238) and [RFC-4226](https://www.rfc-editor.org/rfc/rfc4226), with Base32 codec ([RFC-4648](https://www.rfc-editor.org/rfc/rfc4648)), Steam Guard, YAOTP (Yandex.Key) and `otpauth://` URI parser/builder. **Quick index:** [Public API](#public-api) · [Error Model](#error-model) · [Validation](#validation-helpers-optional) · [Context API](#context-api) · [otpauth:// URIs](#otpauth-uris) · [YAOTP](#yaotp-yandexkey) · [Base32](#base32-encoding--decoding) · [Utilities](#utilities) · [Operational Notes](#operational-notes) ## Requirements - GCC or Clang and CMake - One crypto backend: - libgcrypt ≥ 1.8.0 - OpenSSL ≥ 3.0.0 - MbedTLS 2.x or 3.x ## Build and Install ```sh git clone https://github.com/paolostivanin/libcotp.git cd libcotp mkdir build && cd build cmake -DCMAKE_INSTALL_PREFIX=/usr .. make sudo make install ``` ### CMake Options | Option | Default | Description | |--------|---------|-------------| | `-DBUILD_TESTS=ON` | OFF | Build tests (requires Criterion) | | `-DBUILD_SHARED_LIBS=OFF` | ON | Build static instead of shared | | `-DHMAC_WRAPPER=` | gcrypt | Select crypto backend | | `-DCOTP_ENABLE_VALIDATION=ON` | OFF | Enable validation helper APIs | | `-DCOTP_BUILD_FUZZERS=ON` | OFF | Build libFuzzer harnesses (requires Clang) | --- ## Public API ```c char *get_totp(const char *base32_secret, int digits, int period, int algo, cotp_error_t *err); char *get_steam_totp(const char *base32_secret, int period, cotp_error_t *err); char *get_steam_totp_at(const char *base32_secret, long timestamp, int period, cotp_error_t *err); char *get_hotp(const char *base32_secret, long counter, int digits, int algo, cotp_error_t *err); char *get_totp_at(const char *base32_secret, long timestamp, int digits, int period, int algo, cotp_error_t *err); char *get_yaotp(const char *base32_secret, const char *pin, cotp_error_t *err); char *get_yaotp_at(const char *base32_secret, const char *pin, long timestamp, cotp_error_t *err); int cotp_yaotp_secret_pin_length(const char *base32_secret, cotp_error_t *err); int64_t otp_to_int(const char *otp, cotp_error_t *err); const char *cotp_strerror(cotp_error_t err); ``` Public functions returning a heap pointer or status code are annotated with `__attribute__((warn_unused_result))` (GCC/Clang) so ignoring the return triggers a compile warning. ### Parameter Constraints - `base32_secret`: Base32 encoded (may contain spaces). `NULL` is invalid. - `digits`: 4–10 inclusive - `period`: 1–120 seconds inclusive - `algo`: `COTP_SHA1`, `COTP_SHA256`, `COTP_SHA512` - `counter`: non-negative - `timestamp`: UNIX epoch seconds Secrets are normalized (spaces removed, lowercase → uppercase). --- ## Ownership and Lifetime - On success, OTP functions return `char *`. Caller must `free()`. - On error, they return `NULL` and set `err` if non-NULL. - If `err == NULL`, functions still behave correctly using an internal error variable. - `otp_to_int()` never allocates: - returns `-1` on invalid input - returns integer on success - strips leading zeroes and sets `MISSING_LEADING_ZERO` when applicable Example: ```c cotp_error_t err; char *code = get_totp("HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ", 6, 30, COTP_SHA1, &err); if (!code) { // handle error } free(code); ``` --- ## Error Model | Error | Meaning | |-------|---------| | `NO_ERROR` | Success. From `validate_totp_in_window` / `cotp_ctx_validate_totp`, this means the call ran cleanly but **no offset matched**. | | `VALID` | Validation matched. Set **only** by `validate_totp_in_window` and `cotp_ctx_validate_totp`. Other functions never use it. | | `WHMAC_ERROR` | Backend crypto error | | `WCRYPT_VERSION_MISMATCH` | Crypto backend version too old. Currently emitted by the **gcrypt** backend only; the OpenSSL and MbedTLS backends skip the runtime check. | | `INVALID_B32_INPUT` | Secret not valid Base32 | | `INVALID_ALGO` | Unsupported algorithm | | `INVALID_PERIOD` | Period not in allowed range | | `INVALID_DIGITS` | Digits not in allowed range | | `INVALID_COUNTER` | `counter < 0` | | `INVALID_USER_INPUT` | NULL or malformed user input | | `MISSING_LEADING_ZERO` | Leading zeroes stripped | | `MEMORY_ALLOCATION_ERROR` | Allocation failure | | `EMPTY_STRING` | Input was empty | | `INVALID_YAOTP_SECRET_LENGTH` | YAOTP secret too short or pinLength byte out of range | | `INVALID_YAOTP_SECRET_CRC` | YAOTP secret's CRC-13 checksum did not verify | | `INVALID_YAOTP_PIN` | YAOTP PIN NULL, wrong length, or contains non-digits | Return rules: - `get_totp`, `get_totp_at`, `get_steam_totp`, `get_steam_totp_at`, `get_hotp`, `get_yaotp`, `get_yaotp_at` → `NULL` on failure - `otp_to_int`, `cotp_yaotp_secret_pin_length` → `-1` on failure - `cotp_strerror(err)` returns a static, non-NULL, NUL-terminated description for any `cotp_error_t` value. Unknown values return `"unknown error"`. Do **not** `free()` the result. --- ## Validation Helpers (optional) Enabled with `-DCOTP_ENABLE_VALIDATION=ON`: ```c int validate_totp_in_window(const char *user_code, const char *base32_secret, long timestamp, int digits, int period, int sha_algo, int window, int *matched_delta, cotp_error_t *err); ``` Returns: - `1` on match within `[-window, +window]` periods (sets `VALID`) - `0` otherwise `window` is symmetric and clamped to a maximum of `1024`; values above that return `INVALID_USER_INPUT`. The internal time arithmetic is overflow-safe; deltas whose timestamp would overflow `long` are silently skipped. The compare uses constant-time byte comparison. Example — accept a code generated one period in the past with `window=1`: ```c cotp_error_t err; char *code = get_totp_at("HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ", 1700000000, 6, 30, COTP_SHA1, &err); int matched_delta = 0; int ok = validate_totp_in_window(code, "HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ", 1700000030, /* one period later */ 6, 30, COTP_SHA1, 1, &matched_delta, &err); // ok == 1, matched_delta == -1, err == VALID free(code); ``` --- ## Context API A context bundles `digits`, `period`, and `algo` so you don't repeat them on every call. Contexts are immutable after creation and safe to share across threads. ```c cotp_ctx *cotp_ctx_create(int digits, int period, int sha_algo); void cotp_ctx_free(cotp_ctx *ctx); char *cotp_ctx_totp(cotp_ctx *ctx, const char *base32_secret, cotp_error_t *err); char *cotp_ctx_totp_at(cotp_ctx *ctx, const char *base32_secret, long timestamp, cotp_error_t *err); char *cotp_ctx_hotp(cotp_ctx *ctx, const char *base32_secret, long counter, cotp_error_t *err); /* Steam variants ignore ctx->digits and ctx->algo (Steam fixes both); only ctx->period is used. */ char *cotp_ctx_steam_totp(cotp_ctx *ctx, const char *base32_secret, cotp_error_t *err); char *cotp_ctx_steam_totp_at(cotp_ctx *ctx, const char *base32_secret, long timestamp, cotp_error_t *err); /* YAOTP variants ignore ctx->{digits,period,algo} entirely (all hardcoded by the algorithm). */ char *cotp_ctx_yaotp(cotp_ctx *ctx, const char *base32_secret, const char *pin, cotp_error_t *err); char *cotp_ctx_yaotp_at(cotp_ctx *ctx, const char *base32_secret, const char *pin, long timestamp, cotp_error_t *err); #ifdef COTP_ENABLE_VALIDATION int cotp_ctx_validate_totp(cotp_ctx *ctx, const char *user_code, const char *base32_secret, long timestamp, int window, int *matched_delta, cotp_error_t *err); #endif ``` `NULL` ctx returns `NULL` (or `0` for the validate variant) and sets `err` to `INVALID_USER_INPUT`. `cotp_ctx_free(NULL)` is a no-op. Example — generate three codes from the same configuration: ```c cotp_ctx *ctx = cotp_ctx_create(6, 30, COTP_SHA1); if (!ctx) { /* invalid digits/period/algo */ } cotp_error_t err; for (int i = 0; i < 3; i++) { char *code = cotp_ctx_totp(ctx, "HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ", &err); /* … use code … */ free(code); sleep(30); } cotp_ctx_free(ctx); ``` --- ## otpauth:// URIs Parser and builder for the de-facto Google Authenticator URI format used by most TOTP/HOTP apps and QR-code provisioning flows. ```c typedef enum { COTP_OTPAUTH_TOTP = 0, COTP_OTPAUTH_HOTP = 1 } cotp_otpauth_type; typedef struct { cotp_otpauth_type type; char *issuer; /* may be NULL */ char *account; /* may be NULL */ char *secret; /* base32, required */ int algo; /* COTP_SHA1 / COTP_SHA256 / COTP_SHA512 (default SHA1) */ int digits; /* 4-10 (default 6) */ int period; /* 1-120, TOTP only (default 30) */ long counter; /* >= 0, HOTP only (required for HOTP) */ } cotp_otpauth_uri; cotp_otpauth_uri *cotp_otpauth_uri_parse(const char *uri, cotp_error_t *err); char *cotp_otpauth_uri_build(const cotp_otpauth_uri *u, cotp_error_t *err); void cotp_otpauth_uri_free(cotp_otpauth_uri *u); ``` Behavior: - Format: `otpauth://TYPE/[ISSUER:]ACCOUNT?secret=…&algorithm=…&digits=…&period=…|counter=…&issuer=…` - Label fields are percent-decoded; missing query parameters use the defaults shown above. - For HOTP, the `counter` query parameter is required. Missing → `INVALID_COUNTER`. - If both label-issuer (`Foo:bar`) and `&issuer=` are present, the **label-issuer wins**. - Unknown query keys are silently ignored. - `_parse` returns a heap struct; release it with `cotp_otpauth_uri_free`. The free function securely zeroes `secret` before releasing. - `_build` validates fields against the same bounds as `get_hotp` / `get_totp_at` and returns a newly allocated, NUL-terminated string the caller must `free()`. Example: ```c cotp_error_t err; cotp_otpauth_uri *u = cotp_otpauth_uri_parse( "otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example", &err); if (!u) { /* handle err */ } char *code = get_totp(u->secret, u->digits, u->period, u->algo, &err); /* … */ free(code); cotp_otpauth_uri_free(u); ``` --- ## YAOTP (Yandex.Key) Proprietary OTP scheme used by Yandex 2FA. Produces eight lowercase letters (`a`–`z`) every 30 seconds. Algorithm ported from [KeeYaOtp](https://github.com/norblik/KeeYaOtp) (the canonical reference); matches Yandex servers including the SHA-256 leading-zero quirk. ```c #define COTP_YAOTP_PERIOD 30 #define COTP_YAOTP_DIGITS 8 #define COTP_YAOTP_MIN_PIN_LENGTH 4 #define COTP_YAOTP_MAX_PIN_LENGTH 16 char *get_yaotp(const char *base32_secret, const char *pin, cotp_error_t *err); char *get_yaotp_at(const char *base32_secret, const char *pin, long timestamp, cotp_error_t *err); int cotp_yaotp_secret_pin_length(const char *base32_secret, cotp_error_t *err); ``` Behavior: - The `base32_secret` is a Yandex-format blob: base32 of `[16-byte key][8-byte userId][pinLength nibble + 12-bit CRC-13]`. Decoded length must be ≥ 26 bytes. The CRC-13 checksum (polynomial `0x18F3`) is verified before any code is computed; a flipped bit returns `INVALID_YAOTP_SECRET_CRC`. - The PIN must be ASCII digits, length 4–16, matching the value encoded in the secret. Mismatch returns `INVALID_YAOTP_PIN`. Call `cotp_yaotp_secret_pin_length` first if your UI needs to size the PIN-entry field. - All output parameters are fixed by the algorithm: 30-second period, SHA-256, 8 letters, `a`–`z` alphabet. `digits`, `period`, and `algo` from a `cotp_ctx` are **ignored** by the ctx wrappers. - Return values: 9-byte heap string on success (caller `free()`s); `NULL` on error with `*err` set. - The library does not retain or copy the PIN, but it cannot scrub a `const char *` it doesn't own. Wipe the PIN buffer yourself with `cotp_secure_memzero` after use. Example: ```c const char *secret = "LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI"; char pin[] = "7586"; cotp_error_t err; int expected_len = cotp_yaotp_secret_pin_length(secret, &err); /* expected_len == 4 */ char *code = get_yaotp(secret, pin, &err); /* code is e.g. "oactmacq" */ free(code); cotp_secure_memzero(pin, sizeof pin - 1); ``` ### YAOTP `otpauth://` URIs Yandex apps issue QR codes of the form `otpauth://yaotp/?secret=…&pin_length=N[&issuer=…][&track_id=…][&uid=…]`. A separate struct (`cotp_yaotp_uri`) parses and builds these without overloading the standard `cotp_otpauth_uri` with Yandex-specific opaque fields. ```c typedef struct { char *secret; /* base32, required */ char *account; /* may be NULL (Yandex's "name" field maps here) */ char *issuer; /* may be NULL */ char *track_id; /* opaque pass-through, may be NULL */ char *uid; /* opaque pass-through, may be NULL */ int pin_length; /* 4–16, required */ } cotp_yaotp_uri; cotp_yaotp_uri *cotp_yaotp_uri_parse(const char *uri, cotp_error_t *err); char *cotp_yaotp_uri_build(const cotp_yaotp_uri *u, cotp_error_t *err); void cotp_yaotp_uri_free(cotp_yaotp_uri *u); ``` `_parse` requires both `secret` and `pin_length`. Unknown query keys are silently ignored; `track_id` and `uid` are capped at 128 decoded bytes to prevent URI-bomb allocations. `_free` securely zeroes `secret` before releasing. --- ## Version Macros ```c #define COTP_VERSION_MAJOR 4 #define COTP_VERSION_MINOR 2 #define COTP_VERSION_PATCH 1 #define COTP_VERSION_STRING "4.2.1" #define COTP_VERSION_NUMBER /* MAJOR*10000 + MINOR*100 + PATCH */ ``` Use `COTP_VERSION_NUMBER` for compile-time conditionals: ```c #if COTP_VERSION_NUMBER >= 40201 /* APIs added in 4.2.1 (YAOTP) are available */ #endif ``` The build asserts that `COTP_VERSION_STRING` matches the CMake project version, so the two cannot drift. --- ## Base32 Encoding / Decoding ```c char *base32_encode(const unsigned char *data, size_t len, cotp_error_t *err); unsigned char *base32_decode(const char *user_data, size_t data_len, cotp_error_t *err); bool is_string_valid_b32(const char *user_data); ``` Behavior: - `NULL` on error (sets `err`) - empty input → empty non-NULL string + `EMPTY_STRING` - spaces allowed - invalid base32 → `INVALID_B32_INPUT` Example — round-trip a binary buffer: ```c const unsigned char raw[] = { 0xDE, 0xAD, 0xBE, 0xEF }; cotp_error_t err; char *encoded = base32_encode(raw, sizeof raw, &err); // "326L57Y=" unsigned char *decoded = base32_decode(encoded, strlen(encoded), &err); // memcmp(raw, decoded, sizeof raw) == 0 free(encoded); free(decoded); ``` Lenient-mode caveats — the decoder targets the OTP-secret use case, not strict RFC 4648 conformance. Callers handling general-purpose Base32 should be aware: - Non-zero pad bits in the final group are accepted, not rejected (RFC 4648 §3.5 strict-mode behavior is not implemented). - Embedded NUL bytes silently truncate the input (`strlen` semantics). - Only ASCII space (0x20) is stripped — tabs, newlines, and CRs cause `INVALID_B32_INPUT`. - A single base32 character (e.g. `"J"`) is accepted and decodes to a zero-length buffer. --- ## Utilities Helpers exposed for callers that handle their own secret material. Both are thread-safe and have no internal state. ```c void cotp_secure_memzero(void *ptr, size_t len); int cotp_timing_safe_memcmp(const void *a, const void *b, size_t len); ``` - `cotp_secure_memzero` — wipes `len` bytes at `ptr` in a way the compiler must not elide (uses `memset_s` / `explicit_bzero` / volatile fallback). Safe with `ptr == NULL` or `len == 0`. Use it to scrub the Base32 secret strings you pass into `get_totp` / `get_hotp` once you no longer need them. - `cotp_timing_safe_memcmp` — constant-time byte comparison. Returns `0` on equal, non-zero otherwise. Length is treated as public information. Example — scrub a secret after use: ```c char secret[] = "HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ"; cotp_error_t err; char *code = get_totp(secret, 6, 30, COTP_SHA1, &err); /* … */ free(code); cotp_secure_memzero(secret, sizeof secret - 1); ``` --- ## Operational Notes - **System clock**: `get_totp()` reads `time(NULL)` once at call time; ensure the host clock is synchronized (NTP). A skew larger than the verifier's validation window will cause every code to be rejected. - **Validation window**: allow a small window (±1–2 periods) on the verifier side to absorb minor clock drift. - **HOTP counter persistence**: HOTP requires the caller to persist the counter across runs and increment it for every code consumed. Lose the counter and the device falls out of sync with the verifier. - **Steam TOTP secrets**: Steam stores the seed as a Base64 string on the device. Callers must Base64-decode it to raw bytes and Base32-encode those bytes before passing the result to `get_steam_totp` / `get_steam_totp_at`. This library does not perform that conversion. - **Minimum secret length**: RFC 6238 §5.1 recommends ≥160-bit shared secrets for SHA1 (20 raw bytes / 32 Base32 characters). The library accepts shorter secrets — pass them at your own cryptographic risk. - **Thread safety**: bare functions hold no global state and are safe to call concurrently from multiple threads. `cotp_ctx` is immutable after creation and may be shared. The gcrypt backend performs a one-shot library initialization on the first call; subsequent calls are inert. - **Secrets in memory**: use `cotp_secure_memzero` (see [Utilities](#utilities)) to wipe secret strings the caller owns before freeing them. The library already scrubs its internal copies. libcotp-4.2.1/SECURITY.md000066400000000000000000000023671522115210500147450ustar00rootroot00000000000000# Security Policy ## Supported Versions The following list describes whether a version is eligible or not for security updates. | Version | Supported | EOL | |---------|----------|-------------| | 4.0.x | :white_check_mark: | - | | 3.1.x | :white_check_mark: | 01-May-2026 | | 3.0.x | :x: | 30-Sep-2025 | | 2.0.x | :x: | 31-Dec-2023 | | 1.2.x | :x: | 30-Jun-2023 | | 1.1.x | :x: | 31-Dec-2021 | | 1.0.x | :x: | 31-Dec-2021 | ## Reporting a Vulnerability If you discover a security vulnerability, please report it **privately** via [e-mail](mailto:paolostivanin@users.noreply.github.com). The process is as follows: - Send me an e-mail describing the security issue. - Within **24 hours**, I will acknowledge your report and provide initial feedback (for example, whether it is indeed a vulnerability and its potential severity). - Within **7 days**, I will work on a fix and release an update. - Once the update is available, I will publish a [security advisory](https://github.com/paolostivanin/OTPClient/security/advisories). ## Recent Hardening - 2025-10-03: Strengthened base32 decoding to use exact integer sizing and tightened writes to avoid potential over-allocation and to prevent out-of-bounds writes. libcotp-4.2.1/cmake/000077500000000000000000000000001522115210500142245ustar00rootroot00000000000000libcotp-4.2.1/cmake/COTPConfig.cmake.in000066400000000000000000000002421522115210500175240ustar00rootroot00000000000000@PACKAGE_INIT@ include(CMakeFindDependencyMacro) # Consumers will link to the exported COTP::cotp target include("${CMAKE_CURRENT_LIST_DIR}/cotpTargets.cmake") libcotp-4.2.1/cmake/FindGcrypt.cmake000066400000000000000000000031761522115210500173060ustar00rootroot00000000000000# Copyright (C) 2011 Felix Geyer # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 or (at your option) # version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . find_path(GCRYPT_INCLUDE_DIR gcrypt.h) if(WIN32) set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib" ".dll" ".dll.a") endif() find_library(GCRYPT_LIBRARIES NAMES gcrypt libgcrypt) mark_as_advanced(GCRYPT_LIBRARIES GCRYPT_INCLUDE_DIR) if(GCRYPT_INCLUDE_DIR AND EXISTS "${GCRYPT_INCLUDE_DIR}/gcrypt.h") file(STRINGS "${GCRYPT_INCLUDE_DIR}/gcrypt.h" GCRYPT_H REGEX "^#define GCRYPT_VERSION \"[^\"]*\"$") string(REGEX REPLACE "^.*GCRYPT_VERSION \"([0-9]+).*$" "\\1" GCRYPT_VERSION_MAJOR "${GCRYPT_H}") string(REGEX REPLACE "^.*GCRYPT_VERSION \"[0-9]+\\.([0-9]+).*$" "\\1" GCRYPT_VERSION_MINOR "${GCRYPT_H}") string(REGEX REPLACE "^.*GCRYPT_VERSION \"[0-9]+\\.[0-9]+\\.([0-9]+).*$" "\\1" GCRYPT_VERSION_PATCH "${GCRYPT_H}") set(GCRYPT_VERSION_STRING "${GCRYPT_VERSION_MAJOR}.${GCRYPT_VERSION_MINOR}.${GCRYPT_VERSION_PATCH}") endif() include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Gcrypt DEFAULT_MSG GCRYPT_LIBRARIES GCRYPT_INCLUDE_DIR) libcotp-4.2.1/cmake/FindMbedTLS.cmake000066400000000000000000000103511522115210500172610ustar00rootroot00000000000000#*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) Daniel Stenberg, , et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # # SPDX-License-Identifier: curl # ########################################################################### # Find the mbedtls library # # Input variables: # # MBEDTLS_INCLUDE_DIR The mbedtls include directory # MBEDTLS_INCLUDE_DIRS The mbedtls include directory (deprecated) # MBEDTLS_LIBRARY Path to mbedtls library # MBEDX509_LIBRARY Path to mbedx509 library # MBEDCRYPTO_LIBRARY Path to mbedcrypto library # # Result variables: # # MBEDTLS_FOUND System has mbedtls # MBEDTLS_INCLUDE_DIRS The mbedtls include directories # MBEDTLS_LIBRARIES The mbedtls library names # MBEDTLS_VERSION Version of mbedtls if(DEFINED MBEDTLS_INCLUDE_DIRS AND NOT DEFINED MBEDTLS_INCLUDE_DIR) message(WARNING "MBEDTLS_INCLUDE_DIRS is deprecated, use MBEDTLS_INCLUDE_DIR instead.") set(MBEDTLS_INCLUDE_DIR "${MBEDTLS_INCLUDE_DIRS}") unset(MBEDTLS_INCLUDE_DIRS) endif() if(CURL_USE_PKGCONFIG) find_package(PkgConfig QUIET) pkg_check_modules(PC_MBEDTLS "mbedtls") endif() find_path(MBEDTLS_INCLUDE_DIR NAMES "mbedtls/ssl.h" HINTS ${PC_MBEDTLS_INCLUDEDIR} ${PC_MBEDTLS_INCLUDE_DIRS} ) find_library(MBEDTLS_LIBRARY NAMES "mbedtls" HINTS ${PC_MBEDTLS_LIBDIR} ${PC_MBEDTLS_LIBRARY_DIRS} ) find_library(MBEDX509_LIBRARY NAMES "mbedx509" HINTS ${PC_MBEDTLS_LIBDIR} ${PC_MBEDTLS_LIBRARY_DIRS} ) find_library(MBEDCRYPTO_LIBRARY NAMES "mbedcrypto" HINTS ${PC_MBEDTLS_LIBDIR} ${PC_MBEDTLS_LIBRARY_DIRS} ) # MbedTLS 4.0 split crypto into TF-PSA-Crypto; the PSA symbols the mbedtls backend # needs live in libtfpsacrypto. Optional: absent on 2.x/3.x (those keep the legacy # path), and some 4.x packages still re-export PSA from libmbedcrypto. find_library(TFPSACRYPTO_LIBRARY NAMES "tfpsacrypto" HINTS ${PC_MBEDTLS_LIBDIR} ${PC_MBEDTLS_LIBRARY_DIRS} ) if(PC_MBEDTLS_VERSION) set(MBEDTLS_VERSION ${PC_MBEDTLS_VERSION}) elseif(MBEDTLS_INCLUDE_DIR) if(EXISTS "${MBEDTLS_INCLUDE_DIR}/mbedtls/build_info.h") # 3.x set(_version_header "${MBEDTLS_INCLUDE_DIR}/mbedtls/build_info.h") elseif(EXISTS "${MBEDTLS_INCLUDE_DIR}/mbedtls/version.h") # 2.x set(_version_header "${MBEDTLS_INCLUDE_DIR}/mbedtls/version.h") else() unset(_version_header) endif() if(_version_header) set(_version_regex "#[\t ]*define[\t ]+MBEDTLS_VERSION_STRING[\t ]+\"([0-9.]+)\"") file(STRINGS "${_version_header}" _version_str REGEX "${_version_regex}") string(REGEX REPLACE "${_version_regex}" "\\1" _version_str "${_version_str}") set(MBEDTLS_VERSION "${_version_str}") unset(_version_regex) unset(_version_str) unset(_version_header) endif() endif() include(FindPackageHandleStandardArgs) find_package_handle_standard_args(MbedTLS REQUIRED_VARS MBEDTLS_INCLUDE_DIR MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY VERSION_VAR MBEDTLS_VERSION ) if(MBEDTLS_FOUND) set(MBEDTLS_INCLUDE_DIRS ${MBEDTLS_INCLUDE_DIR}) set(MBEDTLS_LIBRARIES ${MBEDTLS_LIBRARY} ${MBEDX509_LIBRARY} ${MBEDCRYPTO_LIBRARY}) if(TFPSACRYPTO_LIBRARY) list(APPEND MBEDTLS_LIBRARIES ${TFPSACRYPTO_LIBRARY}) endif() endif() mark_as_advanced(MBEDTLS_INCLUDE_DIR MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY TFPSACRYPTO_LIBRARY) libcotp-4.2.1/cotp.pc.in000066400000000000000000000004751522115210500150500ustar00rootroot00000000000000prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} libdir=@PKGCONFIG_TARGET_LIBS@ includedir=@PKGCONFIG_TARGET_INCLUDES@ Name: libcotp Description: C library that generates TOTP and HOTP Version: @CMAKE_PROJECT_VERSION@ URL: https://github.com/paolostivanin/libcotp Libs: -L${libdir} -lcotp Cflags: -I${includedir} libcotp-4.2.1/fuzz/000077500000000000000000000000001522115210500141425ustar00rootroot00000000000000libcotp-4.2.1/fuzz/CMakeLists.txt000066400000000000000000000016411522115210500167040ustar00rootroot00000000000000if (NOT CMAKE_C_COMPILER_ID STREQUAL "Clang") message(FATAL_ERROR "COTP_BUILD_FUZZERS requires Clang (currently: ${CMAKE_C_COMPILER_ID})") endif () set(FUZZ_FLAGS -fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer -g) add_executable(fuzz_base32_decode fuzz_base32_decode.c) target_link_libraries(fuzz_base32_decode PRIVATE cotp) target_compile_options(fuzz_base32_decode PRIVATE ${FUZZ_FLAGS}) target_link_options(fuzz_base32_decode PRIVATE ${FUZZ_FLAGS}) add_executable(fuzz_get_totp_at fuzz_get_totp_at.c) target_link_libraries(fuzz_get_totp_at PRIVATE cotp) target_compile_options(fuzz_get_totp_at PRIVATE ${FUZZ_FLAGS}) target_link_options(fuzz_get_totp_at PRIVATE ${FUZZ_FLAGS}) add_executable(fuzz_otpauth_uri fuzz_otpauth_uri.c) target_link_libraries(fuzz_otpauth_uri PRIVATE cotp) target_compile_options(fuzz_otpauth_uri PRIVATE ${FUZZ_FLAGS}) target_link_options(fuzz_otpauth_uri PRIVATE ${FUZZ_FLAGS}) libcotp-4.2.1/fuzz/fuzz_base32_decode.c000066400000000000000000000007711522115210500177530ustar00rootroot00000000000000#include #include #include #include "cotp.h" int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { if (size > 4096) return 0; char *s = malloc (size + 1); if (!s) return 0; memcpy (s, data, size); s[size] = '\0'; cotp_error_t err; uint8_t *out = base32_decode (s, size + 1, &err); free (out); // Also exercise the no-trailing-NUL path out = base32_decode (s, size, &err); free (out); free (s); return 0; } libcotp-4.2.1/fuzz/fuzz_get_totp_at.c000066400000000000000000000020361522115210500176760ustar00rootroot00000000000000#include #include #include #include "cotp.h" // Layout of input bytes: // [0] algo selector (% 3) -> COTP_SHA1 / COTP_SHA256 / COTP_SHA512 // [1] digits (% 7 + 4) -> 4..10 // [2] period (% 120 + 1) -> 1..120 // [3..10] timestamp (long, host-endian via memcpy) // [11..] secret (NUL-terminated copy) int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { if (size < 11 || size > 4096) return 0; int algo = data[0] % 3; int digits = (data[1] % 7) + 4; int period = (data[2] % 120) + 1; long ts; memcpy (&ts, data + 3, sizeof (ts)); size_t secret_len = size - 11; char *secret = malloc (secret_len + 1); if (!secret) return 0; memcpy (secret, data + 11, secret_len); secret[secret_len] = '\0'; cotp_error_t err; char *otp = get_totp_at (secret, ts, digits, period, algo, &err); free (otp); char *hotp = get_hotp (secret, ts < 0 ? 0 : ts, digits, algo, &err); free (hotp); free (secret); return 0; } libcotp-4.2.1/fuzz/fuzz_otpauth_uri.c000066400000000000000000000013611522115210500177300ustar00rootroot00000000000000#include #include #include #include "cotp.h" int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { if (size > 4096) return 0; char *s = malloc (size + 1); if (!s) return 0; memcpy (s, data, size); s[size] = '\0'; cotp_error_t err; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (s, &err); if (u) { // Round-trip: build back, then parse again — should not crash. char *rebuilt = cotp_otpauth_uri_build (u, &err); if (rebuilt) { cotp_otpauth_uri *u2 = cotp_otpauth_uri_parse (rebuilt, &err); cotp_otpauth_uri_free (u2); free (rebuilt); } cotp_otpauth_uri_free (u); } free (s); return 0; } libcotp-4.2.1/src/000077500000000000000000000000001522115210500137335ustar00rootroot00000000000000libcotp-4.2.1/src/cotp.h000066400000000000000000000341351522115210500150570ustar00rootroot00000000000000#pragma once #include #include #include #if defined(__GNUC__) || defined(__clang__) #define COTP_API __attribute__((visibility("default"))) #define COTP_WUR __attribute__((warn_unused_result)) #else #define COTP_API #define COTP_WUR #endif #define COTP_VERSION_MAJOR 4 #define COTP_VERSION_MINOR 2 #define COTP_VERSION_PATCH 1 #define COTP_VERSION_STRING "4.2.1" #define COTP_VERSION_NUMBER ((COTP_VERSION_MAJOR * 10000) + (COTP_VERSION_MINOR * 100) + COTP_VERSION_PATCH) #define COTP_SHA1 0 #define COTP_SHA256 1 #define COTP_SHA512 2 #define MIN_DIGITS 4 #define MAX_DIGITS 10 // YAOTP (Yandex.Key) fixed parameters. #define COTP_YAOTP_PERIOD 30 #define COTP_YAOTP_DIGITS 8 #define COTP_YAOTP_MIN_PIN_LENGTH 4 #define COTP_YAOTP_MAX_PIN_LENGTH 16 typedef enum cotp_error { NO_ERROR = 0, VALID, WCRYPT_VERSION_MISMATCH, INVALID_B32_INPUT, INVALID_ALGO, INVALID_DIGITS, INVALID_PERIOD, MEMORY_ALLOCATION_ERROR, INVALID_USER_INPUT, EMPTY_STRING, MISSING_LEADING_ZERO, INVALID_COUNTER, WHMAC_ERROR, INVALID_YAOTP_SECRET_LENGTH, INVALID_YAOTP_SECRET_CRC, INVALID_YAOTP_PIN } cotp_error_t; // Opaque context for repeated OTP computations (optional ergonomic API) typedef struct cotp_ctx cotp_ctx; #ifdef __cplusplus extern "C" { #endif #ifdef COTP_ENABLE_VALIDATION /** * validate_totp_in_window * * Validates a user-provided TOTP code within a symmetric time window (in periods) around a timestamp. * Returns 1 if it matches for any offset in [-window, +window], 0 otherwise. * On success and match, sets matched_delta to the offset that matched (may be 0). On general failure, returns 0 and sets err_code. * `window` is clamped to a maximum of 1024 periods; values above that return INVALID_USER_INPUT. */ COTP_API COTP_WUR int validate_totp_in_window(const char* user_code, const char* base32_encoded_secret, long timestamp, int digits, int period, int sha_algo, int window, int* matched_delta, cotp_error_t* err_code); /** * cotp_ctx_validate_totp * * Context-API wrapper around validate_totp_in_window. Uses ctx->digits, ctx->period, ctx->algo. * Returns 1 on match, 0 otherwise (or on error). NULL ctx => INVALID_USER_INPUT, returns 0. */ COTP_API COTP_WUR int cotp_ctx_validate_totp(cotp_ctx* ctx, const char* user_code, const char* base32_encoded_secret, long timestamp, int window, int* matched_delta, cotp_error_t* err); #endif /** * cotp_strerror * * Returns a static, NUL-terminated description of the given error code. * The returned pointer must NOT be freed. Always returns a non-NULL string; * unknown values map to "unknown error". */ COTP_API COTP_WUR const char *cotp_strerror(cotp_error_t err); /** * cotp_secure_memzero * * Wipes `len` bytes at `ptr` in a way the compiler must not elide. Use to scrub * secret material (decoded keys, OTP buffers, secret strings the caller owns) * before freeing or returning. Safe to call with ptr == NULL or len == 0. */ COTP_API void cotp_secure_memzero(void *ptr, size_t len); /** * cotp_timing_safe_memcmp * * Constant-time byte comparison. Returns 0 if the two buffers are equal, * non-zero otherwise. The runtime is independent of where the first differing * byte sits, so it is safe for comparing OTPs, MACs, or other secret-derived * tokens. Length itself is treated as public; the caller must ensure both * buffers have at least `len` accessible bytes. */ COTP_API COTP_WUR int cotp_timing_safe_memcmp(const void *a, const void *b, size_t len); // Context helpers COTP_API COTP_WUR cotp_ctx* cotp_ctx_create(int digits, int period, int sha_algo); COTP_API void cotp_ctx_free(cotp_ctx* ctx); COTP_API COTP_WUR char* cotp_ctx_totp_at(cotp_ctx* ctx, const char* base32_encoded_secret, long timestamp, cotp_error_t* err); COTP_API COTP_WUR char* cotp_ctx_totp(cotp_ctx* ctx, const char* base32_encoded_secret, cotp_error_t* err); COTP_API COTP_WUR char* cotp_ctx_hotp(cotp_ctx* ctx, const char* base32_encoded_secret, long counter, cotp_error_t* err); // Steam variants ignore ctx->digits and ctx->algo (Steam fixes both); only ctx->period is used. COTP_API COTP_WUR char* cotp_ctx_steam_totp(cotp_ctx* ctx, const char* base32_encoded_secret, cotp_error_t* err); COTP_API COTP_WUR char* cotp_ctx_steam_totp_at(cotp_ctx* ctx, const char* base32_encoded_secret, long timestamp, cotp_error_t* err); // YAOTP variants ignore ctx->{digits,period,algo} entirely (all fixed by the algorithm). // The PIN is supplied per-call; libcotp does not retain it. The caller owns the PIN buffer // and is responsible for wiping it (cotp_secure_memzero) after use. COTP_API COTP_WUR char* cotp_ctx_yaotp(cotp_ctx* ctx, const char* base32_encoded_secret, const char* pin, cotp_error_t* err); COTP_API COTP_WUR char* cotp_ctx_yaotp_at(cotp_ctx* ctx, const char* base32_encoded_secret, const char* pin, long timestamp, cotp_error_t* err); /** * base32_encode * * Ownership: returns a newly allocated, NUL-terminated string on success; caller must free() it. * On error: returns NULL and sets err_code. */ COTP_API COTP_WUR char *base32_encode (const uint8_t *user_data, size_t data_len, cotp_error_t *err_code); /** * base32_decode * * Ownership: returns a newly allocated buffer of length data_len_out on success; caller must free() it. * The returned data preserves the input NUL when the original encoded content represented it. * On error: returns NULL and sets err_code. */ COTP_API COTP_WUR uint8_t *base32_decode (const char *user_data_untrimmed, size_t data_len, cotp_error_t *err_code); /** * is_string_valid_b32 * * Checks whether a string is valid Base32 (ignoring ASCII spaces). Does not allocate. */ COTP_API COTP_WUR bool is_string_valid_b32 (const char *user_data); /** * get_hotp * * Ownership: returns a newly allocated, zero-padded OTP string of requested width; caller must free(). * On error: returns NULL and sets err_code. */ COTP_API COTP_WUR char *get_hotp (const char *base32_encoded_secret, long counter, int digits, int sha_algo, cotp_error_t *err_code); /** * get_totp * * Ownership: returns a newly allocated, zero-padded OTP string; caller must free(). * On error: returns NULL and sets err_code. */ COTP_API COTP_WUR char *get_totp (const char *base32_encoded_secret, int digits, int period, int sha_algo, cotp_error_t *err_code); /** * get_steam_totp * * Ownership: returns a newly allocated Steam-style OTP string; caller must free(). * On error: returns NULL and sets err_code. */ COTP_API COTP_WUR char *get_steam_totp (const char *base32_encoded_secret, int period, cotp_error_t *err_code); /** * get_totp_at * * Ownership: returns a newly allocated, zero-padded OTP string; caller must free(). * On error: returns NULL and sets err_code. */ COTP_API COTP_WUR char *get_totp_at (const char *base32_encoded_secret, long time, int digits, int period, int sha_algo, cotp_error_t *err_code); /** * get_steam_totp_at * * Ownership: returns a newly allocated Steam-style OTP string; caller must free(). * On error: returns NULL and sets err_code. */ COTP_API COTP_WUR char *get_steam_totp_at (const char *base32_encoded_secret, long timestamp, int period, cotp_error_t *err_code); /** * get_yaotp / get_yaotp_at * * Generates a YAOTP (Yandex.Key) code: 8 lowercase letters from alphabet 'a'..'z', period 30 s. * The secret must be a base32-encoded Yandex-format blob (key + userId + pinLength + CRC-13); * its decoded length is fixed at 26 bytes. The PIN must be a NUL-terminated string of ASCII * digits whose length matches the value encoded inside the secret (see cotp_yaotp_secret_pin_length). * * Ownership: returns a newly allocated 9-byte NUL-terminated code; caller must free(). * On error: returns NULL and sets err_code (INVALID_YAOTP_SECRET_LENGTH / _CRC, INVALID_YAOTP_PIN, * INVALID_B32_INPUT, MEMORY_ALLOCATION_ERROR, WHMAC_ERROR). * * The caller owns the PIN buffer. libcotp does not copy or retain it, but it cannot scrub a * `const char *` it does not own — the caller should cotp_secure_memzero() the PIN after use. */ COTP_API COTP_WUR char *get_yaotp (const char *base32_encoded_secret, const char *pin, cotp_error_t *err_code); COTP_API COTP_WUR char *get_yaotp_at (const char *base32_encoded_secret, const char *pin, long timestamp, cotp_error_t *err_code); /** * cotp_yaotp_secret_pin_length * * Returns the PIN length (4..16) encoded inside a Yandex-format YAOTP secret. Useful for UIs * that need to render the PIN-entry field before the user enters anything. * Returns -1 on error and sets *err_code. */ COTP_API COTP_WUR int cotp_yaotp_secret_pin_length (const char *base32_encoded_secret, cotp_error_t *err_code); /** * otp_to_int * * Converts a digit string (e.g., from get_totp/get_hotp) to an integer. If leading zeros are present, * the returned integer will naturally drop them; err_code is set to MISSING_LEADING_ZERO in that case. * On invalid input returns -1 and sets err_code to INVALID_USER_INPUT. */ COTP_API COTP_WUR int64_t otp_to_int (const char *otp, cotp_error_t *err_code); // otpauth:// URI parser/builder (Google Authenticator de-facto format). typedef enum { COTP_OTPAUTH_TOTP = 0, COTP_OTPAUTH_HOTP = 1 } cotp_otpauth_type; typedef struct { cotp_otpauth_type type; char *issuer; // owned, may be NULL char *account; // owned, may be NULL char *secret; // owned, base32-encoded; non-NULL on successful parse int algo; // COTP_SHA1 / COTP_SHA256 / COTP_SHA512 int digits; // 4-10 int period; // 1-120 (TOTP only) long counter; // >= 0 (HOTP only) } cotp_otpauth_uri; /** * cotp_otpauth_uri_parse * * Parses an otpauth:// URI. On success, returns a heap-allocated struct that the caller must * release via cotp_otpauth_uri_free(). Defaults for missing query parameters: algorithm=SHA1, * digits=6, period=30. For HOTP the `counter` parameter is required. * Returns NULL on error and sets *err. Unknown query keys are silently ignored. * If both label-issuer ("Issuer:Account") and "&issuer=" query parameter are present, the label-issuer wins. */ COTP_API COTP_WUR cotp_otpauth_uri *cotp_otpauth_uri_parse (const char *uri, cotp_error_t *err); /** * cotp_otpauth_uri_build * * Builds an otpauth:// URI from the given struct. Returns a newly allocated NUL-terminated string * the caller must free(). Validates fields with the same bounds as get_hotp/get_totp_at; returns * NULL with *err set on validation failure or allocation error. */ COTP_API COTP_WUR char *cotp_otpauth_uri_build (const cotp_otpauth_uri *u, cotp_error_t *err); /** * cotp_otpauth_uri_free * * Releases a struct returned by cotp_otpauth_uri_parse(). NULL-safe. Securely zeroes the * `secret` field before freeing. */ COTP_API void cotp_otpauth_uri_free (cotp_otpauth_uri *u); // YAOTP (Yandex.Key) otpauth URI parser/builder. // Lives in a separate struct from cotp_otpauth_uri to avoid bloating the standard URI type // with Yandex-specific opaque pass-throughs (track_id, uid). typedef struct { char *secret; // owned, base32-encoded Yandex-format blob; non-NULL on successful parse char *account; // owned, may be NULL (maps to the "name" parameter in Yandex URIs) char *issuer; // owned, may be NULL char *track_id; // owned opaque pass-through, may be NULL char *uid; // owned opaque pass-through, may be NULL int pin_length; // 4..16 } cotp_yaotp_uri; /** * cotp_yaotp_uri_parse * * Parses an `otpauth://yaotp/?secret=...&pin_length=N[&issuer=...][&track_id=...][&uid=...]` URI. * On success, returns a heap-allocated struct that the caller must release via cotp_yaotp_uri_free(). * pin_length must be present and in [COTP_YAOTP_MIN_PIN_LENGTH, COTP_YAOTP_MAX_PIN_LENGTH]. * Returns NULL on error and sets *err. */ COTP_API COTP_WUR cotp_yaotp_uri *cotp_yaotp_uri_parse (const char *uri, cotp_error_t *err); /** * cotp_yaotp_uri_build * * Builds an `otpauth://yaotp/...` URI from the given struct. Returns a newly allocated NUL-terminated * string the caller must free(). Returns NULL with *err set on validation failure or allocation error. */ COTP_API COTP_WUR char *cotp_yaotp_uri_build (const cotp_yaotp_uri *u, cotp_error_t *err); /** * cotp_yaotp_uri_free * * Releases a struct returned by cotp_yaotp_uri_parse(). NULL-safe. Securely zeroes the * `secret` field before freeing. */ COTP_API void cotp_yaotp_uri_free (cotp_yaotp_uri *u); #ifdef __cplusplus } #endif libcotp-4.2.1/src/ctx.c000066400000000000000000000064541522115210500147060ustar00rootroot00000000000000#include #include "cotp.h" struct cotp_ctx { int digits; int period; int algo; }; cotp_ctx* cotp_ctx_create(int digits, int period, int sha_algo) { if (digits < MIN_DIGITS || digits > MAX_DIGITS) { return NULL; } if (period <= 0 || period > 120) { return NULL; } if (sha_algo != COTP_SHA1 && sha_algo != COTP_SHA256 && sha_algo != COTP_SHA512) { return NULL; } cotp_ctx* ctx = (cotp_ctx*)calloc(1, sizeof(cotp_ctx)); if (!ctx) return NULL; ctx->digits = digits; ctx->period = period; ctx->algo = sha_algo; return ctx; } void cotp_ctx_free(cotp_ctx* ctx) { if (!ctx) return; free(ctx); } char* cotp_ctx_totp_at(cotp_ctx* ctx, const char* base32_encoded_secret, long timestamp, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; return NULL; } return get_totp_at(base32_encoded_secret, timestamp, ctx->digits, ctx->period, ctx->algo, err); } char* cotp_ctx_totp(cotp_ctx* ctx, const char* base32_encoded_secret, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; return NULL; } return get_totp(base32_encoded_secret, ctx->digits, ctx->period, ctx->algo, err); } char* cotp_ctx_hotp(cotp_ctx* ctx, const char* base32_encoded_secret, long counter, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; return NULL; } return get_hotp(base32_encoded_secret, counter, ctx->digits, ctx->algo, err); } char* cotp_ctx_steam_totp(cotp_ctx* ctx, const char* base32_encoded_secret, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; return NULL; } return get_steam_totp(base32_encoded_secret, ctx->period, err); } char* cotp_ctx_steam_totp_at(cotp_ctx* ctx, const char* base32_encoded_secret, long timestamp, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; return NULL; } return get_steam_totp_at(base32_encoded_secret, timestamp, ctx->period, err); } char* cotp_ctx_yaotp(cotp_ctx* ctx, const char* base32_encoded_secret, const char* pin, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; return NULL; } return get_yaotp(base32_encoded_secret, pin, err); } char* cotp_ctx_yaotp_at(cotp_ctx* ctx, const char* base32_encoded_secret, const char* pin, long timestamp, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; return NULL; } return get_yaotp_at(base32_encoded_secret, pin, timestamp, err); } #ifdef COTP_ENABLE_VALIDATION int cotp_ctx_validate_totp(cotp_ctx* ctx, const char* user_code, const char* base32_encoded_secret, long timestamp, int window, int* matched_delta, cotp_error_t* err) { if (!ctx) { if (err) *err = INVALID_USER_INPUT; if (matched_delta) *matched_delta = 0; return 0; } return validate_totp_in_window(user_code, base32_encoded_secret, timestamp, ctx->digits, ctx->period, ctx->algo, window, matched_delta, err); } #endif libcotp-4.2.1/src/otp.c000066400000000000000000000277011522115210500147100ustar00rootroot00000000000000#include #include #include #include #include #include #include "whmac.h" #include "cotp.h" #include "utils/secure_zero.h" static size_t b32_decoded_len_from_str(const char *s) { if (!s) return 0; size_t chars = 0; for (const char *p = s; *p; ++p) { if (*p != '=' && *p != ' ') { ++chars; } } return (chars * 5) / 8; // floor } #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define REVERSE_BYTES(C, C_reverse_byte_order) \ do { \ for (int j = 0, i = 7; j < 8; j++, i--) { \ (C_reverse_byte_order)[i] = ((unsigned char *)&(C))[j]; \ } \ } while (0) #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define REVERSE_BYTES(C, C_reverse_byte_order) \ do { \ for (int j = 0; j < 8; j++) { \ (C_reverse_byte_order)[j] = ((unsigned char *)&(C))[j]; \ } \ } while (0) #else #error "Unknown endianness" #endif static char *normalize_secret (const char *K); static char *get_steam_code (const unsigned char *hmac, whmac_handle_t *hd); static int truncate_otp (const unsigned char *hmac, int digits_length, whmac_handle_t *hd); static unsigned char *compute_hmac (const char *K, long C, whmac_handle_t *hd, cotp_error_t *err_code); static char *finalize (int digits_length, int tk); static int check_period (int period); static int check_otp_len (int digits_length); static int check_algo (int algo); char * get_hotp (const char *secret, long counter, int digits, int algo, cotp_error_t *err_code) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err_code ? err_code : &local_err; if (secret == NULL) { *errp = INVALID_USER_INPUT; return NULL; } if (whmac_check () == -1) { *errp = WCRYPT_VERSION_MISMATCH; return NULL; } if (check_algo (algo) == INVALID_ALGO) { *errp = INVALID_ALGO; return NULL; } if (check_otp_len (digits) == INVALID_DIGITS) { *errp = INVALID_DIGITS; return NULL; } if (counter < 0) { *errp = INVALID_COUNTER; return NULL; } whmac_handle_t *hd = whmac_gethandle (algo); if (hd == NULL) { *errp = WHMAC_ERROR; return NULL; } unsigned char *hmac = compute_hmac (secret, counter, hd, errp); if (hmac == NULL) { whmac_freehandle (hd); return NULL; } size_t dlen = whmac_getlen(hd); int tk = truncate_otp (hmac, digits, hd); whmac_freehandle (hd); cotp_secure_memzero(hmac, dlen); free (hmac); if (tk == INT_MIN) { *errp = WHMAC_ERROR; return NULL; } *errp = NO_ERROR; return finalize (digits, tk); } char * get_totp_at (const char *secret, long current_timestamp, int digits, int period, int algo, cotp_error_t *err_code) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err_code ? err_code : &local_err; if (secret == NULL) { *errp = INVALID_USER_INPUT; return NULL; } if (whmac_check () == -1) { *errp = WCRYPT_VERSION_MISMATCH; return NULL; } if (check_otp_len (digits) == INVALID_DIGITS) { *errp = INVALID_DIGITS; return NULL; } if (check_period (period) == INVALID_PERIOD) { *errp = INVALID_PERIOD; return NULL; } cotp_error_t err; char *totp = get_hotp (secret, current_timestamp / period, digits, algo, &err); if (err != NO_ERROR) { *errp = err; return NULL; } *errp = NO_ERROR; return totp; } char * get_totp (const char *secret, int digits, int period, int algo, cotp_error_t *err_code) { return get_totp_at (secret, (long)time(NULL), digits, period, algo, err_code); } char * get_steam_totp (const char *secret, int period, cotp_error_t *err_code) { // AFAIK, the secret is stored base64 encoded on the device. As I don't have time to waste on reverse engineering // this non-standard solution, the user is responsible for decoding the secret in whatever format this is and then // providing the library with the secret base32 encoded. return get_steam_totp_at (secret, (long)time(NULL), period, err_code); } char * get_steam_totp_at (const char *secret, long current_timestamp, int period, cotp_error_t *err_code) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err_code ? err_code : &local_err; if (secret == NULL) { *errp = INVALID_USER_INPUT; return NULL; } if (whmac_check () == -1) { *errp = WCRYPT_VERSION_MISMATCH; return NULL; } if (check_period (period) == INVALID_PERIOD) { *errp = INVALID_PERIOD; return NULL; } whmac_handle_t *hd = whmac_gethandle (COTP_SHA1); if (hd == NULL) { *errp = WHMAC_ERROR; return NULL; } unsigned char *hmac = compute_hmac (secret, current_timestamp / period, hd, errp); if (hmac == NULL) { whmac_freehandle (hd); return NULL; } char *totp = get_steam_code (hmac, hd); size_t dlen = whmac_getlen(hd); whmac_freehandle (hd); if (totp == NULL) { *errp = WHMAC_ERROR; } else { *errp = NO_ERROR; } cotp_secure_memzero(hmac, dlen); free(hmac); return totp; } int64_t otp_to_int (const char *otp, cotp_error_t *err_code) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err_code ? err_code : &local_err; if (otp == NULL) { *errp = INVALID_USER_INPUT; return -1; } size_t len = strlen (otp); if (len < MIN_DIGITS || len > MAX_DIGITS) { *errp = INVALID_USER_INPUT; return -1; } for (size_t i = 0; i < len; i++) { if (!isdigit((unsigned char)otp[i])) { *errp = INVALID_USER_INPUT; return -1; } } if (otp[0] == '0') { *errp = MISSING_LEADING_ZERO; } else { *errp = NO_ERROR; } return strtoll (otp, NULL, 10); } static char * normalize_secret (const char *K) { char *nK = calloc (strlen (K) + 1, 1); if (nK == NULL) { return nK; } for (int i = 0, j = 0; K[i] != '\0'; i++) { if (K[i] != ' ') { nK[j++] = islower((unsigned char)K[i]) ? (char) toupper((unsigned char)K[i]) : K[i]; } } return nK; } static char * get_steam_code (const unsigned char *hmac, whmac_handle_t *hd) { size_t hlen = whmac_getlen(hd); if (hlen < 4) { return NULL; } int offset = (hmac[hlen-1] & 0x0f); if ((size_t)offset + 3 >= hlen) { return NULL; } // Starting from the offset, take the successive 4 bytes while stripping the topmost bit to prevent it being handled as a signed integer uint32_t bin_code = ((uint32_t)(hmac[offset] & 0x7f) << 24) | ((uint32_t)(hmac[offset + 1] & 0xff) << 16) | ((uint32_t)(hmac[offset + 2] & 0xff) << 8) | ((uint32_t)(hmac[offset + 3] & 0xff)); const char steam_alphabet[] = "23456789BCDFGHJKMNPQRTVWXY"; char code[6]; size_t steam_alphabet_len = strlen (steam_alphabet); for (int i = 0; i < 5; i++) { uint32_t mod = bin_code % (uint32_t)steam_alphabet_len; bin_code = bin_code / (uint32_t)steam_alphabet_len; code[i] = steam_alphabet[mod]; } code[5] = '\0'; return strdup (code); } static int truncate_otp (const unsigned char *hmac, int digits_length, whmac_handle_t *hd) { // take the lower four bits of the last byte size_t hlen = whmac_getlen(hd); if (hlen < 4) { return INT_MIN; } int offset = hmac[hlen - 1] & 0x0f; if ((size_t)offset + 3 >= hlen) { return INT_MIN; } // Starting from the offset, take the successive 4 bytes while stripping the topmost bit to prevent it being handled as a signed integer uint32_t bin_code = ((uint32_t)(hmac[offset] & 0x7f) << 24) | ((uint32_t)(hmac[offset + 1] & 0xff) << 16) | ((uint32_t)(hmac[offset + 2] & 0xff) << 8) | ((uint32_t)(hmac[offset + 3] & 0xff)); uint64_t mod = 1; for (int i = 0; i < digits_length; ++i) { mod *= 10ULL; } int token = (int)(((uint64_t)bin_code) % mod); return token; } static unsigned char * compute_hmac (const char *K, long C, whmac_handle_t *hd, cotp_error_t *err_code) { if (err_code == NULL) { return NULL; } if (K == NULL) { *err_code = INVALID_USER_INPUT; return NULL; } char *normalized_K = normalize_secret (K); if (normalized_K == NULL) { *err_code = MEMORY_ALLOCATION_ERROR; return NULL; } if (normalized_K[0] == '\0') { cotp_secure_memzero(normalized_K, 1); free(normalized_K); *err_code = EMPTY_STRING; return NULL; } size_t secret_len = b32_decoded_len_from_str(normalized_K); size_t normalized_K_len = strlen(normalized_K); unsigned char *secret = base32_decode (normalized_K, normalized_K_len, err_code); cotp_secure_memzero(normalized_K, normalized_K_len); free (normalized_K); if (secret == NULL) { return NULL; } if (*err_code != NO_ERROR) { cotp_secure_memzero(secret, secret_len); free(secret); return NULL; } unsigned char C_reverse_byte_order[8]; REVERSE_BYTES(C, C_reverse_byte_order); cotp_error_t err = whmac_setkey (hd, secret, secret_len); if (err) { cotp_secure_memzero(secret, secret_len); free (secret); *err_code = WHMAC_ERROR; return NULL; } if (whmac_update (hd, C_reverse_byte_order, sizeof(C_reverse_byte_order)) != NO_ERROR) { cotp_secure_memzero(secret, secret_len); free (secret); *err_code = WHMAC_ERROR; return NULL; } size_t dlen = whmac_getlen (hd); unsigned char *hmac = calloc (dlen, 1); if (hmac == NULL) { cotp_secure_memzero(secret, secret_len); free (secret); *err_code = MEMORY_ALLOCATION_ERROR; return NULL; } ssize_t flen = whmac_finalize (hd, hmac, dlen); if (flen < 0) { cotp_secure_memzero(hmac, dlen); free (hmac); cotp_secure_memzero(secret, secret_len); free (secret); *err_code = WHMAC_ERROR; return NULL; } cotp_secure_memzero(secret, secret_len); free (secret); return hmac; } static char * finalize (int digits_length, int tk) { char *token = calloc (digits_length + 1, 1); if (token == NULL) { return NULL; } // Print with leading zeros without building an intermediate format string snprintf (token, digits_length + 1, "%0*d", digits_length, tk); return token; } static int check_period (int period) { return (period <= 0 || period > 120) ? INVALID_PERIOD : VALID; } static int check_otp_len (int digits_length) { return (digits_length < MIN_DIGITS || digits_length > MAX_DIGITS) ? INVALID_DIGITS : VALID; } static int check_algo (int algo) { return (algo != COTP_SHA1 && algo != COTP_SHA256 && algo != COTP_SHA512) ? INVALID_ALGO : VALID; } libcotp-4.2.1/src/strerror.c000066400000000000000000000024411522115210500157620ustar00rootroot00000000000000#include "cotp.h" const char * cotp_strerror (cotp_error_t err) { switch (err) { case NO_ERROR: return "no error"; case VALID: return "OTP validated"; case WCRYPT_VERSION_MISMATCH: return "crypto backend version mismatch"; case INVALID_B32_INPUT: return "invalid base32 input"; case INVALID_ALGO: return "invalid algorithm"; case INVALID_DIGITS: return "invalid digits (must be 4-10)"; case INVALID_PERIOD: return "invalid period (must be 1-120)"; case MEMORY_ALLOCATION_ERROR: return "memory allocation failed"; case INVALID_USER_INPUT: return "invalid user input"; case EMPTY_STRING: return "empty string"; case MISSING_LEADING_ZERO: return "leading zero dropped during conversion"; case INVALID_COUNTER: return "invalid counter (must be >= 0)"; case WHMAC_ERROR: return "HMAC computation error"; case INVALID_YAOTP_SECRET_LENGTH: return "YAOTP secret too short"; case INVALID_YAOTP_SECRET_CRC: return "YAOTP secret checksum invalid"; case INVALID_YAOTP_PIN: return "YAOTP PIN invalid (length or non-digit)"; } return "unknown error"; } libcotp-4.2.1/src/utils/000077500000000000000000000000001522115210500150735ustar00rootroot00000000000000libcotp-4.2.1/src/utils/base32.c000066400000000000000000000231301522115210500163150ustar00rootroot00000000000000#include #include #include "../cotp.h" #include "secure_zero.h" #define BITS_PER_BYTE 8 #define BITS_PER_B32_BLOCK 5 // 64 MB should be more than enough #define MAX_ENCODE_INPUT_LEN (64*1024*1024) // if 64 MB of data is encoded than it should be also possible to decode it. That's why a bigger input is allowed for decoding #define MAX_DECODE_BASE32_INPUT_LEN ((MAX_ENCODE_INPUT_LEN * 8 + 4) / 5) static const uint8_t b32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; // O(1) lookup table for base32 character → index (0-31), -1 for invalid static const int8_t b32_char_index[256] = { ['A'] = 0, ['B'] = 1, ['C'] = 2, ['D'] = 3, ['E'] = 4, ['F'] = 5, ['G'] = 6, ['H'] = 7, ['I'] = 8, ['J'] = 9, ['K'] = 10, ['L'] = 11, ['M'] = 12, ['N'] = 13, ['O'] = 14, ['P'] = 15, ['Q'] = 16, ['R'] = 17, ['S'] = 18, ['T'] = 19, ['U'] = 20, ['V'] = 21, ['W'] = 22, ['X'] = 23, ['Y'] = 24, ['Z'] = 25, ['2'] = 26, ['3'] = 27, ['4'] = 28, ['5'] = 29, ['6'] = 30, ['7'] = 31, }; // Static const validity table for base32 characters (A-Z, a-z, 2-7, =) static const uint8_t b32_valid[128] = { ['A'] = 1, ['B'] = 1, ['C'] = 1, ['D'] = 1, ['E'] = 1, ['F'] = 1, ['G'] = 1, ['H'] = 1, ['I'] = 1, ['J'] = 1, ['K'] = 1, ['L'] = 1, ['M'] = 1, ['N'] = 1, ['O'] = 1, ['P'] = 1, ['Q'] = 1, ['R'] = 1, ['S'] = 1, ['T'] = 1, ['U'] = 1, ['V'] = 1, ['W'] = 1, ['X'] = 1, ['Y'] = 1, ['Z'] = 1, ['a'] = 1, ['b'] = 1, ['c'] = 1, ['d'] = 1, ['e'] = 1, ['f'] = 1, ['g'] = 1, ['h'] = 1, ['i'] = 1, ['j'] = 1, ['k'] = 1, ['l'] = 1, ['m'] = 1, ['n'] = 1, ['o'] = 1, ['p'] = 1, ['q'] = 1, ['r'] = 1, ['s'] = 1, ['t'] = 1, ['u'] = 1, ['v'] = 1, ['w'] = 1, ['x'] = 1, ['y'] = 1, ['z'] = 1, ['2'] = 1, ['3'] = 1, ['4'] = 1, ['5'] = 1, ['6'] = 1, ['7'] = 1, ['='] = 1, }; static int get_char_index (uint8_t c); static bool valid_b32_str (const char *str); static bool has_space (const char *str); static cotp_error_t check_input (const uint8_t *user_data, size_t data_len, size_t max_len); static int strip_char (char *str); // The encoding process represents 40-bit groups of input bits as output strings of 8 encoded characters. The input data must be null terminated. char * base32_encode (const uint8_t *user_data, size_t data_len, cotp_error_t *err_code) { cotp_error_t error = check_input (user_data, data_len, MAX_ENCODE_INPUT_LEN); if (error == EMPTY_STRING) { char *empty = strdup (""); if (empty == NULL) { *err_code = MEMORY_ALLOCATION_ERROR; return NULL; } *err_code = error; return empty; } if (error != NO_ERROR) { *err_code = error; return NULL; } size_t user_data_chars = 0, total_bits = 0; int num_of_equals = 0; int null_terminated = false; if (user_data[data_len - 1] == '\0' && memchr(user_data, '\0', data_len - 1) == NULL) { // the user might give the input with the null byte, we need to check for that null_terminated = true; } for (size_t i = 0; i < data_len; i++) { if (null_terminated == true && user_data[i] == '\0' && i == data_len-1) { break; } total_bits += 8; user_data_chars += 1; } switch (total_bits % 40) { case 8: num_of_equals = 6; break; case 16: num_of_equals = 4; break; case 24: num_of_equals = 3; break; case 32: num_of_equals = 1; break; } size_t output_length = (user_data_chars * 8 + 4) / 5; char *encoded_data = calloc (output_length + num_of_equals + 1, 1); if (encoded_data == NULL) { *err_code = MEMORY_ALLOCATION_ERROR; return NULL; } for (size_t i = 0, j = 0; i < user_data_chars; i += 5) { uint64_t quintuple = 0; for (size_t k = 0; k < 5; k++) { quintuple = (quintuple << 8) | (i + k < user_data_chars ? user_data[i + k] : 0); } for (int shift = 35; shift >= 0; shift -= 5) { encoded_data[j++] = (char)b32_alphabet[(quintuple >> shift) & 0x1F]; } } for (int i = 0; i < num_of_equals; i++) { encoded_data[output_length + i] = '='; } encoded_data[output_length + num_of_equals] = '\0'; *err_code = NO_ERROR; return encoded_data; } uint8_t * base32_decode (const char *user_data_untrimmed, size_t data_len, cotp_error_t *err_code) { cotp_error_t error = check_input ((uint8_t *)user_data_untrimmed, data_len, MAX_DECODE_BASE32_INPUT_LEN); if (error == EMPTY_STRING) { char *empty = strdup (""); if (empty == NULL) { *err_code = MEMORY_ALLOCATION_ERROR; return NULL; } *err_code = error; return (uint8_t *)empty; } if (error != NO_ERROR) { *err_code = error; return NULL; } char *user_data = strdup (user_data_untrimmed); if (user_data == NULL) { *err_code = MEMORY_ALLOCATION_ERROR; return NULL; } size_t user_data_buflen = strlen (user_data); (void)strip_char (user_data); // After strip_char, iterate by the actual NUL-terminated content length — // never by the caller-supplied data_len, which may exceed the buffer when // user_data_untrimmed contains embedded NULs (strdup stops at the first one). size_t user_data_len = strlen (user_data); if (!is_string_valid_b32 (user_data)) { cotp_secure_memzero (user_data, user_data_buflen); free (user_data); *err_code = INVALID_B32_INPUT; return NULL; } size_t user_data_chars = 0; for (size_t i = 0; i < user_data_len; i++) { if (user_data[i] != '=') { user_data_chars += 1; } } // Compute exact maximum output length as floor(chars * 5 / 8) size_t output_length = (user_data_chars * 5) / 8; uint8_t *decoded_data = calloc(output_length + 1, 1); if (decoded_data == NULL) { cotp_secure_memzero (user_data, user_data_buflen); free (user_data); *err_code = MEMORY_ALLOCATION_ERROR; return NULL; } uint8_t mask, current_byte = 0; int bits_left = 8; size_t j = 0; for (size_t i = 0; i < user_data_chars; i++) { int char_index = get_char_index ((uint8_t)user_data[i]); if (bits_left > BITS_PER_B32_BLOCK) { mask = (uint8_t)char_index << (bits_left - BITS_PER_B32_BLOCK); current_byte |= mask; bits_left -= BITS_PER_B32_BLOCK; } else { mask = (uint8_t)char_index >> (BITS_PER_B32_BLOCK - bits_left); current_byte |= mask; if (j < output_length) { decoded_data[j++] = current_byte; } current_byte = (uint8_t)(char_index << (BITS_PER_BYTE - BITS_PER_B32_BLOCK + bits_left)); bits_left += BITS_PER_BYTE - BITS_PER_B32_BLOCK; } } decoded_data[j] = '\0'; cotp_secure_memzero (user_data, user_data_buflen); free (user_data); *err_code = NO_ERROR; return decoded_data; } bool is_string_valid_b32 (const char *user_data) { if (user_data == NULL) { return false; } if (has_space (user_data)) { char *trimmed = strdup (user_data); if (trimmed == NULL) { return false; } strip_char (trimmed); bool valid = valid_b32_str (trimmed); free(trimmed); return valid; } return valid_b32_str (user_data); } static bool valid_b32_str (const char *str) { if (str == NULL) { return false; } size_t len = 0; size_t pad_count = 0; bool seen_pad = false; while (*str) { uint8_t c = (uint8_t)*str; if (c >= 128 || !b32_valid[c]) { return false; } if (c == '=') { seen_pad = true; pad_count++; } else if (seen_pad) { // data character after padding is invalid per RFC 4648 return false; } len++; str++; } // If padding is present, validate count: valid padding counts are 0, 1, 3, 4, 6 if (seen_pad) { if (pad_count == 2 || pad_count == 5 || pad_count == 7 || pad_count > 6) { return false; } // total length (data + padding) must be a multiple of 8 if (len % 8 != 0) { return false; } } return true; } static bool has_space (const char *str) { while (*str) { if (*str == ' ') { return true; } str++; } return false; } static int get_char_index (uint8_t c) { if (c >= 'a' && c <= 'z') { c = c - 'a' + 'A'; } if (c >= 'A' && c <= 'Z') { return b32_char_index[c]; } if (c >= '2' && c <= '7') { return b32_char_index[c]; } return -1; } static int strip_char (char *str) { const char strip = ' '; uint8_t table[256] = {0}; table[(uint8_t)strip] = 1; int found = 0; char *p, *q; for (q = p = str; *p; p++) { if (!table[*(uint8_t *)p]) { *q++ = *p; } else { found++; } } *q = '\0'; return found; } static cotp_error_t check_input (const uint8_t *user_data, size_t data_len, size_t max_len) { if (!user_data || data_len > max_len) { return INVALID_USER_INPUT; } if (data_len == 0) { return EMPTY_STRING; } return NO_ERROR; } libcotp-4.2.1/src/utils/otpauth_uri.c000066400000000000000000000263451522115210500176140ustar00rootroot00000000000000#include #include #include #include #include #include #include #include "../cotp.h" #include "secure_zero.h" #include "pct.h" #define OTPAUTH_PREFIX "otpauth://" #define OTPAUTH_PREFIX_LEN 10 // Reusable validation matching otp.c's check_* helpers. static int validate_algo (int algo) { return (algo == COTP_SHA1 || algo == COTP_SHA256 || algo == COTP_SHA512); } static int validate_digits (int d) { return (d >= MIN_DIGITS && d <= MAX_DIGITS); } static int validate_period (int p) { return (p > 0 && p <= 120); } static int parse_int (const char *s, size_t len, long *out) { if (len == 0 || len > 30) return 0; char buf[32]; memcpy (buf, s, len); buf[len] = '\0'; char *end = NULL; errno = 0; long v = strtol (buf, &end, 10); if (errno != 0 || end == buf || *end != '\0') return 0; *out = v; return 1; } void cotp_otpauth_uri_free (cotp_otpauth_uri *u) { if (!u) return; if (u->secret) { cotp_secure_memzero (u->secret, strlen (u->secret)); free (u->secret); } free (u->issuer); free (u->account); free (u); } cotp_otpauth_uri * cotp_otpauth_uri_parse (const char *uri, cotp_error_t *err) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err ? err : &local_err; if (uri == NULL || strncmp (uri, OTPAUTH_PREFIX, OTPAUTH_PREFIX_LEN) != 0) { *errp = INVALID_USER_INPUT; return NULL; } const char *p = uri + OTPAUTH_PREFIX_LEN; // Type const char *slash = strchr (p, '/'); if (!slash) { *errp = INVALID_USER_INPUT; return NULL; } size_t type_len = (size_t)(slash - p); cotp_otpauth_type type; if (type_len == 4 && strncasecmp (p, "totp", 4) == 0) { type = COTP_OTPAUTH_TOTP; } else if (type_len == 4 && strncasecmp (p, "hotp", 4) == 0) { type = COTP_OTPAUTH_HOTP; } else { *errp = INVALID_USER_INPUT; return NULL; } p = slash + 1; // Label up to '?' const char *qmark = strchr (p, '?'); size_t label_len = qmark ? (size_t)(qmark - p) : strlen (p); char *label_issuer_raw = NULL; char *label_account_raw = NULL; if (label_len > 0) { const char *colon = memchr (p, ':', label_len); if (colon) { size_t issuer_len = (size_t)(colon - p); size_t account_len = label_len - issuer_len - 1; label_issuer_raw = cotp_pct_decode_n (p, issuer_len); label_account_raw = cotp_pct_decode_n (colon + 1, account_len); if (!label_issuer_raw || !label_account_raw) { free (label_issuer_raw); free (label_account_raw); *errp = INVALID_USER_INPUT; return NULL; } } else { label_account_raw = cotp_pct_decode_n (p, label_len); if (!label_account_raw) { *errp = INVALID_USER_INPUT; return NULL; } } } cotp_otpauth_uri *u = calloc (1, sizeof (*u)); if (!u) { free (label_issuer_raw); free (label_account_raw); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } u->type = type; u->issuer = label_issuer_raw; u->account = label_account_raw; u->algo = COTP_SHA1; u->digits = 6; u->period = 30; u->counter = 0; int saw_secret = 0; int saw_counter = 0; // Query string if (qmark) { const char *qp = qmark + 1; while (*qp) { const char *eq = strchr (qp, '='); if (!eq) break; size_t key_len = (size_t)(eq - qp); const char *val = eq + 1; const char *amp = strchr (val, '&'); size_t val_len = amp ? (size_t)(amp - val) : strlen (val); if (key_len == 6 && strncasecmp (qp, "secret", 6) == 0) { free (u->secret); u->secret = cotp_pct_decode_n (val, val_len); if (!u->secret) { cotp_otpauth_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } saw_secret = 1; } else if (key_len == 6 && strncasecmp (qp, "issuer", 6) == 0) { if (!u->issuer) { u->issuer = cotp_pct_decode_n (val, val_len); if (!u->issuer) { cotp_otpauth_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } } } else if (key_len == 9 && strncasecmp (qp, "algorithm", 9) == 0) { if (val_len == 4 && strncasecmp (val, "SHA1", 4) == 0) u->algo = COTP_SHA1; else if (val_len == 6 && strncasecmp (val, "SHA256", 6) == 0) u->algo = COTP_SHA256; else if (val_len == 6 && strncasecmp (val, "SHA512", 6) == 0) u->algo = COTP_SHA512; else { cotp_otpauth_uri_free (u); *errp = INVALID_ALGO; return NULL; } } else if (key_len == 6 && strncasecmp (qp, "digits", 6) == 0) { long v; if (!parse_int (val, val_len, &v) || v < INT_MIN || v > INT_MAX) { cotp_otpauth_uri_free (u); *errp = INVALID_DIGITS; return NULL; } u->digits = (int)v; } else if (key_len == 6 && strncasecmp (qp, "period", 6) == 0) { long v; if (!parse_int (val, val_len, &v) || v < INT_MIN || v > INT_MAX) { cotp_otpauth_uri_free (u); *errp = INVALID_PERIOD; return NULL; } u->period = (int)v; } else if (key_len == 7 && strncasecmp (qp, "counter", 7) == 0) { long v; if (!parse_int (val, val_len, &v)) { cotp_otpauth_uri_free (u); *errp = INVALID_COUNTER; return NULL; } u->counter = v; saw_counter = 1; } // Unknown keys silently ignored. if (!amp) break; qp = amp + 1; } } // Final validation if (!saw_secret || !u->secret || u->secret[0] == '\0') { cotp_otpauth_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } if (!is_string_valid_b32 (u->secret)) { cotp_otpauth_uri_free (u); *errp = INVALID_B32_INPUT; return NULL; } if (!validate_algo (u->algo)) { cotp_otpauth_uri_free (u); *errp = INVALID_ALGO; return NULL; } if (!validate_digits (u->digits)) { cotp_otpauth_uri_free (u); *errp = INVALID_DIGITS; return NULL; } if (u->type == COTP_OTPAUTH_TOTP && !validate_period (u->period)) { cotp_otpauth_uri_free (u); *errp = INVALID_PERIOD; return NULL; } if (u->type == COTP_OTPAUTH_HOTP) { if (!saw_counter) { cotp_otpauth_uri_free (u); *errp = INVALID_COUNTER; return NULL; } if (u->counter < 0) { cotp_otpauth_uri_free (u); *errp = INVALID_COUNTER; return NULL; } } *errp = NO_ERROR; return u; } char * cotp_otpauth_uri_build (const cotp_otpauth_uri *u, cotp_error_t *err) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err ? err : &local_err; if (!u || !u->secret || u->secret[0] == '\0') { *errp = INVALID_USER_INPUT; return NULL; } if (u->type != COTP_OTPAUTH_TOTP && u->type != COTP_OTPAUTH_HOTP) { *errp = INVALID_USER_INPUT; return NULL; } if (!is_string_valid_b32 (u->secret)) { *errp = INVALID_B32_INPUT; return NULL; } if (!validate_algo (u->algo)) { *errp = INVALID_ALGO; return NULL; } if (!validate_digits (u->digits)) { *errp = INVALID_DIGITS; return NULL; } if (u->type == COTP_OTPAUTH_TOTP && !validate_period (u->period)) { *errp = INVALID_PERIOD; return NULL; } if (u->type == COTP_OTPAUTH_HOTP && u->counter < 0) { *errp = INVALID_COUNTER; return NULL; } const char *type_str = (u->type == COTP_OTPAUTH_TOTP) ? "totp" : "hotp"; const char *algo_str = (u->algo == COTP_SHA256) ? "SHA256" : (u->algo == COTP_SHA512) ? "SHA512" : "SHA1"; // Encode each label component; the ':' separator between issuer and account is added literally below. // Same encoded string is reused for both the label-form ("Issuer:Account") and the &issuer= query param. char *enc_issuer = u->issuer ? cotp_pct_encode (u->issuer) : NULL; char *enc_account_label = u->account ? cotp_pct_encode (u->account) : NULL; char *enc_secret = cotp_pct_encode (u->secret); if (!enc_secret || (u->issuer && !enc_issuer) || (u->account && !enc_account_label)) { free (enc_issuer); free (enc_account_label); free (enc_secret); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } // Two-pass snprintf: measure, then format. // Format: otpauth://TYPE/[ISSUER:]ACCOUNT?secret=...&algorithm=...&digits=...&[period|counter]=...&[issuer=...] int n; if (u->type == COTP_OTPAUTH_TOTP) { n = snprintf (NULL, 0, "otpauth://%s/%s%s%s?secret=%s&algorithm=%s&digits=%d&period=%d%s%s", type_str, enc_issuer ? enc_issuer : "", enc_issuer ? ":" : "", enc_account_label ? enc_account_label : "", enc_secret, algo_str, u->digits, u->period, enc_issuer ? "&issuer=" : "", enc_issuer ? enc_issuer : ""); } else { n = snprintf (NULL, 0, "otpauth://%s/%s%s%s?secret=%s&algorithm=%s&digits=%d&counter=%ld%s%s", type_str, enc_issuer ? enc_issuer : "", enc_issuer ? ":" : "", enc_account_label ? enc_account_label : "", enc_secret, algo_str, u->digits, u->counter, enc_issuer ? "&issuer=" : "", enc_issuer ? enc_issuer : ""); } if (n < 0) { free (enc_issuer); free (enc_account_label); free (enc_secret); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } char *out = malloc ((size_t)n + 1); if (!out) { free (enc_issuer); free (enc_account_label); free (enc_secret); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } if (u->type == COTP_OTPAUTH_TOTP) { snprintf (out, (size_t)n + 1, "otpauth://%s/%s%s%s?secret=%s&algorithm=%s&digits=%d&period=%d%s%s", type_str, enc_issuer ? enc_issuer : "", enc_issuer ? ":" : "", enc_account_label ? enc_account_label : "", enc_secret, algo_str, u->digits, u->period, enc_issuer ? "&issuer=" : "", enc_issuer ? enc_issuer : ""); } else { snprintf (out, (size_t)n + 1, "otpauth://%s/%s%s%s?secret=%s&algorithm=%s&digits=%d&counter=%ld%s%s", type_str, enc_issuer ? enc_issuer : "", enc_issuer ? ":" : "", enc_account_label ? enc_account_label : "", enc_secret, algo_str, u->digits, u->counter, enc_issuer ? "&issuer=" : "", enc_issuer ? enc_issuer : ""); } free (enc_issuer); free (enc_account_label); free (enc_secret); *errp = NO_ERROR; return out; } libcotp-4.2.1/src/utils/pct.c000066400000000000000000000030541522115210500160270ustar00rootroot00000000000000#include #include #include #include "pct.h" static int hex_val (char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } char * cotp_pct_decode_n (const char *in, size_t len) { if (in == NULL) return NULL; char *out = malloc (len + 1); if (!out) return NULL; size_t j = 0; for (size_t i = 0; i < len; i++) { if (in[i] == '%' && i + 2 < len) { int hi = hex_val (in[i+1]); int lo = hex_val (in[i+2]); if (hi < 0 || lo < 0) { free (out); return NULL; } unsigned char byte = (unsigned char)((hi << 4) | lo); if (byte == 0) { free (out); return NULL; } out[j++] = (char)byte; i += 2; } else { out[j++] = in[i]; } } out[j] = '\0'; return out; } char * cotp_pct_encode (const char *in) { static const char hex[] = "0123456789ABCDEF"; if (!in) return NULL; size_t len = strlen (in); char *out = malloc (len * 3 + 1); if (!out) return NULL; size_t j = 0; for (size_t i = 0; i < len; i++) { unsigned char c = (unsigned char)in[i]; int unreserved = (isalnum (c) || c == '-' || c == '_' || c == '.' || c == '~'); if (unreserved) { out[j++] = (char)c; } else { out[j++] = '%'; out[j++] = hex[c >> 4]; out[j++] = hex[c & 0x0F]; } } out[j] = '\0'; return out; } libcotp-4.2.1/src/utils/pct.h000066400000000000000000000010031522115210500160240ustar00rootroot00000000000000#pragma once #include /** * Percent-decode `len` bytes from `in`. Returns a malloc'd NUL-terminated string, * or NULL on OOM, malformed escape, or a decoded NUL byte (%00 is rejected to * prevent silent truncation). Caller must free(). */ char *cotp_pct_decode_n (const char *in, size_t len); /** * Percent-encode a NUL-terminated string per the RFC 3986 unreserved set. * Returns a malloc'd NUL-terminated string, or NULL on OOM. Caller must free(). */ char *cotp_pct_encode (const char *in); libcotp-4.2.1/src/utils/secure_zero.c000066400000000000000000000014571522115210500175730ustar00rootroot00000000000000#include "secure_zero.h" #include void cotp_secure_memzero(void *ptr, size_t len) { if (ptr == NULL || len == 0) return; #if defined(__STDC_LIB_EXT1__) memset_s(ptr, len, 0, len); return; #elif defined(HAVE_EXPLICIT_BZERO) explicit_bzero(ptr, len); return; #else volatile unsigned char *p = (volatile unsigned char *)ptr; while (len--) { *p++ = 0; } return; #endif } int cotp_timing_safe_memcmp(const void *a, const void *b, size_t len) { const unsigned char *pa = (const unsigned char *)a; const unsigned char *pb = (const unsigned char *)b; unsigned char diff = 0; for (size_t i = 0; i < len; ++i) { diff |= (unsigned char)(pa[i] ^ pb[i]); } return diff; // 0 if equal } libcotp-4.2.1/src/utils/secure_zero.h000066400000000000000000000003611522115210500175710ustar00rootroot00000000000000#pragma once // Compatibility shim: cotp_secure_memzero / cotp_timing_safe_memcmp are now // declared in the public header. Internal sources include this for legacy // reasons; new code should include directly. #include "../cotp.h" libcotp-4.2.1/src/utils/validation.c000066400000000000000000000044601522115210500173750ustar00rootroot00000000000000#include #include #include #include "../cotp.h" #include "secure_zero.h" #ifdef COTP_ENABLE_VALIDATION #define COTP_MAX_VALIDATION_WINDOW 1024 int validate_totp_in_window(const char* user_code, const char* base32_encoded_secret, long timestamp, int digits, int period, int sha_algo, int window, int* matched_delta, cotp_error_t* err_code) { if (matched_delta) *matched_delta = 0; if (!user_code || !base32_encoded_secret) { if (err_code) *err_code = INVALID_USER_INPUT; return 0; } // Normalize window: handle INT_MIN safely (negation would overflow) if (window == INT_MIN) { window = COTP_MAX_VALIDATION_WINDOW; } else if (window < 0) { window = -window; } if (window > COTP_MAX_VALIDATION_WINDOW) { if (err_code) *err_code = INVALID_USER_INPUT; return 0; } size_t user_len = strlen(user_code); // Try [-window, +window] for (int delta = -window; delta <= window; ++delta) { long step; long t; if (__builtin_mul_overflow((long)delta, (long)period, &step) || __builtin_add_overflow(timestamp, step, &t)) { // Skip deltas whose timestamp would overflow long continue; } cotp_error_t err = NO_ERROR; char* gen = get_totp_at(base32_encoded_secret, t, digits, period, sha_algo, &err); if (!gen) { if (err_code) *err_code = err; return 0; } size_t gen_len = strlen(gen); // Length check is fine non-constant-time: OTP length == digits is public. // When lengths match, do a timing-safe byte compare. int ok = 0; if (gen_len == user_len) { ok = (cotp_timing_safe_memcmp(gen, user_code, gen_len) == 0); } free(gen); if (ok) { if (matched_delta) *matched_delta = delta; if (err_code) *err_code = VALID; return 1; } } if (err_code) *err_code = NO_ERROR; return 0; } #endif // COTP_ENABLE_VALIDATION libcotp-4.2.1/src/utils/whash_gcrypt.c000066400000000000000000000005051522115210500177410ustar00rootroot00000000000000#include #include "../whash.h" int whash_sha256 (const unsigned char *data, size_t len, unsigned char out[32]) { if (out == NULL || (data == NULL && len > 0)) { return -1; } gcry_md_hash_buffer (GCRY_MD_SHA256, out, data, len); return 0; } libcotp-4.2.1/src/utils/whash_mbedtls.c000066400000000000000000000007361522115210500200710ustar00rootroot00000000000000#include #include "../whash.h" int whash_sha256 (const unsigned char *data, size_t len, unsigned char out[32]) { if (out == NULL || (data == NULL && len > 0)) { return -1; } const mbedtls_md_info_t *info = mbedtls_md_info_from_type (MBEDTLS_MD_SHA256); if (info == NULL) { return -1; } if (mbedtls_md (info, data, len, out) != 0) { return -1; } return 0; } libcotp-4.2.1/src/utils/whash_openssl.c000066400000000000000000000007021522115210500201130ustar00rootroot00000000000000#include #include "../whash.h" int whash_sha256 (const unsigned char *data, size_t len, unsigned char out[32]) { if (out == NULL || (data == NULL && len > 0)) { return -1; } unsigned int md_len = 32; if (EVP_Digest (data, len, out, &md_len, EVP_sha256 (), NULL) != 1) { return -1; } if (md_len != 32) { return -1; } return 0; } libcotp-4.2.1/src/utils/whmac_gcrypt.c000066400000000000000000000044761522115210500177410ustar00rootroot00000000000000#include #include "../whmac.h" #include "../cotp.h" typedef struct whmac_handle_s whmac_handle_t; struct whmac_handle_s { gcry_md_hd_t hd; int algo; }; int whmac_check (void) { if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P)) { if (!gcry_check_version ("1.8.0")) { return -1; } gcry_control (GCRYCTL_DISABLE_SECMEM, 0); gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); } return 0; } size_t whmac_getlen (whmac_handle_t *hd) { return gcry_md_get_algo_dlen (hd->algo); } whmac_handle_t * whmac_gethandle (int algo) { int gcrypt_algo[] = { GCRY_MD_SHA1, GCRY_MD_SHA256, GCRY_MD_SHA512, }; whmac_handle_t *whmac_handle = NULL; gcry_md_hd_t hd; if (algo < 0 || algo > 2) { return NULL; } gpg_error_t gpg_err = gcry_md_open (&hd, gcrypt_algo[algo], GCRY_MD_FLAG_HMAC); if (gpg_err == 0) { whmac_handle = calloc (1, sizeof(*whmac_handle)); if (whmac_handle == NULL) { gcry_md_close (hd); return NULL; } memcpy (&whmac_handle->hd, &hd, sizeof(hd)); whmac_handle->algo = gcrypt_algo[algo]; } return whmac_handle; } void whmac_freehandle (whmac_handle_t *hd) { if (!hd) return; gcry_md_close (hd->hd); free (hd); } int whmac_setkey (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { if (gcry_md_setkey (hd->hd, buffer, buflen)) { return WHMAC_ERROR; } return NO_ERROR; } int whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { if (hd == NULL) { return WHMAC_ERROR; } gcry_md_write (hd->hd, buffer, buflen); return NO_ERROR; } ssize_t whmac_finalize (whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { ssize_t dlen = gcry_md_get_algo_dlen (hd->algo); if (buffer == NULL) { return dlen; } if (dlen > buflen) { return -MEMORY_ALLOCATION_ERROR; } gcry_md_final (hd->hd); unsigned char *hmac_tmp = gcry_md_read (hd->hd, hd->algo); if (hmac_tmp == NULL) { return -MEMORY_ALLOCATION_ERROR; } memcpy (buffer, hmac_tmp, dlen); return dlen; } libcotp-4.2.1/src/utils/whmac_mbedtls.c000066400000000000000000000155171522115210500200610ustar00rootroot00000000000000#include #include /* ssize_t */ /* Portable MbedTLS version detection: 2.x predates . */ #if defined(__has_include) # if __has_include() # include # else # include # endif #else # include #endif #include "../whmac.h" #include "../cotp.h" typedef struct whmac_handle_s whmac_handle_t; #if MBEDTLS_VERSION_MAJOR >= 4 /* --------------------------------------------------------------------------- * MbedTLS 4.x demoted the classic mbedtls_md_hmac_* API to private identifiers * (PSA is the public HMAC path now). Implement the wrapper on PSA Crypto. * ------------------------------------------------------------------------- */ #include struct whmac_handle_s { psa_mac_operation_t op; /* zero-initialised == PSA_MAC_OPERATION_INIT */ mbedtls_svc_key_id_t key; /* zero-initialised == PSA_KEY_ID_NULL */ psa_algorithm_t alg; /* PSA_ALG_HMAC(hash) */ size_t dlen; int algo; int op_active; int key_set; }; static const psa_algorithm_t psa_hash_algo[] = { PSA_ALG_SHA_1, PSA_ALG_SHA_256, PSA_ALG_SHA_512, }; int whmac_check (void) { /* psa_crypto_init() is idempotent; safe to call before every computation. */ return (psa_crypto_init () == PSA_SUCCESS) ? 0 : -1; } size_t whmac_getlen (whmac_handle_t *hd) { return hd->dlen; } whmac_handle_t * whmac_gethandle (int algo) { if (algo < 0 || algo > 2) { return NULL; } /* calloc yields {0}, which matches PSA_MAC_OPERATION_INIT and PSA_KEY_ID_NULL. */ whmac_handle_t *whmac_handle = calloc (1, sizeof (*whmac_handle)); if (whmac_handle == NULL) { return NULL; } whmac_handle->algo = algo; whmac_handle->alg = PSA_ALG_HMAC (psa_hash_algo[algo]); whmac_handle->dlen = PSA_HASH_LENGTH (psa_hash_algo[algo]); return whmac_handle; } void whmac_freehandle (whmac_handle_t *hd) { if (!hd) return; if (hd->op_active) { psa_mac_abort (&(hd->op)); } if (hd->key_set) { psa_destroy_key (hd->key); } free (hd); } int whmac_setkey (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { if (hd == NULL) { return WHMAC_ERROR; } psa_key_attributes_t attributes = psa_key_attributes_init (); psa_set_key_usage_flags (&attributes, PSA_KEY_USAGE_SIGN_MESSAGE); psa_set_key_algorithm (&attributes, hd->alg); psa_set_key_type (&attributes, PSA_KEY_TYPE_HMAC); psa_status_t status = psa_import_key (&attributes, buffer, buflen, &(hd->key)); psa_reset_key_attributes (&attributes); if (status != PSA_SUCCESS) { return WHMAC_ERROR; } hd->key_set = 1; if (psa_mac_sign_setup (&(hd->op), hd->key, hd->alg) != PSA_SUCCESS) { psa_destroy_key (hd->key); hd->key_set = 0; return WHMAC_ERROR; } hd->op_active = 1; return NO_ERROR; } int whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { if (hd == NULL || !hd->op_active) { return WHMAC_ERROR; } if (psa_mac_update (&(hd->op), buffer, buflen) != PSA_SUCCESS) { return WHMAC_ERROR; } return NO_ERROR; } ssize_t whmac_finalize (whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { if (hd == NULL) { return -WHMAC_ERROR; } if (buffer == NULL) { /* Length probe: report the digest size without consuming the operation. */ return (ssize_t) hd->dlen; } if (hd->dlen > buflen) { return -MEMORY_ALLOCATION_ERROR; } size_t out_len = 0; psa_status_t status = psa_mac_sign_finish (&(hd->op), buffer, buflen, &out_len); if (status != PSA_SUCCESS) { /* PSA requires an explicit abort to release an operation that errored. */ psa_mac_abort (&(hd->op)); } hd->op_active = 0; if (hd->key_set) { psa_destroy_key (hd->key); hd->key_set = 0; } if (status != PSA_SUCCESS) { return -WHMAC_ERROR; } return (ssize_t) out_len; } #else /* MBEDTLS_VERSION_MAJOR < 4 */ /* --------------------------------------------------------------------------- * MbedTLS 2.x / 3.x: the classic mbedtls_md_hmac_* generic-hash API. * ------------------------------------------------------------------------- */ #include struct whmac_handle_s { mbedtls_md_context_t sha_ctx; const mbedtls_md_info_t *md_info; int algo; size_t dlen; }; int whmac_check (void) { return 0; } size_t whmac_getlen (whmac_handle_t *hd) { return mbedtls_md_get_size(hd->md_info); } whmac_handle_t * whmac_gethandle (int algo) { const mbedtls_md_type_t mbedtls_algo[] = { MBEDTLS_MD_SHA1, MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA512, }; if (algo < 0 || algo > 2) { return NULL; } const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type (mbedtls_algo[algo]); if (md_info == NULL) { return NULL; } whmac_handle_t *whmac_handle = calloc (1, sizeof(*whmac_handle)); if (whmac_handle == NULL) { return NULL; } mbedtls_md_init (&(whmac_handle->sha_ctx)); whmac_handle->md_info = md_info; int ret = mbedtls_md_setup (&(whmac_handle->sha_ctx), whmac_handle->md_info, 1); if (ret != 0) { mbedtls_md_free (&(whmac_handle->sha_ctx)); free (whmac_handle); return NULL; } return whmac_handle; } void whmac_freehandle (whmac_handle_t *hd) { if (!hd) return; mbedtls_md_free (&(hd->sha_ctx)); free (hd); } int whmac_setkey (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { int ret = mbedtls_md_hmac_starts (&(hd->sha_ctx), buffer, buflen); if (ret != 0) { return WHMAC_ERROR; } return NO_ERROR; } int whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { if (hd == NULL) { return WHMAC_ERROR; } if (mbedtls_md_hmac_update (&(hd->sha_ctx), buffer, buflen) != 0) { return WHMAC_ERROR; } return NO_ERROR; } ssize_t whmac_finalize (whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { if (hd == NULL || hd->md_info == NULL) { return -WHMAC_ERROR; } size_t dlen = mbedtls_md_get_size(hd->md_info); if (buffer == NULL) { return (ssize_t)dlen; } if (dlen > buflen) { return -MEMORY_ALLOCATION_ERROR; } if (mbedtls_md_hmac_finish (&(hd->sha_ctx), buffer) != 0) { return -WHMAC_ERROR; } return (ssize_t)dlen; } #endif /* MBEDTLS_VERSION_MAJOR */ libcotp-4.2.1/src/utils/whmac_openssl.c000066400000000000000000000053561522115210500201120ustar00rootroot00000000000000#include #include #include #include "../whmac.h" #include "../cotp.h" typedef struct whmac_handle_s whmac_handle_t; struct whmac_handle_s { EVP_MAC *mac; OSSL_PARAM mac_params[4]; EVP_MAC_CTX *ctx; int algo; size_t dlen; }; int whmac_check (void) { return 0; } size_t whmac_getlen (whmac_handle_t *hd) { return hd->dlen; } whmac_handle_t * whmac_gethandle (int algo) { const char *openssl_algo[] = { "SHA1", "SHA256", "SHA512", }; whmac_handle_t *whmac_handle = NULL; if (algo < 0 || algo > 2) { return NULL; } EVP_MAC *mac = EVP_MAC_fetch (NULL, "HMAC", NULL); if (mac != NULL) { whmac_handle = calloc (1, sizeof(*whmac_handle)); if (whmac_handle == NULL) { EVP_MAC_free (mac); return NULL; } whmac_handle->mac = mac; whmac_handle->algo = algo; size_t params_n = 0; whmac_handle->mac_params[params_n++] = OSSL_PARAM_construct_utf8_string ("digest", (char *)openssl_algo[algo], 0); whmac_handle->mac_params[params_n] = OSSL_PARAM_construct_end (); } return whmac_handle; } void whmac_freehandle (whmac_handle_t *hd) { if (!hd) return; if (hd->ctx) { EVP_MAC_CTX_free (hd->ctx); } EVP_MAC_free (hd->mac); free (hd); } int whmac_setkey (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { hd->ctx = EVP_MAC_CTX_new (hd->mac); if (hd->ctx == NULL) { return WHMAC_ERROR; } if (!EVP_MAC_init (hd->ctx, buffer, buflen, hd->mac_params)) { EVP_MAC_CTX_free (hd->ctx); hd->ctx = NULL; return WHMAC_ERROR; } hd->dlen = EVP_MAC_CTX_get_mac_size (hd->ctx); return NO_ERROR; } int whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { if (hd == NULL || hd->ctx == NULL) { return WHMAC_ERROR; } if (!EVP_MAC_update (hd->ctx, buffer, buflen)) { return WHMAC_ERROR; } return NO_ERROR; } ssize_t whmac_finalize(whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { if (hd == NULL || hd->ctx == NULL) { return -WHMAC_ERROR; } size_t dlen = EVP_MAC_CTX_get_mac_size (hd->ctx); if (buffer == NULL) { return (ssize_t)dlen; } if (dlen > buflen) { EVP_MAC_CTX_free (hd->ctx); hd->ctx = NULL; return -MEMORY_ALLOCATION_ERROR; } int ok = EVP_MAC_final (hd->ctx, buffer, &dlen, buflen); EVP_MAC_CTX_free (hd->ctx); hd->ctx = NULL; if (!ok) { return -WHMAC_ERROR; } return (ssize_t)dlen; } libcotp-4.2.1/src/utils/yaotp_uri.c000066400000000000000000000207031522115210500172540ustar00rootroot00000000000000#include #include #include #include #include #include #include "../cotp.h" #include "secure_zero.h" #include "pct.h" #define YAOTP_URI_PREFIX "otpauth://yaotp/" #define YAOTP_URI_PREFIX_LEN 16 // Cap opaque pass-through fields (track_id, uid) at 128 decoded bytes each. The Yandex format // keeps these short (UUID-like); refusing oversized values prevents URI-bomb-style allocations. #define YAOTP_OPAQUE_MAX 128 static int parse_int (const char *s, size_t len, long *out) { if (len == 0 || len > 30) return 0; char buf[32]; memcpy (buf, s, len); buf[len] = '\0'; char *end = NULL; errno = 0; long v = strtol (buf, &end, 10); if (errno != 0 || end == buf || *end != '\0') return 0; *out = v; return 1; } void cotp_yaotp_uri_free (cotp_yaotp_uri *u) { if (!u) return; if (u->secret) { cotp_secure_memzero (u->secret, strlen (u->secret)); free (u->secret); } free (u->account); free (u->issuer); free (u->track_id); free (u->uid); free (u); } cotp_yaotp_uri * cotp_yaotp_uri_parse (const char *uri, cotp_error_t *err) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err ? err : &local_err; if (uri == NULL || strncasecmp (uri, YAOTP_URI_PREFIX, YAOTP_URI_PREFIX_LEN) != 0) { *errp = INVALID_USER_INPUT; return NULL; } const char *p = uri + YAOTP_URI_PREFIX_LEN; // Label up to '?'. Account from label takes precedence over "&name=" query param. const char *qmark = strchr (p, '?'); size_t label_len = qmark ? (size_t)(qmark - p) : strlen (p); char *label_account_raw = NULL; if (label_len > 0) { label_account_raw = cotp_pct_decode_n (p, label_len); if (!label_account_raw) { *errp = INVALID_USER_INPUT; return NULL; } } cotp_yaotp_uri *u = calloc (1, sizeof (*u)); if (!u) { free (label_account_raw); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } u->account = label_account_raw; u->pin_length = -1; int saw_pin_length = 0; if (qmark) { const char *qp = qmark + 1; while (*qp) { const char *eq = strchr (qp, '='); if (!eq) break; size_t key_len = (size_t)(eq - qp); const char *val = eq + 1; const char *amp = strchr (val, '&'); size_t val_len = amp ? (size_t)(amp - val) : strlen (val); if (key_len == 6 && strncasecmp (qp, "secret", 6) == 0) { free (u->secret); u->secret = cotp_pct_decode_n (val, val_len); if (!u->secret) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } } else if (key_len == 6 && strncasecmp (qp, "issuer", 6) == 0) { free (u->issuer); u->issuer = cotp_pct_decode_n (val, val_len); if (!u->issuer) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } } else if (key_len == 4 && strncasecmp (qp, "name", 4) == 0) { // Only set from query if the label didn't already provide an account. if (!u->account) { u->account = cotp_pct_decode_n (val, val_len); if (!u->account) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } } } else if (key_len == 10 && strncasecmp (qp, "pin_length", 10) == 0) { long v; if (!parse_int (val, val_len, &v) || v < INT_MIN || v > INT_MAX) { cotp_yaotp_uri_free (u); *errp = INVALID_YAOTP_PIN; return NULL; } u->pin_length = (int)v; saw_pin_length = 1; } else if (key_len == 8 && strncasecmp (qp, "track_id", 8) == 0) { if (val_len > YAOTP_OPAQUE_MAX * 3) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } free (u->track_id); u->track_id = cotp_pct_decode_n (val, val_len); if (!u->track_id) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } if (strlen (u->track_id) > YAOTP_OPAQUE_MAX) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } } else if (key_len == 3 && strncasecmp (qp, "uid", 3) == 0) { if (val_len > YAOTP_OPAQUE_MAX * 3) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } free (u->uid); u->uid = cotp_pct_decode_n (val, val_len); if (!u->uid) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } if (strlen (u->uid) > YAOTP_OPAQUE_MAX) { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } } // Unknown keys silently ignored, matching cotp_otpauth_uri_parse's behavior. if (!amp) break; qp = amp + 1; } } if (!u->secret || u->secret[0] == '\0') { cotp_yaotp_uri_free (u); *errp = INVALID_USER_INPUT; return NULL; } if (!is_string_valid_b32 (u->secret)) { cotp_yaotp_uri_free (u); *errp = INVALID_B32_INPUT; return NULL; } if (!saw_pin_length || u->pin_length < COTP_YAOTP_MIN_PIN_LENGTH || u->pin_length > COTP_YAOTP_MAX_PIN_LENGTH) { cotp_yaotp_uri_free (u); *errp = INVALID_YAOTP_PIN; return NULL; } *errp = NO_ERROR; return u; } char * cotp_yaotp_uri_build (const cotp_yaotp_uri *u, cotp_error_t *err) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err ? err : &local_err; if (!u || !u->secret || u->secret[0] == '\0') { *errp = INVALID_USER_INPUT; return NULL; } if (!is_string_valid_b32 (u->secret)) { *errp = INVALID_B32_INPUT; return NULL; } if (u->pin_length < COTP_YAOTP_MIN_PIN_LENGTH || u->pin_length > COTP_YAOTP_MAX_PIN_LENGTH) { *errp = INVALID_YAOTP_PIN; return NULL; } char *enc_account = u->account ? cotp_pct_encode (u->account) : NULL; char *enc_secret = cotp_pct_encode (u->secret); char *enc_issuer = u->issuer ? cotp_pct_encode (u->issuer) : NULL; char *enc_track_id = u->track_id ? cotp_pct_encode (u->track_id) : NULL; char *enc_uid = u->uid ? cotp_pct_encode (u->uid) : NULL; if (!enc_secret || (u->account && !enc_account) || (u->issuer && !enc_issuer) || (u->track_id && !enc_track_id) || (u->uid && !enc_uid)) { free (enc_account); free (enc_secret); free (enc_issuer); free (enc_track_id); free (enc_uid); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } // Format: otpauth://yaotp/[ACCOUNT]?secret=...&pin_length=N[&issuer=...][&track_id=...][&uid=...] // Literal format strings inline to satisfy -Wformat-nonliteral while keeping optional fields conditional. int n = snprintf (NULL, 0, "otpauth://yaotp/%s?secret=%s&pin_length=%d%s%s%s%s%s%s", enc_account ? enc_account : "", enc_secret, u->pin_length, enc_issuer ? "&issuer=" : "", enc_issuer ? enc_issuer : "", enc_track_id ? "&track_id=" : "", enc_track_id ? enc_track_id : "", enc_uid ? "&uid=" : "", enc_uid ? enc_uid : ""); if (n < 0) { free (enc_account); free (enc_secret); free (enc_issuer); free (enc_track_id); free (enc_uid); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } char *out = malloc ((size_t)n + 1); if (!out) { free (enc_account); free (enc_secret); free (enc_issuer); free (enc_track_id); free (enc_uid); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } snprintf (out, (size_t)n + 1, "otpauth://yaotp/%s?secret=%s&pin_length=%d%s%s%s%s%s%s", enc_account ? enc_account : "", enc_secret, u->pin_length, enc_issuer ? "&issuer=" : "", enc_issuer ? enc_issuer : "", enc_track_id ? "&track_id=" : "", enc_track_id ? enc_track_id : "", enc_uid ? "&uid=" : "", enc_uid ? enc_uid : ""); free (enc_account); free (enc_secret); free (enc_issuer); free (enc_track_id); free (enc_uid); *errp = NO_ERROR; return out; } libcotp-4.2.1/src/whash.h000066400000000000000000000004461522115210500152220ustar00rootroot00000000000000#pragma once #include /** * One-shot SHA-256 over `data`. Writes 32 bytes to `out`. * Returns 0 on success, non-zero on backend failure. */ int whash_sha256 (const unsigned char *data, size_t len, unsigned char out[32]); libcotp-4.2.1/src/whmac.h000066400000000000000000000014221522115210500152020ustar00rootroot00000000000000#pragma once typedef struct whmac_handle_s whmac_handle_t; int whmac_check (void); whmac_handle_t* whmac_gethandle (int algo); size_t whmac_getlen (whmac_handle_t* hd); void whmac_freehandle (whmac_handle_t *hd); int whmac_setkey (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen); int whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen); ssize_t whmac_finalize (whmac_handle_t *hd, unsigned char *buffer, size_t buflen); libcotp-4.2.1/src/yaotp.c000066400000000000000000000230721522115210500152370ustar00rootroot00000000000000#include #include #include #include #include #include #include "cotp.h" #include "whmac.h" #include "whash.h" #include "utils/secure_zero.h" // Minimum decoded secret length: 16 (key) + 8 (userId) + 2 (pinLength nibble + 12-bit CRC) = 26. #define YAOTP_SECRET_MIN_BYTES 26 #define YAOTP_KEY_BYTES 16 #define YAOTP_SHA256_BYTES 32 #define YAOTP_BASE26_MOD 208827064576ULL // 26^8 // Derive the decoded length of a base32 string the same way otp.c does: // floor(non-pad chars * 5 / 8). Spaces and '=' don't count toward output bytes. static size_t yaotp_b32_decoded_len (const char *s) { if (!s) return 0; size_t chars = 0; for (const char *p = s; *p; ++p) { if (*p != '=' && *p != ' ') ++chars; } return (chars * 5) / 8; } // Count leading zero bits in a 16-bit value (matches KeeYaOtp's NumberOfLeadingZeros). static int yaotp_clz16 (uint16_t value) { if (value == 0) return 16; int n = 0; if ((value & 0xFF00u) == 0) { n += 8; value <<= 8; } if ((value & 0xF000u) == 0) { n += 4; value <<= 4; } if ((value & 0xC000u) == 0) { n += 2; value <<= 2; } if ((value & 0x8000u) == 0) { n += 1; } return n; } // Port of KeeYaOtp/Core/Secret.cs:ChecksumIsValid. Polynomial 0x18F3 (13 bits). // Stored 12-bit checksum lives in the low 4 bits of byte[len-2] + all 8 bits of byte[len-1]. // All other bits are fed MSB-first into a 13-bit accumulator; when the accumulator hits 13 bits, // it is XORed with the polynomial. The effective bit-width is then re-derived via leading-zero count. static int yaotp_crc_valid (const unsigned char *input, size_t len) { if (len < 4) return 0; const uint16_t poly = 0x18F3u; uint16_t checksum_orig = (uint16_t)(((input[len - 2] & 0x0F) << 8) | input[len - 1]); uint16_t accum = 0; int accum_bits = 0; int total_bits = (int)(len * 8) - 12; size_t idx = 0; int bits_avail = 8; while (total_bits > 0) { int required = 13 - accum_bits; if (total_bits < required) required = total_bits; while (required > 0) { unsigned char cur = (unsigned char)(input[idx] & ((1 << bits_avail) - 1)); int to_read = required > bits_avail ? bits_avail : required; cur = (unsigned char)(cur >> (bits_avail - to_read)); accum = (uint16_t)(((uint32_t)accum << to_read) | cur); total_bits -= to_read; required -= to_read; bits_avail -= to_read; accum_bits += to_read; if (bits_avail == 0) { idx++; bits_avail = 8; } } if (accum_bits == 13) accum ^= poly; accum_bits = 16 - yaotp_clz16 (accum); } return accum == checksum_orig; } // Decode and validate the Yandex-format secret. On success fills out_key (16 bytes) and *out_pin_len. // Always wipes the decoded buffer before returning. static int yaotp_parse_secret (const char *base32_secret, unsigned char out_key[YAOTP_KEY_BYTES], int *out_pin_len, cotp_error_t *err) { if (!is_string_valid_b32 (base32_secret)) { *err = INVALID_B32_INPUT; return -1; } size_t decoded_len_expected = yaotp_b32_decoded_len (base32_secret); if (decoded_len_expected < YAOTP_SECRET_MIN_BYTES) { *err = INVALID_YAOTP_SECRET_LENGTH; return -1; } cotp_error_t b32_err = NO_ERROR; unsigned char *decoded = base32_decode (base32_secret, strlen (base32_secret), &b32_err); if (decoded == NULL || b32_err != NO_ERROR) { free (decoded); *err = b32_err != NO_ERROR ? b32_err : INVALID_B32_INPUT; return -1; } // decoded_len_expected (validated >= YAOTP_SECRET_MIN_BYTES above) equals base32_decode's // own (chars*5)/8 allocation, so every offset read/wiped below is in-bounds. if (!yaotp_crc_valid (decoded, decoded_len_expected)) { cotp_secure_memzero (decoded, decoded_len_expected); free (decoded); *err = INVALID_YAOTP_SECRET_CRC; return -1; } memcpy (out_key, decoded + (decoded_len_expected - 26), YAOTP_KEY_BYTES); *out_pin_len = (int)((decoded[decoded_len_expected - 2] >> 4) + 1); cotp_secure_memzero (decoded, decoded_len_expected); free (decoded); // Secret bytes are fine here; it's the embedded pin-length nibble that is out of range. if (*out_pin_len < COTP_YAOTP_MIN_PIN_LENGTH || *out_pin_len > COTP_YAOTP_MAX_PIN_LENGTH) { cotp_secure_memzero (out_key, YAOTP_KEY_BYTES); *err = INVALID_YAOTP_PIN; return -1; } return 0; } static int yaotp_validate_pin (const char *pin, int expected_len, cotp_error_t *err) { if (pin == NULL) { *err = INVALID_YAOTP_PIN; return -1; } size_t len = strlen (pin); if ((int)len != expected_len) { *err = INVALID_YAOTP_PIN; return -1; } for (size_t i = 0; i < len; i++) { if (!isdigit ((unsigned char)pin[i])) { *err = INVALID_YAOTP_PIN; return -1; } } return 0; } int cotp_yaotp_secret_pin_length (const char *base32_secret, cotp_error_t *err_code) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err_code ? err_code : &local_err; if (base32_secret == NULL) { *errp = INVALID_USER_INPUT; return -1; } unsigned char key[YAOTP_KEY_BYTES]; int pin_len = 0; if (yaotp_parse_secret (base32_secret, key, &pin_len, errp) != 0) { return -1; } cotp_secure_memzero (key, sizeof (key)); *errp = NO_ERROR; return pin_len; } char * get_yaotp_at (const char *base32_secret, const char *pin, long timestamp, cotp_error_t *err_code) { cotp_error_t local_err = NO_ERROR; cotp_error_t *errp = err_code ? err_code : &local_err; if (base32_secret == NULL || pin == NULL) { *errp = INVALID_USER_INPUT; return NULL; } if (whmac_check () == -1) { *errp = WCRYPT_VERSION_MISMATCH; return NULL; } unsigned char key[YAOTP_KEY_BYTES]; int pin_len = 0; if (yaotp_parse_secret (base32_secret, key, &pin_len, errp) != 0) { return NULL; } if (yaotp_validate_pin (pin, pin_len, errp) != 0) { cotp_secure_memzero (key, sizeof (key)); return NULL; } // keyHash = SHA-256(pin || key). Concat into one buffer; wipe after hashing. size_t pin_bytes = (size_t)pin_len; size_t cat_len = pin_bytes + YAOTP_KEY_BYTES; unsigned char *cat = malloc (cat_len); if (cat == NULL) { cotp_secure_memzero (key, sizeof (key)); *errp = MEMORY_ALLOCATION_ERROR; return NULL; } memcpy (cat, pin, pin_bytes); memcpy (cat + pin_bytes, key, YAOTP_KEY_BYTES); cotp_secure_memzero (key, sizeof (key)); unsigned char key_hash[YAOTP_SHA256_BYTES]; int hash_rc = whash_sha256 (cat, cat_len, key_hash); cotp_secure_memzero (cat, cat_len); free (cat); if (hash_rc != 0) { cotp_secure_memzero (key_hash, sizeof (key_hash)); *errp = WHMAC_ERROR; return NULL; } // Leading-zero quirk: if key_hash[0] == 0x00, treat key_hash as starting at byte 1, length 31. // pyYaOTP omits this; KeeYaOtp does it; Yandex servers require it. size_t hash_offset = (key_hash[0] == 0x00) ? 1u : 0u; size_t hash_len = YAOTP_SHA256_BYTES - hash_offset; // counter = floor(unix_time / 30), big-endian 8 bytes. int64_t counter = (int64_t)timestamp / COTP_YAOTP_PERIOD; unsigned char counter_be[8]; for (int i = 0; i < 8; i++) { counter_be[i] = (unsigned char)((uint64_t)counter >> (56 - 8 * i)); } whmac_handle_t *hd = whmac_gethandle (COTP_SHA256); if (hd == NULL) { cotp_secure_memzero (key_hash, sizeof (key_hash)); *errp = WHMAC_ERROR; return NULL; } if (whmac_setkey (hd, key_hash + hash_offset, hash_len) != 0 || whmac_update (hd, counter_be, sizeof (counter_be)) != 0) { whmac_freehandle (hd); cotp_secure_memzero (key_hash, sizeof (key_hash)); *errp = WHMAC_ERROR; return NULL; } unsigned char mac[YAOTP_SHA256_BYTES]; ssize_t flen = whmac_finalize (hd, mac, sizeof (mac)); whmac_freehandle (hd); cotp_secure_memzero (key_hash, sizeof (key_hash)); if (flen != (ssize_t)YAOTP_SHA256_BYTES) { cotp_secure_memzero (mac, sizeof (mac)); *errp = WHMAC_ERROR; return NULL; } // 64-bit dynamic truncation (NOT RFC 4226's 32-bit truncation): // offset = mac[31] & 0x0F; value = be64(mac[offset..offset+8]) & 0x7FFF_FFFF_FFFF_FFFF. unsigned int offset = mac[YAOTP_SHA256_BYTES - 1] & 0x0Fu; if (offset + 8u > YAOTP_SHA256_BYTES) { cotp_secure_memzero (mac, sizeof (mac)); *errp = WHMAC_ERROR; return NULL; } uint64_t value = 0; for (unsigned int i = 0; i < 8; i++) { value = (value << 8) | mac[offset + i]; } value &= 0x7FFFFFFFFFFFFFFFULL; cotp_secure_memzero (mac, sizeof (mac)); value %= YAOTP_BASE26_MOD; // Encode 8 base-26 chars (a..z) MSB-first. char *out = malloc (COTP_YAOTP_DIGITS + 1); if (out == NULL) { *errp = MEMORY_ALLOCATION_ERROR; return NULL; } for (int i = COTP_YAOTP_DIGITS - 1; i >= 0; i--) { out[i] = (char)('a' + (value % 26)); value /= 26; } out[COTP_YAOTP_DIGITS] = '\0'; *errp = NO_ERROR; return out; } char * get_yaotp (const char *base32_secret, const char *pin, cotp_error_t *err_code) { return get_yaotp_at (base32_secret, pin, (long)time (NULL), err_code); } libcotp-4.2.1/tests/000077500000000000000000000000001522115210500143065ustar00rootroot00000000000000libcotp-4.2.1/tests/CMakeLists.txt000066400000000000000000000032461522115210500170530ustar00rootroot00000000000000add_executable (test_cotp test_otp.c) add_executable (test_base32encode test_base32encode.c) add_executable (test_base32decode test_base32decode.c) add_executable (test_base32_roundtrip test_base32_roundtrip.c) add_executable (test_strerror test_strerror.c) add_executable (test_otpauth_uri test_otpauth_uri.c) add_executable (test_secure test_secure.c) add_executable (test_yaotp test_yaotp.c) add_executable (test_yaotp_uri test_yaotp_uri.c) target_link_libraries (test_cotp PRIVATE cotp criterion) target_link_libraries (test_base32encode PRIVATE cotp criterion) target_link_libraries (test_base32decode PRIVATE cotp criterion) target_link_libraries (test_base32_roundtrip PRIVATE cotp criterion) target_link_libraries (test_strerror PRIVATE cotp criterion) target_link_libraries (test_otpauth_uri PRIVATE cotp criterion) target_link_libraries (test_secure PRIVATE cotp criterion) target_link_libraries (test_yaotp PRIVATE cotp criterion) target_link_libraries (test_yaotp_uri PRIVATE cotp criterion) add_test (NAME TestCOTP COMMAND test_cotp) add_test (NAME TestBase32Encode COMMAND test_base32encode) add_test (NAME TestBase32Decode COMMAND test_base32decode) add_test (NAME TestBase32Roundtrip COMMAND test_base32_roundtrip) add_test (NAME TestStrerror COMMAND test_strerror) add_test (NAME TestOTPAuthURI COMMAND test_otpauth_uri) add_test (NAME TestSecure COMMAND test_secure) add_test (NAME TestYAOTP COMMAND test_yaotp) add_test (NAME TestYAOTPURI COMMAND test_yaotp_uri) if (COTP_ENABLE_VALIDATION) add_executable (test_validation test_validation.c) target_link_libraries (test_validation PRIVATE cotp criterion) add_test (NAME TestValidation COMMAND test_validation) endif() libcotp-4.2.1/tests/docker/000077500000000000000000000000001522115210500155555ustar00rootroot00000000000000libcotp-4.2.1/tests/docker/Dockerfile000066400000000000000000000016421522115210500175520ustar00rootroot00000000000000FROM archlinux:latest ARG BRANCH=master COPY PKGBUILD /tmp/PKGBUILD RUN pacman -Syu --noconfirm ; \ pacman -S gcc git clang cmake pkg-config libgcrypt fakeroot sudo --noconfirm ; \ pacman -S base-devel --noconfirm RUN useradd -m -G wheel -s /bin/bash test ; \ cp /tmp/PKGBUILD /home/test/ && chown test:test /home/test/PKGBUILD ; \ sed -i 's/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) NOPASSWD: ALL/' /etc/sudoers USER test RUN cd /home/test && makepkg USER root RUN pacman -U /home/test/*zst --noconfirm USER test RUN yay -S criterion --noconfirm ; \ gpg --keyserver pool.sks-keyservers.net --recv-keys 4EC1EA64 ; \ yay -S libbaseencode --noconfirm USER root RUN git clone https://github.com/paolostivanin/libcotp -b $BRANCH ; \ cd libcotp ; \ mkdir build && cd $_ ; \ cmake .. -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_TESTING=ON ; \ make -j2 ;\ ./tests/test_cotp ;\ make install libcotp-4.2.1/tests/docker/PKGBUILD000066400000000000000000000035601522115210500167050ustar00rootroot00000000000000# Maintainer: Jguer pkgname=yay-bin pkgver=11.0.2 pkgrel=1 pkgdesc="Yet another yogurt. Pacman wrapper and AUR helper written in go. Pre-compiled." arch=('x86_64' 'aarch64' 'armv6h' 'armv7h') url="https://github.com/Jguer/yay" license=('GPL3') depends=( 'git' ) optdepends=( 'sudo' ) provides=('yay') conflicts=('yay' 'libalpm.so<13') source_x86_64=("https://github.com/Jguer/yay/releases/download/v${pkgver}/${pkgname/-bin/}_${pkgver}_x86_64.tar.gz") source_aarch64=("https://github.com/Jguer/yay/releases/download/v${pkgver}/${pkgname/-bin/}_${pkgver}_aarch64.tar.gz") source_armv6h=("https://github.com/Jguer/yay/releases/download/v${pkgver}/${pkgname/-bin/}_${pkgver}_armv6h.tar.gz") source_armv7h=("https://github.com/Jguer/yay/releases/download/v${pkgver}/${pkgname/-bin/}_${pkgver}_armv7h.tar.gz") sha256sums_x86_64=('3b6334a4e719138c80f4c271a77b97bd740329677dfffe6bbe54679a0052140e') sha256sums_aarch64=('d1c1b2d74783cb366a86480fcea9d7fbb325d170815014642ac0790e9bad6637') sha256sums_armv6h=('7b4dd9d33d56b600955ead52bb5bd86bc9ac6fc45c24f0c6b686153b184eb905') sha256sums_armv7h=('80a6317383552272ca9a9d251531fb2ca6e310e811b034a680e6632d4a294f15') package() { _output="${srcdir}/${pkgname/-bin/}_${pkgver}_${CARCH}" install -Dm755 "${_output}/${pkgname/-bin/}" "${pkgdir}/usr/bin/${pkgname/-bin/}" install -Dm644 "${_output}/yay.8" "${pkgdir}/usr/share/man/man8/yay.8" # Shell autocompletion script install -Dm644 "${_output}/bash" "${pkgdir}/usr/share/bash-completion/completions/yay" install -Dm644 "${_output}/zsh" "${pkgdir}/usr/share/zsh/site-functions/_yay" install -Dm644 "${_output}/fish" "${pkgdir}/usr/share/fish/vendor_completions.d/yay.fish" LANGS="pt pt_BR en es eu fr_FR ja pl_PL ru_RU zh_CN ko" for lang in ${LANGS}; do install -Dm644 "${_output}/${lang}.mo" "${pkgdir}/usr/share/locale/${lang}/LC_MESSAGES/yay.mo" done } libcotp-4.2.1/tests/docker/run_docker.sh000066400000000000000000000002241522115210500202420ustar00rootroot00000000000000#!/bin/bash if [[ -z "$1" ]]; then echo "Usage: $0 " exit 1 fi docker build -t "testme:Dockerfile" --build-arg BRANCH="$1" . libcotp-4.2.1/tests/test_base32_roundtrip.c000066400000000000000000000035321522115210500207010ustar00rootroot00000000000000#include #include #include #include "../src/cotp.h" // Round-trip helper: encode raw -> base32, then decode back, compare static void roundtrip_check(const char* raw) { cotp_error_t err = 0; size_t raw_len = strlen(raw) + 1; // keep terminating NUL like other tests char* b32 = base32_encode((const uint8_t*)raw, raw_len, &err); cr_expect_not_null(b32); cr_expect_eq(err, 0); uint8_t* decoded = base32_decode(b32, strlen(b32) + 1, &err); cr_expect_not_null(decoded); cr_expect_eq(err, 0); cr_expect_arr_eq(decoded, raw, raw_len); free(b32); free(decoded); } Test(base32_roundtrip, small_corpus) { roundtrip_check(""); roundtrip_check("a"); roundtrip_check("ab"); roundtrip_check("abc"); roundtrip_check("abcd"); roundtrip_check("abcde"); roundtrip_check("abcdef"); roundtrip_check("abcdefg"); roundtrip_check("abcdefgh"); } Test(base32_decoder, accepts_spaces_and_case) { // These variants should decode to the same bytes const char* raw = "hello world"; cotp_error_t err = 0; char* b32_norm = base32_encode((const uint8_t*)raw, strlen(raw) + 1, &err); cr_expect_eq(err, 0); // introduce spaces and lower case char messy[256]; size_t L = strlen(b32_norm); size_t j = 0; for (size_t i = 0; i < L; ++i) { char c = b32_norm[i]; // insert a space occasionally if (i % 4 == 0) messy[j++] = ' '; messy[j++] = (char) (i % 2 == 0 ? c : (char)tolower((unsigned char)c)); } messy[j] = '\0'; uint8_t* d1 = base32_decode(b32_norm, strlen(b32_norm) + 1, &err); cr_expect_eq(err, 0); uint8_t* d2 = base32_decode(messy, strlen(messy) + 1, &err); cr_expect_eq(err, 0); cr_expect_str_eq((char*)d1, (char*)d2, "%s"); free(b32_norm); free(d1); free(d2); } libcotp-4.2.1/tests/test_base32decode.c000066400000000000000000000120461522115210500177370ustar00rootroot00000000000000#include #include #include "../src/cotp.h" Test(b32_decode_test, b32_all_chars) { cotp_error_t err; const char *k = "IFCEMRZUGEZSDQVDEQSSMJRIFAXT6XWDU7B2SKS3LURSSLJOFR6DYPRL"; const char *k_dec = "ADFG413!£$%&&((/?^çé*[]#)-.,|<>+"; char *dk = base32_decode (k, strlen(k)+1, &err); cr_expect(strcmp(dk, k_dec) == 0, "Expected %s to be equal to %s", dk, k_dec); free(dk); } Test(b32_decode_test, b32_all_chars_noplusone) { cotp_error_t err; const char *k = "IFCEMRZUGEZSDQVDEQSSMJRIFAXT6XWDU7B2SKS3LURSSLJOFR6DYPRL"; const char *k_dec = "ADFG413!£$%&&((/?^çé*[]#)-.,|<>+"; char *dk = base32_decode (k, strlen(k), &err); cr_expect(strcmp(dk, k_dec) == 0, "Expected %s to be equal to %s", dk, k_dec); free(dk); } Test(b32_decode_test, b32_rfc4648) { cotp_error_t err; const char *k[] = {"", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======"}; const char *k_dec[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; for (int i = 0; i < 7; i++) { char *dk = base32_decode (k[i], strlen(k[i])+1, &err); cr_expect(strcmp(dk, k_dec[i]) == 0, "Expected %s to be equal to %s", dk, k_dec[i]); free(dk); } } Test(b32_decode_test, b32_rfc4648_noplusone) { cotp_error_t err; const char *k[] = {"", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======"}; const char *k_dec[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; for (int i = 0; i < 7; i++) { char *dk = base32_decode (k[i], strlen(k[i]), &err); cr_expect(strcmp(dk, k_dec[i]) == 0, "Expected %s to be equal to %s", dk, k_dec[i]); free(dk); } } Test(b32_decode_test, b32_invalid_input) { cotp_error_t err; const char *k = "£&/(&/"; size_t len = strlen(k); uint8_t *dk = base32_decode (k, len, &err); cr_expect_null (dk, "%s"); cr_expect_eq (err, INVALID_B32_INPUT); } Test(b32_decode_test, b32_decode_input_exceeded) { cotp_error_t err; const char *k = "ASDF"; size_t len = 128*1024*1024; uint8_t *dk = base32_decode (k, len, &err); cr_expect_null (dk, "%s"); cr_expect_eq (err, INVALID_USER_INPUT); } Test(b32_decode_test, b32_decode_input_whitespaces) { cotp_error_t err; const char *k = "MZ XW 6Y TB"; const char *expected = "fooba"; uint8_t *dk = base32_decode (k, strlen(k), &err); cr_expect_str_eq (dk, expected, "%s"); } Test(b32_decode_test, b32_decode_encode_null) { const char* token = "LLFTSZYMUGKHEDQBAAACAZAMUFKKVFLS"; cotp_error_t err; uint8_t* binary = base32_decode (token, strlen(token)+1, &err); cr_expect_eq (err, NO_ERROR); char* result = base32_encode (binary, 20, &err); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (result, token, "%s"); } Test(b32_decode_test, b32_decode_empty_string) { cotp_error_t err; uint8_t* binary = base32_decode ("", 0, &err); cr_expect_eq (err, EMPTY_STRING); cr_expect_str_eq ((char *)binary, "", "%s"); free (binary); } Test(b32_decode_test, byte_array_all_zeroes) { cotp_error_t err; const char *token = "AAAAAAA="; uint8_t* binary = base32_decode (token, strlen (token) + 1, &err); cr_expect_eq (err, NO_ERROR); for (int i=0;i<4;i++) { cr_expect_eq (binary[i], 0); } free (binary); } Test(b32_decode_test, b32_padding_in_middle) { cotp_error_t err; const char *k = "MY=W======"; uint8_t *dk = base32_decode (k, strlen(k), &err); cr_expect_null (dk, "Expected NULL for padding in middle of string"); cr_expect_eq (err, INVALID_B32_INPUT); } Test(b32_decode_test, b32_invalid_padding_count) { cotp_error_t err; // 2 padding chars is never valid in base32 const char *k = "MZXW6Y=="; uint8_t *dk = base32_decode (k, strlen(k), &err); cr_expect_null (dk, "Expected NULL for invalid padding count"); cr_expect_eq (err, INVALID_B32_INPUT); } Test(b32_decode_test, b32_no_padding_valid) { cotp_error_t err; // No padding at all is accepted (common for OTP secrets) const char *k = "MZXW6YTBOI"; const char *expected = "foobar"; uint8_t *dk = base32_decode (k, strlen(k), &err); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq ((char *)dk, expected, "Expected %s to be equal to %s", dk, expected); free (dk); } // Regression: caller-supplied data_len longer than the actual NUL-terminated // content (e.g., embedded NUL inside the buffer) must not over-read. // Discovered by libFuzzer. Test(b32_decode_test, b32_decode_embedded_nul_no_overread) { cotp_error_t err = NO_ERROR; char input[40]; memset (input, 0, sizeof (input)); input[0] = 'C'; // valid base32 char input[31] = '?'; // garbage past the embedded NUL — must NOT be read // Tell the function the buffer is 32 bytes even though strlen is 1. uint8_t *out = base32_decode (input, sizeof (input), &err); // We don't care which error code (or success) — only that it doesn't crash // and doesn't read past byte 1 of the input. free (out); }libcotp-4.2.1/tests/test_base32encode.c000066400000000000000000000077351522115210500177620ustar00rootroot00000000000000#include #include #include "../src/cotp.h" Test(b32_encode_test, null_input) { cotp_error_t err; const char *k = NULL; char *ek = base32_encode (k, 5, &err); cr_expect_null (ek, "%s"); } Test(b32_encode_test, invalid_or_empty) { cotp_error_t err; char *null_enc = base32_encode (NULL, 30, &err); cr_expect_null (null_enc); cr_expect_eq (err, INVALID_USER_INPUT); char *k_enc = base32_encode ((const unsigned char *)"asdiasjdijis", 0, &err); cr_expect (strcmp (k_enc, "") == 0, "Expected %s to be equal to %s", k_enc, ""); cr_expect_eq (err, EMPTY_STRING); free (k_enc); } Test(b32_encode_test, byte_array_all_zeroes) { cotp_error_t err; const char *expected_enc = "AAAAAAA="; uint8_t secret_bytes[] = {0, 0, 0, 0}; char *enc = base32_encode(secret_bytes, 4, &err); cr_expect (strcmp (enc, expected_enc) == 0, "Expected %s to be equal to %s", enc, expected_enc); free (enc); } Test(b32_encode_test, array_allzeroes_utf8) { cotp_error_t err; const char *expected_enc = "GAYDAMA="; char *enc = base32_encode((const unsigned char *)"0000", 4, &err); cr_expect (strcmp (enc, expected_enc) == 0, "Expected %s to be equal to %s", enc, expected_enc); free (enc); } Test(b32_encode_test, b32_all_chars) { cotp_error_t err; const char *k = "ADFG413!£$%&&((/?^çé*[]#)-.,|<>+"; const char *k_enc = "IFCEMRZUGEZSDQVDEQSSMJRIFAXT6XWDU7B2SKS3LURSSLJOFR6DYPRL"; char *ek = base32_encode (k, strlen(k), &err); cr_expect (strcmp (ek, k_enc) == 0, "Expected %s to be equal to %s", ek, k_enc); free (ek); } Test(b32_encode_test, b32_all_chars_plusone) { cotp_error_t err; const char *k = "ADFG413!£$%&&((/?^çé*[]#)-.,|<>+"; const char *k_enc = "IFCEMRZUGEZSDQVDEQSSMJRIFAXT6XWDU7B2SKS3LURSSLJOFR6DYPRL"; char *ek = base32_encode (k, strlen(k)+1, &err); cr_expect (strcmp (ek, k_enc) == 0, "Expected %s to be equal to %s", ek, k_enc); free (ek); } Test(b32_encode_test, b32_rfc4648) { cotp_error_t err; const char *k[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; const char *k_enc[] = {"", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======"}; for (int i = 0; i < 7; i++) { char *ek = base32_encode (k[i], strlen(k[i]), &err); cr_expect (strcmp (ek, k_enc[i]) == 0, "Expected %s to be equal to %s", ek, k_enc[i]); free (ek); } } Test(b32_encode_test, b32_rfc4648_plusone) { cotp_error_t err; const char *k[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; const char *k_enc[] = {"", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======"}; for (int i = 0; i < 7; i++) { char *ek = base32_encode (k[i], strlen(k[i])+1, &err); cr_expect (strcmp (ek, k_enc[i]) == 0, "Expected %s to be equal to %s", ek, k_enc[i]); free (ek); } } Test(b32_encode_test, b32_rfc4648_noplusone) { cotp_error_t err; const char *k[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; const char *k_enc[] = {"", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======"}; for (int i = 0; i < 7; i++) { char *ek = base32_encode (k[i], strlen(k[i]), &err); cr_expect (strcmp (ek, k_enc[i]) == 0, "Expected %s to be equal to %s", ek, k_enc[i]); free (ek); } } Test(b32_encode_test, b32_encode_input_exceeded) { cotp_error_t err; const char *k = "test"; size_t len = 65*1024*1024; char *ek = base32_encode (k, len, &err); cr_expect_null (ek, "%s"); cr_expect_eq (err, INVALID_USER_INPUT); } Test(b32_encode_test, test_input_all_zeroes) { cotp_error_t err; const uint8_t secret_bytes[] = {0, 0, 0, 0}; char *encoded_str = base32_encode (secret_bytes, 4, &err); cr_expect_eq (err, NO_ERROR); cr_expect (strcmp (encoded_str, "AAAAAAA=") == 0, "Expected %s to be equal to %s", encoded_str, "AAAAAAA="); free (encoded_str); }libcotp-4.2.1/tests/test_otp.c000066400000000000000000000523471522115210500163260ustar00rootroot00000000000000#include #include #include #include "../src/cotp.h" Test(totp_rfc6238, test_8_digits_sha1) { const char *K = "12345678901234567890"; const int64_t counter[] = {59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000}; const char *expected_totp[] = {"94287082", "07081804", "14050471", "89005924", "69279037", "65353130"}; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp; for (int i = 0; i < 6; i++) { totp = get_totp_at (K_base32, counter[i], 8, 30, COTP_SHA1, &err); cr_expect_str_eq (totp, expected_totp[i], "Expected %s to be equal to %s\n", totp, expected_totp[i]); free (totp); } free (K_base32); } Test(totp_rfc6238, test_8_digits_sha1_toint) { const char *K = "12345678901234567890"; const int64_t counter[] = {59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000}; const int64_t expected_totp[] = {94287082, 7081804, 14050471, 89005924, 69279037, 65353130}; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; for (int i = 0; i < 6; i++) { char *totp_str = get_totp_at (K_base32, counter[i], 8, 30, COTP_SHA1, &err); int64_t totp = otp_to_int (totp_str, &err); cr_expect_eq (totp, expected_totp[i], "Expected %08ld to be equal to %08ld\n", totp, expected_totp[i]); free (totp_str); } free (K_base32); } Test(totp_rfc6238, test_10_digits_sha1) { const char *K = "12345678901234567890"; const long counter = 1234567890; const char *expected_totp = "0689005924"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, counter, 10, 30, COTP_SHA1, &err); cr_expect_str_eq (totp, expected_totp, "Expected %s to be equal to %s\n", totp, expected_totp); free (totp); free (K_base32); } Test(totp_rfc6238, test_10_digits_sha1_toint) { const char *K = "12345678901234567890"; const long counter = 1234567890; int64_t expected_totp = 689005924; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp_str = get_totp_at (K_base32, counter, 10, 30, COTP_SHA1, &err); int64_t totp = otp_to_int (totp_str, &err); cr_expect_eq (totp, expected_totp, "Expected %010ld to be equal to %010ld\n", totp, expected_totp); free (totp_str); free (K_base32); } Test(totp_rfc6238, test_8_digits_sha256) { const char *K = "12345678901234567890123456789012"; const int64_t counter[] = {59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000}; const char *expected_totp[] = {"46119246", "68084774", "67062674", "91819424", "90698825", "77737706"}; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp; for (int i = 0; i < 6; i++) { totp = get_totp_at (K_base32, counter[i], 8, 30, COTP_SHA256, &err); cr_expect_str_eq (totp, expected_totp[i], "Expected %s to be equal to %s\n", totp, expected_totp[i]); free (totp); } free (K_base32); } Test(totp_rfc6238, test_8_digits_sha512) { const char *K = "1234567890123456789012345678901234567890123456789012345678901234"; const int64_t counter[] = {59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000}; const char *expected_totp[] = {"90693936", "25091201", "99943326", "93441116", "38618901", "47863826"}; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen (K) + 1, &cotp_err); cotp_error_t err; char *totp; for (int i = 0; i < 6; i++) { totp = get_totp_at (K_base32, counter[i], 8, 30, COTP_SHA512, &err); cr_expect_str_eq (totp, expected_totp[i], "Expected %s to be equal to %s\n", totp, expected_totp[i]); free (totp); } free (K_base32); } Test(hotp_rfc, test_6_digits) { const char *K = "12345678901234567890"; const int counter[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; const char *expected_hotp[] = {"755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489"}; cotp_error_t cotp_err; char *K_base32 = base32_encode((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *hotp; for (int i = 0; i < 10; i++) { hotp = get_hotp (K_base32, counter[i], 6, COTP_SHA1, &err); cr_expect_str_eq (hotp, expected_hotp[i], "Expected %s to be equal to %s\n", hotp, expected_hotp[i]); free (hotp); } free (K_base32); } Test(hotp_rfc, test_wrong_digits_2) { const char *K = "this is a secret"; cotp_error_t err; char *totp = get_totp (K, 2, 30, COTP_SHA1, &err); cr_expect_eq (err, INVALID_DIGITS, "Expected %d to be equal to %d\n", err, INVALID_DIGITS); cr_assert_null (totp); free (totp); } Test(hotp_rfc, test_wrong_digits_16) { const char *K = "this is a secret"; cotp_error_t err; char *totp = get_totp (K, 16, 30, COTP_SHA1, &err); cr_expect_eq (err, INVALID_DIGITS, "Expected %d to be equal to %d\n", err, INVALID_DIGITS); cr_assert_null (totp); free (totp); } Test(hotp_rfc, test_period_zero) { const char *K = "this is a secret"; cotp_error_t err; char *totp = get_totp (K, 6, 0, COTP_SHA1, &err); cr_expect_eq (err, INVALID_PERIOD, "Expected %d to be equal to %d\n", err, INVALID_PERIOD); cr_assert_null (totp); free (totp); } Test(hotp_rfc, test_totp_wrong_negative) { const char *K = "this is a secret"; cotp_error_t err; char *totp = get_totp (K, 6, -20, COTP_SHA1, &err); cr_expect_eq (err, INVALID_PERIOD, "Expected %d to be equal to %d\n", err, INVALID_PERIOD); cr_assert_null (totp); free (totp); } Test(hotp_rfc, test_hotp_wrong_negative) { const char *K = "this is a secret"; cotp_error_t err; char *hotp = get_hotp (K, -6, 8, COTP_SHA1, &err); cr_expect_eq (err, INVALID_COUNTER, "Expected %d to be equal to %d\n", err, INVALID_COUNTER); cr_assert_null (hotp); } Test(totp_generic, test_secret_with_space) { const char *K = "hxdm vjec jjws rb3h wizr 4ifu gftm xboz"; const char *expected_totp = "488431"; cotp_error_t err; char *totp = get_totp_at (K, 1506268800, 6, 30, COTP_SHA1, &err); cr_expect_str_eq (totp, expected_totp, "Expected %s to be equal to %s\n", totp, expected_totp); free (totp); } Test(totp_generic, test_fail_invalid_b32_input) { const char *K = "This input is not valid!"; cotp_error_t err; char *totp = get_totp (K, 6, 30, COTP_SHA1, &err); cr_expect_eq (err, INVALID_B32_INPUT, "Expected %d to be equal to %d\n", err, INVALID_B32_INPUT); cr_assert_null (totp); } Test(totp_generic, test_fail_invalid_algo) { const char *K = "base32secret"; int MD5 = 3; cotp_error_t err; char *totp = get_totp (K, 6, 30, MD5, &err); cr_expect_eq (err, INVALID_ALGO, "Expected %d to be equal to %d\n", err, INVALID_ALGO); cr_assert_null (totp); } Test(totp_generic, test_steam_totp) { const char *secret = "ON2XAZLSMR2XAZLSONSWG4TFOQ======"; const char *expected_totp = "YRGQJ"; long timestamp = 3000030; cotp_error_t err; char *totp = get_steam_totp_at (secret, timestamp, 30, &err); cr_expect_str_eq (totp, expected_totp, "Expected %s to be equal to %s\n", totp, expected_totp); free (totp); } Test(totp_generic, test_steam_totp_input_b64) { const char *b64_encoded_secret = "VGhpcyBpbnB1dCBpcyBub3QgdmFsaWQhCg=="; cotp_error_t err; char *totp = get_steam_totp (b64_encoded_secret, 30, &err); cr_expect_null (totp, "Expected totp to be null"); cr_expect_eq (err, INVALID_B32_INPUT, "Expected %d to be equal to %d\n", err, INVALID_B32_INPUT); cr_assert_null (totp); } Test(totp_rfc6238, test_60seconds) { const char *K = "12345678901234567890"; const char *expected_totp = "360094"; cotp_error_t cotp_err; char *secret_base32 = base32_encode ((const uint8_t *)K, strlen (K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (secret_base32, 1111111109, 6, 60, COTP_SHA1, &err); cr_expect_str_eq (totp, expected_totp, "Expected %s to be equal to %s\n", totp, expected_totp); free (totp); free (secret_base32); } Test(totp_int, test_err_is_missing_zero) { const char *K = "12345678901234567890"; const long counter = 1234567890; int64_t expected_totp = 689005924; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp_str = get_totp_at (K_base32, counter, 10, 30, COTP_SHA1, &err); int64_t totp = otp_to_int (totp_str, &err); cr_expect_eq (err, MISSING_LEADING_ZERO, "Expected %d to be equal to %d\n", err, MISSING_LEADING_ZERO); free (totp_str); free (K_base32); } Test(totp_int, test_err_invalid_input) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; int64_t totp = otp_to_int ("124", &err); cr_expect_eq (err, INVALID_USER_INPUT, "Expected %d to be equal to %d\n", err, INVALID_USER_INPUT); cr_expect_eq (totp, -1, "Expected %ld to be equal to %d\n", totp, -1); free (K_base32); } Test(totp_int, test_err_invalid_characters) { cotp_error_t err; int64_t totp = otp_to_int ("12a4", &err); cr_expect_eq (err, INVALID_USER_INPUT, "Expected %d to be equal to %d\n", err, INVALID_USER_INPUT); cr_expect_eq (totp, -1, "Expected %ld to be equal to %d\n", totp, -1); } Test(totp_generic, test_null_secret) { cotp_error_t err; char *totp = get_totp (NULL, 6, 30, COTP_SHA1, &err); cr_expect_eq (err, INVALID_USER_INPUT, "Expected %d to be equal to %d\n", err, INVALID_USER_INPUT); cr_assert_null (totp); } Test(totp_generic, test_empty_secret) { cotp_error_t err; char *totp = get_totp ("", 6, 30, COTP_SHA1, &err); cr_expect_eq (err, EMPTY_STRING, "Expected %d to be equal to %d\n", err, EMPTY_STRING); cr_assert_null (totp); } Test(totp_boundary, test_min_digits) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 4, 30, COTP_SHA1, &err); cr_expect_eq (err, NO_ERROR, "Expected %d to be equal to %d\n", err, NO_ERROR); cr_assert_not_null (totp); cr_expect_eq (strlen(totp), 4, "Expected length 4, got %zu\n", strlen(totp)); free (totp); free (K_base32); } Test(totp_boundary, test_max_digits) { const char *K = "12345678901234567890"; const char *expected_totp = "0689005924"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 1234567890, 10, 30, COTP_SHA1, &err); cr_expect_eq (err, NO_ERROR, "Expected %d to be equal to %d\n", err, NO_ERROR); cr_assert_not_null (totp); cr_expect_eq (strlen(totp), 10, "Expected length 10, got %zu\n", strlen(totp)); cr_expect_str_eq (totp, expected_totp, "Expected %s to be equal to %s\n", totp, expected_totp); free (totp); free (K_base32); } Test(totp_boundary, test_min_period) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 6, 1, COTP_SHA1, &err); cr_expect_eq (err, NO_ERROR, "Expected %d to be equal to %d\n", err, NO_ERROR); cr_assert_not_null (totp); free (totp); free (K_base32); } Test(totp_boundary, test_max_period) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 6, 120, COTP_SHA1, &err); cr_expect_eq (err, NO_ERROR, "Expected %d to be equal to %d\n", err, NO_ERROR); cr_assert_not_null (totp); free (totp); free (K_base32); } Test(totp_boundary, test_period_over_max) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 6, 121, COTP_SHA1, &err); cr_expect_eq (err, INVALID_PERIOD, "Expected %d to be equal to %d\n", err, INVALID_PERIOD); cr_assert_null (totp); free (K_base32); } Test(totp_boundary, test_digits_below_min) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 3, 30, COTP_SHA1, &err); cr_expect_eq (err, INVALID_DIGITS, "Expected %d to be equal to %d\n", err, INVALID_DIGITS); cr_assert_null (totp); free (K_base32); } Test(totp_boundary, test_digits_above_max) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 11, 30, COTP_SHA1, &err); cr_expect_eq (err, INVALID_DIGITS, "Expected %d to be equal to %d\n", err, INVALID_DIGITS); cr_assert_null (totp); free (K_base32); } // Context API tests (T2) Test(ctx_api, test_create_valid) { cotp_ctx *ctx = cotp_ctx_create (6, 30, COTP_SHA1); cr_assert_not_null (ctx); cotp_ctx_free (ctx); } Test(ctx_api, test_create_all_algos) { cotp_ctx *ctx1 = cotp_ctx_create (6, 30, COTP_SHA1); cotp_ctx *ctx2 = cotp_ctx_create (6, 30, COTP_SHA256); cotp_ctx *ctx3 = cotp_ctx_create (6, 30, COTP_SHA512); cr_assert_not_null (ctx1); cr_assert_not_null (ctx2); cr_assert_not_null (ctx3); cotp_ctx_free (ctx1); cotp_ctx_free (ctx2); cotp_ctx_free (ctx3); } Test(ctx_api, test_create_invalid_digits) { cotp_ctx *ctx = cotp_ctx_create (3, 30, COTP_SHA1); cr_assert_null (ctx); ctx = cotp_ctx_create (11, 30, COTP_SHA1); cr_assert_null (ctx); } Test(ctx_api, test_create_invalid_period) { cotp_ctx *ctx = cotp_ctx_create (6, 0, COTP_SHA1); cr_assert_null (ctx); ctx = cotp_ctx_create (6, -1, COTP_SHA1); cr_assert_null (ctx); ctx = cotp_ctx_create (6, 121, COTP_SHA1); cr_assert_null (ctx); } Test(ctx_api, test_create_invalid_algo) { cotp_ctx *ctx = cotp_ctx_create (6, 30, 3); cr_assert_null (ctx); ctx = cotp_ctx_create (6, 30, -1); cr_assert_null (ctx); } Test(ctx_api, test_totp_at) { const char *K = "12345678901234567890"; const char *expected_totp = "94287082"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_ctx *ctx = cotp_ctx_create (8, 30, COTP_SHA1); cr_assert_not_null (ctx); cotp_error_t err; char *totp = cotp_ctx_totp_at (ctx, K_base32, 59, &err); cr_expect_eq (err, NO_ERROR, "Expected %d to be equal to %d\n", err, NO_ERROR); cr_expect_str_eq (totp, expected_totp, "Expected %s to be equal to %s\n", totp, expected_totp); free (totp); cotp_ctx_free (ctx); free (K_base32); } Test(ctx_api, test_null_ctx) { cotp_error_t err; char *totp = cotp_ctx_totp_at (NULL, "secret", 59, &err); cr_expect_eq (err, INVALID_USER_INPUT, "Expected %d to be equal to %d\n", err, INVALID_USER_INPUT); cr_assert_null (totp); totp = cotp_ctx_totp (NULL, "secret", &err); cr_expect_eq (err, INVALID_USER_INPUT, "Expected %d to be equal to %d\n", err, INVALID_USER_INPUT); cr_assert_null (totp); } Test(ctx_api, test_free_null) { cotp_ctx_free (NULL); } Test(ctx_api, test_totp_current) { // Positive happy-path test for cotp_ctx_totp (current-time variant). // We compute the bare and ctx versions back-to-back; the race window of // crossing a 30s boundary between the two calls is negligible for a unit test. const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_ctx *ctx = cotp_ctx_create (6, 30, COTP_SHA1); cr_assert_not_null (ctx); cotp_error_t err1 = NO_ERROR, err2 = NO_ERROR; char *bare = get_totp (K_base32, 6, 30, COTP_SHA1, &err1); char *via_ctx = cotp_ctx_totp (ctx, K_base32, &err2); cr_expect_eq (err1, NO_ERROR); cr_expect_eq (err2, NO_ERROR); cr_assert_not_null (bare); cr_assert_not_null (via_ctx); cr_expect_str_eq (bare, via_ctx); cr_expect_eq (strlen (via_ctx), 6); free (bare); free (via_ctx); cotp_ctx_free (ctx); free (K_base32); } Test(ctx_api, test_hotp) { // RFC 4226 Appendix D: counter=0 => "755224" const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_ctx *ctx = cotp_ctx_create (6, 30, COTP_SHA1); cr_assert_not_null (ctx); cotp_error_t err = NO_ERROR; char *hotp = cotp_ctx_hotp (ctx, K_base32, 0, &err); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (hotp, "755224"); free (hotp); cotp_ctx_free (ctx); free (K_base32); } Test(ctx_api, test_hotp_null_ctx) { cotp_error_t err = NO_ERROR; char *hotp = cotp_ctx_hotp (NULL, "secret", 0, &err); cr_expect_null (hotp); cr_expect_eq (err, INVALID_USER_INPUT); } Test(ctx_api, test_steam_totp_at) { const char *secret = "ON2XAZLSMR2XAZLSONSWG4TFOQ======"; cotp_ctx *ctx = cotp_ctx_create (5, 30, COTP_SHA1); cr_assert_not_null (ctx); cotp_error_t err = NO_ERROR; char *totp = cotp_ctx_steam_totp_at (ctx, secret, 3000030, &err); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (totp, "YRGQJ"); free (totp); cotp_ctx_free (ctx); } Test(ctx_api, test_steam_totp_null_ctx) { cotp_error_t err = NO_ERROR; char *totp = cotp_ctx_steam_totp (NULL, "secret", &err); cr_expect_null (totp); cr_expect_eq (err, INVALID_USER_INPUT); err = NO_ERROR; totp = cotp_ctx_steam_totp_at (NULL, "secret", 0, &err); cr_expect_null (totp); cr_expect_eq (err, INVALID_USER_INPUT); } #ifdef COTP_ENABLE_VALIDATION Test(ctx_api, test_validate_totp) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_ctx *ctx = cotp_ctx_create (8, 30, COTP_SHA1); cr_assert_not_null (ctx); cotp_error_t err = NO_ERROR; char *totp = cotp_ctx_totp_at (ctx, K_base32, 59, &err); cr_assert_not_null (totp); int matched_delta = -999; int result = cotp_ctx_validate_totp (ctx, totp, K_base32, 59, 1, &matched_delta, &err); cr_expect_eq (result, 1); cr_expect_eq (matched_delta, 0); cr_expect_eq (err, VALID); // Validate at one period later with window=1 must still match at delta=-1 matched_delta = -999; result = cotp_ctx_validate_totp (ctx, totp, K_base32, 89, 1, &matched_delta, &err); cr_expect_eq (result, 1); cr_expect_eq (matched_delta, -1); free (totp); cotp_ctx_free (ctx); free (K_base32); } Test(ctx_api, test_validate_totp_null_ctx) { cotp_error_t err = NO_ERROR; int matched_delta = 42; int result = cotp_ctx_validate_totp (NULL, "12345678", "secret", 59, 1, &matched_delta, &err); cr_expect_eq (result, 0); cr_expect_eq (err, INVALID_USER_INPUT); cr_expect_eq (matched_delta, 0); } #endif // Regression: very large counter must not cause UB in HMAC/truncation pipeline. Test(hotp_rfc, test_large_counter) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err = NO_ERROR; char *hotp = get_hotp (K_base32, LONG_MAX, 6, COTP_SHA1, &err); cr_expect_eq (err, NO_ERROR, "Expected NO_ERROR for LONG_MAX counter, got %d\n", err); cr_assert_not_null (hotp); cr_expect_eq (strlen(hotp), 6, "Expected 6-digit OTP, got %zu\n", strlen(hotp)); free (hotp); free (K_base32); } // Regression: 10-digit OTP must be exactly 10 digits (no negative/sign artefacts). Test(totp_boundary, test_10_digits_no_sign_artefact) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); // Sweep several timestamps to exercise different bin_code values. const long timestamps[] = {1, 31, 61, 1234567890, 2000000000, 20000000000}; for (int i = 0; i < 6; i++) { cotp_error_t err = NO_ERROR; char *totp = get_totp_at (K_base32, timestamps[i], 10, 30, COTP_SHA1, &err); cr_assert_not_null (totp); cr_expect_eq (strlen(totp), 10, "Expected 10-digit length, got %zu for ts=%ld\n", strlen(totp), timestamps[i]); cr_expect_neq (totp[0], '-', "OTP must not start with '-' (ts=%ld got %s)\n", timestamps[i], totp); for (int k = 0; k < 10; k++) { cr_expect (totp[k] >= '0' && totp[k] <= '9', "OTP[%d] must be a digit, got '%c' for ts=%ld\n", k, totp[k], timestamps[i]); } free (totp); } free (K_base32); } libcotp-4.2.1/tests/test_otpauth_uri.c000066400000000000000000000213231522115210500200550ustar00rootroot00000000000000#include #include #include #include "../src/cotp.h" Test(otpauth, parse_google_example) { const char *uri = "otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_eq (err, NO_ERROR); cr_expect_eq (u->type, COTP_OTPAUTH_TOTP); cr_expect_str_eq (u->issuer, "Example"); cr_expect_str_eq (u->account, "alice@google.com"); cr_expect_str_eq (u->secret, "JBSWY3DPEHPK3PXP"); cr_expect_eq (u->algo, COTP_SHA1); cr_expect_eq (u->digits, 6); cr_expect_eq (u->period, 30); cotp_otpauth_uri_free (u); } Test(otpauth, parse_totp_defaults) { // No algorithm/digits/period → SHA1/6/30 const char *uri = "otpauth://totp/user?secret=JBSWY3DPEHPK3PXP"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_null (u->issuer); cr_expect_str_eq (u->account, "user"); cr_expect_eq (u->algo, COTP_SHA1); cr_expect_eq (u->digits, 6); cr_expect_eq (u->period, 30); cotp_otpauth_uri_free (u); } Test(otpauth, parse_totp_custom) { const char *uri = "otpauth://totp/Foo:bar?secret=JBSWY3DPEHPK3PXP&algorithm=SHA512&digits=8&period=60"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_eq (u->algo, COTP_SHA512); cr_expect_eq (u->digits, 8); cr_expect_eq (u->period, 60); cotp_otpauth_uri_free (u); } Test(otpauth, parse_hotp_with_counter) { const char *uri = "otpauth://hotp/acct?secret=JBSWY3DPEHPK3PXP&counter=42"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_eq (u->type, COTP_OTPAUTH_HOTP); cr_expect_eq (u->counter, 42); cotp_otpauth_uri_free (u); } Test(otpauth, parse_hotp_missing_counter_rejected) { const char *uri = "otpauth://hotp/acct?secret=JBSWY3DPEHPK3PXP"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_expect_null (u); cr_expect_eq (err, INVALID_COUNTER); } Test(otpauth, parse_url_encoded_label) { // "Example Co:alice" with space pct-encoded const char *uri = "otpauth://totp/Example%20Co:alice?secret=JBSWY3DPEHPK3PXP"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_str_eq (u->issuer, "Example Co"); cr_expect_str_eq (u->account, "alice"); cotp_otpauth_uri_free (u); } Test(otpauth, parse_label_issuer_wins_over_query_issuer) { const char *uri = "otpauth://totp/Foo:bar?secret=JBSWY3DPEHPK3PXP&issuer=Bar"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_str_eq (u->issuer, "Foo"); cotp_otpauth_uri_free (u); } Test(otpauth, parse_invalid_scheme) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("https://example.com/", &err)); cr_expect_eq (err, INVALID_USER_INPUT); } Test(otpauth, parse_null_input) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse (NULL, &err)); cr_expect_eq (err, INVALID_USER_INPUT); } Test(otpauth, parse_missing_secret_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?digits=6", &err)); cr_expect_eq (err, INVALID_USER_INPUT); } Test(otpauth, parse_invalid_algo_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP&algorithm=MD5", &err)); cr_expect_eq (err, INVALID_ALGO); } Test(otpauth, parse_invalid_digits_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP&digits=2", &err)); cr_expect_eq (err, INVALID_DIGITS); } Test(otpauth, parse_invalid_period_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP&period=200", &err)); cr_expect_eq (err, INVALID_PERIOD); } Test(otpauth, parse_invalid_b32_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?secret=NOTBASE32!!!", &err)); cr_expect_eq (err, INVALID_B32_INPUT); } Test(otpauth, parse_unknown_keys_ignored) { // unknown keys silently ignored const char *uri = "otpauth://totp/u?secret=JBSWY3DPEHPK3PXP&foo=bar&xyz=abc"; cotp_error_t err = NO_ERROR; cotp_otpauth_uri *u = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (u); cotp_otpauth_uri_free (u); } Test(otpauth, build_totp_minimal) { cotp_otpauth_uri u = {0}; u.type = COTP_OTPAUTH_TOTP; u.secret = (char *)"JBSWY3DPEHPK3PXP"; u.algo = COTP_SHA1; u.digits = 6; u.period = 30; cotp_error_t err = NO_ERROR; char *uri = cotp_otpauth_uri_build (&u, &err); cr_assert_not_null (uri); cr_expect_eq (err, NO_ERROR); cr_expect_neq (strstr (uri, "otpauth://totp/"), NULL); cr_expect_neq (strstr (uri, "secret=JBSWY3DPEHPK3PXP"), NULL); cr_expect_neq (strstr (uri, "algorithm=SHA1"), NULL); cr_expect_neq (strstr (uri, "digits=6"), NULL); cr_expect_neq (strstr (uri, "period=30"), NULL); free (uri); } Test(otpauth, build_then_parse_round_trip_totp) { cotp_otpauth_uri u = {0}; u.type = COTP_OTPAUTH_TOTP; u.issuer = (char *)"Example Co"; u.account = (char *)"alice@example.com"; u.secret = (char *)"JBSWY3DPEHPK3PXP"; u.algo = COTP_SHA256; u.digits = 8; u.period = 60; cotp_error_t err = NO_ERROR; char *uri = cotp_otpauth_uri_build (&u, &err); cr_assert_not_null (uri); cotp_otpauth_uri *back = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (back); cr_expect_eq (back->type, COTP_OTPAUTH_TOTP); cr_expect_str_eq (back->issuer, "Example Co"); cr_expect_str_eq (back->account, "alice@example.com"); cr_expect_str_eq (back->secret, "JBSWY3DPEHPK3PXP"); cr_expect_eq (back->algo, COTP_SHA256); cr_expect_eq (back->digits, 8); cr_expect_eq (back->period, 60); cotp_otpauth_uri_free (back); free (uri); } Test(otpauth, build_then_parse_round_trip_hotp) { cotp_otpauth_uri u = {0}; u.type = COTP_OTPAUTH_HOTP; u.account = (char *)"acct"; u.secret = (char *)"JBSWY3DPEHPK3PXP"; u.algo = COTP_SHA1; u.digits = 6; u.counter = 12345; cotp_error_t err = NO_ERROR; char *uri = cotp_otpauth_uri_build (&u, &err); cr_assert_not_null (uri); cotp_otpauth_uri *back = cotp_otpauth_uri_parse (uri, &err); cr_assert_not_null (back); cr_expect_eq (back->type, COTP_OTPAUTH_HOTP); cr_expect_eq (back->counter, 12345); cotp_otpauth_uri_free (back); free (uri); } Test(otpauth, build_rejects_invalid_secret) { cotp_otpauth_uri u = {0}; u.type = COTP_OTPAUTH_TOTP; u.secret = (char *)"NOT BASE32 !!!"; u.algo = COTP_SHA1; u.digits = 6; u.period = 30; cotp_error_t err = NO_ERROR; char *uri = cotp_otpauth_uri_build (&u, &err); cr_expect_null (uri); cr_expect_eq (err, INVALID_B32_INPUT); } Test(otpauth, free_null_safe) { cotp_otpauth_uri_free (NULL); // must not crash } Test(otpauth, parse_malformed_pct_encoding_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?secret=AB%GG", &err)); cr_expect_eq (err, INVALID_USER_INPUT); } Test(otpauth, parse_pct_null_byte_rejected) { // %00 in any percent-decoded field would silently truncate the resulting C string; // the parser must reject it. cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?secret=AB%00CD", &err)); cr_expect_eq (err, INVALID_USER_INPUT); } Test(otpauth, parse_no_slash_after_type_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp", &err)); cr_expect_eq (err, INVALID_USER_INPUT); } Test(otpauth, parse_invalid_type_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://foo/x?secret=JBSWY3DPEHPK3PXP", &err)); cr_expect_eq (err, INVALID_USER_INPUT); } Test(otpauth, parse_negative_hotp_counter_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://hotp/x?secret=JBSWY3DPEHPK3PXP&counter=-5", &err)); cr_expect_eq (err, INVALID_COUNTER); } Test(otpauth, parse_empty_secret_value_rejected) { cotp_error_t err = NO_ERROR; cr_expect_null (cotp_otpauth_uri_parse ("otpauth://totp/x?secret=", &err)); cr_expect_eq (err, INVALID_USER_INPUT); } libcotp-4.2.1/tests/test_secure.c000066400000000000000000000034631522115210500170050ustar00rootroot00000000000000#include #include #include "../src/cotp.h" Test(secure_memzero, zeroes_buffer) { unsigned char buf[64]; memset (buf, 0xA5, sizeof buf); cotp_secure_memzero (buf, sizeof buf); for (size_t i = 0; i < sizeof buf; i++) { cr_expect_eq (buf[i], 0, "byte %zu was not zeroed (got 0x%02x)", i, buf[i]); } } Test(secure_memzero, null_or_zero_len_is_safe) { cotp_secure_memzero (NULL, 0); cotp_secure_memzero (NULL, 16); unsigned char buf[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; cotp_secure_memzero (buf, 0); cr_expect_eq (buf[0], 1, "len=0 must not modify the buffer"); cr_expect_eq (buf[7], 8, "len=0 must not modify the buffer"); } Test(timing_safe_memcmp, equal_returns_zero) { const unsigned char a[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 }; const unsigned char b[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 }; cr_expect_eq (cotp_timing_safe_memcmp (a, b, sizeof a), 0); } Test(timing_safe_memcmp, differ_first_byte_returns_nonzero) { const unsigned char a[] = { 0xFF, 0x11, 0x22, 0x33 }; const unsigned char b[] = { 0x00, 0x11, 0x22, 0x33 }; cr_expect_neq (cotp_timing_safe_memcmp (a, b, sizeof a), 0); } Test(timing_safe_memcmp, differ_last_byte_returns_nonzero) { const unsigned char a[] = { 0x11, 0x22, 0x33, 0x44 }; const unsigned char b[] = { 0x11, 0x22, 0x33, 0x45 }; cr_expect_neq (cotp_timing_safe_memcmp (a, b, sizeof a), 0); } Test(timing_safe_memcmp, zero_length_returns_zero) { cr_expect_eq (cotp_timing_safe_memcmp ("a", "b", 0), 0); } Test(timing_safe_memcmp, single_bit_difference_returns_nonzero) { const unsigned char a[] = { 0x00, 0x00, 0x00, 0x01 }; const unsigned char b[] = { 0x00, 0x00, 0x00, 0x00 }; cr_expect_neq (cotp_timing_safe_memcmp (a, b, sizeof a), 0); } libcotp-4.2.1/tests/test_strerror.c000066400000000000000000000021041522115210500173700ustar00rootroot00000000000000#include #include #include "../src/cotp.h" Test(strerror, every_enum_value_has_message) { const cotp_error_t codes[] = { NO_ERROR, VALID, WCRYPT_VERSION_MISMATCH, INVALID_B32_INPUT, INVALID_ALGO, INVALID_DIGITS, INVALID_PERIOD, MEMORY_ALLOCATION_ERROR, INVALID_USER_INPUT, EMPTY_STRING, MISSING_LEADING_ZERO, INVALID_COUNTER, WHMAC_ERROR, }; const size_t n = sizeof(codes) / sizeof(codes[0]); for (size_t i = 0; i < n; i++) { const char *s = cotp_strerror (codes[i]); cr_assert_not_null (s, "cotp_strerror(%d) returned NULL\n", codes[i]); cr_expect_gt (strlen (s), 0, "cotp_strerror(%d) returned empty string\n", codes[i]); } } Test(strerror, unknown_value_returns_unknown) { const char *s = cotp_strerror ((cotp_error_t)99999); cr_assert_not_null (s); cr_expect_str_eq (s, "unknown error"); } Test(strerror, no_error_message) { cr_expect_str_eq (cotp_strerror (NO_ERROR), "no error"); } libcotp-4.2.1/tests/test_validation.c000066400000000000000000000124641522115210500176520ustar00rootroot00000000000000#include #include #include #include "../src/cotp.h" #ifdef COTP_ENABLE_VALIDATION Test(validation, test_exact_match) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 8, 30, COTP_SHA1, &err); cr_assert_not_null (totp); int matched_delta = -999; int result = validate_totp_in_window (totp, K_base32, 59, 8, 30, COTP_SHA1, 1, &matched_delta, &err); cr_expect_eq (result, 1, "Expected match\n"); cr_expect_eq (matched_delta, 0, "Expected delta 0, got %d\n", matched_delta); cr_expect_eq (err, VALID, "Expected VALID, got %d\n", err); free (totp); free (K_base32); } Test(validation, test_no_match) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; int matched_delta = -999; int result = validate_totp_in_window ("00000000", K_base32, 59, 8, 30, COTP_SHA1, 0, &matched_delta, &err); cr_expect_eq (result, 0, "Expected no match\n"); free (K_base32); } Test(validation, test_window_offset_match) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); // Generate TOTP for timestamp 59 cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 8, 30, COTP_SHA1, &err); cr_assert_not_null (totp); // Validate at timestamp 59+30=89 (one period later) with window=1 should still match at delta=-1 int matched_delta = -999; int result = validate_totp_in_window (totp, K_base32, 89, 8, 30, COTP_SHA1, 1, &matched_delta, &err); cr_expect_eq (result, 1, "Expected match within window\n"); cr_expect_eq (matched_delta, -1, "Expected delta -1, got %d\n", matched_delta); free (totp); free (K_base32); } Test(validation, test_null_user_code) { cotp_error_t err; int result = validate_totp_in_window (NULL, "secret", 59, 8, 30, COTP_SHA1, 1, NULL, &err); cr_expect_eq (result, 0); cr_expect_eq (err, INVALID_USER_INPUT); } Test(validation, test_null_secret) { cotp_error_t err; int result = validate_totp_in_window ("12345678", NULL, 59, 8, 30, COTP_SHA1, 1, NULL, &err); cr_expect_eq (result, 0); cr_expect_eq (err, INVALID_USER_INPUT); } Test(validation, test_negative_window) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, 59, 8, 30, COTP_SHA1, &err); cr_assert_not_null (totp); // Negative window should be normalized to positive int matched_delta = -999; int result = validate_totp_in_window (totp, K_base32, 59, 8, 30, COTP_SHA1, -2, &matched_delta, &err); cr_expect_eq (result, 1, "Expected match with negative window\n"); cr_expect_eq (matched_delta, 0, "Expected delta 0, got %d\n", matched_delta); free (totp); free (K_base32); } Test(validation, test_window_above_max_rejected) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); // window > 1024 must be rejected with INVALID_USER_INPUT cotp_error_t err = NO_ERROR; int result = validate_totp_in_window ("12345678", K_base32, 59, 8, 30, COTP_SHA1, 2000, NULL, &err); cr_expect_eq (result, 0); cr_expect_eq (err, INVALID_USER_INPUT); free (K_base32); } Test(validation, test_window_int_min_safe) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); // INT_MIN must not crash via -INT_MIN; should be clamped, then exceeding-max rejected cotp_error_t err = NO_ERROR; int result = validate_totp_in_window ("12345678", K_base32, 59, 8, 30, COTP_SHA1, INT_MIN, NULL, &err); cr_expect_eq (result, 0); // INT_MIN is normalized to MAX_WINDOW (1024) which is the boundary; either it runs through without finding a match (NO_ERROR) or hits the > MAX rejection — both are acceptable outcomes here, the assertion is "doesn't crash". free (K_base32); } Test(validation, test_overflow_guard_large_timestamp) { const char *K = "12345678901234567890"; cotp_error_t cotp_err; char *K_base32 = base32_encode ((const uint8_t *)K, strlen(K)+1, &cotp_err); // timestamp near LONG_MAX with non-zero window: deltas whose addition would overflow // must be silently skipped (no UB, no crash). delta=0 still computes correctly so a // valid OTP at LONG_MAX should still match itself. cotp_error_t err = NO_ERROR; char *totp = get_totp_at (K_base32, LONG_MAX - 60, 8, 30, COTP_SHA1, &err); cr_assert_not_null (totp); cr_assert_eq (err, NO_ERROR); int matched_delta = -999; int result = validate_totp_in_window (totp, K_base32, LONG_MAX - 60, 8, 30, COTP_SHA1, 1024, &matched_delta, &err); cr_expect_eq (result, 1, "Expected delta=0 self-match even with overflowing positive deltas\n"); cr_expect_eq (matched_delta, 0); free (totp); free (K_base32); } #endif // COTP_ENABLE_VALIDATION libcotp-4.2.1/tests/test_yaotp.c000066400000000000000000000164661522115210500166620ustar00rootroot00000000000000#include #include #include #include #include "../src/cotp.h" // Known-answer vectors from KeeYaOtp/KeeYaOtp.Tests/YaotpTest.cs. // Source of truth for YAOTP correctness — these exercise the full Yandex secret format // (base32 with CRC-13) and pin lengths from KeeYaOtp's upstream test suite. // // Timestamps converted from the UTC strings in YaotpTest.cs: // 2020-02-07T08:27:00Z -> 1581064020 // 2020-02-07T15:53:30Z -> 1581090810 // 2020-02-07T16:04:29Z -> 1581091469 // 2020-02-07T16:30:59Z -> 1581093059 static const char *kSecret4 = "LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI"; static const char *kPin4 = "7586"; static const char *kSecret16 = "JBGSAU4G7IEZG6OY4UAXX62JU4AAAAAAHTSG4HXU3M"; static const char *kPin16 = "5210481216086702"; Test(yaotp, vector_pin4_t1) { cotp_error_t err = -1; char *code = get_yaotp_at (kSecret4, kPin4, 1581064020L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "oactmacq"); free (code); } Test(yaotp, vector_pin4_t2) { cotp_error_t err = -1; char *code = get_yaotp_at (kSecret4, kPin4, 1581090810L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "wemdwrix"); free (code); } Test(yaotp, vector_pin16_t1) { cotp_error_t err = -1; char *code = get_yaotp_at (kSecret16, kPin16, 1581091469L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "dfrpywob"); free (code); } Test(yaotp, vector_pin16_t2) { cotp_error_t err = -1; char *code = get_yaotp_at (kSecret16, kPin16, 1581093059L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "vunyprpd"); free (code); } Test(yaotp, pin_length_from_secret) { cotp_error_t err = -1; int n = cotp_yaotp_secret_pin_length (kSecret4, &err); cr_expect_eq (err, NO_ERROR); cr_expect_eq (n, 4); err = -1; n = cotp_yaotp_secret_pin_length (kSecret16, &err); cr_expect_eq (err, NO_ERROR); cr_expect_eq (n, 16); } Test(yaotp, output_shape) { cotp_error_t err = NO_ERROR; char *code = get_yaotp_at (kSecret4, kPin4, 1581064020L, &err); cr_assert_not_null (code); cr_expect_eq (strlen (code), 8); for (size_t i = 0; i < 8; i++) { cr_expect (code[i] >= 'a' && code[i] <= 'z', "char at %zu is not a-z: %c", i, code[i]); } free (code); } Test(yaotp, null_secret) { cotp_error_t err = NO_ERROR; char *code = get_yaotp_at (NULL, kPin4, 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_USER_INPUT); } Test(yaotp, null_pin) { cotp_error_t err = NO_ERROR; char *code = get_yaotp_at (kSecret4, NULL, 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_USER_INPUT); } Test(yaotp, wrong_pin_length) { cotp_error_t err = NO_ERROR; char *code = get_yaotp_at (kSecret4, "12345", 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_YAOTP_PIN); } Test(yaotp, non_digit_pin) { cotp_error_t err = NO_ERROR; char *code = get_yaotp_at (kSecret4, "abcd", 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_YAOTP_PIN); } Test(yaotp, non_base32_secret) { cotp_error_t err = NO_ERROR; char *code = get_yaotp_at ("!!!not-base32!!!", kPin4, 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_B32_INPUT); } Test(yaotp, secret_too_short) { // "JBSWY3DPEHPK3PXP" is a valid base32 string but decodes to 10 bytes — well under the 26-byte minimum. cotp_error_t err = NO_ERROR; char *code = get_yaotp_at ("JBSWY3DPEHPK3PXP", kPin4, 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_YAOTP_SECRET_LENGTH); } Test(yaotp, crc_invalid) { // Flip a bit in the key portion of kSecret4 — base32 stays valid, decoded length stays 26, // but the CRC-13 over the preceding bits no longer matches the stored 12-bit tail. // 'L' (10) -> 'M' (12) flips bit 1 of the first decoded byte. char tampered[64]; snprintf (tampered, sizeof (tampered), "%s", kSecret4); tampered[0] = 'M'; cotp_error_t err = NO_ERROR; char *code = get_yaotp_at (tampered, kPin4, 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_YAOTP_SECRET_CRC); } Test(yaotp, ctx_wrappers) { cotp_ctx *ctx = cotp_ctx_create (8, 30, COTP_SHA256); cr_assert_not_null (ctx); cotp_error_t err = -1; char *code = cotp_ctx_yaotp_at (ctx, kSecret4, kPin4, 1581064020L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "oactmacq"); free (code); err = NO_ERROR; code = cotp_ctx_yaotp_at (NULL, kSecret4, kPin4, 1581064020L, &err); cr_expect_null (code); cr_expect_eq (err, INVALID_USER_INPUT); cotp_ctx_free (ctx); } Test(yaotp, get_yaotp_returns_something) { // Smoke-test the wall-clock variant: we can't assert the value, only that it generates a code. cotp_error_t err = NO_ERROR; char *code = get_yaotp (kSecret4, kPin4, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_eq (strlen (code), 8); free (code); } Test(yaotp, secret_normalization_lowercase) { // Yandex QR secrets are uppercase base32; the library normalizes internally. // A lowercased secret must yield the same code (proves CRC/key extraction survives // normalization and that yaotp_b32_decoded_len agrees with base32_decode). cotp_error_t err = -1; char *code = get_yaotp_at ("la2v6kmcgymwwvew64rnp3ja3iaaaaaahtsg4hrzpi", kPin4, 1581064020L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "oactmacq"); free (code); } Test(yaotp, secret_normalization_spaces) { // Spaces are stripped during normalization; grouping the secret must not change the code. cotp_error_t err = -1; char *code = get_yaotp_at ("LA2V 6KMC GYMW WVEW 64RN P3JA 3IAA AAAA HTSG 4HRZ PI", kPin4, 1581064020L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "oactmacq"); free (code); } Test(yaotp, pin_length_error_paths) { cotp_error_t err = NO_ERROR; // NULL secret. cr_expect_eq (cotp_yaotp_secret_pin_length (NULL, &err), -1); cr_expect_eq (err, INVALID_USER_INPUT); // Valid base32 but too short to be a Yandex secret (10 bytes < 26). err = NO_ERROR; cr_expect_eq (cotp_yaotp_secret_pin_length ("JBSWY3DPEHPK3PXP", &err), -1); cr_expect_eq (err, INVALID_YAOTP_SECRET_LENGTH); // Corrupted CRC (same tamper as the crc_invalid test). char tampered[64]; snprintf (tampered, sizeof (tampered), "%s", kSecret4); tampered[0] = 'M'; err = NO_ERROR; cr_expect_eq (cotp_yaotp_secret_pin_length (tampered, &err), -1); cr_expect_eq (err, INVALID_YAOTP_SECRET_CRC); // NULL err_code argument must not crash and still returns the pin length. cr_expect_eq (cotp_yaotp_secret_pin_length (kSecret4, NULL), 4); } Test(yaotp, null_err_code_ok) { // get_yaotp_at supports a NULL err_code; it must not crash and must still compute. char *code = get_yaotp_at (kSecret4, kPin4, 1581064020L, NULL); cr_assert_not_null (code); cr_expect_str_eq (code, "oactmacq"); free (code); } libcotp-4.2.1/tests/test_yaotp_uri.c000066400000000000000000000154441522115210500175340ustar00rootroot00000000000000#include #include #include #include "../src/cotp.h" static const char *kYandexUri = "otpauth://yaotp/alice%40yandex.ru" "?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI" "&pin_length=4" "&issuer=Yandex" "&track_id=abc123" "&uid=987654321"; Test(yaotp_uri, parse_basic) { cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (kYandexUri, &err); cr_assert_not_null (u); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (u->secret, "LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI"); cr_expect_str_eq (u->account, "alice@yandex.ru"); cr_expect_str_eq (u->issuer, "Yandex"); cr_expect_str_eq (u->track_id, "abc123"); cr_expect_str_eq (u->uid, "987654321"); cr_expect_eq (u->pin_length, 4); cotp_yaotp_uri_free (u); } Test(yaotp_uri, parse_minimal) { const char *uri = "otpauth://yaotp/user?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI&pin_length=4"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (u->account, "user"); cr_expect_eq (u->pin_length, 4); cr_expect_null (u->issuer); cr_expect_null (u->track_id); cr_expect_null (u->uid); cotp_yaotp_uri_free (u); } Test(yaotp_uri, name_query_used_when_label_empty) { const char *uri = "otpauth://yaotp/?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI&pin_length=4&name=fromname"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_str_eq (u->account, "fromname"); cotp_yaotp_uri_free (u); } Test(yaotp_uri, label_takes_precedence_over_name) { const char *uri = "otpauth://yaotp/fromlabel?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI&pin_length=4&name=fromname"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_str_eq (u->account, "fromlabel"); cotp_yaotp_uri_free (u); } Test(yaotp_uri, reject_missing_secret) { const char *uri = "otpauth://yaotp/user?pin_length=4"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_expect_null (u); cr_expect_eq (err, INVALID_USER_INPUT); } Test(yaotp_uri, reject_missing_pin_length) { const char *uri = "otpauth://yaotp/user?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_expect_null (u); cr_expect_eq (err, INVALID_YAOTP_PIN); } Test(yaotp_uri, reject_pin_length_out_of_range_low) { const char *uri = "otpauth://yaotp/user?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI&pin_length=3"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_expect_null (u); cr_expect_eq (err, INVALID_YAOTP_PIN); } Test(yaotp_uri, reject_pin_length_out_of_range_high) { const char *uri = "otpauth://yaotp/user?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI&pin_length=17"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_expect_null (u); cr_expect_eq (err, INVALID_YAOTP_PIN); } Test(yaotp_uri, reject_wrong_scheme) { const char *uri = "otpauth://totp/user?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI&pin_length=4"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_expect_null (u); cr_expect_eq (err, INVALID_USER_INPUT); } Test(yaotp_uri, reject_null) { cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (NULL, &err); cr_expect_null (u); cr_expect_eq (err, INVALID_USER_INPUT); } Test(yaotp_uri, build_round_trip) { cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u1 = cotp_yaotp_uri_parse (kYandexUri, &err); cr_assert_not_null (u1); char *built = cotp_yaotp_uri_build (u1, &err); cr_assert_not_null (built); cr_expect_eq (err, NO_ERROR); cotp_yaotp_uri *u2 = cotp_yaotp_uri_parse (built, &err); cr_assert_not_null (u2); cr_expect_str_eq (u2->secret, u1->secret); cr_expect_str_eq (u2->account, u1->account); cr_expect_str_eq (u2->issuer, u1->issuer); cr_expect_str_eq (u2->track_id, u1->track_id); cr_expect_str_eq (u2->uid, u1->uid); cr_expect_eq (u2->pin_length, u1->pin_length); free (built); cotp_yaotp_uri_free (u1); cotp_yaotp_uri_free (u2); } Test(yaotp_uri, build_minimal) { cotp_yaotp_uri u = {0}; u.secret = strdup ("LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI"); u.pin_length = 4; cotp_error_t err = NO_ERROR; char *built = cotp_yaotp_uri_build (&u, &err); cr_assert_not_null (built); cr_expect_eq (err, NO_ERROR); // Should not contain optional fields. cr_expect_null (strstr (built, "issuer")); cr_expect_null (strstr (built, "track_id")); cr_expect_null (strstr (built, "uid")); cr_expect_not_null (strstr (built, "secret=")); cr_expect_not_null (strstr (built, "pin_length=4")); free (built); free (u.secret); } Test(yaotp_uri, build_rejects_invalid_pin_length) { cotp_yaotp_uri u = {0}; u.secret = (char *)"LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI"; u.pin_length = 0; cotp_error_t err = NO_ERROR; char *built = cotp_yaotp_uri_build (&u, &err); cr_expect_null (built); cr_expect_eq (err, INVALID_YAOTP_PIN); } Test(yaotp_uri, end_to_end_uri_to_code) { // Chain the URI parser to the generator: parse, then feed the extracted secret + PIN // straight into get_yaotp_at. Uses the same known-answer vector as test_yaotp.c. const char *uri = "otpauth://yaotp/user?secret=LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI&pin_length=4"; cotp_error_t err = NO_ERROR; cotp_yaotp_uri *u = cotp_yaotp_uri_parse (uri, &err); cr_assert_not_null (u); cr_expect_eq (err, NO_ERROR); cr_expect_eq (u->pin_length, 4); char *code = get_yaotp_at (u->secret, "7586", 1581064020L, &err); cr_assert_not_null (code); cr_expect_eq (err, NO_ERROR); cr_expect_str_eq (code, "oactmacq"); free (code); cotp_yaotp_uri_free (u); } Test(yaotp_uri, build_percent_encodes_account) { // '@' is not RFC 3986 unreserved, so the shared pct codec must emit %40 in the label. cotp_yaotp_uri u = {0}; u.secret = strdup ("LA2V6KMCGYMWWVEW64RNP3JA3IAAAAAAHTSG4HRZPI"); u.account = strdup ("alice@yandex.ru"); u.pin_length = 4; cotp_error_t err = NO_ERROR; char *built = cotp_yaotp_uri_build (&u, &err); cr_assert_not_null (built); cr_expect_eq (err, NO_ERROR); cr_expect_not_null (strstr (built, "yaotp/alice%40yandex.ru")); free (built); free (u.secret); free (u.account); } Test(yaotp_uri, free_null_is_safe) { cotp_yaotp_uri_free (NULL); }