diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 08:06:26 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 08:06:26 +0000 |
commit | 1660d4b7a65d9ad2ce0deaa19d35579ca4084ac5 (patch) | |
tree | 6cf8220b628ebd2ccfc1375dd6516c6996e9abcc /lib/crypto_backend | |
parent | Initial commit. (diff) | |
download | cryptsetup-1660d4b7a65d9ad2ce0deaa19d35579ca4084ac5.tar.xz cryptsetup-1660d4b7a65d9ad2ce0deaa19d35579ca4084ac5.zip |
Adding upstream version 2:2.6.1.upstream/2%2.6.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'lib/crypto_backend')
36 files changed, 9546 insertions, 0 deletions
diff --git a/lib/crypto_backend/Makemodule.am b/lib/crypto_backend/Makemodule.am new file mode 100644 index 0000000..7507763 --- /dev/null +++ b/lib/crypto_backend/Makemodule.am @@ -0,0 +1,41 @@ +noinst_LTLIBRARIES += libcrypto_backend.la + +libcrypto_backend_la_CFLAGS = $(AM_CFLAGS) @CRYPTO_CFLAGS@ + +libcrypto_backend_la_SOURCES = \ + lib/crypto_backend/crypto_backend.h \ + lib/crypto_backend/crypto_backend_internal.h \ + lib/crypto_backend/crypto_cipher_kernel.c \ + lib/crypto_backend/crypto_storage.c \ + lib/crypto_backend/pbkdf_check.c \ + lib/crypto_backend/crc32.c \ + lib/crypto_backend/base64.c \ + lib/crypto_backend/utf8.c \ + lib/crypto_backend/argon2_generic.c \ + lib/crypto_backend/cipher_generic.c \ + lib/crypto_backend/cipher_check.c + +if CRYPTO_BACKEND_GCRYPT +libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_gcrypt.c +endif +if CRYPTO_BACKEND_OPENSSL +libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_openssl.c +endif +if CRYPTO_BACKEND_NSS +libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_nss.c +endif +if CRYPTO_BACKEND_KERNEL +libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_kernel.c +endif +if CRYPTO_BACKEND_NETTLE +libcrypto_backend_la_SOURCES += lib/crypto_backend/crypto_nettle.c +endif + +if CRYPTO_INTERNAL_PBKDF2 +libcrypto_backend_la_SOURCES += lib/crypto_backend/pbkdf2_generic.c +endif + +if CRYPTO_INTERNAL_ARGON2 +libcrypto_backend_la_DEPENDENCIES = libargon2.la +libcrypto_backend_la_LIBADD = libargon2.la +endif diff --git a/lib/crypto_backend/argon2/LICENSE b/lib/crypto_backend/argon2/LICENSE new file mode 100644 index 0000000..de14cd2 --- /dev/null +++ b/lib/crypto_backend/argon2/LICENSE @@ -0,0 +1,30 @@ + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + + the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + moral rights retained by the original author(s) and/or performer(s); + publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + rights protecting the extraction, dissemination, use and reuse of data in a Work; + database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. diff --git a/lib/crypto_backend/argon2/Makemodule.am b/lib/crypto_backend/argon2/Makemodule.am new file mode 100644 index 0000000..6fef2f1 --- /dev/null +++ b/lib/crypto_backend/argon2/Makemodule.am @@ -0,0 +1,30 @@ +noinst_LTLIBRARIES += libargon2.la + +libargon2_la_CFLAGS = $(AM_CFLAGS) -std=c89 -pthread -O3 +libargon2_la_CPPFLAGS = $(AM_CPPFLAGS) \ + -I lib/crypto_backend/argon2 \ + -I lib/crypto_backend/argon2/blake2 + +libargon2_la_SOURCES = \ + lib/crypto_backend/argon2/blake2/blake2b.c \ + lib/crypto_backend/argon2/blake2/blake2.h \ + lib/crypto_backend/argon2/blake2/blake2-impl.h \ + lib/crypto_backend/argon2/argon2.c \ + lib/crypto_backend/argon2/argon2.h \ + lib/crypto_backend/argon2/core.c \ + lib/crypto_backend/argon2/core.h \ + lib/crypto_backend/argon2/encoding.c \ + lib/crypto_backend/argon2/encoding.h \ + lib/crypto_backend/argon2/thread.c \ + lib/crypto_backend/argon2/thread.h + +if CRYPTO_INTERNAL_SSE_ARGON2 +libargon2_la_SOURCES += lib/crypto_backend/argon2/blake2/blamka-round-opt.h \ + lib/crypto_backend/argon2/opt.c +else +libargon2_la_SOURCES += lib/crypto_backend/argon2/blake2/blamka-round-ref.h \ + lib/crypto_backend/argon2/ref.c +endif + +EXTRA_DIST += lib/crypto_backend/argon2/LICENSE +EXTRA_DIST += lib/crypto_backend/argon2/README diff --git a/lib/crypto_backend/argon2/README b/lib/crypto_backend/argon2/README new file mode 100644 index 0000000..5376b52 --- /dev/null +++ b/lib/crypto_backend/argon2/README @@ -0,0 +1,5 @@ +This is bundled Argon2 algorithm library, copied from + https://github.com/P-H-C/phc-winner-argon2 + +For more info see Password Hashing Competition site: + https://password-hashing.net/ diff --git a/lib/crypto_backend/argon2/argon2.c b/lib/crypto_backend/argon2/argon2.c new file mode 100644 index 0000000..c784fca --- /dev/null +++ b/lib/crypto_backend/argon2/argon2.c @@ -0,0 +1,458 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include <string.h> +#include <stdlib.h> +#include <stdio.h> + +#include "argon2.h" +#include "encoding.h" +#include "core.h" + +/* to silent gcc -Wcast-qual for const cast */ +#define CONST_CAST(x) (x)(uintptr_t) + +const char *argon2_type2string(argon2_type type, int uppercase) { + switch (type) { + case Argon2_d: + return uppercase ? "Argon2d" : "argon2d"; + case Argon2_i: + return uppercase ? "Argon2i" : "argon2i"; + case Argon2_id: + return uppercase ? "Argon2id" : "argon2id"; + } + + return NULL; +} + +int argon2_ctx(argon2_context *context, argon2_type type) { + /* 1. Validate all inputs */ + int result = validate_inputs(context); + uint32_t memory_blocks, segment_length; + argon2_instance_t instance; + + if (ARGON2_OK != result) { + return result; + } + + if (Argon2_d != type && Argon2_i != type && Argon2_id != type) { + return ARGON2_INCORRECT_TYPE; + } + + /* 2. Align memory size */ + /* Minimum memory_blocks = 8L blocks, where L is the number of lanes */ + memory_blocks = context->m_cost; + + if (memory_blocks < 2 * ARGON2_SYNC_POINTS * context->lanes) { + memory_blocks = 2 * ARGON2_SYNC_POINTS * context->lanes; + } + + segment_length = memory_blocks / (context->lanes * ARGON2_SYNC_POINTS); + /* Ensure that all segments have equal length */ + memory_blocks = segment_length * (context->lanes * ARGON2_SYNC_POINTS); + + instance.version = context->version; + instance.memory = NULL; + instance.passes = context->t_cost; + instance.memory_blocks = memory_blocks; + instance.segment_length = segment_length; + instance.lane_length = segment_length * ARGON2_SYNC_POINTS; + instance.lanes = context->lanes; + instance.threads = context->threads; + instance.type = type; + + if (instance.threads > instance.lanes) { + instance.threads = instance.lanes; + } + + /* 3. Initialization: Hashing inputs, allocating memory, filling first + * blocks + */ + result = initialize(&instance, context); + + if (ARGON2_OK != result) { + return result; + } + + /* 4. Filling memory */ + result = fill_memory_blocks(&instance); + + if (ARGON2_OK != result) { + return result; + } + /* 5. Finalization */ + finalize(context, &instance); + + return ARGON2_OK; +} + +int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, const size_t saltlen, + void *hash, const size_t hashlen, char *encoded, + const size_t encodedlen, argon2_type type, + const uint32_t version){ + + argon2_context context; + int result; + uint8_t *out; + + if (pwdlen > ARGON2_MAX_PWD_LENGTH) { + return ARGON2_PWD_TOO_LONG; + } + + if (saltlen > ARGON2_MAX_SALT_LENGTH) { + return ARGON2_SALT_TOO_LONG; + } + + if (hashlen > ARGON2_MAX_OUTLEN) { + return ARGON2_OUTPUT_TOO_LONG; + } + + if (hashlen < ARGON2_MIN_OUTLEN) { + return ARGON2_OUTPUT_TOO_SHORT; + } + + out = malloc(hashlen); + if (!out) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + context.out = (uint8_t *)out; + context.outlen = (uint32_t)hashlen; + context.pwd = CONST_CAST(uint8_t *)pwd; + context.pwdlen = (uint32_t)pwdlen; + context.salt = CONST_CAST(uint8_t *)salt; + context.saltlen = (uint32_t)saltlen; + context.secret = NULL; + context.secretlen = 0; + context.ad = NULL; + context.adlen = 0; + context.t_cost = t_cost; + context.m_cost = m_cost; + context.lanes = parallelism; + context.threads = parallelism; + context.allocate_cbk = NULL; + context.free_cbk = NULL; + context.flags = ARGON2_DEFAULT_FLAGS; + context.version = version; + + result = argon2_ctx(&context, type); + + if (result != ARGON2_OK) { + clear_internal_memory(out, hashlen); + free(out); + return result; + } + + /* if raw hash requested, write it */ + if (hash) { + memcpy(hash, out, hashlen); + } + + /* if encoding requested, write it */ + if (encoded && encodedlen) { + if (encode_string(encoded, encodedlen, &context, type) != ARGON2_OK) { + clear_internal_memory(out, hashlen); /* wipe buffers if error */ + clear_internal_memory(encoded, encodedlen); + free(out); + return ARGON2_ENCODING_FAIL; + } + } + clear_internal_memory(out, hashlen); + free(out); + + return ARGON2_OK; +} + +int argon2i_hash_encoded(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, const size_t hashlen, + char *encoded, const size_t encodedlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + NULL, hashlen, encoded, encodedlen, Argon2_i, + ARGON2_VERSION_NUMBER); +} + +int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, const size_t hashlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + hash, hashlen, NULL, 0, Argon2_i, ARGON2_VERSION_NUMBER); +} + +int argon2d_hash_encoded(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, const size_t hashlen, + char *encoded, const size_t encodedlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + NULL, hashlen, encoded, encodedlen, Argon2_d, + ARGON2_VERSION_NUMBER); +} + +int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, const size_t hashlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + hash, hashlen, NULL, 0, Argon2_d, ARGON2_VERSION_NUMBER); +} + +int argon2id_hash_encoded(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, const size_t hashlen, + char *encoded, const size_t encodedlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + NULL, hashlen, encoded, encodedlen, Argon2_id, + ARGON2_VERSION_NUMBER); +} + +int argon2id_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, const size_t hashlen) { + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + hash, hashlen, NULL, 0, Argon2_id, + ARGON2_VERSION_NUMBER); +} + +static int argon2_compare(const uint8_t *b1, const uint8_t *b2, size_t len) { + size_t i; + uint8_t d = 0U; + + for (i = 0U; i < len; i++) { + d |= b1[i] ^ b2[i]; + } + return (int)((1 & ((d - 1) >> 8)) - 1); +} + +int argon2_verify(const char *encoded, const void *pwd, const size_t pwdlen, + argon2_type type) { + + argon2_context ctx; + uint8_t *desired_result = NULL; + + int ret = ARGON2_OK; + + size_t encoded_len; + uint32_t max_field_len; + + if (pwdlen > ARGON2_MAX_PWD_LENGTH) { + return ARGON2_PWD_TOO_LONG; + } + + if (encoded == NULL) { + return ARGON2_DECODING_FAIL; + } + + encoded_len = strlen(encoded); + if (encoded_len > UINT32_MAX) { + return ARGON2_DECODING_FAIL; + } + + /* No field can be longer than the encoded length */ + /* coverity[strlen_assign] */ + max_field_len = (uint32_t)encoded_len; + + ctx.saltlen = max_field_len; + ctx.outlen = max_field_len; + + ctx.salt = malloc(ctx.saltlen); + ctx.out = malloc(ctx.outlen); + if (!ctx.salt || !ctx.out) { + ret = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + ctx.pwd = CONST_CAST(uint8_t *)pwd; + ctx.pwdlen = (uint32_t)pwdlen; + + ret = decode_string(&ctx, encoded, type); + if (ret != ARGON2_OK) { + goto fail; + } + + /* Set aside the desired result, and get a new buffer. */ + desired_result = ctx.out; + ctx.out = malloc(ctx.outlen); + if (!ctx.out) { + ret = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + ret = argon2_verify_ctx(&ctx, (char *)desired_result, type); + if (ret != ARGON2_OK) { + goto fail; + } + +fail: + free(ctx.salt); + free(ctx.out); + free(desired_result); + + return ret; +} + +int argon2i_verify(const char *encoded, const void *pwd, const size_t pwdlen) { + + return argon2_verify(encoded, pwd, pwdlen, Argon2_i); +} + +int argon2d_verify(const char *encoded, const void *pwd, const size_t pwdlen) { + + return argon2_verify(encoded, pwd, pwdlen, Argon2_d); +} + +int argon2id_verify(const char *encoded, const void *pwd, const size_t pwdlen) { + + return argon2_verify(encoded, pwd, pwdlen, Argon2_id); +} + +int argon2d_ctx(argon2_context *context) { + return argon2_ctx(context, Argon2_d); +} + +int argon2i_ctx(argon2_context *context) { + return argon2_ctx(context, Argon2_i); +} + +int argon2id_ctx(argon2_context *context) { + return argon2_ctx(context, Argon2_id); +} + +int argon2_verify_ctx(argon2_context *context, const char *hash, + argon2_type type) { + int ret = argon2_ctx(context, type); + if (ret != ARGON2_OK) { + return ret; + } + + if (argon2_compare(CONST_CAST(uint8_t *)hash, context->out, context->outlen)) { + return ARGON2_VERIFY_MISMATCH; + } + + return ARGON2_OK; +} + +int argon2d_verify_ctx(argon2_context *context, const char *hash) { + return argon2_verify_ctx(context, hash, Argon2_d); +} + +int argon2i_verify_ctx(argon2_context *context, const char *hash) { + return argon2_verify_ctx(context, hash, Argon2_i); +} + +int argon2id_verify_ctx(argon2_context *context, const char *hash) { + return argon2_verify_ctx(context, hash, Argon2_id); +} + +const char *argon2_error_message(int error_code) { + switch (error_code) { + case ARGON2_OK: + return "OK"; + case ARGON2_OUTPUT_PTR_NULL: + return "Output pointer is NULL"; + case ARGON2_OUTPUT_TOO_SHORT: + return "Output is too short"; + case ARGON2_OUTPUT_TOO_LONG: + return "Output is too long"; + case ARGON2_PWD_TOO_SHORT: + return "Password is too short"; + case ARGON2_PWD_TOO_LONG: + return "Password is too long"; + case ARGON2_SALT_TOO_SHORT: + return "Salt is too short"; + case ARGON2_SALT_TOO_LONG: + return "Salt is too long"; + case ARGON2_AD_TOO_SHORT: + return "Associated data is too short"; + case ARGON2_AD_TOO_LONG: + return "Associated data is too long"; + case ARGON2_SECRET_TOO_SHORT: + return "Secret is too short"; + case ARGON2_SECRET_TOO_LONG: + return "Secret is too long"; + case ARGON2_TIME_TOO_SMALL: + return "Time cost is too small"; + case ARGON2_TIME_TOO_LARGE: + return "Time cost is too large"; + case ARGON2_MEMORY_TOO_LITTLE: + return "Memory cost is too small"; + case ARGON2_MEMORY_TOO_MUCH: + return "Memory cost is too large"; + case ARGON2_LANES_TOO_FEW: + return "Too few lanes"; + case ARGON2_LANES_TOO_MANY: + return "Too many lanes"; + case ARGON2_PWD_PTR_MISMATCH: + return "Password pointer is NULL, but password length is not 0"; + case ARGON2_SALT_PTR_MISMATCH: + return "Salt pointer is NULL, but salt length is not 0"; + case ARGON2_SECRET_PTR_MISMATCH: + return "Secret pointer is NULL, but secret length is not 0"; + case ARGON2_AD_PTR_MISMATCH: + return "Associated data pointer is NULL, but ad length is not 0"; + case ARGON2_MEMORY_ALLOCATION_ERROR: + return "Memory allocation error"; + case ARGON2_FREE_MEMORY_CBK_NULL: + return "The free memory callback is NULL"; + case ARGON2_ALLOCATE_MEMORY_CBK_NULL: + return "The allocate memory callback is NULL"; + case ARGON2_INCORRECT_PARAMETER: + return "Argon2_Context context is NULL"; + case ARGON2_INCORRECT_TYPE: + return "There is no such version of Argon2"; + case ARGON2_OUT_PTR_MISMATCH: + return "Output pointer mismatch"; + case ARGON2_THREADS_TOO_FEW: + return "Not enough threads"; + case ARGON2_THREADS_TOO_MANY: + return "Too many threads"; + case ARGON2_MISSING_ARGS: + return "Missing arguments"; + case ARGON2_ENCODING_FAIL: + return "Encoding failed"; + case ARGON2_DECODING_FAIL: + return "Decoding failed"; + case ARGON2_THREAD_FAIL: + return "Threading failure"; + case ARGON2_DECODING_LENGTH_FAIL: + return "Some of encoded parameters are too long or too short"; + case ARGON2_VERIFY_MISMATCH: + return "The password does not match the supplied hash"; + default: + return "Unknown error code"; + } +} + +size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, uint32_t parallelism, + uint32_t saltlen, uint32_t hashlen, argon2_type type) { + if (!argon2_type2string(type, 0)) + return 0; + return strlen("$$v=$m=,t=,p=$$") + strlen(argon2_type2string(type, 0)) + + numlen(t_cost) + numlen(m_cost) + numlen(parallelism) + + b64len(saltlen) + b64len(hashlen) + numlen(ARGON2_VERSION_NUMBER) + 1; +} diff --git a/lib/crypto_backend/argon2/argon2.h b/lib/crypto_backend/argon2/argon2.h new file mode 100644 index 0000000..20df933 --- /dev/null +++ b/lib/crypto_backend/argon2/argon2.h @@ -0,0 +1,437 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_H +#define ARGON2_H + +#include <stdint.h> +#include <stddef.h> +#include <limits.h> + +#if defined(__cplusplus) +extern "C" { +#endif + +/* Symbols visibility control */ +#ifdef A2_VISCTL +#define ARGON2_PUBLIC __attribute__((visibility("default"))) +#define ARGON2_LOCAL __attribute__ ((visibility ("hidden"))) +#elif _MSC_VER +#define ARGON2_PUBLIC __declspec(dllexport) +#define ARGON2_LOCAL +#else +#define ARGON2_PUBLIC +#define ARGON2_LOCAL +#endif + +/* + * Argon2 input parameter restrictions + */ + +/* Minimum and maximum number of lanes (degree of parallelism) */ +#define ARGON2_MIN_LANES UINT32_C(1) +#define ARGON2_MAX_LANES UINT32_C(0xFFFFFF) + +/* Minimum and maximum number of threads */ +#define ARGON2_MIN_THREADS UINT32_C(1) +#define ARGON2_MAX_THREADS UINT32_C(0xFFFFFF) + +/* Number of synchronization points between lanes per pass */ +#define ARGON2_SYNC_POINTS UINT32_C(4) + +/* Minimum and maximum digest size in bytes */ +#define ARGON2_MIN_OUTLEN UINT32_C(4) +#define ARGON2_MAX_OUTLEN UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum number of memory blocks (each of BLOCK_SIZE bytes) */ +#define ARGON2_MIN_MEMORY (2 * ARGON2_SYNC_POINTS) /* 2 blocks per slice */ + +#define ARGON2_MIN(a, b) ((a) < (b) ? (a) : (b)) +/* Max memory size is addressing-space/2, topping at 2^32 blocks (4 TB) */ +#define ARGON2_MAX_MEMORY_BITS \ + ARGON2_MIN(UINT32_C(32), (sizeof(void *) * CHAR_BIT - 10 - 1)) +#define ARGON2_MAX_MEMORY \ + ARGON2_MIN(UINT32_C(0xFFFFFFFF), UINT64_C(1) << ARGON2_MAX_MEMORY_BITS) + +/* Minimum and maximum number of passes */ +#define ARGON2_MIN_TIME UINT32_C(1) +#define ARGON2_MAX_TIME UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum password length in bytes */ +#define ARGON2_MIN_PWD_LENGTH UINT32_C(0) +#define ARGON2_MAX_PWD_LENGTH UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum associated data length in bytes */ +#define ARGON2_MIN_AD_LENGTH UINT32_C(0) +#define ARGON2_MAX_AD_LENGTH UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum salt length in bytes */ +#define ARGON2_MIN_SALT_LENGTH UINT32_C(8) +#define ARGON2_MAX_SALT_LENGTH UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum key length in bytes */ +#define ARGON2_MIN_SECRET UINT32_C(0) +#define ARGON2_MAX_SECRET UINT32_C(0xFFFFFFFF) + +/* Flags to determine which fields are securely wiped (default = no wipe). */ +#define ARGON2_DEFAULT_FLAGS UINT32_C(0) +#define ARGON2_FLAG_CLEAR_PASSWORD (UINT32_C(1) << 0) +#define ARGON2_FLAG_CLEAR_SECRET (UINT32_C(1) << 1) + +/* Global flag to determine if we are wiping internal memory buffers. This flag + * is defined in core.c and defaults to 1 (wipe internal memory). */ +extern int FLAG_clear_internal_memory; + +/* Error codes */ +typedef enum Argon2_ErrorCodes { + ARGON2_OK = 0, + + ARGON2_OUTPUT_PTR_NULL = -1, + + ARGON2_OUTPUT_TOO_SHORT = -2, + ARGON2_OUTPUT_TOO_LONG = -3, + + ARGON2_PWD_TOO_SHORT = -4, + ARGON2_PWD_TOO_LONG = -5, + + ARGON2_SALT_TOO_SHORT = -6, + ARGON2_SALT_TOO_LONG = -7, + + ARGON2_AD_TOO_SHORT = -8, + ARGON2_AD_TOO_LONG = -9, + + ARGON2_SECRET_TOO_SHORT = -10, + ARGON2_SECRET_TOO_LONG = -11, + + ARGON2_TIME_TOO_SMALL = -12, + ARGON2_TIME_TOO_LARGE = -13, + + ARGON2_MEMORY_TOO_LITTLE = -14, + ARGON2_MEMORY_TOO_MUCH = -15, + + ARGON2_LANES_TOO_FEW = -16, + ARGON2_LANES_TOO_MANY = -17, + + ARGON2_PWD_PTR_MISMATCH = -18, /* NULL ptr with non-zero length */ + ARGON2_SALT_PTR_MISMATCH = -19, /* NULL ptr with non-zero length */ + ARGON2_SECRET_PTR_MISMATCH = -20, /* NULL ptr with non-zero length */ + ARGON2_AD_PTR_MISMATCH = -21, /* NULL ptr with non-zero length */ + + ARGON2_MEMORY_ALLOCATION_ERROR = -22, + + ARGON2_FREE_MEMORY_CBK_NULL = -23, + ARGON2_ALLOCATE_MEMORY_CBK_NULL = -24, + + ARGON2_INCORRECT_PARAMETER = -25, + ARGON2_INCORRECT_TYPE = -26, + + ARGON2_OUT_PTR_MISMATCH = -27, + + ARGON2_THREADS_TOO_FEW = -28, + ARGON2_THREADS_TOO_MANY = -29, + + ARGON2_MISSING_ARGS = -30, + + ARGON2_ENCODING_FAIL = -31, + + ARGON2_DECODING_FAIL = -32, + + ARGON2_THREAD_FAIL = -33, + + ARGON2_DECODING_LENGTH_FAIL = -34, + + ARGON2_VERIFY_MISMATCH = -35 +} argon2_error_codes; + +/* Memory allocator types --- for external allocation */ +typedef int (*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate); +typedef void (*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate); + +/* Argon2 external data structures */ + +/* + ***** + * Context: structure to hold Argon2 inputs: + * output array and its length, + * password and its length, + * salt and its length, + * secret and its length, + * associated data and its length, + * number of passes, amount of used memory (in KBytes, can be rounded up a bit) + * number of parallel threads that will be run. + * All the parameters above affect the output hash value. + * Additionally, two function pointers can be provided to allocate and + * deallocate the memory (if NULL, memory will be allocated internally). + * Also, three flags indicate whether to erase password, secret as soon as they + * are pre-hashed (and thus not needed anymore), and the entire memory + ***** + * Simplest situation: you have output array out[8], password is stored in + * pwd[32], salt is stored in salt[16], you do not have keys nor associated + * data. You need to spend 1 GB of RAM and you run 5 passes of Argon2d with + * 4 parallel lanes. + * You want to erase the password, but you're OK with last pass not being + * erased. You want to use the default memory allocator. + * Then you initialize: + Argon2_Context(out,8,pwd,32,salt,16,NULL,0,NULL,0,5,1<<20,4,4,NULL,NULL,true,false,false,false) + */ +typedef struct Argon2_Context { + uint8_t *out; /* output array */ + uint32_t outlen; /* digest length */ + + uint8_t *pwd; /* password array */ + uint32_t pwdlen; /* password length */ + + uint8_t *salt; /* salt array */ + uint32_t saltlen; /* salt length */ + + uint8_t *secret; /* key array */ + uint32_t secretlen; /* key length */ + + uint8_t *ad; /* associated data array */ + uint32_t adlen; /* associated data length */ + + uint32_t t_cost; /* number of passes */ + uint32_t m_cost; /* amount of memory requested (KB) */ + uint32_t lanes; /* number of lanes */ + uint32_t threads; /* maximum number of threads */ + + uint32_t version; /* version number */ + + allocate_fptr allocate_cbk; /* pointer to memory allocator */ + deallocate_fptr free_cbk; /* pointer to memory deallocator */ + + uint32_t flags; /* array of bool options */ +} argon2_context; + +/* Argon2 primitive type */ +typedef enum Argon2_type { + Argon2_d = 0, + Argon2_i = 1, + Argon2_id = 2 +} argon2_type; + +/* Version of the algorithm */ +typedef enum Argon2_version { + ARGON2_VERSION_10 = 0x10, + ARGON2_VERSION_13 = 0x13, + ARGON2_VERSION_NUMBER = ARGON2_VERSION_13 +} argon2_version; + +/* + * Function that gives the string representation of an argon2_type. + * @param type The argon2_type that we want the string for + * @param uppercase Whether the string should have the first letter uppercase + * @return NULL if invalid type, otherwise the string representation. + */ +ARGON2_PUBLIC const char *argon2_type2string(argon2_type type, int uppercase); + +/* + * Function that performs memory-hard hashing with certain degree of parallelism + * @param context Pointer to the Argon2 internal structure + * @return Error code if smth is wrong, ARGON2_OK otherwise + */ +ARGON2_PUBLIC int argon2_ctx(argon2_context *context, argon2_type type); + +/** + * Hashes a password with Argon2i, producing an encoded hash + * @param t_cost Number of iterations + * @param m_cost Sets memory usage to m_cost kibibytes + * @param parallelism Number of threads and compute lanes + * @param pwd Pointer to password + * @param pwdlen Password size in bytes + * @param salt Pointer to salt + * @param saltlen Salt size in bytes + * @param hashlen Desired length of the hash in bytes + * @param encoded Buffer where to write the encoded hash + * @param encodedlen Size of the buffer (thus max size of the encoded hash) + * @pre Different parallelism levels will give different results + * @pre Returns ARGON2_OK if successful + */ +ARGON2_PUBLIC int argon2i_hash_encoded(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, + const void *pwd, const size_t pwdlen, + const void *salt, const size_t saltlen, + const size_t hashlen, char *encoded, + const size_t encodedlen); + +/** + * Hashes a password with Argon2i, producing a raw hash at @hash + * @param t_cost Number of iterations + * @param m_cost Sets memory usage to m_cost kibibytes + * @param parallelism Number of threads and compute lanes + * @param pwd Pointer to password + * @param pwdlen Password size in bytes + * @param salt Pointer to salt + * @param saltlen Salt size in bytes + * @param hash Buffer where to write the raw hash - updated by the function + * @param hashlen Desired length of the hash in bytes + * @pre Different parallelism levels will give different results + * @pre Returns ARGON2_OK if successful + */ +ARGON2_PUBLIC int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen); + +ARGON2_PUBLIC int argon2d_hash_encoded(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, + const void *pwd, const size_t pwdlen, + const void *salt, const size_t saltlen, + const size_t hashlen, char *encoded, + const size_t encodedlen); + +ARGON2_PUBLIC int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen); + +ARGON2_PUBLIC int argon2id_hash_encoded(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, + const void *pwd, const size_t pwdlen, + const void *salt, const size_t saltlen, + const size_t hashlen, char *encoded, + const size_t encodedlen); + +ARGON2_PUBLIC int argon2id_hash_raw(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen); + +/* generic function underlying the above ones */ +ARGON2_PUBLIC int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen, char *encoded, + const size_t encodedlen, argon2_type type, + const uint32_t version); + +/** + * Verifies a password against an encoded string + * Encoded string is restricted as in validate_inputs() + * @param encoded String encoding parameters, salt, hash + * @param pwd Pointer to password + * @pre Returns ARGON2_OK if successful + */ +ARGON2_PUBLIC int argon2i_verify(const char *encoded, const void *pwd, + const size_t pwdlen); + +ARGON2_PUBLIC int argon2d_verify(const char *encoded, const void *pwd, + const size_t pwdlen); + +ARGON2_PUBLIC int argon2id_verify(const char *encoded, const void *pwd, + const size_t pwdlen); + +/* generic function underlying the above ones */ +ARGON2_PUBLIC int argon2_verify(const char *encoded, const void *pwd, + const size_t pwdlen, argon2_type type); + +/** + * Argon2d: Version of Argon2 that picks memory blocks depending + * on the password and salt. Only for side-channel-free + * environment!! + ***** + * @param context Pointer to current Argon2 context + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2d_ctx(argon2_context *context); + +/** + * Argon2i: Version of Argon2 that picks memory blocks + * independent on the password and salt. Good for side-channels, + * but worse w.r.t. tradeoff attacks if only one pass is used. + ***** + * @param context Pointer to current Argon2 context + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2i_ctx(argon2_context *context); + +/** + * Argon2id: Version of Argon2 where the first half-pass over memory is + * password-independent, the rest are password-dependent (on the password and + * salt). OK against side channels (they reduce to 1/2-pass Argon2i), and + * better with w.r.t. tradeoff attacks (similar to Argon2d). + ***** + * @param context Pointer to current Argon2 context + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2id_ctx(argon2_context *context); + +/** + * Verify if a given password is correct for Argon2d hashing + * @param context Pointer to current Argon2 context + * @param hash The password hash to verify. The length of the hash is + * specified by the context outlen member + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2d_verify_ctx(argon2_context *context, const char *hash); + +/** + * Verify if a given password is correct for Argon2i hashing + * @param context Pointer to current Argon2 context + * @param hash The password hash to verify. The length of the hash is + * specified by the context outlen member + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2i_verify_ctx(argon2_context *context, const char *hash); + +/** + * Verify if a given password is correct for Argon2id hashing + * @param context Pointer to current Argon2 context + * @param hash The password hash to verify. The length of the hash is + * specified by the context outlen member + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2id_verify_ctx(argon2_context *context, + const char *hash); + +/* generic function underlying the above ones */ +ARGON2_PUBLIC int argon2_verify_ctx(argon2_context *context, const char *hash, + argon2_type type); + +/** + * Get the associated error message for given error code + * @return The error message associated with the given error code + */ +ARGON2_PUBLIC const char *argon2_error_message(int error_code); + +/** + * Returns the encoded hash length for the given input parameters + * @param t_cost Number of iterations + * @param m_cost Memory usage in kibibytes + * @param parallelism Number of threads; used to compute lanes + * @param saltlen Salt size in bytes + * @param hashlen Hash size in bytes + * @param type The argon2_type that we want the encoded length for + * @return The encoded hash length in bytes + */ +ARGON2_PUBLIC size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, + uint32_t parallelism, uint32_t saltlen, + uint32_t hashlen, argon2_type type); + +#if defined(__cplusplus) +} +#endif + +#endif diff --git a/lib/crypto_backend/argon2/blake2/blake2-impl.h b/lib/crypto_backend/argon2/blake2/blake2-impl.h new file mode 100644 index 0000000..dcac827 --- /dev/null +++ b/lib/crypto_backend/argon2/blake2/blake2-impl.h @@ -0,0 +1,154 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef PORTABLE_BLAKE2_IMPL_H +#define PORTABLE_BLAKE2_IMPL_H + +#include <stdint.h> +#include <string.h> + +#if defined(_MSC_VER) +#define BLAKE2_INLINE __inline +#elif defined(__GNUC__) || defined(__clang__) +#define BLAKE2_INLINE __inline__ +#else +#define BLAKE2_INLINE +#endif + +/* Argon2 Team - Begin Code */ +/* + Not an exhaustive list, but should cover the majority of modern platforms + Additionally, the code will always be correct---this is only a performance + tweak. +*/ +#if (defined(__BYTE_ORDER__) && \ + (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ + defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || defined(__MIPSEL__) || \ + defined(__AARCH64EL__) || defined(__amd64__) || defined(__i386__) || \ + defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || \ + defined(_M_ARM) +#define NATIVE_LITTLE_ENDIAN +#endif +/* Argon2 Team - End Code */ + +static BLAKE2_INLINE uint32_t load32(const void *src) { +#if defined(NATIVE_LITTLE_ENDIAN) + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + const uint8_t *p = (const uint8_t *)src; + uint32_t w = *p++; + w |= (uint32_t)(*p++) << 8; + w |= (uint32_t)(*p++) << 16; + w |= (uint32_t)(*p++) << 24; + return w; +#endif +} + +static BLAKE2_INLINE uint64_t load64(const void *src) { +#if defined(NATIVE_LITTLE_ENDIAN) + uint64_t w; + memcpy(&w, src, sizeof w); + return w; +#else + const uint8_t *p = (const uint8_t *)src; + uint64_t w = *p++; + w |= (uint64_t)(*p++) << 8; + w |= (uint64_t)(*p++) << 16; + w |= (uint64_t)(*p++) << 24; + w |= (uint64_t)(*p++) << 32; + w |= (uint64_t)(*p++) << 40; + w |= (uint64_t)(*p++) << 48; + w |= (uint64_t)(*p++) << 56; + return w; +#endif +} + +static BLAKE2_INLINE void store32(void *dst, uint32_t w) { +#if defined(NATIVE_LITTLE_ENDIAN) + memcpy(dst, &w, sizeof w); +#else + uint8_t *p = (uint8_t *)dst; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; +#endif +} + +static BLAKE2_INLINE void store64(void *dst, uint64_t w) { +#if defined(NATIVE_LITTLE_ENDIAN) + memcpy(dst, &w, sizeof w); +#else + uint8_t *p = (uint8_t *)dst; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; +#endif +} + +static BLAKE2_INLINE uint64_t load48(const void *src) { + const uint8_t *p = (const uint8_t *)src; + uint64_t w = *p++; + w |= (uint64_t)(*p++) << 8; + w |= (uint64_t)(*p++) << 16; + w |= (uint64_t)(*p++) << 24; + w |= (uint64_t)(*p++) << 32; + w |= (uint64_t)(*p++) << 40; + return w; +} + +static BLAKE2_INLINE void store48(void *dst, uint64_t w) { + uint8_t *p = (uint8_t *)dst; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; +} + +static BLAKE2_INLINE uint32_t rotr32(const uint32_t w, const unsigned c) { + return (w >> c) | (w << (32 - c)); +} + +static BLAKE2_INLINE uint64_t rotr64(const uint64_t w, const unsigned c) { + return (w >> c) | (w << (64 - c)); +} + +#endif diff --git a/lib/crypto_backend/argon2/blake2/blake2.h b/lib/crypto_backend/argon2/blake2/blake2.h new file mode 100644 index 0000000..0c1b0ee --- /dev/null +++ b/lib/crypto_backend/argon2/blake2/blake2.h @@ -0,0 +1,89 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef PORTABLE_BLAKE2_H +#define PORTABLE_BLAKE2_H + +#include "../argon2.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +enum blake2b_constant { + BLAKE2B_BLOCKBYTES = 128, + BLAKE2B_OUTBYTES = 64, + BLAKE2B_KEYBYTES = 64, + BLAKE2B_SALTBYTES = 16, + BLAKE2B_PERSONALBYTES = 16 +}; + +#pragma pack(push, 1) +typedef struct __blake2b_param { + uint8_t digest_length; /* 1 */ + uint8_t key_length; /* 2 */ + uint8_t fanout; /* 3 */ + uint8_t depth; /* 4 */ + uint32_t leaf_length; /* 8 */ + uint64_t node_offset; /* 16 */ + uint8_t node_depth; /* 17 */ + uint8_t inner_length; /* 18 */ + uint8_t reserved[14]; /* 32 */ + uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */ + uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */ +} blake2b_param; +#pragma pack(pop) + +typedef struct __blake2b_state { + uint64_t h[8]; + uint64_t t[2]; + uint64_t f[2]; + uint8_t buf[BLAKE2B_BLOCKBYTES]; + unsigned buflen; + unsigned outlen; + uint8_t last_node; +} blake2b_state; + +/* Ensure param structs have not been wrongly padded */ +/* Poor man's static_assert */ +enum { + blake2_size_check_0 = 1 / !!(CHAR_BIT == 8), + blake2_size_check_2 = + 1 / !!(sizeof(blake2b_param) == sizeof(uint64_t) * CHAR_BIT) +}; + +/* Streaming API */ +ARGON2_LOCAL int blake2b_init(blake2b_state *S, size_t outlen); +ARGON2_LOCAL int blake2b_init_key(blake2b_state *S, size_t outlen, const void *key, + size_t keylen); +ARGON2_LOCAL int blake2b_init_param(blake2b_state *S, const blake2b_param *P); +ARGON2_LOCAL int blake2b_update(blake2b_state *S, const void *in, size_t inlen); +ARGON2_LOCAL int blake2b_final(blake2b_state *S, void *out, size_t outlen); + +/* Simple API */ +ARGON2_LOCAL int blake2b(void *out, size_t outlen, const void *in, size_t inlen, + const void *key, size_t keylen); + +/* Argon2 Team - Begin Code */ +ARGON2_LOCAL int blake2b_long(void *out, size_t outlen, const void *in, size_t inlen); +/* Argon2 Team - End Code */ + +#if defined(__cplusplus) +} +#endif + +#endif diff --git a/lib/crypto_backend/argon2/blake2/blake2b.c b/lib/crypto_backend/argon2/blake2/blake2b.c new file mode 100644 index 0000000..d8f69e8 --- /dev/null +++ b/lib/crypto_backend/argon2/blake2/blake2b.c @@ -0,0 +1,392 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include <stdint.h> +#include <string.h> +#include <stdio.h> + +#include "blake2.h" +#include "blake2-impl.h" + +void clear_internal_memory(void *v, size_t n); + +static const uint64_t blake2b_IV[8] = { + UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b), + UINT64_C(0x3c6ef372fe94f82b), UINT64_C(0xa54ff53a5f1d36f1), + UINT64_C(0x510e527fade682d1), UINT64_C(0x9b05688c2b3e6c1f), + UINT64_C(0x1f83d9abfb41bd6b), UINT64_C(0x5be0cd19137e2179)}; + +static const unsigned int blake2b_sigma[12][16] = { + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3}, + {11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4}, + {7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8}, + {9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13}, + {2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9}, + {12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11}, + {13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10}, + {6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5}, + {10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3}, +}; + +static BLAKE2_INLINE void blake2b_set_lastnode(blake2b_state *S) { + S->f[1] = (uint64_t)-1; +} + +static BLAKE2_INLINE void blake2b_set_lastblock(blake2b_state *S) { + if (S->last_node) { + blake2b_set_lastnode(S); + } + S->f[0] = (uint64_t)-1; +} + +static BLAKE2_INLINE void blake2b_increment_counter(blake2b_state *S, + uint64_t inc) { + S->t[0] += inc; + S->t[1] += (S->t[0] < inc); +} + +static BLAKE2_INLINE void blake2b_invalidate_state(blake2b_state *S) { + clear_internal_memory(S, sizeof(*S)); /* wipe */ + blake2b_set_lastblock(S); /* invalidate for further use */ +} + +static BLAKE2_INLINE void blake2b_init0(blake2b_state *S) { + memset(S, 0, sizeof(*S)); + memcpy(S->h, blake2b_IV, sizeof(S->h)); +} + +int blake2b_init_param(blake2b_state *S, const blake2b_param *P) { + const unsigned char *p = (const unsigned char *)P; + unsigned int i; + + if (NULL == P || NULL == S) { + return -1; + } + + blake2b_init0(S); + /* IV XOR Parameter Block */ + for (i = 0; i < 8; ++i) { + S->h[i] ^= load64(&p[i * sizeof(S->h[i])]); + } + S->outlen = P->digest_length; + return 0; +} + +/* Sequential blake2b initialization */ +int blake2b_init(blake2b_state *S, size_t outlen) { + blake2b_param P; + + if (S == NULL) { + return -1; + } + + if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) { + blake2b_invalidate_state(S); + return -1; + } + + /* Setup Parameter Block for unkeyed BLAKE2 */ + P.digest_length = (uint8_t)outlen; + P.key_length = 0; + P.fanout = 1; + P.depth = 1; + P.leaf_length = 0; + P.node_offset = 0; + P.node_depth = 0; + P.inner_length = 0; + memset(P.reserved, 0, sizeof(P.reserved)); + memset(P.salt, 0, sizeof(P.salt)); + memset(P.personal, 0, sizeof(P.personal)); + + return blake2b_init_param(S, &P); +} + +int blake2b_init_key(blake2b_state *S, size_t outlen, const void *key, + size_t keylen) { + blake2b_param P; + + if (S == NULL) { + return -1; + } + + if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) { + blake2b_invalidate_state(S); + return -1; + } + + if ((key == 0) || (keylen == 0) || (keylen > BLAKE2B_KEYBYTES)) { + blake2b_invalidate_state(S); + return -1; + } + + /* Setup Parameter Block for keyed BLAKE2 */ + P.digest_length = (uint8_t)outlen; + P.key_length = (uint8_t)keylen; + P.fanout = 1; + P.depth = 1; + P.leaf_length = 0; + P.node_offset = 0; + P.node_depth = 0; + P.inner_length = 0; + memset(P.reserved, 0, sizeof(P.reserved)); + memset(P.salt, 0, sizeof(P.salt)); + memset(P.personal, 0, sizeof(P.personal)); + + if (blake2b_init_param(S, &P) < 0) { + blake2b_invalidate_state(S); + return -1; + } + + { + uint8_t block[BLAKE2B_BLOCKBYTES]; + memset(block, 0, BLAKE2B_BLOCKBYTES); + memcpy(block, key, keylen); + blake2b_update(S, block, BLAKE2B_BLOCKBYTES); + /* Burn the key from stack */ + clear_internal_memory(block, BLAKE2B_BLOCKBYTES); + } + return 0; +} + +static void blake2b_compress(blake2b_state *S, const uint8_t *block) { + uint64_t m[16]; + uint64_t v[16]; + unsigned int i, r; + + for (i = 0; i < 16; ++i) { + m[i] = load64(block + i * sizeof(m[i])); + } + + for (i = 0; i < 8; ++i) { + v[i] = S->h[i]; + } + + v[8] = blake2b_IV[0]; + v[9] = blake2b_IV[1]; + v[10] = blake2b_IV[2]; + v[11] = blake2b_IV[3]; + v[12] = blake2b_IV[4] ^ S->t[0]; + v[13] = blake2b_IV[5] ^ S->t[1]; + v[14] = blake2b_IV[6] ^ S->f[0]; + v[15] = blake2b_IV[7] ^ S->f[1]; + +#define G(r, i, a, b, c, d) \ + do { \ + a = a + b + m[blake2b_sigma[r][2 * i + 0]]; \ + d = rotr64(d ^ a, 32); \ + c = c + d; \ + b = rotr64(b ^ c, 24); \ + a = a + b + m[blake2b_sigma[r][2 * i + 1]]; \ + d = rotr64(d ^ a, 16); \ + c = c + d; \ + b = rotr64(b ^ c, 63); \ + } while ((void)0, 0) + +#define ROUND(r) \ + do { \ + G(r, 0, v[0], v[4], v[8], v[12]); \ + G(r, 1, v[1], v[5], v[9], v[13]); \ + G(r, 2, v[2], v[6], v[10], v[14]); \ + G(r, 3, v[3], v[7], v[11], v[15]); \ + G(r, 4, v[0], v[5], v[10], v[15]); \ + G(r, 5, v[1], v[6], v[11], v[12]); \ + G(r, 6, v[2], v[7], v[8], v[13]); \ + G(r, 7, v[3], v[4], v[9], v[14]); \ + } while ((void)0, 0) + + for (r = 0; r < 12; ++r) { + ROUND(r); + } + + for (i = 0; i < 8; ++i) { + S->h[i] = S->h[i] ^ v[i] ^ v[i + 8]; + } + +#undef G +#undef ROUND +} + +int blake2b_update(blake2b_state *S, const void *in, size_t inlen) { + const uint8_t *pin = (const uint8_t *)in; + + if (inlen == 0) { + return 0; + } + + /* Sanity check */ + if (S == NULL || in == NULL) { + return -1; + } + + /* Is this a reused state? */ + if (S->f[0] != 0) { + return -1; + } + + if (S->buflen + inlen > BLAKE2B_BLOCKBYTES) { + /* Complete current block */ + size_t left = S->buflen; + size_t fill = BLAKE2B_BLOCKBYTES - left; + memcpy(&S->buf[left], pin, fill); + blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES); + blake2b_compress(S, S->buf); + S->buflen = 0; + inlen -= fill; + pin += fill; + /* Avoid buffer copies when possible */ + while (inlen > BLAKE2B_BLOCKBYTES) { + blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES); + blake2b_compress(S, pin); + inlen -= BLAKE2B_BLOCKBYTES; + pin += BLAKE2B_BLOCKBYTES; + } + } + memcpy(&S->buf[S->buflen], pin, inlen); + S->buflen += (unsigned int)inlen; + return 0; +} + +int blake2b_final(blake2b_state *S, void *out, size_t outlen) { + uint8_t buffer[BLAKE2B_OUTBYTES] = {0}; + unsigned int i; + + /* Sanity checks */ + if (S == NULL || out == NULL || outlen < S->outlen) { + return -1; + } + + /* Is this a reused state? */ + if (S->f[0] != 0) { + return -1; + } + + blake2b_increment_counter(S, S->buflen); + blake2b_set_lastblock(S); + memset(&S->buf[S->buflen], 0, BLAKE2B_BLOCKBYTES - S->buflen); /* Padding */ + blake2b_compress(S, S->buf); + + for (i = 0; i < 8; ++i) { /* Output full hash to temp buffer */ + store64(buffer + sizeof(S->h[i]) * i, S->h[i]); + } + + memcpy(out, buffer, S->outlen); + clear_internal_memory(buffer, sizeof(buffer)); + clear_internal_memory(S->buf, sizeof(S->buf)); + clear_internal_memory(S->h, sizeof(S->h)); + return 0; +} + +int blake2b(void *out, size_t outlen, const void *in, size_t inlen, + const void *key, size_t keylen) { + blake2b_state S; + int ret = -1; + + /* Verify parameters */ + if (NULL == in && inlen > 0) { + goto fail; + } + + if (NULL == out || outlen == 0 || outlen > BLAKE2B_OUTBYTES) { + goto fail; + } + + if ((NULL == key && keylen > 0) || keylen > BLAKE2B_KEYBYTES) { + goto fail; + } + + if (keylen > 0) { + if (blake2b_init_key(&S, outlen, key, keylen) < 0) { + goto fail; + } + } else { + if (blake2b_init(&S, outlen) < 0) { + goto fail; + } + } + + if (blake2b_update(&S, in, inlen) < 0) { + goto fail; + } + ret = blake2b_final(&S, out, outlen); + +fail: + clear_internal_memory(&S, sizeof(S)); + return ret; +} + +/* Argon2 Team - Begin Code */ +int blake2b_long(void *pout, size_t outlen, const void *in, size_t inlen) { + uint8_t *out = (uint8_t *)pout; + blake2b_state blake_state; + uint8_t outlen_bytes[sizeof(uint32_t)] = {0}; + int ret = -1; + + if (outlen > UINT32_MAX) { + goto fail; + } + + /* Ensure little-endian byte order! */ + store32(outlen_bytes, (uint32_t)outlen); + +#define TRY(statement) \ + do { \ + ret = statement; \ + if (ret < 0) { \ + goto fail; \ + } \ + } while ((void)0, 0) + + if (outlen <= BLAKE2B_OUTBYTES) { + TRY(blake2b_init(&blake_state, outlen)); + TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes))); + TRY(blake2b_update(&blake_state, in, inlen)); + TRY(blake2b_final(&blake_state, out, outlen)); + } else { + uint32_t toproduce; + uint8_t out_buffer[BLAKE2B_OUTBYTES]; + uint8_t in_buffer[BLAKE2B_OUTBYTES]; + TRY(blake2b_init(&blake_state, BLAKE2B_OUTBYTES)); + TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes))); + TRY(blake2b_update(&blake_state, in, inlen)); + TRY(blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES)); + memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2); + out += BLAKE2B_OUTBYTES / 2; + toproduce = (uint32_t)outlen - BLAKE2B_OUTBYTES / 2; + + while (toproduce > BLAKE2B_OUTBYTES) { + memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES); + TRY(blake2b(out_buffer, BLAKE2B_OUTBYTES, in_buffer, + BLAKE2B_OUTBYTES, NULL, 0)); + memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2); + out += BLAKE2B_OUTBYTES / 2; + toproduce -= BLAKE2B_OUTBYTES / 2; + } + + memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES); + TRY(blake2b(out_buffer, toproduce, in_buffer, BLAKE2B_OUTBYTES, NULL, + 0)); + memcpy(out, out_buffer, toproduce); + } +fail: + clear_internal_memory(&blake_state, sizeof(blake_state)); + return ret; +#undef TRY +} +/* Argon2 Team - End Code */ diff --git a/lib/crypto_backend/argon2/blake2/blamka-round-opt.h b/lib/crypto_backend/argon2/blake2/blamka-round-opt.h new file mode 100644 index 0000000..3127f2a --- /dev/null +++ b/lib/crypto_backend/argon2/blake2/blamka-round-opt.h @@ -0,0 +1,471 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef BLAKE_ROUND_MKA_OPT_H +#define BLAKE_ROUND_MKA_OPT_H + +#include "blake2-impl.h" + +#include <emmintrin.h> +#if defined(__SSSE3__) +#include <tmmintrin.h> /* for _mm_shuffle_epi8 and _mm_alignr_epi8 */ +#endif + +#if defined(__XOP__) && (defined(__GNUC__) || defined(__clang__)) +#include <x86intrin.h> +#endif + +#if !defined(__AVX512F__) +#if !defined(__AVX2__) +#if !defined(__XOP__) +#if defined(__SSSE3__) +#define r16 \ + (_mm_setr_epi8(2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9)) +#define r24 \ + (_mm_setr_epi8(3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10)) +#define _mm_roti_epi64(x, c) \ + (-(c) == 32) \ + ? _mm_shuffle_epi32((x), _MM_SHUFFLE(2, 3, 0, 1)) \ + : (-(c) == 24) \ + ? _mm_shuffle_epi8((x), r24) \ + : (-(c) == 16) \ + ? _mm_shuffle_epi8((x), r16) \ + : (-(c) == 63) \ + ? _mm_xor_si128(_mm_srli_epi64((x), -(c)), \ + _mm_add_epi64((x), (x))) \ + : _mm_xor_si128(_mm_srli_epi64((x), -(c)), \ + _mm_slli_epi64((x), 64 - (-(c)))) +#else /* defined(__SSE2__) */ +#define _mm_roti_epi64(r, c) \ + _mm_xor_si128(_mm_srli_epi64((r), -(c)), _mm_slli_epi64((r), 64 - (-(c)))) +#endif +#else +#endif + +static BLAKE2_INLINE __m128i fBlaMka(__m128i x, __m128i y) { + const __m128i z = _mm_mul_epu32(x, y); + return _mm_add_epi64(_mm_add_epi64(x, y), _mm_add_epi64(z, z)); +} + +#define G1(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + A0 = fBlaMka(A0, B0); \ + A1 = fBlaMka(A1, B1); \ + \ + D0 = _mm_xor_si128(D0, A0); \ + D1 = _mm_xor_si128(D1, A1); \ + \ + D0 = _mm_roti_epi64(D0, -32); \ + D1 = _mm_roti_epi64(D1, -32); \ + \ + C0 = fBlaMka(C0, D0); \ + C1 = fBlaMka(C1, D1); \ + \ + B0 = _mm_xor_si128(B0, C0); \ + B1 = _mm_xor_si128(B1, C1); \ + \ + B0 = _mm_roti_epi64(B0, -24); \ + B1 = _mm_roti_epi64(B1, -24); \ + } while ((void)0, 0) + +#define G2(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + A0 = fBlaMka(A0, B0); \ + A1 = fBlaMka(A1, B1); \ + \ + D0 = _mm_xor_si128(D0, A0); \ + D1 = _mm_xor_si128(D1, A1); \ + \ + D0 = _mm_roti_epi64(D0, -16); \ + D1 = _mm_roti_epi64(D1, -16); \ + \ + C0 = fBlaMka(C0, D0); \ + C1 = fBlaMka(C1, D1); \ + \ + B0 = _mm_xor_si128(B0, C0); \ + B1 = _mm_xor_si128(B1, C1); \ + \ + B0 = _mm_roti_epi64(B0, -63); \ + B1 = _mm_roti_epi64(B1, -63); \ + } while ((void)0, 0) + +#if defined(__SSSE3__) +#define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + __m128i t0 = _mm_alignr_epi8(B1, B0, 8); \ + __m128i t1 = _mm_alignr_epi8(B0, B1, 8); \ + B0 = t0; \ + B1 = t1; \ + \ + t0 = C0; \ + C0 = C1; \ + C1 = t0; \ + \ + t0 = _mm_alignr_epi8(D1, D0, 8); \ + t1 = _mm_alignr_epi8(D0, D1, 8); \ + D0 = t1; \ + D1 = t0; \ + } while ((void)0, 0) + +#define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + __m128i t0 = _mm_alignr_epi8(B0, B1, 8); \ + __m128i t1 = _mm_alignr_epi8(B1, B0, 8); \ + B0 = t0; \ + B1 = t1; \ + \ + t0 = C0; \ + C0 = C1; \ + C1 = t0; \ + \ + t0 = _mm_alignr_epi8(D0, D1, 8); \ + t1 = _mm_alignr_epi8(D1, D0, 8); \ + D0 = t1; \ + D1 = t0; \ + } while ((void)0, 0) +#else /* SSE2 */ +#define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + __m128i t0 = D0; \ + __m128i t1 = B0; \ + D0 = C0; \ + C0 = C1; \ + C1 = D0; \ + D0 = _mm_unpackhi_epi64(D1, _mm_unpacklo_epi64(t0, t0)); \ + D1 = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(D1, D1)); \ + B0 = _mm_unpackhi_epi64(B0, _mm_unpacklo_epi64(B1, B1)); \ + B1 = _mm_unpackhi_epi64(B1, _mm_unpacklo_epi64(t1, t1)); \ + } while ((void)0, 0) + +#define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + __m128i t0, t1; \ + t0 = C0; \ + C0 = C1; \ + C1 = t0; \ + t0 = B0; \ + t1 = D0; \ + B0 = _mm_unpackhi_epi64(B1, _mm_unpacklo_epi64(B0, B0)); \ + B1 = _mm_unpackhi_epi64(t0, _mm_unpacklo_epi64(B1, B1)); \ + D0 = _mm_unpackhi_epi64(D0, _mm_unpacklo_epi64(D1, D1)); \ + D1 = _mm_unpackhi_epi64(D1, _mm_unpacklo_epi64(t1, t1)); \ + } while ((void)0, 0) +#endif + +#define BLAKE2_ROUND(A0, A1, B0, B1, C0, C1, D0, D1) \ + do { \ + G1(A0, B0, C0, D0, A1, B1, C1, D1); \ + G2(A0, B0, C0, D0, A1, B1, C1, D1); \ + \ + DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ + \ + G1(A0, B0, C0, D0, A1, B1, C1, D1); \ + G2(A0, B0, C0, D0, A1, B1, C1, D1); \ + \ + UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ + } while ((void)0, 0) +#else /* __AVX2__ */ + +#include <immintrin.h> + +#define rotr32(x) _mm256_shuffle_epi32(x, _MM_SHUFFLE(2, 3, 0, 1)) +#define rotr24(x) _mm256_shuffle_epi8(x, _mm256_setr_epi8(3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10, 3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10)) +#define rotr16(x) _mm256_shuffle_epi8(x, _mm256_setr_epi8(2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9, 2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9)) +#define rotr63(x) _mm256_xor_si256(_mm256_srli_epi64((x), 63), _mm256_add_epi64((x), (x))) + +#define G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + do { \ + __m256i ml = _mm256_mul_epu32(A0, B0); \ + ml = _mm256_add_epi64(ml, ml); \ + A0 = _mm256_add_epi64(A0, _mm256_add_epi64(B0, ml)); \ + D0 = _mm256_xor_si256(D0, A0); \ + D0 = rotr32(D0); \ + \ + ml = _mm256_mul_epu32(C0, D0); \ + ml = _mm256_add_epi64(ml, ml); \ + C0 = _mm256_add_epi64(C0, _mm256_add_epi64(D0, ml)); \ + \ + B0 = _mm256_xor_si256(B0, C0); \ + B0 = rotr24(B0); \ + \ + ml = _mm256_mul_epu32(A1, B1); \ + ml = _mm256_add_epi64(ml, ml); \ + A1 = _mm256_add_epi64(A1, _mm256_add_epi64(B1, ml)); \ + D1 = _mm256_xor_si256(D1, A1); \ + D1 = rotr32(D1); \ + \ + ml = _mm256_mul_epu32(C1, D1); \ + ml = _mm256_add_epi64(ml, ml); \ + C1 = _mm256_add_epi64(C1, _mm256_add_epi64(D1, ml)); \ + \ + B1 = _mm256_xor_si256(B1, C1); \ + B1 = rotr24(B1); \ + } while((void)0, 0); + +#define G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + do { \ + __m256i ml = _mm256_mul_epu32(A0, B0); \ + ml = _mm256_add_epi64(ml, ml); \ + A0 = _mm256_add_epi64(A0, _mm256_add_epi64(B0, ml)); \ + D0 = _mm256_xor_si256(D0, A0); \ + D0 = rotr16(D0); \ + \ + ml = _mm256_mul_epu32(C0, D0); \ + ml = _mm256_add_epi64(ml, ml); \ + C0 = _mm256_add_epi64(C0, _mm256_add_epi64(D0, ml)); \ + B0 = _mm256_xor_si256(B0, C0); \ + B0 = rotr63(B0); \ + \ + ml = _mm256_mul_epu32(A1, B1); \ + ml = _mm256_add_epi64(ml, ml); \ + A1 = _mm256_add_epi64(A1, _mm256_add_epi64(B1, ml)); \ + D1 = _mm256_xor_si256(D1, A1); \ + D1 = rotr16(D1); \ + \ + ml = _mm256_mul_epu32(C1, D1); \ + ml = _mm256_add_epi64(ml, ml); \ + C1 = _mm256_add_epi64(C1, _mm256_add_epi64(D1, ml)); \ + B1 = _mm256_xor_si256(B1, C1); \ + B1 = rotr63(B1); \ + } while((void)0, 0); + +#define DIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + B0 = _mm256_permute4x64_epi64(B0, _MM_SHUFFLE(0, 3, 2, 1)); \ + C0 = _mm256_permute4x64_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \ + D0 = _mm256_permute4x64_epi64(D0, _MM_SHUFFLE(2, 1, 0, 3)); \ + \ + B1 = _mm256_permute4x64_epi64(B1, _MM_SHUFFLE(0, 3, 2, 1)); \ + C1 = _mm256_permute4x64_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \ + D1 = _mm256_permute4x64_epi64(D1, _MM_SHUFFLE(2, 1, 0, 3)); \ + } while((void)0, 0); + +#define DIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \ + do { \ + __m256i tmp1 = _mm256_blend_epi32(B0, B1, 0xCC); \ + __m256i tmp2 = _mm256_blend_epi32(B0, B1, 0x33); \ + B1 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \ + B0 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \ + \ + tmp1 = C0; \ + C0 = C1; \ + C1 = tmp1; \ + \ + tmp1 = _mm256_blend_epi32(D0, D1, 0xCC); \ + tmp2 = _mm256_blend_epi32(D0, D1, 0x33); \ + D0 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \ + D1 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \ + } while(0); + +#define UNDIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + B0 = _mm256_permute4x64_epi64(B0, _MM_SHUFFLE(2, 1, 0, 3)); \ + C0 = _mm256_permute4x64_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \ + D0 = _mm256_permute4x64_epi64(D0, _MM_SHUFFLE(0, 3, 2, 1)); \ + \ + B1 = _mm256_permute4x64_epi64(B1, _MM_SHUFFLE(2, 1, 0, 3)); \ + C1 = _mm256_permute4x64_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \ + D1 = _mm256_permute4x64_epi64(D1, _MM_SHUFFLE(0, 3, 2, 1)); \ + } while((void)0, 0); + +#define UNDIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \ + do { \ + __m256i tmp1 = _mm256_blend_epi32(B0, B1, 0xCC); \ + __m256i tmp2 = _mm256_blend_epi32(B0, B1, 0x33); \ + B0 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \ + B1 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \ + \ + tmp1 = C0; \ + C0 = C1; \ + C1 = tmp1; \ + \ + tmp1 = _mm256_blend_epi32(D0, D1, 0x33); \ + tmp2 = _mm256_blend_epi32(D0, D1, 0xCC); \ + D0 = _mm256_permute4x64_epi64(tmp1, _MM_SHUFFLE(2,3,0,1)); \ + D1 = _mm256_permute4x64_epi64(tmp2, _MM_SHUFFLE(2,3,0,1)); \ + } while((void)0, 0); + +#define BLAKE2_ROUND_1(A0, A1, B0, B1, C0, C1, D0, D1) \ + do{ \ + G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + \ + DIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \ + \ + G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + \ + UNDIAGONALIZE_1(A0, B0, C0, D0, A1, B1, C1, D1) \ + } while((void)0, 0); + +#define BLAKE2_ROUND_2(A0, A1, B0, B1, C0, C1, D0, D1) \ + do{ \ + G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + \ + DIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \ + \ + G1_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + G2_AVX2(A0, A1, B0, B1, C0, C1, D0, D1) \ + \ + UNDIAGONALIZE_2(A0, A1, B0, B1, C0, C1, D0, D1) \ + } while((void)0, 0); + +#endif /* __AVX2__ */ + +#else /* __AVX512F__ */ + +#include <immintrin.h> + +#define ror64(x, n) _mm512_ror_epi64((x), (n)) + +static __m512i muladd(__m512i x, __m512i y) +{ + __m512i z = _mm512_mul_epu32(x, y); + return _mm512_add_epi64(_mm512_add_epi64(x, y), _mm512_add_epi64(z, z)); +} + +#define G1(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + A0 = muladd(A0, B0); \ + A1 = muladd(A1, B1); \ +\ + D0 = _mm512_xor_si512(D0, A0); \ + D1 = _mm512_xor_si512(D1, A1); \ +\ + D0 = ror64(D0, 32); \ + D1 = ror64(D1, 32); \ +\ + C0 = muladd(C0, D0); \ + C1 = muladd(C1, D1); \ +\ + B0 = _mm512_xor_si512(B0, C0); \ + B1 = _mm512_xor_si512(B1, C1); \ +\ + B0 = ror64(B0, 24); \ + B1 = ror64(B1, 24); \ + } while ((void)0, 0) + +#define G2(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + A0 = muladd(A0, B0); \ + A1 = muladd(A1, B1); \ +\ + D0 = _mm512_xor_si512(D0, A0); \ + D1 = _mm512_xor_si512(D1, A1); \ +\ + D0 = ror64(D0, 16); \ + D1 = ror64(D1, 16); \ +\ + C0 = muladd(C0, D0); \ + C1 = muladd(C1, D1); \ +\ + B0 = _mm512_xor_si512(B0, C0); \ + B1 = _mm512_xor_si512(B1, C1); \ +\ + B0 = ror64(B0, 63); \ + B1 = ror64(B1, 63); \ + } while ((void)0, 0) + +#define DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + B0 = _mm512_permutex_epi64(B0, _MM_SHUFFLE(0, 3, 2, 1)); \ + B1 = _mm512_permutex_epi64(B1, _MM_SHUFFLE(0, 3, 2, 1)); \ +\ + C0 = _mm512_permutex_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \ + C1 = _mm512_permutex_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \ +\ + D0 = _mm512_permutex_epi64(D0, _MM_SHUFFLE(2, 1, 0, 3)); \ + D1 = _mm512_permutex_epi64(D1, _MM_SHUFFLE(2, 1, 0, 3)); \ + } while ((void)0, 0) + +#define UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + B0 = _mm512_permutex_epi64(B0, _MM_SHUFFLE(2, 1, 0, 3)); \ + B1 = _mm512_permutex_epi64(B1, _MM_SHUFFLE(2, 1, 0, 3)); \ +\ + C0 = _mm512_permutex_epi64(C0, _MM_SHUFFLE(1, 0, 3, 2)); \ + C1 = _mm512_permutex_epi64(C1, _MM_SHUFFLE(1, 0, 3, 2)); \ +\ + D0 = _mm512_permutex_epi64(D0, _MM_SHUFFLE(0, 3, 2, 1)); \ + D1 = _mm512_permutex_epi64(D1, _MM_SHUFFLE(0, 3, 2, 1)); \ + } while ((void)0, 0) + +#define BLAKE2_ROUND(A0, B0, C0, D0, A1, B1, C1, D1) \ + do { \ + G1(A0, B0, C0, D0, A1, B1, C1, D1); \ + G2(A0, B0, C0, D0, A1, B1, C1, D1); \ +\ + DIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ +\ + G1(A0, B0, C0, D0, A1, B1, C1, D1); \ + G2(A0, B0, C0, D0, A1, B1, C1, D1); \ +\ + UNDIAGONALIZE(A0, B0, C0, D0, A1, B1, C1, D1); \ + } while ((void)0, 0) + +#define SWAP_HALVES(A0, A1) \ + do { \ + __m512i t0, t1; \ + t0 = _mm512_shuffle_i64x2(A0, A1, _MM_SHUFFLE(1, 0, 1, 0)); \ + t1 = _mm512_shuffle_i64x2(A0, A1, _MM_SHUFFLE(3, 2, 3, 2)); \ + A0 = t0; \ + A1 = t1; \ + } while((void)0, 0) + +#define SWAP_QUARTERS(A0, A1) \ + do { \ + SWAP_HALVES(A0, A1); \ + A0 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A0); \ + A1 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A1); \ + } while((void)0, 0) + +#define UNSWAP_QUARTERS(A0, A1) \ + do { \ + A0 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A0); \ + A1 = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 1, 4, 5, 2, 3, 6, 7), A1); \ + SWAP_HALVES(A0, A1); \ + } while((void)0, 0) + +#define BLAKE2_ROUND_1(A0, C0, B0, D0, A1, C1, B1, D1) \ + do { \ + SWAP_HALVES(A0, B0); \ + SWAP_HALVES(C0, D0); \ + SWAP_HALVES(A1, B1); \ + SWAP_HALVES(C1, D1); \ + BLAKE2_ROUND(A0, B0, C0, D0, A1, B1, C1, D1); \ + SWAP_HALVES(A0, B0); \ + SWAP_HALVES(C0, D0); \ + SWAP_HALVES(A1, B1); \ + SWAP_HALVES(C1, D1); \ + } while ((void)0, 0) + +#define BLAKE2_ROUND_2(A0, A1, B0, B1, C0, C1, D0, D1) \ + do { \ + SWAP_QUARTERS(A0, A1); \ + SWAP_QUARTERS(B0, B1); \ + SWAP_QUARTERS(C0, C1); \ + SWAP_QUARTERS(D0, D1); \ + BLAKE2_ROUND(A0, B0, C0, D0, A1, B1, C1, D1); \ + UNSWAP_QUARTERS(A0, A1); \ + UNSWAP_QUARTERS(B0, B1); \ + UNSWAP_QUARTERS(C0, C1); \ + UNSWAP_QUARTERS(D0, D1); \ + } while ((void)0, 0) + +#endif /* __AVX512F__ */ +#endif /* BLAKE_ROUND_MKA_OPT_H */ diff --git a/lib/crypto_backend/argon2/blake2/blamka-round-ref.h b/lib/crypto_backend/argon2/blake2/blamka-round-ref.h new file mode 100644 index 0000000..16cfc1c --- /dev/null +++ b/lib/crypto_backend/argon2/blake2/blamka-round-ref.h @@ -0,0 +1,56 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef BLAKE_ROUND_MKA_H +#define BLAKE_ROUND_MKA_H + +#include "blake2.h" +#include "blake2-impl.h" + +/* designed by the Lyra PHC team */ +static BLAKE2_INLINE uint64_t fBlaMka(uint64_t x, uint64_t y) { + const uint64_t m = UINT64_C(0xFFFFFFFF); + const uint64_t xy = (x & m) * (y & m); + return x + y + 2 * xy; +} + +#define G(a, b, c, d) \ + do { \ + a = fBlaMka(a, b); \ + d = rotr64(d ^ a, 32); \ + c = fBlaMka(c, d); \ + b = rotr64(b ^ c, 24); \ + a = fBlaMka(a, b); \ + d = rotr64(d ^ a, 16); \ + c = fBlaMka(c, d); \ + b = rotr64(b ^ c, 63); \ + } while ((void)0, 0) + +#define BLAKE2_ROUND_NOMSG(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, \ + v12, v13, v14, v15) \ + do { \ + G(v0, v4, v8, v12); \ + G(v1, v5, v9, v13); \ + G(v2, v6, v10, v14); \ + G(v3, v7, v11, v15); \ + G(v0, v5, v10, v15); \ + G(v1, v6, v11, v12); \ + G(v2, v7, v8, v13); \ + G(v3, v4, v9, v14); \ + } while ((void)0, 0) + +#endif diff --git a/lib/crypto_backend/argon2/core.c b/lib/crypto_backend/argon2/core.c new file mode 100644 index 0000000..f128d84 --- /dev/null +++ b/lib/crypto_backend/argon2/core.c @@ -0,0 +1,646 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +/*For memory wiping*/ +#ifdef _MSC_VER +#include <windows.h> +#include <winbase.h> /* For SecureZeroMemory */ +#endif +#if defined __STDC_LIB_EXT1__ +#define __STDC_WANT_LIB_EXT1__ 1 +#endif +#define VC_GE_2005(version) (version >= 1400) + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "core.h" +#include "thread.h" +#include "blake2/blake2.h" +#include "blake2/blake2-impl.h" + +#ifdef GENKAT +#include "genkat.h" +#endif + +#if defined(__clang__) +#if __has_attribute(optnone) +#define NOT_OPTIMIZED __attribute__((optnone)) +#endif +#elif defined(__GNUC__) +#define GCC_VERSION \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#if GCC_VERSION >= 40400 +#define NOT_OPTIMIZED __attribute__((optimize("O0"))) +#endif +#endif +#ifndef NOT_OPTIMIZED +#define NOT_OPTIMIZED +#endif + +/***************Instance and Position constructors**********/ +void init_block_value(block *b, uint8_t in) { memset(b->v, in, sizeof(b->v)); } + +void copy_block(block *dst, const block *src) { + memcpy(dst->v, src->v, sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK); +} + +void xor_block(block *dst, const block *src) { + int i; + for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) { + dst->v[i] ^= src->v[i]; + } +} + +static void load_block(block *dst, const void *input) { + unsigned i; + for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) { + dst->v[i] = load64((const uint8_t *)input + i * sizeof(dst->v[i])); + } +} + +static void store_block(void *output, const block *src) { + unsigned i; + for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) { + store64((uint8_t *)output + i * sizeof(src->v[i]), src->v[i]); + } +} + +/***************Memory functions*****************/ + +int allocate_memory(const argon2_context *context, uint8_t **memory, + size_t num, size_t size) { + size_t memory_size = num*size; + if (memory == NULL) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + /* 1. Check for multiplication overflow */ + if (size != 0 && memory_size / size != num) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + /* 2. Try to allocate with appropriate allocator */ + if (context->allocate_cbk) { + (context->allocate_cbk)(memory, memory_size); + } else { + *memory = malloc(memory_size); + } + + if (*memory == NULL) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + return ARGON2_OK; +} + +void free_memory(const argon2_context *context, uint8_t *memory, + size_t num, size_t size) { + size_t memory_size = num*size; + clear_internal_memory(memory, memory_size); + if (context->free_cbk) { + (context->free_cbk)(memory, memory_size); + } else { + free(memory); + } +} + +#if defined(_MSC_VER) && VC_GE_2005(_MSC_VER) +void secure_wipe_memory(void *v, size_t n) { + SecureZeroMemory(v, n); +} +#elif defined memset_s +void secure_wipe_memory(void *v, size_t n) { + memset_s(v, n, 0, n); +} +#elif defined(HAVE_EXPLICIT_BZERO) +void secure_wipe_memory(void *v, size_t n) { + explicit_bzero(v, n); +} +#else +void NOT_OPTIMIZED secure_wipe_memory(void *v, size_t n) { + static void *(*const volatile memset_sec)(void *, int, size_t) = &memset; + memset_sec(v, 0, n); +} +#endif + +/* Memory clear flag defaults to true. */ +int FLAG_clear_internal_memory = 1; +void clear_internal_memory(void *v, size_t n) { + if (FLAG_clear_internal_memory && v) { + secure_wipe_memory(v, n); + } +} + +void finalize(const argon2_context *context, argon2_instance_t *instance) { + if (context != NULL && instance != NULL) { + block blockhash; + uint32_t l; + + copy_block(&blockhash, instance->memory + instance->lane_length - 1); + + /* XOR the last blocks */ + for (l = 1; l < instance->lanes; ++l) { + uint32_t last_block_in_lane = + l * instance->lane_length + (instance->lane_length - 1); + xor_block(&blockhash, instance->memory + last_block_in_lane); + } + + /* Hash the result */ + { + uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE]; + store_block(blockhash_bytes, &blockhash); + blake2b_long(context->out, context->outlen, blockhash_bytes, + ARGON2_BLOCK_SIZE); + /* clear blockhash and blockhash_bytes */ + clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE); + clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); + } + +#ifdef GENKAT + print_tag(context->out, context->outlen); +#endif + + free_memory(context, (uint8_t *)instance->memory, + instance->memory_blocks, sizeof(block)); + } +} + +uint32_t index_alpha(const argon2_instance_t *instance, + const argon2_position_t *position, uint32_t pseudo_rand, + int same_lane) { + /* + * Pass 0: + * This lane : all already finished segments plus already constructed + * blocks in this segment + * Other lanes : all already finished segments + * Pass 1+: + * This lane : (SYNC_POINTS - 1) last segments plus already constructed + * blocks in this segment + * Other lanes : (SYNC_POINTS - 1) last segments + */ + uint32_t reference_area_size; + uint64_t relative_position; + uint32_t start_position, absolute_position; + + if (0 == position->pass) { + /* First pass */ + if (0 == position->slice) { + /* First slice */ + reference_area_size = + position->index - 1; /* all but the previous */ + } else { + if (same_lane) { + /* The same lane => add current segment */ + reference_area_size = + position->slice * instance->segment_length + + position->index - 1; + } else { + reference_area_size = + position->slice * instance->segment_length + + ((position->index == 0) ? (-1) : 0); + } + } + } else { + /* Second pass */ + if (same_lane) { + reference_area_size = instance->lane_length - + instance->segment_length + position->index - + 1; + } else { + reference_area_size = instance->lane_length - + instance->segment_length + + ((position->index == 0) ? (-1) : 0); + } + } + + /* 1.2.4. Mapping pseudo_rand to 0..<reference_area_size-1> and produce + * relative position */ + relative_position = pseudo_rand; + relative_position = relative_position * relative_position >> 32; + relative_position = reference_area_size - 1 - + (reference_area_size * relative_position >> 32); + + /* 1.2.5 Computing starting position */ + start_position = 0; + + if (0 != position->pass) { + start_position = (position->slice == ARGON2_SYNC_POINTS - 1) + ? 0 + : (position->slice + 1) * instance->segment_length; + } + + /* 1.2.6. Computing absolute position */ + absolute_position = (start_position + relative_position) % + instance->lane_length; /* absolute position */ + return absolute_position; +} + +/* Single-threaded version for p=1 case */ +static int fill_memory_blocks_st(argon2_instance_t *instance) { + uint32_t r, s, l; + + for (r = 0; r < instance->passes; ++r) { + for (s = 0; s < ARGON2_SYNC_POINTS; ++s) { + for (l = 0; l < instance->lanes; ++l) { + argon2_position_t position = {r, l, (uint8_t)s, 0}; + fill_segment(instance, position); + } + } +#ifdef GENKAT + internal_kat(instance, r); /* Print all memory blocks */ +#endif + } + return ARGON2_OK; +} + +#if !defined(ARGON2_NO_THREADS) + +#ifdef _WIN32 +static unsigned __stdcall fill_segment_thr(void *thread_data) +#else +static void *fill_segment_thr(void *thread_data) +#endif +{ + argon2_thread_data *my_data = thread_data; + fill_segment(my_data->instance_ptr, my_data->pos); + return 0; +} + +/* Multi-threaded version for p > 1 case */ +static int fill_memory_blocks_mt(argon2_instance_t *instance) { + uint32_t r, s; + argon2_thread_handle_t *thread = NULL; + argon2_thread_data *thr_data = NULL; + int rc = ARGON2_OK; + + /* 1. Allocating space for threads */ + thread = calloc(instance->lanes, sizeof(argon2_thread_handle_t)); + if (thread == NULL) { + rc = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + thr_data = calloc(instance->lanes, sizeof(argon2_thread_data)); + if (thr_data == NULL) { + rc = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + for (r = 0; r < instance->passes; ++r) { + for (s = 0; s < ARGON2_SYNC_POINTS; ++s) { + uint32_t l, ll; + + /* 2. Calling threads */ + for (l = 0; l < instance->lanes; ++l) { + argon2_position_t position; + + /* 2.1 Join a thread if limit is exceeded */ + if (l >= instance->threads) { + if (argon2_thread_join(thread[l - instance->threads])) { + rc = ARGON2_THREAD_FAIL; + goto fail; + } + } + + /* 2.2 Create thread */ + position.pass = r; + position.lane = l; + position.slice = (uint8_t)s; + position.index = 0; + thr_data[l].instance_ptr = + instance; /* preparing the thread input */ + memcpy(&(thr_data[l].pos), &position, + sizeof(argon2_position_t)); + if (argon2_thread_create(&thread[l], &fill_segment_thr, + (void *)&thr_data[l])) { + /* Wait for already running threads */ + for (ll = 0; ll < l; ++ll) + argon2_thread_join(thread[ll]); + rc = ARGON2_THREAD_FAIL; + goto fail; + } + + /* fill_segment(instance, position); */ + /*Non-thread equivalent of the lines above */ + } + + /* 3. Joining remaining threads */ + for (l = instance->lanes - instance->threads; l < instance->lanes; + ++l) { + if (argon2_thread_join(thread[l])) { + rc = ARGON2_THREAD_FAIL; + goto fail; + } + } + } + +#ifdef GENKAT + internal_kat(instance, r); /* Print all memory blocks */ +#endif + } + +fail: + if (thread != NULL) { + free(thread); + } + if (thr_data != NULL) { + free(thr_data); + } + return rc; +} + +#endif /* ARGON2_NO_THREADS */ + +int fill_memory_blocks(argon2_instance_t *instance) { + if (instance == NULL || instance->lanes == 0) { + return ARGON2_INCORRECT_PARAMETER; + } +#if defined(ARGON2_NO_THREADS) + return fill_memory_blocks_st(instance); +#else + return instance->threads == 1 ? + fill_memory_blocks_st(instance) : fill_memory_blocks_mt(instance); +#endif +} + +int validate_inputs(const argon2_context *context) { + if (NULL == context) { + return ARGON2_INCORRECT_PARAMETER; + } + + if (NULL == context->out) { + return ARGON2_OUTPUT_PTR_NULL; + } + + /* Validate output length */ + if (ARGON2_MIN_OUTLEN > context->outlen) { + return ARGON2_OUTPUT_TOO_SHORT; + } + + if (ARGON2_MAX_OUTLEN < context->outlen) { + return ARGON2_OUTPUT_TOO_LONG; + } + + /* Validate password (required param) */ + if (NULL == context->pwd) { + if (0 != context->pwdlen) { + return ARGON2_PWD_PTR_MISMATCH; + } + } +#if ARGON2_MIN_PWD_LENGTH > 0 /* cryptsetup: fix gcc warning */ + if (ARGON2_MIN_PWD_LENGTH > context->pwdlen) { + return ARGON2_PWD_TOO_SHORT; + } +#endif + if (ARGON2_MAX_PWD_LENGTH < context->pwdlen) { + return ARGON2_PWD_TOO_LONG; + } + + /* Validate salt (required param) */ + if (NULL == context->salt) { + if (0 != context->saltlen) { + return ARGON2_SALT_PTR_MISMATCH; + } + } + + if (ARGON2_MIN_SALT_LENGTH > context->saltlen) { + return ARGON2_SALT_TOO_SHORT; + } + + if (ARGON2_MAX_SALT_LENGTH < context->saltlen) { + return ARGON2_SALT_TOO_LONG; + } + + /* Validate secret (optional param) */ + if (NULL == context->secret) { + if (0 != context->secretlen) { + return ARGON2_SECRET_PTR_MISMATCH; + } + } else { +#if ARGON2_MIN_SECRET > 0 /* cryptsetup: fix gcc warning */ + if (ARGON2_MIN_SECRET > context->secretlen) { + return ARGON2_SECRET_TOO_SHORT; + } +#endif + if (ARGON2_MAX_SECRET < context->secretlen) { + return ARGON2_SECRET_TOO_LONG; + } + } + + /* Validate associated data (optional param) */ + if (NULL == context->ad) { + if (0 != context->adlen) { + return ARGON2_AD_PTR_MISMATCH; + } + } else { +#if ARGON2_MIN_AD_LENGTH > 0 /* cryptsetup: fix gcc warning */ + if (ARGON2_MIN_AD_LENGTH > context->adlen) { + return ARGON2_AD_TOO_SHORT; + } +#endif + if (ARGON2_MAX_AD_LENGTH < context->adlen) { + return ARGON2_AD_TOO_LONG; + } + } + + /* Validate memory cost */ + if (ARGON2_MIN_MEMORY > context->m_cost) { + return ARGON2_MEMORY_TOO_LITTLE; + } +#if 0 /* UINT32_MAX, cryptsetup: fix gcc warning */ + if (ARGON2_MAX_MEMORY < context->m_cost) { + return ARGON2_MEMORY_TOO_MUCH; + } +#endif + if (context->m_cost < 8 * context->lanes) { + return ARGON2_MEMORY_TOO_LITTLE; + } + + /* Validate time cost */ + if (ARGON2_MIN_TIME > context->t_cost) { + return ARGON2_TIME_TOO_SMALL; + } + + if (ARGON2_MAX_TIME < context->t_cost) { + return ARGON2_TIME_TOO_LARGE; + } + + /* Validate lanes */ + if (ARGON2_MIN_LANES > context->lanes) { + return ARGON2_LANES_TOO_FEW; + } + + if (ARGON2_MAX_LANES < context->lanes) { + return ARGON2_LANES_TOO_MANY; + } + + /* Validate threads */ + if (ARGON2_MIN_THREADS > context->threads) { + return ARGON2_THREADS_TOO_FEW; + } + + if (ARGON2_MAX_THREADS < context->threads) { + return ARGON2_THREADS_TOO_MANY; + } + + if (NULL != context->allocate_cbk && NULL == context->free_cbk) { + return ARGON2_FREE_MEMORY_CBK_NULL; + } + + if (NULL == context->allocate_cbk && NULL != context->free_cbk) { + return ARGON2_ALLOCATE_MEMORY_CBK_NULL; + } + + return ARGON2_OK; +} + +void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance) { + uint32_t l; + /* Make the first and second block in each lane as G(H0||0||i) or + G(H0||1||i) */ + uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE]; + for (l = 0; l < instance->lanes; ++l) { + + store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 0); + store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH + 4, l); + blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, + ARGON2_PREHASH_SEED_LENGTH); + load_block(&instance->memory[l * instance->lane_length + 0], + blockhash_bytes); + + store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 1); + blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, + ARGON2_PREHASH_SEED_LENGTH); + load_block(&instance->memory[l * instance->lane_length + 1], + blockhash_bytes); + } + clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); +} + +void initial_hash(uint8_t *blockhash, argon2_context *context, + argon2_type type) { + blake2b_state BlakeHash; + uint8_t value[sizeof(uint32_t)]; + + if (NULL == context || NULL == blockhash) { + return; + } + + blake2b_init(&BlakeHash, ARGON2_PREHASH_DIGEST_LENGTH); + + store32(&value, context->lanes); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + store32(&value, context->outlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + store32(&value, context->m_cost); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + store32(&value, context->t_cost); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + store32(&value, context->version); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + store32(&value, (uint32_t)type); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + store32(&value, context->pwdlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->pwd != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->pwd, + context->pwdlen); + + if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) { + secure_wipe_memory(context->pwd, context->pwdlen); + context->pwdlen = 0; + } + } + + store32(&value, context->saltlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->salt != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->salt, + context->saltlen); + } + + store32(&value, context->secretlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->secret != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->secret, + context->secretlen); + + if (context->flags & ARGON2_FLAG_CLEAR_SECRET) { + secure_wipe_memory(context->secret, context->secretlen); + context->secretlen = 0; + } + } + + store32(&value, context->adlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->ad != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->ad, + context->adlen); + } + + blake2b_final(&BlakeHash, blockhash, ARGON2_PREHASH_DIGEST_LENGTH); +} + +int initialize(argon2_instance_t *instance, argon2_context *context) { + uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; + int result = ARGON2_OK; + + if (instance == NULL || context == NULL) + return ARGON2_INCORRECT_PARAMETER; + instance->context_ptr = context; + + /* 1. Memory allocation */ + result = allocate_memory(context, (uint8_t **)&(instance->memory), + instance->memory_blocks, sizeof(block)); + if (result != ARGON2_OK) { + return result; + } + + /* 2. Initial hashing */ + /* H_0 + 8 extra bytes to produce the first blocks */ + /* uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; */ + /* Hashing all inputs */ + initial_hash(blockhash, context, instance->type); + /* Zeroing 8 extra bytes */ + clear_internal_memory(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, + ARGON2_PREHASH_SEED_LENGTH - + ARGON2_PREHASH_DIGEST_LENGTH); + +#ifdef GENKAT + initial_kat(blockhash, context, instance->type); +#endif + + /* 3. Creating first blocks, we always have at least two blocks in a slice + */ + fill_first_blocks(blockhash, instance); + /* Clearing the hash */ + clear_internal_memory(blockhash, ARGON2_PREHASH_SEED_LENGTH); + + return ARGON2_OK; +} diff --git a/lib/crypto_backend/argon2/core.h b/lib/crypto_backend/argon2/core.h new file mode 100644 index 0000000..59e2564 --- /dev/null +++ b/lib/crypto_backend/argon2/core.h @@ -0,0 +1,228 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_CORE_H +#define ARGON2_CORE_H + +#include "argon2.h" + +#define CONST_CAST(x) (x)(uintptr_t) + +/**********************Argon2 internal constants*******************************/ + +enum argon2_core_constants { + /* Memory block size in bytes */ + ARGON2_BLOCK_SIZE = 1024, + ARGON2_QWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 8, + ARGON2_OWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 16, + ARGON2_HWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 32, + ARGON2_512BIT_WORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 64, + + /* Number of pseudo-random values generated by one call to Blake in Argon2i + to + generate reference block positions */ + ARGON2_ADDRESSES_IN_BLOCK = 128, + + /* Pre-hashing digest length and its extension*/ + ARGON2_PREHASH_DIGEST_LENGTH = 64, + ARGON2_PREHASH_SEED_LENGTH = 72 +}; + +/*************************Argon2 internal data types***********************/ + +/* + * Structure for the (1KB) memory block implemented as 128 64-bit words. + * Memory blocks can be copied, XORed. Internal words can be accessed by [] (no + * bounds checking). + */ +typedef struct block_ { uint64_t v[ARGON2_QWORDS_IN_BLOCK]; } block; + +/*****************Functions that work with the block******************/ + +/* Initialize each byte of the block with @in */ +void init_block_value(block *b, uint8_t in); + +/* Copy block @src to block @dst */ +void copy_block(block *dst, const block *src); + +/* XOR @src onto @dst bytewise */ +void xor_block(block *dst, const block *src); + +/* + * Argon2 instance: memory pointer, number of passes, amount of memory, type, + * and derived values. + * Used to evaluate the number and location of blocks to construct in each + * thread + */ +typedef struct Argon2_instance_t { + block *memory; /* Memory pointer */ + uint32_t version; + uint32_t passes; /* Number of passes */ + uint32_t memory_blocks; /* Number of blocks in memory */ + uint32_t segment_length; + uint32_t lane_length; + uint32_t lanes; + uint32_t threads; + argon2_type type; + int print_internals; /* whether to print the memory blocks */ + argon2_context *context_ptr; /* points back to original context */ +} argon2_instance_t; + +/* + * Argon2 position: where we construct the block right now. Used to distribute + * work between threads. + */ +typedef struct Argon2_position_t { + uint32_t pass; + uint32_t lane; + uint8_t slice; + uint32_t index; +} argon2_position_t; + +/*Struct that holds the inputs for thread handling FillSegment*/ +typedef struct Argon2_thread_data { + argon2_instance_t *instance_ptr; + argon2_position_t pos; +} argon2_thread_data; + +/*************************Argon2 core functions********************************/ + +/* Allocates memory to the given pointer, uses the appropriate allocator as + * specified in the context. Total allocated memory is num*size. + * @param context argon2_context which specifies the allocator + * @param memory pointer to the pointer to the memory + * @param size the size in bytes for each element to be allocated + * @param num the number of elements to be allocated + * @return ARGON2_OK if @memory is a valid pointer and memory is allocated + */ +int allocate_memory(const argon2_context *context, uint8_t **memory, + size_t num, size_t size); + +/* + * Frees memory at the given pointer, uses the appropriate deallocator as + * specified in the context. Also cleans the memory using clear_internal_memory. + * @param context argon2_context which specifies the deallocator + * @param memory pointer to buffer to be freed + * @param size the size in bytes for each element to be deallocated + * @param num the number of elements to be deallocated + */ +void free_memory(const argon2_context *context, uint8_t *memory, + size_t num, size_t size); + +/* Function that securely cleans the memory. This ignores any flags set + * regarding clearing memory. Usually one just calls clear_internal_memory. + * @param mem Pointer to the memory + * @param s Memory size in bytes + */ +void secure_wipe_memory(void *v, size_t n); + +/* Function that securely clears the memory if FLAG_clear_internal_memory is + * set. If the flag isn't set, this function does nothing. + * @param mem Pointer to the memory + * @param s Memory size in bytes + */ +void clear_internal_memory(void *v, size_t n); + +/* + * Computes absolute position of reference block in the lane following a skewed + * distribution and using a pseudo-random value as input + * @param instance Pointer to the current instance + * @param position Pointer to the current position + * @param pseudo_rand 32-bit pseudo-random value used to determine the position + * @param same_lane Indicates if the block will be taken from the current lane. + * If so we can reference the current segment + * @pre All pointers must be valid + */ +uint32_t index_alpha(const argon2_instance_t *instance, + const argon2_position_t *position, uint32_t pseudo_rand, + int same_lane); + +/* + * Function that validates all inputs against predefined restrictions and return + * an error code + * @param context Pointer to current Argon2 context + * @return ARGON2_OK if everything is all right, otherwise one of error codes + * (all defined in <argon2.h> + */ +int validate_inputs(const argon2_context *context); + +/* + * Hashes all the inputs into @a blockhash[PREHASH_DIGEST_LENGTH], clears + * password and secret if needed + * @param context Pointer to the Argon2 internal structure containing memory + * pointer, and parameters for time and space requirements. + * @param blockhash Buffer for pre-hashing digest + * @param type Argon2 type + * @pre @a blockhash must have at least @a PREHASH_DIGEST_LENGTH bytes + * allocated + */ +void initial_hash(uint8_t *blockhash, argon2_context *context, + argon2_type type); + +/* + * Function creates first 2 blocks per lane + * @param instance Pointer to the current instance + * @param blockhash Pointer to the pre-hashing digest + * @pre blockhash must point to @a PREHASH_SEED_LENGTH allocated values + */ +void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance); + +/* + * Function allocates memory, hashes the inputs with Blake, and creates first + * two blocks. Returns the pointer to the main memory with 2 blocks per lane + * initialized + * @param context Pointer to the Argon2 internal structure containing memory + * pointer, and parameters for time and space requirements. + * @param instance Current Argon2 instance + * @return Zero if successful, -1 if memory failed to allocate. @context->state + * will be modified if successful. + */ +int initialize(argon2_instance_t *instance, argon2_context *context); + +/* + * XORing the last block of each lane, hashing it, making the tag. Deallocates + * the memory. + * @param context Pointer to current Argon2 context (use only the out parameters + * from it) + * @param instance Pointer to current instance of Argon2 + * @pre instance->state must point to necessary amount of memory + * @pre context->out must point to outlen bytes of memory + * @pre if context->free_cbk is not NULL, it should point to a function that + * deallocates memory + */ +void finalize(const argon2_context *context, argon2_instance_t *instance); + +/* + * Function that fills the segment using previous segments also from other + * threads + * @param context current context + * @param instance Pointer to the current instance + * @param position Current position + * @pre all block pointers must be valid + */ +void fill_segment(const argon2_instance_t *instance, + argon2_position_t position); + +/* + * Function that fills the entire memory t_cost times based on the first two + * blocks in each lane + * @param instance Pointer to the current instance + * @return ARGON2_OK if successful, @context->state + */ +int fill_memory_blocks(argon2_instance_t *instance); + +#endif diff --git a/lib/crypto_backend/argon2/encoding.c b/lib/crypto_backend/argon2/encoding.c new file mode 100644 index 0000000..a717263 --- /dev/null +++ b/lib/crypto_backend/argon2/encoding.c @@ -0,0 +1,462 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <limits.h> +#include "encoding.h" +#include "core.h" + +/* + * Example code for a decoder and encoder of "hash strings", with Argon2 + * parameters. + * + * This code comprises three sections: + * + * -- The first section contains generic Base64 encoding and decoding + * functions. It is conceptually applicable to any hash function + * implementation that uses Base64 to encode and decode parameters, + * salts and outputs. It could be made into a library, provided that + * the relevant functions are made public (non-static) and be given + * reasonable names to avoid collisions with other functions. + * + * -- The second section is specific to Argon2. It encodes and decodes + * the parameters, salts and outputs. It does not compute the hash + * itself. + * + * The code was originally written by Thomas Pornin <pornin@bolet.org>, + * to whom comments and remarks may be sent. It is released under what + * should amount to Public Domain or its closest equivalent; the + * following mantra is supposed to incarnate that fact with all the + * proper legal rituals: + * + * --------------------------------------------------------------------- + * This file is provided under the terms of Creative Commons CC0 1.0 + * Public Domain Dedication. To the extent possible under law, the + * author (Thomas Pornin) has waived all copyright and related or + * neighboring rights to this file. This work is published from: Canada. + * --------------------------------------------------------------------- + * + * Copyright (c) 2015 Thomas Pornin + */ + +/* ==================================================================== */ +/* + * Common code; could be shared between different hash functions. + * + * Note: the Base64 functions below assume that uppercase letters (resp. + * lowercase letters) have consecutive numerical codes, that fit on 8 + * bits. All modern systems use ASCII-compatible charsets, where these + * properties are true. If you are stuck with a dinosaur of a system + * that still defaults to EBCDIC then you already have much bigger + * interoperability issues to deal with. + */ + +/* + * Some macros for constant-time comparisons. These work over values in + * the 0..255 range. Returned value is 0x00 on "false", 0xFF on "true". + */ +#define EQ(x, y) ((((0U - ((unsigned)(x) ^ (unsigned)(y))) >> 8) & 0xFF) ^ 0xFF) +#define GT(x, y) ((((unsigned)(y) - (unsigned)(x)) >> 8) & 0xFF) +#define GE(x, y) (GT(y, x) ^ 0xFF) +#define LT(x, y) GT(y, x) +#define LE(x, y) GE(y, x) + +/* + * Convert value x (0..63) to corresponding Base64 character. + */ +static int b64_byte_to_char(unsigned x) { + return (LT(x, 26) & (x + 'A')) | + (GE(x, 26) & LT(x, 52) & (x + ('a' - 26))) | + (GE(x, 52) & LT(x, 62) & (x + ('0' - 52))) | (EQ(x, 62) & '+') | + (EQ(x, 63) & '/'); +} + +/* + * Convert character c to the corresponding 6-bit value. If character c + * is not a Base64 character, then 0xFF (255) is returned. + */ +static unsigned b64_char_to_byte(int c) { + unsigned x; + + x = (GE(c, 'A') & LE(c, 'Z') & (c - 'A')) | + (GE(c, 'a') & LE(c, 'z') & (c - ('a' - 26))) | + (GE(c, '0') & LE(c, '9') & (c - ('0' - 52))) | (EQ(c, '+') & 62) | + (EQ(c, '/') & 63); + return x | (EQ(x, 0) & (EQ(c, 'A') ^ 0xFF)); +} + +/* + * Convert some bytes to Base64. 'dst_len' is the length (in characters) + * of the output buffer 'dst'; if that buffer is not large enough to + * receive the result (including the terminating 0), then (size_t)-1 + * is returned. Otherwise, the zero-terminated Base64 string is written + * in the buffer, and the output length (counted WITHOUT the terminating + * zero) is returned. + */ +static size_t to_base64(char *dst, size_t dst_len, const void *src, + size_t src_len) { + size_t olen; + const unsigned char *buf; + unsigned acc, acc_len; + + olen = (src_len / 3) << 2; + switch (src_len % 3) { + case 2: + olen++; + /* fall through */ + case 1: + olen += 2; + break; + } + if (dst_len <= olen) { + return (size_t)-1; + } + acc = 0; + acc_len = 0; + buf = (const unsigned char *)src; + while (src_len-- > 0) { + acc = (acc << 8) + (*buf++); + acc_len += 8; + while (acc_len >= 6) { + acc_len -= 6; + *dst++ = (char)b64_byte_to_char((acc >> acc_len) & 0x3F); + } + } + if (acc_len > 0) { + *dst++ = (char)b64_byte_to_char((acc << (6 - acc_len)) & 0x3F); + } + *dst++ = 0; + return olen; +} + +/* + * Decode Base64 chars into bytes. The '*dst_len' value must initially + * contain the length of the output buffer '*dst'; when the decoding + * ends, the actual number of decoded bytes is written back in + * '*dst_len'. + * + * Decoding stops when a non-Base64 character is encountered, or when + * the output buffer capacity is exceeded. If an error occurred (output + * buffer is too small, invalid last characters leading to unprocessed + * buffered bits), then NULL is returned; otherwise, the returned value + * points to the first non-Base64 character in the source stream, which + * may be the terminating zero. + */ +static const char *from_base64(void *dst, size_t *dst_len, const char *src) { + size_t len; + unsigned char *buf; + unsigned acc, acc_len; + + buf = (unsigned char *)dst; + len = 0; + acc = 0; + acc_len = 0; + for (;;) { + unsigned d; + + d = b64_char_to_byte(*src); + if (d == 0xFF) { + break; + } + src++; + acc = (acc << 6) + d; + acc_len += 6; + if (acc_len >= 8) { + acc_len -= 8; + if ((len++) >= *dst_len) { + return NULL; + } + *buf++ = (acc >> acc_len) & 0xFF; + } + } + + /* + * If the input length is equal to 1 modulo 4 (which is + * invalid), then there will remain 6 unprocessed bits; + * otherwise, only 0, 2 or 4 bits are buffered. The buffered + * bits must also all be zero. + */ + if (acc_len > 4 || (acc & (((unsigned)1 << acc_len) - 1)) != 0) { + return NULL; + } + *dst_len = len; + return src; +} + +/* + * Decode decimal integer from 'str'; the value is written in '*v'. + * Returned value is a pointer to the next non-decimal character in the + * string. If there is no digit at all, or the value encoding is not + * minimal (extra leading zeros), or the value does not fit in an + * 'unsigned long', then NULL is returned. + */ +static const char *decode_decimal(const char *str, unsigned long *v) { + const char *orig; + unsigned long acc; + + acc = 0; + for (orig = str;; str++) { + int c; + + c = *str; + if (c < '0' || c > '9') { + break; + } + c -= '0'; + if (acc > (ULONG_MAX / 10)) { + return NULL; + } + acc *= 10; + if ((unsigned long)c > (ULONG_MAX - acc)) { + return NULL; + } + acc += (unsigned long)c; + } + if (str == orig || (*orig == '0' && str != (orig + 1))) { + return NULL; + } + *v = acc; + return str; +} + +/* ==================================================================== */ +/* + * Code specific to Argon2. + * + * The code below applies the following format: + * + * $argon2<T>[$v=<num>]$m=<num>,t=<num>,p=<num>$<bin>$<bin> + * + * where <T> is either 'd', 'id', or 'i', <num> is a decimal integer (positive, + * fits in an 'unsigned long'), and <bin> is Base64-encoded data (no '=' padding + * characters, no newline or whitespace). + * + * The last two binary chunks (encoded in Base64) are, in that order, + * the salt and the output. Both are required. The binary salt length and the + * output length must be in the allowed ranges defined in argon2.h. + * + * The ctx struct must contain buffers large enough to hold the salt and pwd + * when it is fed into decode_string. + */ + +int decode_string(argon2_context *ctx, const char *str, argon2_type type) { + +/* check for prefix */ +#define CC(prefix) \ + do { \ + size_t cc_len = strlen(prefix); \ + if (strncmp(str, prefix, cc_len) != 0) { \ + return ARGON2_DECODING_FAIL; \ + } \ + str += cc_len; \ + } while ((void)0, 0) + +/* optional prefix checking with supplied code */ +#define CC_opt(prefix, code) \ + do { \ + size_t cc_len = strlen(prefix); \ + if (strncmp(str, prefix, cc_len) == 0) { \ + str += cc_len; \ + { code; } \ + } \ + } while ((void)0, 0) + +/* Decoding prefix into decimal */ +#define DECIMAL(x) \ + do { \ + unsigned long dec_x; \ + str = decode_decimal(str, &dec_x); \ + if (str == NULL) { \ + return ARGON2_DECODING_FAIL; \ + } \ + (x) = dec_x; \ + } while ((void)0, 0) + + +/* Decoding prefix into uint32_t decimal */ +#define DECIMAL_U32(x) \ + do { \ + unsigned long dec_x; \ + str = decode_decimal(str, &dec_x); \ + if (str == NULL || dec_x > UINT32_MAX) { \ + return ARGON2_DECODING_FAIL; \ + } \ + (x) = (uint32_t)dec_x; \ + } while ((void)0, 0) + + +/* Decoding base64 into a binary buffer */ +#define BIN(buf, max_len, len) \ + do { \ + size_t bin_len = (max_len); \ + str = from_base64(buf, &bin_len, str); \ + if (str == NULL || bin_len > UINT32_MAX) { \ + return ARGON2_DECODING_FAIL; \ + } \ + (len) = (uint32_t)bin_len; \ + } while ((void)0, 0) + + size_t maxsaltlen = ctx->saltlen; + size_t maxoutlen = ctx->outlen; + int validation_result; + const char* type_string; + + /* We should start with the argon2_type we are using */ + type_string = argon2_type2string(type, 0); + if (!type_string) { + return ARGON2_INCORRECT_TYPE; + } + + CC("$"); + CC(type_string); + + /* Reading the version number if the default is suppressed */ + ctx->version = ARGON2_VERSION_10; + CC_opt("$v=", DECIMAL_U32(ctx->version)); + + CC("$m="); + DECIMAL_U32(ctx->m_cost); + CC(",t="); + DECIMAL_U32(ctx->t_cost); + CC(",p="); + DECIMAL_U32(ctx->lanes); + ctx->threads = ctx->lanes; + + CC("$"); + BIN(ctx->salt, maxsaltlen, ctx->saltlen); + CC("$"); + BIN(ctx->out, maxoutlen, ctx->outlen); + + /* The rest of the fields get the default values */ + ctx->secret = NULL; + ctx->secretlen = 0; + ctx->ad = NULL; + ctx->adlen = 0; + ctx->allocate_cbk = NULL; + ctx->free_cbk = NULL; + ctx->flags = ARGON2_DEFAULT_FLAGS; + + /* On return, must have valid context */ + validation_result = validate_inputs(ctx); + if (validation_result != ARGON2_OK) { + return validation_result; + } + + /* Can't have any additional characters */ + if (*str == 0) { + return ARGON2_OK; + } else { + return ARGON2_DECODING_FAIL; + } +#undef CC +#undef CC_opt +#undef DECIMAL +#undef BIN +} + +int encode_string(char *dst, size_t dst_len, argon2_context *ctx, + argon2_type type) { +#define SS(str) \ + do { \ + size_t pp_len = strlen(str); \ + if (pp_len >= dst_len) { \ + return ARGON2_ENCODING_FAIL; \ + } \ + memcpy(dst, str, pp_len + 1); \ + dst += pp_len; \ + dst_len -= pp_len; \ + } while ((void)0, 0) + +#define SX(x) \ + do { \ + char tmp[30]; \ + sprintf(tmp, "%lu", (unsigned long)(x)); \ + SS(tmp); \ + } while ((void)0, 0) + +#define SB(buf, len) \ + do { \ + size_t sb_len = to_base64(dst, dst_len, buf, len); \ + if (sb_len == (size_t)-1) { \ + return ARGON2_ENCODING_FAIL; \ + } \ + dst += sb_len; \ + dst_len -= sb_len; \ + } while ((void)0, 0) + + const char* type_string = argon2_type2string(type, 0); + int validation_result = validate_inputs(ctx); + + if (!type_string) { + return ARGON2_ENCODING_FAIL; + } + + if (validation_result != ARGON2_OK) { + return validation_result; + } + + + SS("$"); + SS(type_string); + + SS("$v="); + SX(ctx->version); + + SS("$m="); + SX(ctx->m_cost); + SS(",t="); + SX(ctx->t_cost); + SS(",p="); + SX(ctx->lanes); + + SS("$"); + SB(ctx->salt, ctx->saltlen); + + SS("$"); + SB(ctx->out, ctx->outlen); + return ARGON2_OK; + +#undef SS +#undef SX +#undef SB +} + +size_t b64len(uint32_t len) { + size_t olen = ((size_t)len / 3) << 2; + + switch (len % 3) { + case 2: + olen++; + /* fall through */ + case 1: + olen += 2; + break; + } + + return olen; +} + +size_t numlen(uint32_t num) { + size_t len = 1; + while (num >= 10) { + ++len; + num = num / 10; + } + return len; +} diff --git a/lib/crypto_backend/argon2/encoding.h b/lib/crypto_backend/argon2/encoding.h new file mode 100644 index 0000000..5b8b2dd --- /dev/null +++ b/lib/crypto_backend/argon2/encoding.h @@ -0,0 +1,57 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ENCODING_H +#define ENCODING_H +#include "argon2.h" + +#define ARGON2_MAX_DECODED_LANES UINT32_C(255) +#define ARGON2_MIN_DECODED_SALT_LEN UINT32_C(8) +#define ARGON2_MIN_DECODED_OUT_LEN UINT32_C(12) + +/* +* encode an Argon2 hash string into the provided buffer. 'dst_len' +* contains the size, in characters, of the 'dst' buffer; if 'dst_len' +* is less than the number of required characters (including the +* terminating 0), then this function returns ARGON2_ENCODING_ERROR. +* +* on success, ARGON2_OK is returned. +*/ +int encode_string(char *dst, size_t dst_len, argon2_context *ctx, + argon2_type type); + +/* +* Decodes an Argon2 hash string into the provided structure 'ctx'. +* The only fields that must be set prior to this call are ctx.saltlen and +* ctx.outlen (which must be the maximal salt and out length values that are +* allowed), ctx.salt and ctx.out (which must be buffers of the specified +* length), and ctx.pwd and ctx.pwdlen which must hold a valid password. +* +* Invalid input string causes an error. On success, the ctx is valid and all +* fields have been initialized. +* +* Returned value is ARGON2_OK on success, other ARGON2_ codes on error. +*/ +int decode_string(argon2_context *ctx, const char *str, argon2_type type); + +/* Returns the length of the encoded byte stream with length len */ +size_t b64len(uint32_t len); + +/* Returns the length of the encoded number num */ +size_t numlen(uint32_t num); + +#endif diff --git a/lib/crypto_backend/argon2/opt.c b/lib/crypto_backend/argon2/opt.c new file mode 100644 index 0000000..6c5e403 --- /dev/null +++ b/lib/crypto_backend/argon2/opt.c @@ -0,0 +1,283 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include <stdint.h> +#include <string.h> +#include <stdlib.h> + +#include "argon2.h" +#include "core.h" + +#include "blake2/blake2.h" +#include "blake2/blamka-round-opt.h" + +/* + * Function fills a new memory block and optionally XORs the old block over the new one. + * Memory must be initialized. + * @param state Pointer to the just produced block. Content will be updated(!) + * @param ref_block Pointer to the reference block + * @param next_block Pointer to the block to be XORed over. May coincide with @ref_block + * @param with_xor Whether to XOR into the new block (1) or just overwrite (0) + * @pre all block pointers must be valid + */ +#if defined(__AVX512F__) +static void fill_block(__m512i *state, const block *ref_block, + block *next_block, int with_xor) { + __m512i block_XY[ARGON2_512BIT_WORDS_IN_BLOCK]; + unsigned int i; + + if (with_xor) { + for (i = 0; i < ARGON2_512BIT_WORDS_IN_BLOCK; i++) { + state[i] = _mm512_xor_si512( + state[i], _mm512_loadu_si512((const __m512i *)ref_block->v + i)); + block_XY[i] = _mm512_xor_si512( + state[i], _mm512_loadu_si512((const __m512i *)next_block->v + i)); + } + } else { + for (i = 0; i < ARGON2_512BIT_WORDS_IN_BLOCK; i++) { + block_XY[i] = state[i] = _mm512_xor_si512( + state[i], _mm512_loadu_si512((const __m512i *)ref_block->v + i)); + } + } + + for (i = 0; i < 2; ++i) { + BLAKE2_ROUND_1( + state[8 * i + 0], state[8 * i + 1], state[8 * i + 2], state[8 * i + 3], + state[8 * i + 4], state[8 * i + 5], state[8 * i + 6], state[8 * i + 7]); + } + + for (i = 0; i < 2; ++i) { + BLAKE2_ROUND_2( + state[2 * 0 + i], state[2 * 1 + i], state[2 * 2 + i], state[2 * 3 + i], + state[2 * 4 + i], state[2 * 5 + i], state[2 * 6 + i], state[2 * 7 + i]); + } + + for (i = 0; i < ARGON2_512BIT_WORDS_IN_BLOCK; i++) { + state[i] = _mm512_xor_si512(state[i], block_XY[i]); + _mm512_storeu_si512((__m512i *)next_block->v + i, state[i]); + } +} +#elif defined(__AVX2__) +static void fill_block(__m256i *state, const block *ref_block, + block *next_block, int with_xor) { + __m256i block_XY[ARGON2_HWORDS_IN_BLOCK]; + unsigned int i; + + if (with_xor) { + for (i = 0; i < ARGON2_HWORDS_IN_BLOCK; i++) { + state[i] = _mm256_xor_si256( + state[i], _mm256_loadu_si256((const __m256i *)ref_block->v + i)); + block_XY[i] = _mm256_xor_si256( + state[i], _mm256_loadu_si256((const __m256i *)next_block->v + i)); + } + } else { + for (i = 0; i < ARGON2_HWORDS_IN_BLOCK; i++) { + block_XY[i] = state[i] = _mm256_xor_si256( + state[i], _mm256_loadu_si256((const __m256i *)ref_block->v + i)); + } + } + + for (i = 0; i < 4; ++i) { + BLAKE2_ROUND_1(state[8 * i + 0], state[8 * i + 4], state[8 * i + 1], state[8 * i + 5], + state[8 * i + 2], state[8 * i + 6], state[8 * i + 3], state[8 * i + 7]); + } + + for (i = 0; i < 4; ++i) { + BLAKE2_ROUND_2(state[ 0 + i], state[ 4 + i], state[ 8 + i], state[12 + i], + state[16 + i], state[20 + i], state[24 + i], state[28 + i]); + } + + for (i = 0; i < ARGON2_HWORDS_IN_BLOCK; i++) { + state[i] = _mm256_xor_si256(state[i], block_XY[i]); + _mm256_storeu_si256((__m256i *)next_block->v + i, state[i]); + } +} +#else +static void fill_block(__m128i *state, const block *ref_block, + block *next_block, int with_xor) { + __m128i block_XY[ARGON2_OWORDS_IN_BLOCK]; + unsigned int i; + + if (with_xor) { + for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) { + state[i] = _mm_xor_si128( + state[i], _mm_loadu_si128((const __m128i *)ref_block->v + i)); + block_XY[i] = _mm_xor_si128( + state[i], _mm_loadu_si128((const __m128i *)next_block->v + i)); + } + } else { + for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) { + block_XY[i] = state[i] = _mm_xor_si128( + state[i], _mm_loadu_si128((const __m128i *)ref_block->v + i)); + } + } + + for (i = 0; i < 8; ++i) { + BLAKE2_ROUND(state[8 * i + 0], state[8 * i + 1], state[8 * i + 2], + state[8 * i + 3], state[8 * i + 4], state[8 * i + 5], + state[8 * i + 6], state[8 * i + 7]); + } + + for (i = 0; i < 8; ++i) { + BLAKE2_ROUND(state[8 * 0 + i], state[8 * 1 + i], state[8 * 2 + i], + state[8 * 3 + i], state[8 * 4 + i], state[8 * 5 + i], + state[8 * 6 + i], state[8 * 7 + i]); + } + + for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) { + state[i] = _mm_xor_si128(state[i], block_XY[i]); + _mm_storeu_si128((__m128i *)next_block->v + i, state[i]); + } +} +#endif + +static void next_addresses(block *address_block, block *input_block) { + /*Temporary zero-initialized blocks*/ +#if defined(__AVX512F__) + __m512i zero_block[ARGON2_512BIT_WORDS_IN_BLOCK]; + __m512i zero2_block[ARGON2_512BIT_WORDS_IN_BLOCK]; +#elif defined(__AVX2__) + __m256i zero_block[ARGON2_HWORDS_IN_BLOCK]; + __m256i zero2_block[ARGON2_HWORDS_IN_BLOCK]; +#else + __m128i zero_block[ARGON2_OWORDS_IN_BLOCK]; + __m128i zero2_block[ARGON2_OWORDS_IN_BLOCK]; +#endif + + memset(zero_block, 0, sizeof(zero_block)); + memset(zero2_block, 0, sizeof(zero2_block)); + + /*Increasing index counter*/ + input_block->v[6]++; + + /*First iteration of G*/ + fill_block(zero_block, input_block, address_block, 0); + + /*Second iteration of G*/ + fill_block(zero2_block, address_block, address_block, 0); +} + +void fill_segment(const argon2_instance_t *instance, + argon2_position_t position) { + block *ref_block = NULL, *curr_block = NULL; + block address_block, input_block; + uint64_t pseudo_rand, ref_index, ref_lane; + uint32_t prev_offset, curr_offset; + uint32_t starting_index, i; +#if defined(__AVX512F__) + __m512i state[ARGON2_512BIT_WORDS_IN_BLOCK]; +#elif defined(__AVX2__) + __m256i state[ARGON2_HWORDS_IN_BLOCK]; +#else + __m128i state[ARGON2_OWORDS_IN_BLOCK]; +#endif + int data_independent_addressing; + + if (instance == NULL) { + return; + } + + data_independent_addressing = + (instance->type == Argon2_i) || + (instance->type == Argon2_id && (position.pass == 0) && + (position.slice < ARGON2_SYNC_POINTS / 2)); + + if (data_independent_addressing) { + init_block_value(&input_block, 0); + + input_block.v[0] = position.pass; + input_block.v[1] = position.lane; + input_block.v[2] = position.slice; + input_block.v[3] = instance->memory_blocks; + input_block.v[4] = instance->passes; + input_block.v[5] = instance->type; + } + + starting_index = 0; + + if ((0 == position.pass) && (0 == position.slice)) { + starting_index = 2; /* we have already generated the first two blocks */ + + /* Don't forget to generate the first block of addresses: */ + if (data_independent_addressing) { + next_addresses(&address_block, &input_block); + } + } + + /* Offset of the current block */ + curr_offset = position.lane * instance->lane_length + + position.slice * instance->segment_length + starting_index; + + if (0 == curr_offset % instance->lane_length) { + /* Last block in this lane */ + prev_offset = curr_offset + instance->lane_length - 1; + } else { + /* Previous block */ + prev_offset = curr_offset - 1; + } + + memcpy(state, ((instance->memory + prev_offset)->v), ARGON2_BLOCK_SIZE); + + for (i = starting_index; i < instance->segment_length; + ++i, ++curr_offset, ++prev_offset) { + /*1.1 Rotating prev_offset if needed */ + if (curr_offset % instance->lane_length == 1) { + prev_offset = curr_offset - 1; + } + + /* 1.2 Computing the index of the reference block */ + /* 1.2.1 Taking pseudo-random value from the previous block */ + if (data_independent_addressing) { + if (i % ARGON2_ADDRESSES_IN_BLOCK == 0) { + next_addresses(&address_block, &input_block); + } + pseudo_rand = address_block.v[i % ARGON2_ADDRESSES_IN_BLOCK]; + } else { + pseudo_rand = instance->memory[prev_offset].v[0]; + } + + /* 1.2.2 Computing the lane of the reference block */ + ref_lane = ((pseudo_rand >> 32)) % instance->lanes; + + if ((position.pass == 0) && (position.slice == 0)) { + /* Can not reference other lanes yet */ + ref_lane = position.lane; + } + + /* 1.2.3 Computing the number of possible reference block within the + * lane. + */ + position.index = i; + ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, + ref_lane == position.lane); + + /* 2 Creating a new block */ + ref_block = + instance->memory + instance->lane_length * ref_lane + ref_index; + curr_block = instance->memory + curr_offset; + if (ARGON2_VERSION_10 == instance->version) { + /* version 1.2.1 and earlier: overwrite, not XOR */ + fill_block(state, ref_block, curr_block, 0); + } else { + if(0 == position.pass) { + fill_block(state, ref_block, curr_block, 0); + } else { + fill_block(state, ref_block, curr_block, 1); + } + } + } +} diff --git a/lib/crypto_backend/argon2/ref.c b/lib/crypto_backend/argon2/ref.c new file mode 100644 index 0000000..10e45eb --- /dev/null +++ b/lib/crypto_backend/argon2/ref.c @@ -0,0 +1,194 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include <stdint.h> +#include <string.h> +#include <stdlib.h> + +#include "argon2.h" +#include "core.h" + +#include "blake2/blamka-round-ref.h" +#include "blake2/blake2-impl.h" +#include "blake2/blake2.h" + + +/* + * Function fills a new memory block and optionally XORs the old block over the new one. + * @next_block must be initialized. + * @param prev_block Pointer to the previous block + * @param ref_block Pointer to the reference block + * @param next_block Pointer to the block to be constructed + * @param with_xor Whether to XOR into the new block (1) or just overwrite (0) + * @pre all block pointers must be valid + */ +static void fill_block(const block *prev_block, const block *ref_block, + block *next_block, int with_xor) { + block blockR, block_tmp; + unsigned i; + + copy_block(&blockR, ref_block); + xor_block(&blockR, prev_block); + copy_block(&block_tmp, &blockR); + /* Now blockR = ref_block + prev_block and block_tmp = ref_block + prev_block */ + if (with_xor) { + /* Saving the next block contents for XOR over: */ + xor_block(&block_tmp, next_block); + /* Now blockR = ref_block + prev_block and + block_tmp = ref_block + prev_block + next_block */ + } + + /* Apply Blake2 on columns of 64-bit words: (0,1,...,15) , then + (16,17,..31)... finally (112,113,...127) */ + for (i = 0; i < 8; ++i) { + BLAKE2_ROUND_NOMSG( + blockR.v[16 * i], blockR.v[16 * i + 1], blockR.v[16 * i + 2], + blockR.v[16 * i + 3], blockR.v[16 * i + 4], blockR.v[16 * i + 5], + blockR.v[16 * i + 6], blockR.v[16 * i + 7], blockR.v[16 * i + 8], + blockR.v[16 * i + 9], blockR.v[16 * i + 10], blockR.v[16 * i + 11], + blockR.v[16 * i + 12], blockR.v[16 * i + 13], blockR.v[16 * i + 14], + blockR.v[16 * i + 15]); + } + + /* Apply Blake2 on rows of 64-bit words: (0,1,16,17,...112,113), then + (2,3,18,19,...,114,115).. finally (14,15,30,31,...,126,127) */ + for (i = 0; i < 8; i++) { + BLAKE2_ROUND_NOMSG( + blockR.v[2 * i], blockR.v[2 * i + 1], blockR.v[2 * i + 16], + blockR.v[2 * i + 17], blockR.v[2 * i + 32], blockR.v[2 * i + 33], + blockR.v[2 * i + 48], blockR.v[2 * i + 49], blockR.v[2 * i + 64], + blockR.v[2 * i + 65], blockR.v[2 * i + 80], blockR.v[2 * i + 81], + blockR.v[2 * i + 96], blockR.v[2 * i + 97], blockR.v[2 * i + 112], + blockR.v[2 * i + 113]); + } + + copy_block(next_block, &block_tmp); + xor_block(next_block, &blockR); +} + +static void next_addresses(block *address_block, block *input_block, + const block *zero_block) { + input_block->v[6]++; + fill_block(zero_block, input_block, address_block, 0); + fill_block(zero_block, address_block, address_block, 0); +} + +void fill_segment(const argon2_instance_t *instance, + argon2_position_t position) { + block *ref_block = NULL, *curr_block = NULL; + block address_block, input_block, zero_block; + uint64_t pseudo_rand, ref_index, ref_lane; + uint32_t prev_offset, curr_offset; + uint32_t starting_index; + uint32_t i; + int data_independent_addressing; + + if (instance == NULL) { + return; + } + + data_independent_addressing = + (instance->type == Argon2_i) || + (instance->type == Argon2_id && (position.pass == 0) && + (position.slice < ARGON2_SYNC_POINTS / 2)); + + if (data_independent_addressing) { + init_block_value(&zero_block, 0); + init_block_value(&input_block, 0); + + input_block.v[0] = position.pass; + input_block.v[1] = position.lane; + input_block.v[2] = position.slice; + input_block.v[3] = instance->memory_blocks; + input_block.v[4] = instance->passes; + input_block.v[5] = instance->type; + } + + starting_index = 0; + + if ((0 == position.pass) && (0 == position.slice)) { + starting_index = 2; /* we have already generated the first two blocks */ + + /* Don't forget to generate the first block of addresses: */ + if (data_independent_addressing) { + next_addresses(&address_block, &input_block, &zero_block); + } + } + + /* Offset of the current block */ + curr_offset = position.lane * instance->lane_length + + position.slice * instance->segment_length + starting_index; + + if (0 == curr_offset % instance->lane_length) { + /* Last block in this lane */ + prev_offset = curr_offset + instance->lane_length - 1; + } else { + /* Previous block */ + prev_offset = curr_offset - 1; + } + + for (i = starting_index; i < instance->segment_length; + ++i, ++curr_offset, ++prev_offset) { + /*1.1 Rotating prev_offset if needed */ + if (curr_offset % instance->lane_length == 1) { + prev_offset = curr_offset - 1; + } + + /* 1.2 Computing the index of the reference block */ + /* 1.2.1 Taking pseudo-random value from the previous block */ + if (data_independent_addressing) { + if (i % ARGON2_ADDRESSES_IN_BLOCK == 0) { + next_addresses(&address_block, &input_block, &zero_block); + } + pseudo_rand = address_block.v[i % ARGON2_ADDRESSES_IN_BLOCK]; + } else { + pseudo_rand = instance->memory[prev_offset].v[0]; + } + + /* 1.2.2 Computing the lane of the reference block */ + ref_lane = ((pseudo_rand >> 32)) % instance->lanes; + + if ((position.pass == 0) && (position.slice == 0)) { + /* Can not reference other lanes yet */ + ref_lane = position.lane; + } + + /* 1.2.3 Computing the number of possible reference block within the + * lane. + */ + position.index = i; + ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, + ref_lane == position.lane); + + /* 2 Creating a new block */ + ref_block = + instance->memory + instance->lane_length * ref_lane + ref_index; + curr_block = instance->memory + curr_offset; + if (ARGON2_VERSION_10 == instance->version) { + /* version 1.2.1 and earlier: overwrite, not XOR */ + fill_block(instance->memory + prev_offset, ref_block, curr_block, 0); + } else { + if(0 == position.pass) { + fill_block(instance->memory + prev_offset, ref_block, + curr_block, 0); + } else { + fill_block(instance->memory + prev_offset, ref_block, + curr_block, 1); + } + } + } +} diff --git a/lib/crypto_backend/argon2/thread.c b/lib/crypto_backend/argon2/thread.c new file mode 100644 index 0000000..9fd15ed --- /dev/null +++ b/lib/crypto_backend/argon2/thread.c @@ -0,0 +1,49 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#if !defined(ARGON2_NO_THREADS) + +#include "thread.h" +#if defined(_WIN32) +#include <windows.h> +#endif + +int argon2_thread_create(argon2_thread_handle_t *handle, + argon2_thread_func_t func, void *args) { + if (NULL == handle || func == NULL) { + return -1; + } +#if defined(_WIN32) + *handle = _beginthreadex(NULL, 0, func, args, 0, NULL); + return *handle != 0 ? 0 : -1; +#else + return pthread_create(handle, NULL, func, args); +#endif +} + +int argon2_thread_join(argon2_thread_handle_t handle) { +#if defined(_WIN32) + if (WaitForSingleObject((HANDLE)handle, INFINITE) == WAIT_OBJECT_0) { + return CloseHandle((HANDLE)handle) != 0 ? 0 : -1; + } + return -1; +#else + return pthread_join(handle, NULL); +#endif +} + +#endif /* ARGON2_NO_THREADS */ diff --git a/lib/crypto_backend/argon2/thread.h b/lib/crypto_backend/argon2/thread.h new file mode 100644 index 0000000..478e260 --- /dev/null +++ b/lib/crypto_backend/argon2/thread.h @@ -0,0 +1,62 @@ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_THREAD_H +#define ARGON2_THREAD_H + +#if !defined(ARGON2_NO_THREADS) + +/* + Here we implement an abstraction layer for the simpĺe requirements + of the Argon2 code. We only require 3 primitives---thread creation, + joining, and termination---so full emulation of the pthreads API + is unwarranted. Currently we wrap pthreads and Win32 threads. + + The API defines 2 types: the function pointer type, + argon2_thread_func_t, + and the type of the thread handle---argon2_thread_handle_t. +*/ +#if defined(_WIN32) +#include <process.h> +typedef unsigned(__stdcall *argon2_thread_func_t)(void *); +typedef uintptr_t argon2_thread_handle_t; +#else +#include <pthread.h> +typedef void *(*argon2_thread_func_t)(void *); +typedef pthread_t argon2_thread_handle_t; +#endif + +/* Creates a thread + * @param handle pointer to a thread handle, which is the output of this + * function. Must not be NULL. + * @param func A function pointer for the thread's entry point. Must not be + * NULL. + * @param args Pointer that is passed as an argument to @func. May be NULL. + * @return 0 if @handle and @func are valid pointers and a thread is successfully + * created. + */ +int argon2_thread_create(argon2_thread_handle_t *handle, + argon2_thread_func_t func, void *args); + +/* Waits for a thread to terminate + * @param handle Handle to a thread created with argon2_thread_create. + * @return 0 if @handle is a valid handle, and joining completed successfully. +*/ +int argon2_thread_join(argon2_thread_handle_t handle); + +#endif /* ARGON2_NO_THREADS */ +#endif diff --git a/lib/crypto_backend/argon2_generic.c b/lib/crypto_backend/argon2_generic.c new file mode 100644 index 0000000..0ce67da --- /dev/null +++ b/lib/crypto_backend/argon2_generic.c @@ -0,0 +1,79 @@ +/* + * Argon2 PBKDF2 library wrapper + * + * Copyright (C) 2016-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2016-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <errno.h> +#include "crypto_backend_internal.h" +#if HAVE_ARGON2_H +#include <argon2.h> +#else +#include "argon2/argon2.h" +#endif + +#define CONST_CAST(x) (x)(uintptr_t) + +int argon2(const char *type, const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel) +{ +#if !USE_INTERNAL_ARGON2 && !HAVE_ARGON2_H + return -EINVAL; +#else + argon2_type atype; + argon2_context context = { + .flags = ARGON2_DEFAULT_FLAGS, + .version = ARGON2_VERSION_NUMBER, + .t_cost = (uint32_t)iterations, + .m_cost = (uint32_t)memory, + .lanes = (uint32_t)parallel, + .threads = (uint32_t)parallel, + .out = (uint8_t *)key, + .outlen = (uint32_t)key_length, + .pwd = CONST_CAST(uint8_t *)password, + .pwdlen = (uint32_t)password_length, + .salt = CONST_CAST(uint8_t *)salt, + .saltlen = (uint32_t)salt_length, + }; + int r; + + if (!strcmp(type, "argon2i")) + atype = Argon2_i; + else if(!strcmp(type, "argon2id")) + atype = Argon2_id; + else + return -EINVAL; + + switch (argon2_ctx(&context, atype)) { + case ARGON2_OK: + r = 0; + break; + case ARGON2_MEMORY_ALLOCATION_ERROR: + case ARGON2_FREE_MEMORY_CBK_NULL: + case ARGON2_ALLOCATE_MEMORY_CBK_NULL: + r = -ENOMEM; + break; + default: + r = -EINVAL; + } + + return r; +#endif +} diff --git a/lib/crypto_backend/base64.c b/lib/crypto_backend/base64.c new file mode 100644 index 0000000..42f70cb --- /dev/null +++ b/lib/crypto_backend/base64.c @@ -0,0 +1,276 @@ +/* + * Base64 "Not encryption" helpers, copied and adapted from systemd project. + * + * Copyright (C) 2010 Lennart Poettering + * + * cryptsetup related changes + * Copyright (C) 2021-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <errno.h> +#include <stdlib.h> +#include <limits.h> + +#include "crypto_backend.h" + +#define WHITESPACE " \t\n\r" + +/* https://tools.ietf.org/html/rfc4648#section-4 */ +static char base64char(int x) +{ + static const char table[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + return table[x & 63]; +} + +static int unbase64char(char c) +{ + unsigned offset; + + if (c >= 'A' && c <= 'Z') + return c - 'A'; + + offset = 'Z' - 'A' + 1; + + if (c >= 'a' && c <= 'z') + return c - 'a' + offset; + + offset += 'z' - 'a' + 1; + + if (c >= '0' && c <= '9') + return c - '0' + offset; + + offset += '9' - '0' + 1; + + if (c == '+') + return offset; + + offset++; + + if (c == '/') + return offset; + + return -EINVAL; +} + +int crypt_base64_encode(char **out, size_t *out_length, const char *in, size_t in_length) +{ + char *r, *z; + const uint8_t *x; + + assert(in || in_length == 0); + assert(out); + + /* three input bytes makes four output bytes, padding is added so we must round up */ + z = r = malloc(4 * (in_length + 2) / 3 + 1); + if (!r) + return -ENOMEM; + + for (x = (const uint8_t *)in; x < (const uint8_t*)in + (in_length / 3) * 3; x += 3) { + /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */ + *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */ + *(z++) = base64char((x[0] & 3) << 4 | x[1] >> 4); /* 00XXYYYY */ + *(z++) = base64char((x[1] & 15) << 2 | x[2] >> 6); /* 00YYYYZZ */ + *(z++) = base64char(x[2] & 63); /* 00ZZZZZZ */ + } + + switch (in_length % 3) { + case 2: + *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */ + *(z++) = base64char((x[0] & 3) << 4 | x[1] >> 4); /* 00XXYYYY */ + *(z++) = base64char((x[1] & 15) << 2); /* 00YYYY00 */ + *(z++) = '='; + + break; + case 1: + *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */ + *(z++) = base64char((x[0] & 3) << 4); /* 00XX0000 */ + *(z++) = '='; + *(z++) = '='; + + break; + } + + *z = 0; + *out = r; + if (out_length) + *out_length = z - r; + return 0; +} + +static int unbase64_next(const char **p, size_t *l) +{ + int ret; + + assert(p); + assert(l); + + /* Find the next non-whitespace character, and decode it. If we find padding, we return it as INT_MAX. We + * greedily skip all preceding and all following whitespace. */ + + for (;;) { + if (*l == 0) + return -EPIPE; + + if (!strchr(WHITESPACE, **p)) + break; + + /* Skip leading whitespace */ + (*p)++, (*l)--; + } + + if (**p == '=') + ret = INT_MAX; /* return padding as INT_MAX */ + else { + ret = unbase64char(**p); + if (ret < 0) + return ret; + } + + for (;;) { + (*p)++, (*l)--; + + if (*l == 0) + break; + if (!strchr(WHITESPACE, **p)) + break; + + /* Skip following whitespace */ + } + + return ret; +} + +int crypt_base64_decode(char **out, size_t *out_length, const char *in, size_t in_length) +{ + uint8_t *buf = NULL; + const char *x; + uint8_t *z; + size_t len; + int r; + + assert(in || in_length == 0); + assert(out); + assert(out_length); + + if (in_length == (size_t) -1) + in_length = strlen(in); + + /* A group of four input bytes needs three output bytes, in case of padding we need to add two or three extra + * bytes. Note that this calculation is an upper boundary, as we ignore whitespace while decoding */ + len = (in_length / 4) * 3 + (in_length % 4 != 0 ? (in_length % 4) - 1 : 0); + + buf = malloc(len + 1); + if (!buf) + return -ENOMEM; + + for (x = in, z = buf;;) { + int a, b, c, d; /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */ + + a = unbase64_next(&x, &in_length); + if (a == -EPIPE) /* End of string */ + break; + if (a < 0) { + r = a; + goto err; + } + if (a == INT_MAX) { /* Padding is not allowed at the beginning of a 4ch block */ + r = -EINVAL; + goto err; + } + + b = unbase64_next(&x, &in_length); + if (b < 0) { + r = b; + goto err; + } + if (b == INT_MAX) { /* Padding is not allowed at the second character of a 4ch block either */ + r = -EINVAL; + goto err; + } + + c = unbase64_next(&x, &in_length); + if (c < 0) { + r = c; + goto err; + } + + d = unbase64_next(&x, &in_length); + if (d < 0) { + r = d; + goto err; + } + + if (c == INT_MAX) { /* Padding at the third character */ + + if (d != INT_MAX) { /* If the third character is padding, the fourth must be too */ + r = -EINVAL; + goto err; + } + + /* b == 00YY0000 */ + if (b & 15) { + r = -EINVAL; + goto err; + } + + if (in_length > 0) { /* Trailing rubbish? */ + r = -ENAMETOOLONG; + goto err; + } + + *(z++) = (uint8_t) a << 2 | (uint8_t) (b >> 4); /* XXXXXXYY */ + break; + } + + if (d == INT_MAX) { + /* c == 00ZZZZ00 */ + if (c & 3) { + r = -EINVAL; + goto err; + } + + if (in_length > 0) { /* Trailing rubbish? */ + r = -ENAMETOOLONG; + goto err; + } + + *(z++) = (uint8_t) a << 2 | (uint8_t) b >> 4; /* XXXXXXYY */ + *(z++) = (uint8_t) b << 4 | (uint8_t) c >> 2; /* YYYYZZZZ */ + break; + } + + *(z++) = (uint8_t) a << 2 | (uint8_t) b >> 4; /* XXXXXXYY */ + *(z++) = (uint8_t) b << 4 | (uint8_t) c >> 2; /* YYYYZZZZ */ + *(z++) = (uint8_t) c << 6 | (uint8_t) d; /* ZZWWWWWW */ + } + + *z = 0; + + *out_length = (size_t) (z - buf); + *out = (char *)buf; + return 0; +err: + free(buf); + + /* Ignore other errors in crypt_backend */ + if (r != -ENOMEM) + r = -EINVAL; + + return r; +} diff --git a/lib/crypto_backend/cipher_check.c b/lib/crypto_backend/cipher_check.c new file mode 100644 index 0000000..98ec1a5 --- /dev/null +++ b/lib/crypto_backend/cipher_check.c @@ -0,0 +1,161 @@ +/* + * Cipher performance check + * + * Copyright (C) 2018-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2018-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <errno.h> +#include <time.h> +#include "crypto_backend_internal.h" + +#ifndef CLOCK_MONOTONIC_RAW +#define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC +#endif + +/* + * This is not simulating storage, so using disk block causes extreme overhead. + * Let's use some fixed block size where results are more reliable... + */ +#define CIPHER_BLOCK_BYTES 65536 + +/* + * If the measured value is lower, encrypted buffer is probably too small + * and calculated values are not reliable. + */ +#define CIPHER_TIME_MIN_MS 0.001 + +/* + * The whole test depends on Linux kernel usermode crypto API for now. + * (The same implementations are used in dm-crypt though.) + */ + +static int time_ms(struct timespec *start, struct timespec *end, double *ms) +{ + double start_ms, end_ms; + + start_ms = start->tv_sec * 1000.0 + start->tv_nsec / (1000.0 * 1000); + end_ms = end->tv_sec * 1000.0 + end->tv_nsec / (1000.0 * 1000); + + *ms = end_ms - start_ms; + return 0; +} + +static int cipher_perf_one(const char *name, const char *mode, char *buffer, size_t buffer_size, + const char *key, size_t key_size, const char *iv, size_t iv_size, int enc) +{ + struct crypt_cipher_kernel cipher; + size_t done = 0, block = CIPHER_BLOCK_BYTES; + int r; + + if (buffer_size < block) + block = buffer_size; + + r = crypt_cipher_init_kernel(&cipher, name, mode, key, key_size); + if (r < 0) + return r; + + while (done < buffer_size) { + if ((done + block) > buffer_size) + block = buffer_size - done; + + if (enc) + r = crypt_cipher_encrypt_kernel(&cipher, &buffer[done], &buffer[done], + block, iv, iv_size); + else + r = crypt_cipher_decrypt_kernel(&cipher, &buffer[done], &buffer[done], + block, iv, iv_size); + if (r < 0) + break; + + done += block; + } + + crypt_cipher_destroy_kernel(&cipher); + + return r; +} +static int cipher_measure(const char *name, const char *mode, char *buffer, size_t buffer_size, + const char *key, size_t key_size, const char *iv, size_t iv_size, + int encrypt, double *ms) +{ + struct timespec start, end; + int r; + + /* + * Using getrusage would be better here but the precision + * is not adequate, so better stick with CLOCK_MONOTONIC + */ + if (clock_gettime(CLOCK_MONOTONIC_RAW, &start) < 0) + return -EINVAL; + + r = cipher_perf_one(name, mode, buffer, buffer_size, key, key_size, iv, iv_size, encrypt); + if (r < 0) + return r; + + if (clock_gettime(CLOCK_MONOTONIC_RAW, &end) < 0) + return -EINVAL; + + r = time_ms(&start, &end, ms); + if (r < 0) + return r; + + if (*ms < CIPHER_TIME_MIN_MS) + return -ERANGE; + + return 0; +} + +static double speed_mbs(unsigned long bytes, double ms) +{ + double speed = bytes, s = ms / 1000.; + + return speed / (1024 * 1024) / s; +} + +int crypt_cipher_perf_kernel(const char *name, const char *mode, char *buffer, size_t buffer_size, + const char *key, size_t key_size, const char *iv, size_t iv_size, + double *encryption_mbs, double *decryption_mbs) +{ + double ms_enc, ms_dec, ms; + int r, repeat_enc, repeat_dec; + + ms_enc = 0.0; + repeat_enc = 1; + while (ms_enc < 1000.0) { + r = cipher_measure(name, mode, buffer, buffer_size, key, key_size, iv, iv_size, 1, &ms); + if (r < 0) + return r; + ms_enc += ms; + repeat_enc++; + } + + ms_dec = 0.0; + repeat_dec = 1; + while (ms_dec < 1000.0) { + r = cipher_measure(name, mode, buffer, buffer_size, key, key_size, iv, iv_size, 0, &ms); + if (r < 0) + return r; + ms_dec += ms; + repeat_dec++; + } + + *encryption_mbs = speed_mbs(buffer_size * repeat_enc, ms_enc); + *decryption_mbs = speed_mbs(buffer_size * repeat_dec, ms_dec); + + return 0; +} diff --git a/lib/crypto_backend/cipher_generic.c b/lib/crypto_backend/cipher_generic.c new file mode 100644 index 0000000..b3a4407 --- /dev/null +++ b/lib/crypto_backend/cipher_generic.c @@ -0,0 +1,89 @@ +/* + * Linux kernel cipher generic utilities + * + * Copyright (C) 2018-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2018-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <string.h> +#include <stdbool.h> +#include <errno.h> +#include "crypto_backend.h" + +struct cipher_alg { + const char *name; + const char *mode; + int blocksize; + bool wrapped_key; +}; + +static const struct cipher_alg cipher_algs[] = { + { "cipher_null", NULL, 16, false }, + { "aes", NULL, 16, false }, + { "serpent", NULL, 16, false }, + { "twofish", NULL, 16, false }, + { "anubis", NULL, 16, false }, + { "blowfish", NULL, 8, false }, + { "camellia", NULL, 16, false }, + { "cast5", NULL, 8, false }, + { "cast6", NULL, 16, false }, + { "des", NULL, 8, false }, + { "des3_ede", NULL, 8, false }, + { "khazad", NULL, 8, false }, + { "seed", NULL, 16, false }, + { "tea", NULL, 8, false }, + { "xtea", NULL, 8, false }, + { "paes", NULL, 16, true }, /* protected AES, s390 wrapped key scheme */ + { "xchacha12,aes", "adiantum", 32, false }, + { "xchacha20,aes", "adiantum", 32, false }, + { "sm4", NULL, 16, false }, + { NULL, NULL, 0, false } +}; + +static const struct cipher_alg *_get_alg(const char *name, const char *mode) +{ + int i = 0; + + while (name && cipher_algs[i].name) { + if (!strcasecmp(name, cipher_algs[i].name)) + if (!mode || !cipher_algs[i].mode || + !strncasecmp(mode, cipher_algs[i].mode, strlen(cipher_algs[i].mode))) + return &cipher_algs[i]; + i++; + } + return NULL; +} + +int crypt_cipher_ivsize(const char *name, const char *mode) +{ + const struct cipher_alg *ca = _get_alg(name, mode); + + if (!ca) + return -EINVAL; + + if (mode && !strcasecmp(mode, "ecb")) + return 0; + + return ca->blocksize; +} + +int crypt_cipher_wrapped_key(const char *name, const char *mode) +{ + const struct cipher_alg *ca = _get_alg(name, mode); + + return ca ? (int)ca->wrapped_key : 0; +} diff --git a/lib/crypto_backend/crc32.c b/lib/crypto_backend/crc32.c new file mode 100644 index 0000000..9009b02 --- /dev/null +++ b/lib/crypto_backend/crc32.c @@ -0,0 +1,183 @@ +/* + * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or + * code or tables extracted from it, as desired without restriction. + * + * First, the polynomial itself and its table of feedback terms. The + * polynomial is + * X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 + * + * Note that we take it "backwards" and put the highest-order term in + * the lowest-order bit. The X^32 term is "implied"; the LSB is the + * X^31 term, etc. The X^0 term (usually shown as "+1") results in + * the MSB being 1. + * + * Note that the usual hardware shift register implementation, which + * is what we're using (we're merely optimizing it by doing eight-bit + * chunks at a time) shifts bits into the lowest-order term. In our + * implementation, that means shifting towards the right. Why do we + * do it this way? Because the calculated CRC must be transmitted in + * order from highest-order term to lowest-order term. UARTs transmit + * characters in order from LSB to MSB. By storing the CRC this way, + * we hand it to the UART in the order low-byte to high-byte; the UART + * sends each low-bit to high-bit; and the result is transmission bit + * by bit from highest- to lowest-order term without requiring any bit + * shuffling on our part. Reception works similarly. + * + * The feedback terms table consists of 256, 32-bit entries. Notes + * + * The table can be generated at runtime if desired; code to do so + * is shown later. It might not be obvious, but the feedback + * terms simply represent the results of eight shift/xor opera- + * tions for all combinations of data and CRC register values. + * + * The values must be right-shifted by eight bits by the "updcrc" + * logic; the shift must be unsigned (bring in zeroes). On some + * hardware you could probably optimize the shift in assembler by + * using byte-swap instructions. + * polynomial $edb88320 + * + */ + +#include <stdio.h> + +#include "crypto_backend.h" + +static const uint32_t crc32_tab[] = { + 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, + 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, + 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, + 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, + 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, + 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, + 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, + 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, + 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, + 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, + 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, + 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, + 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, + 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, + 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, + 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, + 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, + 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, + 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, + 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, + 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, + 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, + 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, + 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, + 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, + 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, + 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, + 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, + 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, + 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, + 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, + 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, + 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, + 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, + 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, + 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, + 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, + 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, + 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, + 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, + 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, + 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, + 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, + 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, + 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, + 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, + 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, + 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, + 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, + 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, + 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, + 0x2d02ef8dL +}; + +static const uint32_t crc32c_tab[] = { + 0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L, 0xC79A971FL, + 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL, 0x8AD958CFL, 0x78B2DBCCL, + 0x6BE22838L, 0x9989AB3BL, 0x4D43CFD0L, 0xBF284CD3L, 0xAC78BF27L, + 0x5E133C24L, 0x105EC76FL, 0xE235446CL, 0xF165B798L, 0x030E349BL, + 0xD7C45070L, 0x25AFD373L, 0x36FF2087L, 0xC494A384L, 0x9A879FA0L, + 0x68EC1CA3L, 0x7BBCEF57L, 0x89D76C54L, 0x5D1D08BFL, 0xAF768BBCL, + 0xBC267848L, 0x4E4DFB4BL, 0x20BD8EDEL, 0xD2D60DDDL, 0xC186FE29L, + 0x33ED7D2AL, 0xE72719C1L, 0x154C9AC2L, 0x061C6936L, 0xF477EA35L, + 0xAA64D611L, 0x580F5512L, 0x4B5FA6E6L, 0xB93425E5L, 0x6DFE410EL, + 0x9F95C20DL, 0x8CC531F9L, 0x7EAEB2FAL, 0x30E349B1L, 0xC288CAB2L, + 0xD1D83946L, 0x23B3BA45L, 0xF779DEAEL, 0x05125DADL, 0x1642AE59L, + 0xE4292D5AL, 0xBA3A117EL, 0x4851927DL, 0x5B016189L, 0xA96AE28AL, + 0x7DA08661L, 0x8FCB0562L, 0x9C9BF696L, 0x6EF07595L, 0x417B1DBCL, + 0xB3109EBFL, 0xA0406D4BL, 0x522BEE48L, 0x86E18AA3L, 0x748A09A0L, + 0x67DAFA54L, 0x95B17957L, 0xCBA24573L, 0x39C9C670L, 0x2A993584L, + 0xD8F2B687L, 0x0C38D26CL, 0xFE53516FL, 0xED03A29BL, 0x1F682198L, + 0x5125DAD3L, 0xA34E59D0L, 0xB01EAA24L, 0x42752927L, 0x96BF4DCCL, + 0x64D4CECFL, 0x77843D3BL, 0x85EFBE38L, 0xDBFC821CL, 0x2997011FL, + 0x3AC7F2EBL, 0xC8AC71E8L, 0x1C661503L, 0xEE0D9600L, 0xFD5D65F4L, + 0x0F36E6F7L, 0x61C69362L, 0x93AD1061L, 0x80FDE395L, 0x72966096L, + 0xA65C047DL, 0x5437877EL, 0x4767748AL, 0xB50CF789L, 0xEB1FCBADL, + 0x197448AEL, 0x0A24BB5AL, 0xF84F3859L, 0x2C855CB2L, 0xDEEEDFB1L, + 0xCDBE2C45L, 0x3FD5AF46L, 0x7198540DL, 0x83F3D70EL, 0x90A324FAL, + 0x62C8A7F9L, 0xB602C312L, 0x44694011L, 0x5739B3E5L, 0xA55230E6L, + 0xFB410CC2L, 0x092A8FC1L, 0x1A7A7C35L, 0xE811FF36L, 0x3CDB9BDDL, + 0xCEB018DEL, 0xDDE0EB2AL, 0x2F8B6829L, 0x82F63B78L, 0x709DB87BL, + 0x63CD4B8FL, 0x91A6C88CL, 0x456CAC67L, 0xB7072F64L, 0xA457DC90L, + 0x563C5F93L, 0x082F63B7L, 0xFA44E0B4L, 0xE9141340L, 0x1B7F9043L, + 0xCFB5F4A8L, 0x3DDE77ABL, 0x2E8E845FL, 0xDCE5075CL, 0x92A8FC17L, + 0x60C37F14L, 0x73938CE0L, 0x81F80FE3L, 0x55326B08L, 0xA759E80BL, + 0xB4091BFFL, 0x466298FCL, 0x1871A4D8L, 0xEA1A27DBL, 0xF94AD42FL, + 0x0B21572CL, 0xDFEB33C7L, 0x2D80B0C4L, 0x3ED04330L, 0xCCBBC033L, + 0xA24BB5A6L, 0x502036A5L, 0x4370C551L, 0xB11B4652L, 0x65D122B9L, + 0x97BAA1BAL, 0x84EA524EL, 0x7681D14DL, 0x2892ED69L, 0xDAF96E6AL, + 0xC9A99D9EL, 0x3BC21E9DL, 0xEF087A76L, 0x1D63F975L, 0x0E330A81L, + 0xFC588982L, 0xB21572C9L, 0x407EF1CAL, 0x532E023EL, 0xA145813DL, + 0x758FE5D6L, 0x87E466D5L, 0x94B49521L, 0x66DF1622L, 0x38CC2A06L, + 0xCAA7A905L, 0xD9F75AF1L, 0x2B9CD9F2L, 0xFF56BD19L, 0x0D3D3E1AL, + 0x1E6DCDEEL, 0xEC064EEDL, 0xC38D26C4L, 0x31E6A5C7L, 0x22B65633L, + 0xD0DDD530L, 0x0417B1DBL, 0xF67C32D8L, 0xE52CC12CL, 0x1747422FL, + 0x49547E0BL, 0xBB3FFD08L, 0xA86F0EFCL, 0x5A048DFFL, 0x8ECEE914L, + 0x7CA56A17L, 0x6FF599E3L, 0x9D9E1AE0L, 0xD3D3E1ABL, 0x21B862A8L, + 0x32E8915CL, 0xC083125FL, 0x144976B4L, 0xE622F5B7L, 0xF5720643L, + 0x07198540L, 0x590AB964L, 0xAB613A67L, 0xB831C993L, 0x4A5A4A90L, + 0x9E902E7BL, 0x6CFBAD78L, 0x7FAB5E8CL, 0x8DC0DD8FL, 0xE330A81AL, + 0x115B2B19L, 0x020BD8EDL, 0xF0605BEEL, 0x24AA3F05L, 0xD6C1BC06L, + 0xC5914FF2L, 0x37FACCF1L, 0x69E9F0D5L, 0x9B8273D6L, 0x88D28022L, + 0x7AB90321L, 0xAE7367CAL, 0x5C18E4C9L, 0x4F48173DL, 0xBD23943EL, + 0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L, 0x34F4F86AL, + 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL, 0x79B737BAL, 0x8BDCB4B9L, + 0x988C474DL, 0x6AE7C44EL, 0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, + 0xAD7D5351L +}; + +/* + * This a generic crc32() function, it takes seed as an argument, + * and does __not__ xor at the end. Then individual users can do + * whatever they need. + */ +static uint32_t compute_crc32( + const uint32_t *crc32_tab, + uint32_t seed, + const unsigned char *buf, + size_t len) +{ + uint32_t crc = seed; + const unsigned char *p = buf; + + while(len-- > 0) + crc = crc32_tab[(crc ^ *p++) & 0xff] ^ (crc >> 8); + + return crc; +} + +uint32_t crypt_crc32(uint32_t seed, const unsigned char *buf, size_t len) +{ + return compute_crc32(crc32_tab, seed, buf, len); +} + +uint32_t crypt_crc32c(uint32_t seed, const unsigned char *buf, size_t len) +{ + return compute_crc32(crc32c_tab, seed, buf, len); +} diff --git a/lib/crypto_backend/crypto_backend.h b/lib/crypto_backend/crypto_backend.h new file mode 100644 index 0000000..88562e9 --- /dev/null +++ b/lib/crypto_backend/crypto_backend.h @@ -0,0 +1,161 @@ +/* + * crypto backend implementation + * + * Copyright (C) 2010-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2010-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#ifndef _CRYPTO_BACKEND_H +#define _CRYPTO_BACKEND_H + +#include <assert.h> +#include <stdint.h> +#include <stdbool.h> +#include <stddef.h> +#include <string.h> +#ifdef HAVE_UCHAR_H +#include <uchar.h> +#else +#define char32_t uint32_t +#define char16_t uint16_t +#endif + +struct crypt_hash; +struct crypt_hmac; +struct crypt_cipher; +struct crypt_storage; + +int crypt_backend_init(bool fips); +void crypt_backend_destroy(void); + +#define CRYPT_BACKEND_KERNEL (1 << 0) /* Crypto uses kernel part, for benchmark */ +#define CRYPT_BACKEND_PBKDF2_INT (1 << 1) /* Iteration in PBKDF2 is signed int and can overflow */ + +uint32_t crypt_backend_flags(void); +const char *crypt_backend_version(void); + +/* HASH */ +int crypt_hash_size(const char *name); +int crypt_hash_init(struct crypt_hash **ctx, const char *name); +int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length); +int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length); +void crypt_hash_destroy(struct crypt_hash *ctx); + +/* HMAC */ +int crypt_hmac_size(const char *name); +int crypt_hmac_init(struct crypt_hmac **ctx, const char *name, + const void *key, size_t key_length); +int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length); +int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length); +void crypt_hmac_destroy(struct crypt_hmac *ctx); + +/* RNG (if fips parameter set, must provide FIPS compliance) */ +enum { CRYPT_RND_NORMAL = 0, CRYPT_RND_KEY = 1, CRYPT_RND_SALT = 2 }; +int crypt_backend_rng(char *buffer, size_t length, int quality, int fips); + + +/* PBKDF*/ +struct crypt_pbkdf_limits { + uint32_t min_iterations, max_iterations; + uint32_t min_memory, max_memory, min_bench_memory; + uint32_t min_parallel, max_parallel; +}; + +int crypt_pbkdf_get_limits(const char *kdf, struct crypt_pbkdf_limits *l); +int crypt_pbkdf(const char *kdf, const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel); +int crypt_pbkdf_perf(const char *kdf, const char *hash, + const char *password, size_t password_size, + const char *salt, size_t salt_size, + size_t volume_key_size, uint32_t time_ms, + uint32_t max_memory_kb, uint32_t parallel_threads, + uint32_t *iterations_out, uint32_t *memory_out, + int (*progress)(uint32_t time_ms, void *usrptr), void *usrptr); + +/* CRC32 */ +uint32_t crypt_crc32(uint32_t seed, const unsigned char *buf, size_t len); +uint32_t crypt_crc32c(uint32_t seed, const unsigned char *buf, size_t len); + +/* Base64 */ +int crypt_base64_encode(char **out, size_t *out_length, const char *in, size_t in_length); +int crypt_base64_decode(char **out, size_t *out_length, const char *in, size_t in_length); + +/* UTF8/16 */ +int crypt_utf16_to_utf8(char **out, const char16_t *s, size_t length /* bytes! */); +int crypt_utf8_to_utf16(char16_t **out, const char *s, size_t length); + +/* Block ciphers */ +int crypt_cipher_ivsize(const char *name, const char *mode); +int crypt_cipher_wrapped_key(const char *name, const char *mode); +int crypt_cipher_init(struct crypt_cipher **ctx, const char *name, + const char *mode, const void *key, size_t key_length); +void crypt_cipher_destroy(struct crypt_cipher *ctx); +int crypt_cipher_encrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length); +int crypt_cipher_decrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length); +bool crypt_cipher_kernel_only(struct crypt_cipher *ctx); + +/* Benchmark of kernel cipher performance */ +int crypt_cipher_perf_kernel(const char *name, const char *mode, char *buffer, size_t buffer_size, + const char *key, size_t key_size, const char *iv, size_t iv_size, + double *encryption_mbs, double *decryption_mbs); + +/* Check availability of a cipher (in kernel only) */ +int crypt_cipher_check_kernel(const char *name, const char *mode, + const char *integrity, size_t key_length); + +/* Storage encryption wrappers */ +int crypt_storage_init(struct crypt_storage **ctx, size_t sector_size, + const char *cipher, const char *cipher_mode, + const void *key, size_t key_length, bool large_iv); +void crypt_storage_destroy(struct crypt_storage *ctx); +int crypt_storage_decrypt(struct crypt_storage *ctx, uint64_t iv_offset, + uint64_t length, char *buffer); +int crypt_storage_encrypt(struct crypt_storage *ctx, uint64_t iv_offset, + uint64_t length, char *buffer); + +bool crypt_storage_kernel_only(struct crypt_storage *ctx); + +/* Temporary Bitlk helper */ +int crypt_bitlk_decrypt_key(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length); + +/* Memzero helper (memset on stack can be optimized out) */ +static inline void crypt_backend_memzero(void *s, size_t n) +{ +#ifdef HAVE_EXPLICIT_BZERO + explicit_bzero(s, n); +#else + volatile uint8_t *p = (volatile uint8_t *)s; + while(n--) *p++ = 0; +#endif +} + +/* Memcmp helper (memcmp in constant time) */ +int crypt_backend_memeq(const void *m1, const void *m2, size_t n); + +/* crypto backend running in FIPS mode */ +bool crypt_fips_mode(void); + +#endif /* _CRYPTO_BACKEND_H */ diff --git a/lib/crypto_backend/crypto_backend_internal.h b/lib/crypto_backend/crypto_backend_internal.h new file mode 100644 index 0000000..9b1cc69 --- /dev/null +++ b/lib/crypto_backend/crypto_backend_internal.h @@ -0,0 +1,75 @@ +/* + * crypto backend implementation + * + * Copyright (C) 2010-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2010-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#ifndef _CRYPTO_BACKEND_INTERNAL_H +#define _CRYPTO_BACKEND_INTERNAL_H + +#include "crypto_backend.h" + +/* internal PBKDF2 implementation */ +int pkcs5_pbkdf2(const char *hash, + const char *P, size_t Plen, + const char *S, size_t Slen, + unsigned int c, + unsigned int dkLen, char *DK, + unsigned int hash_block_size); + +/* Argon2 implementation wrapper */ +int argon2(const char *type, const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel); + +/* Block ciphers: fallback to kernel crypto API */ + +struct crypt_cipher_kernel { + int tfmfd; + int opfd; +}; + +int crypt_cipher_init_kernel(struct crypt_cipher_kernel *ctx, const char *name, + const char *mode, const void *key, size_t key_length); +int crypt_cipher_encrypt_kernel(struct crypt_cipher_kernel *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length); +int crypt_cipher_decrypt_kernel(struct crypt_cipher_kernel *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length); +void crypt_cipher_destroy_kernel(struct crypt_cipher_kernel *ctx); +int crypt_bitlk_decrypt_key_kernel(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length); + +/* Internal implementation for constant time memory comparison */ +static inline int crypt_internal_memeq(const void *m1, const void *m2, size_t n) +{ + const unsigned char *_m1 = (const unsigned char *) m1; + const unsigned char *_m2 = (const unsigned char *) m2; + unsigned char result = 0; + size_t i; + + for (i = 0; i < n; i++) + result |= _m1[i] ^ _m2[i]; + + return result; +} + +#endif /* _CRYPTO_BACKEND_INTERNAL_H */ diff --git a/lib/crypto_backend/crypto_cipher_kernel.c b/lib/crypto_backend/crypto_cipher_kernel.c new file mode 100644 index 0000000..3460717 --- /dev/null +++ b/lib/crypto_backend/crypto_cipher_kernel.c @@ -0,0 +1,351 @@ +/* + * Linux kernel userspace API crypto backend implementation (skcipher) + * + * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2012-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <string.h> +#include <stdlib.h> +#include <stdio.h> +#include <stdbool.h> +#include <errno.h> +#include <unistd.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include "crypto_backend_internal.h" + +#ifdef ENABLE_AF_ALG + +#include <linux/if_alg.h> + +#ifndef AF_ALG +#define AF_ALG 38 +#endif +#ifndef SOL_ALG +#define SOL_ALG 279 +#endif + +#ifndef ALG_SET_AEAD_AUTHSIZE +#define ALG_SET_AEAD_AUTHSIZE 5 +#endif + +/* + * ciphers + * + * ENOENT - algorithm not available + * ENOTSUP - AF_ALG family not available + * (but cannot check specifically for skcipher API) + */ +static int _crypt_cipher_init(struct crypt_cipher_kernel *ctx, + const void *key, size_t key_length, + size_t tag_length, struct sockaddr_alg *sa) +{ + if (!ctx) + return -EINVAL; + + ctx->opfd = -1; + ctx->tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0); + if (ctx->tfmfd < 0) { + crypt_cipher_destroy_kernel(ctx); + return -ENOTSUP; + } + + if (bind(ctx->tfmfd, (struct sockaddr *)sa, sizeof(*sa)) < 0) { + crypt_cipher_destroy_kernel(ctx); + return -ENOENT; + } + + if (setsockopt(ctx->tfmfd, SOL_ALG, ALG_SET_KEY, key, key_length) < 0) { + crypt_cipher_destroy_kernel(ctx); + return -EINVAL; + } + + if (tag_length && setsockopt(ctx->tfmfd, SOL_ALG, ALG_SET_AEAD_AUTHSIZE, NULL, tag_length) < 0) { + crypt_cipher_destroy_kernel(ctx); + return -EINVAL; + } + + ctx->opfd = accept(ctx->tfmfd, NULL, 0); + if (ctx->opfd < 0) { + crypt_cipher_destroy_kernel(ctx); + return -EINVAL; + } + + return 0; +} + +int crypt_cipher_init_kernel(struct crypt_cipher_kernel *ctx, const char *name, + const char *mode, const void *key, size_t key_length) +{ + struct sockaddr_alg sa = { + .salg_family = AF_ALG, + .salg_type = "skcipher", + }; + int r; + + if (!strcmp(name, "cipher_null")) + key_length = 0; + + r = snprintf((char *)sa.salg_name, sizeof(sa.salg_name), "%s(%s)", mode, name); + if (r < 0 || (size_t)r >= sizeof(sa.salg_name)) + return -EINVAL; + + return _crypt_cipher_init(ctx, key, key_length, 0, &sa); +} + +/* The in/out should be aligned to page boundary */ +static int _crypt_cipher_crypt(struct crypt_cipher_kernel *ctx, + const char *in, size_t in_length, + char *out, size_t out_length, + const char *iv, size_t iv_length, + uint32_t direction) +{ + int r = 0; + ssize_t len; + struct af_alg_iv *alg_iv; + struct cmsghdr *header; + uint32_t *type; + struct iovec iov = { + .iov_base = (void*)(uintptr_t)in, + .iov_len = in_length, + }; + int iv_msg_size = iv ? CMSG_SPACE(sizeof(*alg_iv) + iv_length) : 0; + char buffer[CMSG_SPACE(sizeof(*type)) + iv_msg_size]; + struct msghdr msg = { + .msg_control = buffer, + .msg_controllen = sizeof(buffer), + .msg_iov = &iov, + .msg_iovlen = 1, + }; + + if (!in || !out || !in_length) + return -EINVAL; + + if ((!iv && iv_length) || (iv && !iv_length)) + return -EINVAL; + + memset(buffer, 0, sizeof(buffer)); + + /* Set encrypt/decrypt operation */ + header = CMSG_FIRSTHDR(&msg); + if (!header) + return -EINVAL; + + header->cmsg_level = SOL_ALG; + header->cmsg_type = ALG_SET_OP; + header->cmsg_len = CMSG_LEN(sizeof(*type)); + type = (void*)CMSG_DATA(header); + *type = direction; + + /* Set IV */ + if (iv) { + header = CMSG_NXTHDR(&msg, header); + if (!header) + return -EINVAL; + + header->cmsg_level = SOL_ALG; + header->cmsg_type = ALG_SET_IV; + header->cmsg_len = iv_msg_size; + alg_iv = (void*)CMSG_DATA(header); + alg_iv->ivlen = iv_length; + memcpy(alg_iv->iv, iv, iv_length); + } + + len = sendmsg(ctx->opfd, &msg, 0); + if (len != (ssize_t)(in_length)) + r = -EIO; + else { + len = read(ctx->opfd, out, out_length); + if (len != (ssize_t)out_length) + r = -EIO; + } + + crypt_backend_memzero(buffer, sizeof(buffer)); + return r; +} + +int crypt_cipher_encrypt_kernel(struct crypt_cipher_kernel *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return _crypt_cipher_crypt(ctx, in, length, out, length, + iv, iv_length, ALG_OP_ENCRYPT); +} + +int crypt_cipher_decrypt_kernel(struct crypt_cipher_kernel *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return _crypt_cipher_crypt(ctx, in, length, out, length, + iv, iv_length, ALG_OP_DECRYPT); +} + +void crypt_cipher_destroy_kernel(struct crypt_cipher_kernel *ctx) +{ + if (ctx->tfmfd >= 0) + close(ctx->tfmfd); + if (ctx->opfd >= 0) + close(ctx->opfd); + + ctx->tfmfd = -1; + ctx->opfd = -1; +} + +int crypt_cipher_check_kernel(const char *name, const char *mode, + const char *integrity, size_t key_length) +{ + struct crypt_cipher_kernel c; + char mode_name[64], tmp_salg_name[180], *real_mode = NULL, *cipher_iv = NULL, *key; + const char *salg_type; + bool aead; + int r; + struct sockaddr_alg sa = { + .salg_family = AF_ALG, + }; + + aead = integrity && strcmp(integrity, "none"); + + /* Remove IV if present */ + if (mode) { + strncpy(mode_name, mode, sizeof(mode_name)); + mode_name[sizeof(mode_name) - 1] = 0; + cipher_iv = strchr(mode_name, '-'); + if (cipher_iv) { + *cipher_iv = '\0'; + real_mode = mode_name; + } + } + + salg_type = aead ? "aead" : "skcipher"; + r = snprintf((char *)sa.salg_type, sizeof(sa.salg_type), "%s", salg_type); + if (r < 0 || (size_t)r >= sizeof(sa.salg_name)) + return -EINVAL; + + memset(tmp_salg_name, 0, sizeof(tmp_salg_name)); + + /* FIXME: this is duplicating a part of devmapper backend */ + if (aead && !strcmp(integrity, "poly1305")) + r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "rfc7539(%s,%s)", name, integrity); + else if (!real_mode) + r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "%s", name); + else if (aead && !strcmp(real_mode, "ccm")) + r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "rfc4309(%s(%s))", real_mode, name); + else + r = snprintf(tmp_salg_name, sizeof(tmp_salg_name), "%s(%s)", real_mode, name); + + if (r < 0 || (size_t)r >= sizeof(tmp_salg_name)) + return -EINVAL; + + memcpy(sa.salg_name, tmp_salg_name, sizeof(sa.salg_name)); + + key = malloc(key_length); + if (!key) + return -ENOMEM; + + /* We cannot use RNG yet, any key works here, tweak the first part if it is split key (XTS). */ + memset(key, 0xab, key_length); + *key = 0xef; + + r = _crypt_cipher_init(&c, key, key_length, 0, &sa); + crypt_cipher_destroy_kernel(&c); + free(key); + + return r; +} + +int crypt_bitlk_decrypt_key_kernel(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length) +{ + struct crypt_cipher_kernel c; + struct sockaddr_alg sa = { + .salg_family = AF_ALG, + .salg_type = "aead", + .salg_name = "ccm(aes)", + }; + int r; + char buffer[128], ccm_iv[16]; + + if (length + tag_length > sizeof(buffer)) + return -EINVAL; + + if (iv_length > sizeof(ccm_iv) - 2) + return -EINVAL; + + r = _crypt_cipher_init(&c, key, key_length, tag_length, &sa); + if (r < 0) + return r; + + memcpy(buffer, in, length); + memcpy(buffer + length, tag, tag_length); + + /* CCM IV - RFC3610 */ + memset(ccm_iv, 0, sizeof(ccm_iv)); + ccm_iv[0] = 15 - iv_length - 1; + memcpy(ccm_iv + 1, iv, iv_length); + memset(ccm_iv + 1 + iv_length, 0, ccm_iv[0] + 1); + iv_length = sizeof(ccm_iv); + + r = _crypt_cipher_crypt(&c, buffer, length + tag_length, out, length, + ccm_iv, iv_length, ALG_OP_DECRYPT); + + crypt_cipher_destroy_kernel(&c); + crypt_backend_memzero(buffer, sizeof(buffer)); + + return r; +} + +#else /* ENABLE_AF_ALG */ +int crypt_cipher_init_kernel(struct crypt_cipher_kernel *ctx, const char *name, + const char *mode, const void *key, size_t key_length) +{ + return -ENOTSUP; +} + +void crypt_cipher_destroy_kernel(struct crypt_cipher_kernel *ctx) +{ + return; +} + +int crypt_cipher_encrypt_kernel(struct crypt_cipher_kernel *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return -EINVAL; +} +int crypt_cipher_decrypt_kernel(struct crypt_cipher_kernel *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return -EINVAL; +} +int crypt_cipher_check_kernel(const char *name, const char *mode, + const char *integrity, size_t key_length) +{ + /* Cannot check, expect success. */ + return 0; +} +int crypt_bitlk_decrypt_key_kernel(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length) +{ + return -ENOTSUP; +} +#endif diff --git a/lib/crypto_backend/crypto_gcrypt.c b/lib/crypto_backend/crypto_gcrypt.c new file mode 100644 index 0000000..e974aa8 --- /dev/null +++ b/lib/crypto_backend/crypto_gcrypt.c @@ -0,0 +1,573 @@ +/* + * GCRYPT crypto backend implementation + * + * Copyright (C) 2010-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2010-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <string.h> +#include <stdio.h> +#include <errno.h> +#include <gcrypt.h> +#include "crypto_backend_internal.h" + +static int crypto_backend_initialised = 0; +static int crypto_backend_secmem = 1; +static int crypto_backend_whirlpool_bug = -1; +static char version[64]; + +struct crypt_hash { + gcry_md_hd_t hd; + int hash_id; + int hash_len; +}; + +struct crypt_hmac { + gcry_md_hd_t hd; + int hash_id; + int hash_len; +}; + +struct crypt_cipher { + bool use_kernel; + union { + struct crypt_cipher_kernel kernel; + gcry_cipher_hd_t hd; + } u; +}; + +struct hash_alg { + const char *name; + const char *gcrypt_name; +}; + +/* + * Test for wrong Whirlpool variant, + * Ref: https://lists.gnupg.org/pipermail/gcrypt-devel/2014-January/002889.html + */ +static void crypt_hash_test_whirlpool_bug(void) +{ + struct crypt_hash *h; + char buf[2] = "\0\0", hash_out1[64], hash_out2[64]; + int r; + + if (crypto_backend_whirlpool_bug >= 0) + return; + + crypto_backend_whirlpool_bug = 0; + if (crypt_hash_init(&h, "whirlpool")) + return; + + /* One shot */ + if ((r = crypt_hash_write(h, &buf[0], 2)) || + (r = crypt_hash_final(h, hash_out1, 64))) { + crypt_hash_destroy(h); + return; + } + + /* Split buf (crypt_hash_final resets hash state) */ + if ((r = crypt_hash_write(h, &buf[0], 1)) || + (r = crypt_hash_write(h, &buf[1], 1)) || + (r = crypt_hash_final(h, hash_out2, 64))) { + crypt_hash_destroy(h); + return; + } + + crypt_hash_destroy(h); + + if (memcmp(hash_out1, hash_out2, 64)) + crypto_backend_whirlpool_bug = 1; +} + +int crypt_backend_init(bool fips __attribute__((unused))) +{ + int r; + + if (crypto_backend_initialised) + return 0; + + if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P)) { + if (!gcry_check_version (GCRYPT_REQ_VERSION)) { + return -ENOSYS; + } + +/* If gcrypt compiled to support POSIX 1003.1e capabilities, + * it drops all privileges during secure memory initialisation. + * For now, the only workaround is to disable secure memory in gcrypt. + * cryptsetup always need at least cap_sys_admin privilege for dm-ioctl + * and it locks its memory space anyway. + */ +#if 0 + gcry_control (GCRYCTL_DISABLE_SECMEM); + crypto_backend_secmem = 0; +#else + + gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); + gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0); + gcry_control (GCRYCTL_RESUME_SECMEM_WARN); +#endif + gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); + } + + crypto_backend_initialised = 1; + crypt_hash_test_whirlpool_bug(); + + r = snprintf(version, sizeof(version), "gcrypt %s%s%s", + gcry_check_version(NULL), + crypto_backend_secmem ? "" : ", secmem disabled", + crypto_backend_whirlpool_bug > 0 ? ", flawed whirlpool" : ""); + if (r < 0 || (size_t)r >= sizeof(version)) + return -EINVAL; + + return 0; +} + +void crypt_backend_destroy(void) +{ + if (crypto_backend_initialised) + gcry_control(GCRYCTL_TERM_SECMEM); + + crypto_backend_initialised = 0; +} + +const char *crypt_backend_version(void) +{ + return crypto_backend_initialised ? version : ""; +} + +uint32_t crypt_backend_flags(void) +{ + return 0; +} + +static const char *crypt_hash_compat_name(const char *name, unsigned int *flags) +{ + const char *hash_name = name; + int i; + static struct hash_alg hash_algs[] = { + { "blake2b-160", "blake2b_160" }, + { "blake2b-256", "blake2b_256" }, + { "blake2b-384", "blake2b_384" }, + { "blake2b-512", "blake2b_512" }, + { "blake2s-128", "blake2s_128" }, + { "blake2s-160", "blake2s_160" }, + { "blake2s-224", "blake2s_224" }, + { "blake2s-256", "blake2s_256" }, + { NULL, NULL, }}; + + if (!name) + return NULL; + + /* "whirlpool_gcryptbug" is out shortcut to flawed whirlpool + * in libgcrypt < 1.6.0 */ + if (!strcasecmp(name, "whirlpool_gcryptbug")) { +#if GCRYPT_VERSION_NUMBER >= 0x010601 + if (flags) + *flags |= GCRY_MD_FLAG_BUGEMU1; +#endif + hash_name = "whirlpool"; + } + + i = 0; + while (hash_algs[i].name) { + if (!strcasecmp(name, hash_algs[i].name)) { + hash_name = hash_algs[i].gcrypt_name; + break; + } + i++; + } + + return hash_name; +} + +/* HASH */ +int crypt_hash_size(const char *name) +{ + int hash_id; + + assert(crypto_backend_initialised); + + hash_id = gcry_md_map_name(crypt_hash_compat_name(name, NULL)); + if (!hash_id) + return -EINVAL; + + return gcry_md_get_algo_dlen(hash_id); +} + +int crypt_hash_init(struct crypt_hash **ctx, const char *name) +{ + struct crypt_hash *h; + unsigned int flags = 0; + + assert(crypto_backend_initialised); + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + h->hash_id = gcry_md_map_name(crypt_hash_compat_name(name, &flags)); + if (!h->hash_id) { + free(h); + return -EINVAL; + } + + if (gcry_md_open(&h->hd, h->hash_id, flags)) { + free(h); + return -EINVAL; + } + + h->hash_len = gcry_md_get_algo_dlen(h->hash_id); + *ctx = h; + return 0; +} + +static void crypt_hash_restart(struct crypt_hash *ctx) +{ + gcry_md_reset(ctx->hd); +} + +int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length) +{ + gcry_md_write(ctx->hd, buffer, length); + return 0; +} + +int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length) +{ + unsigned char *hash; + + if (length > (size_t)ctx->hash_len) + return -EINVAL; + + hash = gcry_md_read(ctx->hd, ctx->hash_id); + if (!hash) + return -EINVAL; + + memcpy(buffer, hash, length); + crypt_hash_restart(ctx); + + return 0; +} + +void crypt_hash_destroy(struct crypt_hash *ctx) +{ + gcry_md_close(ctx->hd); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* HMAC */ +int crypt_hmac_size(const char *name) +{ + return crypt_hash_size(name); +} + +int crypt_hmac_init(struct crypt_hmac **ctx, const char *name, + const void *key, size_t key_length) +{ + struct crypt_hmac *h; + unsigned int flags = GCRY_MD_FLAG_HMAC; + + assert(crypto_backend_initialised); + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + h->hash_id = gcry_md_map_name(crypt_hash_compat_name(name, &flags)); + if (!h->hash_id) { + free(h); + return -EINVAL; + } + + if (gcry_md_open(&h->hd, h->hash_id, flags)) { + free(h); + return -EINVAL; + } + + if (gcry_md_setkey(h->hd, key, key_length)) { + gcry_md_close(h->hd); + free(h); + return -EINVAL; + } + + h->hash_len = gcry_md_get_algo_dlen(h->hash_id); + *ctx = h; + return 0; +} + +static void crypt_hmac_restart(struct crypt_hmac *ctx) +{ + gcry_md_reset(ctx->hd); +} + +int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length) +{ + gcry_md_write(ctx->hd, buffer, length); + return 0; +} + +int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length) +{ + unsigned char *hash; + + if (length > (size_t)ctx->hash_len) + return -EINVAL; + + hash = gcry_md_read(ctx->hd, ctx->hash_id); + if (!hash) + return -EINVAL; + + memcpy(buffer, hash, length); + crypt_hmac_restart(ctx); + + return 0; +} + +void crypt_hmac_destroy(struct crypt_hmac *ctx) +{ + gcry_md_close(ctx->hd); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* RNG */ +int crypt_backend_rng(char *buffer, size_t length, int quality, int fips __attribute__((unused))) +{ + switch(quality) { + case CRYPT_RND_NORMAL: + gcry_randomize(buffer, length, GCRY_STRONG_RANDOM); + break; + case CRYPT_RND_SALT: + case CRYPT_RND_KEY: + default: + gcry_randomize(buffer, length, GCRY_VERY_STRONG_RANDOM); + break; + } + return 0; +} + +static int pbkdf2(const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations) +{ + const char *hash_name = crypt_hash_compat_name(hash, NULL); + +#if USE_INTERNAL_PBKDF2 + return pkcs5_pbkdf2(hash_name, password, password_length, salt, salt_length, + iterations, key_length, key, 0); +#else /* USE_INTERNAL_PBKDF2 */ + int hash_id = gcry_md_map_name(hash_name); + + if (!hash_id) + return -EINVAL; + + if (gcry_kdf_derive(password, password_length, GCRY_KDF_PBKDF2, hash_id, + salt, salt_length, iterations, key_length, key)) + return -EINVAL; + + return 0; +#endif /* USE_INTERNAL_PBKDF2 */ +} + +/* PBKDF */ +int crypt_pbkdf(const char *kdf, const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel) +{ + if (!kdf) + return -EINVAL; + + if (!strcmp(kdf, "pbkdf2")) + return pbkdf2(hash, password, password_length, salt, salt_length, + key, key_length, iterations); + else if (!strncmp(kdf, "argon2", 6)) + return argon2(kdf, password, password_length, salt, salt_length, + key, key_length, iterations, memory, parallel); + return -EINVAL; +} + +/* Block ciphers */ +static int _cipher_init(gcry_cipher_hd_t *hd, const char *name, + const char *mode, const void *buffer, size_t length) +{ + int cipher_id, mode_id; + + cipher_id = gcry_cipher_map_name(name); + if (cipher_id == GCRY_CIPHER_MODE_NONE) + return -ENOENT; + + if (!strcmp(mode, "ecb")) + mode_id = GCRY_CIPHER_MODE_ECB; + else if (!strcmp(mode, "cbc")) + mode_id = GCRY_CIPHER_MODE_CBC; +#if HAVE_DECL_GCRY_CIPHER_MODE_XTS + else if (!strcmp(mode, "xts")) + mode_id = GCRY_CIPHER_MODE_XTS; +#endif + else + return -ENOENT; + + if (gcry_cipher_open(hd, cipher_id, mode_id, 0)) + return -EINVAL; + + if (gcry_cipher_setkey(*hd, buffer, length)) { + gcry_cipher_close(*hd); + return -EINVAL; + } + + return 0; +} + +int crypt_cipher_init(struct crypt_cipher **ctx, const char *name, + const char *mode, const void *key, size_t key_length) +{ + struct crypt_cipher *h; + int r; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + if (!_cipher_init(&h->u.hd, name, mode, key, key_length)) { + h->use_kernel = false; + *ctx = h; + return 0; + } + + r = crypt_cipher_init_kernel(&h->u.kernel, name, mode, key, key_length); + if (r < 0) { + free(h); + return r; + } + + h->use_kernel = true; + *ctx = h; + return 0; +} + +void crypt_cipher_destroy(struct crypt_cipher *ctx) +{ + if (ctx->use_kernel) + crypt_cipher_destroy_kernel(&ctx->u.kernel); + else + gcry_cipher_close(ctx->u.hd); + free(ctx); +} + +int crypt_cipher_encrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + if (ctx->use_kernel) + return crypt_cipher_encrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length); + + if (iv && gcry_cipher_setiv(ctx->u.hd, iv, iv_length)) + return -EINVAL; + + if (gcry_cipher_encrypt(ctx->u.hd, out, length, in, length)) + return -EINVAL; + + return 0; +} + +int crypt_cipher_decrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + if (ctx->use_kernel) + return crypt_cipher_decrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length); + + if (iv && gcry_cipher_setiv(ctx->u.hd, iv, iv_length)) + return -EINVAL; + + if (gcry_cipher_decrypt(ctx->u.hd, out, length, in, length)) + return -EINVAL; + + return 0; +} + +bool crypt_cipher_kernel_only(struct crypt_cipher *ctx) +{ + return ctx->use_kernel; +} + +int crypt_bitlk_decrypt_key(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length) +{ +#ifdef GCRY_CCM_BLOCK_LEN + gcry_cipher_hd_t hd; + uint64_t l[3]; + int r = -EINVAL; + + if (gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CCM, 0)) + return -EINVAL; + + if (gcry_cipher_setkey(hd, key, key_length)) + goto out; + + if (gcry_cipher_setiv(hd, iv, iv_length)) + goto out; + + l[0] = length; + l[1] = 0; + l[2] = tag_length; + if (gcry_cipher_ctl(hd, GCRYCTL_SET_CCM_LENGTHS, l, sizeof(l))) + goto out; + + if (gcry_cipher_decrypt(hd, out, length, in, length)) + goto out; + + if (gcry_cipher_checktag(hd, tag, tag_length)) + goto out; + + r = 0; +out: + gcry_cipher_close(hd); + return r; +#else + return -ENOTSUP; +#endif +} + +int crypt_backend_memeq(const void *m1, const void *m2, size_t n) +{ + return crypt_internal_memeq(m1, m2, n); +} + +#if !ENABLE_FIPS +bool crypt_fips_mode(void) { return false; } +#else +bool crypt_fips_mode(void) +{ + static bool fips_mode = false, fips_checked = false; + + if (fips_checked) + return fips_mode; + + fips_mode = gcry_fips_mode_active(); + fips_checked = true; + + return fips_mode; +} +#endif /* ENABLE FIPS */ diff --git a/lib/crypto_backend/crypto_kernel.c b/lib/crypto_backend/crypto_kernel.c new file mode 100644 index 0000000..8493c0a --- /dev/null +++ b/lib/crypto_backend/crypto_kernel.c @@ -0,0 +1,428 @@ +/* + * Linux kernel userspace API crypto backend implementation + * + * Copyright (C) 2010-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2010-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <string.h> +#include <stdlib.h> +#include <stdio.h> +#include <errno.h> +#include <unistd.h> +#include <sys/socket.h> +#include <sys/utsname.h> +#include <linux/if_alg.h> +#include "crypto_backend_internal.h" + +#ifndef AF_ALG +#define AF_ALG 38 +#endif +#ifndef SOL_ALG +#define SOL_ALG 279 +#endif + +static int crypto_backend_initialised = 0; +static char version[256]; + +struct hash_alg { + const char *name; + const char *kernel_name; + int length; + unsigned int block_length; +}; + +static struct hash_alg hash_algs[] = { + { "sha1", "sha1", 20, 64 }, + { "sha224", "sha224", 28, 64 }, + { "sha256", "sha256", 32, 64 }, + { "sha384", "sha384", 48, 128 }, + { "sha512", "sha512", 64, 128 }, + { "ripemd160", "rmd160", 20, 64 }, + { "whirlpool", "wp512", 64, 64 }, + { "sha3-224", "sha3-224", 28, 144 }, + { "sha3-256", "sha3-256", 32, 136 }, + { "sha3-384", "sha3-384", 48, 104 }, + { "sha3-512", "sha3-512", 64, 72 }, + { "stribog256","streebog256", 32, 64 }, + { "stribog512","streebog512", 64, 64 }, + { "sm3", "sm3", 32, 64 }, + { "blake2b-160","blake2b-160",20, 128 }, + { "blake2b-256","blake2b-256",32, 128 }, + { "blake2b-384","blake2b-384",48, 128 }, + { "blake2b-512","blake2b-512",64, 128 }, + { "blake2s-128","blake2s-128",16, 64 }, + { "blake2s-160","blake2s-160",20, 64 }, + { "blake2s-224","blake2s-224",28, 64 }, + { "blake2s-256","blake2s-256",32, 64 }, + { NULL, NULL, 0, 0 } +}; + +struct crypt_hash { + int tfmfd; + int opfd; + int hash_len; +}; + +struct crypt_hmac { + int tfmfd; + int opfd; + int hash_len; +}; + +struct crypt_cipher { + struct crypt_cipher_kernel ck; +}; + +static int crypt_kernel_socket_init(struct sockaddr_alg *sa, int *tfmfd, int *opfd, + const void *key, size_t key_length) +{ + *tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0); + if (*tfmfd < 0) + return -ENOTSUP; + + if (bind(*tfmfd, (struct sockaddr *)sa, sizeof(*sa)) < 0) { + close(*tfmfd); + *tfmfd = -1; + return -ENOENT; + } + + if (key && setsockopt(*tfmfd, SOL_ALG, ALG_SET_KEY, key, key_length) < 0) { + close(*tfmfd); + *tfmfd = -1; + return -EINVAL; + } + + *opfd = accept(*tfmfd, NULL, 0); + if (*opfd < 0) { + close(*tfmfd); + *tfmfd = -1; + return -EINVAL; + } + + return 0; +} + +int crypt_backend_init(bool fips __attribute__((unused))) +{ + struct utsname uts; + struct sockaddr_alg sa = { + .salg_family = AF_ALG, + .salg_type = "hash", + .salg_name = "sha256", + }; + int r, tfmfd = -1, opfd = -1; + + if (crypto_backend_initialised) + return 0; + + if (uname(&uts) == -1 || strcmp(uts.sysname, "Linux")) + return -EINVAL; + + r = snprintf(version, sizeof(version), "%s %s kernel cryptoAPI", + uts.sysname, uts.release); + if (r < 0 || (size_t)r >= sizeof(version)) + return -EINVAL; + + if (crypt_kernel_socket_init(&sa, &tfmfd, &opfd, NULL, 0) < 0) + return -EINVAL; + + close(tfmfd); + close(opfd); + + crypto_backend_initialised = 1; + return 0; +} + +void crypt_backend_destroy(void) +{ + crypto_backend_initialised = 0; +} + +uint32_t crypt_backend_flags(void) +{ + return CRYPT_BACKEND_KERNEL; +} + +const char *crypt_backend_version(void) +{ + return crypto_backend_initialised ? version : ""; +} + +static struct hash_alg *_get_alg(const char *name) +{ + int i = 0; + + while (name && hash_algs[i].name) { + if (!strcmp(name, hash_algs[i].name)) + return &hash_algs[i]; + i++; + } + return NULL; +} + +/* HASH */ +int crypt_hash_size(const char *name) +{ + struct hash_alg *ha = _get_alg(name); + + return ha ? ha->length : -EINVAL; +} + +int crypt_hash_init(struct crypt_hash **ctx, const char *name) +{ + struct crypt_hash *h; + struct hash_alg *ha; + struct sockaddr_alg sa = { + .salg_family = AF_ALG, + .salg_type = "hash", + }; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + ha = _get_alg(name); + if (!ha) { + free(h); + return -EINVAL; + } + h->hash_len = ha->length; + + strncpy((char *)sa.salg_name, ha->kernel_name, sizeof(sa.salg_name)-1); + + if (crypt_kernel_socket_init(&sa, &h->tfmfd, &h->opfd, NULL, 0) < 0) { + free(h); + return -EINVAL; + } + + *ctx = h; + return 0; +} + +int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length) +{ + ssize_t r; + + r = send(ctx->opfd, buffer, length, MSG_MORE); + if (r < 0 || (size_t)r < length) + return -EIO; + + return 0; +} + +int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length) +{ + ssize_t r; + + if (length > (size_t)ctx->hash_len) + return -EINVAL; + + r = read(ctx->opfd, buffer, length); + if (r < 0) + return -EIO; + + return 0; +} + +void crypt_hash_destroy(struct crypt_hash *ctx) +{ + if (ctx->tfmfd >= 0) + close(ctx->tfmfd); + if (ctx->opfd >= 0) + close(ctx->opfd); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* HMAC */ +int crypt_hmac_size(const char *name) +{ + return crypt_hash_size(name); +} + +int crypt_hmac_init(struct crypt_hmac **ctx, const char *name, + const void *key, size_t key_length) +{ + struct crypt_hmac *h; + struct hash_alg *ha; + struct sockaddr_alg sa = { + .salg_family = AF_ALG, + .salg_type = "hash", + }; + int r; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + ha = _get_alg(name); + if (!ha) { + free(h); + return -EINVAL; + } + h->hash_len = ha->length; + + r = snprintf((char *)sa.salg_name, sizeof(sa.salg_name), + "hmac(%s)", ha->kernel_name); + if (r < 0 || (size_t)r >= sizeof(sa.salg_name)) { + free(h); + return -EINVAL; + } + + if (crypt_kernel_socket_init(&sa, &h->tfmfd, &h->opfd, key, key_length) < 0) { + free(h); + return -EINVAL; + } + + *ctx = h; + return 0; +} + +int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length) +{ + ssize_t r; + + r = send(ctx->opfd, buffer, length, MSG_MORE); + if (r < 0 || (size_t)r < length) + return -EIO; + + return 0; +} + +int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length) +{ + ssize_t r; + + if (length > (size_t)ctx->hash_len) + return -EINVAL; + + r = read(ctx->opfd, buffer, length); + if (r < 0) + return -EIO; + + return 0; +} + +void crypt_hmac_destroy(struct crypt_hmac *ctx) +{ + if (ctx->tfmfd >= 0) + close(ctx->tfmfd); + if (ctx->opfd >= 0) + close(ctx->opfd); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* RNG - N/A */ +int crypt_backend_rng(char *buffer __attribute__((unused)), size_t length __attribute__((unused)), + int quality __attribute__((unused)), int fips __attribute__((unused))) +{ + return -EINVAL; +} + +/* PBKDF */ +int crypt_pbkdf(const char *kdf, const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel) +{ + struct hash_alg *ha; + + if (!kdf) + return -EINVAL; + + if (!strcmp(kdf, "pbkdf2")) { + ha = _get_alg(hash); + if (!ha) + return -EINVAL; + + return pkcs5_pbkdf2(hash, password, password_length, salt, salt_length, + iterations, key_length, key, ha->block_length); + } else if (!strncmp(kdf, "argon2", 6)) { + return argon2(kdf, password, password_length, salt, salt_length, + key, key_length, iterations, memory, parallel); + } + + return -EINVAL; +} + +/* Block ciphers */ +int crypt_cipher_init(struct crypt_cipher **ctx, const char *name, + const char *mode, const void *key, size_t key_length) +{ + struct crypt_cipher *h; + int r; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + r = crypt_cipher_init_kernel(&h->ck, name, mode, key, key_length); + if (r < 0) { + free(h); + return r; + } + + *ctx = h; + return 0; +} + +void crypt_cipher_destroy(struct crypt_cipher *ctx) +{ + crypt_cipher_destroy_kernel(&ctx->ck); + free(ctx); +} + +int crypt_cipher_encrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return crypt_cipher_encrypt_kernel(&ctx->ck, in, out, length, iv, iv_length); +} + +int crypt_cipher_decrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return crypt_cipher_decrypt_kernel(&ctx->ck, in, out, length, iv, iv_length); +} + +bool crypt_cipher_kernel_only(struct crypt_cipher *ctx __attribute__((unused))) +{ + return true; +} + +int crypt_bitlk_decrypt_key(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length) +{ + return crypt_bitlk_decrypt_key_kernel(key, key_length, in, out, length, + iv, iv_length, tag, tag_length); +} + +int crypt_backend_memeq(const void *m1, const void *m2, size_t n) +{ + return crypt_internal_memeq(m1, m2, n); +} + +bool crypt_fips_mode(void) +{ + return false; +} diff --git a/lib/crypto_backend/crypto_nettle.c b/lib/crypto_backend/crypto_nettle.c new file mode 100644 index 0000000..086e4fc --- /dev/null +++ b/lib/crypto_backend/crypto_nettle.c @@ -0,0 +1,460 @@ +/* + * Nettle crypto backend implementation + * + * Copyright (C) 2011-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2011-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <nettle/sha.h> +#include <nettle/sha3.h> +#include <nettle/hmac.h> +#include <nettle/pbkdf2.h> +#include <nettle/memops.h> +#include "crypto_backend_internal.h" + +#if HAVE_NETTLE_VERSION_H +#include <nettle/version.h> +#define VSTR(s) STR(s) +#define STR(s) #s +static const char *version = "Nettle "VSTR(NETTLE_VERSION_MAJOR)"."VSTR(NETTLE_VERSION_MINOR); +#else +static const char *version = "Nettle"; +#endif + +typedef void (*init_func) (void *); +typedef void (*update_func) (void *, size_t, const uint8_t *); +typedef void (*digest_func) (void *, size_t, uint8_t *); +typedef void (*set_key_func) (void *, size_t, const uint8_t *); + +struct hash_alg { + const char *name; + int length; + init_func init; + update_func update; + digest_func digest; + update_func hmac_update; + digest_func hmac_digest; + set_key_func hmac_set_key; +}; + +/* Missing HMAC wrappers in Nettle */ +#define HMAC_FCE(xxx) \ +struct xhmac_##xxx##_ctx HMAC_CTX(struct xxx##_ctx); \ +static void xhmac_##xxx##_set_key(struct xhmac_##xxx##_ctx *ctx, \ +size_t key_length, const uint8_t *key) \ +{HMAC_SET_KEY(ctx, &nettle_##xxx, key_length, key);} \ +static void xhmac_##xxx##_update(struct xhmac_##xxx##_ctx *ctx, \ +size_t length, const uint8_t *data) \ +{xxx##_update(&ctx->state, length, data);} \ +static void xhmac_##xxx##_digest(struct xhmac_##xxx##_ctx *ctx, \ +size_t length, uint8_t *digest) \ +{HMAC_DIGEST(ctx, &nettle_##xxx, length, digest);} + +HMAC_FCE(sha3_224); +HMAC_FCE(sha3_256); +HMAC_FCE(sha3_384); +HMAC_FCE(sha3_512); + +static struct hash_alg hash_algs[] = { + { "sha1", SHA1_DIGEST_SIZE, + (init_func) sha1_init, + (update_func) sha1_update, + (digest_func) sha1_digest, + (update_func) hmac_sha1_update, + (digest_func) hmac_sha1_digest, + (set_key_func) hmac_sha1_set_key, + }, + { "sha224", SHA224_DIGEST_SIZE, + (init_func) sha224_init, + (update_func) sha224_update, + (digest_func) sha224_digest, + (update_func) hmac_sha224_update, + (digest_func) hmac_sha224_digest, + (set_key_func) hmac_sha224_set_key, + }, + { "sha256", SHA256_DIGEST_SIZE, + (init_func) sha256_init, + (update_func) sha256_update, + (digest_func) sha256_digest, + (update_func) hmac_sha256_update, + (digest_func) hmac_sha256_digest, + (set_key_func) hmac_sha256_set_key, + }, + { "sha384", SHA384_DIGEST_SIZE, + (init_func) sha384_init, + (update_func) sha384_update, + (digest_func) sha384_digest, + (update_func) hmac_sha384_update, + (digest_func) hmac_sha384_digest, + (set_key_func) hmac_sha384_set_key, + }, + { "sha512", SHA512_DIGEST_SIZE, + (init_func) sha512_init, + (update_func) sha512_update, + (digest_func) sha512_digest, + (update_func) hmac_sha512_update, + (digest_func) hmac_sha512_digest, + (set_key_func) hmac_sha512_set_key, + }, + { "ripemd160", RIPEMD160_DIGEST_SIZE, + (init_func) ripemd160_init, + (update_func) ripemd160_update, + (digest_func) ripemd160_digest, + (update_func) hmac_ripemd160_update, + (digest_func) hmac_ripemd160_digest, + (set_key_func) hmac_ripemd160_set_key, + }, +/* Nettle prior to version 3.2 has incompatible SHA3 implementation */ +#if NETTLE_SHA3_FIPS202 + { "sha3-224", SHA3_224_DIGEST_SIZE, + (init_func) sha3_224_init, + (update_func) sha3_224_update, + (digest_func) sha3_224_digest, + (update_func) xhmac_sha3_224_update, + (digest_func) xhmac_sha3_224_digest, + (set_key_func) xhmac_sha3_224_set_key, + }, + { "sha3-256", SHA3_256_DIGEST_SIZE, + (init_func) sha3_256_init, + (update_func) sha3_256_update, + (digest_func) sha3_256_digest, + (update_func) xhmac_sha3_256_update, + (digest_func) xhmac_sha3_256_digest, + (set_key_func) xhmac_sha3_256_set_key, + }, + { "sha3-384", SHA3_384_DIGEST_SIZE, + (init_func) sha3_384_init, + (update_func) sha3_384_update, + (digest_func) sha3_384_digest, + (update_func) xhmac_sha3_384_update, + (digest_func) xhmac_sha3_384_digest, + (set_key_func) xhmac_sha3_384_set_key, + }, + { "sha3-512", SHA3_512_DIGEST_SIZE, + (init_func) sha3_512_init, + (update_func) sha3_512_update, + (digest_func) sha3_512_digest, + (update_func) xhmac_sha3_512_update, + (digest_func) xhmac_sha3_512_digest, + (set_key_func) xhmac_sha3_512_set_key, + }, +#endif + { NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, } +}; + +struct crypt_hash { + const struct hash_alg *hash; + union { + struct sha1_ctx sha1; + struct sha224_ctx sha224; + struct sha256_ctx sha256; + struct sha384_ctx sha384; + struct sha512_ctx sha512; + struct ripemd160_ctx ripemd160; + struct sha3_224_ctx sha3_224; + struct sha3_256_ctx sha3_256; + struct sha3_384_ctx sha3_384; + struct sha3_512_ctx sha3_512; + } nettle_ctx; +}; + +struct crypt_hmac { + const struct hash_alg *hash; + union { + struct hmac_sha1_ctx sha1; + struct hmac_sha224_ctx sha224; + struct hmac_sha256_ctx sha256; + struct hmac_sha384_ctx sha384; + struct hmac_sha512_ctx sha512; + struct hmac_ripemd160_ctx ripemd160; + struct xhmac_sha3_224_ctx sha3_224; + struct xhmac_sha3_256_ctx sha3_256; + struct xhmac_sha3_384_ctx sha3_384; + struct xhmac_sha3_512_ctx sha3_512; + } nettle_ctx; + size_t key_length; + uint8_t *key; +}; + +struct crypt_cipher { + struct crypt_cipher_kernel ck; +}; + +uint32_t crypt_backend_flags(void) +{ + return 0; +} + +static struct hash_alg *_get_alg(const char *name) +{ + int i = 0; + + while (name && hash_algs[i].name) { + if (!strcmp(name, hash_algs[i].name)) + return &hash_algs[i]; + i++; + } + return NULL; +} + +int crypt_backend_init(bool fips __attribute__((unused))) +{ + return 0; +} + +void crypt_backend_destroy(void) +{ + return; +} + +const char *crypt_backend_version(void) +{ + return version; +} + +/* HASH */ +int crypt_hash_size(const char *name) +{ + struct hash_alg *ha = _get_alg(name); + + return ha ? ha->length : -EINVAL; +} + +int crypt_hash_init(struct crypt_hash **ctx, const char *name) +{ + struct crypt_hash *h; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + h->hash = _get_alg(name); + if (!h->hash) { + free(h); + return -EINVAL; + } + + h->hash->init(&h->nettle_ctx); + + *ctx = h; + return 0; +} + +static void crypt_hash_restart(struct crypt_hash *ctx) +{ + ctx->hash->init(&ctx->nettle_ctx); +} + +int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length) +{ + ctx->hash->update(&ctx->nettle_ctx, length, (const uint8_t*)buffer); + return 0; +} + +int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length) +{ + if (length > (size_t)ctx->hash->length) + return -EINVAL; + + ctx->hash->digest(&ctx->nettle_ctx, length, (uint8_t *)buffer); + crypt_hash_restart(ctx); + return 0; +} + +void crypt_hash_destroy(struct crypt_hash *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* HMAC */ +int crypt_hmac_size(const char *name) +{ + return crypt_hash_size(name); +} + +int crypt_hmac_init(struct crypt_hmac **ctx, const char *name, + const void *key, size_t key_length) +{ + struct crypt_hmac *h; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + memset(ctx, 0, sizeof(*ctx)); + + + h->hash = _get_alg(name); + if (!h->hash) { + free(h); + return -EINVAL; + } + + h->key = malloc(key_length); + if (!h->key) { + free(h); + return -ENOMEM; + } + + memcpy(h->key, key, key_length); + h->key_length = key_length; + + h->hash->init(&h->nettle_ctx); + h->hash->hmac_set_key(&h->nettle_ctx, h->key_length, h->key); + + *ctx = h; + return 0; +} + +static void crypt_hmac_restart(struct crypt_hmac *ctx) +{ + ctx->hash->hmac_set_key(&ctx->nettle_ctx, ctx->key_length, ctx->key); +} + +int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length) +{ + ctx->hash->hmac_update(&ctx->nettle_ctx, length, (const uint8_t *)buffer); + return 0; +} + +int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length) +{ + if (length > (size_t)ctx->hash->length) + return -EINVAL; + + ctx->hash->hmac_digest(&ctx->nettle_ctx, length, (uint8_t *)buffer); + crypt_hmac_restart(ctx); + return 0; +} + +void crypt_hmac_destroy(struct crypt_hmac *ctx) +{ + memset(ctx->key, 0, ctx->key_length); + free(ctx->key); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* RNG - N/A */ +int crypt_backend_rng(char *buffer __attribute__((unused)), + size_t length __attribute__((unused)), + int quality __attribute__((unused)), + int fips __attribute__((unused))) +{ + return -EINVAL; +} + +/* PBKDF */ +int crypt_pbkdf(const char *kdf, const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel) +{ + struct crypt_hmac *h; + int r; + + if (!kdf) + return -EINVAL; + + if (!strcmp(kdf, "pbkdf2")) { + r = crypt_hmac_init(&h, hash, password, password_length); + if (r < 0) + return r; + + nettle_pbkdf2(&h->nettle_ctx, h->hash->hmac_update, + h->hash->hmac_digest, h->hash->length, iterations, + salt_length, (const uint8_t *)salt, key_length, + (uint8_t *)key); + crypt_hmac_destroy(h); + return 0; + } else if (!strncmp(kdf, "argon2", 6)) { + return argon2(kdf, password, password_length, salt, salt_length, + key, key_length, iterations, memory, parallel); + } + + return -EINVAL; +} + +/* Block ciphers */ +int crypt_cipher_init(struct crypt_cipher **ctx, const char *name, + const char *mode, const void *key, size_t key_length) +{ + struct crypt_cipher *h; + int r; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + r = crypt_cipher_init_kernel(&h->ck, name, mode, key, key_length); + if (r < 0) { + free(h); + return r; + } + + *ctx = h; + return 0; +} + +void crypt_cipher_destroy(struct crypt_cipher *ctx) +{ + crypt_cipher_destroy_kernel(&ctx->ck); + free(ctx); +} + +int crypt_cipher_encrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return crypt_cipher_encrypt_kernel(&ctx->ck, in, out, length, iv, iv_length); +} + +int crypt_cipher_decrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return crypt_cipher_decrypt_kernel(&ctx->ck, in, out, length, iv, iv_length); +} + +bool crypt_cipher_kernel_only(struct crypt_cipher *ctx __attribute__((unused))) +{ + return true; +} + +int crypt_bitlk_decrypt_key(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length) +{ + return crypt_bitlk_decrypt_key_kernel(key, key_length, in, out, length, + iv, iv_length, tag, tag_length); +} + +int crypt_backend_memeq(const void *m1, const void *m2, size_t n) +{ + /* The logic is inverse to memcmp... */ + return !memeql_sec(m1, m2, n); +} + +bool crypt_fips_mode(void) +{ + return false; +} diff --git a/lib/crypto_backend/crypto_nss.c b/lib/crypto_backend/crypto_nss.c new file mode 100644 index 0000000..c154812 --- /dev/null +++ b/lib/crypto_backend/crypto_nss.c @@ -0,0 +1,407 @@ +/* + * NSS crypto backend implementation + * + * Copyright (C) 2010-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2010-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <string.h> +#include <errno.h> +#include <nss.h> +#include <pk11pub.h> +#include "crypto_backend_internal.h" + +#define CONST_CAST(x) (x)(uintptr_t) + +static int crypto_backend_initialised = 0; +static char version[64]; + +struct hash_alg { + const char *name; + SECOidTag oid; + CK_MECHANISM_TYPE ck_type; + int length; + unsigned int block_length; +}; + +static struct hash_alg hash_algs[] = { + { "sha1", SEC_OID_SHA1, CKM_SHA_1_HMAC, 20, 64 }, + { "sha256", SEC_OID_SHA256, CKM_SHA256_HMAC, 32, 64 }, + { "sha384", SEC_OID_SHA384, CKM_SHA384_HMAC, 48, 128 }, + { "sha512", SEC_OID_SHA512, CKM_SHA512_HMAC, 64, 128 }, +// { "ripemd160", SEC_OID_RIPEMD160, CKM_RIPEMD160_HMAC, 20, 64 }, + { NULL, 0, 0, 0 } +}; + +struct crypt_hash { + PK11Context *md; + const struct hash_alg *hash; +}; + +struct crypt_hmac { + PK11Context *md; + PK11SymKey *key; + PK11SlotInfo *slot; + const struct hash_alg *hash; +}; + +struct crypt_cipher { + struct crypt_cipher_kernel ck; +}; + +static struct hash_alg *_get_alg(const char *name) +{ + int i = 0; + + while (name && hash_algs[i].name) { + if (!strcmp(name, hash_algs[i].name)) + return &hash_algs[i]; + i++; + } + return NULL; +} + +int crypt_backend_init(bool fips __attribute__((unused))) +{ + int r; + + if (crypto_backend_initialised) + return 0; + + if (NSS_NoDB_Init(".") != SECSuccess) + return -EINVAL; + +#if HAVE_DECL_NSS_GETVERSION + r = snprintf(version, sizeof(version), "NSS %s", NSS_GetVersion()); +#else + r = snprintf(version, sizeof(version), "NSS"); +#endif + if (r < 0 || (size_t)r >= sizeof(version)) + return -EINVAL; + + crypto_backend_initialised = 1; + return 0; +} + +void crypt_backend_destroy(void) +{ + crypto_backend_initialised = 0; +} + +uint32_t crypt_backend_flags(void) +{ + return 0; +} + +const char *crypt_backend_version(void) +{ + return crypto_backend_initialised ? version : ""; +} + +/* HASH */ +int crypt_hash_size(const char *name) +{ + struct hash_alg *ha = _get_alg(name); + + return ha ? ha->length : -EINVAL; +} + +int crypt_hash_init(struct crypt_hash **ctx, const char *name) +{ + struct crypt_hash *h; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + h->hash = _get_alg(name); + if (!h->hash) { + free(h); + return -EINVAL; + } + + h->md = PK11_CreateDigestContext(h->hash->oid); + if (!h->md) { + free(h); + return -EINVAL; + } + + if (PK11_DigestBegin(h->md) != SECSuccess) { + PK11_DestroyContext(h->md, PR_TRUE); + free(h); + return -EINVAL; + } + + *ctx = h; + return 0; +} + +static int crypt_hash_restart(struct crypt_hash *ctx) +{ + if (PK11_DigestBegin(ctx->md) != SECSuccess) + return -EINVAL; + + return 0; +} + +int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length) +{ + if (PK11_DigestOp(ctx->md, CONST_CAST(unsigned char *)buffer, length) != SECSuccess) + return -EINVAL; + + return 0; +} + +int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length) +{ + unsigned char tmp[64]; + unsigned int tmp_len; + + if (length > (size_t)ctx->hash->length) + return -EINVAL; + + if (PK11_DigestFinal(ctx->md, tmp, &tmp_len, length) != SECSuccess) + return -EINVAL; + + memcpy(buffer, tmp, length); + crypt_backend_memzero(tmp, sizeof(tmp)); + + if (tmp_len < length) + return -EINVAL; + + if (crypt_hash_restart(ctx)) + return -EINVAL; + + return 0; +} + +void crypt_hash_destroy(struct crypt_hash *ctx) +{ + PK11_DestroyContext(ctx->md, PR_TRUE); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* HMAC */ +int crypt_hmac_size(const char *name) +{ + return crypt_hash_size(name); +} + +int crypt_hmac_init(struct crypt_hmac **ctx, const char *name, + const void *key, size_t key_length) +{ + struct crypt_hmac *h; + SECItem keyItem; + SECItem noParams; + + keyItem.type = siBuffer; + keyItem.data = CONST_CAST(unsigned char *)key; + keyItem.len = (int)key_length; + + noParams.type = siBuffer; + noParams.data = 0; + noParams.len = 0; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + memset(ctx, 0, sizeof(*ctx)); + + + h->hash = _get_alg(name); + if (!h->hash) + goto err; + + h->slot = PK11_GetInternalKeySlot(); + if (!h->slot) + goto err; + + h->key = PK11_ImportSymKey(h->slot, h->hash->ck_type, PK11_OriginUnwrap, + CKA_SIGN, &keyItem, NULL); + if (!h->key) + goto err; + + h->md = PK11_CreateContextBySymKey(h->hash->ck_type, CKA_SIGN, h->key, + &noParams); + if (!h->md) + goto err; + + if (PK11_DigestBegin(h->md) != SECSuccess) + goto err; + + *ctx = h; + return 0; +err: + crypt_hmac_destroy(h); + return -EINVAL; +} + +static int crypt_hmac_restart(struct crypt_hmac *ctx) +{ + if (PK11_DigestBegin(ctx->md) != SECSuccess) + return -EINVAL; + + return 0; +} + +int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length) +{ + if (PK11_DigestOp(ctx->md, CONST_CAST(unsigned char *)buffer, length) != SECSuccess) + return -EINVAL; + + return 0; +} + +int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length) +{ + unsigned char tmp[64]; + unsigned int tmp_len; + + if (length > (size_t)ctx->hash->length) + return -EINVAL; + + if (PK11_DigestFinal(ctx->md, tmp, &tmp_len, length) != SECSuccess) + return -EINVAL; + + memcpy(buffer, tmp, length); + crypt_backend_memzero(tmp, sizeof(tmp)); + + if (tmp_len < length) + return -EINVAL; + + if (crypt_hmac_restart(ctx)) + return -EINVAL; + + return 0; +} + +void crypt_hmac_destroy(struct crypt_hmac *ctx) +{ + if (ctx->key) + PK11_FreeSymKey(ctx->key); + if (ctx->slot) + PK11_FreeSlot(ctx->slot); + if (ctx->md) + PK11_DestroyContext(ctx->md, PR_TRUE); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* RNG */ +int crypt_backend_rng(char *buffer, size_t length, int quality __attribute__((unused)), int fips) +{ + if (fips) + return -EINVAL; + + if (PK11_GenerateRandom((unsigned char *)buffer, length) != SECSuccess) + return -EINVAL; + + return 0; +} + +/* PBKDF */ +int crypt_pbkdf(const char *kdf, const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel) +{ + struct hash_alg *ha; + + if (!kdf) + return -EINVAL; + + if (!strcmp(kdf, "pbkdf2")) { + ha = _get_alg(hash); + if (!ha) + return -EINVAL; + + return pkcs5_pbkdf2(hash, password, password_length, salt, salt_length, + iterations, key_length, key, ha->block_length); + } else if (!strncmp(kdf, "argon2", 6)) { + return argon2(kdf, password, password_length, salt, salt_length, + key, key_length, iterations, memory, parallel); + } + + return -EINVAL; +} + +/* Block ciphers */ +int crypt_cipher_init(struct crypt_cipher **ctx, const char *name, + const char *mode, const void *key, size_t key_length) +{ + struct crypt_cipher *h; + int r; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + r = crypt_cipher_init_kernel(&h->ck, name, mode, key, key_length); + if (r < 0) { + free(h); + return r; + } + + *ctx = h; + return 0; +} + +void crypt_cipher_destroy(struct crypt_cipher *ctx) +{ + crypt_cipher_destroy_kernel(&ctx->ck); + free(ctx); +} + +int crypt_cipher_encrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return crypt_cipher_encrypt_kernel(&ctx->ck, in, out, length, iv, iv_length); +} + +int crypt_cipher_decrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + return crypt_cipher_decrypt_kernel(&ctx->ck, in, out, length, iv, iv_length); +} + +bool crypt_cipher_kernel_only(struct crypt_cipher *ctx __attribute__((unused))) +{ + return true; +} + +int crypt_bitlk_decrypt_key(const void *key, size_t key_length, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length) +{ + return crypt_bitlk_decrypt_key_kernel(key, key_length, in, out, length, + iv, iv_length, tag, tag_length); +} + +int crypt_backend_memeq(const void *m1, const void *m2, size_t n) +{ + return NSS_SecureMemcmp(m1, m2, n); +} + +bool crypt_fips_mode(void) +{ + return false; +} diff --git a/lib/crypto_backend/crypto_openssl.c b/lib/crypto_backend/crypto_openssl.c new file mode 100644 index 0000000..607ec38 --- /dev/null +++ b/lib/crypto_backend/crypto_openssl.c @@ -0,0 +1,849 @@ +/* + * OPENSSL crypto backend implementation + * + * Copyright (C) 2010-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2010-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * + * You must obey the GNU Lesser General Public License in all respects + * for all of the code used other than OpenSSL. + */ + +#include <string.h> +#include <errno.h> +#include <limits.h> +#include <openssl/crypto.h> +#include <openssl/evp.h> +#include <openssl/hmac.h> +#include <openssl/rand.h> +#include "crypto_backend_internal.h" +#if OPENSSL_VERSION_MAJOR >= 3 +#include <openssl/provider.h> +#include <openssl/kdf.h> +#include <openssl/core_names.h> +static OSSL_PROVIDER *ossl_legacy = NULL; +static OSSL_PROVIDER *ossl_default = NULL; +static OSSL_LIB_CTX *ossl_ctx = NULL; +static char backend_version[256] = "OpenSSL"; +#endif + +#define CONST_CAST(x) (x)(uintptr_t) + +static int crypto_backend_initialised = 0; + +struct crypt_hash { + EVP_MD_CTX *md; + const EVP_MD *hash_id; + int hash_len; +}; + +struct crypt_hmac { +#if OPENSSL_VERSION_MAJOR >= 3 + EVP_MAC *mac; + EVP_MAC_CTX *md; + EVP_MAC_CTX *md_org; +#else + HMAC_CTX *md; + const EVP_MD *hash_id; +#endif + int hash_len; +}; + +struct crypt_cipher { + bool use_kernel; + union { + struct crypt_cipher_kernel kernel; + struct { + EVP_CIPHER_CTX *hd_enc; + EVP_CIPHER_CTX *hd_dec; + const EVP_CIPHER *cipher_type; + size_t iv_length; + } lib; + } u; +}; + +struct hash_alg { + const char *name; + const char *openssl_name; +}; + +/* + * Compatible wrappers for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 + */ +#if OPENSSL_VERSION_NUMBER < 0x10100000L || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + +static int openssl_backend_init(bool fips __attribute__((unused))) +{ + OpenSSL_add_all_algorithms(); + return 0; +} + +static void openssl_backend_exit(void) +{ +} + +static const char *openssl_backend_version(void) +{ + return SSLeay_version(SSLEAY_VERSION); +} + +static EVP_MD_CTX *EVP_MD_CTX_new(void) +{ + EVP_MD_CTX *md = malloc(sizeof(*md)); + + if (md) + EVP_MD_CTX_init(md); + + return md; +} + +static void EVP_MD_CTX_free(EVP_MD_CTX *md) +{ + EVP_MD_CTX_cleanup(md); + free(md); +} + +static HMAC_CTX *HMAC_CTX_new(void) +{ + HMAC_CTX *md = malloc(sizeof(*md)); + + if (md) + HMAC_CTX_init(md); + + return md; +} + +static void HMAC_CTX_free(HMAC_CTX *md) +{ + HMAC_CTX_cleanup(md); + free(md); +} +#else +static void openssl_backend_exit(void) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + if (ossl_legacy) + OSSL_PROVIDER_unload(ossl_legacy); + if (ossl_default) + OSSL_PROVIDER_unload(ossl_default); + if (ossl_ctx) + OSSL_LIB_CTX_free(ossl_ctx); + + ossl_legacy = NULL; + ossl_default = NULL; + ossl_ctx = NULL; +#endif +} + +static int openssl_backend_init(bool fips) +{ +/* + * OpenSSL >= 3.0.0 provides some algorithms in legacy provider + */ +#if OPENSSL_VERSION_MAJOR >= 3 + int r; + + /* + * In FIPS mode we keep default OpenSSL context & global config + */ + if (!fips) { + ossl_ctx = OSSL_LIB_CTX_new(); + if (!ossl_ctx) + return -EINVAL; + + ossl_default = OSSL_PROVIDER_try_load(ossl_ctx, "default", 0); + if (!ossl_default) { + OSSL_LIB_CTX_free(ossl_ctx); + return -EINVAL; + } + + /* Optional */ + ossl_legacy = OSSL_PROVIDER_try_load(ossl_ctx, "legacy", 0); + } + + r = snprintf(backend_version, sizeof(backend_version), "%s %s%s%s", + OpenSSL_version(OPENSSL_VERSION), + ossl_default ? "[default]" : "", + ossl_legacy ? "[legacy]" : "", + fips ? "[fips]" : ""); + + if (r < 0 || (size_t)r >= sizeof(backend_version)) { + openssl_backend_exit(); + return -EINVAL; + } +#endif + return 0; +} + +static const char *openssl_backend_version(void) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + return backend_version; +#else + return OpenSSL_version(OPENSSL_VERSION); +#endif +} +#endif + +int crypt_backend_init(bool fips) +{ + if (crypto_backend_initialised) + return 0; + + if (openssl_backend_init(fips)) + return -EINVAL; + + crypto_backend_initialised = 1; + return 0; +} + +void crypt_backend_destroy(void) +{ + /* + * If Destructor was already called, we must not call it again + */ + if (!crypto_backend_initialised) + return; + + crypto_backend_initialised = 0; + + openssl_backend_exit(); +} + +uint32_t crypt_backend_flags(void) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + return 0; +#else + return CRYPT_BACKEND_PBKDF2_INT; +#endif +} + +const char *crypt_backend_version(void) +{ + return openssl_backend_version(); +} + +static const char *crypt_hash_compat_name(const char *name) +{ + const char *hash_name = name; + int i; + static struct hash_alg hash_algs[] = { + { "blake2b-512", "blake2b512" }, + { "blake2s-256", "blake2s256" }, + { NULL, NULL, }}; + + if (!name) + return NULL; + + i = 0; + while (hash_algs[i].name) { + if (!strcasecmp(name, hash_algs[i].name)) { + hash_name = hash_algs[i].openssl_name; + break; + } + i++; + } + + return hash_name; +} + +static const EVP_MD *hash_id_get(const char *name) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + return EVP_MD_fetch(ossl_ctx, crypt_hash_compat_name(name), NULL); +#else + return EVP_get_digestbyname(crypt_hash_compat_name(name)); +#endif +} + +static void hash_id_free(const EVP_MD *hash_id) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + EVP_MD_free(CONST_CAST(EVP_MD*)hash_id); +#endif +} + +static const EVP_CIPHER *cipher_type_get(const char *name) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + return EVP_CIPHER_fetch(ossl_ctx, name, NULL); +#else + return EVP_get_cipherbyname(name); +#endif +} + +static void cipher_type_free(const EVP_CIPHER *cipher_type) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + EVP_CIPHER_free(CONST_CAST(EVP_CIPHER*)cipher_type); +#endif +} + +/* HASH */ +int crypt_hash_size(const char *name) +{ + int size; + const EVP_MD *hash_id; + + hash_id = hash_id_get(name); + if (!hash_id) + return -EINVAL; + + size = EVP_MD_size(hash_id); + hash_id_free(hash_id); + return size; +} + +int crypt_hash_init(struct crypt_hash **ctx, const char *name) +{ + struct crypt_hash *h; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + h->md = EVP_MD_CTX_new(); + if (!h->md) { + free(h); + return -ENOMEM; + } + + h->hash_id = hash_id_get(name); + if (!h->hash_id) { + EVP_MD_CTX_free(h->md); + free(h); + return -EINVAL; + } + + if (EVP_DigestInit_ex(h->md, h->hash_id, NULL) != 1) { + hash_id_free(h->hash_id); + EVP_MD_CTX_free(h->md); + free(h); + return -EINVAL; + } + + h->hash_len = EVP_MD_size(h->hash_id); + *ctx = h; + return 0; +} + +static int crypt_hash_restart(struct crypt_hash *ctx) +{ + if (EVP_DigestInit_ex(ctx->md, ctx->hash_id, NULL) != 1) + return -EINVAL; + + return 0; +} + +int crypt_hash_write(struct crypt_hash *ctx, const char *buffer, size_t length) +{ + if (EVP_DigestUpdate(ctx->md, buffer, length) != 1) + return -EINVAL; + + return 0; +} + +int crypt_hash_final(struct crypt_hash *ctx, char *buffer, size_t length) +{ + unsigned char tmp[EVP_MAX_MD_SIZE]; + unsigned int tmp_len = 0; + + if (length > (size_t)ctx->hash_len) + return -EINVAL; + + if (EVP_DigestFinal_ex(ctx->md, tmp, &tmp_len) != 1) + return -EINVAL; + + memcpy(buffer, tmp, length); + crypt_backend_memzero(tmp, sizeof(tmp)); + + if (tmp_len < length) + return -EINVAL; + + if (crypt_hash_restart(ctx)) + return -EINVAL; + + return 0; +} + +void crypt_hash_destroy(struct crypt_hash *ctx) +{ + hash_id_free(ctx->hash_id); + EVP_MD_CTX_free(ctx->md); + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* HMAC */ +int crypt_hmac_size(const char *name) +{ + return crypt_hash_size(name); +} + +int crypt_hmac_init(struct crypt_hmac **ctx, const char *name, + const void *key, size_t key_length) +{ + struct crypt_hmac *h; +#if OPENSSL_VERSION_MAJOR >= 3 + OSSL_PARAM params[] = { + OSSL_PARAM_utf8_string(OSSL_MAC_PARAM_DIGEST, CONST_CAST(void*)name, 0), + OSSL_PARAM_END + }; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + h->mac = EVP_MAC_fetch(ossl_ctx, OSSL_MAC_NAME_HMAC, NULL); + if (!h->mac) { + free(h); + return -EINVAL; + } + + h->md = EVP_MAC_CTX_new(h->mac); + if (!h->md) { + EVP_MAC_free(h->mac); + free(h); + return -ENOMEM; + } + + if (EVP_MAC_init(h->md, key, key_length, params) != 1) { + EVP_MAC_CTX_free(h->md); + EVP_MAC_free(h->mac); + free(h); + return -EINVAL; + } + + h->hash_len = EVP_MAC_CTX_get_mac_size(h->md); + h->md_org = EVP_MAC_CTX_dup(h->md); +#else + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + h->md = HMAC_CTX_new(); + if (!h->md) { + free(h); + return -ENOMEM; + } + + h->hash_id = hash_id_get(name); + if (!h->hash_id) { + HMAC_CTX_free(h->md); + free(h); + return -EINVAL; + } + + HMAC_Init_ex(h->md, key, key_length, h->hash_id, NULL); + + h->hash_len = EVP_MD_size(h->hash_id); +#endif + *ctx = h; + return 0; +} + +static int crypt_hmac_restart(struct crypt_hmac *ctx) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + EVP_MAC_CTX_free(ctx->md); + ctx->md = EVP_MAC_CTX_dup(ctx->md_org); + if (!ctx->md) + return -EINVAL; +#else + HMAC_Init_ex(ctx->md, NULL, 0, ctx->hash_id, NULL); +#endif + return 0; +} + +int crypt_hmac_write(struct crypt_hmac *ctx, const char *buffer, size_t length) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + return EVP_MAC_update(ctx->md, (const unsigned char *)buffer, length) == 1 ? 0 : -EINVAL; +#else + HMAC_Update(ctx->md, (const unsigned char *)buffer, length); + return 0; +#endif +} + +int crypt_hmac_final(struct crypt_hmac *ctx, char *buffer, size_t length) +{ + unsigned char tmp[EVP_MAX_MD_SIZE]; +#if OPENSSL_VERSION_MAJOR >= 3 + size_t tmp_len = 0; + + if (length > (size_t)ctx->hash_len) + return -EINVAL; + + if (EVP_MAC_final(ctx->md, tmp, &tmp_len, sizeof(tmp)) != 1) + return -EINVAL; +#else + unsigned int tmp_len = 0; + + if (length > (size_t)ctx->hash_len) + return -EINVAL; + + HMAC_Final(ctx->md, tmp, &tmp_len); +#endif + memcpy(buffer, tmp, length); + crypt_backend_memzero(tmp, sizeof(tmp)); + + if (tmp_len < length) + return -EINVAL; + + if (crypt_hmac_restart(ctx)) + return -EINVAL; + + return 0; +} + +void crypt_hmac_destroy(struct crypt_hmac *ctx) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + EVP_MAC_CTX_free(ctx->md); + EVP_MAC_CTX_free(ctx->md_org); + EVP_MAC_free(ctx->mac); +#else + hash_id_free(ctx->hash_id); + HMAC_CTX_free(ctx->md); +#endif + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +/* RNG */ +int crypt_backend_rng(char *buffer, size_t length, + int quality __attribute__((unused)), int fips __attribute__((unused))) +{ + if (RAND_bytes((unsigned char *)buffer, length) != 1) + return -EINVAL; + + return 0; +} + +static int openssl_pbkdf2(const char *password, size_t password_length, + const char *salt, size_t salt_length, uint32_t iterations, + const char *hash, char *key, size_t key_length) +{ + int r; +#if OPENSSL_VERSION_MAJOR >= 3 + EVP_KDF_CTX *ctx; + EVP_KDF *pbkdf2; + OSSL_PARAM params[] = { + OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, + CONST_CAST(void*)password, password_length), + OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, + CONST_CAST(void*)salt, salt_length), + OSSL_PARAM_uint32(OSSL_KDF_PARAM_ITER, &iterations), + OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, + CONST_CAST(void*)hash, 0), + OSSL_PARAM_END + }; + + pbkdf2 = EVP_KDF_fetch(ossl_ctx, "pbkdf2", NULL); + if (!pbkdf2) + return -EINVAL; + + ctx = EVP_KDF_CTX_new(pbkdf2); + if (!ctx) { + EVP_KDF_free(pbkdf2); + return -EINVAL; + } + + r = EVP_KDF_derive(ctx, (unsigned char*)key, key_length, params); + + EVP_KDF_CTX_free(ctx); + EVP_KDF_free(pbkdf2); +#else + const EVP_MD *hash_id = EVP_get_digestbyname(crypt_hash_compat_name(hash)); + if (!hash_id) + return -EINVAL; + + /* OpenSSL2 has iteration as signed int, avoid overflow */ + if (iterations > INT_MAX) + return -EINVAL; + + r = PKCS5_PBKDF2_HMAC(password, (int)password_length, (const unsigned char *)salt, + (int)salt_length, iterations, hash_id, (int)key_length, (unsigned char*) key); +#endif + return r == 1 ? 0 : -EINVAL; +} + +static int openssl_argon2(const char *type, const char *password, size_t password_length, + const char *salt, size_t salt_length, char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel) +{ + return argon2(type, password, password_length, salt, salt_length, + key, key_length, iterations, memory, parallel); +} + +/* PBKDF */ +int crypt_pbkdf(const char *kdf, const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t iterations, uint32_t memory, uint32_t parallel) +{ + if (!kdf) + return -EINVAL; + + if (!strcmp(kdf, "pbkdf2")) + return openssl_pbkdf2(password, password_length, salt, salt_length, + iterations, hash, key, key_length); + if (!strncmp(kdf, "argon2", 6)) + return openssl_argon2(kdf, password, password_length, salt, salt_length, + key, key_length, iterations, memory, parallel); + return -EINVAL; +} + +/* Block ciphers */ +static void _cipher_destroy(EVP_CIPHER_CTX **hd_enc, EVP_CIPHER_CTX **hd_dec, const EVP_CIPHER **cipher_type) +{ + EVP_CIPHER_CTX_free(*hd_enc); + *hd_enc = NULL; + + EVP_CIPHER_CTX_free(*hd_dec); + *hd_dec = NULL; + + cipher_type_free(*cipher_type); + *cipher_type = NULL; +} + +static int _cipher_init(EVP_CIPHER_CTX **hd_enc, EVP_CIPHER_CTX **hd_dec, const EVP_CIPHER **cipher_type, const char *name, + const char *mode, const void *key, size_t key_length, size_t *iv_length) +{ + char cipher_name[256]; + const EVP_CIPHER *type; + int r, key_bits; + + key_bits = key_length * 8; + if (!strcmp(mode, "xts")) + key_bits /= 2; + + r = snprintf(cipher_name, sizeof(cipher_name), "%s-%d-%s", name, key_bits, mode); + if (r < 0 || (size_t)r >= sizeof(cipher_name)) + return -EINVAL; + + type = cipher_type_get(cipher_name); + if (!type) + return -ENOENT; + + if (EVP_CIPHER_key_length(type) != (int)key_length) { + cipher_type_free(type); + return -EINVAL; + } + + *hd_enc = EVP_CIPHER_CTX_new(); + *hd_dec = EVP_CIPHER_CTX_new(); + *iv_length = EVP_CIPHER_iv_length(type); + + if (!*hd_enc || !*hd_dec) { + cipher_type_free(type); + return -EINVAL; + } + + if (EVP_EncryptInit_ex(*hd_enc, type, NULL, key, NULL) != 1 || + EVP_DecryptInit_ex(*hd_dec, type, NULL, key, NULL) != 1) { + _cipher_destroy(hd_enc, hd_dec, &type); + return -EINVAL; + } + + if (EVP_CIPHER_CTX_set_padding(*hd_enc, 0) != 1 || + EVP_CIPHER_CTX_set_padding(*hd_dec, 0) != 1) { + _cipher_destroy(hd_enc, hd_dec, &type); + return -EINVAL; + } + + *cipher_type = type; + + return 0; +} + +int crypt_cipher_init(struct crypt_cipher **ctx, const char *name, + const char *mode, const void *key, size_t key_length) +{ + struct crypt_cipher *h; + int r; + + h = malloc(sizeof(*h)); + if (!h) + return -ENOMEM; + + if (!_cipher_init(&h->u.lib.hd_enc, &h->u.lib.hd_dec, &h->u.lib.cipher_type, name, mode, key, + key_length, &h->u.lib.iv_length)) { + h->use_kernel = false; + *ctx = h; + return 0; + } + + r = crypt_cipher_init_kernel(&h->u.kernel, name, mode, key, key_length); + if (r < 0) { + free(h); + return r; + } + + h->use_kernel = true; + *ctx = h; + return 0; +} + +void crypt_cipher_destroy(struct crypt_cipher *ctx) +{ + if (ctx->use_kernel) + crypt_cipher_destroy_kernel(&ctx->u.kernel); + else + _cipher_destroy(&ctx->u.lib.hd_enc, &ctx->u.lib.hd_dec, &ctx->u.lib.cipher_type); + free(ctx); +} + +static int _cipher_encrypt(struct crypt_cipher *ctx, const unsigned char *in, unsigned char *out, + int length, const unsigned char *iv, size_t iv_length) +{ + int len; + + if (ctx->u.lib.iv_length != iv_length) + return -EINVAL; + + if (EVP_EncryptInit_ex(ctx->u.lib.hd_enc, NULL, NULL, NULL, iv) != 1) + return -EINVAL; + + if (EVP_EncryptUpdate(ctx->u.lib.hd_enc, out, &len, in, length) != 1) + return -EINVAL; + + if (EVP_EncryptFinal(ctx->u.lib.hd_enc, out + len, &len) != 1) + return -EINVAL; + + return 0; +} + +static int _cipher_decrypt(struct crypt_cipher *ctx, const unsigned char *in, unsigned char *out, + int length, const unsigned char *iv, size_t iv_length) +{ + int len; + + if (ctx->u.lib.iv_length != iv_length) + return -EINVAL; + + if (EVP_DecryptInit_ex(ctx->u.lib.hd_dec, NULL, NULL, NULL, iv) != 1) + return -EINVAL; + + if (EVP_DecryptUpdate(ctx->u.lib.hd_dec, out, &len, in, length) != 1) + return -EINVAL; + + if (EVP_DecryptFinal(ctx->u.lib.hd_dec, out + len, &len) != 1) + return -EINVAL; + + return 0; +} + +int crypt_cipher_encrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + if (ctx->use_kernel) + return crypt_cipher_encrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length); + + return _cipher_encrypt(ctx, (const unsigned char*)in, + (unsigned char *)out, length, (const unsigned char*)iv, iv_length); +} + +int crypt_cipher_decrypt(struct crypt_cipher *ctx, + const char *in, char *out, size_t length, + const char *iv, size_t iv_length) +{ + if (ctx->use_kernel) + return crypt_cipher_decrypt_kernel(&ctx->u.kernel, in, out, length, iv, iv_length); + + return _cipher_decrypt(ctx, (const unsigned char*)in, + (unsigned char *)out, length, (const unsigned char*)iv, iv_length); +} + +bool crypt_cipher_kernel_only(struct crypt_cipher *ctx) +{ + return ctx->use_kernel; +} + +int crypt_bitlk_decrypt_key(const void *key, size_t key_length __attribute__((unused)), + const char *in, char *out, size_t length, + const char *iv, size_t iv_length, + const char *tag, size_t tag_length) +{ +#ifdef EVP_CTRL_CCM_SET_IVLEN + EVP_CIPHER_CTX *ctx; + int len = 0, r = -EINVAL; + + ctx = EVP_CIPHER_CTX_new(); + if (!ctx) + return -EINVAL; + + if (EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), NULL, NULL, NULL) != 1) + goto out; + + if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, iv_length, NULL) != 1) + goto out; + if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, tag_length, CONST_CAST(void*)tag) != 1) + goto out; + + if (EVP_DecryptInit_ex(ctx, NULL, NULL, key, (const unsigned char*)iv) != 1) + goto out; + + if (EVP_DecryptUpdate(ctx, (unsigned char*)out, &len, (const unsigned char*)in, length) == 1) + r = 0; +out: + EVP_CIPHER_CTX_free(ctx); + return r; +#else + return -ENOTSUP; +#endif +} + +int crypt_backend_memeq(const void *m1, const void *m2, size_t n) +{ + return CRYPTO_memcmp(m1, m2, n); +} + +#if !ENABLE_FIPS +bool crypt_fips_mode(void) { return false; } +#else +static bool openssl_fips_mode(void) +{ +#if OPENSSL_VERSION_MAJOR >= 3 + return EVP_default_properties_is_fips_enabled(NULL); +#else + return FIPS_mode(); +#endif +} + +bool crypt_fips_mode(void) +{ + static bool fips_mode = false, fips_checked = false; + + if (fips_checked) + return fips_mode; + + fips_mode = openssl_fips_mode(); + fips_checked = true; + + return fips_mode; +} +#endif /* ENABLE FIPS */ diff --git a/lib/crypto_backend/crypto_storage.c b/lib/crypto_backend/crypto_storage.c new file mode 100644 index 0000000..13479dd --- /dev/null +++ b/lib/crypto_backend/crypto_storage.c @@ -0,0 +1,347 @@ +/* + * Generic wrapper for storage encryption modes and Initial Vectors + * (reimplementation of some functions from Linux dm-crypt kernel) + * + * Copyright (C) 2014-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <stdlib.h> +#include <errno.h> +#include <strings.h> +#include "bitops.h" +#include "crypto_backend.h" + +#define SECTOR_SHIFT 9 + +/* + * Internal IV helper + * IV documentation: https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt + */ +struct crypt_sector_iv { + enum { IV_NONE, IV_NULL, IV_PLAIN, IV_PLAIN64, IV_ESSIV, IV_BENBI, IV_PLAIN64BE, IV_EBOIV } type; + int iv_size; + char *iv; + struct crypt_cipher *cipher; + int shift; +}; + +/* Block encryption storage context */ +struct crypt_storage { + size_t sector_size; + unsigned iv_shift; + struct crypt_cipher *cipher; + struct crypt_sector_iv cipher_iv; +}; + +static int int_log2(unsigned int x) +{ + int r = 0; + for (x >>= 1; x > 0; x >>= 1) + r++; + return r; +} + +static int crypt_sector_iv_init(struct crypt_sector_iv *ctx, + const char *cipher_name, const char *mode_name, + const char *iv_name, const void *key, size_t key_length, + size_t sector_size) +{ + int r; + + memset(ctx, 0, sizeof(*ctx)); + + ctx->iv_size = crypt_cipher_ivsize(cipher_name, mode_name); + if (ctx->iv_size < 0 || (strcmp(mode_name, "ecb") && ctx->iv_size < 8)) + return -ENOENT; + + if (!strcmp(cipher_name, "cipher_null") || + !strcmp(mode_name, "ecb")) { + if (iv_name) + return -EINVAL; + ctx->type = IV_NONE; + ctx->iv_size = 0; + return 0; + } else if (!iv_name) { + return -EINVAL; + } else if (!strcasecmp(iv_name, "null")) { + ctx->type = IV_NULL; + } else if (!strcasecmp(iv_name, "plain64")) { + ctx->type = IV_PLAIN64; + } else if (!strcasecmp(iv_name, "plain64be")) { + ctx->type = IV_PLAIN64BE; + } else if (!strcasecmp(iv_name, "plain")) { + ctx->type = IV_PLAIN; + } else if (!strncasecmp(iv_name, "essiv:", 6)) { + struct crypt_hash *h = NULL; + char *hash_name = strchr(iv_name, ':'); + int hash_size; + char tmp[256]; + + if (!hash_name) + return -EINVAL; + + hash_size = crypt_hash_size(++hash_name); + if (hash_size < 0) + return -ENOENT; + + if ((unsigned)hash_size > sizeof(tmp)) + return -EINVAL; + + if (crypt_hash_init(&h, hash_name)) + return -EINVAL; + + r = crypt_hash_write(h, key, key_length); + if (r) { + crypt_hash_destroy(h); + return r; + } + + r = crypt_hash_final(h, tmp, hash_size); + crypt_hash_destroy(h); + if (r) { + crypt_backend_memzero(tmp, sizeof(tmp)); + return r; + } + + r = crypt_cipher_init(&ctx->cipher, cipher_name, "ecb", + tmp, hash_size); + crypt_backend_memzero(tmp, sizeof(tmp)); + if (r) + return r; + + ctx->type = IV_ESSIV; + } else if (!strncasecmp(iv_name, "benbi", 5)) { + int log = int_log2(ctx->iv_size); + if (log > SECTOR_SHIFT) + return -EINVAL; + + ctx->type = IV_BENBI; + ctx->shift = SECTOR_SHIFT - log; + } else if (!strncasecmp(iv_name, "eboiv", 5)) { + r = crypt_cipher_init(&ctx->cipher, cipher_name, "ecb", + key, key_length); + if (r) + return r; + + ctx->type = IV_EBOIV; + ctx->shift = int_log2(sector_size); + } else + return -ENOENT; + + ctx->iv = malloc(ctx->iv_size); + if (!ctx->iv) + return -ENOMEM; + + return 0; +} + +static int crypt_sector_iv_generate(struct crypt_sector_iv *ctx, uint64_t sector) +{ + uint64_t val, *u64_iv; + uint32_t *u32_iv; + + switch (ctx->type) { + case IV_NONE: + break; + case IV_NULL: + memset(ctx->iv, 0, ctx->iv_size); + break; + case IV_PLAIN: + memset(ctx->iv, 0, ctx->iv_size); + u32_iv = (void *)ctx->iv; + *u32_iv = cpu_to_le32(sector & 0xffffffff); + break; + case IV_PLAIN64: + memset(ctx->iv, 0, ctx->iv_size); + u64_iv = (void *)ctx->iv; + *u64_iv = cpu_to_le64(sector); + break; + case IV_PLAIN64BE: + memset(ctx->iv, 0, ctx->iv_size); + /* iv_size is at least of size u64; usually it is 16 bytes */ + u64_iv = (void *)&ctx->iv[ctx->iv_size - sizeof(uint64_t)]; + *u64_iv = cpu_to_be64(sector); + break; + case IV_ESSIV: + memset(ctx->iv, 0, ctx->iv_size); + u64_iv = (void *)ctx->iv; + *u64_iv = cpu_to_le64(sector); + return crypt_cipher_encrypt(ctx->cipher, + ctx->iv, ctx->iv, ctx->iv_size, NULL, 0); + break; + case IV_BENBI: + memset(ctx->iv, 0, ctx->iv_size); + val = cpu_to_be64((sector << ctx->shift) + 1); + memcpy(ctx->iv + ctx->iv_size - sizeof(val), &val, sizeof(val)); + break; + case IV_EBOIV: + memset(ctx->iv, 0, ctx->iv_size); + u64_iv = (void *)ctx->iv; + *u64_iv = cpu_to_le64(sector << ctx->shift); + return crypt_cipher_encrypt(ctx->cipher, + ctx->iv, ctx->iv, ctx->iv_size, NULL, 0); + break; + default: + return -EINVAL; + } + + return 0; +} + +static void crypt_sector_iv_destroy(struct crypt_sector_iv *ctx) +{ + if (ctx->type == IV_ESSIV || ctx->type == IV_EBOIV) + crypt_cipher_destroy(ctx->cipher); + + if (ctx->iv) { + memset(ctx->iv, 0, ctx->iv_size); + free(ctx->iv); + } + + memset(ctx, 0, sizeof(*ctx)); +} + +/* Block encryption storage wrappers */ + +int crypt_storage_init(struct crypt_storage **ctx, + size_t sector_size, + const char *cipher, + const char *cipher_mode, + const void *key, size_t key_length, + bool large_iv) +{ + struct crypt_storage *s; + char mode_name[64]; + char *cipher_iv = NULL; + int r = -EIO; + + if (sector_size < (1 << SECTOR_SHIFT) || + sector_size > (1 << (SECTOR_SHIFT + 3)) || + sector_size & (sector_size - 1)) + return -EINVAL; + + s = malloc(sizeof(*s)); + if (!s) + return -ENOMEM; + memset(s, 0, sizeof(*s)); + + /* Remove IV if present */ + strncpy(mode_name, cipher_mode, sizeof(mode_name)); + mode_name[sizeof(mode_name) - 1] = 0; + cipher_iv = strchr(mode_name, '-'); + if (cipher_iv) { + *cipher_iv = '\0'; + cipher_iv++; + } + + r = crypt_cipher_init(&s->cipher, cipher, mode_name, key, key_length); + if (r) { + crypt_storage_destroy(s); + return r; + } + + r = crypt_sector_iv_init(&s->cipher_iv, cipher, mode_name, cipher_iv, key, key_length, sector_size); + if (r) { + crypt_storage_destroy(s); + return r; + } + + s->sector_size = sector_size; + s->iv_shift = large_iv ? int_log2(sector_size) - SECTOR_SHIFT : 0; + + *ctx = s; + return 0; +} + +int crypt_storage_decrypt(struct crypt_storage *ctx, + uint64_t iv_offset, + uint64_t length, char *buffer) +{ + uint64_t i; + int r = 0; + + if (length & (ctx->sector_size - 1)) + return -EINVAL; + + if (iv_offset & ((ctx->sector_size >> SECTOR_SHIFT) - 1)) + return -EINVAL; + + for (i = 0; i < length; i += ctx->sector_size) { + r = crypt_sector_iv_generate(&ctx->cipher_iv, (iv_offset + (i >> SECTOR_SHIFT)) >> ctx->iv_shift); + if (r) + break; + r = crypt_cipher_decrypt(ctx->cipher, + &buffer[i], + &buffer[i], + ctx->sector_size, + ctx->cipher_iv.iv, + ctx->cipher_iv.iv_size); + if (r) + break; + } + + return r; +} + +int crypt_storage_encrypt(struct crypt_storage *ctx, + uint64_t iv_offset, + uint64_t length, char *buffer) +{ + uint64_t i; + int r = 0; + + if (length & (ctx->sector_size - 1)) + return -EINVAL; + + if (iv_offset & ((ctx->sector_size >> SECTOR_SHIFT) - 1)) + return -EINVAL; + + for (i = 0; i < length; i += ctx->sector_size) { + r = crypt_sector_iv_generate(&ctx->cipher_iv, (iv_offset + (i >> SECTOR_SHIFT)) >> ctx->iv_shift); + if (r) + break; + r = crypt_cipher_encrypt(ctx->cipher, + &buffer[i], + &buffer[i], + ctx->sector_size, + ctx->cipher_iv.iv, + ctx->cipher_iv.iv_size); + if (r) + break; + } + + return r; +} + +void crypt_storage_destroy(struct crypt_storage *ctx) +{ + if (!ctx) + return; + + crypt_sector_iv_destroy(&ctx->cipher_iv); + + if (ctx->cipher) + crypt_cipher_destroy(ctx->cipher); + + memset(ctx, 0, sizeof(*ctx)); + free(ctx); +} + +bool crypt_storage_kernel_only(struct crypt_storage *ctx) +{ + return crypt_cipher_kernel_only(ctx->cipher); +} diff --git a/lib/crypto_backend/pbkdf2_generic.c b/lib/crypto_backend/pbkdf2_generic.c new file mode 100644 index 0000000..9e87e19 --- /dev/null +++ b/lib/crypto_backend/pbkdf2_generic.c @@ -0,0 +1,232 @@ +/* + * Implementation of Password-Based Cryptography as per PKCS#5 + * Copyright (C) 2002,2003 Simon Josefsson + * Copyright (C) 2004 Free Software Foundation + * + * cryptsetup related changes + * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2012-2023 Milan Broz + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include <errno.h> +#include <alloca.h> +#include "crypto_backend_internal.h" + +static int hash_buf(const char *src, size_t src_len, + char *dst, size_t dst_len, + const char *hash_name) +{ + struct crypt_hash *hd = NULL; + int r; + + if (crypt_hash_init(&hd, hash_name)) + return -EINVAL; + + r = crypt_hash_write(hd, src, src_len); + + if (!r) + r = crypt_hash_final(hd, dst, dst_len); + + crypt_hash_destroy(hd); + return r; +} + +/* + * 5.2 PBKDF2 + * + * PBKDF2 applies a pseudorandom function (see Appendix B.1 for an + * example) to derive keys. The length of the derived key is essentially + * unbounded. (However, the maximum effective search space for the + * derived key may be limited by the structure of the underlying + * pseudorandom function. See Appendix B.1 for further discussion.) + * PBKDF2 is recommended for new applications. + * + * PBKDF2 (P, S, c, dkLen) + * + * Options: PRF underlying pseudorandom function (hLen + * denotes the length in octets of the + * pseudorandom function output) + * + * Input: P password, an octet string (ASCII or UTF-8) + * S salt, an octet string + * c iteration count, a positive integer + * dkLen intended length in octets of the derived + * key, a positive integer, at most + * (2^32 - 1) * hLen + * + * Output: DK derived key, a dkLen-octet string + */ + +/* + * if hash_block_size is not zero, the HMAC key is pre-hashed + * inside this function. + * This prevents situation when crypto backend doesn't support + * long HMAC keys or it tries hash long key in every iteration + * (because of crypt_final() cannot do simple key reset. + */ + +#define MAX_PRF_BLOCK_LEN 80 + +int pkcs5_pbkdf2(const char *hash, + const char *P, size_t Plen, + const char *S, size_t Slen, + unsigned int c, unsigned int dkLen, + char *DK, unsigned int hash_block_size) +{ + struct crypt_hmac *hmac; + char U[MAX_PRF_BLOCK_LEN]; + char T[MAX_PRF_BLOCK_LEN]; + char P_hash[MAX_PRF_BLOCK_LEN]; + int i, k, rc = -EINVAL; + unsigned int u, hLen, l, r; + size_t tmplen = Slen + 4; + char *tmp; + + tmp = alloca(tmplen); + if (tmp == NULL) + return -ENOMEM; + + hLen = crypt_hmac_size(hash); + if (hLen == 0 || hLen > MAX_PRF_BLOCK_LEN) + return -EINVAL; + + if (c == 0) + return -EINVAL; + + if (dkLen == 0) + return -EINVAL; + + /* + * + * Steps: + * + * 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and + * stop. + */ + + if (dkLen > 4294967295U) + return -EINVAL; + + /* + * 2. Let l be the number of hLen-octet blocks in the derived key, + * rounding up, and let r be the number of octets in the last + * block: + * + * l = CEIL (dkLen / hLen) , + * r = dkLen - (l - 1) * hLen . + * + * Here, CEIL (x) is the "ceiling" function, i.e. the smallest + * integer greater than, or equal to, x. + */ + + l = dkLen / hLen; + if (dkLen % hLen) + l++; + r = dkLen - (l - 1) * hLen; + + /* + * 3. For each block of the derived key apply the function F defined + * below to the password P, the salt S, the iteration count c, and + * the block index to compute the block: + * + * T_1 = F (P, S, c, 1) , + * T_2 = F (P, S, c, 2) , + * ... + * T_l = F (P, S, c, l) , + * + * where the function F is defined as the exclusive-or sum of the + * first c iterates of the underlying pseudorandom function PRF + * applied to the password P and the concatenation of the salt S + * and the block index i: + * + * F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c + * + * where + * + * U_1 = PRF (P, S || INT (i)) , + * U_2 = PRF (P, U_1) , + * ... + * U_c = PRF (P, U_{c-1}) . + * + * Here, INT (i) is a four-octet encoding of the integer i, most + * significant octet first. + * + * 4. Concatenate the blocks and extract the first dkLen octets to + * produce a derived key DK: + * + * DK = T_1 || T_2 || ... || T_l<0..r-1> + * + * 5. Output the derived key DK. + * + * Note. The construction of the function F follows a "belt-and- + * suspenders" approach. The iterates U_i are computed recursively to + * remove a degree of parallelism from an opponent; they are exclusive- + * ored together to reduce concerns about the recursion degenerating + * into a small set of values. + * + */ + + /* If hash_block_size is provided, hash password in advance. */ + if (hash_block_size > 0 && Plen > hash_block_size) { + if (hash_buf(P, Plen, P_hash, hLen, hash)) + return -EINVAL; + + if (crypt_hmac_init(&hmac, hash, P_hash, hLen)) + return -EINVAL; + crypt_backend_memzero(P_hash, sizeof(P_hash)); + } else { + if (crypt_hmac_init(&hmac, hash, P, Plen)) + return -EINVAL; + } + + for (i = 1; (unsigned int) i <= l; i++) { + memset(T, 0, hLen); + + for (u = 1; u <= c ; u++) { + if (u == 1) { + memcpy(tmp, S, Slen); + tmp[Slen + 0] = (i & 0xff000000) >> 24; + tmp[Slen + 1] = (i & 0x00ff0000) >> 16; + tmp[Slen + 2] = (i & 0x0000ff00) >> 8; + tmp[Slen + 3] = (i & 0x000000ff) >> 0; + + if (crypt_hmac_write(hmac, tmp, tmplen)) + goto out; + } else { + if (crypt_hmac_write(hmac, U, hLen)) + goto out; + } + + if (crypt_hmac_final(hmac, U, hLen)) + goto out; + + for (k = 0; (unsigned int) k < hLen; k++) + T[k] ^= U[k]; + } + + memcpy(DK + (i - 1) * hLen, T, (unsigned int) i == l ? r : hLen); + } + rc = 0; +out: + crypt_hmac_destroy(hmac); + crypt_backend_memzero(U, sizeof(U)); + crypt_backend_memzero(T, sizeof(T)); + crypt_backend_memzero(tmp, tmplen); + + return rc; +} diff --git a/lib/crypto_backend/pbkdf_check.c b/lib/crypto_backend/pbkdf_check.c new file mode 100644 index 0000000..53a2da9 --- /dev/null +++ b/lib/crypto_backend/pbkdf_check.c @@ -0,0 +1,443 @@ +/* + * PBKDF performance check + * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved. + * Copyright (C) 2012-2023 Milan Broz + * Copyright (C) 2016-2020 Ondrej Mosnacek + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include <stdlib.h> +#include <errno.h> +#include <limits.h> +#include <time.h> +#include <sys/time.h> +#include <sys/resource.h> +#include "crypto_backend.h" + +#ifndef CLOCK_MONOTONIC_RAW +#define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC +#endif + +#define BENCH_MIN_MS 250 +#define BENCH_MIN_MS_FAST 10 +#define BENCH_PERCENT_ATLEAST 95 +#define BENCH_PERCENT_ATMOST 110 +#define BENCH_SAMPLES_FAST 3 +#define BENCH_SAMPLES_SLOW 1 + +/* These PBKDF2 limits must be never violated */ +int crypt_pbkdf_get_limits(const char *kdf, struct crypt_pbkdf_limits *limits) +{ + if (!kdf || !limits) + return -EINVAL; + + if (!strcmp(kdf, "pbkdf2")) { + limits->min_iterations = 1000; /* recommendation in NIST SP 800-132 */ + limits->max_iterations = UINT32_MAX; + limits->min_memory = 0; /* N/A */ + limits->min_bench_memory=0; /* N/A */ + limits->max_memory = 0; /* N/A */ + limits->min_parallel = 0; /* N/A */ + limits->max_parallel = 0; /* N/A */ + return 0; + } else if (!strcmp(kdf, "argon2i") || !strcmp(kdf, "argon2id")) { + limits->min_iterations = 4; + limits->max_iterations = UINT32_MAX; + limits->min_memory = 32; /* hard limit */ + limits->min_bench_memory=64*1024; /* 64 MiB minimum for benchmark */ + limits->max_memory = 4*1024*1024; /* 4GiB */ + limits->min_parallel = 1; + limits->max_parallel = 4; + return 0; + } + + return -EINVAL; +} + +static long time_ms(struct rusage *start, struct rusage *end) +{ + int count_kernel_time = 0; + long ms; + + if (crypt_backend_flags() & CRYPT_BACKEND_KERNEL) + count_kernel_time = 1; + + /* + * If there is no self usage info, count system time. + * This seem like getrusage() bug in some hypervisors... + */ + if (!end->ru_utime.tv_sec && !start->ru_utime.tv_sec && + !end->ru_utime.tv_usec && !start->ru_utime.tv_usec) + count_kernel_time = 1; + + ms = (end->ru_utime.tv_sec - start->ru_utime.tv_sec) * 1000; + ms += (end->ru_utime.tv_usec - start->ru_utime.tv_usec) / 1000; + + if (count_kernel_time) { + ms += (end->ru_stime.tv_sec - start->ru_stime.tv_sec) * 1000; + ms += (end->ru_stime.tv_usec - start->ru_stime.tv_usec) / 1000; + } + + return ms; +} + +static long timespec_ms(struct timespec *start, struct timespec *end) +{ + return (end->tv_sec - start->tv_sec) * 1000 + + (end->tv_nsec - start->tv_nsec) / (1000 * 1000); +} + +static int measure_argon2(const char *kdf, const char *password, size_t password_length, + const char *salt, size_t salt_length, + char *key, size_t key_length, + uint32_t t_cost, uint32_t m_cost, uint32_t parallel, + size_t samples, long ms_atleast, long *out_ms) +{ + long ms, ms_min = LONG_MAX; + int r; + size_t i; + + for (i = 0; i < samples; i++) { + struct timespec tstart, tend; + + /* + * NOTE: We must use clock_gettime here, because Argon2 can run over + * multiple threads, and thus we care about real time, not CPU time! + */ + if (clock_gettime(CLOCK_MONOTONIC_RAW, &tstart) < 0) + return -EINVAL; + + r = crypt_pbkdf(kdf, NULL, password, password_length, salt, + salt_length, key, key_length, t_cost, m_cost, parallel); + if (r < 0) + return r; + + if (clock_gettime(CLOCK_MONOTONIC_RAW, &tend) < 0) + return -EINVAL; + + ms = timespec_ms(&tstart, &tend); + if (ms < 0) + return -EINVAL; + + if (ms < ms_atleast) { + /* early exit */ + ms_min = ms; + break; + } + if (ms < ms_min) { + ms_min = ms; + } + } + *out_ms = ms_min; + return 0; +} + +#define CONTINUE 0 +#define FINAL 1 +static int next_argon2_params(uint32_t *t_cost, uint32_t *m_cost, + uint32_t min_t_cost, uint32_t min_m_cost, + uint32_t max_m_cost, long ms, uint32_t target_ms) +{ + uint32_t old_t_cost, old_m_cost, new_t_cost, new_m_cost; + uint64_t num, denom; + + old_t_cost = *t_cost; + old_m_cost = *m_cost; + + if ((uint32_t)ms > target_ms) { + /* decreasing, first try to lower t_cost, then m_cost */ + num = (uint64_t)*t_cost * (uint64_t)target_ms; + denom = (uint64_t)ms; + new_t_cost = (uint32_t)(num / denom); + if (new_t_cost < min_t_cost) { + num = (uint64_t)*t_cost * (uint64_t)*m_cost * + (uint64_t)target_ms; + denom = (uint64_t)min_t_cost * (uint64_t)ms; + *t_cost = min_t_cost; + *m_cost = (uint32_t)(num / denom); + if (*m_cost < min_m_cost) { + *m_cost = min_m_cost; + return FINAL; + } + } else { + *t_cost = new_t_cost; + } + } else { + /* increasing, first try to increase m_cost, then t_cost */ + num = (uint64_t)*m_cost * (uint64_t)target_ms; + denom = (uint64_t)ms; + new_m_cost = (uint32_t)(num / denom); + if (new_m_cost > max_m_cost) { + num = (uint64_t)*t_cost * (uint64_t)*m_cost * + (uint64_t)target_ms; + denom = (uint64_t)max_m_cost * (uint64_t)ms; + *t_cost = (uint32_t)(num / denom); + *m_cost = max_m_cost; + if (*t_cost <= min_t_cost) { + *t_cost = min_t_cost; + return FINAL; + } + } else if (new_m_cost < min_m_cost) { + *m_cost = min_m_cost; + return FINAL; + } else { + *m_cost = new_m_cost; + } + } + + /* do not continue if it is the same as in the previous run */ + if (old_t_cost == *t_cost && old_m_cost == *m_cost) + return FINAL; + + return CONTINUE; +} + +static int crypt_argon2_check(const char *kdf, const char *password, + size_t password_length, const char *salt, + size_t salt_length, size_t key_length, + uint32_t min_t_cost, uint32_t min_m_cost, uint32_t max_m_cost, + uint32_t parallel, uint32_t target_ms, + uint32_t *out_t_cost, uint32_t *out_m_cost, + int (*progress)(uint32_t time_ms, void *usrptr), + void *usrptr) +{ + int r = 0; + char *key = NULL; + uint32_t t_cost, m_cost; + long ms; + long ms_atleast = (long)target_ms * BENCH_PERCENT_ATLEAST / 100; + long ms_atmost = (long)target_ms * BENCH_PERCENT_ATMOST / 100; + + if (key_length <= 0 || target_ms <= 0) + return -EINVAL; + + if (min_m_cost < (parallel * 8)) + min_m_cost = parallel * 8; + + if (max_m_cost < min_m_cost) + return -EINVAL; + + key = malloc(key_length); + if (!key) + return -ENOMEM; + + t_cost = min_t_cost; + m_cost = min_m_cost; + + /* 1. Find some small parameters, s. t. ms >= BENCH_MIN_MS: */ + while (1) { + r = measure_argon2(kdf, password, password_length, salt, salt_length, + key, key_length, t_cost, m_cost, parallel, + BENCH_SAMPLES_FAST, BENCH_MIN_MS, &ms); + if (!r) { + /* Update parameters to actual measurement */ + *out_t_cost = t_cost; + *out_m_cost = m_cost; + if (progress && progress((uint32_t)ms, usrptr)) + r = -EINTR; + } + + if (r < 0) + goto out; + + if (ms >= BENCH_MIN_MS) + break; + + if (m_cost == max_m_cost) { + if (ms < BENCH_MIN_MS_FAST) + t_cost *= 16; + else { + uint32_t new = (t_cost * BENCH_MIN_MS) / (uint32_t)ms; + if (new == t_cost) + break; + + t_cost = new; + } + } else { + if (ms < BENCH_MIN_MS_FAST) + m_cost *= 16; + else { + uint32_t new = (m_cost * BENCH_MIN_MS) / (uint32_t)ms; + if (new == m_cost) + break; + + m_cost = new; + } + if (m_cost > max_m_cost) { + m_cost = max_m_cost; + } + } + } + /* + * 2. Use the params obtained in (1.) to estimate the target params. + * 3. Then repeatedly measure the candidate params and if they fall out of + * the acceptance range (+-5 %), try to improve the estimate: + */ + do { + if (next_argon2_params(&t_cost, &m_cost, min_t_cost, min_m_cost, + max_m_cost, ms, target_ms)) { + /* Update parameters to final computation */ + *out_t_cost = t_cost; + *out_m_cost = m_cost; + break; + } + + r = measure_argon2(kdf, password, password_length, salt, salt_length, + key, key_length, t_cost, m_cost, parallel, + BENCH_SAMPLES_SLOW, ms_atleast, &ms); + + if (!r) { + /* Update parameters to actual measurement */ + *out_t_cost = t_cost; + *out_m_cost = m_cost; + if (progress && progress((uint32_t)ms, usrptr)) + r = -EINTR; + } + + if (r < 0) + break; + + } while (ms < ms_atleast || ms > ms_atmost); +out: + if (key) { + crypt_backend_memzero(key, key_length); + free(key); + } + return r; +} + +/* This code benchmarks PBKDF and returns iterations/second using specified hash */ +static int crypt_pbkdf_check(const char *kdf, const char *hash, + const char *password, size_t password_length, + const char *salt, size_t salt_length, + size_t key_length, uint32_t *iter_secs, uint32_t target_ms, + int (*progress)(uint32_t time_ms, void *usrptr), void *usrptr) + +{ + struct rusage rstart, rend; + int r = 0, step = 0; + long ms = 0; + char *key = NULL; + uint32_t iterations; + double PBKDF2_temp; + + if (!kdf || !hash || key_length <= 0) + return -EINVAL; + + key = malloc(key_length); + if (!key) + return -ENOMEM; + + *iter_secs = 0; + iterations = 1 << 15; + while (1) { + if (getrusage(RUSAGE_SELF, &rstart) < 0) { + r = -EINVAL; + goto out; + } + + r = crypt_pbkdf(kdf, hash, password, password_length, salt, + salt_length, key, key_length, iterations, 0, 0); + + if (r < 0) + goto out; + + if (getrusage(RUSAGE_SELF, &rend) < 0) { + r = -EINVAL; + goto out; + } + + ms = time_ms(&rstart, &rend); + if (ms) { + PBKDF2_temp = (double)iterations * target_ms / ms; + if (PBKDF2_temp > UINT32_MAX) { + r = -EINVAL; + goto out; + } + *iter_secs = (uint32_t)PBKDF2_temp; + } + + if (progress && progress((uint32_t)ms, usrptr)) { + r = -EINTR; + goto out; + } + + if (ms > 500) + break; + + if (ms <= 62) + iterations <<= 4; + else if (ms <= 125) + iterations <<= 3; + else if (ms <= 250) + iterations <<= 2; + else + iterations <<= 1; + + if (++step > 10 || !iterations) { + r = -EINVAL; + goto out; + } + } +out: + if (key) { + crypt_backend_memzero(key, key_length); + free(key); + } + return r; +} + +int crypt_pbkdf_perf(const char *kdf, const char *hash, + const char *password, size_t password_size, + const char *salt, size_t salt_size, + size_t volume_key_size, uint32_t time_ms, + uint32_t max_memory_kb, uint32_t parallel_threads, + uint32_t *iterations_out, uint32_t *memory_out, + int (*progress)(uint32_t time_ms, void *usrptr), void *usrptr) +{ + struct crypt_pbkdf_limits pbkdf_limits; + int r = -EINVAL; + uint32_t min_memory; + + if (!kdf || !iterations_out || !memory_out) + return -EINVAL; + + r = crypt_pbkdf_get_limits(kdf, &pbkdf_limits); + if (r < 0) + return r; + + min_memory = pbkdf_limits.min_bench_memory; + if (min_memory > max_memory_kb) + min_memory = max_memory_kb; + + *memory_out = 0; + *iterations_out = 0; + + if (!strcmp(kdf, "pbkdf2")) + r = crypt_pbkdf_check(kdf, hash, password, password_size, + salt, salt_size, volume_key_size, + iterations_out, time_ms, progress, usrptr); + + else if (!strncmp(kdf, "argon2", 6)) + r = crypt_argon2_check(kdf, password, password_size, + salt, salt_size, volume_key_size, + pbkdf_limits.min_iterations, + min_memory, + max_memory_kb, + parallel_threads, time_ms, iterations_out, + memory_out, progress, usrptr); + return r; +} diff --git a/lib/crypto_backend/utf8.c b/lib/crypto_backend/utf8.c new file mode 100644 index 0000000..24e0d8d --- /dev/null +++ b/lib/crypto_backend/utf8.c @@ -0,0 +1,288 @@ +/* + * UTF8/16 helpers, copied and adapted from systemd project. + * + * Copyright (C) 2010 Lennart Poettering + * + * cryptsetup related changes + * Copyright (C) 2021-2023 Vojtech Trefny + + * Parts of the original systemd implementation are based on the GLIB utf8 + * validation functions. + * gutf8.c - Operations on UTF-8 strings. + * + * Copyright (C) 1999 Tom Tromey + * Copyright (C) 2000 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include <errno.h> +#include <endian.h> + +#include "crypto_backend.h" + +static inline bool utf16_is_surrogate(char16_t c) +{ + return c >= 0xd800U && c <= 0xdfffU; +} + +static inline bool utf16_is_trailing_surrogate(char16_t c) +{ + return c >= 0xdc00U && c <= 0xdfffU; +} + +static inline char32_t utf16_surrogate_pair_to_unichar(char16_t lead, char16_t trail) +{ + return ((((char32_t) lead - 0xd800U) << 10) + ((char32_t) trail - 0xdc00U) + 0x10000U); +} + +/** + * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8 + * @out_utf8: output buffer of at least 4 bytes or NULL + * @g: UCS-4 character to encode + * + * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8. + * The length of the character is returned. It is not zero-terminated! If the + * output buffer is NULL, only the length is returned. + * + * Returns: The length in bytes that the UTF-8 representation does or would + * occupy. + */ +static size_t utf8_encode_unichar(char *out_utf8, char32_t g) +{ + if (g < (1 << 7)) { + if (out_utf8) + out_utf8[0] = g & 0x7f; + return 1; + } else if (g < (1 << 11)) { + if (out_utf8) { + out_utf8[0] = 0xc0 | ((g >> 6) & 0x1f); + out_utf8[1] = 0x80 | (g & 0x3f); + } + return 2; + } else if (g < (1 << 16)) { + if (out_utf8) { + out_utf8[0] = 0xe0 | ((g >> 12) & 0x0f); + out_utf8[1] = 0x80 | ((g >> 6) & 0x3f); + out_utf8[2] = 0x80 | (g & 0x3f); + } + return 3; + } else if (g < (1 << 21)) { + if (out_utf8) { + out_utf8[0] = 0xf0 | ((g >> 18) & 0x07); + out_utf8[1] = 0x80 | ((g >> 12) & 0x3f); + out_utf8[2] = 0x80 | ((g >> 6) & 0x3f); + out_utf8[3] = 0x80 | (g & 0x3f); + } + return 4; + } + + return 0; +} + +/** + * crypt_utf16_to_utf8() + * @out: output buffer, should be 2 * @length + 1 long + * @s: string to convert + * @length: length of @s in bytes + * + * Converts a UTF16LE encoded string to a UTF8 encoded string. + * + * Returns: 0 on success, negative errno otherwise + */ +int crypt_utf16_to_utf8(char **out, const char16_t *s, size_t length /* bytes! */) +{ + const uint8_t *f; + char *t; + + assert(s); + assert(out); + assert(*out); + + /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may + * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */ + if (length * 2 < length) + return -EOVERFLOW; /* overflow */ + + f = (const uint8_t*) s; + t = *out; + + while (f + 1 < (const uint8_t*) s + length) { + char16_t w1, w2; + + /* see RFC 2781 section 2.2 */ + + w1 = f[1] << 8 | f[0]; + f += 2; + + if (!utf16_is_surrogate(w1)) { + t += utf8_encode_unichar(t, w1); + continue; + } + + if (utf16_is_trailing_surrogate(w1)) + continue; /* spurious trailing surrogate, ignore */ + + if (f + 1 >= (const uint8_t*) s + length) + break; + + w2 = f[1] << 8 | f[0]; + f += 2; + + if (!utf16_is_trailing_surrogate(w2)) { + f -= 2; + continue; /* surrogate missing its trailing surrogate, ignore */ + } + + t += utf8_encode_unichar(t, utf16_surrogate_pair_to_unichar(w1, w2)); + } + + *t = 0; + return 0; +} + +/* count of characters used to encode one unicode char */ +static size_t utf8_encoded_expected_len(uint8_t c) +{ + if (c < 0x80) + return 1; + if ((c & 0xe0) == 0xc0) + return 2; + if ((c & 0xf0) == 0xe0) + return 3; + if ((c & 0xf8) == 0xf0) + return 4; + if ((c & 0xfc) == 0xf8) + return 5; + if ((c & 0xfe) == 0xfc) + return 6; + + return 0; +} + +/* decode one unicode char */ +static int utf8_encoded_to_unichar(const char *str, char32_t *ret_unichar) +{ + char32_t unichar; + size_t len, i; + + assert(str); + + len = utf8_encoded_expected_len(str[0]); + + switch (len) { + case 1: + *ret_unichar = (char32_t)str[0]; + return 0; + case 2: + unichar = str[0] & 0x1f; + break; + case 3: + unichar = (char32_t)str[0] & 0x0f; + break; + case 4: + unichar = (char32_t)str[0] & 0x07; + break; + case 5: + unichar = (char32_t)str[0] & 0x03; + break; + case 6: + unichar = (char32_t)str[0] & 0x01; + break; + default: + return -EINVAL; + } + + for (i = 1; i < len; i++) { + if (((char32_t)str[i] & 0xc0) != 0x80) + return -EINVAL; + + unichar <<= 6; + unichar |= (char32_t)str[i] & 0x3f; + } + + *ret_unichar = unichar; + + return 0; +} + +static size_t utf16_encode_unichar(char16_t *out, char32_t c) +{ + /* Note that this encodes as little-endian. */ + + switch (c) { + + case 0 ... 0xd7ffU: + case 0xe000U ... 0xffffU: + out[0] = htole16(c); + return 1; + + case 0x10000U ... 0x10ffffU: + c -= 0x10000U; + out[0] = htole16((c >> 10) + 0xd800U); + out[1] = htole16((c & 0x3ffU) + 0xdc00U); + return 2; + + default: /* A surrogate (invalid) */ + return 0; + } +} + +/** + * crypt_utf8_to_utf16() + * @out: output buffer, should be @length + 1 long + * @s: string to convert + * @length: length of @s in bytes + * + * Converts a UTF8 encoded string to a UTF16LE encoded string. + * + * Returns: 0 on success, negative errno otherwise + */ +int crypt_utf8_to_utf16(char16_t **out, const char *s, size_t length) +{ + char16_t *p; + size_t i; + int r; + + assert(s); + + p = *out; + + for (i = 0; i < length;) { + char32_t unichar; + size_t e; + + e = utf8_encoded_expected_len(s[i]); + if (e <= 1) /* Invalid and single byte characters are copied as they are */ + goto copy; + + if (i + e > length) /* sequence longer than input buffer, then copy as-is */ + goto copy; + + r = utf8_encoded_to_unichar(s + i, &unichar); + if (r < 0) /* sequence invalid, then copy as-is */ + goto copy; + + p += utf16_encode_unichar(p, unichar); + i += e; + continue; + + copy: + *(p++) = htole16(s[i++]); + } + + *p = 0; + return 0; +} |