pax_global_header00006660000000000000000000000064141630167340014517gustar00rootroot0000000000000052 comment=23a070881cbf5cc09b5ab3c582b3afe0e66b5578 libcotp-1.2.4/000077500000000000000000000000001416301673400131575ustar00rootroot00000000000000libcotp-1.2.4/.gitignore000066400000000000000000000004301416301673400151440ustar00rootroot00000000000000.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-1.2.4/CMakeLists.txt000066400000000000000000000027211416301673400157210ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(cotp) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) find_package(PkgConfig REQUIRED) find_package(Gcrypt 1.6.0 REQUIRED) pkg_check_modules(BASEENCODE REQUIRED baseencode>=1.0.5) include_directories(${GCRYPT_INCLUDE_DIR} ${BASEENCODE_INCLUDE_DIRS}) link_directories(${GCRYPT_LIBRARY_DIRS} ${BASEENCODE_LIBRARY_DIRS}) enable_testing() add_subdirectory(tests) # set up versioning. set(BUILD_MAJOR "1") set(BUILD_MINOR "2") set(BUILD_VERSION "4") set(BUILD_VERSION ${BUILD_MAJOR}.${BUILD_MINOR}.${BUILD_VERSION}) set(CMAKE_C_STANDARD 11) set(COTP_HEADERS src/cotp.h) set(SOURCE_FILES src/otp.c) set(CMAKE_C_FLAGS "-Wall -Wextra -O3 -Wno-format-truncation -fstack-protector-strong -fPIC") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3") add_library(cotp SHARED ${SOURCE_FILES}) target_link_libraries(cotp ${GCRYPT_LIBRARIES} ${BASEENCODE_LIBRARIES}) set_target_properties(cotp PROPERTIES VERSION ${BUILD_VERSION} SOVERSION ${BUILD_MAJOR}${BUILD_MINOR}) include(GNUInstallDirs) set(LIB_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}") # "lib" or "lib64" install( TARGETS cotp ARCHIVE DESTINATION ${LIB_INSTALL_DIR} LIBRARY DESTINATION ${LIB_INSTALL_DIR} COMPONENT library ) install( FILES ${COTP_HEADERS} DESTINATION include ) configure_file("cotp.pc.in" "cotp.pc" @ONLY) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/cotp.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig/) libcotp-1.2.4/LICENSE000066400000000000000000000261211416301673400141660ustar00rootroot00000000000000 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-1.2.4/README.md000066400000000000000000000054271416301673400144460ustar00rootroot00000000000000# libcotp Coverity Scan Build Status C library that generates TOTP and HOTP according to [RFC-6238](https://tools.ietf.org/html/rfc6238) ## Requirements - [libbaseencode](https://github.com/paolostivanin/libbaseencode) - GCC/Clang and CMake to build the library - libgcrypt ## Build and Install ``` $ git clone https://github.com/paolostivanin/libcotp.git $ cd libcotp $ mkdir build && cd $_ $ cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr ../ # add -DBUILD_TESTING=ON if you want to compile also the tests $ make # make install ``` ## How To Use It ``` char *totp = get_totp (const char *base32_encoded_secret, int digits, int period, int algo, cotp_error_t *err); free (totp); 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); free (hotp); char *get_totp_at (const char *base32_encoded_secret, long target_date, int digits, int algo, cotp_error_t *err) int is_valid = totp_verify (const har *base32_encoded_secret, const char *totp, int digits, int period, int algo, cotp_error_t *err); int is_valid = hotp_verify (const char *base32_encoded_secret, long counter, digits, char *hotp, int algo, cotp_error_t *err); ``` 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` ## Errors `get_totp`, `get_hotp` and `get_totp_at` return `NULL` if an error occurs and `err` is set accordingly. The following errors are currently supported: - `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 `< 3` or `> 10` `totp_verify` and `hotp_verify` can return, in addition to one of the previous code, also the error `INVALID_OTP` if the given OTP doesn't match the computed one. In case of success, the value returned by `get_totp`, `get_hotp` and `get_totp_at` **must be freed** once no longer needed. libcotp-1.2.4/cmake/000077500000000000000000000000001416301673400142375ustar00rootroot00000000000000libcotp-1.2.4/cmake/FindGcrypt.cmake000066400000000000000000000030401416301673400173070ustar00rootroot00000000000000# 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-1.2.4/cotp.pc.in000066400000000000000000000004311416301673400150530ustar00rootroot00000000000000prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ Name: libcotp Description: C library that generates TOTP and HOTP Version: @BUILD_VERSION@ Libs: -L${libdir} -lcotp Cflags: -I${includedir} libcotp-1.2.4/src/000077500000000000000000000000001416301673400137465ustar00rootroot00000000000000libcotp-1.2.4/src/cotp.h000066400000000000000000000044531416301673400150720ustar00rootroot00000000000000#pragma once #include #define SHA1 GCRY_MD_SHA1 #define SHA256 GCRY_MD_SHA256 #define SHA512 GCRY_MD_SHA512 typedef enum _cotp_errno { VALID = 0, GCRYPT_VERSION_MISMATCH = 1, INVALID_B32_INPUT = 2, INVALID_ALGO = 3, INVALID_OTP = 4, INVALID_DIGITS = 5, INVALID_PERIOD = 6 } cotp_error_t; #ifdef __cplusplus extern "C" { #endif 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); int totp_verify (const char *base32_encoded_secret, const char *user_totp, int digits, int period, int sha_algo); int hotp_verify (const char *base32_encoded_secret, long counter, int digits, const char *user_hotp, int sha_algo); #ifdef __cplusplus } #endif libcotp-1.2.4/src/otp.c000066400000000000000000000203241416301673400147150ustar00rootroot00000000000000#include #include #include #include #include #include "cotp.h" #define SHA1_DIGEST_SIZE 20 #define SHA256_DIGEST_SIZE 32 #define SHA512_DIGEST_SIZE 64 static long long int DIGITS_POWER[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000}; static int check_gcrypt() { if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) { if (!gcry_check_version("1.6.0")) { fprintf(stderr, "libgcrypt v1.6.0 and above is required\n"); return -1; } gcry_control(GCRYCTL_DISABLE_SECMEM, 0); gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0); } return 0; } static char * normalize_secret (const char *K) { char *nK = calloc (1, strlen (K) + 1); if (nK == NULL) { fprintf (stderr, "Error during memory allocation\n"); return nK; } int i = 0, j = 0; while (K[i] != '\0') { if (K[i] != ' ') { if (K[i] >= 'a' && K[i] <= 'z') { nK[j++] = (char) (K[i] - 32); } else { nK[j++] = K[i]; } } i++; } return nK; } static char * get_steam_code(unsigned const char *hmac) { int offset = (hmac[SHA1_DIGEST_SIZE-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 = bin_code % steam_alphabet_len; bin_code = bin_code / steam_alphabet_len; code[i] = steam_alphabet[mod]; } code[5] = '\0'; return strdup(code); } static int truncate(unsigned const char *hmac, int digits_length, int algo) { // take the lower four bits of the last byte int offset = 0; switch (algo) { case SHA1: offset = (hmac[SHA1_DIGEST_SIZE-1] & 0x0f); break; case SHA256: offset = (hmac[SHA256_DIGEST_SIZE-1] & 0x0f); break; case SHA512: offset = (hmac[SHA512_DIGEST_SIZE-1] & 0x0f); break; default: break; } // 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)); int token = bin_code % DIGITS_POWER[digits_length]; return token; } static unsigned char * compute_hmac(const char *K, long C, int algo) { baseencode_error_t err; 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; } 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]; gcry_md_hd_t hd; gcry_md_open(&hd, algo, GCRY_MD_FLAG_HMAC); gcry_md_setkey(hd, secret, secret_len); gcry_md_write(hd, C_reverse_byte_order, sizeof(C_reverse_byte_order)); gcry_md_final (hd); unsigned char *hmac = gcry_md_read(hd, algo); free(secret); return hmac; } static char * finalize(int digits_length, int tk) { char *token = malloc((size_t)digits_length + 1); if (token == NULL) { fprintf (stderr, "Error during memory allocation\n"); return token; } else { int extra_char = digits_length < 10 ? 0 : 1; char *fmt = calloc(1, 5 + extra_char); if (fmt == NULL) { fprintf (stderr, "Error during memory allocation\n"); free (token); return fmt; } memcpy (fmt, "%.", 3); snprintf (fmt + 2, 2 + extra_char, "%d", digits_length); memcpy (fmt + 3 + extra_char, "d", 2); snprintf (token, digits_length + 1, fmt, tk); free (fmt); } return token; } static int check_period(int period) { if (period <= 0 || period > 120) { return INVALID_PERIOD; } return VALID; } static int check_otp_len(int digits_length) { if (digits_length < 3 || digits_length > 10) { return INVALID_DIGITS; } return VALID; } static int check_algo(int algo) { if (algo != SHA1 && algo != SHA256 && algo != SHA512) { return INVALID_ALGO; } else { return VALID; } } char * get_hotp(const char *secret, long timestamp, int digits, int algo, cotp_error_t *err_code) { if (check_gcrypt() == -1) { *err_code = GCRYPT_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; } unsigned char *hmac = compute_hmac(secret, timestamp, algo); if (hmac == NULL) { *err_code = INVALID_B32_INPUT; return NULL; } int tk = truncate(hmac, digits, algo); char *token = finalize(digits, tk); return token; } 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_totp_at(const char *secret, long current_timestamp, int digits, int period, int algo, cotp_error_t *err_code) { if (check_gcrypt() == -1) { *err_code = GCRYPT_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; } long timestamp = current_timestamp / period; cotp_error_t err; char *token = get_hotp(secret, timestamp, digits, algo, &err); if (token == NULL) { *err_code = err; return NULL; } return token; } char * get_steam_totp_at (const char *secret, long current_timestamp, int period, cotp_error_t *err_code) { if (check_gcrypt() == -1) { *err_code = GCRYPT_VERSION_MISMATCH; return NULL; } if (check_period(period) == INVALID_PERIOD) { *err_code = INVALID_PERIOD; return NULL; } long timestamp = current_timestamp / period; unsigned char *hmac = compute_hmac(secret, timestamp, SHA1); if (hmac == NULL) { *err_code = INVALID_B32_INPUT; return NULL; } return get_steam_code(hmac); } int totp_verify(const char *secret, const char *user_totp, int digits, int period, int algo) { cotp_error_t err; char *current_totp = get_totp(secret, digits, period, algo, &err); if (current_totp == NULL) { return err; } int token_status; if (strcmp(current_totp, user_totp) != 0) { token_status = INVALID_OTP; } else { token_status = VALID; } free(current_totp); return token_status; } int hotp_verify(const char *K, long C, int N, const char *user_hotp, int algo) { cotp_error_t err; char *current_hotp = get_hotp(K, C, N, algo, &err); if (current_hotp == NULL) { return err; } int token_status; if (strcmp(current_hotp, user_hotp) != 0) { token_status = INVALID_OTP; } else { token_status = VALID; } free(current_hotp); return token_status; } libcotp-1.2.4/tests/000077500000000000000000000000001416301673400143215ustar00rootroot00000000000000libcotp-1.2.4/tests/CMakeLists.txt000066400000000000000000000004761416301673400170700ustar00rootroot00000000000000 IF(BUILD_TESTING) add_executable (test_cotp test_otp.c) target_link_libraries (test_cotp -lcotp -lcriterion -lbaseencode -lgcrypt) target_link_directories (test_cotp PRIVATE ${PROJECT_BINARY_DIR}) add_dependencies (test_cotp cotp) add_test (NAME TestCOTP COMMAND test_cotp) ENDIF(BUILD_TESTING) libcotp-1.2.4/tests/docker/000077500000000000000000000000001416301673400155705ustar00rootroot00000000000000libcotp-1.2.4/tests/docker/Dockerfile000066400000000000000000000016421416301673400175650ustar00rootroot00000000000000FROM 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-1.2.4/tests/docker/PKGBUILD000066400000000000000000000035601416301673400167200ustar00rootroot00000000000000# 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-1.2.4/tests/docker/run_docker.sh000066400000000000000000000002241416301673400202550ustar00rootroot00000000000000#!/bin/bash if [[ -z "$1" ]]; then echo "Usage: $0 " exit 1 fi docker build -t "testme:Dockerfile" --build-arg BRANCH="$1" . libcotp-1.2.4/tests/test_otp.c000066400000000000000000000153541416301673400163360ustar00rootroot00000000000000#include #include #include "../src/cotp.h" #include 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"}; baseencode_error_t base_err; char *K_base32 = base32_encode(K, strlen(K)+1, &base_err); cotp_error_t err; for (int i = 0; i < 6; i++) { char *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_10_digits_sha1) { const char *K = "12345678901234567890"; const long counter = 1234567890; const char *expected_totp = "0689005924"; baseencode_error_t base_err; char *K_base32 = base32_encode(K, strlen(K)+1, &base_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_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"}; baseencode_error_t base_err; char *K_base32 = base32_encode(K, strlen(K)+1, &base_err); cotp_error_t err; for (int i = 0; i < 6; i++) { char *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"}; baseencode_error_t base_err; char *K_base32 = base32_encode(K, strlen(K)+1, &base_err); cotp_error_t err; for (int i = 0; i < 6; i++) { char *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"}; baseencode_error_t base_err; char *K_base32 = base32_encode(K, strlen(K)+1, &base_err); cotp_error_t err; for (int i = 0; i < 10; i++) { char *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_null (totp, "Expected totp to be null"); cr_expect_eq (err, INVALID_DIGITS, "Expected %d to be equal to %d\n", err, INVALID_DIGITS); 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_null (totp, "Expected totp to be null"); cr_expect_eq (err, INVALID_DIGITS, "Expected %d to be equal to %d\n", err, INVALID_DIGITS); 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_null (totp, "Expected totp to be null"); cr_expect_eq (err, INVALID_PERIOD, "Expected %d to be equal to %d\n", err, INVALID_PERIOD); free (totp); } Test(hotp_rfc, test_wrong_negative) { const char *K = "this is a secret"; cotp_error_t err; char *totp = get_totp (K, 6, -20, SHA1, &err); cr_expect_null (totp, "Expected totp to be null"); cr_expect_eq (err, INVALID_PERIOD, "Expected %d to be equal to %d\n", err, INVALID_PERIOD); free (totp); } 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_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); } Test(totp_generic, test_fail_invalid_algo) { const char *K = "base32secret"; cotp_error_t err; char *totp = get_totp (K, 6, 30, GCRY_MD_MD5, &err); cr_expect_null (totp, "Expected totp to be null"); cr_expect_eq (err, INVALID_ALGO, "Expected %d to be equal to %d\n", err, INVALID_ALGO); } 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); } Test(totp_rfc6238, test_60seconds) { const char *secret = "12345678901234567890"; const char *expected_totp = "360094"; baseencode_error_t base_err; char *secret_base32 = base32_encode(secret, strlen(secret)+1, &base_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); }