pax_global_header00006660000000000000000000000064151472755570014534gustar00rootroot0000000000000052 comment=d82cb520a11523286fc56da782b10ee0bb22a533 libcotp-4.0.0/000077500000000000000000000000001514727555700131715ustar00rootroot00000000000000libcotp-4.0.0/.circleci/000077500000000000000000000000001514727555700150245ustar00rootroot00000000000000libcotp-4.0.0/.circleci/config.yml000066400000000000000000000064441514727555700170240ustar00rootroot00000000000000version: 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.0.0/.github/000077500000000000000000000000001514727555700145315ustar00rootroot00000000000000libcotp-4.0.0/.github/workflows/000077500000000000000000000000001514727555700165665ustar00rootroot00000000000000libcotp-4.0.0/.github/workflows/codeql-analysis.yml000066400000000000000000000025351514727555700224060ustar00rootroot00000000000000name: "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.0.0/.gitignore000066400000000000000000000003301514727555700151550ustar00rootroot00000000000000.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.0.0/CMakeLists.txt000066400000000000000000000112741514727555700157360ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.16) project(cotp VERSION "4.0.0" LANGUAGES "C") set(CMAKE_C_STANDARD 11) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(GNUInstallDirs) include(CMakePackageConfigHelpers) 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 ) 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(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(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 ${HMAC_SOURCE_FILES} src/utils/base32.c src/utils/secure_zero.c src/ctx.c ) if (COTP_ENABLE_VALIDATION) list(APPEND SOURCE_FILES src/utils/validation.c) endif() add_library(cotp ${SOURCE_FILES}) 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}) 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 -Wno-format-nonliteral -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3) set_target_properties(cotp PROPERTIES VERSION ${CMAKE_PROJECT_VERSION} SOVERSION ${CMAKE_PROJECT_VERSION_MAJOR}) if (BUILD_TESTS) enable_testing() add_subdirectory(tests) 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.0.0/LICENSE000066400000000000000000000261211514727555700142000ustar00rootroot00000000000000 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.0.0/README.md000066400000000000000000000115411514727555700144520ustar00rootroot00000000000000# libcotp Coverity Scan Build Status C library that generates TOTP and HOTP according to [RFC-6238](https://www.rfc-editor.org/rfc/rfc6238). ## 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 | | `-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 | --- ## 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_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); int64_t otp_to_int(const char *otp, cotp_error_t *err); ``` ### Parameter Constraints - `base32_secret`: Base32 encoded (may contain spaces). `NULL` is invalid. - `digits`: 4–10 inclusive - `period`: 1–120 seconds inclusive - `algo`: `SHA1`, `SHA256`, `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, SHA1, &err); if (!code) { // handle error } free(code); ``` --- ## Error Model | Error | Meaning | |-------|---------| | `NO_ERROR` | Success | | `VALID` | Validation helper matched | | `WHMAC_ERROR` | Backend crypto error | | `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 | Return rules: - `get_totp`, `get_totp_at`, `get_steam_totp`, `get_hotp` → `NULL` on failure - `otp_to_int` → `-1` on failure --- ## 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 --- ## Context API ```c cotp_ctx *cotp_ctx_create(int digits, int period, int sha_algo); char *cotp_ctx_totp_at(cotp_ctx *ctx, const char *base32_secret, long timestamp, cotp_error_t *err); char *cotp_ctx_totp(cotp_ctx *ctx, const char *base32_secret, cotp_error_t *err); void cotp_ctx_free(cotp_ctx *ctx); ``` --- ## 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 output + `EMPTY_STRING` - spaces allowed - invalid base32 → `INVALID_B32_INPUT` --- ## Operational Notes - TOTP requires correct system time (use NTP) - Validation should allow small window (±1–2 periods) - Secrets should be handled securely libcotp-4.0.0/SECURITY.md000066400000000000000000000023671514727555700147720ustar00rootroot00000000000000# 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.0.0/cmake/000077500000000000000000000000001514727555700142515ustar00rootroot00000000000000libcotp-4.0.0/cmake/COTPConfig.cmake.in000066400000000000000000000002421514727555700175510ustar00rootroot00000000000000@PACKAGE_INIT@ include(CMakeFindDependencyMacro) # Consumers will link to the exported COTP::cotp target include("${CMAKE_CURRENT_LIST_DIR}/cotpTargets.cmake") libcotp-4.0.0/cmake/FindGcrypt.cmake000066400000000000000000000031761514727555700173330ustar00rootroot00000000000000# 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.0.0/cmake/FindMbedTLS.cmake000066400000000000000000000073751514727555700173220ustar00rootroot00000000000000#*************************************************************************** # _ _ ____ _ # 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} ) 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}) endif() mark_as_advanced(MBEDTLS_INCLUDE_DIR MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY) libcotp-4.0.0/cotp.pc.in000066400000000000000000000004751514727555700150750ustar00rootroot00000000000000prefix=@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.0.0/src/000077500000000000000000000000001514727555700137605ustar00rootroot00000000000000libcotp-4.0.0/src/cotp.h000066400000000000000000000122041514727555700150750ustar00rootroot00000000000000#pragma once #include #include #define COTP_SHA1 0 #define COTP_SHA256 1 #define COTP_SHA512 2 #define MIN_DIGITS 4 #define MAX_DIGITS 10 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 } 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. */ 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); #endif // Context helpers cotp_ctx* cotp_ctx_create(int digits, int period, int sha_algo); void cotp_ctx_free(cotp_ctx* ctx); char* cotp_ctx_totp_at(cotp_ctx* ctx, const char* base32_encoded_secret, long timestamp, cotp_error_t* err); char* cotp_ctx_totp(cotp_ctx* ctx, const char* base32_encoded_secret, 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. */ 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. */ 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. */ 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. */ 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. */ 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. */ 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. */ 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. */ char *get_steam_totp_at (const char *base32_encoded_secret, long timestamp, int period, 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. */ int64_t otp_to_int (const char *otp, cotp_error_t *err_code); #ifdef __cplusplus } #endif libcotp-4.0.0/src/ctx.c000066400000000000000000000023271514727555700147260ustar00rootroot00000000000000#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) { 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); } libcotp-4.0.0/src/otp.c000066400000000000000000000266351514727555700147420ustar00rootroot00000000000000#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) \ for (int j = 0, i = 7; j < 8; j++, i--) { \ (C_reverse_byte_order)[i] = ((unsigned char *)&(C))[j]; \ } #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define REVERSE_BYTES(C, C_reverse_byte_order) \ for (int j = 0; j < 8; j++) { \ (C_reverse_byte_order)[j] = ((unsigned char *)&(C))[j]; \ } #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 && err != VALID) { *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') { free(normalized_K); *err_code = EMPTY_STRING; return NULL; } size_t secret_len = b32_decoded_len_from_str(normalized_K); unsigned char *secret = base32_decode (normalized_K, strlen(normalized_K), err_code); 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; } whmac_update (hd, C_reverse_byte_order, sizeof(C_reverse_byte_order)); 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.0.0/src/utils/000077500000000000000000000000001514727555700151205ustar00rootroot00000000000000libcotp-4.0.0/src/utils/base32.c000066400000000000000000000204221514727555700163430ustar00rootroot00000000000000#include #include #include "../cotp.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, int32_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) { *err_code = error; return strdup (""); } 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 (int 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 (int i = 0, j = 0; i < user_data_chars; i += 5) { uint64_t quintuple = 0; for (int 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) { *err_code = error; return (uint8_t *)strdup (""); } 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; } data_len -= strip_char (user_data); if (!is_string_valid_b32 (user_data)) { free (user_data); *err_code = INVALID_B32_INPUT; return NULL; } size_t user_data_chars = 0; for (int i = 0; i < data_len; i++) { // As it's not known whether data_len is with or without the +1 for the null byte, a manual check is required. if (user_data[i] != '=' && user_data[i] != '\0') { 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) { 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 (int i = 0; i < (int)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'; 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; } while (*str) { uint8_t c = (uint8_t)*str; if (c >= 128 || !b32_valid[c]) { return false; } str++; } 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, int32_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.0.0/src/utils/secure_zero.c000066400000000000000000000014571514727555700176200ustar00rootroot00000000000000#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.0.0/src/utils/secure_zero.h000066400000000000000000000005771514727555700176270ustar00rootroot00000000000000#pragma once #include #ifdef __cplusplus extern "C" { #endif // Wipes memory in a way that compilers must not elide. Use for secrets and HMAC outputs. void cotp_secure_memzero(void *ptr, size_t len); // Constant-time comparison. Returns 0 if equal, non-zero otherwise. int cotp_timing_safe_memcmp(const void *a, const void *b, size_t len); #ifdef __cplusplus } #endif libcotp-4.0.0/src/utils/validation.c000066400000000000000000000031371514727555700174220ustar00rootroot00000000000000#include #include #include "../cotp.h" #include "secure_zero.h" #ifdef COTP_ENABLE_VALIDATION 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 if (window < 0) window = -window; size_t user_len = strlen(user_code); // Try [-window, +window] for (int delta = -window; delta <= window; ++delta) { long t = timestamp + (long)delta * (long)period; 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); int ok = (gen_len == user_len) && (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.0.0/src/utils/whmac_gcrypt.c000066400000000000000000000043461514727555700177620ustar00rootroot00000000000000#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 > 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; } void whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { gcry_md_write (hd->hd, buffer, buflen); } 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.0.0/src/utils/whmac_mbedtls.c000066400000000000000000000040621514727555700200770ustar00rootroot00000000000000#include #include #include "../whmac.h" #include "../cotp.h" typedef struct whmac_handle_s whmac_handle_t; 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 openssl_algo[] = { MBEDTLS_MD_SHA1, MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA512, }; whmac_handle_t *whmac_handle = calloc (1, sizeof(*whmac_handle)); if (whmac_handle == NULL) { return NULL; } if (algo > 2) { free (whmac_handle); return NULL; } mbedtls_md_init (&(whmac_handle->sha_ctx)); whmac_handle->md_info = mbedtls_md_info_from_type (openssl_algo[algo]); 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; } void whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { mbedtls_md_hmac_update (&(hd->sha_ctx), buffer, buflen); } ssize_t whmac_finalize (whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { size_t dlen = mbedtls_md_get_size(hd->md_info); if (buffer == NULL) { return (ssize_t)dlen; } if (dlen > buflen) { return -MEMORY_ALLOCATION_ERROR; } mbedtls_md_hmac_finish (&(hd->sha_ctx), buffer); return (ssize_t)dlen; } libcotp-4.0.0/src/utils/whmac_openssl.c000066400000000000000000000044501514727555700201310ustar00rootroot00000000000000#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 > 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) { 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; 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; } void whmac_update (whmac_handle_t *hd, const unsigned char *buffer, size_t buflen) { EVP_MAC_update (hd->ctx, buffer, buflen); } ssize_t whmac_finalize(whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { size_t dlen = EVP_MAC_CTX_get_mac_size (hd->ctx); if (buffer == NULL) { return dlen; } if (dlen > buflen) { return -MEMORY_ALLOCATION_ERROR; } EVP_MAC_final (hd->ctx, buffer, &dlen, buflen); EVP_MAC_CTX_free (hd->ctx); hd->ctx = NULL; return dlen; } libcotp-4.0.0/src/whmac.h000066400000000000000000000014221514727555700152270ustar00rootroot00000000000000#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); void 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.0.0/tests/000077500000000000000000000000001514727555700143335ustar00rootroot00000000000000libcotp-4.0.0/tests/CMakeLists.txt000066400000000000000000000012701514727555700170730ustar00rootroot00000000000000add_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) 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) 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) libcotp-4.0.0/tests/docker/000077500000000000000000000000001514727555700156025ustar00rootroot00000000000000libcotp-4.0.0/tests/docker/Dockerfile000066400000000000000000000016421514727555700175770ustar00rootroot00000000000000FROM 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.0.0/tests/docker/PKGBUILD000066400000000000000000000035601514727555700167320ustar00rootroot00000000000000# 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.0.0/tests/docker/run_docker.sh000066400000000000000000000002241514727555700202670ustar00rootroot00000000000000#!/bin/bash if [[ -z "$1" ]]; then echo "Usage: $0 " exit 1 fi docker build -t "testme:Dockerfile" --build-arg BRANCH="$1" . libcotp-4.0.0/tests/test_base32_roundtrip.c000066400000000000000000000035321514727555700207260ustar00rootroot00000000000000#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.0.0/tests/test_base32decode.c000066400000000000000000000065251514727555700177710ustar00rootroot00000000000000#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); }libcotp-4.0.0/tests/test_base32encode.c000066400000000000000000000076551514727555700200100ustar00rootroot00000000000000#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; base32_encode (NULL, 30, &err); 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.0.0/tests/test_otp.c000066400000000000000000000233771514727555700163540ustar00rootroot00000000000000#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++) { int64_t totp = otp_to_int (get_totp_at (K_base32, counter[i], 8, 30, COTP_SHA1, &err), &err); cr_expect_eq (totp, expected_totp[i], "Expected %08ld to be equal to %08ld\n", totp, expected_totp[i]); } 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; int64_t totp = otp_to_int (get_totp_at (K_base32, counter, 10, 30, COTP_SHA1, &err), &err); cr_expect_eq (totp, expected_totp, "Expected %010ld to be equal to %010ld\n", totp, expected_totp); 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; int64_t totp = otp_to_int (get_totp_at (K_base32, counter, 10, 30, COTP_SHA1, &err), &err); cr_expect_eq (err, MISSING_LEADING_ZERO, "Expected %d to be equal to %d\n", err, MISSING_LEADING_ZERO); 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); }