pax_global_header00006660000000000000000000000064145362671470014531gustar00rootroot0000000000000052 comment=60461cd28c297eed476ff93d9b1123c3855c7053 libcotp-3.0.0/000077500000000000000000000000001453626714700131655ustar00rootroot00000000000000libcotp-3.0.0/.circleci/000077500000000000000000000000001453626714700150205ustar00rootroot00000000000000libcotp-3.0.0/.circleci/config.yml000066400000000000000000000017361453626714700170170ustar00rootroot00000000000000version: 2.0 jobs: debian: docker: - image: debian:testing steps: - checkout - run: command: | 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 ubuntu: docker: - image: ubuntu:latest steps: - checkout - run: command: | 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 workflows: version: 2 build: jobs: - debian - ubuntu libcotp-3.0.0/.github/000077500000000000000000000000001453626714700145255ustar00rootroot00000000000000libcotp-3.0.0/.github/workflows/000077500000000000000000000000001453626714700165625ustar00rootroot00000000000000libcotp-3.0.0/.github/workflows/codeql-analysis.yml000066400000000000000000000025351453626714700224020ustar00rootroot00000000000000name: "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-3.0.0/.gitignore000066400000000000000000000004301453626714700151520ustar00rootroot00000000000000.idea/ cmake-build-debug/ build/ # Object files *.o *.ko *.obj *.elf # Precompiled Headers *.gch *.pch # Libraries *.lib *.a *.la *.lo # Shared objects (inc. Windows DLLs) *.dll *.so *.so.* *.dylib # Executables *.exe *.out *.app *.i*86 *.x86_64 *.hex # Debug files *.dSYM/ libcotp-3.0.0/CMakeLists.txt000066400000000000000000000072731453626714700157360ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.16) project(cotp VERSION "3.0.0" LANGUAGES "C") set(CMAKE_C_STANDARD 11) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(GNUInstallDirs) find_package(PkgConfig REQUIRED) 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 "library to use during hmac computation") 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_LIBRARY_DIRS ${GCRYPT_LIBRARY_DIRS}) set(HMAC_LIBRARIES ${GCRYPT_LIBRARIES}) message("libcotp will use gcrypt for hmac") 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_LIBRARY_DIRS ${OPENSSL_LIBRARY_DIRS}) set(HMAC_LIBRARIES ${OPENSSL_LIBRARIES}) message("libcotp will use openssl for hmac") else() message("libcotp can't use ${HMAC_WRAPPER} for hmac") endif() include_directories(${HMAC_INCLUDE_DIR}) link_directories(${HMAC_LIBRARY_DIRS}) if (BUILD_TESTS) add_subdirectory(tests) endif () set(COTP_HEADERS src/cotp.h ) set(SOURCE_FILES src/otp.c ${HMAC_SOURCE_FILES} src/utils/base32.c ) # Set compiler flags for all targets add_compile_options(-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) add_library(cotp ${SOURCE_FILES}) target_link_libraries(cotp ${HMAC_LIBRARIES}) target_include_directories(cotp PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src 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) target_link_directories(cotp PRIVATE ${HMACLIBRARY_DIRS}) set_target_properties(cotp PROPERTIES VERSION ${CMAKE_PROJECT_VERSION} SOVERSION ${CMAKE_PROJECT_VERSION_MAJOR}) set(COTP_LIB_DIR "${CMAKE_INSTALL_LIBDIR}") set(COTP_INC_DIR "${CMAKE_INSTALL_INCLUDEDIR}") install( TARGETS cotp ARCHIVE DESTINATION ${COTP_LIB_DIR} LIBRARY DESTINATION ${COTP_LIB_DIR} COMPONENT library ) install( FILES ${COTP_HEADERS} DESTINATION ${COTP_INC_DIR} ) # 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/) libcotp-3.0.0/LICENSE000066400000000000000000000261211453626714700141740ustar00rootroot00000000000000 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-3.0.0/README.md000066400000000000000000000131301453626714700144420ustar00rootroot00000000000000# libcotp Coverity Scan Build Status C library that generates TOTP and HOTP according to [RFC-6238](https://tools.ietf.org/html/rfc6238) ## Requirements - GCC/Clang and CMake to build the library - libgcrypt or openssl ## Build and Install ``` $ git clone https://github.com/paolostivanin/libcotp.git $ cd libcotp $ mkdir build && cd $_ $ cmake -DCMAKE_INSTALL_PREFIX=/usr .. $ make # make install ``` Available options you can pass to `cmake`: * `-DBUILD_TESTS=ON`: if you want to compile also the tests (default **OFF**, requires criterion) * `-DBUILD_SHARED_LIBS=ON`: if you want to build libcotp as a shared library (default **ON**) * `-DHMAC_WRAPPER=""`: you can choose between GCrypt and OpenSSL (default **Gcrypt**) ## How To Use It ``` char *totp = get_totp (const char *base32_encoded_secret, int digits, int period, int algo, cotp_error_t *err); char *steam_totp = get_steam_totp (const char *secret, int period, cotp_error_t *err); char *hotp = get_hotp (const char *base32_encoded_secret, long counter, int digits, int algo, cotp_error_t *err); char *totp_at = get_totp_at (const char *base32_encoded_secret, long target_date, int digits, int algo, cotp_error_t *err); int64_t otp_i = otp_to_int (const char *otp, cotp_error_t *err_code); ``` where: - `secret_key` is the **base32 encoded** secret. Usually, a website gives you the secret already base32 encoded, so you should pay attention to not encode the secret again. The format of the secret can either be `hxdm vjec jjws` or `HXDMVJECJJWS`. In the first case, the library will normalize the secret to second format before computing the OTP. - `digits` is between `3` and `10` inclusive - `period` is between `1` and `120` inclusive - `counter` is a value decided with the server - `target_date` is the target date specified as the **unix epoch format in seconds** - `algo` is either `SHA1`, `SHA256` or `SHA512` ## Return values `get_totp`, `get_hotp` and `get_totp_at` return `NULL` if an error occurs and `err` is set to one of the following values: Errors: - `GCRYPT_VERSION_MISMATCH`, set if the installed Gcrypt library is too old - `INVALID_B32_INPUT`, set if the given input is not valid base32 text - `INVALID_ALGO`, set if the given algo is not supported by the library - `INVALID_PERIOD`, set if `period` is `<= 0` or `> 120` seconds - `INVALID_DIGITS`, set if `digits` is `< 4` or `> 10` - `MEMORY_ALLOCATION_ERROR`, set if an error happened during memory allocation - `INVALID_USER_INPUT`, set if the given input is not valid - `INVALID_COUNTER`, set if `counter` is `< 0` All good: - `NO_ERROR`, set if no error occurred - `VALID`, set if the given OTP is valid The function `otp_to_int`: * returns `-1` if an error occurs and sets `err` to `INVALID_USER_INPUT`. * warns the user if the leading zero is missing. For example, since the otp string `"012345"` **can't** be returned as the integer `012345` (because it would be interpreted as octal number), the function returns `12345` and sets `err` to `MISSING_LEADING_ZERO`) In case of success, the value returned by `get_totp`, `get_hotp`, `get_totp_at` and `get_steam_totp` **must be freed** once no longer needed. # Base32 encoding and decoding Since release 2.0.0, libbaseencode has been merged with libcotp. This means that you can now use base32 functions by just including `cotp.h`: ``` char *base32_encode (const uchar *user_data, size_t data_len, cotp_error_t *err_code); uchar *base32_decode (const char *user_data, size_t data_len, cotp_error_t *err_code); bool is_string_valid_b32 (const char *user_data); ``` where: - `user_data` is the data to be encoded or decoded - `data_len` is the length of the data to be encoded/decoded - `err_code` is where the error is stored `base32_encode` returns `NULL` if an error occurs and `err_code` is set to one of the following values: - `INVALID_USER_INPUT`, set if the given input is not valid - `MEMORY_ALLOCATION_ERROR`, set if an error happened during memory allocation - `INVALID_USER_INPUT`, set if the given input is not valid `base32_decode` returns `NULL` if an error occurs and `err_code` is set to one of the following values: - `INVALID_USER_INPUT`, set if the given input is not valid - `MEMORY_ALLOCATION_ERROR`, set if an error happened during memory allocation - `INVALID_B32_INPUT`, set if the given input is not valid base32 text - `INVALID_USER_INPUT`, set if the given input is not valid Both functions return and empty string if the input is an empty string. In such a case, `err` is set to `EMPTY_STRING`. `is_string_valid_b32` returns `true` if `user_data` is a valid base32 encoded string, `false` otherwise. Please note that `user_data` can contain spaces, since the fucntion will also take care of trimming those. libcotp-3.0.0/SECURITY.md000066400000000000000000000017631453626714700147650ustar00rootroot00000000000000# Security Policy ## Supported Versions The following list describes whether a version is eligible or not for security updates. | Version | Supported | EOL | |---------| ------------------ |-------------| | 3.0.x | :white_check_mark: | - | | 2.0.x | :white_check_mark: | 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 Should you find a vulnerability, please report it privately to me via [e-mail](mailto:paolostivanin@users.noreply.github.com). The following is the workflow: - security issue is found, an e-mail is sent to me - within 24 hours I will reply to your e-mail with some info like, for example, whether it actually is a security issue and how serious it is - within 7 days I will develop and ship a fix - once the update is out I will open a [security advisory](https://github.com/paolostivanin/OTPClient/security/advisories) libcotp-3.0.0/cmake/000077500000000000000000000000001453626714700142455ustar00rootroot00000000000000libcotp-3.0.0/cmake/FindGcrypt.cmake000066400000000000000000000030401453626714700173150ustar00rootroot00000000000000# 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) find_library(GCRYPT_LIBRARIES gcrypt) 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-3.0.0/cotp.pc.in000066400000000000000000000005021453626714700150600ustar00rootroot00000000000000prefix=@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: URL: https://github.com/paolostivanin/libcotp Libs: -L${libdir} -lcotp Cflags: -I${includedir} libcotp-3.0.0/src/000077500000000000000000000000001453626714700137545ustar00rootroot00000000000000libcotp-3.0.0/src/cotp.h000066400000000000000000000044401453626714700150740ustar00rootroot00000000000000#pragma once #include #include #define SHA1 0 #define SHA256 1 #define SHA512 2 #define MIN_DIGTS 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; typedef unsigned char uchar; #ifdef __cplusplus extern "C" { #endif extern const uint8_t b32_alphabet[]; char *base32_encode (const uchar *user_data, size_t data_len, cotp_error_t *err_code); uchar *base32_decode (const char *user_data_untrimmed, size_t data_len, cotp_error_t *err_code); bool is_string_valid_b32 (const char *user_data); char *get_hotp (const char *base32_encoded_secret, long counter, int digits, int sha_algo, cotp_error_t *err_code); char *get_totp (const char *base32_encoded_secret, int digits, int period, int sha_algo, cotp_error_t *err_code); char *get_steam_totp (const char *base32_encoded_secret, int period, cotp_error_t *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); char *get_steam_totp_at (const char *base32_encoded_secret, long timestamp, int period, cotp_error_t *err_code); int64_t otp_to_int (const char *otp, cotp_error_t *err_code); #ifdef __cplusplus } #endif libcotp-3.0.0/src/otp.c000066400000000000000000000211561453626714700147270ustar00rootroot00000000000000#include #include #include #include #include #include "whmac.h" #include "cotp.h" static char *normalize_secret (const char *K); static char *get_steam_code (const uchar *hmac, whmac_handle_t *hd); static int truncate (const uchar *hmac, int digits_length, whmac_handle_t *hd); static uchar *compute_hmac (const char *K, long C, whmac_handle_t *hd); 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) { if (whmac_check () == -1) { *err_code = WCRYPT_VERSION_MISMATCH; return NULL; } if (check_algo (algo) == INVALID_ALGO) { *err_code = INVALID_ALGO; return NULL; } if (check_otp_len (digits) == INVALID_DIGITS) { *err_code = INVALID_DIGITS; return NULL; } if (counter < 0) { *err_code = INVALID_COUNTER; return NULL; } whmac_handle_t *hd = whmac_gethandle (algo); if (hd == NULL) { fprintf (stderr, "Error while opening the cipher handle.\n"); return NULL; } unsigned char *hmac = compute_hmac (secret, counter, hd); if (hmac == NULL) { *err_code = WHMAC_ERROR; whmac_freehandle (hd); return NULL; } int tk = truncate (hmac, digits, hd); whmac_freehandle (hd); free (hmac); *err_code = 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) { if (whmac_check () == -1) { *err_code = WCRYPT_VERSION_MISMATCH; return NULL; } if (check_otp_len (digits) == INVALID_DIGITS) { *err_code = INVALID_DIGITS; return NULL; } if (check_period (period) == INVALID_PERIOD) { *err_code = 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) { *err_code = err; return NULL; } *err_code = 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) { if (whmac_check () == -1) { *err_code = WCRYPT_VERSION_MISMATCH; return NULL; } if (check_period (period) == INVALID_PERIOD) { *err_code = INVALID_PERIOD; return NULL; } whmac_handle_t *hd = whmac_gethandle (SHA1); if (hd == NULL) { fprintf (stderr, "Error while opening the cipher handle.\n"); return NULL; } unsigned char *hmac = compute_hmac (secret, current_timestamp / period, hd); if (hmac == NULL) { *err_code = WHMAC_ERROR; whmac_freehandle (hd); return NULL; } char *totp = get_steam_code (hmac, hd); whmac_freehandle (hd); *err_code = NO_ERROR; free(hmac); return totp; } int64_t otp_to_int (const char *otp, cotp_error_t *err_code) { size_t len = strlen (otp); if (len < MIN_DIGTS || len > MAX_DIGITS) { *err_code = INVALID_USER_INPUT; return -1; } if (otp[0] == '0') { *err_code = MISSING_LEADING_ZERO; } else { *err_code = NO_ERROR; } return strtoll (otp, NULL, 10); } static char * normalize_secret (const char *K) { char *nK = calloc (strlen (K) + 1, 1); if (nK == NULL) { fprintf (stderr, "Error during memory allocation\n"); return nK; } for (int i = 0, j = 0; K[i] != '\0'; i++) { if (K[i] != ' ') { nK[j++] = islower(K[i]) ? (char) toupper(K[i]) : K[i]; } } return nK; } static char * get_steam_code (const unsigned char *hmac, whmac_handle_t *hd) { int offset = (hmac[whmac_getlen(hd)-1] & 0x0f); // Starting from the offset, take the successive 4 bytes while stripping the topmost bit to prevent it being handled as a signed integer int bin_code = ((hmac[offset] & 0x7f) << 24) | ((hmac[offset + 1] & 0xff) << 16) | ((hmac[offset + 2] & 0xff) << 8) | ((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++) { int mod = (int)(bin_code % steam_alphabet_len); bin_code = (int)(bin_code / steam_alphabet_len); code[i] = steam_alphabet[mod]; } code[5] = '\0'; return strdup (code); } static int truncate (const unsigned char *hmac, int digits_length, whmac_handle_t *hd) { // take the lower four bits of the last byte int offset = hmac[whmac_getlen(hd) - 1] & 0x0f; // Starting from the offset, take the successive 4 bytes while stripping the topmost bit to prevent it being handled as a signed integer int bin_code = ((hmac[offset] & 0x7f) << 24) | ((hmac[offset + 1] & 0xff) << 16) | ((hmac[offset + 2] & 0xff) << 8) | ((hmac[offset + 3] & 0xff)); long long int DIGITS_POWER[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000}; int token = (int)(bin_code % DIGITS_POWER[digits_length]); return token; } static unsigned char * compute_hmac (const char *K, long C, whmac_handle_t *hd) { size_t secret_len = (size_t)((strlen(K) + 1.6 - 1) / 1.6); char *normalized_K = normalize_secret (K); if (normalized_K == NULL) { return NULL; } cotp_error_t err; unsigned char *secret = base32_decode (normalized_K, strlen(normalized_K), &err); free (normalized_K); if (secret == NULL) { return NULL; } unsigned char C_reverse_byte_order[8]; int j, i; for (j = 0, i = 7; j < 8 && i >= 0; j++, i--) { C_reverse_byte_order[i] = ((unsigned char *) &C)[j]; } cotp_error_t copterr = whmac_setkey (hd, secret, secret_len); if (copterr) { fprintf (stderr, "Error while setting the cipher key.\n"); free (secret); 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) { fprintf (stderr, "Error allocating memory"); free (secret); return NULL; } ssize_t flen = whmac_finalize (hd, hmac, dlen); if (flen < 0) { fprintf (stderr, "Error getting digest\n"); free (hmac); free (secret); return NULL; } free (secret); return hmac; } static char * finalize (int digits_length, int tk) { char *token = calloc (digits_length + 1, 1); if (token == NULL) { return NULL; } char fmt[6]; sprintf (fmt, "%%0%dd", digits_length); snprintf (token, digits_length + 1, fmt, 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_DIGTS || digits_length > MAX_DIGITS) ? INVALID_DIGITS : VALID; } static int check_algo (int algo) { return (algo != SHA1 && algo != SHA256 && algo != SHA512) ? INVALID_ALGO : VALID; } libcotp-3.0.0/src/utils/000077500000000000000000000000001453626714700151145ustar00rootroot00000000000000libcotp-3.0.0/src/utils/base32.c000066400000000000000000000155111453626714700163420ustar00rootroot00000000000000#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) const uint8_t b32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; 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 (strlen ((char *)user_data) == data_len - 1) { // 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; } } size_t output_length = (size_t)((user_data_chars + 1.6 + 1) / 1.6); // round up 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; for (int i = 0, j = 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; 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[output_length-1] = '\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; } uint8_t table[128] = {0}; for (const uint8_t *p = b32_alphabet; *p; p++) { table[*p] = 1; } table['='] = 1; while (*str) { if (!table[(uint8_t)*str]) { 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) { for (int i = 0; i < sizeof(b32_alphabet); i++) { if (b32_alphabet[i] == c) { return i; } } return -1; } static int strip_char (char *str) { const char strip = ' '; uint8_t table[128] = {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-3.0.0/src/utils/whmac_gcrypt.c000066400000000000000000000044211453626714700177500ustar00rootroot00000000000000#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")) { fprintf (stderr, "libgcrypt v1.8.0 and above is required\n"); 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) { gcry_md_close (hd->hd); free (hd); } int whmac_setkey (whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { if (gcry_md_setkey (hd->hd, buffer, buflen)) { return -INVALID_ALGO; } return NO_ERROR; } void whmac_update (whmac_handle_t *hd, 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-3.0.0/src/utils/whmac_openssl.c000066400000000000000000000042771453626714700201340ustar00rootroot00000000000000#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) { EVP_MAC_free (hd->mac); free (hd); } int whmac_setkey (whmac_handle_t *hd, unsigned char *buffer, size_t buflen) { hd->ctx = EVP_MAC_CTX_new (hd->mac); if (hd->ctx && !EVP_MAC_init (hd->ctx, buffer, buflen, hd->mac_params)) { ERR_print_errors_fp (stderr); return -INVALID_ALGO; } hd->dlen = EVP_MAC_CTX_get_mac_size (hd->ctx); return NO_ERROR; } void whmac_update (whmac_handle_t *hd, 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-3.0.0/src/whmac.h000066400000000000000000000014061453626714700152250ustar00rootroot00000000000000#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, unsigned char *buffer, size_t buflen); void whmac_update (whmac_handle_t *hd, unsigned char *buffer, size_t buflen); ssize_t whmac_finalize (whmac_handle_t *hd, unsigned char *buffer, size_t buflen); libcotp-3.0.0/tests/000077500000000000000000000000001453626714700143275ustar00rootroot00000000000000libcotp-3.0.0/tests/CMakeLists.txt000066400000000000000000000015151453626714700170710ustar00rootroot00000000000000add_executable (test_cotp test_otp.c) add_executable (test_base32encode test_base32encode.c) add_executable (test_base32decode test_base32decode.c) target_link_libraries (test_cotp -lcotp -lcriterion -lgcrypt) target_link_libraries (test_base32encode -lcotp -lcriterion -lgcrypt) target_link_libraries (test_base32decode -lcotp -lcriterion -lgcrypt) target_link_directories (test_cotp PRIVATE ${PROJECT_BINARY_DIR}) target_link_directories (test_base32encode PRIVATE ${PROJECT_BINARY_DIR}) target_link_directories (test_base32decode PRIVATE ${PROJECT_BINARY_DIR}) add_dependencies (test_cotp cotp) add_dependencies (test_base32encode cotp) add_dependencies (test_base32decode cotp) add_test (NAME TestCOTP COMMAND test_cotp) add_test (NAME TestBase32Encode COMMAND test_base32encode) add_test (NAME TestBase32Decode COMMAND test_base32decode) libcotp-3.0.0/tests/docker/000077500000000000000000000000001453626714700155765ustar00rootroot00000000000000libcotp-3.0.0/tests/docker/Dockerfile000066400000000000000000000016421453626714700175730ustar00rootroot00000000000000FROM 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-3.0.0/tests/docker/PKGBUILD000066400000000000000000000035601453626714700167260ustar00rootroot00000000000000# 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-3.0.0/tests/docker/run_docker.sh000066400000000000000000000002241453626714700202630ustar00rootroot00000000000000#!/bin/bash if [[ -z "$1" ]]; then echo "Usage: $0 " exit 1 fi docker build -t "testme:Dockerfile" --build-arg BRANCH="$1" . libcotp-3.0.0/tests/test_base32decode.c000066400000000000000000000065251453626714700177650ustar00rootroot00000000000000#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-3.0.0/tests/test_base32encode.c000066400000000000000000000075411453626714700177760ustar00rootroot00000000000000#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); // TODO: add also str comparison free (encoded_str); }libcotp-3.0.0/tests/test_otp.c000066400000000000000000000221321453626714700163340ustar00rootroot00000000000000#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 uchar *)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, 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 uchar *)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, 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 uchar *)K, strlen(K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (K_base32, counter, 10, 30, 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 uchar *)K, strlen(K)+1, &cotp_err); cotp_error_t err; int64_t totp = otp_to_int (get_totp_at (K_base32, counter, 10, 30, 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 uchar *)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, 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 uchar *)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, 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 uchar *)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, 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, 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, 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, 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, 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, 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, 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, SHA1, &err); cr_expect_eq (err, WHMAC_ERROR, "Expected %d to be equal to %d\n", err, WHMAC_ERROR); 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, WHMAC_ERROR, "Expected %d to be equal to %d\n", err, WHMAC_ERROR); 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 uchar *)K, strlen (K)+1, &cotp_err); cotp_error_t err; char *totp = get_totp_at (secret_base32, 1111111109, 6, 60, 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 uchar *)K, strlen(K)+1, &cotp_err); cotp_error_t err; int64_t totp = otp_to_int (get_totp_at (K_base32, counter, 10, 30, 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 uchar *)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); }