From dc71f861df8929deee300368b88ef47d45560695 Mon Sep 17 00:00:00 2001 From: vnugent Date: Mon, 1 Jul 2024 15:05:34 -0400 Subject: fix: #7 fix confusing inline functions --- CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index 7a1f707..53fbe29 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,6 +142,8 @@ if(CRYPTO_LIB STREQUAL "") elseif(OPENSSL_FOUND) set(CRYPTO_LIB "openssl") endif() + + message(STATUS "No crypto library was specified, defaulting to ${CRYPTO_LIB}") endif() #Include mbedtls if enabled -- cgit From 23fe6e8c8596333c2183f0f4389817087442c551 Mon Sep 17 00:00:00 2001 From: vnugent Date: Fri, 5 Jul 2024 00:03:48 -0400 Subject: push latest utils and changes --- CMakeLists.txt | 14 ++ CMakePresets.json | 24 +-- include/noscrypt.h | 2 +- include/noscryptutil.h | 76 +++++++++ src/hkdf.c | 15 +- src/hkdf.h | 4 +- src/nc-util.h | 46 ++++++ src/noscrypt.c | 15 +- src/noscryptutil.c | 418 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/test.c | 53 ++++++- 10 files changed, 630 insertions(+), 37 deletions(-) create mode 100644 include/noscryptutil.h create mode 100644 src/noscryptutil.c (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index 53fbe29..493b18a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,6 +17,7 @@ project( set(_NC_PROJ_NAME "noscrypt") option(NC_BUILD_TESTS "Build tests" OFF) +option(NC_ENABLE_UTILS "Enables the sidecar utility library" OFF) option(NC_DISABLE_INPUT_VALIDATION "Disables public function input validation" OFF) option(NC_FETCH_MBEDTLS "Fetch Mbed-TLS from it's source repository locally" OFF) option(NC_FETCH_SECP256K1 "Fetch and locally build secp256k1 source code" ON) @@ -94,6 +95,17 @@ set(NOSCRYPT_HEADERS "src/nc-crypto.h" ) +#if utils are enabled, add the source files +if(NC_ENABLE_UTILS) + list(APPEND NOSCRYPT_SRCS "src/noscryptutil.c") + list(APPEND NOSCRYPT_HEADERS "include/noscryptutil.h") + + #notify the project that utils are enabled + list(APPEND NC_PROJ_DEFINTIONS NC_ENABLE_UTILS) + + message(STATUS "Utilities libraries are enabled") +endif() + #static/shared library add_library(${_NC_PROJ_NAME} SHARED ${NOSCRYPT_SRCS} ${NOSCRYPT_HEADERS}) add_library(${_NC_PROJ_NAME}_static STATIC ${NOSCRYPT_SRCS} ${NOSCRYPT_HEADERS}) @@ -366,11 +378,13 @@ if(NC_BUILD_TESTS) #add test executable and link to shared library for more realistic usage add_executable(nctest tests/test.c) target_link_libraries(nctest ${_NC_PROJ_NAME}) + target_include_directories(nctest PRIVATE include) target_include_directories(nctest PRIVATE src) #allow access to internal headers #enable c11 for testing target_compile_features(nctest PRIVATE c_std_11) + target_compile_definitions(nctest PRIVATE ${NC_PROJ_DEFINTIONS}) enable_testing() diff --git a/CMakePresets.json b/CMakePresets.json index 63ccfec..1b6d907 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -15,7 +15,7 @@ "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" - } + }, }, { "name": "x64-debug", @@ -27,7 +27,8 @@ }, "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", - "NC_BUILD_TESTS": true + "NC_BUILD_TESTS": true, + "NC_ENABLE_UTILS": true } }, { @@ -44,13 +45,18 @@ "CRYPTO_LIB": "openssl" } }, - { - "name": "x64-release", - "displayName": "x64 Release", - "inherits": "x64-debug", - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Release" - } + { + "name": "x64-release", + "displayName": "x64 Release", + "inherits": "windows-base", + "architecture": { + "value": "x64", + "strategy": "external" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "NC_ENABLE_UTILS": true } + } ] } diff --git a/include/noscrypt.h b/include/noscrypt.h index bdfaa9f..8b39f17 100644 --- a/include/noscrypt.h +++ b/include/noscrypt.h @@ -228,7 +228,7 @@ NC_EXPORT NCResult NC_CC NCResultWithArgPosition(NCResult err, uint8_t argPositi * Parses an error code and returns the error code and the argument position that caused the error. * @param result The error code to parse -* @param argPositionOut A pointer to the argument position to write to +* @param argPositionOut A pointer to the argument position to write to (optionall, set to NULL of unobserved) * @return The error code */ NC_EXPORT int NC_CC NCParseErrorCode(NCResult result, uint8_t* argPositionOut); diff --git a/include/noscryptutil.h b/include/noscryptutil.h new file mode 100644 index 0000000..1a98698 --- /dev/null +++ b/include/noscryptutil.h @@ -0,0 +1,76 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Package: noscrypt +* File: noscryptutil.h +* +* This library 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 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 +* Lesser General Public License for more details. +* +* You should have received a copy of the GNU Lesser General Public License +* along with noscrypt. If not, see http://www.gnu.org/licenses/. +*/ + +/* +* noscrypt is a an open-source, strict C89 library that performs the basic +* cryptographic operations found in the Nostr protocol. It is designed to be +* portable and easy to use in any C89 compatible environment. It is also designed +*/ + +#pragma once + +#ifndef NOSCRYPTUTIL_H +#define NOSCRYPTUTIL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "noscrypt.h" + +#define E_OUT_OF_MEMORY -10 + +typedef struct nc_util_enc_struct NCUtilEncryptionContext; + +NC_EXPORT NCResult NC_CC NCUtilGetEncryptionPaddedSize(uint32_t encVersion, int32_t plaintextSize); + +NC_EXPORT NCResult NC_CC NCUtilGetEncryptionBufferSize(uint32_t encVersion, int32_t plaintextSize); + +NC_EXPORT NCUtilEncryptionContext* NC_CC NCUtilAllocEncryptionContext(uint32_t encVersion); + +NC_EXPORT NCResult NC_CC NCUtilInitEncryptionContext( + NCUtilEncryptionContext* encCtx, + const uint8_t* plainText, + uint32_t plainTextSize +); + +NC_EXPORT void NC_CC NCUtilFreeEncryptionContext(NCUtilEncryptionContext* encCtx); + +NC_EXPORT NCResult NC_CC NCUtilGetEncryptedSize(const NCUtilEncryptionContext* encCtx); + +NC_EXPORT NCResult NC_CC NCUtilReadEncryptedData( + const NCUtilEncryptionContext* encCtx, + uint8_t* output, + uint32_t outputSize +); + +NC_EXPORT NCResult NCUtilSetEncryptionProperty( + NCUtilEncryptionContext* ctx, + uint32_t property, + uint8_t* value, + uint32_t valueLen +); + +#ifdef __cplusplus +} +#endif + +#endif /* NOSCRYPTUTIL_H */ \ No newline at end of file diff --git a/src/hkdf.c b/src/hkdf.c index 0d91d14..cff7d60 100644 --- a/src/hkdf.c +++ b/src/hkdf.c @@ -21,23 +21,10 @@ #include "hkdf.h" -/* Include string for memmove */ -#include - #define HKDF_MIN(a, b) (a < b ? a : b) STATIC_ASSERT(HKDF_IN_BUF_SIZE > SHA256_DIGEST_SIZE, "HDK Buffer must be at least the size of the underlying hashing alg output") -static _nc_fn_inline void ncWriteSpanS(span_t* span, uint32_t offset, const uint8_t* data, uint32_t size) -{ - DEBUG_ASSERT2(span != NULL, "Expected span to be non-null") - DEBUG_ASSERT2(data != NULL, "Expected data to be non-null") - DEBUG_ASSERT2(offset + size <= span->size, "Expected offset + size to be less than span size") - - /* Copy data to span */ - memmove(span->data + offset, data, size); -} - static _nc_fn_inline void debugValidateHandler(const struct nc_hkdf_fn_cb_struct* handler) { DEBUG_ASSERT(handler != NULL) @@ -114,7 +101,7 @@ cstatus_t hkdfExpandProcess( DEBUG_ASSERT(tLen <= sizeof(t)); /* write the T buffer back to okm */ - ncWriteSpanS(okm, okmOffset, t, tLen); + ncSpanWrite(*okm, okmOffset, t, tLen); /* shift base okm pointer by T */ okmOffset += tLen; diff --git a/src/hkdf.h b/src/hkdf.h index 460e203..2e3a55e 100644 --- a/src/hkdf.h +++ b/src/hkdf.h @@ -42,12 +42,12 @@ /* typedefs for hdkf callback functions */ -typedef cstatus_t (*hmac_hash_func)(void* ctx, const cspan_t* data); +typedef cstatus_t (*hmac_hash_fn)(void* ctx, const cspan_t* data); typedef cstatus_t (*hmac_finish_fn)(void* ctx, sha256_t hmacOut32); struct nc_hkdf_fn_cb_struct { - hmac_hash_func update; + hmac_hash_fn update; hmac_finish_fn finish; }; diff --git a/src/nc-util.h b/src/nc-util.h index dd319c7..0647f4c 100644 --- a/src/nc-util.h +++ b/src/nc-util.h @@ -68,6 +68,28 @@ #define _overflow_check(x) #endif +#ifdef NC_EXTREME_COMPAT + + void _nc_memmove(void* dst, const void* src, uint32_t size) + { + uint32_t i; + + for (i = 0; i < size; i++) + { + ((uint8_t*)dst)[i] = ((uint8_t*)src)[i]; + } + } + + #define MEMMOV _nc_memmove + +#else + + /* Include string for memmove */ + #include + #define MEMMOV(dst, src, size) memmove(dst, src, size) + +#endif /* NC_EXTREME_COMPAT */ + typedef struct memory_span_struct { uint8_t* data; @@ -92,4 +114,28 @@ static _nc_fn_inline void ncSpanInit(span_t* span, uint8_t* data, uint32_t size) span->size = size; } +static _nc_fn_inline void ncSpanWrite(span_t span, uint32_t offset, const uint8_t* data, uint32_t size) +{ + DEBUG_ASSERT2(span.data != NULL, "Expected span to be non-null") + DEBUG_ASSERT2(data != NULL, "Expected data to be non-null") + DEBUG_ASSERT2(offset + size <= span.size, "Expected offset + size to be less than span size") + + /* Copy data to span */ + MEMMOV(span.data + offset, data, size); +} + +static _nc_fn_inline void ncSpanAppend(span_t span, uint32_t* offset, const uint8_t* data, uint32_t size) +{ + DEBUG_ASSERT2(span.data != NULL, "Expected span to be non-null") + DEBUG_ASSERT2(offset != NULL, "Expected offset to be non-null") + DEBUG_ASSERT2(data != NULL, "Expected data to be non-null") + DEBUG_ASSERT2(*offset + size <= span.size, "Expected offset + size to be less than span size") + + /* Copy data to span */ + MEMMOV(span.data + *offset, data, size); + + /* Increment offset */ + *offset += size; +} + #endif /* !_NC_UTIL_H */ \ No newline at end of file diff --git a/src/noscrypt.c b/src/noscrypt.c index c523262..910f559 100644 --- a/src/noscrypt.c +++ b/src/noscrypt.c @@ -32,10 +32,6 @@ */ #define ZERO_FILL(x, size) ncCryptoSecureZero(x, size) -/* Include string for memmove */ -#include -#define MEMMOV(dst, src, size) memmove(dst, src, size) - /* * Validation macros */ @@ -44,7 +40,6 @@ #define CHECK_INVALID_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_INVALID_ARG, argPos); #define CHECK_NULL_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_NULL_PTR, argPos); #define CHECK_ARG_RANGE(x, min, max, argPos) if(x < min || x > max) return NCResultWithArgPosition(E_ARGUMENT_OUT_OF_RANGE, argPos); - #define CHECK_CONTEXT_STATE(ctx, argPos) CHECK_INVALID_ARG(ctx->secpCtx, argPos) #else /* empty macros */ #define CHECK_INVALID_ARG(x) @@ -52,6 +47,8 @@ #define CHECK_ARG_RANGE(x, min, max, argPos) #endif /* !NC_DISABLE_INPUT_VALIDATION */ +#define CHECK_CONTEXT_STATE(ctx, argPos) CHECK_INVALID_ARG(ctx->secpCtx, argPos) + /* * Actual, private defintion of the NCContext structure * to allow for future development and ABI backords @@ -449,7 +446,6 @@ NC_EXPORT NCResult NC_CC NCResultWithArgPosition(NCResult err, uint8_t argPositi return -(((NCResult)argPosition << NC_ARG_POSITION_OFFSET) | -err); } - NC_EXPORT int NC_CC NCParseErrorCode(NCResult result, uint8_t* argPositionOut) { NCResult asPositive; @@ -460,7 +456,12 @@ NC_EXPORT int NC_CC NCParseErrorCode(NCResult result, uint8_t* argPositionOut) /* Get the error code from the lower 8 bits and the argument position from the upper 8 bits*/ code = -(asPositive & NC_ERROR_CODE_MASK); - *argPositionOut = (asPositive >> NC_ARG_POSITION_OFFSET) & 0xFF; + + /* Allow argument position assignment to be null */ + if (argPositionOut) + { + *argPositionOut = (asPositive >> NC_ARG_POSITION_OFFSET) & 0xFF; + } return code; } diff --git a/src/noscryptutil.c b/src/noscryptutil.c new file mode 100644 index 0000000..b7723cb --- /dev/null +++ b/src/noscryptutil.c @@ -0,0 +1,418 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Package: noscrypt +* File: noscryptutil.h +* +* This library 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 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 +* Lesser General Public License for more details. +* +* You should have received a copy of the GNU Lesser General Public License +* along with noscrypt. If not, see http://www.gnu.org/licenses/. +*/ + + +#include +#include "nc-util.h" +#include "nc-crypto.h" + +/* +* Validation macros +*/ + +#ifdef NC_EXTREME_COMPAT + #error "Utilities library must be disabled when using extreme compat mode" +#endif /* NC_EXTREME_COMPAT */ + +#include +#include + +#define _nc_mem_free(x) if(x != NULL) { free(x); x = NULL; } +#define _nc_mem_alloc(elements, size) calloc(elements, size); + +#ifndef NC_INPUT_VALIDATION_OFF + #define CHECK_INVALID_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_INVALID_ARG, argPos); + #define CHECK_NULL_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_NULL_PTR, argPos); + #define CHECK_ARG_RANGE(x, min, max, argPos) if(x < min || x > max) return NCResultWithArgPosition(E_ARGUMENT_OUT_OF_RANGE, argPos); +#else + /* empty macros */ + #define CHECK_INVALID_ARG(x) + #define CHECK_NULL_ARG(x, argPos) + #define CHECK_ARG_RANGE(x, min, max, argPos) +#endif /* !NC_DISABLE_INPUT_VALIDATION */ + + +/* performs a log2 on integer types */ +#define _math_int_log2(x) (int32_t)log2((double)x) + +#define MIN_PADDING_SIZE 0x20 +#define NIP44_VERSION_SIZE 0x01 +#define NIP44_PT_LEN_SIZE 0x02 + +/* Currently were on nip44 version 2 */ +const static uint8_t Nip44VersionValue = 0x02; + +typedef struct nc_util_enc_buffer_state +{ + uint8_t* ciphertext; + uint32_t ciphertextSize; + +} NCCipherTextOutState; + +struct nc_util_enc_struct { + + /* Dynamically allocated during initialization */ + NCCipherTextOutState* outState; + + const uint8_t* plaintext; + + uint32_t plaintextSize; + + NCEncryptionArgs encArgs; +}; + +static _nc_fn_inline int32_t _calcNip44PtPadding(int32_t plaintextSize) +{ + int32_t chunk, nextPower, factor; + + /* + * Taken from https://github.com/nostr-protocol/nips/blob/master/44.md + * + * I believe the idea is to add consisten padding for some better + * disgusing of the plainText data. + */ + + if (plaintextSize <= MIN_PADDING_SIZE) + { + return MIN_PADDING_SIZE; + } + + nextPower = _math_int_log2(plaintextSize - 1); + + nextPower += 1; + + nextPower = 1 << nextPower; + + if (nextPower <= 256) + { + chunk = 32; + } + else + { + chunk = nextPower / 8; + } + + factor = plaintextSize - 1; + + factor /= chunk; + + factor += 1; + + return chunk * factor; +} + +static _nc_fn_inline int32_t _calcNip44TotalOutSize(int32_t inputSize) +{ + int32_t bufferSize; + + /* + * Buffer size for nip44 is calculated as follows: + * 1 byte for the version + * 32 bytes for the nonce + * 2 bytes for the length of the plainText + * ... padding size + * 32 bytes for the MAC + */ + + bufferSize = NIP44_VERSION_SIZE; + + bufferSize += NC_ENCRYPTION_NONCE_SIZE; + + bufferSize += NIP44_PT_LEN_SIZE; + + bufferSize += _calcNip44PtPadding(inputSize); + + bufferSize += NC_ENCRYPTION_MAC_SIZE; + + return bufferSize; +} + +static NCResult _nip44EncryptCompleteCore( + const NCContext* libContext, + const NCSecretKey* sk, + const NCPublicKey* pk, + NCEncryptionArgs encArgs, + span_t cipherText, + span_t plainText +) +{ + + NCResult result; + uint32_t outPos, paddedCtSize; + uint16_t ptSize; + + outPos = 0; + + DEBUG_ASSERT(encArgs.version == NC_ENC_VERSION_NIP44); + + /* Padded size is required to know how large the CT buffer is for encryption */ + paddedCtSize = (int32_t)_calcNip44PtPadding((int32_t)plainText.size); + + /* Start by appending the version number */ + ncSpanAppend(cipherText, &outPos, &Nip44VersionValue, 0x01); + + /* next is nonce data */ + ncSpanAppend(cipherText, &outPos, encArgs.nonceData, NC_ENCRYPTION_NONCE_SIZE); + DEBUG_ASSERT(outPos == 1 + NC_ENCRYPTION_NONCE_SIZE); + + /* + * So this is the tricky part. The encryption operation appens directly + * on the ciphertext segment + * + * All current implementations allow overlapping input and output buffers + * so we can assign the pt segment on the encryption args + */ + + /* + * Since the message size and padding bytes will get encrypted, + * the buffer should currently point to the start of the encryption segment + * + * The size of the data to encrypt is the padded size plus the size of the + * plainText size field. + */ + + encArgs.inputData = (cipherText.data + outPos); + encArgs.outputData = (cipherText.data + outPos); + encArgs.dataSize = paddedCtSize + sizeof(uint16_t); /* Plaintext + pt size must be encrypted */ + + ptSize = (uint16_t)plainText.size; + + /* Can write the plainText size to buffer now */ + ncSpanAppend(cipherText, &outPos, &ptSize, sizeof(uint16_t)); + + /* concat plainText */ + ncSpanAppend(cipherText, &outPos, plainText.data, plainText.size); + + /* Time to perform encryption operation */ + result = NCEncrypt(libContext, sk, pk, &encArgs); + + if (result == NC_SUCCESS) + { + + } +} + +static NCResult _nip44EncryptCompleteCore( + NCUtilEncryptionContext* encCtx, + const NCContext* libContext, + const NCSecretKey* sk, + const NCPublicKey* pk +) +{ + span_t cipherText, plainText; + + /* Set up spans */ + ncSpanInit( + &cipherText, + encCtx->outState->ciphertext, + encCtx->outState->ciphertextSize + ); + + ncSpanInit( + &plainText, + encCtx->plaintext, + encCtx->plaintextSize + ); + + return _nip44EncryptCompleteCore( + libContext, + sk, + pk, + encCtx->encArgs, + cipherText, + plainText + ); +} + +NC_EXPORT NCResult NC_CC NCUtilGetEncryptionPaddedSize(uint32_t encVersion, int32_t plaintextSize) +{ + int32_t paddingSize; + + CHECK_ARG_RANGE(plaintextSize, 0, INT32_MAX, 1) + + switch (encVersion) + { + default: + return E_VERSION_NOT_SUPPORTED; + + case NC_ENC_VERSION_NIP04: + return plaintextSize; + + case NC_ENC_VERSION_NIP44: + paddingSize = _calcNip44PtPadding(plaintextSize); + + DEBUG_ASSERT(paddingSize > 0) + + return (NCResult)(paddingSize); + } +} + +NC_EXPORT NCResult NC_CC NCUtilGetEncryptionBufferSize(uint32_t encVersion, int32_t plaintextSize) +{ + int32_t totalSize; + + CHECK_ARG_RANGE(plaintextSize, 0, INT32_MAX, 1) + + switch (encVersion) + { + default: + return E_VERSION_NOT_SUPPORTED; + + /* + * NIP-04 simply uses AES to 1:1 encrypt the plainText + * to ciphertext. + */ + case NC_ENC_VERSION_NIP04: + return plaintextSize; + + case NC_ENC_VERSION_NIP44: + totalSize = _calcNip44TotalOutSize(plaintextSize); + + DEBUG_ASSERT(totalSize > 0) + + return (NCResult)(totalSize); + + } +} + + +NC_EXPORT NCUtilEncryptionContext* NC_CC NCUtilAllocEncryptionContext(uint32_t encVersion) +{ + NCUtilEncryptionContext* encCtx; + + /* + * Alloc context on heap + */ + encCtx = (NCUtilEncryptionContext*)_nc_mem_alloc(1, sizeof(NCUtilEncryptionContext)); + + if (encCtx != NULL) + { + encCtx->encArgs.version = encVersion; + } + + return encCtx; +} + +NC_EXPORT void NC_CC NCUtilFreeEncryptionContext(NCUtilEncryptionContext* encCtx) +{ + if (!encCtx) + { + return; + } + + /* Free output buffers */ + _nc_mem_free(encCtx->outState); + + /* context can be released */ + _nc_mem_free(encCtx); +} + +NC_EXPORT NCResult NC_CC NCUtilInitEncryptionContext( + NCUtilEncryptionContext* encCtx, + const uint8_t* plainText, + uint32_t plainTextSize +) +{ + + NCResult outputSize; + NCCipherTextOutState* output; + + CHECK_NULL_ARG(encCtx, 0) + CHECK_NULL_ARG(plainText, 1) + CHECK_ARG_RANGE(plainTextSize, 0, INT32_MAX, 2) + + /* + * The output state must not have alraedy been allocated + */ + if (encCtx->outState) + { + return E_INVALID_ARG; + } + + /* + * Calculate the correct output size to store the encryption + * data for the given cipher version + */ + outputSize = NCUtilGetEncryptionBufferSize(encCtx->encArgs.version, plainTextSize); + + if (outputSize <= 0) + { + return outputSize; + } + + /*Alloc output buffer within the struct */ + output = (NCCipherTextOutState*)_nc_mem_alloc(sizeof(NCCipherTextOutState) + (int)outputSize, 1); + + if (!output) + { + return E_OUT_OF_MEMORY; + } + + /* set cipertext buffer to end of the structure memory */ + output->ciphertext = (uint8_t*)(output + 1); + output->ciphertextSize = outputSize; + + encCtx->outState = output; + encCtx->plaintext = plainText; + encCtx->plaintextSize = plainTextSize; + + return NC_SUCCESS; +} + +NC_EXPORT NCResult NC_CC NCUtilGetEncryptedSize(const NCUtilEncryptionContext* encCtx) +{ + CHECK_NULL_ARG(encCtx, 0); + + return (NCResult)(encCtx->outState->ciphertextSize); +} + +NC_EXPORT NCResult NC_CC NCUtilReadEncryptedData( + const NCUtilEncryptionContext* encCtx, + uint8_t* output, + uint32_t outputSize +) +{ + CHECK_NULL_ARG(encCtx, 0) + CHECK_NULL_ARG(output, 1) + CHECK_ARG_RANGE(outputSize, 0, INT32_MAX, 2) + + if (outputSize < encCtx->outState->ciphertextSize) + { + return E_OPERATION_FAILED; + } + + MEMMOV(output, encCtx->outState->ciphertext, encCtx->outState->ciphertextSize); + + return (NCResult)encCtx->outState->ciphertextSize; +} + +NC_EXPORT NCResult NCUtilSetEncryptionProperty( + NCUtilEncryptionContext* ctx, + uint32_t property, + uint8_t* value, + uint32_t valueLen +) +{ + + CHECK_NULL_ARG(ctx, 0) + + /* All other arguments are verified */ + return NCSetEncryptionPropertyEx(&ctx->encArgs, property, value, valueLen); +} diff --git a/tests/test.c b/tests/test.c index 5feae79..3833e7b 100644 --- a/tests/test.c +++ b/tests/test.c @@ -101,6 +101,10 @@ static int InitKepair(const NCContext* context, NCSecretKey* secKey, NCPublicKey static int TestKnownKeys(const NCContext* context); static int TestCorrectEncryption(const NCContext* context); +#ifdef NC_ENABLE_UTILS +static int TestUtilFunctions(void); +#endif + #ifndef NC_INPUT_VALIDATION_OFF static int TestPublicApiArgumentValidation(void); #endif @@ -167,6 +171,13 @@ static int RunTests(void) return 1; } +#ifdef NC_ENABLE_UTILS + if (TestUtilFunctions() != 0) + { + return 1; + } +#endif + TEST(NCDestroyContext(ctx), NC_SUCCESS) PRINTL("\nSUCCESS All tests passed") @@ -277,6 +288,8 @@ static int TestPublicApiArgumentValidation() NCEncryptionArgs cryptoData; + PRINTL("TEST: Public API argument validation tests") + { /* * Test arguments for encryption properties @@ -332,6 +345,7 @@ static int TestPublicApiArgumentValidation() TEST(NCSetEncryptionPropertyEx(&cryptoData, NC_ENC_SET_NIP04_KEY, testBuff32, NC_NIP04_AES_KEY_SIZE - 1), ARG_RANGE_ERROR_POS_3) } + /* Prep the crypto structure for proper usage */ ENSURE(NCSetEncryptionProperty(&cryptoData, NC_ENC_SET_VERSION, NC_ENC_VERSION_NIP44) == NC_SUCCESS); ENSURE(NCSetEncryptionPropertyEx(&cryptoData, NC_ENC_SET_NIP44_NONCE, nonce, sizeof(nonce)) == NC_SUCCESS); ENSURE(NCSetEncryptionPropertyEx(&cryptoData, NC_ENC_SET_NIP44_MAC_KEY, hmacKeyOut, sizeof(hmacKeyOut)) == NC_SUCCESS); @@ -339,14 +353,13 @@ static int TestPublicApiArgumentValidation() /* Assign the encryption material */ ENSURE(NCSetEncryptionData(&cryptoData, zero32, sig64, sizeof(zero32)) == NC_SUCCESS); - PRINTL("TEST: Public API argument validation tests") FillRandomData(ctxRandom, 32); FillRandomData(nonce, sizeof(nonce)); /* * Alloc context structure on the heap before use. - * THIS WILL LEAK IN THE CURRENT CONFIG ALWAYS FEE UNDER NORMAL CONDITIONS + * THIS WILL LEAK IN THE CURRENT CONFIG ALWAYS FREE UNDER NORMAL CONDITIONS */ ctx = (NCContext*)malloc(NCGetContextStructSize()); TASSERT(ctx != NULL) @@ -540,6 +553,8 @@ static int TestCorrectEncryption(const NCContext* context) NCEncryptionArgs cryptoData; NCMacVerifyArgs macVerifyArgs; + PRINTL("TEST: Correct encryption") + ENSURE(NCSetEncryptionProperty(&cryptoData, NC_ENC_SET_VERSION, NC_ENC_VERSION_NIP44) == NC_SUCCESS); ENSURE(NCSetEncryptionPropertyEx(&cryptoData, NC_ENC_SET_NIP44_NONCE, nonce, sizeof(nonce)) == NC_SUCCESS); ENSURE(NCSetEncryptionPropertyEx(&cryptoData, NC_ENC_SET_NIP44_MAC_KEY, hmacKeyOut, NC_HMAC_KEY_SIZE) == NC_SUCCESS); @@ -552,8 +567,6 @@ static int TestCorrectEncryption(const NCContext* context) macVerifyArgs.payload = cipherText; macVerifyArgs.payloadSize = TEST_ENC_DATA_SIZE; - PRINTL("TEST: Correct encryption") - /* init a sending and receiving key */ FillRandomData(&secKey1, sizeof(NCSecretKey)); FillRandomData(&secKey2, sizeof(NCSecretKey)); @@ -590,6 +603,38 @@ static int TestCorrectEncryption(const NCContext* context) return 0; } +#ifdef NC_ENABLE_UTILS + +#include + +/* +* This function is not currently public, but we can access it for testing +* purposes because it is used to calculate the output buffer size for encryption +*/ +extern NCResult NCUtilGetEncryptionPaddedSize(uint32_t encVersion, int32_t plaintextSize); + +/* Padding tests taken from the nip44 repo vectors.json file */ +const int32_t _padTestActual[24] = { 16, 32, 33, 37, 45, 49, 64, 65, 100, 111, 200, 250, 320, 383, 384, 400, 500, 512, 515, 700, 800, 900, 1020, 65536 }; +const int32_t _padTestExpected[24] = { 32, 32, 64, 64, 64, 64, 64, 96, 128, 128, 224, 256, 320, 384, 384, 448, 512, 512, 640, 768, 896, 1024, 1024, 65536 }; + +static int TestUtilFunctions(void) +{ + PRINTL("TEST: Util functions") + + for (int i = 0; i < 24; i++) + { + int32_t totalSize = _padTestExpected[i] + 67; + + TEST(NCUtilGetEncryptionPaddedSize(NC_ENC_VERSION_NIP44, _padTestActual[i]), _padTestExpected[i]); + TEST(NCUtilGetEncryptionBufferSize(NC_ENC_VERSION_NIP44, _padTestActual[i]), totalSize); + } + + PRINTL("PASSED: Util functions tests completed") + return 0; +} + +#endif + static void FillRandomData(void* pbBuffer, size_t length) { -- cgit From 12feb33dba2061415d6f39fa59dec16fafcda2a0 Mon Sep 17 00:00:00 2001 From: vnugent Date: Sun, 21 Jul 2024 17:51:04 -0400 Subject: Push latest changes, patches, and internal upgrades --- CMakeLists.txt | 31 ++-- Taskfile.yaml | 53 ++++-- include/noscrypt.h | 2 +- include/noscryptutil.h | 4 +- src/hkdf.c | 30 ++-- src/hkdf.h | 6 +- src/nc-crypto.c | 34 ++-- src/nc-crypto.h | 8 +- src/nc-util.h | 78 ++++++++- src/noscrypt.c | 12 +- src/noscryptutil.c | 451 ++++++++++++++++++++++++++---------------------- src/providers/bcrypt.c | 20 +-- src/providers/mbedtls.c | 42 ++--- tests/hex.h | 7 +- tests/test.c | 19 +- 15 files changed, 469 insertions(+), 328 deletions(-) (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index 493b18a..6dad383 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -143,21 +143,6 @@ target_include_directories(${_NC_PROJ_NAME}_static SYSTEM PUBLIC vendor/secp256k # ############################################# -#try to load openssl quietly in order to check for its availability -find_package(OpenSSL QUIET) - -#setup default linking to crypto libraries for certain plaftorms. -#Windows defaults to bcrypt, openssl otherwise if installed -if(CRYPTO_LIB STREQUAL "") - if(MSVC) - set(CRYPTO_LIB "bcrypt") - elseif(OPENSSL_FOUND) - set(CRYPTO_LIB "openssl") - endif() - - message(STATUS "No crypto library was specified, defaulting to ${CRYPTO_LIB}") -endif() - #Include mbedtls if enabled if(NC_FETCH_MBEDTLS) @@ -186,6 +171,22 @@ if(NC_FETCH_MBEDTLS) endif() +#try to load openssl quietly in order to check for its availability +find_package(OpenSSL QUIET) + +#setup default linking to crypto libraries for certain plaftorms. +#Windows defaults to bcrypt, openssl otherwise if installed +if(CRYPTO_LIB STREQUAL "") + if(MSVC) + set(CRYPTO_LIB "bcrypt") + elseif(OPENSSL_FOUND) + set(CRYPTO_LIB "openssl") + endif() + + message(STATUS "No crypto library was specified, defaulting to ${CRYPTO_LIB}") +endif() + + #if mbedtls linking is enabled target the library if(CRYPTO_LIB STREQUAL "mbedtls") diff --git a/Taskfile.yaml b/Taskfile.yaml index a79921c..93ea182 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -14,6 +14,7 @@ version: '3' vars: CMAKE_BUILD_DIR: 'build/{{ OS }}' + TEST_EXE_NAME: 'nctest' tasks: @@ -29,14 +30,6 @@ tasks: - task: build-internal vars: { CMAKE_TEST_STATUS: 'ON', BUILD_CONFIG: 'Debug' } - build-internal: - internal: true - cmds: - - cmake -S . -B{{.CMAKE_BUILD_DIR}} -DCMAKE_BUILD_TYPE={{.BUILD_CONFIG}} -DNC_BUILD_TESTS={{ .CMAKE_TEST_STATUS }} {{.CLI_ARGS}} - - cmake --build {{.CMAKE_BUILD_DIR}} --config {{.BUILD_CONFIG}} - - cmd: echo "Build complete. Your files can be found in the {{.CMAKE_BUILD_DIR}} directory" - silent: true - #available to users and vnbuild runner test: desc: "Builds a local copy of the library in a debug configuration, then runs the test executable" @@ -44,6 +37,37 @@ tasks: - task: build-debug - cmd: cd {{.CMAKE_BUILD_DIR}} && ctest -C Debug --verbose + test-mbedtls: + desc: "Builds and runs tests for noscrypt using the mbedtls crypto library for the current platform" + cmds: + - task: build-internal + vars: + CMAKE_TEST_STATUS: 'ON' + BUILD_CONFIG: 'Debug' + CLI_ARGS: '-DNC_FETCH_MBEDTLS=ON {{.CLI_ARGS}}' #fetches and enabled medtls + - cmd: cd {{.CMAKE_BUILD_DIR}} && ctest -C Debug --verbose + + test-dev: + desc: "Re-runs compilation phase and test execution" + cmds: + - task: compile + vars: { BUILD_CONFIG: 'Debug' } + - cmd: cd {{.CMAKE_BUILD_DIR}} && ctest -C Debug --verbose --output-on-failure + + compile: + internal: true + cmds: + - cmake --build {{.CMAKE_BUILD_DIR}} --config {{.BUILD_CONFIG}} + + build-internal: + internal: true + cmds: + - cmake -S . -B{{.CMAKE_BUILD_DIR}} -DCMAKE_BUILD_TYPE={{.BUILD_CONFIG}} -DNC_BUILD_TESTS={{ .CMAKE_TEST_STATUS }} {{.CLI_ARGS}} + - task: compile + vars: { BUILD_CONFIG: '{{.BUILD_CONFIG}}' } + - cmd: echo "Build complete. Your files can be found in the {{.CMAKE_BUILD_DIR}} directory" + silent: true + install: desc: "Uses cmake to install the library on your system" cmds: @@ -115,17 +139,26 @@ tasks: desc: "Packs up the project source code and creates a tarball in the builds binary directory" vars: TARGET_SOURCE: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/{{.PROJECT_NAME}}-src.tgz' - SOURCE_FILES: 'CMakeLists.txt src include license tests vendor readme.md Taskfile.yaml' + SOURCE_FILES: [ CMakeLists.txt, Taskfile.yaml, src, include, license, tests, vendor, readme.md, CMakePresets.json ] cmds: #tar up the source - - tar -czf "{{.TARGET_SOURCE}}" {{.SOURCE_FILES}} + - tar -czf "{{.TARGET_SOURCE}}" {{ .SOURCE_FILES | join " " }} ################################# # # DEV TASKS # ################################# + + dev-gdb-test: + platforms: [ linux ] + desc: "Starts a new gdb session on the test executable" + interactive: true + cmds: + - task: compile + vars: { BUILD_CONFIG: 'Debug' } + - cmd: gdb '{{.CMAKE_BUILD_DIR}}/{{.TEST_EXE_NAME}}' dev-update-deps: desc: "Updates vendored projects files (headers mostly) from their source repositories to the latest version" diff --git a/include/noscrypt.h b/include/noscrypt.h index 8b39f17..b91bc2b 100644 --- a/include/noscrypt.h +++ b/include/noscrypt.h @@ -58,7 +58,7 @@ extern "C" { #ifdef _NC_IS_WINDOWS #define NC_EXPORT __declspec(dllimport) #else - #define NC_EXPORT + #define NC_EXPORT extern #endif /* _NC_IS_WINDOWS */ #endif /* !NOSCRYPT_EXPORTING */ #endif /* !NC_EXPORT */ diff --git a/include/noscryptutil.h b/include/noscryptutil.h index 13b9231..a5e460f 100644 --- a/include/noscryptutil.h +++ b/include/noscryptutil.h @@ -39,11 +39,13 @@ extern "C" { #define E_CIPHER_INVALID_FORMAT -11 #define E_CIPHER_BAD_NONCE -12 #define E_CIPHER_MAC_INVALID -13 +#define E_CIPHER_NO_OUTPUT -14 #define NC_UTIL_CIPHER_MODE_ENCRYPT 0x00u #define NC_UTIL_CIPHER_MODE_DECRYPT 0x01u #define NC_UTIL_CIPHER_ZERO_ON_FREE 0x02u #define NC_UTIL_CIPHER_MAC_NO_VERIFY 0x04u +#define NC_UTIL_CIPHER_REUSEABLE 0x08u /* * The encryption context structure. This structure is used to store the state @@ -166,7 +168,7 @@ NC_EXPORT NCResult NC_CC NCUtilCipherGetFlags(const NCUtilCipherContext* ctx); * so the exact same operation should happen if called again. */ NC_EXPORT NCResult NC_CC NCUtilCipherUpdate( - const NCUtilCipherContext* encCtx, + NCUtilCipherContext* encCtx, const NCContext* libContext, const NCSecretKey* sk, const NCPublicKey* pk diff --git a/src/hkdf.c b/src/hkdf.c index cff7d60..ab661de 100644 --- a/src/hkdf.c +++ b/src/hkdf.c @@ -42,16 +42,15 @@ static _nc_fn_inline void debugValidateHandler(const struct nc_hkdf_fn_cb_struct cstatus_t hkdfExpandProcess( const struct nc_hkdf_fn_cb_struct* handler, void* ctx, - const cspan_t* info, - span_t* okm + cspan_t info, + span_t okm ) { cstatus_t result; - - uint8_t counter; + cspan_t tSpan, counterSpan; uint32_t tLen, okmOffset; + uint8_t counter[1]; uint8_t t[HKDF_IN_BUF_SIZE]; - cspan_t tSpan, counterSpan; debugValidateHandler(handler); @@ -59,18 +58,18 @@ cstatus_t hkdfExpandProcess( tLen = 0; /* T(0) is an empty string(zero length) */ okmOffset = 0; - counter = 1; /* counter is offset by 1 for init */ + counter[0] = 1; /* counter is offset by 1 for init */ result = CSTATUS_FAIL; /* Start in fail state */ /* counter as a span */ - ncSpanInitC(&counterSpan, &counter, sizeof(counter)); + ncSpanInitC(&counterSpan, counter, sizeof(counter)); /* Compute T(N) = HMAC(prk, T(n-1) | info | n) */ - while (okmOffset < okm->size) + while (okmOffset < okm.size) { ncSpanInitC(&tSpan, t, tLen); - if (handler->update(ctx, &tSpan) != CSTATUS_OK) + if (handler->update(ctx, tSpan) != CSTATUS_OK) { goto Exit; } @@ -80,7 +79,7 @@ cstatus_t hkdfExpandProcess( goto Exit; } - if (handler->update(ctx, &counterSpan) != CSTATUS_OK) + if (handler->update(ctx, counterSpan) != CSTATUS_OK) { goto Exit; } @@ -96,18 +95,15 @@ cstatus_t hkdfExpandProcess( } /* tlen becomes the hash size or remaining okm size */ - tLen = HKDF_MIN(okm->size - okmOffset, SHA256_DIGEST_SIZE); + tLen = HKDF_MIN(okm.size - okmOffset, SHA256_DIGEST_SIZE); DEBUG_ASSERT(tLen <= sizeof(t)); - /* write the T buffer back to okm */ - ncSpanWrite(*okm, okmOffset, t, tLen); - - /* shift base okm pointer by T */ - okmOffset += tLen; + /* write the T buffer back to okm and advance okmOffset by tLen */ + ncSpanAppend(okm, &okmOffset, t, tLen); /* increment counter */ - counter++; + (*counter)++; } result = CSTATUS_OK; /* HMAC operation completed, so set success */ diff --git a/src/hkdf.h b/src/hkdf.h index 2e3a55e..50ee6e8 100644 --- a/src/hkdf.h +++ b/src/hkdf.h @@ -42,7 +42,7 @@ /* typedefs for hdkf callback functions */ -typedef cstatus_t (*hmac_hash_fn)(void* ctx, const cspan_t* data); +typedef cstatus_t (*hmac_hash_fn)(void* ctx, cspan_t data); typedef cstatus_t (*hmac_finish_fn)(void* ctx, sha256_t hmacOut32); struct nc_hkdf_fn_cb_struct @@ -54,8 +54,8 @@ struct nc_hkdf_fn_cb_struct cstatus_t hkdfExpandProcess( const struct nc_hkdf_fn_cb_struct* handler, void* ctx, - const cspan_t* info, - span_t* okm + cspan_t info, + span_t okm ); #endif /* !_NC_HKDF_H */ diff --git a/src/nc-crypto.c b/src/nc-crypto.c index 99c072d..752c9b0 100644 --- a/src/nc-crypto.c +++ b/src/nc-crypto.c @@ -134,7 +134,7 @@ _IMPLSTB cstatus_t _dummyAesFunc( #define _IMPL_CRYPTO_SHA256_HKDF_EXTRACT _fallbackHkdfExtract - _IMPLSTB cstatus_t _fallbackHkdfExtract(const cspan_t* salt, const cspan_t* ikm, sha256_t prk) + _IMPLSTB cstatus_t _fallbackHkdfExtract(cspan_t salt, cspan_t ikm, sha256_t prk) { return _IMPL_CRYPTO_SHA256_HMAC(salt, ikm, prk); } @@ -217,11 +217,11 @@ uint32_t ncCryptoFixedTimeComp(const uint8_t* a, const uint8_t* b, uint32_t size return _IMPL_CRYPTO_FIXED_TIME_COMPARE(a, b, size); } -cstatus_t ncCryptoDigestSha256(const cspan_t* data, sha256_t digestOut32) +cstatus_t ncCryptoDigestSha256(cspan_t data, sha256_t digestOut32) { /* Debug arg validate */ - DEBUG_ASSERT2(data != NULL && data->data != NULL, "Expected data to be non-null") - DEBUG_ASSERT2(digestOut32 != NULL, "Expected digestOut32 to be non-null") + DEBUG_ASSERT2(ncSpanIsValidC(data), "Expected data to be non-null") + DEBUG_ASSERT2(digestOut32 != NULL, "Expected digestOut32 to be non-null") #ifndef _IMPL_CRYPTO_SHA256_DIGEST #error "No SHA256 implementation defined" @@ -230,12 +230,12 @@ cstatus_t ncCryptoDigestSha256(const cspan_t* data, sha256_t digestOut32) return _IMPL_CRYPTO_SHA256_DIGEST(data, digestOut32); } -cstatus_t ncCryptoHmacSha256(const cspan_t* key, const cspan_t* data, sha256_t hmacOut32) +cstatus_t ncCryptoHmacSha256(cspan_t key, cspan_t data, sha256_t hmacOut32) { /* Debug arg validate */ - DEBUG_ASSERT2(key != NULL && key->data != NULL, "Expected key to be non-null") - DEBUG_ASSERT2(data != NULL && data->data != NULL, "Expected data to be non-null") - DEBUG_ASSERT2(hmacOut32 != NULL && data->data != NULL, "Expected hmacOut32 to be non-null") + DEBUG_ASSERT2(ncSpanIsValidC(key), "Expected key to be non-null") + DEBUG_ASSERT2(ncSpanIsValidC(data), "Expected data to be non-null") + DEBUG_ASSERT2(hmacOut32 != NULL, "Expected hmacOut32 to be non-null") #ifndef _IMPL_CRYPTO_SHA256_HMAC #error "No SHA256 HMAC implementation defined" @@ -244,12 +244,12 @@ cstatus_t ncCryptoHmacSha256(const cspan_t* key, const cspan_t* data, sha256_t h return _IMPL_CRYPTO_SHA256_HMAC(key, data, hmacOut32); } -cstatus_t ncCryptoSha256HkdfExpand(const cspan_t* prk, const cspan_t* info, span_t* okm) +cstatus_t ncCryptoSha256HkdfExpand(cspan_t prk, cspan_t info, span_t okm) { /* Debug arg validate */ - DEBUG_ASSERT2(prk != NULL && prk->data != NULL, "Expected prk to be non-null") - DEBUG_ASSERT2(info != NULL && info->data != NULL, "Expected info to be non-null") - DEBUG_ASSERT2(okm != NULL && okm->data != NULL, "Expected okm to be non-null") + DEBUG_ASSERT2(ncSpanIsValidC(prk), "Expected prk to be non-null") + DEBUG_ASSERT2(ncSpanIsValidC(info), "Expected info to be non-null") + DEBUG_ASSERT2(ncSpanIsValid(okm), "Expected okm to be non-null") /* * RFC 5869: 2.3 @@ -258,7 +258,7 @@ cstatus_t ncCryptoSha256HkdfExpand(const cspan_t* prk, const cspan_t* info, span * important as the counter is 1 byte, so it cannot overflow */ - if(okm->size > (uint32_t)(0xFFu * SHA256_DIGEST_SIZE)) + if(okm.size > (uint32_t)(0xFFu * SHA256_DIGEST_SIZE)) { return CSTATUS_FAIL; } @@ -270,12 +270,12 @@ cstatus_t ncCryptoSha256HkdfExpand(const cspan_t* prk, const cspan_t* info, span return _IMPL_CRYPTO_SHA256_HKDF_EXPAND(prk, info, okm); } -cstatus_t ncCryptoSha256HkdfExtract(const cspan_t* salt, const cspan_t* ikm, sha256_t prk) +cstatus_t ncCryptoSha256HkdfExtract(cspan_t salt, cspan_t ikm, sha256_t prk) { /* Debug arg validate */ - DEBUG_ASSERT2(salt != NULL, "Expected salt to be non-null") - DEBUG_ASSERT2(ikm != NULL, "Expected ikm to be non-null") - DEBUG_ASSERT2(prk != NULL, "Expected prk to be non-null") + DEBUG_ASSERT2(ncSpanIsValidC(salt), "Expected salt to be non-null") + DEBUG_ASSERT2(ncSpanIsValidC(ikm), "Expected ikm to be non-null") + DEBUG_ASSERT2(prk != NULL, "Expected prk to be non-null") #ifndef _IMPL_CRYPTO_SHA256_HKDF_EXTRACT #error "No SHA256 HKDF extract implementation defined" diff --git a/src/nc-crypto.h b/src/nc-crypto.h index 11da6d3..a1545de 100644 --- a/src/nc-crypto.h +++ b/src/nc-crypto.h @@ -42,13 +42,13 @@ uint32_t ncCryptoFixedTimeComp(const uint8_t* a, const uint8_t* b, uint32_t size void ncCryptoSecureZero(void* ptr, uint32_t size); -cstatus_t ncCryptoDigestSha256(const cspan_t* data, sha256_t digestOut32); +cstatus_t ncCryptoDigestSha256(cspan_t data, sha256_t digestOut32); -cstatus_t ncCryptoHmacSha256(const cspan_t* key, const cspan_t* data, sha256_t hmacOut32); +cstatus_t ncCryptoHmacSha256(cspan_t key, cspan_t data, sha256_t hmacOut32); -cstatus_t ncCryptoSha256HkdfExpand(const cspan_t* prk, const cspan_t* info, span_t* okm); +cstatus_t ncCryptoSha256HkdfExpand(cspan_t prk, cspan_t info, span_t okm); -cstatus_t ncCryptoSha256HkdfExtract(const cspan_t* salt, const cspan_t* ikm, sha256_t prk); +cstatus_t ncCryptoSha256HkdfExtract(cspan_t salt, cspan_t ikm, sha256_t prk); cstatus_t ncCryptoChacha20( const uint8_t key[CHACHA_KEY_SIZE], diff --git a/src/nc-util.h b/src/nc-util.h index d0afe28..2ddfd3f 100644 --- a/src/nc-util.h +++ b/src/nc-util.h @@ -102,6 +102,26 @@ typedef struct read_only_memory_span_struct uint32_t size; } cspan_t; +static _nc_fn_inline int ncSpanIsValid(span_t span) +{ + return span.data != NULL; +} + +static _nc_fn_inline int ncSpanIsValidC(cspan_t span) +{ + return span.data != NULL; +} + +static _nc_fn_inline int ncSpanIsValidRange(span_t span, uint32_t offset, uint32_t size) +{ + return ncSpanIsValid(span) && offset + size <= span.size; +} + +static _nc_fn_inline int ncSpanIsValidRangeC(cspan_t span, uint32_t offset, uint32_t size) +{ + return ncSpanIsValidC(span) && offset + size <= span.size; +} + static _nc_fn_inline void ncSpanInitC(cspan_t* span, const uint8_t* data, uint32_t size) { span->data = data; @@ -114,9 +134,25 @@ static _nc_fn_inline void ncSpanInit(span_t* span, uint8_t* data, uint32_t size) span->size = size; } +static _nc_fn_inline const uint8_t* ncSpanGetOffsetC(cspan_t span, uint32_t offset) +{ + DEBUG_ASSERT2(ncSpanIsValidC(span), "Expected span to be non-null"); + DEBUG_ASSERT2(offset < span.size, "Expected offset to be less than span size"); + + return span.data + offset; +} + +static _nc_fn_inline uint8_t* ncSpanGetOffset(span_t span, uint32_t offset) +{ + DEBUG_ASSERT2(ncSpanIsValid(span), "Expected span to be non-null"); + DEBUG_ASSERT2(offset < span.size, "Expected offset to be less than span size"); + + return span.data + offset; +} + static _nc_fn_inline void ncSpanWrite(span_t span, uint32_t offset, const uint8_t* data, uint32_t size) { - DEBUG_ASSERT2(span.data != NULL, "Expected span to be non-null") + DEBUG_ASSERT2(ncSpanIsValid(span), "Expected span to be non-null") DEBUG_ASSERT2(data != NULL, "Expected data to be non-null") DEBUG_ASSERT2(offset + size <= span.size, "Expected offset + size to be less than span size") @@ -126,7 +162,7 @@ static _nc_fn_inline void ncSpanWrite(span_t span, uint32_t offset, const uint8_ static _nc_fn_inline void ncSpanAppend(span_t span, uint32_t* offset, const uint8_t* data, uint32_t size) { - DEBUG_ASSERT2(span.data != NULL, "Expected span to be non-null") + DEBUG_ASSERT2(ncSpanIsValid(span), "Expected span to be non-null") DEBUG_ASSERT2(offset != NULL, "Expected offset to be non-null") DEBUG_ASSERT2(data != NULL, "Expected data to be non-null") DEBUG_ASSERT2(*offset + size <= span.size, "Expected offset + size to be less than span size") @@ -142,7 +178,7 @@ static _nc_fn_inline span_t ncSpanSlice(span_t span, uint32_t offset, uint32_t s { span_t slice; - DEBUG_ASSERT2(span.data != NULL, "Expected span to be non-null"); + DEBUG_ASSERT2(ncSpanIsValid(span), "Expected span to be non-null"); DEBUG_ASSERT2(offset + size <= span.size, "Expected offset + size to be less than span size") /* Initialize slice, offset input data by the specified offset */ @@ -155,7 +191,7 @@ static _nc_fn_inline cspan_t ncSpanSliceC(cspan_t span, uint32_t offset, uint32_ { cspan_t slice; - DEBUG_ASSERT2(span.data != NULL, "Expected span to be non-null"); + DEBUG_ASSERT2(ncSpanIsValidC(span), "Expected span to be non-null"); DEBUG_ASSERT2(offset + size <= span.size, "Expected offset + size to be less than span size") /* Initialize slice, offset input data by the specified offset */ @@ -164,5 +200,39 @@ static _nc_fn_inline cspan_t ncSpanSliceC(cspan_t span, uint32_t offset, uint32_ return slice; } +static _nc_fn_inline void ncSpanCopyC(cspan_t src, span_t dest) +{ + DEBUG_ASSERT2(ncSpanIsValidC(src), "Expected span to be non-null"); + DEBUG_ASSERT2(ncSpanIsValid(dest), "Expected offset + size to be less than span size"); + DEBUG_ASSERT2(dest.size >= src.size, "Output buffer too small. Overrun detected"); + + /* Copy data to span */ + MEMMOV(dest.data, src.data, src.size); +} + +static _nc_fn_inline void ncSpanCopy(span_t src, span_t dest) +{ + cspan_t csrc; + + ncSpanInitC(&csrc, src.data, src.size); + ncSpanCopyC(csrc, dest); +} + +static _nc_fn_inline void ncSpanReadC(cspan_t src, uint8_t* dest, uint32_t size) +{ + span_t dsts; + + ncSpanInit(&dsts, dest, size); + ncSpanCopyC(src, dsts); +} + +static _nc_fn_inline void ncSpanRead(span_t src, uint8_t* dest, uint32_t size) +{ + cspan_t srcs; + + ncSpanInitC(&srcs, src.data, src.size); + ncSpanReadC(srcs, dest, size); +} + #endif /* !_NC_UTIL_H */ \ No newline at end of file diff --git a/src/noscrypt.c b/src/noscrypt.c index f3c28cb..46b3d65 100644 --- a/src/noscrypt.c +++ b/src/noscrypt.c @@ -244,7 +244,9 @@ static _nc_fn_inline NCResult _computeConversationKey( ncSpanInitC(&saltSpan, Nip44ConstantSalt, sizeof(Nip44ConstantSalt)); ncSpanInitC(&ikmSpan, sharedSecret->value, NC_SHARED_SEC_SIZE); - return ncCryptoSha256HkdfExtract(&saltSpan, &ikmSpan, ck->value) == CSTATUS_OK ? NC_SUCCESS : E_OPERATION_FAILED; + return ncCryptoSha256HkdfExtract(saltSpan, ikmSpan, ck->value) == CSTATUS_OK + ? NC_SUCCESS + : E_OPERATION_FAILED; } @@ -286,7 +288,7 @@ static _nc_fn_inline cstatus_t _getMessageKey( ncSpanInit(&okmSpan, messageKey->value, sizeof(struct message_key)); /* Output produces a message key (write it directly to struct memory) */ /* Nonce is the info */ - return ncCryptoSha256HkdfExpand(&prkSpan, &nonce, &okmSpan); + return ncCryptoSha256HkdfExpand(prkSpan, nonce, okmSpan); } static _nc_fn_inline NCResult _encryptNip44Ex( @@ -380,7 +382,7 @@ static _nc_fn_inline cstatus_t _computeHmac(const uint8_t key[NC_HMAC_KEY_SIZE], ncSpanInitC(&keySpan, key, NC_HMAC_KEY_SIZE); - return ncCryptoHmacSha256(&keySpan, &payload, hmacOut); + return ncCryptoHmacSha256(keySpan, payload, hmacOut); } static NCResult _verifyMacEx( @@ -650,7 +652,7 @@ NC_EXPORT NCResult NC_CC NCSignData( ncSpanInitC(&dataSpan, data, dataSize); /* Compute sha256 of the data before signing */ - if(ncCryptoDigestSha256(&dataSpan, digest) != CSTATUS_OK) + if(ncCryptoDigestSha256(dataSpan, digest) != CSTATUS_OK) { return E_INVALID_ARG; } @@ -708,7 +710,7 @@ NC_EXPORT NCResult NC_CC NCVerifyData( ncSpanInitC(&dataSpan, data, dataSize); /* Compute sha256 of the data before verifying */ - if (ncCryptoDigestSha256(&dataSpan, digest) != CSTATUS_OK) + if (ncCryptoDigestSha256(dataSpan, digest) != CSTATUS_OK) { return E_INVALID_ARG; } diff --git a/src/noscryptutil.c b/src/noscryptutil.c index 97526d9..56acb1b 100644 --- a/src/noscryptutil.c +++ b/src/noscryptutil.c @@ -34,6 +34,23 @@ #error "Utilities library must be disabled when using extreme compat mode" #endif /* NC_EXTREME_COMPAT */ +#define MIN_PADDING_SIZE 0x20u +#define NIP44_VERSION_SIZE 0x01u +#define NIP44_PT_LEN_SIZE sizeof(uint16_t) + +/* +* minimum size for a valid nip44 payload +* 1 byte version + 32 byte nonce + 32 byte mac + 2 byte ptSize + 32bytes minimum length +*/ +#define NIP44_MIN_PAYLOAD_SIZE (NIP44_VERSION_SIZE + 0x20 + 0x02 + 0x20 + 0x02) + +/* +* The minimum ciphertext size is the minimum padded size + the minimum +* size of the plaintext length field +*/ +#define NIP44_MIN_CIPHERTEXT_SIZE (MIN_PADDING_SIZE + NIP44_PT_LEN_SIZE) + + #define _nc_mem_free(x) if(x != NULL) { free(x); x = NULL; } #define _nc_mem_alloc(elements, size) calloc(elements, size); #define ZERO_FILL ncCryptoSecureZero @@ -51,7 +68,6 @@ #define CHECK_ARG_IS(is, expected, argPos) #endif /* !NC_DISABLE_INPUT_VALIDATION */ - #ifdef _NC_IS_WINDOWS #include @@ -73,38 +89,24 @@ } #endif -#define MIN_PADDING_SIZE 0x20u -#define NIP44_VERSION_SIZE 0x01u -#define NIP44_PT_LEN_SIZE sizeof(uint16_t) - -/* -* minimum size for a valid nip44 payload -* 1 byte version + 32 byte nonce + 32 byte mac + 2 byte ptSize + 32bytes minimum length -*/ -#define NIP44_MIN_PAYLOAD_SIZE (NIP44_VERSION_SIZE + 0x20 + 0x02 + 0x20 + 0x02) - -/* -* The minimum ciphertext size is the minimum padded size + the minimum -* size of the plaintext length field -*/ -#define NIP44_MIN_CIPHERTEXT_SIZE (MIN_PADDING_SIZE + NIP44_PT_LEN_SIZE) - - /* Currently were on nip44 version 2 */ static const uint8_t Nip44VersionValue[1] = { 0x02u }; -struct nc_util_enc_struct { +struct cipher_buffer_state { + + cspan_t input; + span_t output; - uint32_t _flags; + cspan_t actualOutput; +}; - cspan_t cipherInput; +struct nc_util_enc_struct { - /* - The data this span points to is allocated during initialization - */ - span_t cipherOutput; + uint32_t _flags; NCEncryptionArgs encArgs; + + struct cipher_buffer_state buffer; }; static _nc_fn_inline span_t _ncUtilAllocSpan(uint32_t count, size_t size) @@ -126,6 +128,11 @@ static _nc_fn_inline span_t _ncUtilAllocSpan(uint32_t count, size_t size) return span; } +static _nc_fn_inline void _ncUtilZeroSpan(span_t span) +{ + ZERO_FILL(span.data, span.size); +} + static _nc_fn_inline void _ncUtilFreeSpan(span_t span) { _nc_mem_free(span.data); @@ -198,7 +205,7 @@ static _nc_fn_inline uint32_t _calcNip44TotalOutSize(uint32_t inputSize) return bufferSize; } -static _nc_fn_inline cspan_t _nip44GetMacData(cspan_t payload) +static _nc_fn_inline span_t _nip44GetMacData(span_t payload) { DEBUG_ASSERT(payload.size > NIP44_VERSION_SIZE + NC_ENCRYPTION_MAC_SIZE); @@ -216,7 +223,7 @@ static _nc_fn_inline cspan_t _nip44GetMacData(cspan_t payload) * macData = ct.size - version.size + mac.size */ - return ncSpanSliceC( + return ncSpanSlice( payload, NIP44_VERSION_SIZE, payload.size - (NIP44_VERSION_SIZE + NC_ENCRYPTION_MAC_SIZE) @@ -237,70 +244,105 @@ static _nc_fn_inline span_t _nip44GetMacOutput(span_t payload) ); } -static _nc_fn_inline cspan_t _nip44ParseMac(cspan_t payload) +static _nc_fn_inline int _nip44ParseSegments( + cspan_t payload, + cspan_t* nonce, + cspan_t* mac, + cspan_t* macData, + cspan_t* cipherText +) { - DEBUG_ASSERT(payload.size >= NIP44_MIN_PAYLOAD_SIZE); + if (payload.size < NIP44_MIN_PAYLOAD_SIZE) + { + return 0; + } + + /* slice after the version and before the mac segments */ + *nonce = ncSpanSliceC( + payload, + NIP44_VERSION_SIZE, + NC_ENCRYPTION_NONCE_SIZE + ); /* * Mac is the final 32 bytes of the ciphertext buffer */ - return ncSpanSliceC( + *mac = ncSpanSliceC( payload, payload.size - NC_ENCRYPTION_MAC_SIZE, NC_ENCRYPTION_MAC_SIZE ); -} -static _nc_fn_inline cspan_t _nip44ParseCipherText(cspan_t payload) -{ - DEBUG_ASSERT(payload.size >= NIP44_MIN_PAYLOAD_SIZE); + /* + * The mac data is the nonce+ct segment of the buffer for mac computation. + */ + *macData = ncSpanSliceC( + payload, + NIP44_VERSION_SIZE, + payload.size - (NIP44_VERSION_SIZE + NC_ENCRYPTION_MAC_SIZE) + ); - /* ct is all of the data after the nonce and before the mac segment */ - return ncSpanSliceC( + /* + * Ciphertext is after the nonce segment and before the mac segment + */ + *cipherText = ncSpanSliceC( payload, NIP44_VERSION_SIZE + NC_ENCRYPTION_NONCE_SIZE, payload.size - (NIP44_VERSION_SIZE + NC_ENCRYPTION_NONCE_SIZE + NC_ENCRYPTION_MAC_SIZE) ); + + return 1; } -static _nc_fn_inline cspan_t _nip44ParseNonce(cspan_t payload) + +static _nc_fn_inline void _cipherPublishOutput(NCUtilCipherContext* buffer, uint32_t offset, uint32_t size) { - DEBUG_ASSERT(payload.size >= NIP44_MIN_PAYLOAD_SIZE); + span_t slice; - /* slice after the version and before the mac segments */ - return ncSpanSliceC( - payload, - NIP44_VERSION_SIZE, - NC_ENCRYPTION_NONCE_SIZE - ); + DEBUG_ASSERT(ncSpanIsValid(buffer->buffer.output)); + + if (size == 0) + { + ncSpanInitC(&buffer->buffer.actualOutput, NULL, 0); + } + else + { + /* use slice for debug guards */ + slice = ncSpanSlice(buffer->buffer.output, offset, size); + ncSpanInitC(&buffer->buffer.actualOutput, slice.data, slice.size); + } } +/* +* I want the encryption/decyption functions to be indempodent +* meaning all mutations that happen can be repeated without +* side effects. IE no perminent state changes that can't be +* undone. +*/ + static NCResult _nip44EncryptCompleteCore( const NCContext* libContext, const NCSecretKey* sk, const NCPublicKey* pk, - NCEncryptionArgs encArgs, - cspan_t plainText, - span_t payload + NCUtilCipherContext* state ) { NCResult result; - cspan_t macData, cPayload; - span_t macOutput; - uint32_t outPos, paddedCtSize; + cspan_t plainText; + span_t macData, macOutput, payload; + uint32_t outPos; uint8_t ptSize[NIP44_PT_LEN_SIZE]; uint8_t hmacKeyOut[NC_ENCRYPTION_MAC_SIZE]; + NCEncryptionArgs encArgs; outPos = 0; + encArgs = state->encArgs; + payload = state->buffer.output; + plainText = state->buffer.input; DEBUG_ASSERT(encArgs.version == NC_ENC_VERSION_NIP44); - ncSpanInitC(&cPayload, payload.data, payload.size); - - /* Padded size is required to know how large the CT buffer is for encryption */ - paddedCtSize = _calcNip44PtPadding(plainText.size); - /* Start by appending the version number */ ncSpanAppend(payload, &outPos, Nip44VersionValue, sizeof(Nip44VersionValue)); @@ -343,9 +385,9 @@ static NCResult _nip44EncryptCompleteCore( result = NCSetEncryptionData( &encArgs, - (payload.data + outPos), /* in place encryption */ - (payload.data + outPos), - paddedCtSize + NIP44_PT_LEN_SIZE /* Plaintext + pt size must be encrypted */ + ncSpanGetOffset(payload, outPos), /* in place encryption */ + ncSpanGetOffset(payload, outPos), + NIP44_PT_LEN_SIZE + _calcNip44PtPadding(plainText.size) /* Plaintext + pt size must be encrypted */ ); DEBUG_ASSERT(result == NC_SUCCESS); @@ -363,7 +405,7 @@ static NCResult _nip44EncryptCompleteCore( * the plaintext data, followed by zero padding. */ - ncSpanWrite(payload, outPos, ptSize, NIP44_PT_LEN_SIZE); + ncSpanWrite(payload, outPos, ptSize, sizeof(ptSize)); ncSpanWrite( payload, @@ -387,15 +429,15 @@ static NCResult _nip44EncryptCompleteCore( this helper captures that data segment into a span */ - macData = _nip44GetMacData(cPayload); + macData = _nip44GetMacData(payload); macOutput = _nip44GetMacOutput(payload); result = NCComputeMac( libContext, hmacKeyOut, - macData.data, + ncSpanGetOffset(macData, 0), macData.size, - macOutput.data + ncSpanGetOffset(macOutput, 0) ); if (result != NC_SUCCESS) @@ -407,6 +449,9 @@ static NCResult _nip44EncryptCompleteCore( DEBUG_ASSERT2(outPos == payload.size, "Buffer under/overflow detected"); + /* publish all payload bytes to output */ + _cipherPublishOutput(state, 0, outPos); + /* zero hmac key before returning */ ZERO_FILL(hmacKeyOut, sizeof(hmacKeyOut)); @@ -418,45 +463,55 @@ static NCResult _nip44DecryptCompleteCore( const NCContext* libContext, const NCSecretKey* recvKey, const NCPublicKey* sendKey, - const NCUtilCipherContext* cipher + NCUtilCipherContext* state ) { NCResult result; NCMacVerifyArgs macArgs; NCEncryptionArgs encArgs; - cspan_t macData, macValue, cipherText, nonce; + cspan_t macData, macValue, nonce, payload, cipherText; + span_t output; + uint16_t ptSize; - DEBUG_ASSERT(libContext && recvKey && sendKey && cipher); - DEBUG_ASSERT(cipher->encArgs.version == NC_ENC_VERSION_NIP44); + DEBUG_ASSERT(libContext && recvKey && sendKey && state); + DEBUG_ASSERT(state->encArgs.version == NC_ENC_VERSION_NIP44); + DEBUG_ASSERT(state->buffer.input.size >= NIP44_MIN_PAYLOAD_SIZE); /* ensure decryption mode */ - DEBUG_ASSERT(cipher->_flags & NC_UTIL_CIPHER_MODE_DECRYPT); + DEBUG_ASSERT(state->_flags & NC_UTIL_CIPHER_MODE_DECRYPT); /* store local stack copy for safe mutation */ - encArgs = cipher->encArgs; + encArgs = state->encArgs; + payload = state->buffer.input; + output = state->buffer.output; - nonce = _nip44ParseNonce(cipher->cipherInput); + /* + * Copy the input buffer to the output buffer because the + * decryption happens in-place and needs a writable buffer + * + * After the operation is complete, we will assign the actual plaintext + * data to the actual output buffer + */ - /* Verify mac if the user allowed it */ - if ((cipher->_flags & NC_UTIL_CIPHER_MAC_NO_VERIFY) == 0) - { - /* - * The mac data to verify against is the nonce+ciphertext data - * from within the nip44 message payload - */ + DEBUG_ASSERT2(ncSpanIsValid(output), "Output buffer was not allocated"); - macData = _nip44GetMacData(cipher->cipherInput); - macValue = _nip44ParseMac(cipher->cipherInput); + if (!_nip44ParseSegments(payload, &nonce, &macValue, &macData, &cipherText)) + { + return E_CIPHER_INVALID_FORMAT; + } + /* Verify mac if the user allowed it */ + if ((state->_flags & NC_UTIL_CIPHER_MAC_NO_VERIFY) == 0) + { DEBUG_ASSERT(macValue.size == NC_ENCRYPTION_MAC_SIZE); - DEBUG_ASSERT(macData.size > NC_ENCRYPTION_NONCE_SIZE + 0x20); + DEBUG_ASSERT(macData.size > NC_ENCRYPTION_NONCE_SIZE + MIN_PADDING_SIZE); /* Assign the mac data to the mac verify args */ - macArgs.mac32 = macValue.data; - macArgs.nonce32 = nonce.data; + macArgs.mac32 = ncSpanGetOffsetC(macValue, 0); + macArgs.nonce32 = ncSpanGetOffsetC(nonce, 0); /* payload for verifying a mac in nip44 is the nonce+ciphertext */ - macArgs.payload = macData.data; + macArgs.payload = ncSpanGetOffsetC(macData, 0); macArgs.payloadSize = macData.size; /* Verify the mac */ @@ -474,44 +529,60 @@ static NCResult _nip44DecryptCompleteCore( } } - cipherText = _nip44ParseCipherText(cipher->cipherInput); - - DEBUG_ASSERT2(cipherText.size >= MIN_PADDING_SIZE, "Cipertext segment was parsed incorrectly. Too small"); - - /* manually sign nonce */ - encArgs.nonceData = nonce.data; - - /* - * Remember the decryption operation is symmetric, it reads the input bytes and writes - * directly to the output. - * - * The decryption is performed on the ciphertext segment and we can write the output - * directly the output buffer. - * - * The leading 2 bytes will be the encoded plaintext size, followed by the plaintext data - * and padding. That's okay. The user will call NCUtilCipherGetOutputSize to get the - * actual size of the plaintext, which will exlcude the leading 2 bytes and padding. + /* + * manually assign nonce because it's a constant pointer which + * is not allowed when calling setproperty */ + encArgs.nonceData = ncSpanGetOffsetC(nonce, 0); - DEBUG_ASSERT(cipher->cipherOutput.size >= cipherText.size); - + DEBUG_ASSERT2(cipherText.size >= MIN_PADDING_SIZE, "Cipertext segment was parsed incorrectly. Too small"); + result = NCSetEncryptionData( &encArgs, - cipherText.data, - cipher->cipherOutput.data, + ncSpanGetOffsetC(cipherText, 0), + ncSpanGetOffset(output, 0), /*decrypt ciphertext and write directly to the output buffer */ cipherText.size ); + DEBUG_ASSERT(result == NC_SUCCESS); + + /* + * If decryption was successful, the data should be written + * directly to the output buffer + */ + result = NCDecrypt(libContext, recvKey, sendKey, &encArgs); + if (result != NC_SUCCESS) { return result; } /* - * If decryption was successful, the data should be written - * directly to the output buffer + * Parse CT length and assign the output buffer. + * + * PT size is stored at the beginning of the ciphertext + * segment and is 2 bytes in size, big endian. */ - result = NCDecrypt(libContext, recvKey, sendKey, &encArgs); + + ptSize = (uint16_t)(output.data[0] << 8 | output.data[1]); + + /* + * If the PT is corrupted or set maliciously, it can overrun + * the current buffer. The PT size must be less than the + * ciphertext size. + */ + if (!ncSpanIsValidRange(output, NIP44_PT_LEN_SIZE, ptSize)) + { + return E_OPERATION_FAILED; + } + + /* + * actual output span should now point to the decrypted plaintext + * data segment + */ + _cipherPublishOutput(state, NIP44_PT_LEN_SIZE, ptSize); + + DEBUG_ASSERT(state->buffer.actualOutput.size < cipherText.size); return result; } @@ -582,13 +653,13 @@ NC_EXPORT void NC_CC NCUtilCipherFree(NCUtilCipherContext* encCtx) * If zero on free flag is set, we can zero all output memory * before returning the buffer back to the heap */ - if ((encCtx->_flags & NC_UTIL_CIPHER_ZERO_ON_FREE) > 0 && encCtx->cipherOutput.data) + if ((encCtx->_flags & NC_UTIL_CIPHER_ZERO_ON_FREE) > 0 && ncSpanIsValid(encCtx->buffer.output)) { - ZERO_FILL(encCtx->cipherOutput.data, encCtx->cipherOutput.size); + _ncUtilZeroSpan(encCtx->buffer.output); } - /* Free output buffers */ - _ncUtilFreeSpan(encCtx->cipherOutput); + /* Free output buffers (null buffers are allowed) */ + _ncUtilFreeSpan(encCtx->buffer.output); /* context can be released */ _nc_mem_free(encCtx); @@ -604,14 +675,12 @@ NC_EXPORT NCResult NC_CC NCUtilCipherInit( CHECK_NULL_ARG(encCtx, 0); CHECK_NULL_ARG(inputData, 1); - /* The output state must not have alraedy been allocated */ - CHECK_ARG_IS(encCtx->cipherOutput.data == NULL, 0); if ((encCtx->_flags & NC_UTIL_CIPHER_MODE_DECRYPT) > 0) { /* * Validate the input data for proper format for - * the current cipher version + * the current state version */ switch (encCtx->encArgs.version) { @@ -652,7 +721,7 @@ NC_EXPORT NCResult NC_CC NCUtilCipherInit( { /* * Calculate the correct output size to store the encryption - * data for the given cipher version + * data for the given state version */ outputSize = NCUtilGetEncryptionBufferSize(encCtx->encArgs.version, inputSize); } @@ -662,15 +731,48 @@ NC_EXPORT NCResult NC_CC NCUtilCipherInit( return outputSize; } + /* + * If the buffer was previously allocated, the reuseable flag + * must be set to allow the buffer to be re-used for another + * operation. + */ + + if (ncSpanIsValid(encCtx->buffer.output)) + { + CHECK_ARG_IS((encCtx->_flags & NC_UTIL_CIPHER_REUSEABLE) > 0, 0); + + /* + * if the existing buffer is large enough to hold the new + * data reuse it, otherwise free it and allocate a new buffer + */ + + if (outputSize <= encCtx->buffer.output.size) + { + _ncUtilZeroSpan(encCtx->buffer.output); + + goto AssignInputAndExit; + } + else + { + _ncUtilFreeSpan(encCtx->buffer.output); + } + } + /* Alloc output buffer within the struct */ - encCtx->cipherOutput = _ncUtilAllocSpan((uint32_t)outputSize, sizeof(uint8_t)); + encCtx->buffer.output = _ncUtilAllocSpan((uint32_t)outputSize, sizeof(uint8_t)); - if (!encCtx->cipherOutput.data) + if (!ncSpanIsValid(encCtx->buffer.output)) { return E_OUT_OF_MEMORY; } - ncSpanInitC(&encCtx->cipherInput, inputData, inputSize); +AssignInputAndExit: + + /* Confirm output was allocated */ + DEBUG_ASSERT(ncSpanIsValid(encCtx->buffer.output)); + + /* Assign the input data span to point to the assigned input data */ + ncSpanInitC(&encCtx->buffer.input, inputData, inputSize); return NC_SUCCESS; } @@ -684,48 +786,14 @@ NC_EXPORT NCResult NC_CC NCUtilCipherGetFlags(const NCUtilCipherContext* ctx) NC_EXPORT NCResult NC_CC NCUtilCipherGetOutputSize(const NCUtilCipherContext* encCtx) { - uint16_t nip44PtSize; - CHECK_NULL_ARG(encCtx, 0); - /* - * if nip44 decryption is desired, the output buffer will be - * overallocated. It will also contain some padding bytes - * so we need to parse the plaintext size from the buffer - * and return that as the output size. - */ - if (encCtx->encArgs.version == NC_ENC_VERSION_NIP44 - && (encCtx->_flags & NC_UTIL_CIPHER_MODE_DECRYPT) > 0) + if (!ncSpanIsValidC(encCtx->buffer.actualOutput)) { - - /* ensure the output has been allocated correctly */ - if (encCtx->cipherOutput.size < NIP44_PT_LEN_SIZE) - { - return E_INVALID_CONTEXT; - } - - /* - * If a decryption operation was performed the leading 2 bytes will - * be the big-endian encoded plaintext size. This function should - * return the size of the plaintext data, not the entire buffer. - */ - - nip44PtSize = (encCtx->cipherOutput.data[0] << 8) | encCtx->cipherOutput.data[1]; - - /* - * If improperly decryption/formatted, the pt size may be some really large - * number when decoded, so make sure it doesn't point to a location outside - * the buffer, that would be invalid - */ - if (nip44PtSize > (encCtx->cipherOutput.size - NIP44_PT_LEN_SIZE)) - { - return E_CIPHER_INVALID_FORMAT; - } - - return (NCResult)nip44PtSize; + return E_CIPHER_NO_OUTPUT; } - return (NCResult)(encCtx->cipherOutput.size); + return (NCResult)(encCtx->buffer.actualOutput.size); } NC_EXPORT NCResult NC_CC NCUtilCipherReadOutput( @@ -734,55 +802,24 @@ NC_EXPORT NCResult NC_CC NCUtilCipherReadOutput( uint32_t outputSize ) { - NCResult result; - - CHECK_NULL_ARG(encCtx, 0) - CHECK_NULL_ARG(output, 1) - - /* - * Again if in nip44 decrypt mode we only want the - * actual plaintext data - */ + CHECK_NULL_ARG(encCtx, 0); + CHECK_NULL_ARG(output, 1); - if (encCtx->encArgs.version == NC_ENC_VERSION_NIP44 - && (encCtx->_flags & NC_UTIL_CIPHER_MODE_DECRYPT) > 0) + if (!ncSpanIsValidC(encCtx->buffer.actualOutput)) { - result = NCUtilCipherGetOutputSize(encCtx); - - if (result < 0) - { - return result; - } - - DEBUG_ASSERT((result + NIP44_PT_LEN_SIZE) < encCtx->cipherOutput.size); - - /* Make sure the output buffer is large enough */ - CHECK_ARG_RANGE(outputSize, result, UINT32_MAX, 2); - - /* - * Plaintext data sits directly after the length bytes - * and up to the length of the plaintext size - */ - MEMMOV( - output, - encCtx->cipherOutput.data + NIP44_PT_LEN_SIZE, - (uint32_t)result - ); - - return result; + return E_CIPHER_NO_OUTPUT; } - else - { - CHECK_ARG_RANGE(outputSize, encCtx->cipherOutput.size, UINT32_MAX, 2); - MEMMOV( - output, - encCtx->cipherOutput.data, - encCtx->cipherOutput.size - ); + /* Buffer must be as large as the output data */ + CHECK_ARG_RANGE(outputSize, encCtx->buffer.actualOutput.size, UINT32_MAX, 2); - return (NCResult)encCtx->cipherOutput.size; - } + ncSpanReadC( + encCtx->buffer.actualOutput, + output, + outputSize + ); + + return (NCResult)encCtx->buffer.actualOutput.size; } NC_EXPORT NCResult NCUtilCipherSetProperty( @@ -804,7 +841,7 @@ NC_EXPORT NCResult NCUtilCipherSetProperty( } NC_EXPORT NCResult NC_CC NCUtilCipherUpdate( - const NCUtilCipherContext* encCtx, + NCUtilCipherContext* encCtx, const NCContext* libContext, const NCSecretKey* sk, const NCPublicKey* pk @@ -816,15 +853,18 @@ NC_EXPORT NCResult NC_CC NCUtilCipherUpdate( CHECK_NULL_ARG(pk, 3); /* Make sure input & output buffers have been assigned/allocated */ - if (encCtx->cipherOutput.data == NULL) + if (!ncSpanIsValid(encCtx->buffer.output)) { return E_INVALID_CONTEXT; } - if (encCtx->cipherInput.data == NULL) + if (!ncSpanIsValidC(encCtx->buffer.input)) { return E_INVALID_CONTEXT; } + /* Reset output data pointer incase it has been moved */ + _cipherPublishOutput(encCtx, 0, 0); + switch (encCtx->encArgs.version) { case NC_ENC_VERSION_NIP44: @@ -841,14 +881,7 @@ NC_EXPORT NCResult NC_CC NCUtilCipherUpdate( return E_CIPHER_BAD_NONCE; } - return _nip44EncryptCompleteCore( - libContext, - sk, - pk, - encCtx->encArgs, - encCtx->cipherInput, - encCtx->cipherOutput - ); + return _nip44EncryptCompleteCore(libContext, sk, pk, encCtx); } default: diff --git a/src/providers/bcrypt.c b/src/providers/bcrypt.c index d1b9aa5..67ae695 100644 --- a/src/providers/bcrypt.c +++ b/src/providers/bcrypt.c @@ -63,7 +63,7 @@ _IMPLSTB NTSTATUS _bcInitSha256(struct _bcrypt_ctx* ctx, DWORD flags) return result; } -_IMPLSTB NTSTATUS _bcCreateHmac(struct _bcrypt_ctx* ctx, const cspan_t* key) +_IMPLSTB NTSTATUS _bcCreateHmac(struct _bcrypt_ctx* ctx, cspan_t key) { /* * NOTE: @@ -79,8 +79,8 @@ _IMPLSTB NTSTATUS _bcCreateHmac(struct _bcrypt_ctx* ctx, const cspan_t* key) &ctx->hHash, NULL, 0, - (uint8_t*)key->data, - key->size, + (uint8_t*)key.data, + key.size, BCRYPT_HASH_REUSABLE_FLAG /* Enable reusable for expand function */ ); } @@ -92,7 +92,7 @@ _IMPLSTB NTSTATUS _bcCreate(struct _bcrypt_ctx* ctx) /* Zero out key span for 0 size and NULL data ptr */ SecureZeroMemory(&key, sizeof(cspan_t)); - return _bcCreateHmac(ctx, &key); + return _bcCreateHmac(ctx, key); } _IMPLSTB NTSTATUS _bcHashDataRaw(const struct _bcrypt_ctx* ctx, const uint8_t* data, uint32_t len) @@ -100,9 +100,9 @@ _IMPLSTB NTSTATUS _bcHashDataRaw(const struct _bcrypt_ctx* ctx, const uint8_t* d return BCryptHashData(ctx->hHash, (uint8_t*)data, len, 0); } -_IMPLSTB NTSTATUS _bcHashData(const struct _bcrypt_ctx* ctx, const cspan_t* data) +_IMPLSTB NTSTATUS _bcHashData(const struct _bcrypt_ctx* ctx, cspan_t data) { - return _bcHashDataRaw(ctx, data->data, data->size); + return _bcHashDataRaw(ctx, data.data, data.size); } _IMPLSTB NTSTATUS _bcFinishHash(const struct _bcrypt_ctx* ctx, sha256_t digestOut32) @@ -146,7 +146,7 @@ _IMPLSTB void _bcDestroyCtx(struct _bcrypt_ctx* ctx) /* Export function fallack */ #define _IMPL_CRYPTO_SHA256_DIGEST _bcrypt_sha256_digest - _IMPLSTB cstatus_t _bcrypt_sha256_digest(const cspan_t* data, sha256_t digestOut32) + _IMPLSTB cstatus_t _bcrypt_sha256_digest(cspan_t data, sha256_t digestOut32) { cstatus_t result; struct _bcrypt_ctx ctx; @@ -177,7 +177,7 @@ _IMPLSTB void _bcDestroyCtx(struct _bcrypt_ctx* ctx) /* Export function */ #define _IMPL_CRYPTO_SHA256_HMAC _bcrypt_hmac_sha256 - _IMPLSTB cstatus_t _bcrypt_hmac_sha256(const cspan_t* key, const cspan_t* data, sha256_t hmacOut32) + _IMPLSTB cstatus_t _bcrypt_hmac_sha256(cspan_t key, cspan_t data, sha256_t hmacOut32) { cstatus_t result; struct _bcrypt_ctx ctx; @@ -213,7 +213,7 @@ _IMPLSTB void _bcDestroyCtx(struct _bcrypt_ctx* ctx) #define _IMPL_CRYPTO_SHA256_HKDF_EXPAND _bcrypt_fallback_hkdf_expand - cstatus_t _bcrypt_hkdf_update(void* ctx, const cspan_t* data) + cstatus_t _bcrypt_hkdf_update(void* ctx, cspan_t data) { DEBUG_ASSERT(ctx != NULL) @@ -229,7 +229,7 @@ _IMPLSTB void _bcDestroyCtx(struct _bcrypt_ctx* ctx) return CSTATUS_OK; } - _IMPLSTB cstatus_t _bcrypt_fallback_hkdf_expand(const cspan_t* prk, const cspan_t* info, span_t* okm) + _IMPLSTB cstatus_t _bcrypt_fallback_hkdf_expand(cspan_t prk, cspan_t info, span_t okm) { cstatus_t result; struct _bcrypt_ctx ctx; diff --git a/src/providers/mbedtls.c b/src/providers/mbedtls.c index df5201f..8479380 100644 --- a/src/providers/mbedtls.c +++ b/src/providers/mbedtls.c @@ -95,13 +95,13 @@ _IMPLSTB const mbedtls_md_info_t* _mbed_sha256_alg(void) #define _IMPL_CRYPTO_SHA256_DIGEST _mbed_sha256_digest - _IMPLSTB cstatus_t _mbed_sha256_digest(const cspan_t* data, sha256_t digestOut32) + _IMPLSTB cstatus_t _mbed_sha256_digest(cspan_t data, sha256_t digestOut32) { - _overflow_check(data->size) + _overflow_check(data.size) return mbedtls_sha256( - data->data, - data->size, + data.data, + data.size, digestOut32, 0 /* Set 0 for sha256 mode */ ) == 0 ? CSTATUS_OK : CSTATUS_FAIL; @@ -114,19 +114,19 @@ _IMPLSTB const mbedtls_md_info_t* _mbed_sha256_alg(void) #define _IMPL_CRYPTO_SHA256_HMAC _mbed_sha256_hmac - _IMPLSTB cstatus_t _mbed_sha256_hmac(const cspan_t* key, const cspan_t* data, sha256_t hmacOut32) + _IMPLSTB cstatus_t _mbed_sha256_hmac(cspan_t key, cspan_t data, sha256_t hmacOut32) { - _overflow_check(data->size) + _overflow_check(data.size) /* Keys should never be large enough for this to matter, but sanity check. */ - DEBUG_ASSERT2(key->size < SIZE_MAX, "Expected key size to be less than SIZE_MAX") + DEBUG_ASSERT2(key.size < SIZE_MAX, "Expected key size to be less than SIZE_MAX") return mbedtls_md_hmac( _mbed_sha256_alg(), - key->data, - key->size, - data->data, - data->size, + key.data, + key.size, + data.data, + data.size, hmacOut32 ) == 0 ? CSTATUS_OK : CSTATUS_FAIL; } @@ -137,21 +137,21 @@ _IMPLSTB const mbedtls_md_info_t* _mbed_sha256_alg(void) #define _IMPL_CRYPTO_SHA256_HKDF_EXPAND _mbed_sha256_hkdf_expand - _IMPLSTB cstatus_t _mbed_sha256_hkdf_expand(const cspan_t* prk, const cspan_t* info, span_t* okm) + _IMPLSTB cstatus_t _mbed_sha256_hkdf_expand(cspan_t prk, cspan_t info, span_t okm) { /* These sizes should never be large enough to overflow on <64bit platforms, but sanity check */ - DEBUG_ASSERT(okm->size < SIZE_MAX) - DEBUG_ASSERT(prk->size < SIZE_MAX) - DEBUG_ASSERT(info->size < SIZE_MAX) + DEBUG_ASSERT(okm.size < SIZE_MAX) + DEBUG_ASSERT(prk.size < SIZE_MAX) + DEBUG_ASSERT(info.size < SIZE_MAX) return mbedtls_hkdf_expand( _mbed_sha256_alg(), - prk->data, - prk->size, - info->data, - info->size, - okm->data, - okm->size + prk.data, + prk.size, + info.data, + info.size, + okm.data, + okm.size ) == 0 ? CSTATUS_OK : CSTATUS_FAIL; } diff --git a/tests/hex.h b/tests/hex.h index e6a2a07..3cfe559 100644 --- a/tests/hex.h +++ b/tests/hex.h @@ -68,6 +68,7 @@ static span_t _fromHexString(const char* hexLiteral, uint32_t strLen) if(!hexLiteral) { + ncSpanInit(&hexBytes, NULL, 0); return hexBytes; } @@ -125,13 +126,13 @@ static void PrintHexRaw(void* bytes, size_t len) */ static void PrintHexBytes(span_t hexBytes) { - if (!hexBytes.data) + if (ncSpanIsValid(hexBytes)) { - puts("NULL"); + PrintHexRaw(hexBytes.data, hexBytes.size); } else { - PrintHexRaw(hexBytes.data, hexBytes.size); + puts("NULL"); } } diff --git a/tests/test.c b/tests/test.c index 80b8704..b4cdef1 100644 --- a/tests/test.c +++ b/tests/test.c @@ -617,7 +617,7 @@ static int TestUtilNip44Encryption( span_t recvKey, span_t nonce, span_t expected, - const char* plainText + span_t plainText ) { NCPublicKey recvPubKey; @@ -634,7 +634,7 @@ static int TestUtilNip44Encryption( ENSURE(ctx != NULL); - TEST(NCUtilCipherInit(ctx, (const uint8_t*)plainText, strlen(plainText)), NC_SUCCESS); + TEST(NCUtilCipherInit(ctx, plainText.data, plainText.size), NC_SUCCESS); /* Nonce is required for nip44 encryption */ TEST(NCUtilCipherSetProperty(ctx, NC_ENC_SET_NIP44_NONCE, nonce.data, nonce.size), NC_SUCCESS); @@ -659,6 +659,8 @@ static int TestUtilNip44Encryption( /* Free encryption memory */ NCUtilCipherFree(ctx); + + return 0; } static int TestUtilNip44Decryption( @@ -666,7 +668,7 @@ static int TestUtilNip44Decryption( span_t sendKey, span_t recvKey, span_t payload, - const char* expectedPt + span_t expectedPt ) { NCPublicKey recvPubKey; @@ -690,7 +692,7 @@ static int TestUtilNip44Decryption( NCResult plaintextSize = NCUtilCipherGetOutputSize(ctx); - TEST(plaintextSize, strlen(expectedPt)); + TEST(plaintextSize, expectedPt.size); outData = (uint8_t*)malloc(plaintextSize); @@ -700,12 +702,14 @@ static int TestUtilNip44Decryption( TEST(NCUtilCipherReadOutput(ctx, outData, plaintextSize), plaintextSize); /* Ensure encrypted payload matches */ - TEST(memcmp(outData, expectedPt, plaintextSize), 0); + TEST(memcmp(outData, expectedPt.data, plaintextSize), 0); free(outData); /* Free encryption memory */ NCUtilCipherFree(ctx); + + return 0; } static int TestUtilFunctions(const NCContext* libCtx) @@ -727,7 +731,7 @@ static int TestUtilFunctions(const NCContext* libCtx) span_t recvKey = FromHexString("0000000000000000000000000000000000000000000000000000000000000002", sizeof(NCSecretKey)); span_t nonce = FromHexString("0000000000000000000000000000000000000000000000000000000000000001", NC_ENCRYPTION_NONCE_SIZE); span_t payload = FromHexString("02000000000000000000000000000000000000000000000000000000000000000179ed06e5548ad3ff58ca920e6c0b4329f6040230f7e6e5641f20741780f0adc35a09794259929a02bb06ad8e8cf709ee4ccc567e9d514cdf5781af27a3e905e55b1b", 99); - const char* plainText = "a"; + span_t plainText = FromHexString("61", 1); if (TestUtilNip44Encryption(libCtx, sendKey, recvKey, nonce, payload, plainText) != 0) { @@ -740,9 +744,8 @@ static int TestUtilFunctions(const NCContext* libCtx) /* From the nip44 vectors file */ span_t sendKey = FromHexString("0000000000000000000000000000000000000000000000000000000000000001", sizeof(NCSecretKey)); span_t recvKey = FromHexString("0000000000000000000000000000000000000000000000000000000000000002", sizeof(NCSecretKey)); - span_t nonce = FromHexString("0000000000000000000000000000000000000000000000000000000000000001", NC_ENCRYPTION_NONCE_SIZE); span_t payload = FromHexString("02000000000000000000000000000000000000000000000000000000000000000179ed06e5548ad3ff58ca920e6c0b4329f6040230f7e6e5641f20741780f0adc35a09794259929a02bb06ad8e8cf709ee4ccc567e9d514cdf5781af27a3e905e55b1b", 99); - const char* plainText = "a"; + span_t plainText = FromHexString("61", 1); if (TestUtilNip44Decryption(libCtx, sendKey, recvKey, payload, plainText) != 0) { -- cgit From 3b97f84fd0477eafcd6567eb8597b213e4136664 Mon Sep 17 00:00:00 2001 From: vnugent Date: Tue, 6 Aug 2024 19:57:10 -0400 Subject: update libsecp256k1 to v0.5.1 --- CMakeLists.txt | 2 +- Taskfile.yaml | 4 +- .../include/secp256k1/secp256k1_ellswift.h | 200 +++++++++++++++++++++ .../include/secp256k1/secp256k1_recovery.h | 113 ++++++++++++ 4 files changed, 316 insertions(+), 3 deletions(-) create mode 100644 vendor/secp256k1/include/secp256k1/secp256k1_ellswift.h create mode 100644 vendor/secp256k1/include/secp256k1/secp256k1_recovery.h (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index 6dad383..89b2026 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,7 +51,7 @@ if(NC_FETCH_SECP256K1) FetchContent_Declare( libsecp256k1 GIT_REPOSITORY https://github.com/bitcoin-core/secp256k1 - GIT_TAG e3a885d42a7800c1ccebad94ad1e2b82c4df5c65 # release-0.5.0 + GIT_TAG 642c885b6102725e25623738529895a95addc4f4 # release-0.5.1 GIT_PROGRESS TRUE ) diff --git a/Taskfile.yaml b/Taskfile.yaml index 053cef2..0af15f3 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -226,9 +226,9 @@ tasks: dev-set-secp256-headers: vars: SECP256_GIT_URL: 'https://github.com/bitcoin-core/secp256k1' - SECP256_GIT_BRANCH: 'v0.5.0' + SECP256_GIT_BRANCH: 'v0.5.1' SECP256_DIR: 'vendor/secp256k1' - TMP_DIR: '.update/openssl' + TMP_DIR: '.update/secp256k1' cmds: - cmd: powershell mkdir '{{.TMP_DIR}}' -Force ignore_error: true diff --git a/vendor/secp256k1/include/secp256k1/secp256k1_ellswift.h b/vendor/secp256k1/include/secp256k1/secp256k1_ellswift.h new file mode 100644 index 0000000..ae37287 --- /dev/null +++ b/vendor/secp256k1/include/secp256k1/secp256k1_ellswift.h @@ -0,0 +1,200 @@ +#ifndef SECP256K1_ELLSWIFT_H +#define SECP256K1_ELLSWIFT_H + +#include "secp256k1.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* This module provides an implementation of ElligatorSwift as well as a + * version of x-only ECDH using it (including compatibility with BIP324). + * + * ElligatorSwift is described in https://eprint.iacr.org/2022/759 by + * Chavez-Saab, Rodriguez-Henriquez, and Tibouchi. It permits encoding + * uniformly chosen public keys as 64-byte arrays which are indistinguishable + * from uniformly random arrays. + * + * Let f be the function from pairs of field elements to point X coordinates, + * defined as follows (all operations modulo p = 2^256 - 2^32 - 977) + * f(u,t): + * - Let C = 0xa2d2ba93507f1df233770c2a797962cc61f6d15da14ecd47d8d27ae1cd5f852, + * a square root of -3. + * - If u=0, set u=1 instead. + * - If t=0, set t=1 instead. + * - If u^3 + t^2 + 7 = 0, multiply t by 2. + * - Let X = (u^3 + 7 - t^2) / (2 * t) + * - Let Y = (X + t) / (C * u) + * - Return the first in [u + 4 * Y^2, (-X/Y - u) / 2, (X/Y - u) / 2] that is an + * X coordinate on the curve (at least one of them is, for any u and t). + * + * Then an ElligatorSwift encoding of x consists of the 32-byte big-endian + * encodings of field elements u and t concatenated, where f(u,t) = x. + * The encoding algorithm is described in the paper, and effectively picks a + * uniformly random pair (u,t) among those which encode x. + * + * If the Y coordinate is relevant, it is given the same parity as t. + * + * Changes w.r.t. the the paper: + * - The u=0, t=0, and u^3+t^2+7=0 conditions result in decoding to the point + * at infinity in the paper. Here they are remapped to finite points. + * - The paper uses an additional encoding bit for the parity of y. Here the + * parity of t is used (negating t does not affect the decoded x coordinate, + * so this is possible). + * + * For mathematical background about the scheme, see the doc/ellswift.md file. + */ + +/** A pointer to a function used by secp256k1_ellswift_xdh to hash the shared X + * coordinate along with the encoded public keys to a uniform shared secret. + * + * Returns: 1 if a shared secret was successfully computed. + * 0 will cause secp256k1_ellswift_xdh to fail and return 0. + * Other return values are not allowed, and the behaviour of + * secp256k1_ellswift_xdh is undefined for other return values. + * Out: output: pointer to an array to be filled by the function + * In: x32: pointer to the 32-byte serialized X coordinate + * of the resulting shared point (will not be NULL) + * ell_a64: pointer to the 64-byte encoded public key of party A + * (will not be NULL) + * ell_b64: pointer to the 64-byte encoded public key of party B + * (will not be NULL) + * data: arbitrary data pointer that is passed through + */ +typedef int (*secp256k1_ellswift_xdh_hash_function)( + unsigned char *output, + const unsigned char *x32, + const unsigned char *ell_a64, + const unsigned char *ell_b64, + void *data +); + +/** An implementation of an secp256k1_ellswift_xdh_hash_function which uses + * SHA256(prefix64 || ell_a64 || ell_b64 || x32), where prefix64 is the 64-byte + * array pointed to by data. */ +SECP256K1_API const secp256k1_ellswift_xdh_hash_function secp256k1_ellswift_xdh_hash_function_prefix; + +/** An implementation of an secp256k1_ellswift_xdh_hash_function compatible with + * BIP324. It returns H_tag(ell_a64 || ell_b64 || x32), where H_tag is the + * BIP340 tagged hash function with tag "bip324_ellswift_xonly_ecdh". Equivalent + * to secp256k1_ellswift_xdh_hash_function_prefix with prefix64 set to + * SHA256("bip324_ellswift_xonly_ecdh")||SHA256("bip324_ellswift_xonly_ecdh"). + * The data argument is ignored. */ +SECP256K1_API const secp256k1_ellswift_xdh_hash_function secp256k1_ellswift_xdh_hash_function_bip324; + +/** Construct a 64-byte ElligatorSwift encoding of a given pubkey. + * + * Returns: 1 always. + * Args: ctx: pointer to a context object + * Out: ell64: pointer to a 64-byte array to be filled + * In: pubkey: pointer to a secp256k1_pubkey containing an + * initialized public key + * rnd32: pointer to 32 bytes of randomness + * + * It is recommended that rnd32 consists of 32 uniformly random bytes, not + * known to any adversary trying to detect whether public keys are being + * encoded, though 16 bytes of randomness (padded to an array of 32 bytes, + * e.g., with zeros) suffice to make the result indistinguishable from + * uniform. The randomness in rnd32 must not be a deterministic function of + * the pubkey (it can be derived from the private key, though). + * + * It is not guaranteed that the computed encoding is stable across versions + * of the library, even if all arguments to this function (including rnd32) + * are the same. + * + * This function runs in variable time. + */ +SECP256K1_API int secp256k1_ellswift_encode( + const secp256k1_context *ctx, + unsigned char *ell64, + const secp256k1_pubkey *pubkey, + const unsigned char *rnd32 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Decode a 64-bytes ElligatorSwift encoded public key. + * + * Returns: always 1 + * Args: ctx: pointer to a context object + * Out: pubkey: pointer to a secp256k1_pubkey that will be filled + * In: ell64: pointer to a 64-byte array to decode + * + * This function runs in variable time. + */ +SECP256K1_API int secp256k1_ellswift_decode( + const secp256k1_context *ctx, + secp256k1_pubkey *pubkey, + const unsigned char *ell64 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Compute an ElligatorSwift public key for a secret key. + * + * Returns: 1: secret was valid, public key was stored. + * 0: secret was invalid, try again. + * Args: ctx: pointer to a context object + * Out: ell64: pointer to a 64-byte array to receive the ElligatorSwift + * public key + * In: seckey32: pointer to a 32-byte secret key + * auxrnd32: (optional) pointer to 32 bytes of randomness + * + * Constant time in seckey and auxrnd32, but not in the resulting public key. + * + * It is recommended that auxrnd32 contains 32 uniformly random bytes, though + * it is optional (and does result in encodings that are indistinguishable from + * uniform even without any auxrnd32). It differs from the (mandatory) rnd32 + * argument to secp256k1_ellswift_encode in this regard. + * + * This function can be used instead of calling secp256k1_ec_pubkey_create + * followed by secp256k1_ellswift_encode. It is safer, as it uses the secret + * key as entropy for the encoding (supplemented with auxrnd32, if provided). + * + * Like secp256k1_ellswift_encode, this function does not guarantee that the + * computed encoding is stable across versions of the library, even if all + * arguments (including auxrnd32) are the same. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ellswift_create( + const secp256k1_context *ctx, + unsigned char *ell64, + const unsigned char *seckey32, + const unsigned char *auxrnd32 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Given a private key, and ElligatorSwift public keys sent in both directions, + * compute a shared secret using x-only Elliptic Curve Diffie-Hellman (ECDH). + * + * Returns: 1: shared secret was successfully computed + * 0: secret was invalid or hashfp returned 0 + * Args: ctx: pointer to a context object. + * Out: output: pointer to an array to be filled by hashfp. + * In: ell_a64: pointer to the 64-byte encoded public key of party A + * (will not be NULL) + * ell_b64: pointer to the 64-byte encoded public key of party B + * (will not be NULL) + * seckey32: pointer to our 32-byte secret key + * party: boolean indicating which party we are: zero if we are + * party A, non-zero if we are party B. seckey32 must be + * the private key corresponding to that party's ell_?64. + * This correspondence is not checked. + * hashfp: pointer to a hash function. + * data: arbitrary data pointer passed through to hashfp. + * + * Constant time in seckey32. + * + * This function is more efficient than decoding the public keys, and performing + * ECDH on them. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ellswift_xdh( + const secp256k1_context *ctx, + unsigned char *output, + const unsigned char *ell_a64, + const unsigned char *ell_b64, + const unsigned char *seckey32, + int party, + secp256k1_ellswift_xdh_hash_function hashfp, + void *data +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(7); + +#ifdef __cplusplus +} +#endif + +#endif /* SECP256K1_ELLSWIFT_H */ diff --git a/vendor/secp256k1/include/secp256k1/secp256k1_recovery.h b/vendor/secp256k1/include/secp256k1/secp256k1_recovery.h new file mode 100644 index 0000000..341b8ba --- /dev/null +++ b/vendor/secp256k1/include/secp256k1/secp256k1_recovery.h @@ -0,0 +1,113 @@ +#ifndef SECP256K1_RECOVERY_H +#define SECP256K1_RECOVERY_H + +#include "secp256k1.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Opaque data structured that holds a parsed ECDSA signature, + * supporting pubkey recovery. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 65 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage or transmission, use + * the secp256k1_ecdsa_signature_serialize_* and + * secp256k1_ecdsa_signature_parse_* functions. + * + * Furthermore, it is guaranteed that identical signatures (including their + * recoverability) will have identical representation, so they can be + * memcmp'ed. + */ +typedef struct { + unsigned char data[65]; +} secp256k1_ecdsa_recoverable_signature; + +/** Parse a compact ECDSA signature (64 bytes + recovery id). + * + * Returns: 1 when the signature could be parsed, 0 otherwise + * Args: ctx: pointer to a context object + * Out: sig: pointer to a signature object + * In: input64: pointer to a 64-byte compact signature + * recid: the recovery id (0, 1, 2 or 3) + */ +SECP256K1_API int secp256k1_ecdsa_recoverable_signature_parse_compact( + const secp256k1_context *ctx, + secp256k1_ecdsa_recoverable_signature *sig, + const unsigned char *input64, + int recid +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Convert a recoverable signature into a normal signature. + * + * Returns: 1 + * Args: ctx: pointer to a context object. + * Out: sig: pointer to a normal signature. + * In: sigin: pointer to a recoverable signature. + */ +SECP256K1_API int secp256k1_ecdsa_recoverable_signature_convert( + const secp256k1_context *ctx, + secp256k1_ecdsa_signature *sig, + const secp256k1_ecdsa_recoverable_signature *sigin +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize an ECDSA signature in compact format (64 bytes + recovery id). + * + * Returns: 1 + * Args: ctx: pointer to a context object. + * Out: output64: pointer to a 64-byte array of the compact signature. + * recid: pointer to an integer to hold the recovery id. + * In: sig: pointer to an initialized signature object. + */ +SECP256K1_API int secp256k1_ecdsa_recoverable_signature_serialize_compact( + const secp256k1_context *ctx, + unsigned char *output64, + int *recid, + const secp256k1_ecdsa_recoverable_signature *sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Create a recoverable ECDSA signature. + * + * Returns: 1: signature created + * 0: the nonce generation function failed, or the secret key was invalid. + * Args: ctx: pointer to a context object (not secp256k1_context_static). + * Out: sig: pointer to an array where the signature will be placed. + * In: msghash32: the 32-byte message hash being signed. + * seckey: pointer to a 32-byte secret key. + * noncefp: pointer to a nonce generation function. If NULL, + * secp256k1_nonce_function_default is used. + * ndata: pointer to arbitrary data used by the nonce generation function + * (can be NULL for secp256k1_nonce_function_default). + */ +SECP256K1_API int secp256k1_ecdsa_sign_recoverable( + const secp256k1_context *ctx, + secp256k1_ecdsa_recoverable_signature *sig, + const unsigned char *msghash32, + const unsigned char *seckey, + secp256k1_nonce_function noncefp, + const void *ndata +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Recover an ECDSA public key from a signature. + * + * Returns: 1: public key successfully recovered (which guarantees a correct signature). + * 0: otherwise. + * Args: ctx: pointer to a context object. + * Out: pubkey: pointer to the recovered public key. + * In: sig: pointer to initialized signature that supports pubkey recovery. + * msghash32: the 32-byte message hash assumed to be signed. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_recover( + const secp256k1_context *ctx, + secp256k1_pubkey *pubkey, + const secp256k1_ecdsa_recoverable_signature *sig, + const unsigned char *msghash32 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +#ifdef __cplusplus +} +#endif + +#endif /* SECP256K1_RECOVERY_H */ -- cgit From a6392806eae7f302031afbcf22664ba33cbc4ad1 Mon Sep 17 00:00:00 2001 From: vnugent Date: Mon, 12 Aug 2024 13:56:03 -0400 Subject: simple cleanup & some api notes --- CMakeLists.txt | 15 +++++++++++++-- include/noscrypt.h | 21 +++++++++++++++++++++ src/nc-util.h | 19 ++++++++++++------- 3 files changed, 46 insertions(+), 9 deletions(-) (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index 89b2026..4a10738 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -421,9 +421,20 @@ install(TARGETS ${_NC_PROJ_NAME}_static INCLUDES DESTINATION include ) -install(FILES - include/noscrypt.h +SET(NC_INSTALL_HEADERS + include/noscrypt.h #static install headers include/platform.h +) + +if(NC_ENABLE_UTILS) + LIST(APPEND + NC_INSTALL_HEADERS + include/noscryptutil.h + ) +endif() + +install(FILES + ${NC_INSTALL_HEADERS} DESTINATION noscrypt ) diff --git a/include/noscrypt.h b/include/noscrypt.h index 574cef9..3702555 100644 --- a/include/noscrypt.h +++ b/include/noscrypt.h @@ -125,6 +125,27 @@ extern "C" { #define NC_ENC_SET_NIP44_MAC_KEY 0x03 #define NC_ENC_SET_NIP04_KEY 0x04 +/* +* API NOTES: +* +* - Decisions on integer width +* Since noscrypt will target general purpose processors and embedded +* systems (future) I didn't want to risk word size issues causing under/overflow +* for the time being, so a fixed integer width was used and internal code +* supports and guards against the platform default integer width (size_t) +* +* I'd like to support 64bit stuff, but really the underlying systems don't +* need to support that size buffer, nor do I expect platforms to have more than +* 4GB sized buffers (int32_t), it's just not practial and most work is on +* digests anyway. +* +* - Decisions on unsigned vs signed +* Yeah, I know this is a popular squabble in C land, but implementation details +* should not trouble the user. If I expect an unsigned int, then it should be +* explicit, negative number guards are cumbersom to handle return codes with +* that IMO most engineers don't bother doing anyway or doing well at the very +* least, so I'm using unsgined integers. Sorry, not sorry. +*/ /* A compressed resul/return value, negative values are failure, 0 is success and positive values are diff --git a/src/nc-util.h b/src/nc-util.h index a248578..36d26de 100644 --- a/src/nc-util.h +++ b/src/nc-util.h @@ -193,13 +193,10 @@ static _nc_fn_inline void ncSpanWrite(span_t span, uint32_t offset, const uint8_ static _nc_fn_inline void ncSpanAppend(span_t span, uint32_t* offset, const uint8_t* data, uint32_t size) { - DEBUG_ASSERT2(ncSpanIsValid(span), "Expected span to be non-null") DEBUG_ASSERT2(offset != NULL, "Expected offset to be non-null") - DEBUG_ASSERT2(data != NULL, "Expected data to be non-null") - DEBUG_ASSERT2(*offset + size <= span.size, "Expected offset + size to be less than span size") - /* Copy data to span */ - MEMMOV(span.data + *offset, data, size); + /* Copy data to span (also performs argument assertions) */ + ncSpanWrite(span, *offset, data, size); /* Increment offset */ *offset += size; @@ -213,7 +210,11 @@ static _nc_fn_inline span_t ncSpanSlice(span_t span, uint32_t offset, uint32_t s DEBUG_ASSERT2(offset + size <= span.size, "Expected offset + size to be less than span size") /* Initialize slice, offset input data by the specified offset */ - ncSpanInit(&slice, span.data + offset, size); + ncSpanInit( + &slice, + ncSpanGetOffset(span, offset), + size + ); return slice; } @@ -226,7 +227,11 @@ static _nc_fn_inline cspan_t ncSpanSliceC(cspan_t span, uint32_t offset, uint32_ DEBUG_ASSERT2(offset + size <= span.size, "Expected offset + size to be less than span size") /* Initialize slice, offset input data by the specified offset */ - ncSpanInitC(&slice, span.data + offset, size); + ncSpanInitC( + &slice, + ncSpanGetOffsetC(span, offset), + size + ); return slice; } -- cgit