Externals: Update mbedtls to 2.16.1

On a few of our buildbot instances, we get warnings about the usage of
deprecated functions. We should correct these, especially if we're
delegating to system versions of the libraries if they're available.
However, in order to do that, we need to update our library variant from
2.1.1 so that the non-deprecated alternatives are actually available.
This commit is contained in:
Lioncash 2019-06-07 20:44:51 -04:00
parent e73a3ba1c6
commit 3053fea160
160 changed files with 34616 additions and 8673 deletions

View File

@ -7,7 +7,7 @@ set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}
string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${CMAKE_C_COMPILER_ID}")
if(CMAKE_COMPILER_IS_GNUCC)
if(CMAKE_COMPILER_IS_GNU)
# some warnings we want are not available with old GCC versions
# note: starting with CMake 2.8 we could use CMAKE_C_COMPILER_VERSION
execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpversion
@ -26,23 +26,35 @@ if(CMAKE_COMPILER_IS_GNUCC)
set(CMAKE_C_FLAGS_ASANDBG "-Werror -fsanitize=address -fno-common -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls ")
set(CMAKE_C_FLAGS_CHECK "-Werror -Os")
set(CMAKE_C_FLAGS_CHECKFULL "${CMAKE_C_FLAGS_CHECK} -Wcast-qual")
endif(CMAKE_COMPILER_IS_GNUCC)
endif(CMAKE_COMPILER_IS_GNU)
if(CMAKE_COMPILER_IS_CLANG)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -W -Wdeclaration-after-statement -Wwrite-strings -Wpointer-arith -Wimplicit-fallthrough -Wshadow")
set(CMAKE_C_FLAGS_RELEASE "-O2")
set(CMAKE_C_FLAGS_DEBUG "-O0 -g3")
set(CMAKE_C_FLAGS_COVERAGE "-O0 -g3 --coverage")
set(CMAKE_C_FLAGS_ASAN "-Werror -fsanitize=address -fno-common -fsanitize=undefined -fno-sanitize-recover -O3")
set(CMAKE_C_FLAGS_ASANDBG "-Werror -fsanitize=address -fno-common -fsanitize=undefined -fno-sanitize-recover -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls ")
set(CMAKE_C_FLAGS_ASAN "-Werror -fsanitize=address -fno-common -fsanitize=undefined -fno-sanitize-recover=all -O3")
set(CMAKE_C_FLAGS_ASANDBG "-Werror -fsanitize=address -fno-common -fsanitize=undefined -fno-sanitize-recover=all -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls ")
set(CMAKE_C_FLAGS_MEMSAN "-Werror -fsanitize=memory -O3")
set(CMAKE_C_FLAGS_MEMSANDBG "-Werror -fsanitize=memory -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls -fsanitize-memory-track-origins=2")
set(CMAKE_C_FLAGS_CHECK "-Werror -Os")
endif(CMAKE_COMPILER_IS_CLANG)
if(MSVC)
set(CMAKE_C_FLAGS_CHECK "/WX")
endif(MSVC)
if(CMAKE_COMPILER_IS_IAR)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --warn_about_c_style_casts --warnings_are_errors -Ohz")
endif(CMAKE_COMPILER_IS_IAR)
if(CMAKE_COMPILER_IS_MSVC)
# Strictest warnings, and treat as errors
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W3")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX")
endif(CMAKE_COMPILER_IS_MSVC)
if(CMAKE_BUILD_TYPE STREQUAL "Coverage")
if(CMAKE_COMPILER_IS_GNU OR CMAKE_COMPILER_IS_CLANG)
set(CMAKE_SHARED_LINKER_FLAGS "--coverage")
endif(CMAKE_COMPILER_IS_GNU OR CMAKE_COMPILER_IS_CLANG)
endif(CMAKE_BUILD_TYPE STREQUAL "Coverage")
if(LIB_INSTALL_DIR)
else()

View File

@ -0,0 +1,16 @@
option(INSTALL_MBEDTLS_HEADERS "Install mbed TLS headers." ON)
if(INSTALL_MBEDTLS_HEADERS)
file(GLOB headers "mbedtls/*.h")
install(FILES ${headers}
DESTINATION include/mbedtls
PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)
endif(INSTALL_MBEDTLS_HEADERS)
# Make config.h available in an out-of-source build. ssl-opt.sh requires it.
if (NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
link_to_source(mbedtls)
endif()

View File

@ -1,9 +1,26 @@
/**
* \file aes.h
*
* \brief AES block cipher
* \brief This file contains AES definitions and functions.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* The Advanced Encryption Standard (AES) specifies a FIPS-approved
* cryptographic algorithm that can be used to protect electronic
* data.
*
* The AES algorithm is a symmetric block cipher that can
* encrypt and decrypt information. For more information, see
* <em>FIPS Publication 197: Advanced Encryption Standard</em> and
* <em>ISO/IEC 18033-2:2006: Information technology -- Security
* techniques -- Encryption algorithms -- Part 2: Asymmetric
* ciphers</em>.
*
* The AES-XTS block mode is standardized by NIST SP 800-38E
* <https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38e.pdf>
* and described in detail by IEEE P1619
* <https://ieeexplore.ieee.org/servlet/opac?punumber=4375278>.
*/
/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,8 +35,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_AES_H
#define MBEDTLS_AES_H
@ -33,83 +51,210 @@
#include <stdint.h>
/* padlock.c and aesni.c rely on these values! */
#define MBEDTLS_AES_ENCRYPT 1
#define MBEDTLS_AES_DECRYPT 0
#define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */
#define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */
/* Error codes in range 0x0020-0x0022 */
#define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */
#define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */
#if !defined(MBEDTLS_AES_ALT)
// Regular implementation
//
/* Error codes in range 0x0021-0x0025 */
#define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */
/* MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE is deprecated and should not be used. */
#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */
/* MBEDTLS_ERR_AES_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_AES_ALT)
// Regular implementation
//
/**
* \brief AES context structure
*
* \note buf is able to hold 32 extra bytes, which can be used:
* - for alignment purposes if VIA padlock is used, and/or
* - to simplify key expansion in the 256-bit case by
* generating an extra round key
* \brief The AES context-type definition.
*/
typedef struct
typedef struct mbedtls_aes_context
{
int nr; /*!< number of rounds */
uint32_t *rk; /*!< AES round keys */
uint32_t buf[68]; /*!< unaligned data */
int nr; /*!< The number of rounds. */
uint32_t *rk; /*!< AES round keys. */
uint32_t buf[68]; /*!< Unaligned data buffer. This buffer can
hold 32 extra Bytes, which can be used for
one of the following purposes:
<ul><li>Alignment if VIA padlock is
used.</li>
<li>Simplifying key expansion in the 256-bit
case by generating an extra round key.
</li></ul> */
}
mbedtls_aes_context;
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief Initialize AES context
* \brief The AES XTS context-type definition.
*/
typedef struct mbedtls_aes_xts_context
{
mbedtls_aes_context crypt; /*!< The AES context to use for AES block
encryption or decryption. */
mbedtls_aes_context tweak; /*!< The AES context used for tweak
computation. */
} mbedtls_aes_xts_context;
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#else /* MBEDTLS_AES_ALT */
#include "aes_alt.h"
#endif /* MBEDTLS_AES_ALT */
/**
* \brief This function initializes the specified AES context.
*
* \param ctx AES context to be initialized
* It must be the first API called before using
* the context.
*
* \param ctx The AES context to initialize. This must not be \c NULL.
*/
void mbedtls_aes_init( mbedtls_aes_context *ctx );
/**
* \brief Clear AES context
* \brief This function releases and clears the specified AES context.
*
* \param ctx AES context to be cleared
* \param ctx The AES context to clear.
* If this is \c NULL, this function does nothing.
* Otherwise, the context must have been at least initialized.
*/
void mbedtls_aes_free( mbedtls_aes_context *ctx );
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief AES key schedule (encryption)
* \brief This function initializes the specified AES XTS context.
*
* \param ctx AES context to be initialized
* \param key encryption key
* \param keybits must be 128, 192 or 256
* It must be the first API called before using
* the context.
*
* \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
* \param ctx The AES XTS context to initialize. This must not be \c NULL.
*/
void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx );
/**
* \brief This function releases and clears the specified AES XTS context.
*
* \param ctx The AES XTS context to clear.
* If this is \c NULL, this function does nothing.
* Otherwise, the context must have been at least initialized.
*/
void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx );
#endif /* MBEDTLS_CIPHER_MODE_XTS */
/**
* \brief This function sets the encryption key.
*
* \param ctx The AES context to which the key should be bound.
* It must be initialized.
* \param key The encryption key.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of data passed in bits. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,
unsigned int keybits );
/**
* \brief AES key schedule (decryption)
* \brief This function sets the decryption key.
*
* \param ctx AES context to be initialized
* \param key decryption key
* \param keybits must be 128, 192 or 256
* \param ctx The AES context to which the key should be bound.
* It must be initialized.
* \param key The decryption key.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of data passed. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,
unsigned int keybits );
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief AES-ECB block encryption/decryption
* \brief This function prepares an XTS context for encryption and
* sets the encryption key.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
* \param input 16-byte input block
* \param output 16-byte output block
* \param ctx The AES XTS context to which the key should be bound.
* It must be initialized.
* \param key The encryption key. This is comprised of the XTS key1
* concatenated with the XTS key2.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of \p key passed in bits. Valid options are:
* <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>
* <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>
*
* \return 0 if successful
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx,
const unsigned char *key,
unsigned int keybits );
/**
* \brief This function prepares an XTS context for decryption and
* sets the decryption key.
*
* \param ctx The AES XTS context to which the key should be bound.
* It must be initialized.
* \param key The decryption key. This is comprised of the XTS key1
* concatenated with the XTS key2.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of \p key passed in bits. Valid options are:
* <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>
* <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx,
const unsigned char *key,
unsigned int keybits );
#endif /* MBEDTLS_CIPHER_MODE_XTS */
/**
* \brief This function performs an AES single-block encryption or
* decryption operation.
*
* It performs the operation defined in the \p mode parameter
* (encrypt or decrypt), on the input data buffer defined in
* the \p input parameter.
*
* mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or
* mbedtls_aes_setkey_dec() must be called before the first
* call to this API with the same context.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param input The buffer holding the input data.
* It must be readable and at least \c 16 Bytes long.
* \param output The buffer where the output data will be written.
* It must be writeable and at least \c 16 Bytes long.
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
int mode,
@ -118,26 +263,45 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/**
* \brief AES-CBC buffer encryption/decryption
* Length should be a multiple of the block
* size (16 bytes)
* \brief This function performs an AES-CBC encryption or decryption operation
* on full blocks.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If on the other hand you need to retain the contents of the
* IV, you should either save it manually or use the cipher
* module instead.
* It performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer defined in
* the \p input parameter.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
* \param length length of the input data
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
* It can be called as many times as needed, until all the input
* data is processed. mbedtls_aes_init(), and either
* mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called
* before the first call to this API with the same context.
*
* \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
* \note This function operates on full blocks, that is, the input size
* must be a multiple of the AES block size of \c 16 Bytes.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the IV, you should
* either save it manually or use the cipher module instead.
*
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param length The length of the input data in Bytes. This must be a
* multiple of the block size (\c 16 Bytes).
* \param iv Initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
* on failure.
*/
int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
int mode,
@ -147,31 +311,89 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
unsigned char *output );
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief This function performs an AES-XTS encryption or decryption
* operation for an entire XTS data unit.
*
* AES-XTS encrypts or decrypts blocks based on their location as
* defined by a data unit number. The data unit number must be
* provided by \p data_unit.
*
* NIST SP 800-38E limits the maximum size of a data unit to 2^20
* AES blocks. If the data unit is larger than this, this function
* returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH.
*
* \param ctx The AES XTS context to use for AES XTS operations.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param length The length of a data unit in Bytes. This can be any
* length between 16 bytes and 2^24 bytes inclusive
* (between 1 and 2^20 block cipher blocks).
* \param data_unit The address of the data unit encoded as an array of 16
* bytes in little-endian format. For disk encryption, this
* is typically the index of the block device sector that
* contains the data.
* \param input The buffer holding the input data (which is an entire
* data unit). This function reads \p length Bytes from \p
* input.
* \param output The buffer holding the output data (which is an entire
* data unit). This function writes \p length Bytes to \p
* output.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is
* smaller than an AES block in size (16 Bytes) or if \p
* length is larger than 2^20 blocks (16 MiB).
*/
int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx,
int mode,
size_t length,
const unsigned char data_unit[16],
const unsigned char *input,
unsigned char *output );
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
/**
* \brief AES-CFB128 buffer encryption/decryption.
* \brief This function performs an AES-CFB128 encryption or decryption
* operation.
*
* Note: Due to the nature of CFB you should use the same key schedule for
* both encryption and decryption. So a context initialized with
* mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
* It performs the operation defined in the \p mode
* parameter (encrypt or decrypt), on the input data buffer
* defined in the \p input parameter.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If on the other hand you need to retain the contents of the
* IV, you should either save it manually or use the cipher
* module instead.
* For CFB, you must set up the context with mbedtls_aes_setkey_enc(),
* regardless of whether you are performing an encryption or decryption
* operation, that is, regardless of the \p mode parameter. This is
* because CFB mode uses the same key schedule for encryption and
* decryption.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
* \param length length of the input data
* \param iv_off offset in IV (updated after use)
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the
* IV, you must either save it manually or use the cipher
* module instead.
*
* \return 0 if successful
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param length The length of the input data in Bytes.
* \param iv_off The offset in IV (updated after use).
* It must point to a valid \c size_t.
* \param iv The initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,
int mode,
@ -182,28 +404,40 @@ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,
unsigned char *output );
/**
* \brief AES-CFB8 buffer encryption/decryption.
* \brief This function performs an AES-CFB8 encryption or decryption
* operation.
*
* Note: Due to the nature of CFB you should use the same key schedule for
* both encryption and decryption. So a context initialized with
* mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
* It performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer defined
* in the \p input parameter.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If on the other hand you need to retain the contents of the
* IV, you should either save it manually or use the cipher
* module instead.
* Due to the nature of CFB, you must use the same key schedule for
* both encryption and decryption operations. Therefore, you must
* use the context initialized with mbedtls_aes_setkey_enc() for
* both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
* \param length length of the input data
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the
* IV, you should either save it manually or use the cipher
* module instead.
*
* \return 0 if successful
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT
* \param length The length of the input data.
* \param iv The initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,
int mode,
@ -213,28 +447,137 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,
unsigned char *output );
#endif /*MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
/**
* \brief This function performs an AES-OFB (Output Feedback Mode)
* encryption or decryption operation.
*
* For OFB, you must set up the context with
* mbedtls_aes_setkey_enc(), regardless of whether you are
* performing an encryption or decryption operation. This is
* because OFB mode uses the same key schedule for encryption and
* decryption.
*
* The OFB operation is identical for encryption or decryption,
* therefore no operation mode needs to be specified.
*
* \note Upon exit, the content of iv, the Initialisation Vector, is
* updated so that you can call the same function again on the next
* block(s) of data and get the same result as if it was encrypted
* in one call. This allows a "streaming" usage, by initialising
* iv_off to 0 before the first call, and preserving its value
* between calls.
*
* For non-streaming use, the iv should be initialised on each call
* to a unique value, and iv_off set to 0 on each call.
*
* If you need to retain the contents of the initialisation vector,
* you must either save it manually or use the cipher module
* instead.
*
* \warning For the OFB mode, the initialisation vector must be unique
* every encryption operation. Reuse of an initialisation vector
* will compromise security.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param length The length of the input data.
* \param iv_off The offset in IV (updated after use).
* It must point to a valid \c size_t.
* \param iv The initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx,
size_t length,
size_t *iv_off,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output );
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/**
* \brief AES-CTR buffer encryption/decryption
* \brief This function performs an AES-CTR encryption or decryption
* operation.
*
* Warning: You have to keep the maximum use of your counter in mind!
* This function performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer
* defined in the \p input parameter.
*
* Note: Due to the nature of CTR you should use the same key schedule for
* both encryption and decryption. So a context initialized with
* mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
* Due to the nature of CTR, you must use the same key schedule
* for both encryption and decryption operations. Therefore, you
* must use the context initialized with mbedtls_aes_setkey_enc()
* for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
*
* \param ctx AES context
* \param length The length of the data
* \param nc_off The offset in the current stream_block (for resuming
* within current cipher stream). The offset pointer to
* should be 0 at the start of a stream.
* \param nonce_counter The 128-bit nonce and counter.
* \param stream_block The saved stream-block for resuming. Is overwritten
* by the function.
* \param input The input data stream
* \param output The output data stream
* \warning You must never reuse a nonce value with the same key. Doing so
* would void the encryption for the two messages encrypted with
* the same nonce and key.
*
* \return 0 if successful
* There are two common strategies for managing nonces with CTR:
*
* 1. You can handle everything as a single message processed over
* successive calls to this function. In that case, you want to
* set \p nonce_counter and \p nc_off to 0 for the first call, and
* then preserve the values of \p nonce_counter, \p nc_off and \p
* stream_block across calls to this function as they will be
* updated by this function.
*
* With this strategy, you must not encrypt more than 2**128
* blocks of data with the same key.
*
* 2. You can encrypt separate messages by dividing the \p
* nonce_counter buffer in two areas: the first one used for a
* per-message nonce, handled by yourself, and the second one
* updated by this function internally.
*
* For example, you might reserve the first 12 bytes for the
* per-message nonce, and the last 4 bytes for internal use. In that
* case, before calling this function on a new message you need to
* set the first 12 bytes of \p nonce_counter to your chosen nonce
* value, the last 4 to 0, and \p nc_off to 0 (which will cause \p
* stream_block to be ignored). That way, you can encrypt at most
* 2**96 messages of up to 2**32 blocks each with the same key.
*
* The per-message nonce (or information sufficient to reconstruct
* it) needs to be communicated with the ciphertext and must be unique.
* The recommended way to ensure uniqueness is to use a message
* counter. An alternative is to generate random nonces, but this
* limits the number of messages that can be securely encrypted:
* for example, with 96-bit random nonces, you should not encrypt
* more than 2**32 messages with the same key.
*
* Note that for both stategies, sizes are measured in blocks and
* that an AES block is 16 bytes.
*
* \warning Upon return, \p stream_block contains sensitive data. Its
* content must not be written to insecure storage and should be
* securely discarded as soon as it's no longer needed.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param length The length of the input data.
* \param nc_off The offset in the current \p stream_block, for
* resuming within the current cipher stream. The
* offset pointer should be 0 at the start of a stream.
* It must point to a valid \c size_t.
* \param nonce_counter The 128-bit nonce and counter.
* It must be a readable-writeable buffer of \c 16 Bytes.
* \param stream_block The saved stream block for resuming. This is
* overwritten by the function.
* It must be a readable-writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
size_t length,
@ -246,50 +589,84 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
#endif /* MBEDTLS_CIPHER_MODE_CTR */
/**
* \brief Internal AES block encryption function
* (Only exposed to allow overriding it,
* see MBEDTLS_AES_ENCRYPT_ALT)
* \brief Internal AES block encryption function. This is only
* exposed to allow overriding it using
* \c MBEDTLS_AES_ENCRYPT_ALT.
*
* \param ctx AES context
* \param input Plaintext block
* \param output Output (ciphertext) block
* \param ctx The AES context to use for encryption.
* \param input The plaintext block.
* \param output The output (ciphertext) block.
*
* \return \c 0 on success.
*/
void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
/**
* \brief Internal AES block decryption function
* (Only exposed to allow overriding it,
* see MBEDTLS_AES_DECRYPT_ALT)
* \brief Internal AES block decryption function. This is only
* exposed to allow overriding it using see
* \c MBEDTLS_AES_DECRYPT_ALT.
*
* \param ctx AES context
* \param input Ciphertext block
* \param output Output (plaintext) block
* \param ctx The AES context to use for decryption.
* \param input The ciphertext block.
* \param output The output (plaintext) block.
*
* \return \c 0 on success.
*/
void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_AES_ALT */
#include "aes_alt.h"
#endif /* MBEDTLS_AES_ALT */
#ifdef __cplusplus
extern "C" {
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Deprecated internal AES block encryption function
* without return value.
*
* \deprecated Superseded by mbedtls_internal_aes_encrypt()
*
* \param ctx The AES context to use for encryption.
* \param input Plaintext block.
* \param output Output (ciphertext) block.
*/
MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
/**
* \brief Checkup routine
* \brief Deprecated internal AES block decryption function
* without return value.
*
* \return 0 if successful, or 1 if the test failed
* \deprecated Superseded by mbedtls_internal_aes_decrypt()
*
* \param ctx The AES context to use for decryption.
* \param input Ciphertext block.
* \param output Output (plaintext) block.
*/
MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_aes_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

View File

@ -3,6 +3,10 @@
*
* \brief AES-NI for hardware AES acceleration on some Intel processors
*
* \warning These functions are only for internal use by other library
* functions; you must not call them directly.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +27,12 @@
#ifndef MBEDTLS_AESNI_H
#define MBEDTLS_AESNI_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "aes.h"
#define MBEDTLS_AESNI_AES 0x02000000u
@ -41,7 +51,10 @@ extern "C" {
#endif
/**
* \brief AES-NI features detection routine
* \brief Internal function to detect the AES-NI feature in CPUs.
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param what The feature to detect
* (MBEDTLS_AESNI_AES or MBEDTLS_AESNI_CLMUL)
@ -51,7 +64,10 @@ extern "C" {
int mbedtls_aesni_has_support( unsigned int what );
/**
* \brief AES-NI AES-ECB block en(de)cryption
* \brief Internal AES-NI AES-ECB block encryption and decryption
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
@ -61,12 +77,15 @@ int mbedtls_aesni_has_support( unsigned int what );
* \return 0 on success (cannot fail)
*/
int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] );
int mode,
const unsigned char input[16],
unsigned char output[16] );
/**
* \brief GCM multiplication: c = a * b in GF(2^128)
* \brief Internal GCM multiplication: c = a * b in GF(2^128)
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param c Result
* \param a First operand
@ -76,21 +95,29 @@ int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,
* elements of GF(2^128) as per the GCM spec.
*/
void mbedtls_aesni_gcm_mult( unsigned char c[16],
const unsigned char a[16],
const unsigned char b[16] );
const unsigned char a[16],
const unsigned char b[16] );
/**
* \brief Compute decryption round keys from encryption round keys
* \brief Internal round key inversion. This function computes
* decryption round keys from the encryption round keys.
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param invkey Round keys for the equivalent inverse cipher
* \param fwdkey Original round keys (for encryption)
* \param nr Number of rounds (that is, number of round keys minus one)
*/
void mbedtls_aesni_inverse_key( unsigned char *invkey,
const unsigned char *fwdkey, int nr );
const unsigned char *fwdkey,
int nr );
/**
* \brief Perform key expansion (for encryption)
* \brief Internal key expansion for encryption
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param rk Destination buffer where the round keys are written
* \param key Encryption key
@ -99,8 +126,8 @@ void mbedtls_aesni_inverse_key( unsigned char *invkey,
* \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
*/
int mbedtls_aesni_setkey_enc( unsigned char *rk,
const unsigned char *key,
size_t bits );
const unsigned char *key,
size_t bits );
#ifdef __cplusplus
}

View File

@ -3,6 +3,10 @@
*
* \brief The ARCFOUR stream cipher
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers instead.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -19,6 +23,7 @@
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
*/
#ifndef MBEDTLS_ARC4_H
#define MBEDTLS_ARC4_H
@ -31,18 +36,25 @@
#include <stddef.h>
#if !defined(MBEDTLS_ARC4_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED -0x0019 /**< ARC4 hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_ARC4_ALT)
// Regular implementation
//
/**
* \brief ARC4 context structure
* \brief ARC4 context structure
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers instead.
*
*/
typedef struct
typedef struct mbedtls_arc4_context
{
int x; /*!< permutation index */
int y; /*!< permutation index */
@ -50,10 +62,19 @@ typedef struct
}
mbedtls_arc4_context;
#else /* MBEDTLS_ARC4_ALT */
#include "arc4_alt.h"
#endif /* MBEDTLS_ARC4_ALT */
/**
* \brief Initialize ARC4 context
*
* \param ctx ARC4 context to be initialized
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*
*/
void mbedtls_arc4_init( mbedtls_arc4_context *ctx );
@ -61,6 +82,11 @@ void mbedtls_arc4_init( mbedtls_arc4_context *ctx );
* \brief Clear ARC4 context
*
* \param ctx ARC4 context to be cleared
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*
*/
void mbedtls_arc4_free( mbedtls_arc4_context *ctx );
@ -70,6 +96,11 @@ void mbedtls_arc4_free( mbedtls_arc4_context *ctx );
* \param ctx ARC4 context to be setup
* \param key the secret key
* \param keylen length of the key, in bytes
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*
*/
void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
unsigned int keylen );
@ -83,29 +114,31 @@ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
* \param output buffer for the output data
*
* \return 0 if successful
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*
*/
int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,
unsigned char *output );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_ARC4_ALT */
#include "arc4_alt.h"
#endif /* MBEDTLS_ARC4_ALT */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*
*/
int mbedtls_arc4_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

370
Externals/mbedtls/include/mbedtls/aria.h vendored Normal file
View File

@ -0,0 +1,370 @@
/**
* \file aria.h
*
* \brief ARIA block cipher
*
* The ARIA algorithm is a symmetric block cipher that can encrypt and
* decrypt information. It is defined by the Korean Agency for
* Technology and Standards (KATS) in <em>KS X 1213:2004</em> (in
* Korean, but see http://210.104.33.10/ARIA/index-e.html in English)
* and also described by the IETF in <em>RFC 5794</em>.
*/
/* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_ARIA_H
#define MBEDTLS_ARIA_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#include <stdint.h>
#include "platform_util.h"
#define MBEDTLS_ARIA_ENCRYPT 1 /**< ARIA encryption. */
#define MBEDTLS_ARIA_DECRYPT 0 /**< ARIA decryption. */
#define MBEDTLS_ARIA_BLOCKSIZE 16 /**< ARIA block size in bytes. */
#define MBEDTLS_ARIA_MAX_ROUNDS 16 /**< Maxiumum number of rounds in ARIA. */
#define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( -0x005C )
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#define MBEDTLS_ERR_ARIA_BAD_INPUT_DATA -0x005C /**< Bad input data. */
#define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E /**< Invalid data input length. */
/* MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE is deprecated and should not be used.
*/
#define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE -0x005A /**< Feature not available. For example, an unsupported ARIA key size. */
/* MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED -0x0058 /**< ARIA hardware accelerator failed. */
#if !defined(MBEDTLS_ARIA_ALT)
// Regular implementation
//
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The ARIA context-type definition.
*/
typedef struct mbedtls_aria_context
{
unsigned char nr; /*!< The number of rounds (12, 14 or 16) */
/*! The ARIA round keys. */
uint32_t rk[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4];
}
mbedtls_aria_context;
#else /* MBEDTLS_ARIA_ALT */
#include "aria_alt.h"
#endif /* MBEDTLS_ARIA_ALT */
/**
* \brief This function initializes the specified ARIA context.
*
* It must be the first API called before using
* the context.
*
* \param ctx The ARIA context to initialize. This must not be \c NULL.
*/
void mbedtls_aria_init( mbedtls_aria_context *ctx );
/**
* \brief This function releases and clears the specified ARIA context.
*
* \param ctx The ARIA context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized ARIA context.
*/
void mbedtls_aria_free( mbedtls_aria_context *ctx );
/**
* \brief This function sets the encryption key.
*
* \param ctx The ARIA context to which the key should be bound.
* This must be initialized.
* \param key The encryption key. This must be a readable buffer
* of size \p keybits Bits.
* \param keybits The size of \p key in Bits. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx,
const unsigned char *key,
unsigned int keybits );
/**
* \brief This function sets the decryption key.
*
* \param ctx The ARIA context to which the key should be bound.
* This must be initialized.
* \param key The decryption key. This must be a readable buffer
* of size \p keybits Bits.
* \param keybits The size of data passed. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx,
const unsigned char *key,
unsigned int keybits );
/**
* \brief This function performs an ARIA single-block encryption or
* decryption operation.
*
* It performs encryption or decryption (depending on whether
* the key was set for encryption on decryption) on the input
* data buffer defined in the \p input parameter.
*
* mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or
* mbedtls_aria_setkey_dec() must be called before the first
* call to this API with the same context.
*
* \param ctx The ARIA context to use for encryption or decryption.
* This must be initialized and bound to a key.
* \param input The 16-Byte buffer holding the input data.
* \param output The 16-Byte buffer holding the output data.
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,
const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] );
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/**
* \brief This function performs an ARIA-CBC encryption or decryption operation
* on full blocks.
*
* It performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer defined in
* the \p input parameter.
*
* It can be called as many times as needed, until all the input
* data is processed. mbedtls_aria_init(), and either
* mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called
* before the first call to this API with the same context.
*
* \note This function operates on aligned blocks, that is, the input size
* must be a multiple of the ARIA block size of 16 Bytes.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the IV, you should
* either save it manually or use the cipher module instead.
*
*
* \param ctx The ARIA context to use for encryption or decryption.
* This must be initialized and bound to a key.
* \param mode The mode of operation. This must be either
* #MBEDTLS_ARIA_ENCRYPT for encryption, or
* #MBEDTLS_ARIA_DECRYPT for decryption.
* \param length The length of the input data in Bytes. This must be a
* multiple of the block size (16 Bytes).
* \param iv Initialization vector (updated after use).
* This must be a readable buffer of size 16 Bytes.
* \param input The buffer holding the input data. This must
* be a readable buffer of length \p length Bytes.
* \param output The buffer holding the output data. This must
* be a writable buffer of length \p length Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,
int mode,
size_t length,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output );
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
/**
* \brief This function performs an ARIA-CFB128 encryption or decryption
* operation.
*
* It performs the operation defined in the \p mode
* parameter (encrypt or decrypt), on the input data buffer
* defined in the \p input parameter.
*
* For CFB, you must set up the context with mbedtls_aria_setkey_enc(),
* regardless of whether you are performing an encryption or decryption
* operation, that is, regardless of the \p mode parameter. This is
* because CFB mode uses the same key schedule for encryption and
* decryption.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the
* IV, you must either save it manually or use the cipher
* module instead.
*
*
* \param ctx The ARIA context to use for encryption or decryption.
* This must be initialized and bound to a key.
* \param mode The mode of operation. This must be either
* #MBEDTLS_ARIA_ENCRYPT for encryption, or
* #MBEDTLS_ARIA_DECRYPT for decryption.
* \param length The length of the input data \p input in Bytes.
* \param iv_off The offset in IV (updated after use).
* This must not be larger than 15.
* \param iv The initialization vector (updated after use).
* This must be a readable buffer of size 16 Bytes.
* \param input The buffer holding the input data. This must
* be a readable buffer of length \p length Bytes.
* \param output The buffer holding the output data. This must
* be a writable buffer of length \p length Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx,
int mode,
size_t length,
size_t *iv_off,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output );
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/**
* \brief This function performs an ARIA-CTR encryption or decryption
* operation.
*
* This function performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer
* defined in the \p input parameter.
*
* Due to the nature of CTR, you must use the same key schedule
* for both encryption and decryption operations. Therefore, you
* must use the context initialized with mbedtls_aria_setkey_enc()
* for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT.
*
* \warning You must never reuse a nonce value with the same key. Doing so
* would void the encryption for the two messages encrypted with
* the same nonce and key.
*
* There are two common strategies for managing nonces with CTR:
*
* 1. You can handle everything as a single message processed over
* successive calls to this function. In that case, you want to
* set \p nonce_counter and \p nc_off to 0 for the first call, and
* then preserve the values of \p nonce_counter, \p nc_off and \p
* stream_block across calls to this function as they will be
* updated by this function.
*
* With this strategy, you must not encrypt more than 2**128
* blocks of data with the same key.
*
* 2. You can encrypt separate messages by dividing the \p
* nonce_counter buffer in two areas: the first one used for a
* per-message nonce, handled by yourself, and the second one
* updated by this function internally.
*
* For example, you might reserve the first 12 bytes for the
* per-message nonce, and the last 4 bytes for internal use. In that
* case, before calling this function on a new message you need to
* set the first 12 bytes of \p nonce_counter to your chosen nonce
* value, the last 4 to 0, and \p nc_off to 0 (which will cause \p
* stream_block to be ignored). That way, you can encrypt at most
* 2**96 messages of up to 2**32 blocks each with the same key.
*
* The per-message nonce (or information sufficient to reconstruct
* it) needs to be communicated with the ciphertext and must be unique.
* The recommended way to ensure uniqueness is to use a message
* counter. An alternative is to generate random nonces, but this
* limits the number of messages that can be securely encrypted:
* for example, with 96-bit random nonces, you should not encrypt
* more than 2**32 messages with the same key.
*
* Note that for both stategies, sizes are measured in blocks and
* that an ARIA block is 16 bytes.
*
* \warning Upon return, \p stream_block contains sensitive data. Its
* content must not be written to insecure storage and should be
* securely discarded as soon as it's no longer needed.
*
* \param ctx The ARIA context to use for encryption or decryption.
* This must be initialized and bound to a key.
* \param length The length of the input data \p input in Bytes.
* \param nc_off The offset in Bytes in the current \p stream_block,
* for resuming within the current cipher stream. The
* offset pointer should be \c 0 at the start of a
* stream. This must not be larger than \c 15 Bytes.
* \param nonce_counter The 128-bit nonce and counter. This must point to
* a read/write buffer of length \c 16 bytes.
* \param stream_block The saved stream block for resuming. This must
* point to a read/write buffer of length \c 16 bytes.
* This is overwritten by the function.
* \param input The buffer holding the input data. This must
* be a readable buffer of length \p length Bytes.
* \param output The buffer holding the output data. This must
* be a writable buffer of length \p length Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output );
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine.
*
* \return \c 0 on success, or \c 1 on failure.
*/
int mbedtls_aria_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* aria.h */

View File

@ -2,7 +2,8 @@
* \file asn1.h
*
* \brief Generic ASN.1 parsing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -59,7 +60,7 @@
/**
* \name DER constants
* These constants comply with DER encoded the ANS1 type tags.
* These constants comply with the DER encoded ASN.1 type tags.
* DER encoding uses hexadecimal representation.
* An example DER sequence is:\n
* - 0x02 -- tag indicating INTEGER
@ -87,6 +88,21 @@
#define MBEDTLS_ASN1_PRIMITIVE 0x00
#define MBEDTLS_ASN1_CONSTRUCTED 0x20
#define MBEDTLS_ASN1_CONTEXT_SPECIFIC 0x80
/*
* Bit masks for each of the components of an ASN.1 tag as specified in
* ITU X.690 (08/2015), section 8.1 "General rules for encoding",
* paragraph 8.1.2.2:
*
* Bit 8 7 6 5 1
* +-------+-----+------------+
* | Class | P/C | Tag number |
* +-------+-----+------------+
*/
#define MBEDTLS_ASN1_TAG_CLASS_MASK 0xC0
#define MBEDTLS_ASN1_TAG_PC_MASK 0x20
#define MBEDTLS_ASN1_TAG_VALUE_MASK 0x1F
/* \} name */
/* \} addtogroup asn1_module */

View File

@ -2,7 +2,8 @@
* \file asn1write.h
*
* \brief ASN.1 buffer writing functionality
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,193 +24,280 @@
#ifndef MBEDTLS_ASN1_WRITE_H
#define MBEDTLS_ASN1_WRITE_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "asn1.h"
#define MBEDTLS_ASN1_CHK_ADD(g, f) do { if( ( ret = f ) < 0 ) return( ret ); else \
g += ret; } while( 0 )
#define MBEDTLS_ASN1_CHK_ADD(g, f) \
do { \
if( ( ret = f ) < 0 ) \
return( ret ); \
else \
g += ret; \
} while( 0 )
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Write a length field in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write a length field in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param len the length to write
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param len The length value to write.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len );
int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start,
size_t len );
/**
* \brief Write a ASN.1 tag in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write an ASN.1 tag in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param tag the tag to write
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param tag The tag to write.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start,
unsigned char tag );
unsigned char tag );
/**
* \brief Write raw buffer data
* Note: function works backwards in data buffer
* \brief Write raw buffer data.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param buf data buffer to write
* \param size length of the data buffer
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param buf The data buffer to write.
* \param size The length of the data buffer.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t size );
const unsigned char *buf, size_t size );
#if defined(MBEDTLS_BIGNUM_C)
/**
* \brief Write a big number (MBEDTLS_ASN1_INTEGER) in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write a arbitrary-precision number (#MBEDTLS_ASN1_INTEGER)
* in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param X the MPI to write
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param X The MPI to write.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, const mbedtls_mpi *X );
int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start,
const mbedtls_mpi *X );
#endif /* MBEDTLS_BIGNUM_C */
/**
* \brief Write a NULL tag (MBEDTLS_ASN1_NULL) with zero data in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write a NULL tag (#MBEDTLS_ASN1_NULL) with zero data
* in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_null( unsigned char **p, unsigned char *start );
/**
* \brief Write an OID tag (MBEDTLS_ASN1_OID) and data in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write an OID tag (#MBEDTLS_ASN1_OID) and data
* in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param oid the OID to write
* \param oid_len length of the OID
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param oid The OID to write.
* \param oid_len The length of the OID.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_oid( unsigned char **p, unsigned char *start,
const char *oid, size_t oid_len );
const char *oid, size_t oid_len );
/**
* \brief Write an AlgorithmIdentifier sequence in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write an AlgorithmIdentifier sequence in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param oid the OID of the algorithm
* \param oid_len length of the OID
* \param par_len length of parameters, which must be already written.
* \note This function works backwards in data buffer.
*
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param oid The OID of the algorithm to write.
* \param oid_len The length of the algorithm's OID.
* \param par_len The length of the parameters, which must be already written.
* If 0, NULL parameters are added
*
* \return the length written or a negative error code
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len );
int mbedtls_asn1_write_algorithm_identifier( unsigned char **p,
unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len );
/**
* \brief Write a boolean tag (MBEDTLS_ASN1_BOOLEAN) and value in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write a boolean tag (#MBEDTLS_ASN1_BOOLEAN) and value
* in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param boolean 0 or 1
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param boolean The boolean value to write, either \c 0 or \c 1.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, int boolean );
int mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start,
int boolean );
/**
* \brief Write an int tag (MBEDTLS_ASN1_INTEGER) and value in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write an int tag (#MBEDTLS_ASN1_INTEGER) and value
* in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param val the integer value
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param val The integer value to write.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val );
/**
* \brief Write a printable string tag (MBEDTLS_ASN1_PRINTABLE_STRING) and
* value in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write a string in ASN.1 format using a specific
* string encoding tag.
* \note This function works backwards in data buffer.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param text the text to write
* \param text_len length of the text
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param tag The string encoding tag to write, e.g.
* #MBEDTLS_ASN1_UTF8_STRING.
* \param text The string to write.
* \param text_len The length of \p text in bytes (which might
* be strictly larger than the number of characters).
*
* \return the length written or a negative error code
* \return The number of bytes written to \p p on success.
* \return A negative error code on failure.
*/
int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len );
int mbedtls_asn1_write_tagged_string( unsigned char **p, unsigned char *start,
int tag, const char *text,
size_t text_len );
/**
* \brief Write an IA5 string tag (MBEDTLS_ASN1_IA5_STRING) and
* value in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write a string in ASN.1 format using the PrintableString
* string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING).
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param text the text to write
* \param text_len length of the text
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param text The string to write.
* \param text_len The length of \p text in bytes (which might
* be strictly larger than the number of characters).
*
* \return The number of bytes written to \p p on success.
* \return A negative error code on failure.
*/
int mbedtls_asn1_write_printable_string( unsigned char **p,
unsigned char *start,
const char *text, size_t text_len );
/**
* \brief Write a UTF8 string in ASN.1 format using the UTF8String
* string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING).
*
* \note This function works backwards in data buffer.
*
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param text The string to write.
* \param text_len The length of \p text in bytes (which might
* be strictly larger than the number of characters).
*
* \return The number of bytes written to \p p on success.
* \return A negative error code on failure.
*/
int mbedtls_asn1_write_utf8_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len );
/**
* \brief Write a string in ASN.1 format using the IA5String
* string encoding tag (#MBEDTLS_ASN1_IA5_STRING).
*
* \note This function works backwards in data buffer.
*
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param text The string to write.
* \param text_len The length of \p text in bytes (which might
* be strictly larger than the number of characters).
*
* \return The number of bytes written to \p p on success.
* \return A negative error code on failure.
*/
int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len );
const char *text, size_t text_len );
/**
* \brief Write a bitstring tag (MBEDTLS_ASN1_BIT_STRING) and
* value in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write a bitstring tag (#MBEDTLS_ASN1_BIT_STRING) and
* value in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param buf the bitstring
* \param bits the total number of bits in the bitstring
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param buf The bitstring to write.
* \param bits The total number of bits in the bitstring.
*
* \return The number of bytes written to \p p on success.
* \return A negative error code on failure.
*/
int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t bits );
const unsigned char *buf, size_t bits );
/**
* \brief Write an octet string tag (MBEDTLS_ASN1_OCTET_STRING) and
* value in ASN.1 format
* Note: function works backwards in data buffer
* \brief Write an octet string tag (#MBEDTLS_ASN1_OCTET_STRING)
* and value in ASN.1 format.
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param buf data buffer to write
* \param size length of the data buffer
* \note This function works backwards in data buffer.
*
* \return the length written or a negative error code
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param buf The buffer holding the data to write.
* \param size The length of the data buffer \p buf.
*
* \return The number of bytes written to \p p on success.
* \return A negative error code on failure.
*/
int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t size );
const unsigned char *buf, size_t size );
/**
* \brief Create or find a specific named_data entry for writing in a
@ -217,15 +305,16 @@ int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start,
* a new entry is added to the head of the list.
* Warning: Destructive behaviour for the val data!
*
* \param list Pointer to the location of the head of the list to seek
* through (will be updated in case of a new entry)
* \param oid The OID to look for
* \param oid_len Size of the OID
* \param val Data to store (can be NULL if you want to fill it by hand)
* \param val_len Minimum length of the data buffer needed
* \param list The pointer to the location of the head of the list to seek
* through (will be updated in case of a new entry).
* \param oid The OID to look for.
* \param oid_len The size of the OID.
* \param val The data to store (can be \c NULL if you want to fill
* it by hand).
* \param val_len The minimum length of the data buffer needed.
*
* \return NULL if if there was a memory allocation error, or a pointer
* to the new / existing entry.
* \return A pointer to the new / existing entry on success.
* \return \c NULL if if there was a memory allocation error.
*/
mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( mbedtls_asn1_named_data **list,
const char *oid, size_t oid_len,

View File

@ -2,7 +2,8 @@
* \file base64.h
*
* \brief RFC 1521 base64 encoding/decoding
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_BASE64_H
#define MBEDTLS_BASE64_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#define MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL -0x002A /**< Output buffer too small. */
@ -74,6 +81,7 @@ int mbedtls_base64_encode( unsigned char *dst, size_t dlen, size_t *olen,
int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
@ -81,6 +89,8 @@ int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
*/
int mbedtls_base64_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,8 @@
* \file blowfish.h
*
* \brief Blowfish block cipher
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -32,6 +33,8 @@
#include <stddef.h>
#include <stdint.h>
#include "platform_util.h"
#define MBEDTLS_BLOWFISH_ENCRYPT 1
#define MBEDTLS_BLOWFISH_DECRYPT 0
#define MBEDTLS_BLOWFISH_MAX_KEY_BITS 448
@ -39,62 +42,87 @@
#define MBEDTLS_BLOWFISH_ROUNDS 16 /**< Rounds to use. When increasing this value, make sure to extend the initialisation vectors */
#define MBEDTLS_BLOWFISH_BLOCKSIZE 8 /* Blowfish uses 64 bit blocks */
#define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH -0x0016 /**< Invalid key length. */
#define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH -0x0018 /**< Invalid data input length. */
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( -0x0016 )
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#define MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA -0x0016 /**< Bad input data. */
#if !defined(MBEDTLS_BLOWFISH_ALT)
// Regular implementation
//
#define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH -0x0018 /**< Invalid data input length. */
/* MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED is deprecated and should not be used.
*/
#define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED -0x0017 /**< Blowfish hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_BLOWFISH_ALT)
// Regular implementation
//
/**
* \brief Blowfish context structure
*/
typedef struct
typedef struct mbedtls_blowfish_context
{
uint32_t P[MBEDTLS_BLOWFISH_ROUNDS + 2]; /*!< Blowfish round keys */
uint32_t S[4][256]; /*!< key dependent S-boxes */
}
mbedtls_blowfish_context;
#else /* MBEDTLS_BLOWFISH_ALT */
#include "blowfish_alt.h"
#endif /* MBEDTLS_BLOWFISH_ALT */
/**
* \brief Initialize Blowfish context
* \brief Initialize a Blowfish context.
*
* \param ctx Blowfish context to be initialized
* \param ctx The Blowfish context to be initialized.
* This must not be \c NULL.
*/
void mbedtls_blowfish_init( mbedtls_blowfish_context *ctx );
/**
* \brief Clear Blowfish context
* \brief Clear a Blowfish context.
*
* \param ctx Blowfish context to be cleared
* \param ctx The Blowfish context to be cleared.
* This may be \c NULL, in which case this function
* returns immediately. If it is not \c NULL, it must
* point to an initialized Blowfish context.
*/
void mbedtls_blowfish_free( mbedtls_blowfish_context *ctx );
/**
* \brief Blowfish key schedule
* \brief Perform a Blowfish key schedule operation.
*
* \param ctx Blowfish context to be initialized
* \param key encryption key
* \param keybits must be between 32 and 448 bits
* \param ctx The Blowfish context to perform the key schedule on.
* \param key The encryption key. This must be a readable buffer of
* length \p keybits Bits.
* \param keybits The length of \p key in Bits. This must be between
* \c 32 and \c 448 and a multiple of \c 8.
*
* \return 0 if successful, or MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx, const unsigned char *key,
unsigned int keybits );
/**
* \brief Blowfish-ECB block encryption/decryption
* \brief Perform a Blowfish-ECB block encryption/decryption operation.
*
* \param ctx Blowfish context
* \param mode MBEDTLS_BLOWFISH_ENCRYPT or MBEDTLS_BLOWFISH_DECRYPT
* \param input 8-byte input block
* \param output 8-byte output block
* \param ctx The Blowfish context to use. This must be initialized
* and bound to a key.
* \param mode The mode of operation. Possible values are
* #MBEDTLS_BLOWFISH_ENCRYPT for encryption, or
* #MBEDTLS_BLOWFISH_DECRYPT for decryption.
* \param input The input block. This must be a readable buffer
* of size \c 8 Bytes.
* \param output The output block. This must be a writable buffer
* of size \c 8 Bytes.
*
* \return 0 if successful
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx,
int mode,
@ -103,9 +131,7 @@ int mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/**
* \brief Blowfish-CBC buffer encryption/decryption
* Length should be a multiple of the block
* size (8 bytes)
* \brief Perform a Blowfish-CBC buffer encryption/decryption operation.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
@ -115,15 +141,22 @@ int mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx,
* IV, you should either save it manually or use the cipher
* module instead.
*
* \param ctx Blowfish context
* \param mode MBEDTLS_BLOWFISH_ENCRYPT or MBEDTLS_BLOWFISH_DECRYPT
* \param length length of the input data
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
* \param ctx The Blowfish context to use. This must be initialized
* and bound to a key.
* \param mode The mode of operation. Possible values are
* #MBEDTLS_BLOWFISH_ENCRYPT for encryption, or
* #MBEDTLS_BLOWFISH_DECRYPT for decryption.
* \param length The length of the input data in Bytes. This must be
* multiple of \c 8.
* \param iv The initialization vector. This must be a read/write buffer
* of length \c 8 Bytes. It is updated by this function.
* \param input The input data. This must be a readable buffer of length
* \p length Bytes.
* \param output The output data. This must be a writable buffer of length
* \p length Bytes.
*
* \return 0 if successful, or
* MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
int mode,
@ -135,7 +168,7 @@ int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
#if defined(MBEDTLS_CIPHER_MODE_CFB)
/**
* \brief Blowfish CFB buffer encryption/decryption.
* \brief Perform a Blowfish CFB buffer encryption/decryption operation.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
@ -145,15 +178,25 @@ int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
* IV, you should either save it manually or use the cipher
* module instead.
*
* \param ctx Blowfish context
* \param mode MBEDTLS_BLOWFISH_ENCRYPT or MBEDTLS_BLOWFISH_DECRYPT
* \param length length of the input data
* \param iv_off offset in IV (updated after use)
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
* \param ctx The Blowfish context to use. This must be initialized
* and bound to a key.
* \param mode The mode of operation. Possible values are
* #MBEDTLS_BLOWFISH_ENCRYPT for encryption, or
* #MBEDTLS_BLOWFISH_DECRYPT for decryption.
* \param length The length of the input data in Bytes.
* \param iv_off The offset in the initialiation vector.
* The value pointed to must be smaller than \c 8 Bytes.
* It is updated by this function to support the aforementioned
* streaming usage.
* \param iv The initialization vector. This must be a read/write buffer
* of size \c 8 Bytes. It is updated after use.
* \param input The input data. This must be a readable buffer of length
* \p length Bytes.
* \param output The output data. This must be a writable buffer of length
* \p length Bytes.
*
* \return 0 if successful
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx,
int mode,
@ -166,22 +209,67 @@ int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx,
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/**
* \brief Blowfish-CTR buffer encryption/decryption
* \brief Perform a Blowfish-CTR buffer encryption/decryption operation.
*
* Warning: You have to keep the maximum use of your counter in mind!
* \warning You must never reuse a nonce value with the same key. Doing so
* would void the encryption for the two messages encrypted with
* the same nonce and key.
*
* \param ctx Blowfish context
* \param length The length of the data
* There are two common strategies for managing nonces with CTR:
*
* 1. You can handle everything as a single message processed over
* successive calls to this function. In that case, you want to
* set \p nonce_counter and \p nc_off to 0 for the first call, and
* then preserve the values of \p nonce_counter, \p nc_off and \p
* stream_block across calls to this function as they will be
* updated by this function.
*
* With this strategy, you must not encrypt more than 2**64
* blocks of data with the same key.
*
* 2. You can encrypt separate messages by dividing the \p
* nonce_counter buffer in two areas: the first one used for a
* per-message nonce, handled by yourself, and the second one
* updated by this function internally.
*
* For example, you might reserve the first 4 bytes for the
* per-message nonce, and the last 4 bytes for internal use. In that
* case, before calling this function on a new message you need to
* set the first 4 bytes of \p nonce_counter to your chosen nonce
* value, the last 4 to 0, and \p nc_off to 0 (which will cause \p
* stream_block to be ignored). That way, you can encrypt at most
* 2**32 messages of up to 2**32 blocks each with the same key.
*
* The per-message nonce (or information sufficient to reconstruct
* it) needs to be communicated with the ciphertext and must be unique.
* The recommended way to ensure uniqueness is to use a message
* counter.
*
* Note that for both stategies, sizes are measured in blocks and
* that a Blowfish block is 8 bytes.
*
* \warning Upon return, \p stream_block contains sensitive data. Its
* content must not be written to insecure storage and should be
* securely discarded as soon as it's no longer needed.
*
* \param ctx The Blowfish context to use. This must be initialized
* and bound to a key.
* \param length The length of the input data in Bytes.
* \param nc_off The offset in the current stream_block (for resuming
* within current cipher stream). The offset pointer to
* should be 0 at the start of a stream.
* \param nonce_counter The 64-bit nonce and counter.
* \param stream_block The saved stream-block for resuming. Is overwritten
* by the function.
* \param input The input data stream
* \param output The output data stream
* within current cipher stream). The offset pointer
* should be \c 0 at the start of a stream and must be
* smaller than \c 8. It is updated by this function.
* \param nonce_counter The 64-bit nonce and counter. This must point to a
* read/write buffer of length \c 8 Bytes.
* \param stream_block The saved stream-block for resuming. This must point to
* a read/write buffer of length \c 8 Bytes.
* \param input The input data. This must be a readable buffer of
* length \p length Bytes.
* \param output The output data. This must be a writable buffer of
* length \p length Bytes.
*
* \return 0 if successful
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx,
size_t length,
@ -196,8 +284,4 @@ int mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx,
}
#endif
#else /* MBEDTLS_BLOWFISH_ALT */
#include "blowfish_alt.h"
#endif /* MBEDTLS_BLOWFISH_ALT */
#endif /* blowfish.h */

View File

@ -1,8 +1,9 @@
/**
* \file bn_mul.h
*
* \brief Multi-precision integer library
*
* \brief Multi-precision integer library
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -37,6 +38,12 @@
#ifndef MBEDTLS_BN_MUL_H
#define MBEDTLS_BN_MUL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "bignum.h"
#if defined(MBEDTLS_HAVE_ASM)
@ -48,7 +55,14 @@
/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */
#if defined(__GNUC__) && \
( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 )
#if defined(__i386__)
/*
* Disable use of the i386 assembly code below if option -O0, to disable all
* compiler optimisations, is passed, detected with __OPTIMIZE__
* This is done as the number of registers used in the assembly code doesn't
* work with the -O0 option.
*/
#if defined(__i386__) && defined(__OPTIMIZE__)
#define MULADDC_INIT \
asm( \
@ -141,7 +155,7 @@
"movl %%esi, %3 \n\t" \
: "=m" (t), "=m" (c), "=m" (d), "=m" (s) \
: "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \
: "eax", "ecx", "edx", "esi", "edi" \
: "eax", "ebx", "ecx", "edx", "esi", "edi" \
);
#else
@ -153,7 +167,7 @@
"movl %%esi, %3 \n\t" \
: "=m" (t), "=m" (c), "=m" (d), "=m" (s) \
: "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \
: "eax", "ecx", "edx", "esi", "edi" \
: "eax", "ebx", "ecx", "edx", "esi", "edi" \
);
#endif /* SSE2 */
#endif /* i386 */
@ -162,19 +176,19 @@
#define MULADDC_INIT \
asm( \
"xorq %%r8, %%r8 \n\t"
"xorq %%r8, %%r8\n"
#define MULADDC_CORE \
"movq (%%rsi), %%rax \n\t" \
"mulq %%rbx \n\t" \
"addq $8, %%rsi \n\t" \
"addq %%rcx, %%rax \n\t" \
"movq %%r8, %%rcx \n\t" \
"adcq $0, %%rdx \n\t" \
"nop \n\t" \
"addq %%rax, (%%rdi) \n\t" \
"adcq %%rdx, %%rcx \n\t" \
"addq $8, %%rdi \n\t"
"movq (%%rsi), %%rax\n" \
"mulq %%rbx\n" \
"addq $8, %%rsi\n" \
"addq %%rcx, %%rax\n" \
"movq %%r8, %%rcx\n" \
"adcq $0, %%rdx\n" \
"nop \n" \
"addq %%rax, (%%rdi)\n" \
"adcq %%rdx, %%rcx\n" \
"addq $8, %%rdi\n"
#define MULADDC_STOP \
: "+c" (c), "+D" (d), "+S" (s) \
@ -520,7 +534,7 @@
"swi r3, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r3", "r4" "r5", "r6", "r7", "r8", \
: "r3", "r4", "r5", "r6", "r7", "r8", \
"r9", "r10", "r11", "r12", "r13" \
);
@ -557,9 +571,8 @@
#endif /* TriCore */
/*
* gcc -O0 by default uses r7 for the frame pointer, so it complains about our
* use of r7 below, unless -fomit-frame-pointer is passed. Unfortunately,
* passing that option is not easy when building with yotta.
* Note, gcc -O0 by default uses r7 for the frame pointer, so it complains about
* our use of r7 below, unless -fomit-frame-pointer is passed.
*
* On the other hand, -fomit-frame-pointer is implied by any -Ox options with
* x !=0, which we can detect using __OPTIMIZE__ (which is also defined by
@ -629,6 +642,23 @@
"r6", "r7", "r8", "r9", "cc" \
);
#elif defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1)
#define MULADDC_INIT \
asm(
#define MULADDC_CORE \
"ldr r0, [%0], #4 \n\t" \
"ldr r1, [%1] \n\t" \
"umaal r1, %2, %3, r0 \n\t" \
"str r1, [%1], #4 \n\t"
#define MULADDC_STOP \
: "=r" (s), "=r" (d), "=r" (c) \
: "r" (b), "0" (s), "1" (d), "2" (c) \
: "r0", "r1", "memory" \
);
#else
#define MULADDC_INIT \
@ -726,7 +756,7 @@
"sw $10, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "$9", "$10", "$11", "$12", "$13", "$14", "$15" \
: "$9", "$10", "$11", "$12", "$13", "$14", "$15", "lo", "hi" \
);
#endif /* MIPS */

View File

@ -2,7 +2,8 @@
* \file camellia.h
*
* \brief Camellia block cipher
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -32,77 +33,107 @@
#include <stddef.h>
#include <stdint.h>
#include "platform_util.h"
#define MBEDTLS_CAMELLIA_ENCRYPT 1
#define MBEDTLS_CAMELLIA_DECRYPT 0
#define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH -0x0024 /**< Invalid key length. */
#define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026 /**< Invalid data input length. */
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( -0x0024 )
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#define MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA -0x0024 /**< Bad input data. */
#if !defined(MBEDTLS_CAMELLIA_ALT)
// Regular implementation
//
#define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026 /**< Invalid data input length. */
/* MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED is deprecated and should not be used.
*/
#define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED -0x0027 /**< Camellia hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_CAMELLIA_ALT)
// Regular implementation
//
/**
* \brief CAMELLIA context structure
*/
typedef struct
typedef struct mbedtls_camellia_context
{
int nr; /*!< number of rounds */
uint32_t rk[68]; /*!< CAMELLIA round keys */
}
mbedtls_camellia_context;
#else /* MBEDTLS_CAMELLIA_ALT */
#include "camellia_alt.h"
#endif /* MBEDTLS_CAMELLIA_ALT */
/**
* \brief Initialize CAMELLIA context
* \brief Initialize a CAMELLIA context.
*
* \param ctx CAMELLIA context to be initialized
* \param ctx The CAMELLIA context to be initialized.
* This must not be \c NULL.
*/
void mbedtls_camellia_init( mbedtls_camellia_context *ctx );
/**
* \brief Clear CAMELLIA context
* \brief Clear a CAMELLIA context.
*
* \param ctx CAMELLIA context to be cleared
* \param ctx The CAMELLIA context to be cleared. This may be \c NULL,
* in which case this function returns immediately. If it is not
* \c NULL, it must be initialized.
*/
void mbedtls_camellia_free( mbedtls_camellia_context *ctx );
/**
* \brief CAMELLIA key schedule (encryption)
* \brief Perform a CAMELLIA key schedule operation for encryption.
*
* \param ctx CAMELLIA context to be initialized
* \param key encryption key
* \param keybits must be 128, 192 or 256
* \param ctx The CAMELLIA context to use. This must be initialized.
* \param key The encryption key to use. This must be a readable buffer
* of size \p keybits Bits.
* \param keybits The length of \p key in Bits. This must be either \c 128,
* \c 192 or \c 256.
*
* \return 0 if successful, or MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, const unsigned char *key,
unsigned int keybits );
int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx,
const unsigned char *key,
unsigned int keybits );
/**
* \brief CAMELLIA key schedule (decryption)
* \brief Perform a CAMELLIA key schedule operation for decryption.
*
* \param ctx CAMELLIA context to be initialized
* \param key decryption key
* \param keybits must be 128, 192 or 256
* \param ctx The CAMELLIA context to use. This must be initialized.
* \param key The decryption key. This must be a readable buffer
* of size \p keybits Bits.
* \param keybits The length of \p key in Bits. This must be either \c 128,
* \c 192 or \c 256.
*
* \return 0 if successful, or MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_camellia_setkey_dec( mbedtls_camellia_context *ctx, const unsigned char *key,
unsigned int keybits );
int mbedtls_camellia_setkey_dec( mbedtls_camellia_context *ctx,
const unsigned char *key,
unsigned int keybits );
/**
* \brief CAMELLIA-ECB block encryption/decryption
* \brief Perform a CAMELLIA-ECB block encryption/decryption operation.
*
* \param ctx CAMELLIA context
* \param mode MBEDTLS_CAMELLIA_ENCRYPT or MBEDTLS_CAMELLIA_DECRYPT
* \param input 16-byte input block
* \param output 16-byte output block
* \param ctx The CAMELLIA context to use. This must be initialized
* and bound to a key.
* \param mode The mode of operation. This must be either
* #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
* \param input The input block. This must be a readable buffer
* of size \c 16 Bytes.
* \param output The output block. This must be a writable buffer
* of size \c 16 Bytes.
*
* \return 0 if successful
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx,
int mode,
@ -111,9 +142,7 @@ int mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/**
* \brief CAMELLIA-CBC buffer encryption/decryption
* Length should be a multiple of the block
* size (16 bytes)
* \brief Perform a CAMELLIA-CBC buffer encryption/decryption operation.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
@ -123,15 +152,22 @@ int mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx,
* IV, you should either save it manually or use the cipher
* module instead.
*
* \param ctx CAMELLIA context
* \param mode MBEDTLS_CAMELLIA_ENCRYPT or MBEDTLS_CAMELLIA_DECRYPT
* \param length length of the input data
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
* \param ctx The CAMELLIA context to use. This must be initialized
* and bound to a key.
* \param mode The mode of operation. This must be either
* #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
* \param length The length in Bytes of the input data \p input.
* This must be a multiple of \c 16 Bytes.
* \param iv The initialization vector. This must be a read/write buffer
* of length \c 16 Bytes. It is updated to allow streaming
* use as explained above.
* \param input The buffer holding the input data. This must point to a
* readable buffer of length \p length Bytes.
* \param output The buffer holding the output data. This must point to a
* writable buffer of length \p length Bytes.
*
* \return 0 if successful, or
* MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,
int mode,
@ -143,11 +179,14 @@ int mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,
#if defined(MBEDTLS_CIPHER_MODE_CFB)
/**
* \brief CAMELLIA-CFB128 buffer encryption/decryption
* \brief Perform a CAMELLIA-CFB128 buffer encryption/decryption
* operation.
*
* Note: Due to the nature of CFB you should use the same key schedule for
* both encryption and decryption. So a context initialized with
* mbedtls_camellia_setkey_enc() for both MBEDTLS_CAMELLIA_ENCRYPT and CAMELLIE_DECRYPT.
* \note Due to the nature of CFB mode, you should use the same
* key for both encryption and decryption. In particular, calls
* to this function should be preceded by a key-schedule via
* mbedtls_camellia_setkey_enc() regardless of whether \p mode
* is #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the function same function again on the following
@ -157,16 +196,24 @@ int mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,
* IV, you should either save it manually or use the cipher
* module instead.
*
* \param ctx CAMELLIA context
* \param mode MBEDTLS_CAMELLIA_ENCRYPT or MBEDTLS_CAMELLIA_DECRYPT
* \param length length of the input data
* \param iv_off offset in IV (updated after use)
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
* \param ctx The CAMELLIA context to use. This must be initialized
* and bound to a key.
* \param mode The mode of operation. This must be either
* #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
* \param length The length of the input data \p input. Any value is allowed.
* \param iv_off The current offset in the IV. This must be smaller
* than \c 16 Bytes. It is updated after this call to allow
* the aforementioned streaming usage.
* \param iv The initialization vector. This must be a read/write buffer
* of length \c 16 Bytes. It is updated after this call to
* allow the aforementioned streaming usage.
* \param input The buffer holding the input data. This must be a readable
* buffer of size \p length Bytes.
* \param output The buffer to hold the output data. This must be a writable
* buffer of length \p length Bytes.
*
* \return 0 if successful, or
* MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx,
int mode,
@ -179,26 +226,78 @@ int mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx,
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/**
* \brief CAMELLIA-CTR buffer encryption/decryption
* \brief Perform a CAMELLIA-CTR buffer encryption/decryption operation.
*
* Warning: You have to keep the maximum use of your counter in mind!
* *note Due to the nature of CTR mode, you should use the same
* key for both encryption and decryption. In particular, calls
* to this function should be preceded by a key-schedule via
* mbedtls_camellia_setkey_enc() regardless of whether \p mode
* is #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
*
* Note: Due to the nature of CTR you should use the same key schedule for
* both encryption and decryption. So a context initialized with
* mbedtls_camellia_setkey_enc() for both MBEDTLS_CAMELLIA_ENCRYPT and MBEDTLS_CAMELLIA_DECRYPT.
* \warning You must never reuse a nonce value with the same key. Doing so
* would void the encryption for the two messages encrypted with
* the same nonce and key.
*
* \param ctx CAMELLIA context
* \param length The length of the data
* \param nc_off The offset in the current stream_block (for resuming
* There are two common strategies for managing nonces with CTR:
*
* 1. You can handle everything as a single message processed over
* successive calls to this function. In that case, you want to
* set \p nonce_counter and \p nc_off to 0 for the first call, and
* then preserve the values of \p nonce_counter, \p nc_off and \p
* stream_block across calls to this function as they will be
* updated by this function.
*
* With this strategy, you must not encrypt more than 2**128
* blocks of data with the same key.
*
* 2. You can encrypt separate messages by dividing the \p
* nonce_counter buffer in two areas: the first one used for a
* per-message nonce, handled by yourself, and the second one
* updated by this function internally.
*
* For example, you might reserve the first \c 12 Bytes for the
* per-message nonce, and the last \c 4 Bytes for internal use.
* In that case, before calling this function on a new message you
* need to set the first \c 12 Bytes of \p nonce_counter to your
* chosen nonce value, the last four to \c 0, and \p nc_off to \c 0
* (which will cause \p stream_block to be ignored). That way, you
* can encrypt at most \c 2**96 messages of up to \c 2**32 blocks
* each with the same key.
*
* The per-message nonce (or information sufficient to reconstruct
* it) needs to be communicated with the ciphertext and must be
* unique. The recommended way to ensure uniqueness is to use a
* message counter. An alternative is to generate random nonces,
* but this limits the number of messages that can be securely
* encrypted: for example, with 96-bit random nonces, you should
* not encrypt more than 2**32 messages with the same key.
*
* Note that for both stategies, sizes are measured in blocks and
* that a CAMELLIA block is \c 16 Bytes.
*
* \warning Upon return, \p stream_block contains sensitive data. Its
* content must not be written to insecure storage and should be
* securely discarded as soon as it's no longer needed.
*
* \param ctx The CAMELLIA context to use. This must be initialized
* and bound to a key.
* \param length The length of the input data \p input in Bytes.
* Any value is allowed.
* \param nc_off The offset in the current \p stream_block (for resuming
* within current cipher stream). The offset pointer to
* should be 0 at the start of a stream.
* \param nonce_counter The 128-bit nonce and counter.
* \param stream_block The saved stream-block for resuming. Is overwritten
* by the function.
* \param input The input data stream
* \param output The output data stream
* should be \c 0 at the start of a stream. It is updated
* at the end of this call.
* \param nonce_counter The 128-bit nonce and counter. This must be a read/write
* buffer of length \c 16 Bytes.
* \param stream_block The saved stream-block for resuming. This must be a
* read/write buffer of length \c 16 Bytes.
* \param input The input data stream. This must be a readable buffer of
* size \p length Bytes.
* \param output The output data stream. This must be a writable buffer
* of size \p length Bytes.
*
* \return 0 if successful
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx,
size_t length,
@ -209,17 +308,7 @@ int mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx,
unsigned char *output );
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_CAMELLIA_ALT */
#include "camellia_alt.h"
#endif /* MBEDTLS_CAMELLIA_ALT */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
@ -228,6 +317,8 @@ extern "C" {
*/
int mbedtls_camellia_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

View File

@ -1,9 +1,34 @@
/**
* \file ccm.h
*
* \brief Counter with CBC-MAC (CCM) for 128-bit block ciphers
* \brief This file provides an API for the CCM authenticated encryption
* mode for block ciphers.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* CCM combines Counter mode encryption with CBC-MAC authentication
* for 128-bit block ciphers.
*
* Input to CCM includes the following elements:
* <ul><li>Payload - data that is both authenticated and encrypted.</li>
* <li>Associated data (Adata) - data that is authenticated but not
* encrypted, For example, a header.</li>
* <li>Nonce - A unique value that is assigned to the payload and the
* associated data.</li></ul>
*
* Definition of CCM:
* http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
* RFC 3610 "Counter with CBC-MAC (CCM)"
*
* Related:
* RFC 5116 "An Interface and Algorithms for Authenticated Encryption"
*
* Definition of CCM*:
* IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks
* Integer representation is fixed most-significant-octet-first order and
* the representation of octets is most-significant-bit-first order. This is
* consistent with RFC 3610.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,46 +43,69 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_CCM_H
#define MBEDTLS_CCM_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "cipher.h"
#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to function. */
#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */
#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to the function. */
#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */
/* MBEDTLS_ERR_CCM_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_CCM_ALT)
// Regular implementation
//
/**
* \brief CCM context structure
* \brief The CCM context-type definition. The CCM context is passed
* to the APIs called.
*/
typedef struct {
mbedtls_cipher_context_t cipher_ctx; /*!< cipher context used */
typedef struct mbedtls_ccm_context
{
mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */
}
mbedtls_ccm_context;
#else /* MBEDTLS_CCM_ALT */
#include "ccm_alt.h"
#endif /* MBEDTLS_CCM_ALT */
/**
* \brief Initialize CCM context (just makes references valid)
* Makes the context ready for mbedtls_ccm_setkey() or
* mbedtls_ccm_free().
* \brief This function initializes the specified CCM context,
* to make references valid, and prepare the context
* for mbedtls_ccm_setkey() or mbedtls_ccm_free().
*
* \param ctx CCM context to initialize
* \param ctx The CCM context to initialize. This must not be \c NULL.
*/
void mbedtls_ccm_init( mbedtls_ccm_context *ctx );
/**
* \brief CCM initialization (encryption and decryption)
* \brief This function initializes the CCM context set in the
* \p ctx parameter and sets the encryption key.
*
* \param ctx CCM context to be initialized
* \param cipher cipher to use (a 128-bit block cipher)
* \param key encryption key
* \param keybits key size in bits (must be acceptable by the cipher)
* \param ctx The CCM context to initialize. This must be an initialized
* context.
* \param cipher The 128-bit block cipher to use.
* \param key The encryption key. This must not be \c NULL.
* \param keybits The key size in bits. This must be acceptable by the cipher.
*
* \return 0 if successful, or a cipher specific error code
* \return \c 0 on success.
* \return A CCM or cipher-specific error code on failure.
*/
int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
mbedtls_cipher_id_t cipher,
@ -65,36 +113,49 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
unsigned int keybits );
/**
* \brief Free a CCM context and underlying cipher sub-context
* \brief This function releases and clears the specified CCM context
* and underlying cipher sub-context.
*
* \param ctx CCM context to free
* \param ctx The CCM context to clear. If this is \c NULL, the function
* has no effect. Otherwise, this must be initialized.
*/
void mbedtls_ccm_free( mbedtls_ccm_context *ctx );
/**
* \brief CCM buffer encryption
* \brief This function encrypts a buffer using CCM.
*
* \param ctx CCM context
* \param length length of the input data in bytes
* \param iv nonce (initialization vector)
* \param iv_len length of IV in bytes
* must be 2, 3, 4, 5, 6, 7 or 8
* \param add additional data
* \param add_len length of additional data in bytes
* must be less than 2^16 - 2^8
* \param input buffer holding the input data
* \param output buffer for holding the output data
* must be at least 'length' bytes wide
* \param tag buffer for holding the tag
* \param tag_len length of the tag to generate in bytes
* must be 4, 6, 8, 10, 14 or 16
* \note The tag is written to a separate buffer. To concatenate
* the \p tag with the \p output, as done in <em>RFC-3610:
* Counter with CBC-MAC (CCM)</em>, use
* \p tag = \p output + \p length, and make sure that the
* output buffer is at least \p length + \p tag_len wide.
*
* \note The tag is written to a separate buffer. To get the tag
* concatenated with the output as in the CCM spec, use
* tag = output + length and make sure the output buffer is
* at least length + tag_len wide.
* \param ctx The CCM context to use for encryption. This must be
* initialized and bound to a key.
* \param length The length of the input data in Bytes.
* \param iv The initialization vector (nonce). This must be a readable
* buffer of at least \p iv_len Bytes.
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. If \p add_len is greater than
* zero, \p add must be a readable buffer of at least that
* length.
* \param add_len The length of additional data in Bytes.
* This must be less than `2^16 - 2^8`.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
* that length.
* \param output The buffer holding the output data. If \p length is greater
* than zero, \p output must be a writable buffer of at least
* that length.
* \param tag The buffer holding the authentication field. This must be a
* readable buffer of at least \p tag_len Bytes.
* \param tag_len The length of the authentication field to generate in Bytes:
* 4, 6, 8, 10, 12, 14 or 16.
*
* \return 0 if successful
* \return \c 0 on success.
* \return A CCM or cipher-specific error code on failure.
*/
int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
@ -103,21 +164,83 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
unsigned char *tag, size_t tag_len );
/**
* \brief CCM buffer authenticated decryption
* \brief This function encrypts a buffer using CCM*.
*
* \param ctx CCM context
* \param length length of the input data
* \param iv initialization vector
* \param iv_len length of IV
* \param add additional data
* \param add_len length of additional data
* \param input buffer holding the input data
* \param output buffer for holding the output data
* \param tag buffer holding the tag
* \param tag_len length of the tag
* \note The tag is written to a separate buffer. To concatenate
* the \p tag with the \p output, as done in <em>RFC-3610:
* Counter with CBC-MAC (CCM)</em>, use
* \p tag = \p output + \p length, and make sure that the
* output buffer is at least \p length + \p tag_len wide.
*
* \return 0 if successful and authenticated,
* MBEDTLS_ERR_CCM_AUTH_FAILED if tag does not match
* \note When using this function in a variable tag length context,
* the tag length has to be encoded into the \p iv passed to
* this function.
*
* \param ctx The CCM context to use for encryption. This must be
* initialized and bound to a key.
* \param length The length of the input data in Bytes.
* \param iv The initialization vector (nonce). This must be a readable
* buffer of at least \p iv_len Bytes.
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. This must be a readable buffer of
* at least \p add_len Bytes.
* \param add_len The length of additional data in Bytes.
* This must be less than 2^16 - 2^8.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
* that length.
* \param output The buffer holding the output data. If \p length is greater
* than zero, \p output must be a writable buffer of at least
* that length.
* \param tag The buffer holding the authentication field. This must be a
* readable buffer of at least \p tag_len Bytes.
* \param tag_len The length of the authentication field to generate in Bytes:
* 0, 4, 6, 8, 10, 12, 14 or 16.
*
* \warning Passing \c 0 as \p tag_len means that the message is no
* longer authenticated.
*
* \return \c 0 on success.
* \return A CCM or cipher-specific error code on failure.
*/
int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len );
/**
* \brief This function performs a CCM authenticated decryption of a
* buffer.
*
* \param ctx The CCM context to use for decryption. This must be
* initialized and bound to a key.
* \param length The length of the input data in Bytes.
* \param iv The initialization vector (nonce). This must be a readable
* buffer of at least \p iv_len Bytes.
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. This must be a readable buffer
* of at least that \p add_len Bytes..
* \param add_len The length of additional data in Bytes.
* This must be less than 2^16 - 2^8.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
* that length.
* \param output The buffer holding the output data. If \p length is greater
* than zero, \p output must be a writable buffer of at least
* that length.
* \param tag The buffer holding the authentication field. This must be a
* readable buffer of at least \p tag_len Bytes.
* \param tag_len The length of the authentication field to generate in Bytes:
* 4, 6, 8, 10, 12, 14 or 16.
*
* \return \c 0 on success. This indicates that the message is authentic.
* \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.
* \return A cipher-specific error code on calculation failure.
*/
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
@ -125,11 +248,57 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len );
/**
* \brief This function performs a CCM* authenticated decryption of a
* buffer.
*
* \note When using this function in a variable tag length context,
* the tag length has to be decoded from \p iv and passed to
* this function as \p tag_len. (\p tag needs to be adjusted
* accordingly.)
*
* \param ctx The CCM context to use for decryption. This must be
* initialized and bound to a key.
* \param length The length of the input data in Bytes.
* \param iv The initialization vector (nonce). This must be a readable
* buffer of at least \p iv_len Bytes.
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. This must be a readable buffer of
* at least that \p add_len Bytes.
* \param add_len The length of additional data in Bytes.
* This must be less than 2^16 - 2^8.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
* that length.
* \param output The buffer holding the output data. If \p length is greater
* than zero, \p output must be a writable buffer of at least
* that length.
* \param tag The buffer holding the authentication field. This must be a
* readable buffer of at least \p tag_len Bytes.
* \param tag_len The length of the authentication field in Bytes.
* 0, 4, 6, 8, 10, 12, 14 or 16.
*
* \warning Passing \c 0 as \p tag_len means that the message is nos
* longer authenticated.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.
* \return A cipher-specific error code on calculation failure.
*/
int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len );
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/**
* \brief Checkup routine
* \brief The CCM checkup routine.
*
* \return 0 if successful, or 1 if the test failed
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_ccm_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

View File

@ -2,7 +2,8 @@
* \file certs.h
*
* \brief Sample certificates and DHM parameters for testing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_CERTS_H
#define MBEDTLS_CERTS_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#ifdef __cplusplus

View File

@ -0,0 +1,226 @@
/**
* \file chacha20.h
*
* \brief This file contains ChaCha20 definitions and functions.
*
* ChaCha20 is a stream cipher that can encrypt and decrypt
* information. ChaCha was created by Daniel Bernstein as a variant of
* its Salsa cipher https://cr.yp.to/chacha/chacha-20080128.pdf
* ChaCha20 is the variant with 20 rounds, that was also standardized
* in RFC 7539.
*
* \author Daniel King <damaki.gh@gmail.com>
*/
/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_CHACHA20_H
#define MBEDTLS_CHACHA20_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stdint.h>
#include <stddef.h>
#define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051 /**< Invalid input parameter(s). */
/* MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE is deprecated and should not be
* used. */
#define MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE -0x0053 /**< Feature not available. For example, s part of the API is not implemented. */
/* MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED is deprecated and should not be used.
*/
#define MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED -0x0055 /**< Chacha20 hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_CHACHA20_ALT)
typedef struct mbedtls_chacha20_context
{
uint32_t state[16]; /*! The state (before round operations). */
uint8_t keystream8[64]; /*! Leftover keystream bytes. */
size_t keystream_bytes_used; /*! Number of keystream bytes already used. */
}
mbedtls_chacha20_context;
#else /* MBEDTLS_CHACHA20_ALT */
#include "chacha20_alt.h"
#endif /* MBEDTLS_CHACHA20_ALT */
/**
* \brief This function initializes the specified ChaCha20 context.
*
* It must be the first API called before using
* the context.
*
* It is usually followed by calls to
* \c mbedtls_chacha20_setkey() and
* \c mbedtls_chacha20_starts(), then one or more calls to
* to \c mbedtls_chacha20_update(), and finally to
* \c mbedtls_chacha20_free().
*
* \param ctx The ChaCha20 context to initialize.
* This must not be \c NULL.
*/
void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx );
/**
* \brief This function releases and clears the specified
* ChaCha20 context.
*
* \param ctx The ChaCha20 context to clear. This may be \c NULL,
* in which case this function is a no-op. If it is not
* \c NULL, it must point to an initialized context.
*
*/
void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx );
/**
* \brief This function sets the encryption/decryption key.
*
* \note After using this function, you must also call
* \c mbedtls_chacha20_starts() to set a nonce before you
* start encrypting/decrypting data with
* \c mbedtls_chacha_update().
*
* \param ctx The ChaCha20 context to which the key should be bound.
* It must be initialized.
* \param key The encryption/decryption key. This must be \c 32 Bytes
* in length.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL.
*/
int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx,
const unsigned char key[32] );
/**
* \brief This function sets the nonce and initial counter value.
*
* \note A ChaCha20 context can be re-used with the same key by
* calling this function to change the nonce.
*
* \warning You must never use the same nonce twice with the same key.
* This would void any confidentiality guarantees for the
* messages encrypted with the same nonce and key.
*
* \param ctx The ChaCha20 context to which the nonce should be bound.
* It must be initialized and bound to a key.
* \param nonce The nonce. This must be \c 12 Bytes in size.
* \param counter The initial counter value. This is usually \c 0.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is
* NULL.
*/
int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx,
const unsigned char nonce[12],
uint32_t counter );
/**
* \brief This function encrypts or decrypts data.
*
* Since ChaCha20 is a stream cipher, the same operation is
* used for encrypting and decrypting data.
*
* \note The \p input and \p output pointers must either be equal or
* point to non-overlapping buffers.
*
* \note \c mbedtls_chacha20_setkey() and
* \c mbedtls_chacha20_starts() must be called at least once
* to setup the context before this function can be called.
*
* \note This function can be called multiple times in a row in
* order to encrypt of decrypt data piecewise with the same
* key and nonce.
*
* \param ctx The ChaCha20 context to use for encryption or decryption.
* It must be initialized and bound to a key and nonce.
* \param size The length of the input data in Bytes.
* \param input The buffer holding the input data.
* This pointer can be \c NULL if `size == 0`.
* \param output The buffer holding the output data.
* This must be able to hold \p size Bytes.
* This pointer can be \c NULL if `size == 0`.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,
size_t size,
const unsigned char *input,
unsigned char *output );
/**
* \brief This function encrypts or decrypts data with ChaCha20 and
* the given key and nonce.
*
* Since ChaCha20 is a stream cipher, the same operation is
* used for encrypting and decrypting data.
*
* \warning You must never use the same (key, nonce) pair more than
* once. This would void any confidentiality guarantees for
* the messages encrypted with the same nonce and key.
*
* \note The \p input and \p output pointers must either be equal or
* point to non-overlapping buffers.
*
* \param key The encryption/decryption key.
* This must be \c 32 Bytes in length.
* \param nonce The nonce. This must be \c 12 Bytes in size.
* \param counter The initial counter value. This is usually \c 0.
* \param size The length of the input data in Bytes.
* \param input The buffer holding the input data.
* This pointer can be \c NULL if `size == 0`.
* \param output The buffer holding the output data.
* This must be able to hold \p size Bytes.
* This pointer can be \c NULL if `size == 0`.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_chacha20_crypt( const unsigned char key[32],
const unsigned char nonce[12],
uint32_t counter,
size_t size,
const unsigned char* input,
unsigned char* output );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief The ChaCha20 checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_chacha20_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_CHACHA20_H */

View File

@ -0,0 +1,358 @@
/**
* \file chachapoly.h
*
* \brief This file contains the AEAD-ChaCha20-Poly1305 definitions and
* functions.
*
* ChaCha20-Poly1305 is an algorithm for Authenticated Encryption
* with Associated Data (AEAD) that can be used to encrypt and
* authenticate data. It is based on ChaCha20 and Poly1305 by Daniel
* Bernstein and was standardized in RFC 7539.
*
* \author Daniel King <damaki.gh@gmail.com>
*/
/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_CHACHAPOLY_H
#define MBEDTLS_CHACHAPOLY_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
/* for shared error codes */
#include "poly1305.h"
#define MBEDTLS_ERR_CHACHAPOLY_BAD_STATE -0x0054 /**< The requested operation is not permitted in the current state. */
#define MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED -0x0056 /**< Authenticated decryption failed: data was not authentic. */
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
MBEDTLS_CHACHAPOLY_ENCRYPT, /**< The mode value for performing encryption. */
MBEDTLS_CHACHAPOLY_DECRYPT /**< The mode value for performing decryption. */
}
mbedtls_chachapoly_mode_t;
#if !defined(MBEDTLS_CHACHAPOLY_ALT)
#include "chacha20.h"
typedef struct mbedtls_chachapoly_context
{
mbedtls_chacha20_context chacha20_ctx; /**< The ChaCha20 context. */
mbedtls_poly1305_context poly1305_ctx; /**< The Poly1305 context. */
uint64_t aad_len; /**< The length (bytes) of the Additional Authenticated Data. */
uint64_t ciphertext_len; /**< The length (bytes) of the ciphertext. */
int state; /**< The current state of the context. */
mbedtls_chachapoly_mode_t mode; /**< Cipher mode (encrypt or decrypt). */
}
mbedtls_chachapoly_context;
#else /* !MBEDTLS_CHACHAPOLY_ALT */
#include "chachapoly_alt.h"
#endif /* !MBEDTLS_CHACHAPOLY_ALT */
/**
* \brief This function initializes the specified ChaCha20-Poly1305 context.
*
* It must be the first API called before using
* the context. It must be followed by a call to
* \c mbedtls_chachapoly_setkey() before any operation can be
* done, and to \c mbedtls_chachapoly_free() once all
* operations with that context have been finished.
*
* In order to encrypt or decrypt full messages at once, for
* each message you should make a single call to
* \c mbedtls_chachapoly_crypt_and_tag() or
* \c mbedtls_chachapoly_auth_decrypt().
*
* In order to encrypt messages piecewise, for each
* message you should make a call to
* \c mbedtls_chachapoly_starts(), then 0 or more calls to
* \c mbedtls_chachapoly_update_aad(), then 0 or more calls to
* \c mbedtls_chachapoly_update(), then one call to
* \c mbedtls_chachapoly_finish().
*
* \warning Decryption with the piecewise API is discouraged! Always
* use \c mbedtls_chachapoly_auth_decrypt() when possible!
*
* If however this is not possible because the data is too
* large to fit in memory, you need to:
*
* - call \c mbedtls_chachapoly_starts() and (if needed)
* \c mbedtls_chachapoly_update_aad() as above,
* - call \c mbedtls_chachapoly_update() multiple times and
* ensure its output (the plaintext) is NOT used in any other
* way than placing it in temporary storage at this point,
* - call \c mbedtls_chachapoly_finish() to compute the
* authentication tag and compared it in constant time to the
* tag received with the ciphertext.
*
* If the tags are not equal, you must immediately discard
* all previous outputs of \c mbedtls_chachapoly_update(),
* otherwise you can now safely use the plaintext.
*
* \param ctx The ChachaPoly context to initialize. Must not be \c NULL.
*/
void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx );
/**
* \brief This function releases and clears the specified
* ChaCha20-Poly1305 context.
*
* \param ctx The ChachaPoly context to clear. This may be \c NULL, in which
* case this function is a no-op.
*/
void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx );
/**
* \brief This function sets the ChaCha20-Poly1305
* symmetric encryption key.
*
* \param ctx The ChaCha20-Poly1305 context to which the key should be
* bound. This must be initialized.
* \param key The \c 256 Bit (\c 32 Bytes) key.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,
const unsigned char key[32] );
/**
* \brief This function starts a ChaCha20-Poly1305 encryption or
* decryption operation.
*
* \warning You must never use the same nonce twice with the same key.
* This would void any confidentiality and authenticity
* guarantees for the messages encrypted with the same nonce
* and key.
*
* \note If the context is being used for AAD only (no data to
* encrypt or decrypt) then \p mode can be set to any value.
*
* \warning Decryption with the piecewise API is discouraged, see the
* warning on \c mbedtls_chachapoly_init().
*
* \param ctx The ChaCha20-Poly1305 context. This must be initialized
* and bound to a key.
* \param nonce The nonce/IV to use for the message.
* This must be a redable buffer of length \c 12 Bytes.
* \param mode The operation to perform: #MBEDTLS_CHACHAPOLY_ENCRYPT or
* #MBEDTLS_CHACHAPOLY_DECRYPT (discouraged, see warning).
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
const unsigned char nonce[12],
mbedtls_chachapoly_mode_t mode );
/**
* \brief This function feeds additional data to be authenticated
* into an ongoing ChaCha20-Poly1305 operation.
*
* The Additional Authenticated Data (AAD), also called
* Associated Data (AD) is only authenticated but not
* encrypted nor included in the encrypted output. It is
* usually transmitted separately from the ciphertext or
* computed locally by each party.
*
* \note This function is called before data is encrypted/decrypted.
* I.e. call this function to process the AAD before calling
* \c mbedtls_chachapoly_update().
*
* You may call this function multiple times to process
* an arbitrary amount of AAD. It is permitted to call
* this function 0 times, if no AAD is used.
*
* This function cannot be called any more if data has
* been processed by \c mbedtls_chachapoly_update(),
* or if the context has been finished.
*
* \warning Decryption with the piecewise API is discouraged, see the
* warning on \c mbedtls_chachapoly_init().
*
* \param ctx The ChaCha20-Poly1305 context. This must be initialized
* and bound to a key.
* \param aad_len The length in Bytes of the AAD. The length has no
* restrictions.
* \param aad Buffer containing the AAD.
* This pointer can be \c NULL if `aad_len == 0`.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA
* if \p ctx or \p aad are NULL.
* \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
* if the operations has not been started or has been
* finished, or if the AAD has been finished.
*/
int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,
const unsigned char *aad,
size_t aad_len );
/**
* \brief Thus function feeds data to be encrypted or decrypted
* into an on-going ChaCha20-Poly1305
* operation.
*
* The direction (encryption or decryption) depends on the
* mode that was given when calling
* \c mbedtls_chachapoly_starts().
*
* You may call this function multiple times to process
* an arbitrary amount of data. It is permitted to call
* this function 0 times, if no data is to be encrypted
* or decrypted.
*
* \warning Decryption with the piecewise API is discouraged, see the
* warning on \c mbedtls_chachapoly_init().
*
* \param ctx The ChaCha20-Poly1305 context to use. This must be initialized.
* \param len The length (in bytes) of the data to encrypt or decrypt.
* \param input The buffer containing the data to encrypt or decrypt.
* This pointer can be \c NULL if `len == 0`.
* \param output The buffer to where the encrypted or decrypted data is
* written. This must be able to hold \p len bytes.
* This pointer can be \c NULL if `len == 0`.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
* if the operation has not been started or has been
* finished.
* \return Another negative error code on other kinds of failure.
*/
int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,
size_t len,
const unsigned char *input,
unsigned char *output );
/**
* \brief This function finished the ChaCha20-Poly1305 operation and
* generates the MAC (authentication tag).
*
* \param ctx The ChaCha20-Poly1305 context to use. This must be initialized.
* \param mac The buffer to where the 128-bit (16 bytes) MAC is written.
*
* \warning Decryption with the piecewise API is discouraged, see the
* warning on \c mbedtls_chachapoly_init().
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
* if the operation has not been started or has been
* finished.
* \return Another negative error code on other kinds of failure.
*/
int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
unsigned char mac[16] );
/**
* \brief This function performs a complete ChaCha20-Poly1305
* authenticated encryption with the previously-set key.
*
* \note Before using this function, you must set the key with
* \c mbedtls_chachapoly_setkey().
*
* \warning You must never use the same nonce twice with the same key.
* This would void any confidentiality and authenticity
* guarantees for the messages encrypted with the same nonce
* and key.
*
* \param ctx The ChaCha20-Poly1305 context to use (holds the key).
* This must be initialized.
* \param length The length (in bytes) of the data to encrypt or decrypt.
* \param nonce The 96-bit (12 bytes) nonce/IV to use.
* \param aad The buffer containing the additional authenticated
* data (AAD). This pointer can be \c NULL if `aad_len == 0`.
* \param aad_len The length (in bytes) of the AAD data to process.
* \param input The buffer containing the data to encrypt or decrypt.
* This pointer can be \c NULL if `ilen == 0`.
* \param output The buffer to where the encrypted or decrypted data
* is written. This pointer can be \c NULL if `ilen == 0`.
* \param tag The buffer to where the computed 128-bit (16 bytes) MAC
* is written. This must not be \c NULL.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16] );
/**
* \brief This function performs a complete ChaCha20-Poly1305
* authenticated decryption with the previously-set key.
*
* \note Before using this function, you must set the key with
* \c mbedtls_chachapoly_setkey().
*
* \param ctx The ChaCha20-Poly1305 context to use (holds the key).
* \param length The length (in Bytes) of the data to decrypt.
* \param nonce The \c 96 Bit (\c 12 bytes) nonce/IV to use.
* \param aad The buffer containing the additional authenticated data (AAD).
* This pointer can be \c NULL if `aad_len == 0`.
* \param aad_len The length (in bytes) of the AAD data to process.
* \param tag The buffer holding the authentication tag.
* This must be a readable buffer of length \c 16 Bytes.
* \param input The buffer containing the data to decrypt.
* This pointer can be \c NULL if `ilen == 0`.
* \param output The buffer to where the decrypted data is written.
* This pointer can be \c NULL if `ilen == 0`.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED
* if the data was not authentic.
* \return Another negative error code on other kinds of failure.
*/
int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char tag[16],
const unsigned char *input,
unsigned char *output );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief The ChaCha20-Poly1305 checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_chachapoly_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_CHACHAPOLY_H */

View File

@ -2,8 +2,9 @@
* \file check_config.h
*
* \brief Consistency checks for configuration options
*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
*/
/*
* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -77,11 +78,20 @@
#error "MBEDTLS_DHM_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) && !defined(MBEDTLS_SSL_TRUNCATED_HMAC)
#error "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_CMAC_C) && \
!defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C)
#error "MBEDTLS_CMAC_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_NIST_KW_C) && \
( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) )
#error "MBEDTLS_NIST_KW_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C)
#error "MBEDTLS_ECDH_C defined, but not all prerequisites"
#endif
@ -98,6 +108,17 @@
#error "MBEDTLS_ECJPAKE_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE) && \
( defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) || \
defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) || \
defined(MBEDTLS_ECDSA_SIGN_ALT) || \
defined(MBEDTLS_ECDSA_VERIFY_ALT) || \
defined(MBEDTLS_ECDSA_GENKEY_ALT) || \
defined(MBEDTLS_ECP_INTERNAL_ALT) || \
defined(MBEDTLS_ECP_ALT) )
#error "MBEDTLS_ECP_RESTARTABLE defined, but it cannot coexist with an alternative ECP implementation"
#endif
#if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C)
#error "MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites"
#endif
@ -117,6 +138,10 @@
#error "MBEDTLS_ECP_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_ASN1_PARSE_C)
#error "MBEDTLS_PK_PARSE_C defined, but not all prerequesites"
#endif
#if defined(MBEDTLS_ENTROPY_C) && (!defined(MBEDTLS_SHA512_C) && \
!defined(MBEDTLS_SHA256_C))
#error "MBEDTLS_ENTROPY_C defined, but not all prerequisites"
@ -150,10 +175,46 @@
#error "MBEDTLS_GCM_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_RANDOMIZE_JAC_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_ADD_MIXED_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_ADD_MIXED_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_DOUBLE_JAC_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_NORMALIZE_JAC_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_RANDOMIZE_MXZ_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
#error "MBEDTLS_ECP_NORMALIZE_MXZ_ALT defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_HAVEGE_C) && !defined(MBEDTLS_TIMING_C)
#error "MBEDTLS_HAVEGE_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C)
#error "MBEDTLS_HKDF_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C)
#error "MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites"
#endif
@ -618,6 +679,15 @@
#error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64)
#error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously"
#endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */
#if ( defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64) ) && \
defined(MBEDTLS_HAVE_ASM)
#error "MBEDTLS_HAVE_INT32/MBEDTLS_HAVE_INT64 and MBEDTLS_HAVE_ASM cannot be defined simultaneously"
#endif /* (MBEDTLS_HAVE_INT32 || MBEDTLS_HAVE_INT64) && MBEDTLS_HAVE_ASM */
/*
* Avoid warning from -pedantic. This is a convenient place for this
* workaround since this is included by every single file before the

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,8 @@
* \brief Cipher wrappers.
*
* \author Adriaan de Jong <dejong@fox-it.com>
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -63,6 +64,14 @@ struct mbedtls_cipher_base_t
unsigned char *output );
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
/** Encrypt using OFB (Full length) */
int (*ofb_func)( void *ctx, size_t length, size_t *iv_off,
unsigned char *iv,
const unsigned char *input,
unsigned char *output );
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/** Encrypt using CTR */
int (*ctr_func)( void *ctx, size_t length, size_t *nc_off,
@ -70,6 +79,13 @@ struct mbedtls_cipher_base_t
const unsigned char *input, unsigned char *output );
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/** Encrypt or decrypt using XTS. */
int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length,
const unsigned char data_unit[16],
const unsigned char *input, unsigned char *output );
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
/** Encrypt using STREAM */
int (*stream_func)( void *ctx, size_t length,

View File

@ -1,10 +1,13 @@
/**
* \file cmac.h
*
* \brief Cipher-based Message Authentication Code (CMAC) Mode for
* Authentication
* \brief This file contains CMAC definitions and functions.
*
* Copyright (C) 2015-2016, ARM Limited, All Rights Reserved
* The Cipher-based Message Authentication Code (CMAC) Mode for
* Authentication is defined in <em>RFC-4493: The AES-CMAC Algorithm</em>.
*/
/*
* Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -19,113 +22,151 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_CMAC_H
#define MBEDTLS_CMAC_H
#include "mbedtls/cipher.h"
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "cipher.h"
#ifdef __cplusplus
extern "C" {
#endif
/* MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED -0x007A /**< CMAC hardware accelerator failed. */
#define MBEDTLS_AES_BLOCK_SIZE 16
#define MBEDTLS_DES3_BLOCK_SIZE 8
#if defined(MBEDTLS_AES_C)
#define MBEDTLS_CIPHER_BLKSIZE_MAX 16 /* longest used by CMAC is AES */
#define MBEDTLS_CIPHER_BLKSIZE_MAX 16 /**< The longest block used by CMAC is that of AES. */
#else
#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /* longest used by CMAC is 3DES */
#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /**< The longest block used by CMAC is that of 3DES. */
#endif
#if !defined(MBEDTLS_CMAC_ALT)
/**
* CMAC context structure - Contains internal state information only
* The CMAC context structure.
*/
struct mbedtls_cmac_context_t
{
/** Internal state of the CMAC algorithm */
/** The internal state of the CMAC algorithm. */
unsigned char state[MBEDTLS_CIPHER_BLKSIZE_MAX];
/** Unprocessed data - either data that was not block aligned and is still
* pending to be processed, or the final block */
* pending processing, or the final block. */
unsigned char unprocessed_block[MBEDTLS_CIPHER_BLKSIZE_MAX];
/** Length of data pending to be processed */
/** The length of data pending processing. */
size_t unprocessed_len;
};
#else /* !MBEDTLS_CMAC_ALT */
#include "cmac_alt.h"
#endif /* !MBEDTLS_CMAC_ALT */
/**
* \brief Set the CMAC key and prepare to authenticate the input
* data.
* Should be called with an initialised cipher context.
* \brief This function sets the CMAC key, and prepares to authenticate
* the input data.
* Must be called with an initialized cipher context.
*
* \param ctx Cipher context
* \param key CMAC key
* \param keybits length of the CMAC key in bits
* (must be acceptable by the cipher)
* \param ctx The cipher context used for the CMAC operation, initialized
* as one of the following types: MBEDTLS_CIPHER_AES_128_ECB,
* MBEDTLS_CIPHER_AES_192_ECB, MBEDTLS_CIPHER_AES_256_ECB,
* or MBEDTLS_CIPHER_DES_EDE3_ECB.
* \param key The CMAC key.
* \param keybits The length of the CMAC key in bits.
* Must be supported by the cipher.
*
* \return 0 if successful, or a cipher specific error code
* \return \c 0 on success.
* \return A cipher-specific error code on failure.
*/
int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,
const unsigned char *key, size_t keybits );
/**
* \brief Generic CMAC process buffer.
* Called between mbedtls_cipher_cmac_starts() or
* mbedtls_cipher_cmac_reset() and
* mbedtls_cipher_cmac_finish().
* May be called repeatedly.
* \brief This function feeds an input buffer into an ongoing CMAC
* computation.
*
* \param ctx CMAC context
* \param input buffer holding the data
* \param ilen length of the input data
* It is called between mbedtls_cipher_cmac_starts() or
* mbedtls_cipher_cmac_reset(), and mbedtls_cipher_cmac_finish().
* Can be called repeatedly.
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The cipher context used for the CMAC operation.
* \param input The buffer holding the input data.
* \param ilen The length of the input data.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
* if parameter verification fails.
*/
int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
const unsigned char *input, size_t ilen );
/**
* \brief Output CMAC.
* Called after mbedtls_cipher_cmac_update().
* Usually followed by mbedtls_cipher_cmac_reset(), then
* mbedtls_cipher_cmac_starts(), or mbedtls_cipher_free().
* \brief This function finishes the CMAC operation, and writes
* the result to the output buffer.
*
* \param ctx CMAC context
* \param output Generic CMAC checksum result
* It is called after mbedtls_cipher_cmac_update().
* It can be followed by mbedtls_cipher_cmac_reset() and
* mbedtls_cipher_cmac_update(), or mbedtls_cipher_free().
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The cipher context used for the CMAC operation.
* \param output The output buffer for the CMAC checksum result.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
* if parameter verification fails.
*/
int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,
unsigned char *output );
/**
* \brief Prepare to authenticate a new message with the same key.
* Called after mbedtls_cipher_cmac_finish() and before
* mbedtls_cipher_cmac_update().
* \brief This function prepares the authentication of another
* message with the same key as the previous CMAC
* operation.
*
* \param ctx CMAC context to be reset
* It is called after mbedtls_cipher_cmac_finish()
* and before mbedtls_cipher_cmac_update().
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The cipher context used for the CMAC operation.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
* if parameter verification fails.
*/
int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx );
/**
* \brief Output = Generic_CMAC( hmac key, input buffer )
* \brief This function calculates the full generic CMAC
* on the input buffer with the provided key.
*
* \param cipher_info message digest info
* \param key CMAC key
* \param keylen length of the CMAC key in bits
* \param input buffer holding the data
* \param ilen length of the input data
* \param output Generic CMAC-result
* The function allocates the context, performs the
* calculation, and frees the context.
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* The CMAC result is calculated as
* output = generic CMAC(cmac key, input buffer).
*
*
* \param cipher_info The cipher information.
* \param key The CMAC key.
* \param keylen The length of the CMAC key in bits.
* \param input The buffer holding the input data.
* \param ilen The length of the input data.
* \param output The buffer for the generic CMAC result.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
* if parameter verification fails.
*/
int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,
const unsigned char *key, size_t keylen,
@ -134,16 +175,21 @@ int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,
#if defined(MBEDTLS_AES_C)
/**
* \brief AES-CMAC-128-PRF
* Implementation of (AES-CMAC-PRF-128), as defined in RFC 4615
* \brief This function implements the AES-CMAC-PRF-128 pseudorandom
* function, as defined in
* <em>RFC-4615: The Advanced Encryption Standard-Cipher-based
* Message Authentication Code-Pseudo-Random Function-128
* (AES-CMAC-PRF-128) Algorithm for the Internet Key
* Exchange Protocol (IKE).</em>
*
* \param key PRF key
* \param key_len PRF key length in bytes
* \param input buffer holding the input data
* \param in_len length of the input data in bytes
* \param output buffer holding the generated pseudorandom output (16 bytes)
* \param key The key to use.
* \param key_len The key length in Bytes.
* \param input The buffer holding the input data.
* \param in_len The length of the input data in Bytes.
* \param output The buffer holding the generated 16 Bytes of
* pseudorandom output.
*
* \return 0 if successful
* \return \c 0 on success.
*/
int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len,
const unsigned char *input, size_t in_len,
@ -152,9 +198,10 @@ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len,
#if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) )
/**
* \brief Checkup routine
* \brief The CMAC checkup routine.
*
* \return 0 if successful, or 1 if the test failed
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_cmac_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */

View File

@ -5,7 +5,8 @@
* for the PolarSSL naming conventions.
*
* \deprecated Use the new names directly instead
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -24,6 +25,12 @@
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if ! defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
@ -207,9 +214,6 @@
#if defined MBEDTLS_ERROR_C
#define POLARSSL_ERROR_C MBEDTLS_ERROR_C
#endif
#if defined MBEDTLS_ERROR_STRERROR_BC
#define POLARSSL_ERROR_STRERROR_BC MBEDTLS_ERROR_STRERROR_BC
#endif
#if defined MBEDTLS_ERROR_STRERROR_DUMMY
#define POLARSSL_ERROR_STRERROR_DUMMY MBEDTLS_ERROR_STRERROR_DUMMY
#endif
@ -318,9 +322,6 @@
#if defined MBEDTLS_MEMORY_BUFFER_ALLOC_C
#define POLARSSL_MEMORY_BUFFER_ALLOC_C MBEDTLS_MEMORY_BUFFER_ALLOC_C
#endif
#if defined MBEDTLS_MEMORY_C
#define POLARSSL_MEMORY_C MBEDTLS_MEMORY_C
#endif
#if defined MBEDTLS_MEMORY_DEBUG
#define POLARSSL_MEMORY_DEBUG MBEDTLS_MEMORY_DEBUG
#endif
@ -345,9 +346,6 @@
#if defined MBEDTLS_PADLOCK_C
#define POLARSSL_PADLOCK_C MBEDTLS_PADLOCK_C
#endif
#if defined MBEDTLS_PBKDF2_C
#define POLARSSL_PBKDF2_C MBEDTLS_PBKDF2_C
#endif
#if defined MBEDTLS_PEM_PARSE_C
#define POLARSSL_PEM_PARSE_C MBEDTLS_PEM_PARSE_C
#endif
@ -429,9 +427,6 @@
#if defined MBEDTLS_PLATFORM_STD_FREE
#define POLARSSL_PLATFORM_STD_FREE MBEDTLS_PLATFORM_STD_FREE
#endif
#if defined MBEDTLS_PLATFORM_STD_MALLOC
#define POLARSSL_PLATFORM_STD_MALLOC MBEDTLS_PLATFORM_STD_MALLOC
#endif
#if defined MBEDTLS_PLATFORM_STD_MEM_HDR
#define POLARSSL_PLATFORM_STD_MEM_HDR MBEDTLS_PLATFORM_STD_MEM_HDR
#endif
@ -492,12 +487,6 @@
#if defined MBEDTLS_SHA512_PROCESS_ALT
#define POLARSSL_SHA512_PROCESS_ALT MBEDTLS_SHA512_PROCESS_ALT
#endif
#if defined MBEDTLS_SSL_AEAD_RANDOM_IV
#define POLARSSL_SSL_AEAD_RANDOM_IV MBEDTLS_SSL_AEAD_RANDOM_IV
#endif
#if defined MBEDTLS_SSL_ALERT_MESSAGES
#define POLARSSL_SSL_ALERT_MESSAGES MBEDTLS_SSL_ALERT_MESSAGES
#endif
#if defined MBEDTLS_SSL_ALL_ALERT_MESSAGES
#define POLARSSL_SSL_ALL_ALERT_MESSAGES MBEDTLS_SSL_ALL_ALERT_MESSAGES
#endif
@ -522,9 +511,6 @@
#if defined MBEDTLS_SSL_DEBUG_ALL
#define POLARSSL_SSL_DEBUG_ALL MBEDTLS_SSL_DEBUG_ALL
#endif
#if defined MBEDTLS_SSL_DISABLE_RENEGOTIATION
#define POLARSSL_SSL_DISABLE_RENEGOTIATION MBEDTLS_SSL_DISABLE_RENEGOTIATION
#endif
#if defined MBEDTLS_SSL_DTLS_ANTI_REPLAY
#define POLARSSL_SSL_DTLS_ANTI_REPLAY MBEDTLS_SSL_DTLS_ANTI_REPLAY
#endif
@ -752,7 +738,6 @@
#define KU_KEY_ENCIPHERMENT MBEDTLS_X509_KU_KEY_ENCIPHERMENT
#define KU_NON_REPUDIATION MBEDTLS_X509_KU_NON_REPUDIATION
#define LN_2_DIV_LN_10_SCALE100 MBEDTLS_LN_2_DIV_LN_10_SCALE100
#define MD_CONTEXT_T_INIT MBEDTLS_MD_CONTEXT_T_INIT
#define MEMORY_VERIFY_ALLOC MBEDTLS_MEMORY_VERIFY_ALLOC
#define MEMORY_VERIFY_ALWAYS MBEDTLS_MEMORY_VERIFY_ALWAYS
#define MEMORY_VERIFY_FREE MBEDTLS_MEMORY_VERIFY_FREE
@ -1017,19 +1002,13 @@
#define POLARSSL_CONFIG_H MBEDTLS_CONFIG_H
#define POLARSSL_CTR_DRBG_H MBEDTLS_CTR_DRBG_H
#define POLARSSL_DEBUG_H MBEDTLS_DEBUG_H
#define POLARSSL_DEBUG_LOG_FULL MBEDTLS_DEBUG_LOG_FULL
#define POLARSSL_DEBUG_LOG_RAW MBEDTLS_DEBUG_LOG_RAW
#define POLARSSL_DECRYPT MBEDTLS_DECRYPT
#define POLARSSL_DES_H MBEDTLS_DES_H
#define POLARSSL_DHM_H MBEDTLS_DHM_H
#define POLARSSL_DHM_RFC2409_MODP_1024_G MBEDTLS_DHM_RFC2409_MODP_1024_G
#define POLARSSL_DHM_RFC2409_MODP_1024_P MBEDTLS_DHM_RFC2409_MODP_1024_P
#define POLARSSL_DHM_RFC3526_MODP_2048_G MBEDTLS_DHM_RFC3526_MODP_2048_G
#define POLARSSL_DHM_RFC3526_MODP_2048_P MBEDTLS_DHM_RFC3526_MODP_2048_P
#define POLARSSL_DHM_RFC3526_MODP_3072_G MBEDTLS_DHM_RFC3526_MODP_3072_G
#define POLARSSL_DHM_RFC3526_MODP_3072_P MBEDTLS_DHM_RFC3526_MODP_3072_P
#define POLARSSL_DHM_RFC5114_MODP_1024_G MBEDTLS_DHM_RFC5114_MODP_1024_G
#define POLARSSL_DHM_RFC5114_MODP_1024_P MBEDTLS_DHM_RFC5114_MODP_1024_P
#define POLARSSL_DHM_RFC5114_MODP_2048_G MBEDTLS_DHM_RFC5114_MODP_2048_G
#define POLARSSL_DHM_RFC5114_MODP_2048_P MBEDTLS_DHM_RFC5114_MODP_2048_P
#define POLARSSL_ECDH_H MBEDTLS_ECDH_H
@ -1117,9 +1096,6 @@
#define POLARSSL_ERR_HMAC_DRBG_FILE_IO_ERROR MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR
#define POLARSSL_ERR_HMAC_DRBG_INPUT_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG
#define POLARSSL_ERR_HMAC_DRBG_REQUEST_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG
#define POLARSSL_ERR_MD2_FILE_IO_ERROR MBEDTLS_ERR_MD2_FILE_IO_ERROR
#define POLARSSL_ERR_MD4_FILE_IO_ERROR MBEDTLS_ERR_MD4_FILE_IO_ERROR
#define POLARSSL_ERR_MD5_FILE_IO_ERROR MBEDTLS_ERR_MD5_FILE_IO_ERROR
#define POLARSSL_ERR_MD_ALLOC_FAILED MBEDTLS_ERR_MD_ALLOC_FAILED
#define POLARSSL_ERR_MD_BAD_INPUT_DATA MBEDTLS_ERR_MD_BAD_INPUT_DATA
#define POLARSSL_ERR_MD_FEATURE_UNAVAILABLE MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE
@ -1147,7 +1123,6 @@
#define POLARSSL_ERR_OID_BUF_TOO_SMALL MBEDTLS_ERR_OID_BUF_TOO_SMALL
#define POLARSSL_ERR_OID_NOT_FOUND MBEDTLS_ERR_OID_NOT_FOUND
#define POLARSSL_ERR_PADLOCK_DATA_MISALIGNED MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED
#define POLARSSL_ERR_PBKDF2_BAD_INPUT_DATA MBEDTLS_ERR_PBKDF2_BAD_INPUT_DATA
#define POLARSSL_ERR_PEM_BAD_INPUT_DATA MBEDTLS_ERR_PEM_BAD_INPUT_DATA
#define POLARSSL_ERR_PEM_FEATURE_UNAVAILABLE MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE
#define POLARSSL_ERR_PEM_INVALID_DATA MBEDTLS_ERR_PEM_INVALID_DATA
@ -1179,7 +1154,6 @@
#define POLARSSL_ERR_PK_TYPE_MISMATCH MBEDTLS_ERR_PK_TYPE_MISMATCH
#define POLARSSL_ERR_PK_UNKNOWN_NAMED_CURVE MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE
#define POLARSSL_ERR_PK_UNKNOWN_PK_ALG MBEDTLS_ERR_PK_UNKNOWN_PK_ALG
#define POLARSSL_ERR_RIPEMD160_FILE_IO_ERROR MBEDTLS_ERR_RIPEMD160_FILE_IO_ERROR
#define POLARSSL_ERR_RSA_BAD_INPUT_DATA MBEDTLS_ERR_RSA_BAD_INPUT_DATA
#define POLARSSL_ERR_RSA_INVALID_PADDING MBEDTLS_ERR_RSA_INVALID_PADDING
#define POLARSSL_ERR_RSA_KEY_CHECK_FAILED MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
@ -1189,9 +1163,6 @@
#define POLARSSL_ERR_RSA_PUBLIC_FAILED MBEDTLS_ERR_RSA_PUBLIC_FAILED
#define POLARSSL_ERR_RSA_RNG_FAILED MBEDTLS_ERR_RSA_RNG_FAILED
#define POLARSSL_ERR_RSA_VERIFY_FAILED MBEDTLS_ERR_RSA_VERIFY_FAILED
#define POLARSSL_ERR_SHA1_FILE_IO_ERROR MBEDTLS_ERR_SHA1_FILE_IO_ERROR
#define POLARSSL_ERR_SHA256_FILE_IO_ERROR MBEDTLS_ERR_SHA256_FILE_IO_ERROR
#define POLARSSL_ERR_SHA512_FILE_IO_ERROR MBEDTLS_ERR_SHA512_FILE_IO_ERROR
#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE
#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST
#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY
@ -1305,7 +1276,6 @@
#define POLARSSL_MD_SHA512 MBEDTLS_MD_SHA512
#define POLARSSL_MD_WRAP_H MBEDTLS_MD_WRAP_H
#define POLARSSL_MEMORY_BUFFER_ALLOC_H MBEDTLS_MEMORY_BUFFER_ALLOC_H
#define POLARSSL_MEMORY_H MBEDTLS_MEMORY_H
#define POLARSSL_MODE_CBC MBEDTLS_MODE_CBC
#define POLARSSL_MODE_CCM MBEDTLS_MODE_CCM
#define POLARSSL_MODE_CFB MBEDTLS_MODE_CFB
@ -1319,7 +1289,7 @@
#define POLARSSL_MPI_MAX_BITS_SCALE100 MBEDTLS_MPI_MAX_BITS_SCALE100
#define POLARSSL_MPI_MAX_LIMBS MBEDTLS_MPI_MAX_LIMBS
#define POLARSSL_MPI_RW_BUFFER_SIZE MBEDTLS_MPI_RW_BUFFER_SIZE
#define POLARSSL_NET_H MBEDTLS_NET_H
#define POLARSSL_NET_H MBEDTLS_NET_SOCKETS_H
#define POLARSSL_NET_LISTEN_BACKLOG MBEDTLS_NET_LISTEN_BACKLOG
#define POLARSSL_OID_H MBEDTLS_OID_H
#define POLARSSL_OPERATION_NONE MBEDTLS_OPERATION_NONE
@ -1329,7 +1299,6 @@
#define POLARSSL_PADDING_ZEROS MBEDTLS_PADDING_ZEROS
#define POLARSSL_PADDING_ZEROS_AND_LEN MBEDTLS_PADDING_ZEROS_AND_LEN
#define POLARSSL_PADLOCK_H MBEDTLS_PADLOCK_H
#define POLARSSL_PBKDF2_H MBEDTLS_PBKDF2_H
#define POLARSSL_PEM_H MBEDTLS_PEM_H
#define POLARSSL_PKCS11_H MBEDTLS_PKCS11_H
#define POLARSSL_PKCS12_H MBEDTLS_PKCS12_H
@ -1415,7 +1384,8 @@
#define SSL_ANTI_REPLAY_ENABLED MBEDTLS_SSL_ANTI_REPLAY_ENABLED
#define SSL_ARC4_DISABLED MBEDTLS_SSL_ARC4_DISABLED
#define SSL_ARC4_ENABLED MBEDTLS_SSL_ARC4_ENABLED
#define SSL_BUFFER_LEN MBEDTLS_SSL_BUFFER_LEN
#define SSL_BUFFER_LEN ( ( ( MBEDTLS_SSL_IN_BUFFER_LEN ) < ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) \
? ( MBEDTLS_SSL_IN_BUFFER_LEN ) : ( MBEDTLS_SSL_OUT_BUFFER_LEN ) )
#define SSL_CACHE_DEFAULT_MAX_ENTRIES MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES
#define SSL_CACHE_DEFAULT_TIMEOUT MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT
#define SSL_CBC_RECORD_SPLITTING_DISABLED MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED
@ -1712,7 +1682,6 @@
#define TLS_RSA_WITH_NULL_SHA256 MBEDTLS_TLS_RSA_WITH_NULL_SHA256
#define TLS_RSA_WITH_RC4_128_MD5 MBEDTLS_TLS_RSA_WITH_RC4_128_MD5
#define TLS_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_RSA_WITH_RC4_128_SHA
#define UL64 MBEDTLS_UL64
#define X509_CRT_VERSION_1 MBEDTLS_X509_CRT_VERSION_1
#define X509_CRT_VERSION_2 MBEDTLS_X509_CRT_VERSION_2
#define X509_CRT_VERSION_3 MBEDTLS_X509_CRT_VERSION_3
@ -1736,7 +1705,6 @@
#define _ssl_key_cert mbedtls_ssl_key_cert
#define _ssl_premaster_secret mbedtls_ssl_premaster_secret
#define _ssl_session mbedtls_ssl_session
#define _ssl_ticket_keys mbedtls_ssl_ticket_keys
#define _ssl_transform mbedtls_ssl_transform
#define _x509_crl mbedtls_x509_crl
#define _x509_crl_entry mbedtls_x509_crl_entry
@ -1836,7 +1804,6 @@
#define cipher_definitions mbedtls_cipher_definitions
#define cipher_finish mbedtls_cipher_finish
#define cipher_free mbedtls_cipher_free
#define cipher_free_ctx mbedtls_cipher_free_ctx
#define cipher_get_block_size mbedtls_cipher_get_block_size
#define cipher_get_cipher_mode mbedtls_cipher_get_cipher_mode
#define cipher_get_iv_size mbedtls_cipher_get_iv_size
@ -1855,7 +1822,6 @@
#define cipher_mode_t mbedtls_cipher_mode_t
#define cipher_padding_t mbedtls_cipher_padding_t
#define cipher_reset mbedtls_cipher_reset
#define cipher_self_test mbedtls_cipher_self_test
#define cipher_set_iv mbedtls_cipher_set_iv
#define cipher_set_padding_mode mbedtls_cipher_set_padding_mode
#define cipher_setkey mbedtls_cipher_setkey
@ -1866,7 +1832,6 @@
#define ctr_drbg_context mbedtls_ctr_drbg_context
#define ctr_drbg_free mbedtls_ctr_drbg_free
#define ctr_drbg_init mbedtls_ctr_drbg_init
#define ctr_drbg_init_entropy_len mbedtls_ctr_drbg_init_entropy_len
#define ctr_drbg_random mbedtls_ctr_drbg_random
#define ctr_drbg_random_with_add mbedtls_ctr_drbg_random_with_add
#define ctr_drbg_reseed mbedtls_ctr_drbg_reseed
@ -1877,14 +1842,12 @@
#define ctr_drbg_update mbedtls_ctr_drbg_update
#define ctr_drbg_update_seed_file mbedtls_ctr_drbg_update_seed_file
#define ctr_drbg_write_seed_file mbedtls_ctr_drbg_write_seed_file
#define debug_fmt mbedtls_debug_fmt
#define debug_print_buf mbedtls_debug_print_buf
#define debug_print_crt mbedtls_debug_print_crt
#define debug_print_ecp mbedtls_debug_print_ecp
#define debug_print_mpi mbedtls_debug_print_mpi
#define debug_print_msg mbedtls_debug_print_msg
#define debug_print_ret mbedtls_debug_print_ret
#define debug_set_log_mode mbedtls_debug_set_log_mode
#define debug_set_threshold mbedtls_debug_set_threshold
#define des3_context mbedtls_des3_context
#define des3_crypt_cbc mbedtls_des3_crypt_cbc
@ -1928,7 +1891,6 @@
#define ecdh_make_public mbedtls_ecdh_make_public
#define ecdh_read_params mbedtls_ecdh_read_params
#define ecdh_read_public mbedtls_ecdh_read_public
#define ecdh_self_test mbedtls_ecdh_self_test
#define ecdh_side mbedtls_ecdh_side
#define ecdsa_context mbedtls_ecdsa_context
#define ecdsa_free mbedtls_ecdsa_free
@ -1937,7 +1899,6 @@
#define ecdsa_info mbedtls_ecdsa_info
#define ecdsa_init mbedtls_ecdsa_init
#define ecdsa_read_signature mbedtls_ecdsa_read_signature
#define ecdsa_self_test mbedtls_ecdsa_self_test
#define ecdsa_sign mbedtls_ecdsa_sign
#define ecdsa_sign_det mbedtls_ecdsa_sign_det
#define ecdsa_verify mbedtls_ecdsa_verify
@ -1945,7 +1906,6 @@
#define ecdsa_write_signature_det mbedtls_ecdsa_write_signature_det
#define eckey_info mbedtls_eckey_info
#define eckeydh_info mbedtls_eckeydh_info
#define ecp_add mbedtls_ecp_add
#define ecp_check_privkey mbedtls_ecp_check_privkey
#define ecp_check_pub_priv mbedtls_ecp_check_pub_priv
#define ecp_check_pubkey mbedtls_ecp_check_pubkey
@ -1962,7 +1922,6 @@
#define ecp_group_free mbedtls_ecp_group_free
#define ecp_group_id mbedtls_ecp_group_id
#define ecp_group_init mbedtls_ecp_group_init
#define ecp_group_read_string mbedtls_ecp_group_read_string
#define ecp_grp_id_list mbedtls_ecp_grp_id_list
#define ecp_is_zero mbedtls_ecp_is_zero
#define ecp_keypair mbedtls_ecp_keypair
@ -1977,7 +1936,6 @@
#define ecp_point_write_binary mbedtls_ecp_point_write_binary
#define ecp_self_test mbedtls_ecp_self_test
#define ecp_set_zero mbedtls_ecp_set_zero
#define ecp_sub mbedtls_ecp_sub
#define ecp_tls_read_group mbedtls_ecp_tls_read_group
#define ecp_tls_read_point mbedtls_ecp_tls_read_point
#define ecp_tls_write_group mbedtls_ecp_tls_write_group
@ -2015,7 +1973,6 @@
#define hmac_drbg_context mbedtls_hmac_drbg_context
#define hmac_drbg_free mbedtls_hmac_drbg_free
#define hmac_drbg_init mbedtls_hmac_drbg_init
#define hmac_drbg_init_buf mbedtls_hmac_drbg_init_buf
#define hmac_drbg_random mbedtls_hmac_drbg_random
#define hmac_drbg_random_with_add mbedtls_hmac_drbg_random_with_add
#define hmac_drbg_reseed mbedtls_hmac_drbg_reseed
@ -2031,14 +1988,8 @@
#define md mbedtls_md
#define md2 mbedtls_md2
#define md2_context mbedtls_md2_context
#define md2_file mbedtls_md2_file
#define md2_finish mbedtls_md2_finish
#define md2_free mbedtls_md2_free
#define md2_hmac mbedtls_md2_hmac
#define md2_hmac_finish mbedtls_md2_hmac_finish
#define md2_hmac_reset mbedtls_md2_hmac_reset
#define md2_hmac_starts mbedtls_md2_hmac_starts
#define md2_hmac_update mbedtls_md2_hmac_update
#define md2_info mbedtls_md2_info
#define md2_init mbedtls_md2_init
#define md2_process mbedtls_md2_process
@ -2047,14 +1998,8 @@
#define md2_update mbedtls_md2_update
#define md4 mbedtls_md4
#define md4_context mbedtls_md4_context
#define md4_file mbedtls_md4_file
#define md4_finish mbedtls_md4_finish
#define md4_free mbedtls_md4_free
#define md4_hmac mbedtls_md4_hmac
#define md4_hmac_finish mbedtls_md4_hmac_finish
#define md4_hmac_reset mbedtls_md4_hmac_reset
#define md4_hmac_starts mbedtls_md4_hmac_starts
#define md4_hmac_update mbedtls_md4_hmac_update
#define md4_info mbedtls_md4_info
#define md4_init mbedtls_md4_init
#define md4_process mbedtls_md4_process
@ -2063,14 +2008,8 @@
#define md4_update mbedtls_md4_update
#define md5 mbedtls_md5
#define md5_context mbedtls_md5_context
#define md5_file mbedtls_md5_file
#define md5_finish mbedtls_md5_finish
#define md5_free mbedtls_md5_free
#define md5_hmac mbedtls_md5_hmac
#define md5_hmac_finish mbedtls_md5_hmac_finish
#define md5_hmac_reset mbedtls_md5_hmac_reset
#define md5_hmac_starts mbedtls_md5_hmac_starts
#define md5_hmac_update mbedtls_md5_hmac_update
#define md5_info mbedtls_md5_info
#define md5_init mbedtls_md5_init
#define md5_process mbedtls_md5_process
@ -2081,7 +2020,6 @@
#define md_file mbedtls_md_file
#define md_finish mbedtls_md_finish
#define md_free mbedtls_md_free
#define md_free_ctx mbedtls_md_free_ctx
#define md_get_name mbedtls_md_get_name
#define md_get_size mbedtls_md_get_size
#define md_get_type mbedtls_md_get_type
@ -2109,7 +2047,6 @@
#define memory_buffer_alloc_status mbedtls_memory_buffer_alloc_status
#define memory_buffer_alloc_verify mbedtls_memory_buffer_alloc_verify
#define memory_buffer_set_verify mbedtls_memory_buffer_set_verify
#define memory_set_own mbedtls_memory_set_own
#define mpi mbedtls_mpi
#define mpi_add_abs mbedtls_mpi_add_abs
#define mpi_add_int mbedtls_mpi_add_int
@ -2185,8 +2122,6 @@
#define padlock_supports mbedtls_padlock_has_support
#define padlock_xcryptcbc mbedtls_padlock_xcryptcbc
#define padlock_xcryptecb mbedtls_padlock_xcryptecb
#define pbkdf2_hmac mbedtls_pbkdf2_hmac
#define pbkdf2_self_test mbedtls_pbkdf2_self_test
#define pem_context mbedtls_pem_context
#define pem_free mbedtls_pem_free
#define pem_init mbedtls_pem_init
@ -2246,13 +2181,11 @@
#define platform_entropy_poll mbedtls_platform_entropy_poll
#define platform_set_exit mbedtls_platform_set_exit
#define platform_set_fprintf mbedtls_platform_set_fprintf
#define platform_set_malloc_free mbedtls_platform_set_malloc_free
#define platform_set_printf mbedtls_platform_set_printf
#define platform_set_snprintf mbedtls_platform_set_snprintf
#define polarssl_exit mbedtls_exit
#define polarssl_fprintf mbedtls_fprintf
#define polarssl_free mbedtls_free
#define polarssl_malloc mbedtls_malloc
#define polarssl_mutex_free mbedtls_mutex_free
#define polarssl_mutex_init mbedtls_mutex_init
#define polarssl_mutex_lock mbedtls_mutex_lock
@ -2262,14 +2195,8 @@
#define polarssl_strerror mbedtls_strerror
#define ripemd160 mbedtls_ripemd160
#define ripemd160_context mbedtls_ripemd160_context
#define ripemd160_file mbedtls_ripemd160_file
#define ripemd160_finish mbedtls_ripemd160_finish
#define ripemd160_free mbedtls_ripemd160_free
#define ripemd160_hmac mbedtls_ripemd160_hmac
#define ripemd160_hmac_finish mbedtls_ripemd160_hmac_finish
#define ripemd160_hmac_reset mbedtls_ripemd160_hmac_reset
#define ripemd160_hmac_starts mbedtls_ripemd160_hmac_starts
#define ripemd160_hmac_update mbedtls_ripemd160_hmac_update
#define ripemd160_info mbedtls_ripemd160_info
#define ripemd160_init mbedtls_ripemd160_init
#define ripemd160_process mbedtls_ripemd160_process
@ -2283,12 +2210,10 @@
#define rsa_check_pubkey mbedtls_rsa_check_pubkey
#define rsa_context mbedtls_rsa_context
#define rsa_copy mbedtls_rsa_copy
#define rsa_decrypt_func mbedtls_rsa_decrypt_func
#define rsa_free mbedtls_rsa_free
#define rsa_gen_key mbedtls_rsa_gen_key
#define rsa_info mbedtls_rsa_info
#define rsa_init mbedtls_rsa_init
#define rsa_key_len_func mbedtls_rsa_key_len_func
#define rsa_pkcs1_decrypt mbedtls_rsa_pkcs1_decrypt
#define rsa_pkcs1_encrypt mbedtls_rsa_pkcs1_encrypt
#define rsa_pkcs1_sign mbedtls_rsa_pkcs1_sign
@ -2306,19 +2231,12 @@
#define rsa_rsassa_pss_verify_ext mbedtls_rsa_rsassa_pss_verify_ext
#define rsa_self_test mbedtls_rsa_self_test
#define rsa_set_padding mbedtls_rsa_set_padding
#define rsa_sign_func mbedtls_rsa_sign_func
#define safer_memcmp mbedtls_ssl_safer_memcmp
#define set_alarm mbedtls_set_alarm
#define sha1 mbedtls_sha1
#define sha1_context mbedtls_sha1_context
#define sha1_file mbedtls_sha1_file
#define sha1_finish mbedtls_sha1_finish
#define sha1_free mbedtls_sha1_free
#define sha1_hmac mbedtls_sha1_hmac
#define sha1_hmac_finish mbedtls_sha1_hmac_finish
#define sha1_hmac_reset mbedtls_sha1_hmac_reset
#define sha1_hmac_starts mbedtls_sha1_hmac_starts
#define sha1_hmac_update mbedtls_sha1_hmac_update
#define sha1_info mbedtls_sha1_info
#define sha1_init mbedtls_sha1_init
#define sha1_process mbedtls_sha1_process
@ -2328,14 +2246,8 @@
#define sha224_info mbedtls_sha224_info
#define sha256 mbedtls_sha256
#define sha256_context mbedtls_sha256_context
#define sha256_file mbedtls_sha256_file
#define sha256_finish mbedtls_sha256_finish
#define sha256_free mbedtls_sha256_free
#define sha256_hmac mbedtls_sha256_hmac
#define sha256_hmac_finish mbedtls_sha256_hmac_finish
#define sha256_hmac_reset mbedtls_sha256_hmac_reset
#define sha256_hmac_starts mbedtls_sha256_hmac_starts
#define sha256_hmac_update mbedtls_sha256_hmac_update
#define sha256_info mbedtls_sha256_info
#define sha256_init mbedtls_sha256_init
#define sha256_process mbedtls_sha256_process
@ -2345,14 +2257,8 @@
#define sha384_info mbedtls_sha384_info
#define sha512 mbedtls_sha512
#define sha512_context mbedtls_sha512_context
#define sha512_file mbedtls_sha512_file
#define sha512_finish mbedtls_sha512_finish
#define sha512_free mbedtls_sha512_free
#define sha512_hmac mbedtls_sha512_hmac
#define sha512_hmac_finish mbedtls_sha512_hmac_finish
#define sha512_hmac_reset mbedtls_sha512_hmac_reset
#define sha512_hmac_starts mbedtls_sha512_hmac_starts
#define sha512_hmac_update mbedtls_sha512_hmac_update
#define sha512_info mbedtls_sha512_info
#define sha512_init mbedtls_sha512_init
#define sha512_process mbedtls_sha512_process
@ -2385,7 +2291,6 @@
#define ssl_cookie_setup mbedtls_ssl_cookie_setup
#define ssl_cookie_write mbedtls_ssl_cookie_write
#define ssl_cookie_write_t mbedtls_ssl_cookie_write_t
#define ssl_curve_is_acceptable mbedtls_ssl_curve_is_acceptable
#define ssl_derive_keys mbedtls_ssl_derive_keys
#define ssl_dtls_replay_check mbedtls_ssl_dtls_replay_check
#define ssl_dtls_replay_update mbedtls_ssl_dtls_replay_update
@ -2453,7 +2358,6 @@
#define ssl_set_arc4_support mbedtls_ssl_conf_arc4_support
#define ssl_set_authmode mbedtls_ssl_conf_authmode
#define ssl_set_bio mbedtls_ssl_set_bio
#define ssl_set_bio mbedtls_ssl_set_bio_timeout
#define ssl_set_ca_chain mbedtls_ssl_conf_ca_chain
#define ssl_set_cbc_record_splitting mbedtls_ssl_conf_cbc_record_splitting
#define ssl_set_ciphersuites mbedtls_ssl_conf_ciphersuites
@ -2476,8 +2380,6 @@
#define ssl_set_max_version mbedtls_ssl_conf_max_version
#define ssl_set_min_version mbedtls_ssl_conf_min_version
#define ssl_set_own_cert mbedtls_ssl_conf_own_cert
#define ssl_set_own_cert_alt mbedtls_ssl_set_own_cert_alt
#define ssl_set_own_cert_rsa mbedtls_ssl_set_own_cert_rsa
#define ssl_set_psk mbedtls_ssl_conf_psk
#define ssl_set_psk_cb mbedtls_ssl_conf_psk_cb
#define ssl_set_renegotiation mbedtls_ssl_conf_renegotiation
@ -2486,7 +2388,6 @@
#define ssl_set_rng mbedtls_ssl_conf_rng
#define ssl_set_session mbedtls_ssl_set_session
#define ssl_set_session_cache mbedtls_ssl_conf_session_cache
#define ssl_set_session_ticket_lifetime mbedtls_ssl_conf_session_ticket_lifetime
#define ssl_set_session_tickets mbedtls_ssl_conf_session_tickets
#define ssl_set_sni mbedtls_ssl_conf_sni
#define ssl_set_transport mbedtls_ssl_conf_transport
@ -2494,7 +2395,6 @@
#define ssl_set_verify mbedtls_ssl_conf_verify
#define ssl_sig_from_pk mbedtls_ssl_sig_from_pk
#define ssl_states mbedtls_ssl_states
#define ssl_ticket_keys mbedtls_ssl_ticket_keys
#define ssl_transform mbedtls_ssl_transform
#define ssl_transform_free mbedtls_ssl_transform_free
#define ssl_write mbedtls_ssl_write
@ -2523,7 +2423,6 @@
#define test_cli_key mbedtls_test_cli_key
#define test_cli_key_ec mbedtls_test_cli_key_ec
#define test_cli_key_rsa mbedtls_test_cli_key_rsa
#define test_dhm_params mbedtls_test_dhm_params
#define test_srv_crt mbedtls_test_srv_crt
#define test_srv_crt_ec mbedtls_test_srv_crt_ec
#define test_srv_crt_rsa mbedtls_test_srv_crt_rsa
@ -2578,8 +2477,6 @@
#define x509_get_time mbedtls_x509_get_time
#define x509_key_size_helper mbedtls_x509_key_size_helper
#define x509_name mbedtls_x509_name
#define x509_oid_get_description mbedtls_x509_oid_get_description
#define x509_oid_get_numeric_string mbedtls_x509_oid_get_numeric_string
#define x509_self_test mbedtls_x509_self_test
#define x509_sequence mbedtls_x509_sequence
#define x509_serial_gets mbedtls_x509_serial_gets

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,21 @@
/**
* \file ctr_drbg.h
*
* \brief CTR_DRBG based on AES-256 (NIST SP 800-90)
* \brief This file contains CTR_DRBG definitions and functions.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* CTR_DRBG is a standardized way of building a PRNG from a block-cipher
* in counter mode operation, as defined in <em>NIST SP 800-90A:
* Recommendation for Random Number Generation Using Deterministic Random
* Bit Generators</em>.
*
* The Mbed TLS implementation of CTR_DRBG uses AES-256 (default) or AES-128
* as the underlying block cipher.
*
* \warning Using 128-bit keys for CTR_DRBG limits the security of generated
* keys and operations that use random values generated to 128-bit security.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,90 +30,120 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_CTR_DRBG_H
#define MBEDTLS_CTR_DRBG_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "aes.h"
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#include "threading.h"
#endif
#define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED -0x0034 /**< The entropy source failed. */
#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG -0x0036 /**< Too many random requested in single call. */
#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG -0x0038 /**< Input too large (Entropy + additional). */
#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A /**< Read/write error in file. */
#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG -0x0036 /**< The requested random buffer length is too big. */
#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG -0x0038 /**< The input (entropy + additional data) is too large. */
#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A /**< Read or write error in file. */
#define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< Block size used by the cipher */
#define MBEDTLS_CTR_DRBG_KEYSIZE 32 /**< Key size used by the cipher */
#define MBEDTLS_CTR_DRBG_KEYBITS ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 )
#define MBEDTLS_CTR_DRBG_SEEDLEN ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE )
/**< The seed length (counter + AES key) */
#define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< The block size used by the cipher. */
#if defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY)
#define MBEDTLS_CTR_DRBG_KEYSIZE 16 /**< The key size used by the cipher (compile-time choice: 128 bits). */
#else
#define MBEDTLS_CTR_DRBG_KEYSIZE 32 /**< The key size used by the cipher (compile-time choice: 256 bits). */
#endif
#define MBEDTLS_CTR_DRBG_KEYBITS ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */
#define MBEDTLS_CTR_DRBG_SEEDLEN ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) /**< The seed length, calculated as (counter + AES key). */
/**
* \name SECTION: Module settings
*
* The configuration options you can set for this module are in this section.
* Either change them in config.h or define them on the compiler command line.
* Either change them in config.h or define them using the compiler command
* line.
* \{
*/
#if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48
/**< The amount of entropy used per seed by default:
* <ul><li>48 with SHA-512.</li>
* <li>32 with SHA-256.</li></ul>
*/
#else
#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 32 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 32
/**< Amount of entropy used per seed by default:
* <ul><li>48 with SHA-512.</li>
* <li>32 with SHA-256.</li></ul>
*/
#endif
#endif
#if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */
#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000
/**< The interval before reseed is performed by default. */
#endif
#if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT)
#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */
#define MBEDTLS_CTR_DRBG_MAX_INPUT 256
/**< The maximum number of additional input Bytes. */
#endif
#if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST)
#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */
#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024
/**< The maximum number of requested Bytes per call. */
#endif
#if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)
#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */
#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384
/**< The maximum size of seed or reseed buffer. */
#endif
/* \} name SECTION: Module settings */
#define MBEDTLS_CTR_DRBG_PR_OFF 0 /**< No prediction resistance */
#define MBEDTLS_CTR_DRBG_PR_ON 1 /**< Prediction resistance enabled */
#define MBEDTLS_CTR_DRBG_PR_OFF 0
/**< Prediction resistance is disabled. */
#define MBEDTLS_CTR_DRBG_PR_ON 1
/**< Prediction resistance is enabled. */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief CTR_DRBG context structure
* \brief The CTR_DRBG context structure.
*/
typedef struct
typedef struct mbedtls_ctr_drbg_context
{
unsigned char counter[16]; /*!< counter (V) */
int reseed_counter; /*!< reseed counter */
int prediction_resistance; /*!< enable prediction resistance (Automatic
reseed before every random generation) */
size_t entropy_len; /*!< amount of entropy grabbed on each
(re)seed */
int reseed_interval; /*!< reseed interval */
unsigned char counter[16]; /*!< The counter (V). */
int reseed_counter; /*!< The reseed counter. */
int prediction_resistance; /*!< This determines whether prediction
resistance is enabled, that is
whether to systematically reseed before
each random generation. */
size_t entropy_len; /*!< The amount of entropy grabbed on each
seed or reseed operation. */
int reseed_interval; /*!< The reseed interval. */
mbedtls_aes_context aes_ctx; /*!< AES context */
mbedtls_aes_context aes_ctx; /*!< The AES context. */
/*
* Callbacks (Entropy)
*/
int (*f_entropy)(void *, unsigned char *, size_t);
/*!< The entropy callback function. */
void *p_entropy; /*!< context for the entropy function */
void *p_entropy; /*!< The context for the entropy function. */
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
@ -110,31 +152,32 @@ typedef struct
mbedtls_ctr_drbg_context;
/**
* \brief CTR_DRBG context initialization
* Makes the context ready for mbedtls_ctr_drbg_seed() or
* mbedtls_ctr_drbg_free().
* \brief This function initializes the CTR_DRBG context,
* and prepares it for mbedtls_ctr_drbg_seed()
* or mbedtls_ctr_drbg_free().
*
* \param ctx CTR_DRBG context to be initialized
* \param ctx The CTR_DRBG context to initialize.
*/
void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx );
/**
* \brief CTR_DRBG initial seeding
* Seed and setup entropy source for future reseeds.
* \brief This function seeds and sets up the CTR_DRBG
* entropy source for future reseeds.
*
* Note: Personalization data can be provided in addition to the more generic
* entropy source to make this instantiation as unique as possible.
* \note Personalization data can be provided in addition to the more generic
* entropy source, to make this instantiation as unique as possible.
*
* \param ctx CTR_DRBG context to be seeded
* \param f_entropy Entropy callback (p_entropy, buffer to fill, buffer
* length)
* \param p_entropy Entropy context
* \param custom Personalization data (Device specific identifiers)
* (Can be NULL)
* \param len Length of personalization data
* \param ctx The CTR_DRBG context to seed.
* \param f_entropy The entropy callback, taking as arguments the
* \p p_entropy context, the buffer to fill, and the
length of the buffer.
* \param p_entropy The entropy context.
* \param custom Personalization data, that is device-specific
identifiers. Can be NULL.
* \param len The length of the personalization data.
*
* \return 0 if successful, or
* MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
*/
int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
int (*f_entropy)(void *, unsigned char *, size_t),
@ -143,141 +186,188 @@ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
size_t len );
/**
* \brief Clear CTR_CRBG context data
* \brief This function clears CTR_CRBG context data.
*
* \param ctx CTR_DRBG context to clear
* \param ctx The CTR_DRBG context to clear.
*/
void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx );
/**
* \brief Enable / disable prediction resistance (Default: Off)
* \brief This function turns prediction resistance on or off.
* The default value is off.
*
* Note: If enabled, entropy is used for ctx->entropy_len before each call!
* Only use this if you have ample supply of good entropy!
* \note If enabled, entropy is gathered at the beginning of
* every call to mbedtls_ctr_drbg_random_with_add().
* Only use this if your entropy source has sufficient
* throughput.
*
* \param ctx CTR_DRBG context
* \param resistance MBEDTLS_CTR_DRBG_PR_ON or MBEDTLS_CTR_DRBG_PR_OFF
* \param ctx The CTR_DRBG context.
* \param resistance #MBEDTLS_CTR_DRBG_PR_ON or #MBEDTLS_CTR_DRBG_PR_OFF.
*/
void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx,
int resistance );
/**
* \brief Set the amount of entropy grabbed on each (re)seed
* (Default: MBEDTLS_CTR_DRBG_ENTROPY_LEN)
* \brief This function sets the amount of entropy grabbed on each
* seed or reseed. The default value is
* #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
*
* \param ctx CTR_DRBG context
* \param len Amount of entropy to grab
* \param ctx The CTR_DRBG context.
* \param len The amount of entropy to grab.
*/
void mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx,
size_t len );
/**
* \brief Set the reseed interval
* (Default: MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
* \brief This function sets the reseed interval.
* The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL.
*
* \param ctx CTR_DRBG context
* \param interval Reseed interval
* \param ctx The CTR_DRBG context.
* \param interval The reseed interval.
*/
void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx,
int interval );
/**
* \brief CTR_DRBG reseeding (extracts data from entropy source)
* \brief This function reseeds the CTR_DRBG context, that is
* extracts data from the entropy source.
*
* \param ctx CTR_DRBG context
* \param additional Additional data to add to state (Can be NULL)
* \param len Length of additional data
* \param ctx The CTR_DRBG context.
* \param additional Additional data to add to the state. Can be NULL.
* \param len The length of the additional data.
*
* \return 0 if successful, or
* MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
*/
int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional, size_t len );
/**
* \brief CTR_DRBG update state
* \brief This function updates the state of the CTR_DRBG context.
*
* \param ctx CTR_DRBG context
* \param additional Additional data to update state with
* \param add_len Length of additional data
* \param ctx The CTR_DRBG context.
* \param additional The data to update the state with.
* \param add_len Length of \p additional in bytes. This must be at
* most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
*
* \note If add_len is greater than MBEDTLS_CTR_DRBG_MAX_SEED_INPUT,
* only the first MBEDTLS_CTR_DRBG_MAX_SEED_INPUT bytes are used,
* the remaining ones are silently discarded.
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if
* \p add_len is more than
* #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
* \return An error from the underlying AES cipher on failure.
*/
void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional, size_t add_len );
int mbedtls_ctr_drbg_update_ret( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional,
size_t add_len );
/**
* \brief CTR_DRBG generate random with additional update input
* \brief This function updates a CTR_DRBG instance with additional
* data and uses it to generate random data.
*
* Note: Automatically reseeds if reseed_counter is reached.
* \note The function automatically reseeds if the reseed counter is exceeded.
*
* \param p_rng CTR_DRBG context
* \param output Buffer to fill
* \param output_len Length of the buffer
* \param additional Additional data to update with (Can be NULL)
* \param add_len Length of additional data
* \param p_rng The CTR_DRBG context. This must be a pointer to a
* #mbedtls_ctr_drbg_context structure.
* \param output The buffer to fill.
* \param output_len The length of the buffer.
* \param additional Additional data to update. Can be NULL.
* \param add_len The length of the additional data.
*
* \return 0 if successful, or
* MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or
* MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
* #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
*/
int mbedtls_ctr_drbg_random_with_add( void *p_rng,
unsigned char *output, size_t output_len,
const unsigned char *additional, size_t add_len );
/**
* \brief CTR_DRBG generate random
* \brief This function uses CTR_DRBG to generate random data.
*
* Note: Automatically reseeds if reseed_counter is reached.
* \note The function automatically reseeds if the reseed counter is exceeded.
*
* \param p_rng CTR_DRBG context
* \param output Buffer to fill
* \param output_len Length of the buffer
* \param p_rng The CTR_DRBG context. This must be a pointer to a
* #mbedtls_ctr_drbg_context structure.
* \param output The buffer to fill.
* \param output_len The length of the buffer.
*
* \return 0 if successful, or
* MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or
* MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
* #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
*/
int mbedtls_ctr_drbg_random( void *p_rng,
unsigned char *output, size_t output_len );
#if ! defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function updates the state of the CTR_DRBG context.
*
* \deprecated Superseded by mbedtls_ctr_drbg_update_ret()
* in 2.16.0.
*
* \note If \p add_len is greater than
* #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, only the first
* #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used.
* The remaining Bytes are silently discarded.
*
* \param ctx The CTR_DRBG context.
* \param additional The data to update the state with.
* \param add_len Length of \p additional data.
*/
MBEDTLS_DEPRECATED void mbedtls_ctr_drbg_update(
mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional,
size_t add_len );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_FS_IO)
/**
* \brief Write a seed file
* \brief This function writes a seed file.
*
* \param ctx CTR_DRBG context
* \param path Name of the file
* \param ctx The CTR_DRBG context.
* \param path The name of the file.
*
* \return 0 if successful,
* MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or
* MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on
* failure.
*/
int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
/**
* \brief Read and update a seed file. Seed is added to this
* instance
* \brief This function reads and updates a seed file. The seed
* is added to this instance.
*
* \param ctx CTR_DRBG context
* \param path Name of the file
* \param ctx The CTR_DRBG context.
* \param path The name of the file.
*
* \return 0 if successful,
* MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error,
* MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
* MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
* #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG on failure.
*/
int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
#endif /* MBEDTLS_FS_IO */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
* \brief The CTR_DRBG checkup routine.
*
* \return 0 if successful, or 1 if the test failed
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_ctr_drbg_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
/* Internal functions (do not call directly) */
int mbedtls_ctr_drbg_seed_entropy_len( mbedtls_ctr_drbg_context *,
int (*)(void *, unsigned char *, size_t), void *,

View File

@ -2,7 +2,8 @@
* \file debug.h
*
* \brief Functions for controlling and providing debug output from the library.
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -64,6 +65,11 @@
mbedtls_debug_print_crt( ssl, level, __FILE__, __LINE__, text, crt )
#endif
#if defined(MBEDTLS_ECDH_C)
#define MBEDTLS_SSL_DEBUG_ECDH( level, ecdh, attr ) \
mbedtls_debug_printf_ecdh( ssl, level, __FILE__, __LINE__, ecdh, attr )
#endif
#else /* MBEDTLS_DEBUG_C */
#define MBEDTLS_SSL_DEBUG_MSG( level, args ) do { } while( 0 )
@ -72,6 +78,7 @@
#define MBEDTLS_SSL_DEBUG_MPI( level, text, X ) do { } while( 0 )
#define MBEDTLS_SSL_DEBUG_ECP( level, text, X ) do { } while( 0 )
#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt ) do { } while( 0 )
#define MBEDTLS_SSL_DEBUG_ECDH( level, ecdh, attr ) do { } while( 0 )
#endif /* MBEDTLS_DEBUG_C */
@ -220,6 +227,36 @@ void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,
const char *text, const mbedtls_x509_crt *crt );
#endif
#if defined(MBEDTLS_ECDH_C)
typedef enum
{
MBEDTLS_DEBUG_ECDH_Q,
MBEDTLS_DEBUG_ECDH_QP,
MBEDTLS_DEBUG_ECDH_Z,
} mbedtls_debug_ecdh_attr;
/**
* \brief Print a field of the ECDH structure in the SSL context to the debug
* output. This function is always used through the
* MBEDTLS_SSL_DEBUG_ECDH() macro, which supplies the ssl context, file
* and line number parameters.
*
* \param ssl SSL context
* \param level error level of the debug message
* \param file file the error has occurred in
* \param line line number the error has occurred in
* \param ecdh the ECDH context
* \param attr the identifier of the attribute being output
*
* \attention This function is intended for INTERNAL usage within the
* library only.
*/
void mbedtls_debug_printf_ecdh( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const mbedtls_ecdh_context *ecdh,
mbedtls_debug_ecdh_attr attr );
#endif
#ifdef __cplusplus
}
#endif

View File

@ -3,6 +3,11 @@
*
* \brief DES block cipher
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -19,6 +24,7 @@
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
*/
#ifndef MBEDTLS_DES_H
#define MBEDTLS_DES_H
@ -37,20 +43,27 @@
#define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH -0x0032 /**< The data input has an invalid length. */
#define MBEDTLS_DES_KEY_SIZE 8
/* MBEDTLS_ERR_DES_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_DES_HW_ACCEL_FAILED -0x0033 /**< DES hardware accelerator failed. */
#if !defined(MBEDTLS_DES_ALT)
// Regular implementation
//
#define MBEDTLS_DES_KEY_SIZE 8
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_DES_ALT)
// Regular implementation
//
/**
* \brief DES context structure
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
typedef struct
typedef struct mbedtls_des_context
{
uint32_t sk[32]; /*!< DES subkeys */
}
@ -59,16 +72,24 @@ mbedtls_des_context;
/**
* \brief Triple-DES context structure
*/
typedef struct
typedef struct mbedtls_des3_context
{
uint32_t sk[96]; /*!< 3DES subkeys */
}
mbedtls_des3_context;
#else /* MBEDTLS_DES_ALT */
#include "des_alt.h"
#endif /* MBEDTLS_DES_ALT */
/**
* \brief Initialize DES context
*
* \param ctx DES context to be initialized
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
void mbedtls_des_init( mbedtls_des_context *ctx );
@ -76,6 +97,10 @@ void mbedtls_des_init( mbedtls_des_context *ctx );
* \brief Clear DES context
*
* \param ctx DES context to be cleared
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
void mbedtls_des_free( mbedtls_des_context *ctx );
@ -100,6 +125,10 @@ void mbedtls_des3_free( mbedtls_des3_context *ctx );
* a parity bit to allow verification.
*
* \param key 8-byte secret key
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );
@ -112,6 +141,10 @@ void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );
* \param key 8-byte secret key
*
* \return 0 is parity was ok, 1 if parity was not correct.
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
@ -121,6 +154,10 @@ int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SI
* \param key 8-byte secret key
*
* \return 0 if no weak key was found, 1 if a weak key was identified.
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
@ -131,6 +168,10 @@ int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
* \param key 8-byte secret key
*
* \return 0
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
@ -141,6 +182,10 @@ int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MB
* \param key 8-byte secret key
*
* \return 0
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
@ -196,6 +241,10 @@ int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx,
* \param output 64-bit output block
*
* \return 0 if successful
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
const unsigned char input[8],
@ -219,6 +268,10 @@ int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
int mode,
@ -277,20 +330,15 @@ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,
*
* \param SK Round keys
* \param key Base key
*
* \warning DES is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers
* instead.
*/
void mbedtls_des_setkey( uint32_t SK[32],
const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_DES_ALT */
#include "des_alt.h"
#endif /* MBEDTLS_DES_ALT */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
@ -299,6 +347,8 @@ extern "C" {
*/
int mbedtls_des_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,19 @@
/**
* \file ecdh.h
*
* \brief Elliptic curve Diffie-Hellman
* \brief This file contains ECDH definitions and functions.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous
* key agreement protocol allowing two parties to establish a shared
* secret over an insecure channel. Each party must have an
* elliptic-curve publicprivate key pair.
*
* For more information, see <em>NIST SP 800-56A Rev. 2: Recommendation for
* Pair-Wise Key Establishment Schemes Using Discrete Logarithm
* Cryptography</em>.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,77 +28,185 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_ECDH_H
#define MBEDTLS_ECDH_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "ecp.h"
/*
* Use a backward compatible ECDH context.
*
* This flag is always enabled for now and future versions might add a
* configuration option that conditionally undefines this flag.
* The configuration option in question may have a different name.
*
* Features undefining this flag, must have a warning in their description in
* config.h stating that the feature breaks backward compatibility.
*/
#define MBEDTLS_ECDH_LEGACY_CONTEXT
#ifdef __cplusplus
extern "C" {
#endif
/**
* When importing from an EC key, select if it is our key or the peer's key
* Defines the source of the imported EC key.
*/
typedef enum
{
MBEDTLS_ECDH_OURS,
MBEDTLS_ECDH_THEIRS,
MBEDTLS_ECDH_OURS, /**< Our key. */
MBEDTLS_ECDH_THEIRS, /**< The key of the peer. */
} mbedtls_ecdh_side;
#if !defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
/**
* \brief ECDH context structure
* Defines the ECDH implementation used.
*
* Later versions of the library may add new variants, therefore users should
* not make any assumptions about them.
*/
typedef struct
typedef enum
{
mbedtls_ecp_group grp; /*!< elliptic curve used */
mbedtls_mpi d; /*!< our secret value (private key) */
mbedtls_ecp_point Q; /*!< our public value (public key) */
mbedtls_ecp_point Qp; /*!< peer's public value (public key) */
mbedtls_mpi z; /*!< shared secret */
int point_format; /*!< format for point export in TLS messages */
mbedtls_ecp_point Vi; /*!< blinding value (for later) */
mbedtls_ecp_point Vf; /*!< un-blinding value (for later) */
mbedtls_mpi _d; /*!< previous d (for later) */
MBEDTLS_ECDH_VARIANT_NONE = 0, /*!< Implementation not defined. */
MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0,/*!< The default Mbed TLS implementation */
} mbedtls_ecdh_variant;
/**
* The context used by the default ECDH implementation.
*
* Later versions might change the structure of this context, therefore users
* should not make any assumptions about the structure of
* mbedtls_ecdh_context_mbed.
*/
typedef struct mbedtls_ecdh_context_mbed
{
mbedtls_ecp_group grp; /*!< The elliptic curve used. */
mbedtls_mpi d; /*!< The private key. */
mbedtls_ecp_point Q; /*!< The public key. */
mbedtls_ecp_point Qp; /*!< The value of the public key of the peer. */
mbedtls_mpi z; /*!< The shared secret. */
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx rs; /*!< The restart context for EC computations. */
#endif
} mbedtls_ecdh_context_mbed;
#endif
/**
*
* \warning Performing multiple operations concurrently on the same
* ECDSA context is not supported; objects of this type
* should not be shared between multiple threads.
* \brief The ECDH context structure.
*/
typedef struct mbedtls_ecdh_context
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
mbedtls_ecp_group grp; /*!< The elliptic curve used. */
mbedtls_mpi d; /*!< The private key. */
mbedtls_ecp_point Q; /*!< The public key. */
mbedtls_ecp_point Qp; /*!< The value of the public key of the peer. */
mbedtls_mpi z; /*!< The shared secret. */
int point_format; /*!< The format of point export in TLS messages. */
mbedtls_ecp_point Vi; /*!< The blinding value. */
mbedtls_ecp_point Vf; /*!< The unblinding value. */
mbedtls_mpi _d; /*!< The previous \p d. */
#if defined(MBEDTLS_ECP_RESTARTABLE)
int restart_enabled; /*!< The flag for restartable mode. */
mbedtls_ecp_restart_ctx rs; /*!< The restart context for EC computations. */
#endif /* MBEDTLS_ECP_RESTARTABLE */
#else
uint8_t point_format; /*!< The format of point export in TLS messages
as defined in RFC 4492. */
mbedtls_ecp_group_id grp_id;/*!< The elliptic curve used. */
mbedtls_ecdh_variant var; /*!< The ECDH implementation/structure used. */
union
{
mbedtls_ecdh_context_mbed mbed_ecdh;
} ctx; /*!< Implementation-specific context. The
context in use is specified by the \c var
field. */
#if defined(MBEDTLS_ECP_RESTARTABLE)
uint8_t restart_enabled; /*!< The flag for restartable mode. Functions of
an alternative implementation not supporting
restartable mode must return
MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED error
if this flag is set. */
#endif /* MBEDTLS_ECP_RESTARTABLE */
#endif /* MBEDTLS_ECDH_LEGACY_CONTEXT */
}
mbedtls_ecdh_context;
/**
* \brief Generate a public key.
* Raw function that only does the core computation.
* \brief This function generates an ECDH keypair on an elliptic
* curve.
*
* \param grp ECP group
* \param d Destination MPI (secret exponent, aka private key)
* \param Q Destination point (public key)
* \param f_rng RNG function
* \param p_rng RNG parameter
* This function performs the first of two core computations
* implemented during the ECDH key exchange. The second core
* computation is performed by mbedtls_ecdh_compute_shared().
*
* \return 0 if successful,
* or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
* \see ecp.h
*
* \param grp The ECP group to use. This must be initialized and have
* domain parameters loaded, for example through
* mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
* \param d The destination MPI (private key).
* This must be initialized.
* \param Q The destination point (public key).
* This must be initialized.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL in case \p f_rng doesn't need a context argument.
*
* \return \c 0 on success.
* \return Another \c MBEDTLS_ERR_ECP_XXX or
* \c MBEDTLS_MPI_XXX error code on failure.
*/
int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief Compute shared secret
* Raw function that only does the core computation.
* \brief This function computes the shared secret.
*
* \param grp ECP group
* \param z Destination MPI (shared secret)
* \param Q Public key from other party
* \param d Our secret exponent (private key)
* \param f_rng RNG function (see notes)
* \param p_rng RNG parameter
* This function performs the second of two core computations
* implemented during the ECDH key exchange. The first core
* computation is performed by mbedtls_ecdh_gen_public().
*
* \return 0 if successful,
* or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
* \see ecp.h
*
* \note If f_rng is not NULL, it is used to implement
* countermeasures against potential elaborate timing
* attacks, see \c mbedtls_ecp_mul() for details.
* \note If \p f_rng is not NULL, it is used to implement
* countermeasures against side-channel attacks.
* For more information, see mbedtls_ecp_mul().
*
* \param grp The ECP group to use. This must be initialized and have
* domain parameters loaded, for example through
* mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
* \param z The destination MPI (shared secret).
* This must be initialized.
* \param Q The public key from another party.
* This must be initialized.
* \param d Our secret exponent (private key).
* This must be initialized.
* \param f_rng The RNG function. This may be \c NULL if randomization
* of intermediate results during the ECP computations is
* not needed (discouraged). See the documentation of
* mbedtls_ecp_mul() for more.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL if \p f_rng is \c NULL or doesn't need a
* context argument.
*
* \return \c 0 on success.
* \return Another \c MBEDTLS_ERR_ECP_XXX or
* \c MBEDTLS_MPI_XXX error code on failure.
*/
int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
@ -96,34 +214,64 @@ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
void *p_rng );
/**
* \brief Initialize context
* \brief This function initializes an ECDH context.
*
* \param ctx Context to initialize
* \param ctx The ECDH context to initialize. This must not be \c NULL.
*/
void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx );
/**
* \brief Free context
* \brief This function sets up the ECDH context with the information
* given.
*
* \param ctx Context to free
* This function should be called after mbedtls_ecdh_init() but
* before mbedtls_ecdh_make_params(). There is no need to call
* this function before mbedtls_ecdh_read_params().
*
* This is the first function used by a TLS server for ECDHE
* ciphersuites.
*
* \param ctx The ECDH context to set up. This must be initialized.
* \param grp_id The group id of the group to set up the context for.
*
* \return \c 0 on success.
*/
int mbedtls_ecdh_setup( mbedtls_ecdh_context *ctx,
mbedtls_ecp_group_id grp_id );
/**
* \brief This function frees a context.
*
* \param ctx The context to free. This may be \c NULL, in which
* case this function does nothing. If it is not \c NULL,
* it must point to an initialized ECDH context.
*/
void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx );
/**
* \brief Generate a public key and a TLS ServerKeyExchange payload.
* (First function used by a TLS server for ECDHE.)
* \brief This function generates an EC key pair and exports its
* in the format used in a TLS ServerKeyExchange handshake
* message.
*
* \param ctx ECDH context
* \param olen number of chars written
* \param buf destination buffer
* \param blen length of buffer
* \param f_rng RNG function
* \param p_rng RNG parameter
* This is the second function used by a TLS server for ECDHE
* ciphersuites. (It is called after mbedtls_ecdh_setup().)
*
* \note This function assumes that ctx->grp has already been
* properly set (for example using mbedtls_ecp_group_load).
* \see ecp.h
*
* \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
* \param ctx The ECDH context to use. This must be initialized
* and bound to a group, for example via mbedtls_ecdh_setup().
* \param olen The address at which to store the number of Bytes written.
* \param buf The destination buffer. This must be a writable buffer of
* length \p blen Bytes.
* \param blen The length of the destination buffer \p buf in Bytes.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL in case \p f_rng doesn't need a context argument.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
* \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
@ -131,45 +279,81 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
void *p_rng );
/**
* \brief Parse and procress a TLS ServerKeyExhange payload.
* (First function used by a TLS client for ECDHE.)
* \brief This function parses the ECDHE parameters in a
* TLS ServerKeyExchange handshake message.
*
* \param ctx ECDH context
* \param buf pointer to start of input buffer
* \param end one past end of buffer
* \note In a TLS handshake, this is the how the client
* sets up its ECDHE context from the server's public
* ECDHE key material.
*
* \see ecp.h
*
* \param ctx The ECDHE context to use. This must be initialized.
* \param buf On input, \c *buf must be the start of the input buffer.
* On output, \c *buf is updated to point to the end of the
* data that has been read. On success, this is the first byte
* past the end of the ServerKeyExchange parameters.
* On error, this is the point at which an error has been
* detected, which is usually not useful except to debug
* failures.
* \param end The end of the input buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
* \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
*/
int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
const unsigned char **buf, const unsigned char *end );
const unsigned char **buf,
const unsigned char *end );
/**
* \brief Setup an ECDH context from an EC key.
* (Used by clients and servers in place of the
* ServerKeyEchange for static ECDH: import ECDH parameters
* from a certificate's EC key information.)
* \brief This function sets up an ECDH context from an EC key.
*
* \param ctx ECDH constext to set
* \param key EC key to use
* \param side Is it our key (1) or the peer's key (0) ?
* It is used by clients and servers in place of the
* ServerKeyEchange for static ECDH, and imports ECDH
* parameters from the EC key information of a certificate.
*
* \see ecp.h
*
* \param ctx The ECDH context to set up. This must be initialized.
* \param key The EC key to use. This must be initialized.
* \param side Defines the source of the key. Possible values are:
* - #MBEDTLS_ECDH_OURS: The key is ours.
* - #MBEDTLS_ECDH_THEIRS: The key is that of the peer.
*
* \return \c 0 on success.
* \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
* \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
*/
int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side );
int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side );
/**
* \brief Generate a public key and a TLS ClientKeyExchange payload.
* (Second function used by a TLS client for ECDH(E).)
* \brief This function generates a public key and exports it
* as a TLS ClientKeyExchange payload.
*
* \param ctx ECDH context
* \param olen number of bytes actually written
* \param buf destination buffer
* \param blen size of destination buffer
* \param f_rng RNG function
* \param p_rng RNG parameter
* This is the second function used by a TLS client for ECDH(E)
* ciphersuites.
*
* \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
* \see ecp.h
*
* \param ctx The ECDH context to use. This must be initialized
* and bound to a group, the latter usually by
* mbedtls_ecdh_read_params().
* \param olen The address at which to store the number of Bytes written.
* This must not be \c NULL.
* \param buf The destination buffer. This must be a writable buffer
* of length \p blen Bytes.
* \param blen The size of the destination buffer \p buf in Bytes.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL in case \p f_rng doesn't need a context argument.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
* \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
@ -177,36 +361,78 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
void *p_rng );
/**
* \brief Parse and process a TLS ClientKeyExchange payload.
* (Second function used by a TLS server for ECDH(E).)
* \brief This function parses and processes the ECDHE payload of a
* TLS ClientKeyExchange message.
*
* \param ctx ECDH context
* \param buf start of input buffer
* \param blen length of input buffer
* This is the third function used by a TLS server for ECDH(E)
* ciphersuites. (It is called after mbedtls_ecdh_setup() and
* mbedtls_ecdh_make_params().)
*
* \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
* \see ecp.h
*
* \param ctx The ECDH context to use. This must be initialized
* and bound to a group, for example via mbedtls_ecdh_setup().
* \param buf The pointer to the ClientKeyExchange payload. This must
* be a readable buffer of length \p blen Bytes.
* \param blen The length of the input buffer \p buf in Bytes.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,
const unsigned char *buf, size_t blen );
const unsigned char *buf, size_t blen );
/**
* \brief Derive and export the shared secret.
* (Last function used by both TLS client en servers.)
* \brief This function derives and exports the shared secret.
*
* \param ctx ECDH context
* \param olen number of bytes written
* \param buf destination buffer
* \param blen buffer length
* \param f_rng RNG function, see notes for \c mbedtls_ecdh_compute_shared()
* \param p_rng RNG parameter
* This is the last function used by both TLS client
* and servers.
*
* \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
* \note If \p f_rng is not NULL, it is used to implement
* countermeasures against side-channel attacks.
* For more information, see mbedtls_ecp_mul().
*
* \see ecp.h
* \param ctx The ECDH context to use. This must be initialized
* and have its own private key generated and the peer's
* public key imported.
* \param olen The address at which to store the total number of
* Bytes written on success. This must not be \c NULL.
* \param buf The buffer to write the generated shared key to. This
* must be a writable buffer of size \p blen Bytes.
* \param blen The length of the destination buffer \p buf in Bytes.
* \param f_rng The RNG function, for blinding purposes. This may
* b \c NULL if blinding isn't needed.
* \param p_rng The RNG context. This may be \c NULL if \p f_rng
* doesn't need a context argument.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
* \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
#if defined(MBEDTLS_ECP_RESTARTABLE)
/**
* \brief This function enables restartable EC computations for this
* context. (Default: disabled.)
*
* \see \c mbedtls_ecp_set_max_ops()
*
* \note It is not possible to safely disable restartable
* computations once enabled, except by free-ing the context,
* which cancels possible in-progress operations.
*
* \param ctx The ECDH context to use. This must be initialized.
*/
void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx );
#endif /* MBEDTLS_ECP_RESTARTABLE */
#ifdef __cplusplus
}
#endif

View File

@ -1,9 +1,17 @@
/**
* \file ecdsa.h
*
* \brief Elliptic curve DSA
* \brief This file contains ECDSA definitions and functions.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* The Elliptic Curve Digital Signature Algorithm (ECDSA) is defined in
* <em>Standards for Efficient Cryptography Group (SECG):
* SEC1 Elliptic Curve Cryptography</em>.
* The use of ECDSA for TLS is defined in <em>RFC-4492: Elliptic Curve
* Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)</em>.
*
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,16 +26,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_ECDSA_H
#define MBEDTLS_ECDSA_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "ecp.h"
#include "md.h"
/*
* RFC 4492 page 20:
* RFC-4492 page 20:
*
* Ecdsa-Sig-Value ::= SEQUENCE {
* r INTEGER,
@ -43,34 +58,103 @@
#if MBEDTLS_ECP_MAX_BYTES > 124
#error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN"
#endif
/** Maximum size of an ECDSA signature in bytes */
/** The maximal size of an ECDSA signature in Bytes. */
#define MBEDTLS_ECDSA_MAX_LEN ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) )
/**
* \brief ECDSA context structure
*/
typedef mbedtls_ecp_keypair mbedtls_ecdsa_context;
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Compute ECDSA signature of a previously hashed message
* \brief The ECDSA context structure.
*
* \note The deterministic version is usually prefered.
* \warning Performing multiple operations concurrently on the same
* ECDSA context is not supported; objects of this type
* should not be shared between multiple threads.
*/
typedef mbedtls_ecp_keypair mbedtls_ecdsa_context;
#if defined(MBEDTLS_ECP_RESTARTABLE)
/**
* \brief Internal restart context for ecdsa_verify()
*
* \param grp ECP group
* \param r First output integer
* \param s Second output integer
* \param d Private signing key
* \param buf Message hash
* \param blen Length of buf
* \param f_rng RNG function
* \param p_rng RNG parameter
* \note Opaque struct, defined in ecdsa.c
*/
typedef struct mbedtls_ecdsa_restart_ver mbedtls_ecdsa_restart_ver_ctx;
/**
* \brief Internal restart context for ecdsa_sign()
*
* \return 0 if successful,
* or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
* \note Opaque struct, defined in ecdsa.c
*/
typedef struct mbedtls_ecdsa_restart_sig mbedtls_ecdsa_restart_sig_ctx;
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
/**
* \brief Internal restart context for ecdsa_sign_det()
*
* \note Opaque struct, defined in ecdsa.c
*/
typedef struct mbedtls_ecdsa_restart_det mbedtls_ecdsa_restart_det_ctx;
#endif
/**
* \brief General context for resuming ECDSA operations
*/
typedef struct
{
mbedtls_ecp_restart_ctx ecp; /*!< base context for ECP restart and
shared administrative info */
mbedtls_ecdsa_restart_ver_ctx *ver; /*!< ecdsa_verify() sub-context */
mbedtls_ecdsa_restart_sig_ctx *sig; /*!< ecdsa_sign() sub-context */
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
mbedtls_ecdsa_restart_det_ctx *det; /*!< ecdsa_sign_det() sub-context */
#endif
} mbedtls_ecdsa_restart_ctx;
#else /* MBEDTLS_ECP_RESTARTABLE */
/* Now we can declare functions that take a pointer to that */
typedef void mbedtls_ecdsa_restart_ctx;
#endif /* MBEDTLS_ECP_RESTARTABLE */
/**
* \brief This function computes the ECDSA signature of a
* previously-hashed message.
*
* \note The deterministic version implemented in
* mbedtls_ecdsa_sign_det() is usually preferred.
*
* \note If the bitlength of the message hash is larger than the
* bitlength of the group order, then the hash is truncated
* as defined in <em>Standards for Efficient Cryptography Group
* (SECG): SEC1 Elliptic Curve Cryptography</em>, section
* 4.1.3, step 5.
*
* \see ecp.h
*
* \param grp The context for the elliptic curve to use.
* This must be initialized and have group parameters
* set, for example through mbedtls_ecp_group_load().
* \param r The MPI context in which to store the first part
* the signature. This must be initialized.
* \param s The MPI context in which to store the second part
* the signature. This must be initialized.
* \param d The private signing key. This must be initialized.
* \param buf The content to be signed. This is usually the hash of
* the original data to be signed. This must be a readable
* buffer of length \p blen Bytes. It may be \c NULL if
* \p blen is zero.
* \param blen The length of \p buf in Bytes.
* \param f_rng The RNG function. This must not be \c NULL.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL if \p f_rng doesn't need a context parameter.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX
* or \c MBEDTLS_MPI_XXX error code on failure.
*/
int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
@ -78,74 +162,184 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
/**
* \brief Compute ECDSA signature of a previously hashed message,
* deterministic version (RFC 6979).
* \brief This function computes the ECDSA signature of a
* previously-hashed message, deterministic version.
*
* \param grp ECP group
* \param r First output integer
* \param s Second output integer
* \param d Private signing key
* \param buf Message hash
* \param blen Length of buf
* \param md_alg MD algorithm used to hash the message
* For more information, see <em>RFC-6979: Deterministic
* Usage of the Digital Signature Algorithm (DSA) and Elliptic
* Curve Digital Signature Algorithm (ECDSA)</em>.
*
* \return 0 if successful,
* or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
* \note If the bitlength of the message hash is larger than the
* bitlength of the group order, then the hash is truncated as
* defined in <em>Standards for Efficient Cryptography Group
* (SECG): SEC1 Elliptic Curve Cryptography</em>, section
* 4.1.3, step 5.
*
* \see ecp.h
*
* \param grp The context for the elliptic curve to use.
* This must be initialized and have group parameters
* set, for example through mbedtls_ecp_group_load().
* \param r The MPI context in which to store the first part
* the signature. This must be initialized.
* \param s The MPI context in which to store the second part
* the signature. This must be initialized.
* \param d The private signing key. This must be initialized
* and setup, for example through mbedtls_ecp_gen_privkey().
* \param buf The hashed content to be signed. This must be a readable
* buffer of length \p blen Bytes. It may be \c NULL if
* \p blen is zero.
* \param blen The length of \p buf in Bytes.
* \param md_alg The hash algorithm used to hash the original data.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
* error code on failure.
*/
int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
mbedtls_md_type_t md_alg );
int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r,
mbedtls_mpi *s, const mbedtls_mpi *d,
const unsigned char *buf, size_t blen,
mbedtls_md_type_t md_alg );
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
/**
* \brief Verify ECDSA signature of a previously hashed message
* \brief This function verifies the ECDSA signature of a
* previously-hashed message.
*
* \param grp ECP group
* \param buf Message hash
* \param blen Length of buf
* \param Q Public key to use for verification
* \param r First integer of the signature
* \param s Second integer of the signature
* \note If the bitlength of the message hash is larger than the
* bitlength of the group order, then the hash is truncated as
* defined in <em>Standards for Efficient Cryptography Group
* (SECG): SEC1 Elliptic Curve Cryptography</em>, section
* 4.1.4, step 3.
*
* \return 0 if successful,
* MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid
* or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
* \see ecp.h
*
* \param grp The ECP group to use.
* This must be initialized and have group parameters
* set, for example through mbedtls_ecp_group_load().
* \param buf The hashed content that was signed. This must be a readable
* buffer of length \p blen Bytes. It may be \c NULL if
* \p blen is zero.
* \param blen The length of \p buf in Bytes.
* \param Q The public key to use for verification. This must be
* initialized and setup.
* \param r The first integer of the signature.
* This must be initialized.
* \param s The second integer of the signature.
* This must be initialized.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the signature
* is invalid.
* \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
* error code on failure for any other reason.
*/
int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
const unsigned char *buf, size_t blen,
const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s);
const unsigned char *buf, size_t blen,
const mbedtls_ecp_point *Q, const mbedtls_mpi *r,
const mbedtls_mpi *s);
/**
* \brief Compute ECDSA signature and write it to buffer,
* serialized as defined in RFC 4492 page 20.
* (Not thread-safe to use same context in multiple threads)
* \brief This function computes the ECDSA signature and writes it
* to a buffer, serialized as defined in <em>RFC-4492:
* Elliptic Curve Cryptography (ECC) Cipher Suites for
* Transport Layer Security (TLS)</em>.
*
* \note The deterministice version (RFC 6979) is used if
* MBEDTLS_ECDSA_DETERMINISTIC is defined.
* \warning It is not thread-safe to use the same context in
* multiple threads.
*
* \param ctx ECDSA context
* \param md_alg Algorithm that was used to hash the message
* \param hash Message hash
* \param hlen Length of hash
* \param sig Buffer that will hold the signature
* \param slen Length of the signature written
* \param f_rng RNG function
* \param p_rng RNG parameter
* \note The deterministic version is used if
* #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more
* information, see <em>RFC-6979: Deterministic Usage
* of the Digital Signature Algorithm (DSA) and Elliptic
* Curve Digital Signature Algorithm (ECDSA)</em>.
*
* \note The "sig" buffer must be at least as large as twice the
* size of the curve used, plus 9 (eg. 73 bytes if a 256-bit
* curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe.
* \note If the bitlength of the message hash is larger than the
* bitlength of the group order, then the hash is truncated as
* defined in <em>Standards for Efficient Cryptography Group
* (SECG): SEC1 Elliptic Curve Cryptography</em>, section
* 4.1.3, step 5.
*
* \return 0 if successful,
* or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or
* MBEDTLS_ERR_ASN1_XXX error code
* \see ecp.h
*
* \param ctx The ECDSA context to use. This must be initialized
* and have a group and private key bound to it, for example
* via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair().
* \param md_alg The message digest that was used to hash the message.
* \param hash The message hash to be signed. This must be a readable
* buffer of length \p blen Bytes.
* \param hlen The length of the hash \p hash in Bytes.
* \param sig The buffer to which to write the signature. This must be a
* writable buffer of length at least twice as large as the
* size of the curve used, plus 9. For example, 73 Bytes if
* a 256-bit curve is used. A buffer length of
* #MBEDTLS_ECDSA_MAX_LEN is always safe.
* \param slen The address at which to store the actual length of
* the signature written. Must not be \c NULL.
* \param f_rng The RNG function. This must not be \c NULL if
* #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise,
* it is unused and may be set to \c NULL.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL if \p f_rng is \c NULL or doesn't use a context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
* \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief This function computes the ECDSA signature and writes it
* to a buffer, in a restartable way.
*
* \see \c mbedtls_ecdsa_write_signature()
*
* \note This function is like \c mbedtls_ecdsa_write_signature()
* but it can return early and restart according to the limit
* set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
*
* \param ctx The ECDSA context to use. This must be initialized
* and have a group and private key bound to it, for example
* via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair().
* \param md_alg The message digest that was used to hash the message.
* \param hash The message hash to be signed. This must be a readable
* buffer of length \p blen Bytes.
* \param hlen The length of the hash \p hash in Bytes.
* \param sig The buffer to which to write the signature. This must be a
* writable buffer of length at least twice as large as the
* size of the curve used, plus 9. For example, 73 Bytes if
* a 256-bit curve is used. A buffer length of
* #MBEDTLS_ECDSA_MAX_LEN is always safe.
* \param slen The address at which to store the actual length of
* the signature written. Must not be \c NULL.
* \param f_rng The RNG function. This must not be \c NULL if
* #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise,
* it is unused and may be set to \c NULL.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL if \p f_rng is \c NULL or doesn't use a context.
* \param rs_ctx The restart context to use. This may be \c NULL to disable
* restarting. If it is not \c NULL, it must point to an
* initialized restart context.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
* \return Another \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
* \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
#if ! defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
@ -154,27 +348,47 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Compute ECDSA signature and write it to buffer,
* serialized as defined in RFC 4492 page 20.
* Deterministic version, RFC 6979.
* (Not thread-safe to use same context in multiple threads)
* \brief This function computes an ECDSA signature and writes
* it to a buffer, serialized as defined in <em>RFC-4492:
* Elliptic Curve Cryptography (ECC) Cipher Suites for
* Transport Layer Security (TLS)</em>.
*
* \deprecated Superseded by mbedtls_ecdsa_write_signature() in 2.0.0
* The deterministic version is defined in <em>RFC-6979:
* Deterministic Usage of the Digital Signature Algorithm (DSA)
* and Elliptic Curve Digital Signature Algorithm (ECDSA)</em>.
*
* \param ctx ECDSA context
* \param hash Message hash
* \param hlen Length of hash
* \param sig Buffer that will hold the signature
* \param slen Length of the signature written
* \param md_alg MD algorithm used to hash the message
* \warning It is not thread-safe to use the same context in
* multiple threads.
*
* \note The "sig" buffer must be at least as large as twice the
* size of the curve used, plus 9 (eg. 73 bytes if a 256-bit
* curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe.
* \note If the bitlength of the message hash is larger than the
* bitlength of the group order, then the hash is truncated as
* defined in <em>Standards for Efficient Cryptography Group
* (SECG): SEC1 Elliptic Curve Cryptography</em>, section
* 4.1.3, step 5.
*
* \return 0 if successful,
* or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or
* MBEDTLS_ERR_ASN1_XXX error code
* \see ecp.h
*
* \deprecated Superseded by mbedtls_ecdsa_write_signature() in
* Mbed TLS version 2.0 and later.
*
* \param ctx The ECDSA context to use. This must be initialized
* and have a group and private key bound to it, for example
* via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair().
* \param hash The message hash to be signed. This must be a readable
* buffer of length \p blen Bytes.
* \param hlen The length of the hash \p hash in Bytes.
* \param sig The buffer to which to write the signature. This must be a
* writable buffer of length at least twice as large as the
* size of the curve used, plus 9. For example, 73 Bytes if
* a 256-bit curve is used. A buffer length of
* #MBEDTLS_ECDSA_MAX_LEN is always safe.
* \param slen The address at which to store the actual length of
* the signature written. Must not be \c NULL.
* \param md_alg The message digest that was used to hash the message.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
* \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
@ -185,62 +399,145 @@ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
/**
* \brief Read and verify an ECDSA signature
* \brief This function reads and verifies an ECDSA signature.
*
* \param ctx ECDSA context
* \param hash Message hash
* \param hlen Size of hash
* \param sig Signature to read and verify
* \param slen Size of sig
* \note If the bitlength of the message hash is larger than the
* bitlength of the group order, then the hash is truncated as
* defined in <em>Standards for Efficient Cryptography Group
* (SECG): SEC1 Elliptic Curve Cryptography</em>, section
* 4.1.4, step 3.
*
* \return 0 if successful,
* MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid,
* MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if the signature is
* valid but its actual length is less than siglen,
* or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_ERR_MPI_XXX error code
* \see ecp.h
*
* \param ctx The ECDSA context to use. This must be initialized
* and have a group and public key bound to it.
* \param hash The message hash that was signed. This must be a readable
* buffer of length \p size Bytes.
* \param hlen The size of the hash \p hash.
* \param sig The signature to read and verify. This must be a readable
* buffer of length \p slen Bytes.
* \param slen The size of \p sig in Bytes.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid.
* \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid
* signature in \p sig, but its length is less than \p siglen.
* \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX
* error code on failure for any other reason.
*/
int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
const unsigned char *sig, size_t slen );
/**
* \brief Generate an ECDSA keypair on the given curve
* \brief This function reads and verifies an ECDSA signature,
* in a restartable way.
*
* \param ctx ECDSA context in which the keypair should be stored
* \param gid Group (elliptic curve) to use. One of the various
* MBEDTLS_ECP_DP_XXX macros depending on configuration.
* \param f_rng RNG function
* \param p_rng RNG parameter
* \see \c mbedtls_ecdsa_read_signature()
*
* \return 0 on success, or a MBEDTLS_ERR_ECP_XXX code.
* \note This function is like \c mbedtls_ecdsa_read_signature()
* but it can return early and restart according to the limit
* set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
*
* \param ctx The ECDSA context to use. This must be initialized
* and have a group and public key bound to it.
* \param hash The message hash that was signed. This must be a readable
* buffer of length \p size Bytes.
* \param hlen The size of the hash \p hash.
* \param sig The signature to read and verify. This must be a readable
* buffer of length \p slen Bytes.
* \param slen The size of \p sig in Bytes.
* \param rs_ctx The restart context to use. This may be \c NULL to disable
* restarting. If it is not \c NULL, it must point to an
* initialized restart context.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid.
* \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid
* signature in \p sig, but its length is less than \p siglen.
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
* \return Another \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX
* error code on failure for any other reason.
*/
int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx,
const unsigned char *hash, size_t hlen,
const unsigned char *sig, size_t slen,
mbedtls_ecdsa_restart_ctx *rs_ctx );
/**
* \brief This function generates an ECDSA keypair on the given curve.
*
* \see ecp.h
*
* \param ctx The ECDSA context to store the keypair in.
* This must be initialized.
* \param gid The elliptic curve to use. One of the various
* \c MBEDTLS_ECP_DP_XXX macros depending on configuration.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG context to be passed to \p f_rng. This may be
* \c NULL if \p f_rng doesn't need a context argument.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX code on failure.
*/
int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
/**
* \brief Set an ECDSA context from an EC key pair
* \brief This function sets up an ECDSA context from an EC key pair.
*
* \param ctx ECDSA context to set
* \param key EC key to use
* \see ecp.h
*
* \return 0 on success, or a MBEDTLS_ERR_ECP_XXX code.
* \param ctx The ECDSA context to setup. This must be initialized.
* \param key The EC key to use. This must be initialized and hold
* a private-public key pair or a public key. In the former
* case, the ECDSA context may be used for signature creation
* and verification after this call. In the latter case, it
* may be used for signature verification.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX code on failure.
*/
int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key );
int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx,
const mbedtls_ecp_keypair *key );
/**
* \brief Initialize context
* \brief This function initializes an ECDSA context.
*
* \param ctx Context to initialize
* \param ctx The ECDSA context to initialize.
* This must not be \c NULL.
*/
void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx );
/**
* \brief Free context
* \brief This function frees an ECDSA context.
*
* \param ctx Context to free
* \param ctx The ECDSA context to free. This may be \c NULL,
* in which case this function does nothing. If it
* is not \c NULL, it must be initialized.
*/
void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx );
#if defined(MBEDTLS_ECP_RESTARTABLE)
/**
* \brief Initialize a restart context.
*
* \param ctx The restart context to initialize.
* This must not be \c NULL.
*/
void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx );
/**
* \brief Free the components of a restart context.
*
* \param ctx The restart context to free. This may be \c NULL,
* in which case this function does nothing. If it
* is not \c NULL, it must be initialized.
*/
void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx );
#endif /* MBEDTLS_ECP_RESTARTABLE */
#ifdef __cplusplus
}
#endif

View File

@ -2,7 +2,8 @@
* \file ecjpake.h
*
* \brief Elliptic curve J-PAKE
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -39,6 +40,11 @@
* The payloads are serialized in a way suitable for use in TLS, but could
* also be use outside TLS.
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "ecp.h"
#include "md.h"
@ -55,6 +61,7 @@ typedef enum {
MBEDTLS_ECJPAKE_SERVER, /**< Server */
} mbedtls_ecjpake_role;
#if !defined(MBEDTLS_ECJPAKE_ALT)
/**
* EC J-PAKE context structure.
*
@ -66,7 +73,7 @@ typedef enum {
* convetion from the Thread v1.0 spec. Correspondance is indicated in the
* description as a pair C: client name, S: server name
*/
typedef struct
typedef struct mbedtls_ecjpake_context
{
const mbedtls_md_info_t *md_info; /**< Hash to use */
mbedtls_ecp_group grp; /**< Elliptic curve */
@ -85,29 +92,38 @@ typedef struct
mbedtls_mpi s; /**< Pre-shared secret (passphrase) */
} mbedtls_ecjpake_context;
#else /* MBEDTLS_ECJPAKE_ALT */
#include "ecjpake_alt.h"
#endif /* MBEDTLS_ECJPAKE_ALT */
/**
* \brief Initialize a context
* (just makes it ready for setup() or free()).
* \brief Initialize an ECJPAKE context.
*
* \param ctx context to initialize
* \param ctx The ECJPAKE context to initialize.
* This must not be \c NULL.
*/
void mbedtls_ecjpake_init( mbedtls_ecjpake_context *ctx );
/**
* \brief Set up a context for use
* \brief Set up an ECJPAKE context for use.
*
* \note Currently the only values for hash/curve allowed by the
* standard are MBEDTLS_MD_SHA256/MBEDTLS_ECP_DP_SECP256R1.
* standard are #MBEDTLS_MD_SHA256/#MBEDTLS_ECP_DP_SECP256R1.
*
* \param ctx context to set up
* \param role Our role: client or server
* \param hash hash function to use (MBEDTLS_MD_XXX)
* \param curve elliptic curve identifier (MBEDTLS_ECP_DP_XXX)
* \param secret pre-shared secret (passphrase)
* \param len length of the shared secret
* \param ctx The ECJPAKE context to set up. This must be initialized.
* \param role The role of the caller. This must be either
* #MBEDTLS_ECJPAKE_CLIENT or #MBEDTLS_ECJPAKE_SERVER.
* \param hash The identifier of the hash function to use,
* for example #MBEDTLS_MD_SHA256.
* \param curve The identifier of the elliptic curve to use,
* for example #MBEDTLS_ECP_DP_SECP256R1.
* \param secret The pre-shared secret (passphrase). This must be
* a readable buffer of length \p len Bytes. It need
* only be valid for the duration of this call.
* \param len The length of the pre-shared secret \p secret.
*
* \return 0 if successfull,
* a negative error code otherwise
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx,
mbedtls_ecjpake_role role,
@ -116,30 +132,35 @@ int mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx,
const unsigned char *secret,
size_t len );
/*
* \brief Check if a context is ready for use
/**
* \brief Check if an ECJPAKE context is ready for use.
*
* \param ctx Context to check
* \param ctx The ECJPAKE context to check. This must be
* initialized.
*
* \return 0 if the context is ready for use,
* MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise
* \return \c 0 if the context is ready for use.
* \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise.
*/
int mbedtls_ecjpake_check( const mbedtls_ecjpake_context *ctx );
/**
* \brief Generate and write the first round message
* (TLS: contents of the Client/ServerHello extension,
* excluding extension type and length bytes)
* excluding extension type and length bytes).
*
* \param ctx Context to use
* \param buf Buffer to write the contents to
* \param len Buffer size
* \param olen Will be updated with the number of bytes written
* \param f_rng RNG function
* \param p_rng RNG parameter
* \param ctx The ECJPAKE context to use. This must be
* initialized and set up.
* \param buf The buffer to write the contents to. This must be a
* writable buffer of length \p len Bytes.
* \param len The length of \p buf in Bytes.
* \param olen The address at which to store the total number
* of Bytes written to \p buf. This must not be \c NULL.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG parameter to be passed to \p f_rng. This
* may be \c NULL if \p f_rng doesn't use a context.
*
* \return 0 if successfull,
* a negative error code otherwise
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_ecjpake_write_round_one( mbedtls_ecjpake_context *ctx,
unsigned char *buf, size_t len, size_t *olen,
@ -149,14 +170,16 @@ int mbedtls_ecjpake_write_round_one( mbedtls_ecjpake_context *ctx,
/**
* \brief Read and process the first round message
* (TLS: contents of the Client/ServerHello extension,
* excluding extension type and length bytes)
* excluding extension type and length bytes).
*
* \param ctx Context to use
* \param buf Pointer to extension contents
* \param len Extension length
* \param ctx The ECJPAKE context to use. This must be initialized
* and set up.
* \param buf The buffer holding the first round message. This must
* be a readable buffer of length \p len Bytes.
* \param len The length in Bytes of \p buf.
*
* \return 0 if successfull,
* a negative error code otherwise
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_ecjpake_read_round_one( mbedtls_ecjpake_context *ctx,
const unsigned char *buf,
@ -164,17 +187,21 @@ int mbedtls_ecjpake_read_round_one( mbedtls_ecjpake_context *ctx,
/**
* \brief Generate and write the second round message
* (TLS: contents of the Client/ServerKeyExchange)
* (TLS: contents of the Client/ServerKeyExchange).
*
* \param ctx Context to use
* \param buf Buffer to write the contents to
* \param len Buffer size
* \param olen Will be updated with the number of bytes written
* \param f_rng RNG function
* \param p_rng RNG parameter
* \param ctx The ECJPAKE context to use. This must be initialized,
* set up, and already have performed round one.
* \param buf The buffer to write the round two contents to.
* This must be a writable buffer of length \p len Bytes.
* \param len The size of \p buf in Bytes.
* \param olen The address at which to store the total number of Bytes
* written to \p buf. This must not be \c NULL.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG parameter to be passed to \p f_rng. This
* may be \c NULL if \p f_rng doesn't use a context.
*
* \return 0 if successfull,
* a negative error code otherwise
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_ecjpake_write_round_two( mbedtls_ecjpake_context *ctx,
unsigned char *buf, size_t len, size_t *olen,
@ -183,14 +210,16 @@ int mbedtls_ecjpake_write_round_two( mbedtls_ecjpake_context *ctx,
/**
* \brief Read and process the second round message
* (TLS: contents of the Client/ServerKeyExchange)
* (TLS: contents of the Client/ServerKeyExchange).
*
* \param ctx Context to use
* \param buf Pointer to the message
* \param len Message length
* \param ctx The ECJPAKE context to use. This must be initialized
* and set up and already have performed round one.
* \param buf The buffer holding the second round message. This must
* be a readable buffer of length \p len Bytes.
* \param len The length in Bytes of \p buf.
*
* \return 0 if successfull,
* a negative error code otherwise
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_ecjpake_read_round_two( mbedtls_ecjpake_context *ctx,
const unsigned char *buf,
@ -198,17 +227,21 @@ int mbedtls_ecjpake_read_round_two( mbedtls_ecjpake_context *ctx,
/**
* \brief Derive the shared secret
* (TLS: Pre-Master Secret)
* (TLS: Pre-Master Secret).
*
* \param ctx Context to use
* \param buf Buffer to write the contents to
* \param len Buffer size
* \param olen Will be updated with the number of bytes written
* \param f_rng RNG function
* \param p_rng RNG parameter
* \param ctx The ECJPAKE context to use. This must be initialized,
* set up and have performed both round one and two.
* \param buf The buffer to write the derived secret to. This must
* be a writable buffer of length \p len Bytes.
* \param len The length of \p buf in Bytes.
* \param olen The address at which to store the total number of Bytes
* written to \p buf. This must not be \c NULL.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG parameter to be passed to \p f_rng. This
* may be \c NULL if \p f_rng doesn't use a context.
*
* \return 0 if successfull,
* a negative error code otherwise
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx,
unsigned char *buf, size_t len, size_t *olen,
@ -216,23 +249,29 @@ int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx,
void *p_rng );
/**
* \brief Free a context's content
* \brief This clears an ECJPAKE context and frees any
* embedded data structure.
*
* \param ctx context to free
* \param ctx The ECJPAKE context to free. This may be \c NULL,
* in which case this function does nothing. If it is not
* \c NULL, it must point to an initialized ECJPAKE context.
*/
void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if a test failed
*/
int mbedtls_ecjpake_self_test( int verbose );
#endif
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* ecjpake.h */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,299 @@
/**
* \file ecp_internal.h
*
* \brief Function declarations for alternative implementation of elliptic curve
* point arithmetic.
*/
/*
* Copyright (C) 2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* References:
*
* [1] BERNSTEIN, Daniel J. Curve25519: new Diffie-Hellman speed records.
* <http://cr.yp.to/ecdh/curve25519-20060209.pdf>
*
* [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
* for elliptic curve cryptosystems. In : Cryptographic Hardware and
* Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
* <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
*
* [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
* render ECC resistant against Side Channel Attacks. IACR Cryptology
* ePrint Archive, 2004, vol. 2004, p. 342.
* <http://eprint.iacr.org/2004/342.pdf>
*
* [4] Certicom Research. SEC 2: Recommended Elliptic Curve Domain Parameters.
* <http://www.secg.org/sec2-v2.pdf>
*
* [5] HANKERSON, Darrel, MENEZES, Alfred J., VANSTONE, Scott. Guide to Elliptic
* Curve Cryptography.
*
* [6] Digital Signature Standard (DSS), FIPS 186-4.
* <http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf>
*
* [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer
* Security (TLS), RFC 4492.
* <https://tools.ietf.org/search/rfc4492>
*
* [8] <http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html>
*
* [9] COHEN, Henri. A Course in Computational Algebraic Number Theory.
* Springer Science & Business Media, 1 Aug 2000
*/
#ifndef MBEDTLS_ECP_INTERNAL_H
#define MBEDTLS_ECP_INTERNAL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
/**
* \brief Indicate if the Elliptic Curve Point module extension can
* handle the group.
*
* \param grp The pointer to the elliptic curve group that will be the
* basis of the cryptographic computations.
*
* \return Non-zero if successful.
*/
unsigned char mbedtls_internal_ecp_grp_capable( const mbedtls_ecp_group *grp );
/**
* \brief Initialise the Elliptic Curve Point module extension.
*
* If mbedtls_internal_ecp_grp_capable returns true for a
* group, this function has to be able to initialise the
* module for it.
*
* This module can be a driver to a crypto hardware
* accelerator, for which this could be an initialise function.
*
* \param grp The pointer to the group the module needs to be
* initialised for.
*
* \return 0 if successful.
*/
int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp );
/**
* \brief Frees and deallocates the Elliptic Curve Point module
* extension.
*
* \param grp The pointer to the group the module was initialised for.
*/
void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp );
#if defined(ECP_SHORTWEIERSTRASS)
#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
/**
* \brief Randomize jacobian coordinates:
* (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l.
*
* \param grp Pointer to the group representing the curve.
*
* \param pt The point on the curve to be randomised, given with Jacobian
* coordinates.
*
* \param f_rng A function pointer to the random number generator.
*
* \param p_rng A pointer to the random number generator state.
*
* \return 0 if successful.
*/
int mbedtls_internal_ecp_randomize_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt, int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
#endif
#if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
/**
* \brief Addition: R = P + Q, mixed affine-Jacobian coordinates.
*
* The coordinates of Q must be normalized (= affine),
* but those of P don't need to. R is not normalized.
*
* This function is used only as a subrutine of
* ecp_mul_comb().
*
* Special cases: (1) P or Q is zero, (2) R is zero,
* (3) P == Q.
* None of these cases can happen as intermediate step in
* ecp_mul_comb():
* - at each step, P, Q and R are multiples of the base
* point, the factor being less than its order, so none of
* them is zero;
* - Q is an odd multiple of the base point, P an even
* multiple, due to the choice of precomputed points in the
* modified comb method.
* So branches for these cases do not leak secret information.
*
* We accept Q->Z being unset (saving memory in tables) as
* meaning 1.
*
* Cost in field operations if done by [5] 3.22:
* 1A := 8M + 3S
*
* \param grp Pointer to the group representing the curve.
*
* \param R Pointer to a point structure to hold the result.
*
* \param P Pointer to the first summand, given with Jacobian
* coordinates
*
* \param Q Pointer to the second summand, given with affine
* coordinates.
*
* \return 0 if successful.
*/
int mbedtls_internal_ecp_add_mixed( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q );
#endif
/**
* \brief Point doubling R = 2 P, Jacobian coordinates.
*
* Cost: 1D := 3M + 4S (A == 0)
* 4M + 4S (A == -3)
* 3M + 6S + 1a otherwise
* when the implementation is based on the "dbl-1998-cmo-2"
* doubling formulas in [8] and standard optimizations are
* applied when curve parameter A is one of { 0, -3 }.
*
* \param grp Pointer to the group representing the curve.
*
* \param R Pointer to a point structure to hold the result.
*
* \param P Pointer to the point that has to be doubled, given with
* Jacobian coordinates.
*
* \return 0 if successful.
*/
#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
int mbedtls_internal_ecp_double_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, const mbedtls_ecp_point *P );
#endif
/**
* \brief Normalize jacobian coordinates of an array of (pointers to)
* points.
*
* Using Montgomery's trick to perform only one inversion mod P
* the cost is:
* 1N(t) := 1I + (6t - 3)M + 1S
* (See for example Algorithm 10.3.4. in [9])
*
* This function is used only as a subrutine of
* ecp_mul_comb().
*
* Warning: fails (returning an error) if one of the points is
* zero!
* This should never happen, see choice of w in ecp_mul_comb().
*
* \param grp Pointer to the group representing the curve.
*
* \param T Array of pointers to the points to normalise.
*
* \param t_len Number of elements in the array.
*
* \return 0 if successful,
* an error if one of the points is zero.
*/
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
int mbedtls_internal_ecp_normalize_jac_many( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *T[], size_t t_len );
#endif
/**
* \brief Normalize jacobian coordinates so that Z == 0 || Z == 1.
*
* Cost in field operations if done by [5] 3.2.1:
* 1N := 1I + 3M + 1S
*
* \param grp Pointer to the group representing the curve.
*
* \param pt pointer to the point to be normalised. This is an
* input/output parameter.
*
* \return 0 if successful.
*/
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
int mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt );
#endif
#endif /* ECP_SHORTWEIERSTRASS */
#if defined(ECP_MONTGOMERY)
#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
int mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, mbedtls_ecp_point *S, const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d );
#endif
/**
* \brief Randomize projective x/z coordinates:
* (X, Z) -> (l X, l Z) for random l
*
* \param grp pointer to the group representing the curve
*
* \param P the point on the curve to be randomised given with
* projective coordinates. This is an input/output parameter.
*
* \param f_rng a function pointer to the random number generator
*
* \param p_rng a pointer to the random number generator state
*
* \return 0 if successful
*/
#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
int mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
#endif
/**
* \brief Normalize Montgomery x/z coordinates: X = X/Z, Z = 1.
*
* \param grp pointer to the group representing the curve
*
* \param P pointer to the point to be normalised. This is an
* input/output parameter.
*
* \return 0 if successful
*/
#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
int mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P );
#endif
#endif /* ECP_MONTGOMERY */
#endif /* MBEDTLS_ECP_INTERNAL_ALT */
#endif /* ecp_internal.h */

View File

@ -2,7 +2,8 @@
* \file entropy.h
*
* \brief Entropy accumulator implementation
*
*/
/*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -106,7 +107,7 @@ typedef int (*mbedtls_entropy_f_source_ptr)(void *data, unsigned char *output, s
/**
* \brief Entropy source state
*/
typedef struct
typedef struct mbedtls_entropy_source_state
{
mbedtls_entropy_f_source_ptr f_source; /**< The entropy source callback */
void * p_source; /**< The callback data pointer */
@ -119,8 +120,9 @@ mbedtls_entropy_source_state;
/**
* \brief Entropy context structure
*/
typedef struct
typedef struct mbedtls_entropy_context
{
int accumulator_started;
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
mbedtls_sha512_context accumulator;
#else
@ -164,7 +166,7 @@ void mbedtls_entropy_free( mbedtls_entropy_context *ctx );
* \param threshold Minimum required from source before entropy is released
* ( with mbedtls_entropy_func() ) (in bytes)
* \param strong MBEDTLS_ENTROPY_SOURCE_STRONG or
* MBEDTSL_ENTROPY_SOURCE_WEAK.
* MBEDTLS_ENTROPY_SOURCE_WEAK.
* At least one strong source needs to be added.
* Weaker sources (such as the cycle counter) can be used as
* a complement.

View File

@ -2,7 +2,8 @@
* \file entropy_poll.h
*
* \brief Platform-specific and custom entropy polling functions
*
*/
/*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*

View File

@ -2,8 +2,9 @@
* \file error.h
*
* \brief Error to string translation
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
*/
/*
* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -23,6 +24,12 @@
#ifndef MBEDTLS_ERROR_H
#define MBEDTLS_ERROR_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
/**
@ -49,38 +56,53 @@
*
* Module Nr Codes assigned
* MPI 7 0x0002-0x0010
* GCM 2 0x0012-0x0014
* BLOWFISH 2 0x0016-0x0018
* GCM 3 0x0012-0x0014 0x0013-0x0013
* BLOWFISH 3 0x0016-0x0018 0x0017-0x0017
* THREADING 3 0x001A-0x001E
* AES 2 0x0020-0x0022
* CAMELLIA 2 0x0024-0x0026
* XTEA 1 0x0028-0x0028
* AES 5 0x0020-0x0022 0x0021-0x0025
* CAMELLIA 3 0x0024-0x0026 0x0027-0x0027
* XTEA 2 0x0028-0x0028 0x0029-0x0029
* BASE64 2 0x002A-0x002C
* OID 1 0x002E-0x002E 0x000B-0x000B
* PADLOCK 1 0x0030-0x0030
* DES 1 0x0032-0x0032
* DES 2 0x0032-0x0032 0x0033-0x0033
* CTR_DBRG 4 0x0034-0x003A
* ENTROPY 3 0x003C-0x0040 0x003D-0x003F
* NET 11 0x0042-0x0052 0x0043-0x0045
* NET 13 0x0042-0x0052 0x0043-0x0049
* ARIA 4 0x0058-0x005E
* ASN1 7 0x0060-0x006C
* CMAC 1 0x007A-0x007A
* PBKDF2 1 0x007C-0x007C
* HMAC_DRBG 4 0x0003-0x0009
* CCM 2 0x000D-0x000F
* HMAC_DRBG 4 0x0003-0x0009
* CCM 3 0x000D-0x0011
* ARC4 1 0x0019-0x0019
* MD2 1 0x002B-0x002B
* MD4 1 0x002D-0x002D
* MD5 1 0x002F-0x002F
* RIPEMD160 1 0x0031-0x0031
* SHA1 1 0x0035-0x0035 0x0073-0x0073
* SHA256 1 0x0037-0x0037 0x0074-0x0074
* SHA512 1 0x0039-0x0039 0x0075-0x0075
* CHACHA20 3 0x0051-0x0055
* POLY1305 3 0x0057-0x005B
* CHACHAPOLY 2 0x0054-0x0056
* PLATFORM 1 0x0070-0x0072
*
* High-level module nr (3 bits - 0x0...-0x7...)
* Name ID Nr of Errors
* PEM 1 9
* PKCS#12 1 4 (Started from top)
* X509 2 19
* X509 2 20
* PKCS5 2 4 (Started from top)
* DHM 3 9
* PK 3 14 (Started from top)
* RSA 4 9
* ECP 4 8 (Started from top)
* MD 5 4
* CIPHER 6 6
* SSL 6 17 (Started from top)
* SSL 7 31
* DHM 3 11
* PK 3 15 (Started from top)
* RSA 4 11
* ECP 4 10 (Started from top)
* MD 5 5
* HKDF 5 1 (Started from top)
* CIPHER 6 8
* SSL 6 23 (Started from top)
* SSL 7 32
*
* Module dependent error code (5 bits 0x.00.-0x.F8.)
*/

View File

@ -1,9 +1,18 @@
/**
* \file gcm.h
*
* \brief Galois/Counter mode for 128-bit block ciphers
* \brief This file contains GCM definitions and functions.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined
* in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation
* (GCM), Natl. Inst. Stand. Technol.</em>
*
* For more information on GCM, see <em>NIST SP 800-38D: Recommendation for
* Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>.
*
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,11 +27,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_GCM_H
#define MBEDTLS_GCM_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "cipher.h"
#include <stdint.h>
@ -31,46 +47,69 @@
#define MBEDTLS_GCM_DECRYPT 0
#define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */
/* MBEDTLS_ERR_GCM_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED -0x0013 /**< GCM hardware accelerator failed. */
#define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_GCM_ALT)
/**
* \brief GCM context structure
* \brief The GCM context structure.
*/
typedef struct {
mbedtls_cipher_context_t cipher_ctx;/*!< cipher context used */
uint64_t HL[16]; /*!< Precalculated HTable */
uint64_t HH[16]; /*!< Precalculated HTable */
uint64_t len; /*!< Total data length */
uint64_t add_len; /*!< Total add length */
unsigned char base_ectr[16];/*!< First ECTR for tag */
unsigned char y[16]; /*!< Y working value */
unsigned char buf[16]; /*!< buf working value */
int mode; /*!< Encrypt or Decrypt */
typedef struct mbedtls_gcm_context
{
mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */
uint64_t HL[16]; /*!< Precalculated HTable low. */
uint64_t HH[16]; /*!< Precalculated HTable high. */
uint64_t len; /*!< The total length of the encrypted data. */
uint64_t add_len; /*!< The total length of the additional data. */
unsigned char base_ectr[16]; /*!< The first ECTR for tag. */
unsigned char y[16]; /*!< The Y working value. */
unsigned char buf[16]; /*!< The buf working value. */
int mode; /*!< The operation to perform:
#MBEDTLS_GCM_ENCRYPT or
#MBEDTLS_GCM_DECRYPT. */
}
mbedtls_gcm_context;
#else /* !MBEDTLS_GCM_ALT */
#include "gcm_alt.h"
#endif /* !MBEDTLS_GCM_ALT */
/**
* \brief Initialize GCM context (just makes references valid)
* Makes the context ready for mbedtls_gcm_setkey() or
* mbedtls_gcm_free().
* \brief This function initializes the specified GCM context,
* to make references valid, and prepares the context
* for mbedtls_gcm_setkey() or mbedtls_gcm_free().
*
* \param ctx GCM context to initialize
* The function does not bind the GCM context to a particular
* cipher, nor set the key. For this purpose, use
* mbedtls_gcm_setkey().
*
* \param ctx The GCM context to initialize. This must not be \c NULL.
*/
void mbedtls_gcm_init( mbedtls_gcm_context *ctx );
/**
* \brief GCM initialization (encryption)
* \brief This function associates a GCM context with a
* cipher algorithm and a key.
*
* \param ctx GCM context to be initialized
* \param cipher cipher to use (a 128-bit block cipher)
* \param key encryption key
* \param keybits must be 128, 192 or 256
* \param ctx The GCM context. This must be initialized.
* \param cipher The 128-bit block cipher to use.
* \param key The encryption key. This must be a readable buffer of at
* least \p keybits bits.
* \param keybits The key size in bits. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return 0 if successful, or a cipher specific error code
* \return \c 0 on success.
* \return A cipher-specific error code on failure.
*/
int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
mbedtls_cipher_id_t cipher,
@ -78,26 +117,55 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
unsigned int keybits );
/**
* \brief GCM buffer encryption/decryption using a block cipher
* \brief This function performs GCM encryption or decryption of a buffer.
*
* \note On encryption, the output buffer can be the same as the input buffer.
* On decryption, the output buffer cannot be the same as input buffer.
* If buffers overlap, the output buffer must trail at least 8 bytes
* behind the input buffer.
* \note For encryption, the output buffer can be the same as the
* input buffer. For decryption, the output buffer cannot be
* the same as input buffer. If the buffers overlap, the output
* buffer must trail at least 8 Bytes behind the input buffer.
*
* \param ctx GCM context
* \param mode MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT
* \param length length of the input data
* \param iv initialization vector
* \param iv_len length of IV
* \param add additional data
* \param add_len length of additional data
* \param input buffer holding the input data
* \param output buffer for holding the output data
* \param tag_len length of the tag to generate
* \param tag buffer for holding the tag
* \warning When this function performs a decryption, it outputs the
* authentication tag and does not verify that the data is
* authentic. You should use this function to perform encryption
* only. For decryption, use mbedtls_gcm_auth_decrypt() instead.
*
* \return 0 if successful
* \param ctx The GCM context to use for encryption or decryption. This
* must be initialized.
* \param mode The operation to perform:
* - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption.
* The ciphertext is written to \p output and the
* authentication tag is written to \p tag.
* - #MBEDTLS_GCM_DECRYPT to perform decryption.
* The plaintext is written to \p output and the
* authentication tag is written to \p tag.
* Note that this mode is not recommended, because it does
* not verify the authenticity of the data. For this reason,
* you should use mbedtls_gcm_auth_decrypt() instead of
* calling this function in decryption mode.
* \param length The length of the input data, which is equal to the length
* of the output data.
* \param iv The initialization vector. This must be a readable buffer of
* at least \p iv_len Bytes.
* \param iv_len The length of the IV.
* \param add The buffer holding the additional data. This must be of at
* least that size in Bytes.
* \param add_len The length of the additional data.
* \param input The buffer holding the input data. If \p length is greater
* than zero, this must be a readable buffer of at least that
* size in Bytes.
* \param output The buffer for holding the output data. If \p length is greater
* than zero, this must be a writable buffer of at least that
* size in Bytes.
* \param tag_len The length of the tag to generate.
* \param tag The buffer for holding the tag. This must be a readable
* buffer of at least \p tag_len Bytes.
*
* \return \c 0 if the encryption or decryption was performed
* successfully. Note that in #MBEDTLS_GCM_DECRYPT mode,
* this does not indicate that the data is authentic.
* \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are
* not valid or a cipher-specific error code if the encryption
* or decryption failed.
*/
int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
int mode,
@ -112,25 +180,37 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
unsigned char *tag );
/**
* \brief GCM buffer authenticated decryption using a block cipher
* \brief This function performs a GCM authenticated decryption of a
* buffer.
*
* \note On decryption, the output buffer cannot be the same as input buffer.
* If buffers overlap, the output buffer must trail at least 8 bytes
* behind the input buffer.
* \note For decryption, the output buffer cannot be the same as
* input buffer. If the buffers overlap, the output buffer
* must trail at least 8 Bytes behind the input buffer.
*
* \param ctx GCM context
* \param length length of the input data
* \param iv initialization vector
* \param iv_len length of IV
* \param add additional data
* \param add_len length of additional data
* \param tag buffer holding the tag
* \param tag_len length of the tag
* \param input buffer holding the input data
* \param output buffer for holding the output data
* \param ctx The GCM context. This must be initialized.
* \param length The length of the ciphertext to decrypt, which is also
* the length of the decrypted plaintext.
* \param iv The initialization vector. This must be a readable buffer
* of at least \p iv_len Bytes.
* \param iv_len The length of the IV.
* \param add The buffer holding the additional data. This must be of at
* least that size in Bytes.
* \param add_len The length of the additional data.
* \param tag The buffer holding the tag to verify. This must be a
* readable buffer of at least \p tag_len Bytes.
* \param tag_len The length of the tag to verify.
* \param input The buffer holding the ciphertext. If \p length is greater
* than zero, this must be a readable buffer of at least that
* size.
* \param output The buffer for holding the decrypted plaintext. If \p length
* is greater than zero, this must be a writable buffer of at
* least that size.
*
* \return 0 if successful and authenticated,
* MBEDTLS_ERR_GCM_AUTH_FAILED if tag does not match
* \return \c 0 if successful and authenticated.
* \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match.
* \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are
* not valid or a cipher-specific error code if the decryption
* failed.
*/
int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
size_t length,
@ -144,16 +224,21 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
unsigned char *output );
/**
* \brief Generic GCM stream start function
* \brief This function starts a GCM encryption or decryption
* operation.
*
* \param ctx GCM context
* \param mode MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT
* \param iv initialization vector
* \param iv_len length of IV
* \param add additional data (or NULL if length is 0)
* \param add_len length of additional data
* \param ctx The GCM context. This must be initialized.
* \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or
* #MBEDTLS_GCM_DECRYPT.
* \param iv The initialization vector. This must be a readable buffer of
* at least \p iv_len Bytes.
* \param iv_len The length of the IV.
* \param add The buffer holding the additional data, or \c NULL
* if \p add_len is \c 0.
* \param add_len The length of the additional data. If \c 0,
* \p add may be \c NULL.
*
* \return 0 if successful
* \return \c 0 on success.
*/
int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
int mode,
@ -163,21 +248,29 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
size_t add_len );
/**
* \brief Generic GCM update function. Encrypts/decrypts using the
* given GCM context. Expects input to be a multiple of 16
* bytes! Only the last call before mbedtls_gcm_finish() can be less
* than 16 bytes!
* \brief This function feeds an input buffer into an ongoing GCM
* encryption or decryption operation.
*
* \note On decryption, the output buffer cannot be the same as input buffer.
* If buffers overlap, the output buffer must trail at least 8 bytes
* behind the input buffer.
* ` The function expects input to be a multiple of 16
* Bytes. Only the last call before calling
* mbedtls_gcm_finish() can be less than 16 Bytes.
*
* \param ctx GCM context
* \param length length of the input data
* \param input buffer holding the input data
* \param output buffer for holding the output data
* \note For decryption, the output buffer cannot be the same as
* input buffer. If the buffers overlap, the output buffer
* must trail at least 8 Bytes behind the input buffer.
*
* \return 0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT
* \param ctx The GCM context. This must be initialized.
* \param length The length of the input data. This must be a multiple of
* 16 except in the last call before mbedtls_gcm_finish().
* \param input The buffer holding the input data. If \p length is greater
* than zero, this must be a readable buffer of at least that
* size in Bytes.
* \param output The buffer for holding the output data. If \p length is
* greater than zero, this must be a writable buffer of at
* least that size in Bytes.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
*/
int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
size_t length,
@ -185,36 +278,49 @@ int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
unsigned char *output );
/**
* \brief Generic GCM finalisation function. Wraps up the GCM stream
* and generates the tag. The tag can have a maximum length of
* 16 bytes.
* \brief This function finishes the GCM operation and generates
* the authentication tag.
*
* \param ctx GCM context
* \param tag buffer for holding the tag
* \param tag_len length of the tag to generate (must be at least 4)
* It wraps up the GCM stream, and generates the
* tag. The tag can have a maximum length of 16 Bytes.
*
* \return 0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT
* \param ctx The GCM context. This must be initialized.
* \param tag The buffer for holding the tag. This must be a readable
* buffer of at least \p tag_len Bytes.
* \param tag_len The length of the tag to generate. This must be at least
* four.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
*/
int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
unsigned char *tag,
size_t tag_len );
/**
* \brief Free a GCM context and underlying cipher sub-context
* \brief This function clears a GCM context and the underlying
* cipher sub-context.
*
* \param ctx GCM context to free
* \param ctx The GCM context to clear. If this is \c NULL, the call has
* no effect. Otherwise, this must be initialized.
*/
void mbedtls_gcm_free( mbedtls_gcm_context *ctx );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
* \brief The GCM checkup routine.
*
* \return 0 if successful, or 1 if the test failed
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_gcm_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* gcm.h */

View File

@ -2,7 +2,8 @@
* \file havege.h
*
* \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_HAVEGE_H
#define MBEDTLS_HAVEGE_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#define MBEDTLS_HAVEGE_COLLECT_SIZE 1024
@ -34,7 +41,7 @@ extern "C" {
/**
* \brief HAVEGE state structure
*/
typedef struct
typedef struct mbedtls_havege_state
{
int PT1, PT2, offset[2];
int pool[MBEDTLS_HAVEGE_COLLECT_SIZE];

141
Externals/mbedtls/include/mbedtls/hkdf.h vendored Normal file
View File

@ -0,0 +1,141 @@
/**
* \file hkdf.h
*
* \brief This file contains the HKDF interface.
*
* The HMAC-based Extract-and-Expand Key Derivation Function (HKDF) is
* specified by RFC 5869.
*/
/*
* Copyright (C) 2016-2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_HKDF_H
#define MBEDTLS_HKDF_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "md.h"
/**
* \name HKDF Error codes
* \{
*/
#define MBEDTLS_ERR_HKDF_BAD_INPUT_DATA -0x5F80 /**< Bad input parameters to function. */
/* \} name */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief This is the HMAC-based Extract-and-Expand Key Derivation Function
* (HKDF).
*
* \param md A hash function; md.size denotes the length of the hash
* function output in bytes.
* \param salt An optional salt value (a non-secret random value);
* if the salt is not provided, a string of all zeros of
* md.size length is used as the salt.
* \param salt_len The length in bytes of the optional \p salt.
* \param ikm The input keying material.
* \param ikm_len The length in bytes of \p ikm.
* \param info An optional context and application specific information
* string. This can be a zero-length string.
* \param info_len The length of \p info in bytes.
* \param okm The output keying material of \p okm_len bytes.
* \param okm_len The length of the output keying material in bytes. This
* must be less than or equal to 255 * md.size bytes.
*
* \return 0 on success.
* \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.
* \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
* MD layer.
*/
int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,
size_t salt_len, const unsigned char *ikm, size_t ikm_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len );
/**
* \brief Take the input keying material \p ikm and extract from it a
* fixed-length pseudorandom key \p prk.
*
* \warning This function should only be used if the security of it has been
* studied and established in that particular context (eg. TLS 1.3
* key schedule). For standard HKDF security guarantees use
* \c mbedtls_hkdf instead.
*
* \param md A hash function; md.size denotes the length of the
* hash function output in bytes.
* \param salt An optional salt value (a non-secret random value);
* if the salt is not provided, a string of all zeros
* of md.size length is used as the salt.
* \param salt_len The length in bytes of the optional \p salt.
* \param ikm The input keying material.
* \param ikm_len The length in bytes of \p ikm.
* \param[out] prk A pseudorandom key of at least md.size bytes.
*
* \return 0 on success.
* \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.
* \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
* MD layer.
*/
int mbedtls_hkdf_extract( const mbedtls_md_info_t *md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk );
/**
* \brief Expand the supplied \p prk into several additional pseudorandom
* keys, which is the output of the HKDF.
*
* \warning This function should only be used if the security of it has been
* studied and established in that particular context (eg. TLS 1.3
* key schedule). For standard HKDF security guarantees use
* \c mbedtls_hkdf instead.
*
* \param md A hash function; md.size denotes the length of the hash
* function output in bytes.
* \param prk A pseudorandom key of at least md.size bytes. \p prk is
* usually the output from the HKDF extract step.
* \param prk_len The length in bytes of \p prk.
* \param info An optional context and application specific information
* string. This can be a zero-length string.
* \param info_len The length of \p info in bytes.
* \param okm The output keying material of \p okm_len bytes.
* \param okm_len The length of the output keying material in bytes. This
* must be less than or equal to 255 * md.size bytes.
*
* \return 0 on success.
* \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.
* \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
* MD layer.
*/
int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
size_t prk_len, const unsigned char *info,
size_t info_len, unsigned char *okm, size_t okm_len );
#ifdef __cplusplus
}
#endif
#endif /* hkdf.h */

View File

@ -2,7 +2,8 @@
* \file hmac_drbg.h
*
* \brief HMAC_DRBG (NIST SP 800-90A)
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,10 +24,16 @@
#ifndef MBEDTLS_HMAC_DRBG_H
#define MBEDTLS_HMAC_DRBG_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "md.h"
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#include "threading.h"
#endif
/*
@ -73,7 +80,7 @@ extern "C" {
/**
* HMAC_DRBG context.
*/
typedef struct
typedef struct mbedtls_hmac_drbg_context
{
/* Working state: the key K is not stored explicitely,
* but is implied by the HMAC context */
@ -194,10 +201,13 @@ void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx,
* \param additional Additional data to update state with, or NULL
* \param add_len Length of additional data, or 0
*
* \return \c 0 on success, or an error from the underlying
* hash calculation.
*
* \note Additional data is optional, pass NULL and 0 as second
* third argument if no additional data is being used.
*/
void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t add_len );
/**
@ -256,6 +266,31 @@ int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len
*/
void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx );
#if ! defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief HMAC_DRBG update state
*
* \deprecated Superseded by mbedtls_hmac_drbg_update_ret()
* in 2.16.0.
*
* \param ctx HMAC_DRBG context
* \param additional Additional data to update state with, or NULL
* \param add_len Length of additional data, or 0
*
* \note Additional data is optional, pass NULL and 0 as second
* third argument if no additional data is being used.
*/
MBEDTLS_DEPRECATED void mbedtls_hmac_drbg_update(
mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t add_len );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_FS_IO)
/**
* \brief Write a seed file

View File

@ -1,11 +1,12 @@
/**
/**
* \file md.h
*
* \brief Generic message digest wrapper
* \brief This file contains the generic message-digest wrapper.
*
* \author Adriaan de Jong <dejong@fox-it.com>
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -20,33 +21,51 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_MD_H
#define MBEDTLS_MD_H
#include <stddef.h>
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */
#define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */
#define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */
#define MBEDTLS_ERR_MD_FILE_IO_ERROR -0x5200 /**< Opening or reading of file failed. */
/* MBEDTLS_ERR_MD_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_MD_HW_ACCEL_FAILED -0x5280 /**< MD hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Supported message digests.
*
* \warning MD2, MD4, MD5 and SHA-1 are considered weak message digests and
* their use constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef enum {
MBEDTLS_MD_NONE=0,
MBEDTLS_MD_MD2,
MBEDTLS_MD_MD4,
MBEDTLS_MD_MD5,
MBEDTLS_MD_SHA1,
MBEDTLS_MD_SHA224,
MBEDTLS_MD_SHA256,
MBEDTLS_MD_SHA384,
MBEDTLS_MD_SHA512,
MBEDTLS_MD_RIPEMD160,
MBEDTLS_MD_NONE=0, /**< None. */
MBEDTLS_MD_MD2, /**< The MD2 message digest. */
MBEDTLS_MD_MD4, /**< The MD4 message digest. */
MBEDTLS_MD_MD5, /**< The MD5 message digest. */
MBEDTLS_MD_SHA1, /**< The SHA-1 message digest. */
MBEDTLS_MD_SHA224, /**< The SHA-224 message digest. */
MBEDTLS_MD_SHA256, /**< The SHA-256 message digest. */
MBEDTLS_MD_SHA384, /**< The SHA-384 message digest. */
MBEDTLS_MD_SHA512, /**< The SHA-512 message digest. */
MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */
} mbedtls_md_type_t;
#if defined(MBEDTLS_SHA512_C)
@ -56,65 +75,80 @@ typedef enum {
#endif
/**
* Opaque struct defined in md_internal.h
* Opaque struct defined in md_internal.h.
*/
typedef struct mbedtls_md_info_t mbedtls_md_info_t;
/**
* Generic message digest context.
* The generic message-digest context.
*/
typedef struct {
/** Information about the associated message digest */
typedef struct mbedtls_md_context_t
{
/** Information about the associated message digest. */
const mbedtls_md_info_t *md_info;
/** Digest-specific context */
/** The digest-specific context. */
void *md_ctx;
/** HMAC part of the context */
/** The HMAC part of the context. */
void *hmac_ctx;
} mbedtls_md_context_t;
/**
* \brief Returns the list of digests supported by the generic digest module.
* \brief This function returns the list of digests supported by the
* generic digest module.
*
* \return a statically allocated array of digests, the last entry
* is 0.
* \return A statically allocated array of digests. Each element
* in the returned list is an integer belonging to the
* message-digest enumeration #mbedtls_md_type_t.
* The last entry is 0.
*/
const int *mbedtls_md_list( void );
/**
* \brief Returns the message digest information associated with the
* given digest name.
* \brief This function returns the message-digest information
* associated with the given digest name.
*
* \param md_name Name of the digest to search for.
* \param md_name The name of the digest to search for.
*
* \return The message digest information associated with md_name or
* NULL if not found.
* \return The message-digest information associated with \p md_name.
* \return NULL if the associated message-digest information is not found.
*/
const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name );
/**
* \brief Returns the message digest information associated with the
* given digest type.
* \brief This function returns the message-digest information
* associated with the given digest type.
*
* \param md_type type of digest to search for.
* \param md_type The type of digest to search for.
*
* \return The message digest information associated with md_type or
* NULL if not found.
* \return The message-digest information associated with \p md_type.
* \return NULL if the associated message-digest information is not found.
*/
const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type );
/**
* \brief Initialize a md_context (as NONE)
* This should always be called first.
* Prepares the context for mbedtls_md_setup() or mbedtls_md_free().
* \brief This function initializes a message-digest context without
* binding it to a particular message-digest algorithm.
*
* This function should always be called first. It prepares the
* context for mbedtls_md_setup() for binding it to a
* message-digest algorithm.
*/
void mbedtls_md_init( mbedtls_md_context_t *ctx );
/**
* \brief Free and clear the internal structures of ctx.
* Can be called at any time after mbedtls_md_init().
* Mandatory once mbedtls_md_setup() has been called.
* \brief This function clears the internal structure of \p ctx and
* frees any embedded internal structure, but does not free
* \p ctx itself.
*
* If you have called mbedtls_md_setup() on \p ctx, you must
* call mbedtls_md_free() when you are no longer using the
* context.
* Calling this function if you have previously
* called mbedtls_md_init() and nothing else is optional.
* You must not call this function if you have not called
* mbedtls_md_init().
*/
void mbedtls_md_free( mbedtls_md_context_t *ctx );
@ -125,220 +159,300 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx );
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Select MD to use and allocate internal structures.
* Should be called after mbedtls_md_init() or mbedtls_md_free().
* \brief This function selects the message digest algorithm to use,
* and allocates internal structures.
*
* It should be called after mbedtls_md_init() or mbedtls_md_free().
* Makes it necessary to call mbedtls_md_free() later.
*
* \deprecated Superseded by mbedtls_md_setup() in 2.0.0
*
* \param ctx Context to set up.
* \param md_info Message digest to use.
* \param ctx The context to set up.
* \param md_info The information structure of the message-digest algorithm
* to use.
*
* \returns \c 0 on success,
* \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
* \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure.
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
* \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure.
*/
int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED;
#undef MBEDTLS_DEPRECATED
#endif /* MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Select MD to use and allocate internal structures.
* Should be called after mbedtls_md_init() or mbedtls_md_free().
* Makes it necessary to call mbedtls_md_free() later.
* \brief This function selects the message digest algorithm to use,
* and allocates internal structures.
*
* \param ctx Context to set up.
* \param md_info Message digest to use.
* \param hmac 0 to save some memory if HMAC will not be used,
* non-zero is HMAC is going to be used with this context.
* It should be called after mbedtls_md_init() or
* mbedtls_md_free(). Makes it necessary to call
* mbedtls_md_free() later.
*
* \returns \c 0 on success,
* \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
* \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure.
* \param ctx The context to set up.
* \param md_info The information structure of the message-digest algorithm
* to use.
* \param hmac Defines if HMAC is used. 0: HMAC is not used (saves some memory),
* or non-zero: HMAC is used with this context.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
* \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure.
*/
int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac );
/**
* \brief Clone the state of an MD context
* \brief This function clones the state of an message-digest
* context.
*
* \note The two contexts must have been setup to the same type
* (cloning from SHA-256 to SHA-512 make no sense).
* \note You must call mbedtls_md_setup() on \c dst before calling
* this function.
*
* \warning Only clones the MD state, not the HMAC state! (for now)
* \note The two contexts must have the same type,
* for example, both are SHA-256.
*
* \param dst The destination context
* \param src The context to be cloned
* \warning This function clones the message-digest state, not the
* HMAC state.
*
* \return \c 0 on success,
* \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure.
* \param dst The destination context.
* \param src The context to be cloned.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure.
*/
int mbedtls_md_clone( mbedtls_md_context_t *dst,
const mbedtls_md_context_t *src );
/**
* \brief Returns the size of the message digest output.
* \brief This function extracts the message-digest size from the
* message-digest information structure.
*
* \param md_info message digest info
* \param md_info The information structure of the message-digest algorithm
* to use.
*
* \return size of the message digest output in bytes.
* \return The size of the message-digest output in Bytes.
*/
unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info );
/**
* \brief Returns the type of the message digest output.
* \brief This function extracts the message-digest type from the
* message-digest information structure.
*
* \param md_info message digest info
* \param md_info The information structure of the message-digest algorithm
* to use.
*
* \return type of the message digest output.
* \return The type of the message digest.
*/
mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info );
/**
* \brief Returns the name of the message digest output.
* \brief This function extracts the message-digest name from the
* message-digest information structure.
*
* \param md_info message digest info
* \param md_info The information structure of the message-digest algorithm
* to use.
*
* \return name of the message digest output.
* \return The name of the message digest.
*/
const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info );
/**
* \brief Prepare the context to digest a new message.
* Generally called after mbedtls_md_setup() or mbedtls_md_finish().
* Followed by mbedtls_md_update().
* \brief This function starts a message-digest computation.
*
* \param ctx generic message digest context.
* You must call this function after setting up the context
* with mbedtls_md_setup(), and before passing data with
* mbedtls_md_update().
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The generic message-digest context.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_starts( mbedtls_md_context_t *ctx );
/**
* \brief Generic message digest process buffer
* Called between mbedtls_md_starts() and mbedtls_md_finish().
* May be called repeatedly.
* \brief This function feeds an input buffer into an ongoing
* message-digest computation.
*
* \param ctx Generic message digest context
* \param input buffer holding the datal
* \param ilen length of the input data
* You must call mbedtls_md_starts() before calling this
* function. You may call this function multiple times.
* Afterwards, call mbedtls_md_finish().
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The generic message-digest context.
* \param input The buffer holding the input data.
* \param ilen The length of the input data.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen );
/**
* \brief Generic message digest final digest
* Called after mbedtls_md_update().
* Usually followed by mbedtls_md_free() or mbedtls_md_starts().
* \brief This function finishes the digest operation,
* and writes the result to the output buffer.
*
* \param ctx Generic message digest context
* \param output Generic message digest checksum result
* Call this function after a call to mbedtls_md_starts(),
* followed by any number of calls to mbedtls_md_update().
* Afterwards, you may either clear the context with
* mbedtls_md_free(), or call mbedtls_md_starts() to reuse
* the context for another digest operation with the same
* algorithm.
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The generic message-digest context.
* \param output The buffer for the generic message-digest checksum result.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
/**
* \brief Output = message_digest( input buffer )
* \brief This function calculates the message-digest of a buffer,
* with respect to a configurable message-digest algorithm
* in a single call.
*
* \param md_info message digest info
* \param input buffer holding the data
* \param ilen length of the input data
* \param output Generic message digest checksum result
* The result is calculated as
* Output = message_digest(input buffer).
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param md_info The information structure of the message-digest algorithm
* to use.
* \param input The buffer holding the data.
* \param ilen The length of the input data.
* \param output The generic message-digest checksum result.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
unsigned char *output );
#if defined(MBEDTLS_FS_IO)
/**
* \brief Output = message_digest( file contents )
* \brief This function calculates the message-digest checksum
* result of the contents of the provided file.
*
* \param md_info message digest info
* \param path input file name
* \param output generic message digest checksum result
* The result is calculated as
* Output = message_digest(file contents).
*
* \return 0 if successful,
* MBEDTLS_ERR_MD_FILE_IO_ERROR if file input failed,
* MBEDTLS_ERR_MD_BAD_INPUT_DATA if md_info was NULL.
* \param md_info The information structure of the message-digest algorithm
* to use.
* \param path The input file name.
* \param output The generic message-digest checksum result.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing
* the file pointed by \p path.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL.
*/
int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path,
unsigned char *output );
#endif /* MBEDTLS_FS_IO */
/**
* \brief Set HMAC key and prepare to authenticate a new message.
* Usually called after mbedtls_md_setup() or mbedtls_md_hmac_finish().
* \brief This function sets the HMAC key and prepares to
* authenticate a new message.
*
* \param ctx HMAC context
* \param key HMAC secret key
* \param keylen length of the HMAC key in bytes
* Call this function after mbedtls_md_setup(), to use
* the MD context for an HMAC calculation, then call
* mbedtls_md_hmac_update() to provide the input data, and
* mbedtls_md_hmac_finish() to get the HMAC value.
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The message digest context containing an embedded HMAC
* context.
* \param key The HMAC secret key.
* \param keylen The length of the HMAC key in Bytes.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
size_t keylen );
/**
* \brief Generic HMAC process buffer.
* Called between mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()
* and mbedtls_md_hmac_finish().
* May be called repeatedly.
* \brief This function feeds an input buffer into an ongoing HMAC
* computation.
*
* \param ctx HMAC context
* \param input buffer holding the data
* \param ilen length of the input data
* Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()
* before calling this function.
* You may call this function multiple times to pass the
* input piecewise.
* Afterwards, call mbedtls_md_hmac_finish().
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The message digest context containing an embedded HMAC
* context.
* \param input The buffer holding the input data.
* \param ilen The length of the input data.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input,
size_t ilen );
/**
* \brief Output HMAC.
* Called after mbedtls_md_hmac_update().
* Usually followed by mbedtls_md_hmac_reset(),
* mbedtls_md_hmac_starts(), or mbedtls_md_free().
* \brief This function finishes the HMAC operation, and writes
* the result to the output buffer.
*
* \param ctx HMAC context
* \param output Generic HMAC checksum result
* Call this function after mbedtls_md_hmac_starts() and
* mbedtls_md_hmac_update() to get the HMAC value. Afterwards
* you may either call mbedtls_md_free() to clear the context,
* or call mbedtls_md_hmac_reset() to reuse the context with
* the same HMAC key.
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The message digest context containing an embedded HMAC
* context.
* \param output The generic HMAC checksum result.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output);
/**
* \brief Prepare to authenticate a new message with the same key.
* Called after mbedtls_md_hmac_finish() and before
* mbedtls_md_hmac_update().
* \brief This function prepares to authenticate a new message with
* the same key as the previous HMAC operation.
*
* \param ctx HMAC context to be reset
* You may call this function after mbedtls_md_hmac_finish().
* Afterwards call mbedtls_md_hmac_update() to pass the new
* input.
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* \param ctx The message digest context containing an embedded HMAC
* context.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx );
/**
* \brief Output = Generic_HMAC( hmac key, input buffer )
* \brief This function calculates the full generic HMAC
* on the input buffer with the provided key.
*
* \param md_info message digest info
* \param key HMAC secret key
* \param keylen length of the HMAC key in bytes
* \param input buffer holding the data
* \param ilen length of the input data
* \param output Generic HMAC-result
* The function allocates the context, performs the
* calculation, and frees the context.
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
* The HMAC result is calculated as
* output = generic HMAC(hmac key, input buffer).
*
* \param md_info The information structure of the message-digest algorithm
* to use.
* \param key The HMAC secret key.
* \param keylen The length of the HMAC secret key in Bytes.
* \param input The buffer holding the input data.
* \param ilen The length of the input data.
* \param output The generic HMAC result.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,
const unsigned char *input, size_t ilen,

View File

@ -3,6 +3,11 @@
*
* \brief MD2 message digest algorithm (hash function)
*
* \warning MD2 is considered a weak message digest and its use constitutes a
* security risk. We recommend considering stronger message digests
* instead.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -19,6 +24,7 @@
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
*/
#ifndef MBEDTLS_MD2_H
#define MBEDTLS_MD2_H
@ -31,18 +37,26 @@
#include <stddef.h>
#if !defined(MBEDTLS_MD2_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_MD2_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED -0x002B /**< MD2 hardware accelerator failed */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_MD2_ALT)
// Regular implementation
//
/**
* \brief MD2 context structure
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct
typedef struct mbedtls_md2_context
{
unsigned char cksum[16]; /*!< checksum of the data block */
unsigned char state[48]; /*!< intermediate digest state */
@ -51,10 +65,19 @@ typedef struct
}
mbedtls_md2_context;
#else /* MBEDTLS_MD2_ALT */
#include "md2_alt.h"
#endif /* MBEDTLS_MD2_ALT */
/**
* \brief Initialize MD2 context
*
* \param ctx MD2 context to be initialized
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md2_init( mbedtls_md2_context *ctx );
@ -62,6 +85,11 @@ void mbedtls_md2_init( mbedtls_md2_context *ctx );
* \brief Clear MD2 context
*
* \param ctx MD2 context to be cleared
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md2_free( mbedtls_md2_context *ctx );
@ -70,6 +98,11 @@ void mbedtls_md2_free( mbedtls_md2_context *ctx );
*
* \param dst The destination context
* \param src The context to be cloned
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md2_clone( mbedtls_md2_context *dst,
const mbedtls_md2_context *src );
@ -78,56 +111,193 @@ void mbedtls_md2_clone( mbedtls_md2_context *dst,
* \brief MD2 context setup
*
* \param ctx context to be initialized
*
* \return 0 if successful
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md2_starts( mbedtls_md2_context *ctx );
int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx );
/**
* \brief MD2 process buffer
*
* \param ctx MD2 context
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
*
* \return 0 if successful
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md2_update( mbedtls_md2_context *ctx, const unsigned char *input, size_t ilen );
int mbedtls_md2_update_ret( mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief MD2 final digest
*
* \param ctx MD2 context
* \param output MD2 checksum result
*
* \return 0 if successful
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md2_finish( mbedtls_md2_context *ctx, unsigned char output[16] );
int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,
unsigned char output[16] );
#ifdef __cplusplus
}
/**
* \brief MD2 process data block (internal use only)
*
* \param ctx MD2 context
*
* \return 0 if successful
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_internal_md2_process( mbedtls_md2_context *ctx );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief MD2 context setup
*
* \deprecated Superseded by mbedtls_md2_starts_ret() in 2.7.0
*
* \param ctx context to be initialized
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md2_starts( mbedtls_md2_context *ctx );
#else /* MBEDTLS_MD2_ALT */
#include "md2_alt.h"
#endif /* MBEDTLS_MD2_ALT */
/**
* \brief MD2 process buffer
*
* \deprecated Superseded by mbedtls_md2_update_ret() in 2.7.0
*
* \param ctx MD2 context
* \param input buffer holding the data
* \param ilen length of the input data
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md2_update( mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen );
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief MD2 final digest
*
* \deprecated Superseded by mbedtls_md2_finish_ret() in 2.7.0
*
* \param ctx MD2 context
* \param output MD2 checksum result
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md2_finish( mbedtls_md2_context *ctx,
unsigned char output[16] );
/**
* \brief MD2 process data block (internal use only)
*
* \deprecated Superseded by mbedtls_internal_md2_process() in 2.7.0
*
* \param ctx MD2 context
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md2_process( mbedtls_md2_context *ctx );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Output = MD2( input buffer )
*
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD2 checksum result
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md2( const unsigned char *input, size_t ilen, unsigned char output[16] );
int mbedtls_md2_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = MD2( input buffer )
*
* \deprecated Superseded by mbedtls_md2_ret() in 2.7.0
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD2 checksum result
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md2( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*
* \warning MD2 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md2_self_test( int verbose );
/* Internal use */
void mbedtls_md2_process( mbedtls_md2_context *ctx );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}

View File

@ -3,6 +3,11 @@
*
* \brief MD4 message digest algorithm (hash function)
*
* \warning MD4 is considered a weak message digest and its use constitutes a
* security risk. We recommend considering stronger message digests
* instead.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -19,6 +24,7 @@
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
*/
#ifndef MBEDTLS_MD4_H
#define MBEDTLS_MD4_H
@ -32,18 +38,26 @@
#include <stddef.h>
#include <stdint.h>
#if !defined(MBEDTLS_MD4_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_MD4_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED -0x002D /**< MD4 hardware accelerator failed */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_MD4_ALT)
// Regular implementation
//
/**
* \brief MD4 context structure
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct
typedef struct mbedtls_md4_context
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */
@ -51,10 +65,19 @@ typedef struct
}
mbedtls_md4_context;
#else /* MBEDTLS_MD4_ALT */
#include "md4_alt.h"
#endif /* MBEDTLS_MD4_ALT */
/**
* \brief Initialize MD4 context
*
* \param ctx MD4 context to be initialized
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md4_init( mbedtls_md4_context *ctx );
@ -62,6 +85,11 @@ void mbedtls_md4_init( mbedtls_md4_context *ctx );
* \brief Clear MD4 context
*
* \param ctx MD4 context to be cleared
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md4_free( mbedtls_md4_context *ctx );
@ -70,6 +98,11 @@ void mbedtls_md4_free( mbedtls_md4_context *ctx );
*
* \param dst The destination context
* \param src The context to be cloned
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md4_clone( mbedtls_md4_context *dst,
const mbedtls_md4_context *src );
@ -78,56 +111,198 @@ void mbedtls_md4_clone( mbedtls_md4_context *dst,
* \brief MD4 context setup
*
* \param ctx context to be initialized
*
* \return 0 if successful
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*/
void mbedtls_md4_starts( mbedtls_md4_context *ctx );
int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx );
/**
* \brief MD4 process buffer
*
* \param ctx MD4 context
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
*
* \return 0 if successful
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, size_t ilen );
int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief MD4 final digest
*
* \param ctx MD4 context
* \param output MD4 checksum result
*
* \return 0 if successful
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md4_finish( mbedtls_md4_context *ctx, unsigned char output[16] );
int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,
unsigned char output[16] );
#ifdef __cplusplus
}
/**
* \brief MD4 process data block (internal use only)
*
* \param ctx MD4 context
* \param data buffer holding one block of data
*
* \return 0 if successful
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_internal_md4_process( mbedtls_md4_context *ctx,
const unsigned char data[64] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief MD4 context setup
*
* \deprecated Superseded by mbedtls_md4_starts_ret() in 2.7.0
*
* \param ctx context to be initialized
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md4_starts( mbedtls_md4_context *ctx );
#else /* MBEDTLS_MD4_ALT */
#include "md4_alt.h"
#endif /* MBEDTLS_MD4_ALT */
/**
* \brief MD4 process buffer
*
* \deprecated Superseded by mbedtls_md4_update_ret() in 2.7.0
*
* \param ctx MD4 context
* \param input buffer holding the data
* \param ilen length of the input data
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md4_update( mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen );
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief MD4 final digest
*
* \deprecated Superseded by mbedtls_md4_finish_ret() in 2.7.0
*
* \param ctx MD4 context
* \param output MD4 checksum result
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md4_finish( mbedtls_md4_context *ctx,
unsigned char output[16] );
/**
* \brief MD4 process data block (internal use only)
*
* \deprecated Superseded by mbedtls_internal_md4_process() in 2.7.0
*
* \param ctx MD4 context
* \param data buffer holding one block of data
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md4_process( mbedtls_md4_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Output = MD4( input buffer )
*
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD4 checksum result
*
* \return 0 if successful
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md4( const unsigned char *input, size_t ilen, unsigned char output[16] );
int mbedtls_md4_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = MD4( input buffer )
*
* \deprecated Superseded by mbedtls_md4_ret() in 2.7.0
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD4 checksum result
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md4( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*
* \warning MD4 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md4_self_test( int verbose );
/* Internal use */
void mbedtls_md4_process( mbedtls_md4_context *ctx, const unsigned char data[64] );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}

View File

@ -3,6 +3,11 @@
*
* \brief MD5 message digest algorithm (hash function)
*
* \warning MD5 is considered a weak message digest and its use constitutes a
* security risk. We recommend considering stronger message
* digests instead.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -32,18 +37,26 @@
#include <stddef.h>
#include <stdint.h>
#if !defined(MBEDTLS_MD5_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_MD5_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /**< MD5 hardware accelerator failed */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_MD5_ALT)
// Regular implementation
//
/**
* \brief MD5 context structure
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct
typedef struct mbedtls_md5_context
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */
@ -51,10 +64,19 @@ typedef struct
}
mbedtls_md5_context;
#else /* MBEDTLS_MD5_ALT */
#include "md5_alt.h"
#endif /* MBEDTLS_MD5_ALT */
/**
* \brief Initialize MD5 context
*
* \param ctx MD5 context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_init( mbedtls_md5_context *ctx );
@ -62,6 +84,11 @@ void mbedtls_md5_init( mbedtls_md5_context *ctx );
* \brief Clear MD5 context
*
* \param ctx MD5 context to be cleared
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_free( mbedtls_md5_context *ctx );
@ -70,6 +97,11 @@ void mbedtls_md5_free( mbedtls_md5_context *ctx );
*
* \param dst The destination context
* \param src The context to be cloned
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_clone( mbedtls_md5_context *dst,
const mbedtls_md5_context *src );
@ -78,57 +110,200 @@ void mbedtls_md5_clone( mbedtls_md5_context *dst,
* \brief MD5 context setup
*
* \param ctx context to be initialized
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_starts( mbedtls_md5_context *ctx );
int mbedtls_md5_starts_ret( mbedtls_md5_context *ctx );
/**
* \brief MD5 process buffer
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_update( mbedtls_md5_context *ctx, const unsigned char *input, size_t ilen );
int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief MD5 final digest
*
* \param ctx MD5 context
* \param output MD5 checksum result
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_finish( mbedtls_md5_context *ctx, unsigned char output[16] );
int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
unsigned char output[16] );
/* Internal use */
void mbedtls_md5_process( mbedtls_md5_context *ctx, const unsigned char data[64] );
/**
* \brief MD5 process data block (internal use only)
*
* \param ctx MD5 context
* \param data buffer holding one block of data
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_internal_md5_process( mbedtls_md5_context *ctx,
const unsigned char data[64] );
#ifdef __cplusplus
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief MD5 context setup
*
* \deprecated Superseded by mbedtls_md5_starts_ret() in 2.7.0
*
* \param ctx context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_starts( mbedtls_md5_context *ctx );
#else /* MBEDTLS_MD5_ALT */
#include "md5_alt.h"
#endif /* MBEDTLS_MD5_ALT */
/**
* \brief MD5 process buffer
*
* \deprecated Superseded by mbedtls_md5_update_ret() in 2.7.0
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param ilen length of the input data
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_update( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen );
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief MD5 final digest
*
* \deprecated Superseded by mbedtls_md5_finish_ret() in 2.7.0
*
* \param ctx MD5 context
* \param output MD5 checksum result
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_finish( mbedtls_md5_context *ctx,
unsigned char output[16] );
/**
* \brief MD5 process data block (internal use only)
*
* \deprecated Superseded by mbedtls_internal_md5_process() in 2.7.0
*
* \param ctx MD5 context
* \param data buffer holding one block of data
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_process( mbedtls_md5_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Output = MD5( input buffer )
*
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5( const unsigned char *input, size_t ilen, unsigned char output[16] );
int mbedtls_md5_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = MD5( input buffer )
*
* \deprecated Superseded by mbedtls_md5_ret() in 2.7.0
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

View File

@ -6,7 +6,8 @@
* \warning This in an internal header. Do not include directly.
*
* \author Adriaan de Jong <dejong@fox-it.com>
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -58,17 +59,17 @@ struct mbedtls_md_info_t
int block_size;
/** Digest initialisation function */
void (*starts_func)( void *ctx );
int (*starts_func)( void *ctx );
/** Digest update function */
void (*update_func)( void *ctx, const unsigned char *input, size_t ilen );
int (*update_func)( void *ctx, const unsigned char *input, size_t ilen );
/** Digest finalisation function */
void (*finish_func)( void *ctx, unsigned char *output );
int (*finish_func)( void *ctx, unsigned char *output );
/** Generic digest function */
void (*digest_func)( const unsigned char *input, size_t ilen,
unsigned char *output );
int (*digest_func)( const unsigned char *input, size_t ilen,
unsigned char *output );
/** Allocate a new context */
void * (*ctx_alloc_func)( void );
@ -80,7 +81,7 @@ struct mbedtls_md_info_t
void (*clone_func)( void *dst, const void *src );
/** Internal use only */
void (*process_func)( void *ctx, const unsigned char *input );
int (*process_func)( void *ctx, const unsigned char *input );
};
#if defined(MBEDTLS_MD2_C)

View File

@ -2,7 +2,8 @@
* \file memory_buffer_alloc.h
*
* \brief Buffer-based memory allocator
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*

View File

@ -1,8 +1,11 @@
/**
* \file net.h
*
* \brief Deprecated header file that includes mbedtls/net_sockets.h
* \brief Deprecated header file that includes net_sockets.h
*
* \deprecated Superseded by mbedtls/net_sockets.h
*/
/*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -19,12 +22,15 @@
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
* \deprecated Superseded by mbedtls/net_sockets.h
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#include "mbedtls/net_sockets.h"
#include "net_sockets.h"
#if defined(MBEDTLS_DEPRECATED_WARNING)
#warning "Deprecated header file: Superseded by mbedtls/net_sockets.h"
#endif /* MBEDTLS_DEPRECATED_WARNING */

View File

@ -1,8 +1,25 @@
/**
* \file net_sockets.h
*
* \brief Network communication functions
* \brief Network sockets abstraction layer to integrate Mbed TLS into a
* BSD-style sockets API.
*
* The network sockets module provides an example integration of the
* Mbed TLS library into a BSD sockets implementation. The module is
* intended to be an example of how Mbed TLS can be integrated into a
* networking stack, as well as to be Mbed TLS's network integration
* for its supported platforms.
*
* The module is intended only to be used with the Mbed TLS library and
* is not intended to be used by third party application software
* directly.
*
* The supported platforms are as follows:
* * Microsoft Windows and Windows CE
* * POSIX/Unix platforms including Linux, OS X
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -45,12 +62,17 @@
#define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /**< Failed to get an IP address for the given hostname. */
#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /**< Buffer is too small to hold the data. */
#define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /**< The context is invalid, eg because it was free()ed. */
#define MBEDTLS_ERR_NET_POLL_FAILED -0x0047 /**< Polling the net context failed. */
#define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049 /**< Input invalid. */
#define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */
#define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */
#define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */
#define MBEDTLS_NET_POLL_READ 1 /**< Used in \c mbedtls_net_poll to check for pending data */
#define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */
#ifdef __cplusplus
extern "C" {
#endif
@ -62,7 +84,7 @@ extern "C" {
* (eg two file descriptors for combined IPv4 + IPv6 support, or additional
* structures for hand-made UDP demultiplexing).
*/
typedef struct
typedef struct mbedtls_net_context
{
int fd; /**< The underlying file descriptor */
}
@ -117,9 +139,10 @@ int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char
*
* \param bind_ctx Relevant socket
* \param client_ctx Will contain the connected client socket
* \param client_ip Will contain the client IP address
* \param client_ip Will contain the client IP address, can be NULL
* \param buf_size Size of the client_ip buffer
* \param ip_len Will receive the size of the client IP written
* \param ip_len Will receive the size of the client IP written,
* can be NULL if client_ip is null
*
* \return 0 if successful, or
* MBEDTLS_ERR_NET_ACCEPT_FAILED, or
@ -131,6 +154,29 @@ int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
mbedtls_net_context *client_ctx,
void *client_ip, size_t buf_size, size_t *ip_len );
/**
* \brief Check and wait for the context to be ready for read/write
*
* \param ctx Socket to check
* \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and
* MBEDTLS_NET_POLL_WRITE specifying the events
* to wait for:
* - If MBEDTLS_NET_POLL_READ is set, the function
* will return as soon as the net context is available
* for reading.
* - If MBEDTLS_NET_POLL_WRITE is set, the function
* will return as soon as the net context is available
* for writing.
* \param timeout Maximal amount of time to wait before returning,
* in milliseconds. If \c timeout is zero, the
* function returns immediately. If \c timeout is
* -1u, the function blocks potentially indefinitely.
*
* \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE
* on success or timeout, or a negative return code otherwise.
*/
int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout );
/**
* \brief Set the socket blocking
*

View File

@ -0,0 +1,184 @@
/**
* \file nist_kw.h
*
* \brief This file provides an API for key wrapping (KW) and key wrapping with
* padding (KWP) as defined in NIST SP 800-38F.
* https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf
*
* Key wrapping specifies a deterministic authenticated-encryption mode
* of operation, according to <em>NIST SP 800-38F: Recommendation for
* Block Cipher Modes of Operation: Methods for Key Wrapping</em>. Its
* purpose is to protect cryptographic keys.
*
* Its equivalent is RFC 3394 for KW, and RFC 5649 for KWP.
* https://tools.ietf.org/html/rfc3394
* https://tools.ietf.org/html/rfc5649
*
*/
/*
* Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_NIST_KW_H
#define MBEDTLS_NIST_KW_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "cipher.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
MBEDTLS_KW_MODE_KW = 0,
MBEDTLS_KW_MODE_KWP = 1
} mbedtls_nist_kw_mode_t;
#if !defined(MBEDTLS_NIST_KW_ALT)
// Regular implementation
//
/**
* \brief The key wrapping context-type definition. The key wrapping context is passed
* to the APIs called.
*
* \note The definition of this type may change in future library versions.
* Don't make any assumptions on this context!
*/
typedef struct {
mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */
} mbedtls_nist_kw_context;
#else /* MBEDTLS_NIST_key wrapping_ALT */
#include "nist_kw_alt.h"
#endif /* MBEDTLS_NIST_KW_ALT */
/**
* \brief This function initializes the specified key wrapping context
* to make references valid and prepare the context
* for mbedtls_nist_kw_setkey() or mbedtls_nist_kw_free().
*
* \param ctx The key wrapping context to initialize.
*
*/
void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx );
/**
* \brief This function initializes the key wrapping context set in the
* \p ctx parameter and sets the encryption key.
*
* \param ctx The key wrapping context.
* \param cipher The 128-bit block cipher to use. Only AES is supported.
* \param key The Key Encryption Key (KEK).
* \param keybits The KEK size in bits. This must be acceptable by the cipher.
* \param is_wrap Specify whether the operation within the context is wrapping or unwrapping
*
* \return \c 0 on success.
* \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for any invalid input.
* \return \c MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE for 128-bit block ciphers
* which are not supported.
* \return cipher-specific error code on failure of the underlying cipher.
*/
int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits,
const int is_wrap );
/**
* \brief This function releases and clears the specified key wrapping context
* and underlying cipher sub-context.
*
* \param ctx The key wrapping context to clear.
*/
void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx );
/**
* \brief This function encrypts a buffer using key wrapping.
*
* \param ctx The key wrapping context to use for encryption.
* \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP)
* \param input The buffer holding the input data.
* \param in_len The length of the input data in Bytes.
* The input uses units of 8 Bytes called semiblocks.
* <ul><li>For KW mode: a multiple of 8 bytes between 16 and 2^57-8 inclusive. </li>
* <li>For KWP mode: any length between 1 and 2^32-1 inclusive.</li></ul>
* \param[out] output The buffer holding the output data.
* <ul><li>For KW mode: Must be at least 8 bytes larger than \p in_len.</li>
* <li>For KWP mode: Must be at least 8 bytes larger rounded up to a multiple of
* 8 bytes for KWP (15 bytes at most).</li></ul>
* \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure.
* \param[in] out_size The capacity of the output buffer.
*
* \return \c 0 on success.
* \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.
* \return cipher-specific error code on failure of the underlying cipher.
*/
int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t* out_len, size_t out_size );
/**
* \brief This function decrypts a buffer using key wrapping.
*
* \param ctx The key wrapping context to use for decryption.
* \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP)
* \param input The buffer holding the input data.
* \param in_len The length of the input data in Bytes.
* The input uses units of 8 Bytes called semiblocks.
* The input must be a multiple of semiblocks.
* <ul><li>For KW mode: a multiple of 8 bytes between 24 and 2^57 inclusive. </li>
* <li>For KWP mode: a multiple of 8 bytes between 16 and 2^32 inclusive.</li></ul>
* \param[out] output The buffer holding the output data.
* The output buffer's minimal length is 8 bytes shorter than \p in_len.
* \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure.
* For KWP mode, the length could be up to 15 bytes shorter than \p in_len,
* depending on how much padding was added to the data.
* \param[in] out_size The capacity of the output buffer.
*
* \return \c 0 on success.
* \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.
* \return \c MBEDTLS_ERR_CIPHER_AUTH_FAILED for verification failure of the ciphertext.
* \return cipher-specific error code on failure of the underlying cipher.
*/
int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t* out_len, size_t out_size);
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/**
* \brief The key wrapping checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_nist_kw_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_NIST_KW_H */

View File

@ -2,7 +2,8 @@
* \file oid.h
*
* \brief Object Identifier (OID) database
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -96,6 +97,8 @@
/* ISO arc for standard certificate and CRL extensions */
#define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /**< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */
#define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */
/**
* Private Internet Extensions
* { iso(1) identified-organization(3) dod(6) internet(1)
@ -218,21 +221,42 @@
#define MBEDTLS_OID_DIGEST_ALG_MD4 MBEDTLS_OID_RSA_COMPANY "\x02\x04" /**< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */
#define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_GOV "\x03\x04\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_GOV "\x03\x04\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_GOV "\x03\x04\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_GOV "\x03\x04\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */
#define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */
#define MBEDTLS_OID_HMAC_SHA224 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */
#define MBEDTLS_OID_HMAC_SHA256 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */
#define MBEDTLS_OID_HMAC_SHA384 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */
#define MBEDTLS_OID_HMAC_SHA512 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */
/*
* Encryption algorithms
*/
#define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */
#define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */
#define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */
/*
* Key Wrapping algorithms
*/
/*
* RFC 5649
*/
#define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */
#define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */
#define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */
#define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */
#define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */
#define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */
/*
* PKCS#5 OIDs
*/
@ -379,7 +403,8 @@ extern "C" {
/**
* \brief Base OID descriptor structure
*/
typedef struct {
typedef struct mbedtls_oid_descriptor_t
{
const char *asn1; /*!< OID ASN.1 representation */
size_t asn1_len; /*!< length of asn1 */
const char *name; /*!< official name (e.g. from RFC) */
@ -513,6 +538,16 @@ int mbedtls_oid_get_oid_by_sig_alg( mbedtls_pk_type_t pk_alg, mbedtls_md_type_t
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg );
/**
* \brief Translate hmac algorithm OID into md_type
*
* \param oid OID to use
* \param md_hmac place to store message hmac algorithm
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac );
#endif /* MBEDTLS_MD_C */
/**

View File

@ -4,6 +4,10 @@
* \brief VIA PadLock ACE for HW encryption/decryption supported by some
* processors
*
* \warning These functions are only for internal use by other library
* functions; you must not call them directly.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -24,6 +28,12 @@
#ifndef MBEDTLS_PADLOCK_H
#define MBEDTLS_PADLOCK_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "aes.h"
#define MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED -0x0030 /**< Input data should be aligned. */
@ -56,7 +66,10 @@ extern "C" {
#endif
/**
* \brief PadLock detection routine
* \brief Internal PadLock detection routine
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param feature The feature to detect
*
@ -65,7 +78,10 @@ extern "C" {
int mbedtls_padlock_has_support( int feature );
/**
* \brief PadLock AES-ECB block en(de)cryption
* \brief Internal PadLock AES-ECB block en(de)cryption
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
@ -75,12 +91,15 @@ int mbedtls_padlock_has_support( int feature );
* \return 0 if success, 1 if operation failed
*/
int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] );
int mode,
const unsigned char input[16],
unsigned char output[16] );
/**
* \brief PadLock AES-CBC buffer en(de)cryption
* \brief Internal PadLock AES-CBC buffer en(de)cryption
*
* \note This function is only for internal use by other library
* functions; you must not call it directly.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
@ -92,11 +111,11 @@ int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
* \return 0 if success, 1 if operation failed
*/
int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output );
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output );
#ifdef __cplusplus
}

View File

@ -2,7 +2,8 @@
* \file pem.h
*
* \brief Privacy Enhanced Mail (PEM) decoding
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_PEM_H
#define MBEDTLS_PEM_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
/**
@ -50,7 +57,7 @@ extern "C" {
/**
* \brief PEM context structure
*/
typedef struct
typedef struct mbedtls_pem_context
{
unsigned char *buf; /*!< buffer for decoded data */
size_t buflen; /*!< length of the buffer */

View File

@ -2,7 +2,8 @@
* \file pk.h
*
* \brief Public Key abstraction layer
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -62,7 +63,10 @@
#define MBEDTLS_ERR_PK_INVALID_ALG -0x3A80 /**< The algorithm tag or value is invalid. */
#define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00 /**< Elliptic curve is unsupported (only NIST curves are supported). */
#define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980 /**< Unavailable feature, e.g. RSA disabled for RSA key. */
#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The signature is valid but its length is less than expected. */
#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The buffer contains a valid signature followed by more data. */
/* MBEDTLS_ERR_PK_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_PK_HW_ACCEL_FAILED -0x3880 /**< PK hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
@ -85,7 +89,7 @@ typedef enum {
* \brief Options for RSASSA-PSS signature verification.
* See \c mbedtls_rsa_rsassa_pss_verify_ext()
*/
typedef struct
typedef struct mbedtls_pk_rsassa_pss_options
{
mbedtls_md_type_t mgf1_hash_id;
int expected_salt_len;
@ -105,7 +109,7 @@ typedef enum
/**
* \brief Item to send to the debug module
*/
typedef struct
typedef struct mbedtls_pk_debug_item
{
mbedtls_pk_debug_type type;
const char *name;
@ -123,12 +127,26 @@ typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
/**
* \brief Public key container
*/
typedef struct
typedef struct mbedtls_pk_context
{
const mbedtls_pk_info_t * pk_info; /**< Public key informations */
const mbedtls_pk_info_t * pk_info; /**< Public key information */
void * pk_ctx; /**< Underlying public key context */
} mbedtls_pk_context;
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/**
* \brief Context for resuming operations
*/
typedef struct
{
const mbedtls_pk_info_t * pk_info; /**< Public key information */
void * rs_ctx; /**< Underlying restart context */
} mbedtls_pk_restart_ctx;
#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/* Now we can declare functions that take a pointer to that */
typedef void mbedtls_pk_restart_ctx;
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
#if defined(MBEDTLS_RSA_C)
/**
* Quick access to an RSA context inside a PK context.
@ -179,20 +197,45 @@ typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)( void *ctx );
const mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type );
/**
* \brief Initialize a mbedtls_pk_context (as NONE)
* \brief Initialize a #mbedtls_pk_context (as NONE).
*
* \param ctx The context to initialize.
* This must not be \c NULL.
*/
void mbedtls_pk_init( mbedtls_pk_context *ctx );
/**
* \brief Free a mbedtls_pk_context
* \brief Free the components of a #mbedtls_pk_context.
*
* \param ctx The context to clear. It must have been initialized.
* If this is \c NULL, this function does nothing.
*/
void mbedtls_pk_free( mbedtls_pk_context *ctx );
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/**
* \brief Initialize a restart context
*
* \param ctx The context to initialize.
* This must not be \c NULL.
*/
void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx );
/**
* \brief Free the components of a restart context
*
* \param ctx The context to clear. It must have been initialized.
* If this is \c NULL, this function does nothing.
*/
void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx );
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/**
* \brief Initialize a PK context with the information given
* and allocates the type-specific PK subcontext.
*
* \param ctx Context to initialize. Must be empty (type NONE).
* \param ctx Context to initialize. It must not have been set
* up yet (type #MBEDTLS_PK_NONE).
* \param info Information to use
*
* \return 0 on success,
@ -208,7 +251,8 @@ int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info );
/**
* \brief Initialize an RSA-alt context
*
* \param ctx Context to initialize. Must be empty (type NONE).
* \param ctx Context to initialize. It must not have been set
* up yet (type #MBEDTLS_PK_NONE).
* \param key RSA key pointer
* \param decrypt_func Decryption function
* \param sign_func Signing function
@ -228,7 +272,7 @@ int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,
/**
* \brief Get the size in bits of the underlying key
*
* \param ctx Context to use
* \param ctx The context to query. It must have been initialized.
*
* \return Key size in bits, or 0 on error
*/
@ -236,7 +280,8 @@ size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx );
/**
* \brief Get the length in bytes of the underlying key
* \param ctx Context to use
*
* \param ctx The context to query. It must have been initialized.
*
* \return Key length in bytes, or 0 on error
*/
@ -248,18 +293,21 @@ static inline size_t mbedtls_pk_get_len( const mbedtls_pk_context *ctx )
/**
* \brief Tell if a context can do the operation given by type
*
* \param ctx Context to test
* \param type Target type
* \param ctx The context to query. It must have been initialized.
* \param type The desired type.
*
* \return 0 if context can't do the operations,
* 1 otherwise.
* \return 1 if the context can do operations on the given type.
* \return 0 if the context cannot do the operations on the given
* type. This is always the case for a context that has
* been initialized but not set up, or that has been
* cleared with mbedtls_pk_free().
*/
int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type );
/**
* \brief Verify signature (including padding if relevant).
*
* \param ctx PK context to use
* \param ctx The PK context to use. It must have been set up.
* \param md_alg Hash algorithm used (see notes)
* \param hash Hash of the message to sign
* \param hash_len Hash length or 0 (see notes)
@ -267,8 +315,8 @@ int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type );
* \param sig_len Signature length
*
* \return 0 on success (signature is valid),
* MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is
* valid but its actual length is less than sig_len,
* #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
* signature in sig but its length is less than \p siglen,
* or a specific error code.
*
* \note For RSA keys, the default padding type is PKCS#1 v1.5.
@ -284,13 +332,39 @@ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len );
/**
* \brief Restartable version of \c mbedtls_pk_verify()
*
* \note Performs the same job as \c mbedtls_pk_verify(), but can
* return early and restart according to the limit set with
* \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
* operations. For RSA, same as \c mbedtls_pk_verify().
*
* \param ctx The PK context to use. It must have been set up.
* \param md_alg Hash algorithm used (see notes)
* \param hash Hash of the message to sign
* \param hash_len Hash length or 0 (see notes)
* \param sig Signature to verify
* \param sig_len Signature length
* \param rs_ctx Restart context (NULL to disable restart)
*
* \return See \c mbedtls_pk_verify(), or
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
*/
int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
mbedtls_pk_restart_ctx *rs_ctx );
/**
* \brief Verify signature, with options.
* (Includes verification of the padding depending on type.)
*
* \param type Signature type (inc. possible padding type) to verify
* \param options Pointer to type-specific options, or NULL
* \param ctx PK context to use
* \param ctx The PK context to use. It must have been set up.
* \param md_alg Hash algorithm used (see notes)
* \param hash Hash of the message to sign
* \param hash_len Hash length or 0 (see notes)
@ -298,10 +372,10 @@ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
* \param sig_len Signature length
*
* \return 0 on success (signature is valid),
* MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
* #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
* used for this type of signatures,
* MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is
* valid but its actual length is less than sig_len,
* #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
* signature in sig but its length is less than \p siglen,
* or a specific error code.
*
* \note If hash_len is 0, then the length associated with md_alg
@ -321,7 +395,8 @@ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
/**
* \brief Make signature, including padding if relevant.
*
* \param ctx PK context to use - must hold a private key
* \param ctx The PK context to use. It must have been set up
* with a private key.
* \param md_alg Hash algorithm used (see notes)
* \param hash Hash of the message to sign
* \param hash_len Hash length or 0 (see notes)
@ -347,10 +422,41 @@ int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
/**
* \brief Restartable version of \c mbedtls_pk_sign()
*
* \note Performs the same job as \c mbedtls_pk_sign(), but can
* return early and restart according to the limit set with
* \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
* operations. For RSA, same as \c mbedtls_pk_sign().
*
* \param ctx The PK context to use. It must have been set up
* with a private key.
* \param md_alg Hash algorithm used (see notes)
* \param hash Hash of the message to sign
* \param hash_len Hash length or 0 (see notes)
* \param sig Place to write the signature
* \param sig_len Number of bytes written
* \param f_rng RNG function
* \param p_rng RNG parameter
* \param rs_ctx Restart context (NULL to disable restart)
*
* \return See \c mbedtls_pk_sign(), or
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
*/
int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_pk_restart_ctx *rs_ctx );
/**
* \brief Decrypt message (including padding if relevant).
*
* \param ctx PK context to use - must hold a private key
* \param ctx The PK context to use. It must have been set up
* with a private key.
* \param input Input to decrypt
* \param ilen Input size
* \param output Decrypted output
@ -371,7 +477,7 @@ int mbedtls_pk_decrypt( mbedtls_pk_context *ctx,
/**
* \brief Encrypt message (including padding if relevant).
*
* \param ctx PK context to use
* \param ctx The PK context to use. It must have been set up.
* \param input Message to encrypt
* \param ilen Message size
* \param output Encrypted output
@ -402,7 +508,7 @@ int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_conte
/**
* \brief Export debug information
*
* \param ctx Context to use
* \param ctx The PK context to use. It must have been initialized.
* \param items Place to write debug items
*
* \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
@ -412,7 +518,7 @@ int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *item
/**
* \brief Access the type name
*
* \param ctx Context to use
* \param ctx The PK context to use. It must have been initialized.
*
* \return Type name on success, or "invalid PK"
*/
@ -421,9 +527,10 @@ const char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx );
/**
* \brief Get the key type
*
* \param ctx Context to use
* \param ctx The PK context to use. It must have been initialized.
*
* \return Type on success, or MBEDTLS_PK_NONE
* \return Type on success.
* \return #MBEDTLS_PK_NONE for a context that has not been set up.
*/
mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );
@ -432,12 +539,22 @@ mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );
/**
* \brief Parse a private key in PEM or DER format
*
* \param ctx key to be initialized
* \param key input buffer
* \param keylen size of the buffer
* (including the terminating null byte for PEM data)
* \param pwd password for decryption (optional)
* \param pwdlen size of the password
* \param ctx The PK context to fill. It must have been initialized
* but not set up.
* \param key Input buffer to parse.
* The buffer must contain the input exactly, with no
* extra trailing material. For PEM, the buffer must
* contain a null-terminated string.
* \param keylen Size of \b key in bytes.
* For PEM data, this includes the terminating null byte,
* so \p keylen must be equal to `strlen(key) + 1`.
* \param pwd Optional password for decryption.
* Pass \c NULL if expecting a non-encrypted key.
* Pass a string of \p pwdlen bytes if expecting an encrypted
* key; a non-encrypted key will also be accepted.
* The empty password is not supported.
* \param pwdlen Size of the password in bytes.
* Ignored if \p pwd is \c NULL.
*
* \note On entry, ctx must be empty, either freshly initialised
* with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
@ -455,10 +572,15 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *ctx,
/**
* \brief Parse a public key in PEM or DER format
*
* \param ctx key to be initialized
* \param key input buffer
* \param keylen size of the buffer
* (including the terminating null byte for PEM data)
* \param ctx The PK context to fill. It must have been initialized
* but not set up.
* \param key Input buffer to parse.
* The buffer must contain the input exactly, with no
* extra trailing material. For PEM, the buffer must
* contain a null-terminated string.
* \param keylen Size of \b key in bytes.
* For PEM data, this includes the terminating null byte,
* so \p keylen must be equal to `strlen(key) + 1`.
*
* \note On entry, ctx must be empty, either freshly initialised
* with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
@ -476,9 +598,14 @@ int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,
/**
* \brief Load and parse a private key
*
* \param ctx key to be initialized
* \param ctx The PK context to fill. It must have been initialized
* but not set up.
* \param path filename to read the private key from
* \param password password to decrypt the file (can be NULL)
* \param password Optional password to decrypt the file.
* Pass \c NULL if expecting a non-encrypted key.
* Pass a null-terminated string if expecting an encrypted
* key; a non-encrypted key will also be accepted.
* The empty password is not supported.
*
* \note On entry, ctx must be empty, either freshly initialised
* with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
@ -495,7 +622,8 @@ int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
/**
* \brief Load and parse a public key
*
* \param ctx key to be initialized
* \param ctx The PK context to fill. It must have been initialized
* but not set up.
* \param path filename to read the public key from
*
* \note On entry, ctx must be empty, either freshly initialised
@ -518,7 +646,7 @@ int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path )
* return value to determine where you should start
* using the buffer
*
* \param ctx private to write away
* \param ctx PK context which must contain a valid private key.
* \param buf buffer to write to
* \param size size of the buffer
*
@ -533,7 +661,7 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *ctx, unsigned char *buf, size_
* return value to determine where you should start
* using the buffer
*
* \param ctx public key to write away
* \param ctx PK context which must contain a valid public or private key.
* \param buf buffer to write to
* \param size size of the buffer
*
@ -546,9 +674,10 @@ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *ctx, unsigned char *buf, si
/**
* \brief Write a public key to a PEM string
*
* \param ctx public key to write away
* \param buf buffer to write to
* \param size size of the buffer
* \param ctx PK context which must contain a valid public or private key.
* \param buf Buffer to write to. The output includes a
* terminating null byte.
* \param size Size of the buffer in bytes.
*
* \return 0 if successful, or a specific error code
*/
@ -557,9 +686,10 @@ int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *ctx, unsigned char *buf, si
/**
* \brief Write a private key to a PKCS#1 or SEC1 PEM string
*
* \param ctx private to write away
* \param buf buffer to write to
* \param size size of the buffer
* \param ctx PK context which must contain a valid private key.
* \param buf Buffer to write to. The output includes a
* terminating null byte.
* \param size Size of the buffer in bytes.
*
* \return 0 if successful, or a specific error code
*/
@ -578,7 +708,8 @@ int mbedtls_pk_write_key_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_
*
* \param p the position in the ASN.1 data
* \param end end of the buffer
* \param pk the key to fill
* \param pk The PK context to fill. It must have been initialized
* but not set up.
*
* \return 0 if successful, or a specific PK error code
*/
@ -593,7 +724,7 @@ int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,
*
* \param p reference to current position pointer
* \param start start of the buffer (for bounds-checking)
* \param key public key to write away
* \param key PK context which must contain a valid public or private key.
*
* \return the length written or a negative error code
*/

View File

@ -1,8 +1,9 @@
/**
* \file pk.h
* \file pk_internal.h
*
* \brief Public Key abstraction layer: wrapper functions
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -58,6 +59,21 @@ struct mbedtls_pk_info_t
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/** Verify signature (restartable) */
int (*verify_rs_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx );
/** Make signature (restartable) */
int (*sign_rs_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, void *rs_ctx );
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/** Decrypt message */
int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen, size_t osize,
@ -79,6 +95,14 @@ struct mbedtls_pk_info_t
/** Free the given context */
void (*ctx_free_func)( void *ctx );
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/** Allocate the restart context */
void * (*rs_alloc_func)( void );
/** Free the restart context */
void (*rs_free_func)( void *rs_ctx );
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/** Interface with the debug module */
void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items );

View File

@ -4,7 +4,8 @@
* \brief Wrapper for PKCS#11 library libpkcs11-helper
*
* \author Adriaan de Jong <dejong@fox-it.com>
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -49,7 +50,8 @@ extern "C" {
/**
* Context for PKCS #11 private keys.
*/
typedef struct {
typedef struct mbedtls_pkcs11_context
{
pkcs11h_certificate_t pkcs11h_cert;
int len;
} mbedtls_pkcs11_context;

View File

@ -2,7 +2,8 @@
* \file pkcs12.h
*
* \brief PKCS#12 Personal Information Exchange Syntax
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_PKCS12_H
#define MBEDTLS_PKCS12_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "md.h"
#include "cipher.h"
#include "asn1.h"
@ -45,6 +52,8 @@
extern "C" {
#endif
#if defined(MBEDTLS_ASN1_PARSE_C)
/**
* \brief PKCS12 Password Based function (encryption / decryption)
* for pbeWithSHAAnd128BitRC4
@ -86,6 +95,8 @@ int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *input, size_t len,
unsigned char *output );
#endif /* MBEDTLS_ASN1_PARSE_C */
/**
* \brief The PKCS#12 derivation function uses a password and a salt
* to produce pseudo-random bits for a particular "purpose".

View File

@ -4,7 +4,8 @@
* \brief PKCS#5 functions
*
* \author Mathias Olsson <mathias@kompetensum.com>
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -25,6 +26,12 @@
#ifndef MBEDTLS_PKCS5_H
#define MBEDTLS_PKCS5_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "asn1.h"
#include "md.h"
@ -43,6 +50,8 @@
extern "C" {
#endif
#if defined(MBEDTLS_ASN1_PARSE_C)
/**
* \brief PKCS#5 PBES2 function
*
@ -61,6 +70,8 @@ int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *data, size_t datalen,
unsigned char *output );
#endif /* MBEDTLS_ASN1_PARSE_C */
/**
* \brief PKCS#5 PBKDF2 using HMAC
*
@ -80,6 +91,8 @@ int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *p
unsigned int iteration_count,
uint32_t key_length, unsigned char *output );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
@ -87,6 +100,8 @@ int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *p
*/
int mbedtls_pkcs5_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

View File

@ -1,9 +1,19 @@
/**
* \file platform.h
*
* \brief mbed TLS Platform abstraction layer
* \brief This file contains the definitions and functions of the
* Mbed TLS platform abstraction layer.
*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* The platform abstraction layer removes the need for the library
* to directly link to standard C library functions or operating
* system services, making the library easier to port and embed.
* Application developers and users of the library can provide their own
* implementations of these functions, or implementations specific to
* their platform, which can be statically linked to the library or
* dynamically configured at runtime.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,7 +28,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_PLATFORM_H
#define MBEDTLS_PLATFORM_H
@ -30,9 +40,12 @@
#endif
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#include "platform_time.h"
#endif
#define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070 /**< Hardware accelerator failed */
#define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /**< The requested feature is not supported by the platform */
#ifdef __cplusplus
extern "C" {
#endif
@ -51,34 +64,34 @@ extern "C" {
#include <time.h>
#if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)
#if defined(_WIN32)
#define MBEDTLS_PLATFORM_STD_SNPRINTF mbedtls_platform_win32_snprintf /**< Default snprintf to use */
#define MBEDTLS_PLATFORM_STD_SNPRINTF mbedtls_platform_win32_snprintf /**< The default \c snprintf function to use. */
#else
#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use */
#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< The default \c snprintf function to use. */
#endif
#endif
#if !defined(MBEDTLS_PLATFORM_STD_PRINTF)
#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use */
#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< The default \c printf function to use. */
#endif
#if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)
#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use */
#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \c fprintf function to use. */
#endif
#if !defined(MBEDTLS_PLATFORM_STD_CALLOC)
#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default allocator to use */
#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< The default \c calloc function to use. */
#endif
#if !defined(MBEDTLS_PLATFORM_STD_FREE)
#define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use */
#define MBEDTLS_PLATFORM_STD_FREE free /**< The default \c free function to use. */
#endif
#if !defined(MBEDTLS_PLATFORM_STD_EXIT)
#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use */
#define MBEDTLS_PLATFORM_STD_EXIT exit /**< The default \c exit function to use. */
#endif
#if !defined(MBEDTLS_PLATFORM_STD_TIME)
#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use */
#define MBEDTLS_PLATFORM_STD_TIME time /**< The default \c time function to use. */
#endif
#if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)
#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS EXIT_SUCCESS /**< Default exit value to use */
#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS EXIT_SUCCESS /**< The default exit value to use. */
#endif
#if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)
#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE EXIT_FAILURE /**< Default exit value to use */
#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE EXIT_FAILURE /**< The default exit value to use. */
#endif
#if defined(MBEDTLS_FS_IO)
#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)
@ -101,7 +114,7 @@ extern "C" {
/* \} name SECTION: Module settings */
/*
* The function pointers for calloc and free
* The function pointers for calloc and free.
*/
#if defined(MBEDTLS_PLATFORM_MEMORY)
#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \
@ -111,16 +124,17 @@ extern "C" {
#else
/* For size_t */
#include <stddef.h>
extern void * (*mbedtls_calloc)( size_t n, size_t size );
extern void (*mbedtls_free)( void *ptr );
extern void *mbedtls_calloc( size_t n, size_t size );
extern void mbedtls_free( void *ptr );
/**
* \brief Set your own memory implementation function pointers
* \brief This function dynamically sets the memory-management
* functions used by the library, during runtime.
*
* \param calloc_func the calloc function implementation
* \param free_func the free function implementation
* \param calloc_func The \c calloc function implementation.
* \param free_func The \c free function implementation.
*
* \return 0 if successful
* \return \c 0.
*/
int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
void (*free_func)( void * ) );
@ -139,11 +153,13 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
extern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... );
/**
* \brief Set your own fprintf function pointer
* \brief This function dynamically configures the fprintf
* function that is called when the
* mbedtls_fprintf() function is invoked by the library.
*
* \param fprintf_func the fprintf function implementation
* \param fprintf_func The \c fprintf function implementation.
*
* \return 0
* \return \c 0.
*/
int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *,
... ) );
@ -162,11 +178,13 @@ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char
extern int (*mbedtls_printf)( const char *format, ... );
/**
* \brief Set your own printf function pointer
* \brief This function dynamically configures the snprintf
* function that is called when the mbedtls_snprintf()
* function is invoked by the library.
*
* \param printf_func the printf function implementation
* \param printf_func The \c printf function implementation.
*
* \return 0
* \return \c 0 on success.
*/
int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) );
#else /* !MBEDTLS_PLATFORM_PRINTF_ALT */
@ -195,11 +213,12 @@ int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... );
extern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... );
/**
* \brief Set your own snprintf function pointer
* \brief This function allows configuring a custom
* \c snprintf function pointer.
*
* \param snprintf_func the snprintf function implementation
* \param snprintf_func The \c snprintf function implementation.
*
* \return 0
* \return \c 0 on success.
*/
int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
const char * format, ... ) );
@ -207,7 +226,7 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)
#define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO
#else
#define mbedtls_snprintf snprintf
#define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF
#endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */
#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
@ -218,11 +237,13 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
extern void (*mbedtls_exit)( int status );
/**
* \brief Set your own exit function pointer
* \brief This function dynamically configures the exit
* function that is called when the mbedtls_exit()
* function is invoked by the library.
*
* \param exit_func the exit function implementation
* \param exit_func The \c exit function implementation.
*
* \return 0
* \return \c 0 on success.
*/
int mbedtls_platform_set_exit( void (*exit_func)( int status ) );
#else
@ -265,12 +286,13 @@ extern int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len );
extern int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len );
/**
* \brief Set your own seed file writing/reading functions
* \brief This function allows configuring custom seed file writing and
* reading functions.
*
* \param nv_seed_read_func the seed reading function implementation
* \param nv_seed_write_func the seed writing function implementation
* \param nv_seed_read_func The seed reading function implementation.
* \param nv_seed_write_func The seed writing function implementation.
*
* \return 0
* \return \c 0 on success.
*/
int mbedtls_platform_set_nv_seed(
int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),
@ -288,6 +310,56 @@ int mbedtls_platform_set_nv_seed(
#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
#endif /* MBEDTLS_ENTROPY_NV_SEED */
#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
/**
* \brief The platform context structure.
*
* \note This structure may be used to assist platform-specific
* setup or teardown operations.
*/
typedef struct mbedtls_platform_context
{
char dummy; /**< A placeholder member, as empty structs are not portable. */
}
mbedtls_platform_context;
#else
#include "platform_alt.h"
#endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
/**
* \brief This function performs any platform-specific initialization
* operations.
*
* \note This function should be called before any other library functions.
*
* Its implementation is platform-specific, and unless
* platform-specific code is provided, it does nothing.
*
* \note The usage and necessity of this function is dependent on the platform.
*
* \param ctx The platform context.
*
* \return \c 0 on success.
*/
int mbedtls_platform_setup( mbedtls_platform_context *ctx );
/**
* \brief This function performs any platform teardown operations.
*
* \note This function should be called after every other Mbed TLS module
* has been correctly freed using the appropriate free function.
*
* Its implementation is platform-specific, and unless
* platform-specific code is provided, it does nothing.
*
* \note The usage and necessity of this function is dependent on the platform.
*
* \param ctx The platform context.
*
*/
void mbedtls_platform_teardown( mbedtls_platform_context *ctx );
#ifdef __cplusplus
}
#endif

View File

@ -2,7 +2,8 @@
* \file platform_time.h
*
* \brief mbed TLS Platform time abstraction
*
*/
/*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*

View File

@ -0,0 +1,185 @@
/**
* \file platform_util.h
*
* \brief Common and shared functions used by multiple modules in the Mbed TLS
* library.
*/
/*
* Copyright (C) 2018, Arm Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_PLATFORM_UTIL_H
#define MBEDTLS_PLATFORM_UTIL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#if defined(MBEDTLS_HAVE_TIME_DATE)
#include "platform_time.h"
#include <time.h>
#endif /* MBEDTLS_HAVE_TIME_DATE */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_CHECK_PARAMS)
#if defined(MBEDTLS_PARAM_FAILED)
/** An alternative definition of MBEDTLS_PARAM_FAILED has been set in config.h.
*
* This flag can be used to check whether it is safe to assume that
* MBEDTLS_PARAM_FAILED() will expand to a call to mbedtls_param_failed().
*/
#define MBEDTLS_PARAM_FAILED_ALT
#else /* MBEDTLS_PARAM_FAILED */
#define MBEDTLS_PARAM_FAILED( cond ) \
mbedtls_param_failed( #cond, __FILE__, __LINE__ )
/**
* \brief User supplied callback function for parameter validation failure.
* See #MBEDTLS_CHECK_PARAMS for context.
*
* This function will be called unless an alternative treatement
* is defined through the #MBEDTLS_PARAM_FAILED macro.
*
* This function can return, and the operation will be aborted, or
* alternatively, through use of setjmp()/longjmp() can resume
* execution in the application code.
*
* \param failure_condition The assertion that didn't hold.
* \param file The file where the assertion failed.
* \param line The line in the file where the assertion failed.
*/
void mbedtls_param_failed( const char *failure_condition,
const char *file,
int line );
#endif /* MBEDTLS_PARAM_FAILED */
/* Internal macro meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) \
do { \
if( !(cond) ) \
{ \
MBEDTLS_PARAM_FAILED( cond ); \
return( ret ); \
} \
} while( 0 )
/* Internal macro meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE( cond ) \
do { \
if( !(cond) ) \
{ \
MBEDTLS_PARAM_FAILED( cond ); \
return; \
} \
} while( 0 )
#else /* MBEDTLS_CHECK_PARAMS */
/* Internal macros meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) do { } while( 0 )
#define MBEDTLS_INTERNAL_VALIDATE( cond ) do { } while( 0 )
#endif /* MBEDTLS_CHECK_PARAMS */
/* Internal helper macros for deprecating API constants. */
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
/* Deliberately don't (yet) export MBEDTLS_DEPRECATED here
* to avoid conflict with other headers which define and use
* it, too. We might want to move all these definitions here at
* some point for uniformity. */
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
MBEDTLS_DEPRECATED typedef char const * mbedtls_deprecated_string_constant_t;
#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) \
( (mbedtls_deprecated_string_constant_t) ( VAL ) )
MBEDTLS_DEPRECATED typedef int mbedtls_deprecated_numeric_constant_t;
#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( VAL ) \
( (mbedtls_deprecated_numeric_constant_t) ( VAL ) )
#undef MBEDTLS_DEPRECATED
#else /* MBEDTLS_DEPRECATED_WARNING */
#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) VAL
#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( VAL ) VAL
#endif /* MBEDTLS_DEPRECATED_WARNING */
#endif /* MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Securely zeroize a buffer
*
* The function is meant to wipe the data contained in a buffer so
* that it can no longer be recovered even if the program memory
* is later compromised. Call this function on sensitive data
* stored on the stack before returning from a function, and on
* sensitive data stored on the heap before freeing the heap
* object.
*
* It is extremely difficult to guarantee that calls to
* mbedtls_platform_zeroize() are not removed by aggressive
* compiler optimizations in a portable way. For this reason, Mbed
* TLS provides the configuration option
* MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure
* mbedtls_platform_zeroize() to use a suitable implementation for
* their platform and needs
*
* \param buf Buffer to be zeroized
* \param len Length of the buffer in bytes
*
*/
void mbedtls_platform_zeroize( void *buf, size_t len );
#if defined(MBEDTLS_HAVE_TIME_DATE)
/**
* \brief Platform-specific implementation of gmtime_r()
*
* The function is a thread-safe abstraction that behaves
* similarly to the gmtime_r() function from Unix/POSIX.
*
* Mbed TLS will try to identify the underlying platform and
* make use of an appropriate underlying implementation (e.g.
* gmtime_r() for POSIX and gmtime_s() for Windows). If this is
* not possible, then gmtime() will be used. In this case, calls
* from the library to gmtime() will be guarded by the mutex
* mbedtls_threading_gmtime_mutex if MBEDTLS_THREADING_C is
* enabled. It is recommended that calls from outside the library
* are also guarded by this mutex.
*
* If MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, then Mbed TLS will
* unconditionally use the alternative implementation for
* mbedtls_platform_gmtime_r() supplied by the user at compile time.
*
* \param tt Pointer to an object containing time (in seconds) since the
* epoch to be converted
* \param tm_buf Pointer to an object where the results will be stored
*
* \return Pointer to an object of type struct tm on success, otherwise
* NULL
*/
struct tm *mbedtls_platform_gmtime_r( const mbedtls_time_t *tt,
struct tm *tm_buf );
#endif /* MBEDTLS_HAVE_TIME_DATE */
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_PLATFORM_UTIL_H */

View File

@ -0,0 +1,192 @@
/**
* \file poly1305.h
*
* \brief This file contains Poly1305 definitions and functions.
*
* Poly1305 is a one-time message authenticator that can be used to
* authenticate messages. Poly1305-AES was created by Daniel
* Bernstein https://cr.yp.to/mac/poly1305-20050329.pdf The generic
* Poly1305 algorithm (not tied to AES) was also standardized in RFC
* 7539.
*
* \author Daniel King <damaki.gh@gmail.com>
*/
/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_POLY1305_H
#define MBEDTLS_POLY1305_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stdint.h>
#include <stddef.h>
#define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA -0x0057 /**< Invalid input parameter(s). */
/* MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE is deprecated and should not be
* used. */
#define MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE -0x0059 /**< Feature not available. For example, s part of the API is not implemented. */
/* MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED is deprecated and should not be used.
*/
#define MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED -0x005B /**< Poly1305 hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_POLY1305_ALT)
typedef struct mbedtls_poly1305_context
{
uint32_t r[4]; /** The value for 'r' (low 128 bits of the key). */
uint32_t s[4]; /** The value for 's' (high 128 bits of the key). */
uint32_t acc[5]; /** The accumulator number. */
uint8_t queue[16]; /** The current partial block of data. */
size_t queue_len; /** The number of bytes stored in 'queue'. */
}
mbedtls_poly1305_context;
#else /* MBEDTLS_POLY1305_ALT */
#include "poly1305_alt.h"
#endif /* MBEDTLS_POLY1305_ALT */
/**
* \brief This function initializes the specified Poly1305 context.
*
* It must be the first API called before using
* the context.
*
* It is usually followed by a call to
* \c mbedtls_poly1305_starts(), then one or more calls to
* \c mbedtls_poly1305_update(), then one call to
* \c mbedtls_poly1305_finish(), then finally
* \c mbedtls_poly1305_free().
*
* \param ctx The Poly1305 context to initialize. This must
* not be \c NULL.
*/
void mbedtls_poly1305_init( mbedtls_poly1305_context *ctx );
/**
* \brief This function releases and clears the specified
* Poly1305 context.
*
* \param ctx The Poly1305 context to clear. This may be \c NULL, in which
* case this function is a no-op. If it is not \c NULL, it must
* point to an initialized Poly1305 context.
*/
void mbedtls_poly1305_free( mbedtls_poly1305_context *ctx );
/**
* \brief This function sets the one-time authentication key.
*
* \warning The key must be unique and unpredictable for each
* invocation of Poly1305.
*
* \param ctx The Poly1305 context to which the key should be bound.
* This must be initialized.
* \param key The buffer containing the \c 32 Byte (\c 256 Bit) key.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx,
const unsigned char key[32] );
/**
* \brief This functions feeds an input buffer into an ongoing
* Poly1305 computation.
*
* It is called between \c mbedtls_cipher_poly1305_starts() and
* \c mbedtls_cipher_poly1305_finish().
* It can be called repeatedly to process a stream of data.
*
* \param ctx The Poly1305 context to use for the Poly1305 operation.
* This must be initialized and bound to a key.
* \param ilen The length of the input data in Bytes.
* Any value is accepted.
* \param input The buffer holding the input data.
* This pointer can be \c NULL if `ilen == 0`.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_poly1305_update( mbedtls_poly1305_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function generates the Poly1305 Message
* Authentication Code (MAC).
*
* \param ctx The Poly1305 context to use for the Poly1305 operation.
* This must be initialized and bound to a key.
* \param mac The buffer to where the MAC is written. This must
* be a writable buffer of length \c 16 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx,
unsigned char mac[16] );
/**
* \brief This function calculates the Poly1305 MAC of the input
* buffer with the provided key.
*
* \warning The key must be unique and unpredictable for each
* invocation of Poly1305.
*
* \param key The buffer containing the \c 32 Byte (\c 256 Bit) key.
* \param ilen The length of the input data in Bytes.
* Any value is accepted.
* \param input The buffer holding the input data.
* This pointer can be \c NULL if `ilen == 0`.
* \param mac The buffer to where the MAC is written. This must be
* a writable buffer of length \c 16 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_poly1305_mac( const unsigned char key[32],
const unsigned char *input,
size_t ilen,
unsigned char mac[16] );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief The Poly1305 checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_poly1305_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_POLY1305_H */

View File

@ -2,7 +2,8 @@
* \file ripemd160.h
*
* \brief RIPE MD-160 message digest
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -32,18 +33,22 @@
#include <stddef.h>
#include <stdint.h>
#if !defined(MBEDTLS_RIPEMD160_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED is deprecated and should not be used.
*/
#define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED -0x0031 /**< RIPEMD160 hardware accelerator failed */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_RIPEMD160_ALT)
// Regular implementation
//
/**
* \brief RIPEMD-160 context structure
*/
typedef struct
typedef struct mbedtls_ripemd160_context
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[5]; /*!< intermediate digest state */
@ -51,6 +56,10 @@ typedef struct
}
mbedtls_ripemd160_context;
#else /* MBEDTLS_RIPEMD160_ALT */
#include "ripemd160.h"
#endif /* MBEDTLS_RIPEMD160_ALT */
/**
* \brief Initialize RIPEMD-160 context
*
@ -78,51 +87,139 @@ void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst,
* \brief RIPEMD-160 context setup
*
* \param ctx context to be initialized
*
* \return 0 if successful
*/
void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx );
int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx );
/**
* \brief RIPEMD-160 process buffer
*
* \param ctx RIPEMD-160 context
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
*
* \return 0 if successful
*/
void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx,
const unsigned char *input, size_t ilen );
int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief RIPEMD-160 final digest
*
* \param ctx RIPEMD-160 context
* \param output RIPEMD-160 checksum result
*
* \return 0 if successful
*/
void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx, unsigned char output[20] );
int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx,
unsigned char output[20] );
/* Internal use */
void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] );
/**
* \brief RIPEMD-160 process data block (internal use only)
*
* \param ctx RIPEMD-160 context
* \param data buffer holding one block of data
*
* \return 0 if successful
*/
int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
const unsigned char data[64] );
#ifdef __cplusplus
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief RIPEMD-160 context setup
*
* \deprecated Superseded by mbedtls_ripemd160_starts_ret() in 2.7.0
*
* \param ctx context to be initialized
*/
MBEDTLS_DEPRECATED void mbedtls_ripemd160_starts(
mbedtls_ripemd160_context *ctx );
#else /* MBEDTLS_RIPEMD160_ALT */
#include "ripemd160.h"
#endif /* MBEDTLS_RIPEMD160_ALT */
/**
* \brief RIPEMD-160 process buffer
*
* \deprecated Superseded by mbedtls_ripemd160_update_ret() in 2.7.0
*
* \param ctx RIPEMD-160 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
MBEDTLS_DEPRECATED void mbedtls_ripemd160_update(
mbedtls_ripemd160_context *ctx,
const unsigned char *input,
size_t ilen );
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief RIPEMD-160 final digest
*
* \deprecated Superseded by mbedtls_ripemd160_finish_ret() in 2.7.0
*
* \param ctx RIPEMD-160 context
* \param output RIPEMD-160 checksum result
*/
MBEDTLS_DEPRECATED void mbedtls_ripemd160_finish(
mbedtls_ripemd160_context *ctx,
unsigned char output[20] );
/**
* \brief RIPEMD-160 process data block (internal use only)
*
* \deprecated Superseded by mbedtls_internal_ripemd160_process() in 2.7.0
*
* \param ctx RIPEMD-160 context
* \param data buffer holding one block of data
*/
MBEDTLS_DEPRECATED void mbedtls_ripemd160_process(
mbedtls_ripemd160_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Output = RIPEMD-160( input buffer )
*
* \param input buffer holding the data
* \param input buffer holding the data
* \param ilen length of the input data
* \param output RIPEMD-160 checksum result
*
* \return 0 if successful
*/
int mbedtls_ripemd160_ret( const unsigned char *input,
size_t ilen,
unsigned char output[20] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = RIPEMD-160( input buffer )
*
* \deprecated Superseded by mbedtls_ripemd160_ret() in 2.7.0
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output RIPEMD-160 checksum result
*/
void mbedtls_ripemd160( const unsigned char *input, size_t ilen,
unsigned char output[20] );
MBEDTLS_DEPRECATED void mbedtls_ripemd160( const unsigned char *input,
size_t ilen,
unsigned char output[20] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
@ -131,6 +228,8 @@ void mbedtls_ripemd160( const unsigned char *input, size_t ilen,
*/
int mbedtls_ripemd160_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,226 @@
/**
* \file rsa_internal.h
*
* \brief Context-independent RSA helper functions
*
* This module declares some RSA-related helper functions useful when
* implementing the RSA interface. These functions are provided in a separate
* compilation unit in order to make it easy for designers of alternative RSA
* implementations to use them in their own code, as it is conceived that the
* functionality they provide will be necessary for most complete
* implementations.
*
* End-users of Mbed TLS who are not providing their own alternative RSA
* implementations should not use these functions directly, and should instead
* use only the functions declared in rsa.h.
*
* The interface provided by this module will be maintained through LTS (Long
* Term Support) branches of Mbed TLS, but may otherwise be subject to change,
* and must be considered an internal interface of the library.
*
* There are two classes of helper functions:
*
* (1) Parameter-generating helpers. These are:
* - mbedtls_rsa_deduce_primes
* - mbedtls_rsa_deduce_private_exponent
* - mbedtls_rsa_deduce_crt
* Each of these functions takes a set of core RSA parameters and
* generates some other, or CRT related parameters.
*
* (2) Parameter-checking helpers. These are:
* - mbedtls_rsa_validate_params
* - mbedtls_rsa_validate_crt
* They take a set of core or CRT related RSA parameters and check their
* validity.
*
*/
/*
* Copyright (C) 2006-2017, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
*/
#ifndef MBEDTLS_RSA_INTERNAL_H
#define MBEDTLS_RSA_INTERNAL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "bignum.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Compute RSA prime moduli P, Q from public modulus N=PQ
* and a pair of private and public key.
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param N RSA modulus N = PQ, with P, Q to be found
* \param E RSA public exponent
* \param D RSA private exponent
* \param P Pointer to MPI holding first prime factor of N on success
* \param Q Pointer to MPI holding second prime factor of N on success
*
* \return
* - 0 if successful. In this case, P and Q constitute a
* factorization of N.
* - A non-zero error code otherwise.
*
* \note It is neither checked that P, Q are prime nor that
* D, E are modular inverses wrt. P-1 and Q-1. For that,
* use the helper function \c mbedtls_rsa_validate_params.
*
*/
int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E,
mbedtls_mpi const *D,
mbedtls_mpi *P, mbedtls_mpi *Q );
/**
* \brief Compute RSA private exponent from
* prime moduli and public key.
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param P First prime factor of RSA modulus
* \param Q Second prime factor of RSA modulus
* \param E RSA public exponent
* \param D Pointer to MPI holding the private exponent on success.
*
* \return
* - 0 if successful. In this case, D is set to a simultaneous
* modular inverse of E modulo both P-1 and Q-1.
* - A non-zero error code otherwise.
*
* \note This function does not check whether P and Q are primes.
*
*/
int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,
mbedtls_mpi const *Q,
mbedtls_mpi const *E,
mbedtls_mpi *D );
/**
* \brief Generate RSA-CRT parameters
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param P First prime factor of N
* \param Q Second prime factor of N
* \param D RSA private exponent
* \param DP Output variable for D modulo P-1
* \param DQ Output variable for D modulo Q-1
* \param QP Output variable for the modular inverse of Q modulo P.
*
* \return 0 on success, non-zero error code otherwise.
*
* \note This function does not check whether P, Q are
* prime and whether D is a valid private exponent.
*
*/
int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, mbedtls_mpi *DP,
mbedtls_mpi *DQ, mbedtls_mpi *QP );
/**
* \brief Check validity of core RSA parameters
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param N RSA modulus N = PQ
* \param P First prime factor of N
* \param Q Second prime factor of N
* \param D RSA private exponent
* \param E RSA public exponent
* \param f_rng PRNG to be used for primality check, or NULL
* \param p_rng PRNG context for f_rng, or NULL
*
* \return
* - 0 if the following conditions are satisfied
* if all relevant parameters are provided:
* - P prime if f_rng != NULL (%)
* - Q prime if f_rng != NULL (%)
* - 1 < N = P * Q
* - 1 < D, E < N
* - D and E are modular inverses modulo P-1 and Q-1
* (%) This is only done if MBEDTLS_GENPRIME is defined.
* - A non-zero error code otherwise.
*
* \note The function can be used with a restricted set of arguments
* to perform specific checks only. E.g., calling it with
* (-,P,-,-,-) and a PRNG amounts to a primality check for P.
*/
int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
const mbedtls_mpi *Q, const mbedtls_mpi *D,
const mbedtls_mpi *E,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief Check validity of RSA CRT parameters
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param P First prime factor of RSA modulus
* \param Q Second prime factor of RSA modulus
* \param D RSA private exponent
* \param DP MPI to check for D modulo P-1
* \param DQ MPI to check for D modulo P-1
* \param QP MPI to check for the modular inverse of Q modulo P.
*
* \return
* - 0 if the following conditions are satisfied:
* - D = DP mod P-1 if P, D, DP != NULL
* - Q = DQ mod P-1 if P, D, DQ != NULL
* - QP = Q^-1 mod P if P, Q, QP != NULL
* - \c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed,
* potentially including \c MBEDTLS_ERR_MPI_XXX if some
* MPI calculations failed.
* - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient
* data was provided to check DP, DQ or QP.
*
* \note The function can be used with a restricted set of arguments
* to perform specific checks only. E.g., calling it with the
* parameters (P, -, D, DP, -, -) will check DP = D mod P-1.
*/
int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *DP,
const mbedtls_mpi *DQ, const mbedtls_mpi *QP );
#ifdef __cplusplus
}
#endif
#endif /* rsa_internal.h */

View File

@ -1,9 +1,17 @@
/**
* \file sha1.h
*
* \brief SHA-1 cryptographic hash function
* \brief This file contains SHA-1 definitions and functions.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in
* <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. We recommend considering stronger message
* digests instead.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,7 +26,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_SHA1_H
#define MBEDTLS_SHA1_H
@ -32,103 +40,311 @@
#include <stddef.h>
#include <stdint.h>
#if !defined(MBEDTLS_SHA1_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED -0x0035 /**< SHA-1 hardware accelerator failed */
#define MBEDTLS_ERR_SHA1_BAD_INPUT_DATA -0x0073 /**< SHA-1 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA1_ALT)
// Regular implementation
//
/**
* \brief SHA-1 context structure
* \brief The SHA-1 context structure.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct
typedef struct mbedtls_sha1_context
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[5]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[5]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
}
mbedtls_sha1_context;
/**
* \brief Initialize SHA-1 context
*
* \param ctx SHA-1 context to be initialized
*/
void mbedtls_sha1_init( mbedtls_sha1_context *ctx );
/**
* \brief Clear SHA-1 context
*
* \param ctx SHA-1 context to be cleared
*/
void mbedtls_sha1_free( mbedtls_sha1_context *ctx );
/**
* \brief Clone (the state of) a SHA-1 context
*
* \param dst The destination context
* \param src The context to be cloned
*/
void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src );
/**
* \brief SHA-1 context setup
*
* \param ctx context to be initialized
*/
void mbedtls_sha1_starts( mbedtls_sha1_context *ctx );
/**
* \brief SHA-1 process buffer
*
* \param ctx SHA-1 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen );
/**
* \brief SHA-1 final digest
*
* \param ctx SHA-1 context
* \param output SHA-1 checksum result
*/
void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] );
/* Internal use */
void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_SHA1_ALT */
#include "sha1_alt.h"
#endif /* MBEDTLS_SHA1_ALT */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Output = SHA-1( input buffer )
* \brief This function initializes a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize.
* This must not be \c NULL.
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-1 checksum result
*/
void mbedtls_sha1( const unsigned char *input, size_t ilen, unsigned char output[20] );
void mbedtls_sha1_init( mbedtls_sha1_context *ctx );
/**
* \brief Checkup routine
* \brief This function clears a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to clear. This may be \c NULL,
* in which case this function does nothing. If it is
* not \c NULL, it must point to an initialized
* SHA-1 context.
*
*/
void mbedtls_sha1_free( mbedtls_sha1_context *ctx );
/**
* \brief This function clones the state of a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param dst The SHA-1 context to clone to. This must be initialized.
* \param src The SHA-1 context to clone from. This must be initialized.
*
*/
void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src );
/**
* \brief This function starts a SHA-1 checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize. This must be initialized.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx );
/**
* \brief This function feeds an input buffer into an ongoing SHA-1
* checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-1 operation, and writes
* the result to the output buffer.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to use. This must be initialized and
* have a hash operation started.
* \param output The SHA-1 checksum result. This must be a writable
* buffer of length \c 20 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
unsigned char output[20] );
/**
* \brief SHA-1 process data block (internal use only).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to use. This must be initialized.
* \param data The data block being processed. This must be a
* readable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-1 checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_starts_ret() in 2.7.0.
*
* \param ctx The SHA-1 context to initialize. This must be initialized.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_starts( mbedtls_sha1_context *ctx );
/**
* \brief This function feeds an input buffer into an ongoing SHA-1
* checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_update_ret() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized and
* have a hash operation started.
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_update( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-1 operation, and writes
* the result to the output buffer.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_finish_ret() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized and
* have a hash operation started.
* \param output The SHA-1 checksum result.
* This must be a writable buffer of length \c 20 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,
unsigned char output[20] );
/**
* \brief SHA-1 process data block (internal use only).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_internal_sha1_process() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized.
* \param data The data block being processed.
* This must be a readable buffer of length \c 64 bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief This function calculates the SHA-1 checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-1 result is calculated as
* output = SHA-1(input buffer).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
* \param output The SHA-1 checksum result.
* This must be a writable buffer of length \c 20 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_sha1_ret( const unsigned char *input,
size_t ilen,
unsigned char output[20] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function calculates the SHA-1 checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-1 result is calculated as
* output = SHA-1(input buffer).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_ret() in 2.7.0
*
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
* \param output The SHA-1 checksum result. This must be a writable
* buffer of size \c 20 Bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input,
size_t ilen,
unsigned char output[20] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief The SHA-1 checkup routine.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*
* \return 0 if successful, or 1 if the test failed
*/
int mbedtls_sha1_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

View File

@ -1,9 +1,13 @@
/**
* \file sha256.h
*
* \brief SHA-224 and SHA-256 cryptographic hash function
* \brief This file contains SHA-224 and SHA-256 definitions and functions.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic
* hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,7 +22,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_SHA256_H
#define MBEDTLS_SHA256_H
@ -32,108 +36,260 @@
#include <stddef.h>
#include <stdint.h>
#if !defined(MBEDTLS_SHA256_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /**< SHA-256 hardware accelerator failed */
#define MBEDTLS_ERR_SHA256_BAD_INPUT_DATA -0x0074 /**< SHA-256 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA256_ALT)
// Regular implementation
//
/**
* \brief SHA-256 context structure
* \brief The SHA-256 context structure.
*
* The structure is used both for SHA-256 and for SHA-224
* checksum calculations. The choice between these two is
* made in the call to mbedtls_sha256_starts_ret().
*/
typedef struct
typedef struct mbedtls_sha256_context
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[8]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
int is224; /*!< 0 => SHA-256, else SHA-224 */
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[8]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
int is224; /*!< Determines which function to use:
0: Use SHA-256, or 1: Use SHA-224. */
}
mbedtls_sha256_context;
/**
* \brief Initialize SHA-256 context
*
* \param ctx SHA-256 context to be initialized
*/
void mbedtls_sha256_init( mbedtls_sha256_context *ctx );
/**
* \brief Clear SHA-256 context
*
* \param ctx SHA-256 context to be cleared
*/
void mbedtls_sha256_free( mbedtls_sha256_context *ctx );
/**
* \brief Clone (the state of) a SHA-256 context
*
* \param dst The destination context
* \param src The context to be cloned
*/
void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src );
/**
* \brief SHA-256 context setup
*
* \param ctx context to be initialized
* \param is224 0 = use SHA256, 1 = use SHA224
*/
void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 );
/**
* \brief SHA-256 process buffer
*
* \param ctx SHA-256 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input,
size_t ilen );
/**
* \brief SHA-256 final digest
*
* \param ctx SHA-256 context
* \param output SHA-224/256 checksum result
*/
void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] );
/* Internal use */
void mbedtls_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_SHA256_ALT */
#include "sha256_alt.h"
#endif /* MBEDTLS_SHA256_ALT */
#ifdef __cplusplus
extern "C" {
/**
* \brief This function initializes a SHA-256 context.
*
* \param ctx The SHA-256 context to initialize. This must not be \c NULL.
*/
void mbedtls_sha256_init( mbedtls_sha256_context *ctx );
/**
* \brief This function clears a SHA-256 context.
*
* \param ctx The SHA-256 context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized SHA-256 context.
*/
void mbedtls_sha256_free( mbedtls_sha256_context *ctx );
/**
* \brief This function clones the state of a SHA-256 context.
*
* \param dst The destination context. This must be initialized.
* \param src The context to clone. This must be initialized.
*/
void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src );
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \param ctx The context to use. This must be initialized.
* \param is224 This determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result.
* This must be a writable buffer of length \c 32 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
unsigned char output[32] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must
* be a readable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \deprecated Superseded by mbedtls_sha256_starts_ret() in 2.7.0.
*
* \param ctx The context to use. This must be initialized.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
int is224 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \deprecated Superseded by mbedtls_sha256_update_ret() in 2.7.0.
*
* \param ctx The SHA-256 context to use. This must be
* initialized and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_update( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \deprecated Superseded by mbedtls_sha256_finish_ret() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized and
* have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
unsigned char output[32] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \deprecated Superseded by mbedtls_internal_sha256_process() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must be
* a readable buffer of size \c 64 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief This function calculates the SHA-224 or SHA-256
* checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must
* be a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
int mbedtls_sha256_ret( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = SHA-256( input buffer )
* \brief This function calculates the SHA-224 or SHA-256 checksum
* of a buffer.
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-224/256 checksum result
* \param is224 0 = use SHA256, 1 = use SHA224
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \deprecated Superseded by mbedtls_sha256_ret() in 2.7.0.
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be either
* \c 0 for SHA-256, or \c 1 for SHA-224.
*/
void mbedtls_sha256( const unsigned char *input, size_t ilen,
unsigned char output[32], int is224 );
MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
* \brief The SHA-224 and SHA-256 checkup routine.
*
* \return 0 if successful, or 1 if the test failed
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_sha256_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

View File

@ -1,9 +1,12 @@
/**
* \file sha512.h
* \brief This file contains SHA-384 and SHA-512 definitions and functions.
*
* \brief SHA-384 and SHA-512 cryptographic hash function
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic
* hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -18,7 +21,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_SHA512_H
#define MBEDTLS_SHA512_H
@ -32,107 +35,263 @@
#include <stddef.h>
#include <stdint.h>
#if !defined(MBEDTLS_SHA512_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED -0x0039 /**< SHA-512 hardware accelerator failed */
#define MBEDTLS_ERR_SHA512_BAD_INPUT_DATA -0x0075 /**< SHA-512 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA512_ALT)
// Regular implementation
//
/**
* \brief SHA-512 context structure
* \brief The SHA-512 context structure.
*
* The structure is used both for SHA-384 and for SHA-512
* checksum calculations. The choice between these two is
* made in the call to mbedtls_sha512_starts_ret().
*/
typedef struct
typedef struct mbedtls_sha512_context
{
uint64_t total[2]; /*!< number of bytes processed */
uint64_t state[8]; /*!< intermediate digest state */
unsigned char buffer[128]; /*!< data block being processed */
int is384; /*!< 0 => SHA-512, else SHA-384 */
uint64_t total[2]; /*!< The number of Bytes processed. */
uint64_t state[8]; /*!< The intermediate digest state. */
unsigned char buffer[128]; /*!< The data block being processed. */
int is384; /*!< Determines which function to use:
0: Use SHA-512, or 1: Use SHA-384. */
}
mbedtls_sha512_context;
/**
* \brief Initialize SHA-512 context
*
* \param ctx SHA-512 context to be initialized
*/
void mbedtls_sha512_init( mbedtls_sha512_context *ctx );
/**
* \brief Clear SHA-512 context
*
* \param ctx SHA-512 context to be cleared
*/
void mbedtls_sha512_free( mbedtls_sha512_context *ctx );
/**
* \brief Clone (the state of) a SHA-512 context
*
* \param dst The destination context
* \param src The context to be cloned
*/
void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
const mbedtls_sha512_context *src );
/**
* \brief SHA-512 context setup
*
* \param ctx context to be initialized
* \param is384 0 = use SHA512, 1 = use SHA384
*/
void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 );
/**
* \brief SHA-512 process buffer
*
* \param ctx SHA-512 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void mbedtls_sha512_update( mbedtls_sha512_context *ctx, const unsigned char *input,
size_t ilen );
/**
* \brief SHA-512 final digest
*
* \param ctx SHA-512 context
* \param output SHA-384/512 checksum result
*/
void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, unsigned char output[64] );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_SHA512_ALT */
#include "sha512_alt.h"
#endif /* MBEDTLS_SHA512_ALT */
#ifdef __cplusplus
extern "C" {
/**
* \brief This function initializes a SHA-512 context.
*
* \param ctx The SHA-512 context to initialize. This must
* not be \c NULL.
*/
void mbedtls_sha512_init( mbedtls_sha512_context *ctx );
/**
* \brief This function clears a SHA-512 context.
*
* \param ctx The SHA-512 context to clear. This may be \c NULL,
* in which case this function does nothing. If it
* is not \c NULL, it must point to an initialized
* SHA-512 context.
*/
void mbedtls_sha512_free( mbedtls_sha512_context *ctx );
/**
* \brief This function clones the state of a SHA-512 context.
*
* \param dst The destination context. This must be initialized.
* \param src The context to clone. This must be initialized.
*/
void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
const mbedtls_sha512_context *src );
/**
* \brief This function starts a SHA-384 or SHA-512 checksum
* calculation.
*
* \param ctx The SHA-512 context to use. This must be initialized.
* \param is384 Determines which function to use. This must be
* either \c for SHA-512, or \c 1 for SHA-384.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-512 checksum calculation.
*
* \param ctx The SHA-512 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the input data. This must
* be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-512 operation, and writes
* the result to the output buffer. This function is for
* internal use only.
*
* \param ctx The SHA-512 context. This must be initialized
* and have a hash operation started.
* \param output The SHA-384 or SHA-512 checksum result.
* This must be a writable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
unsigned char output[64] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-512 computation.
*
* \param ctx The SHA-512 context. This must be initialized.
* \param data The buffer holding one block of data. This
* must be a readable buffer of length \c 128 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
const unsigned char data[128] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-384 or SHA-512 checksum
* calculation.
*
* \deprecated Superseded by mbedtls_sha512_starts_ret() in 2.7.0
*
* \param ctx The SHA-512 context to use. This must be initialized.
* \param is384 Determines which function to use. This must be either
* \c 0 for SHA-512 or \c 1 for SHA-384.
*/
MBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx,
int is384 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-512 checksum calculation.
*
* \deprecated Superseded by mbedtls_sha512_update_ret() in 2.7.0.
*
* \param ctx The SHA-512 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha512_update( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-512 operation, and writes
* the result to the output buffer.
*
* \deprecated Superseded by mbedtls_sha512_finish_ret() in 2.7.0.
*
* \param ctx The SHA-512 context. This must be initialized
* and have a hash operation started.
* \param output The SHA-384 or SHA-512 checksum result. This must
* be a writable buffer of size \c 64 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha512_finish( mbedtls_sha512_context *ctx,
unsigned char output[64] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-512 computation. This function is for
* internal use only.
*
* \deprecated Superseded by mbedtls_internal_sha512_process() in 2.7.0.
*
* \param ctx The SHA-512 context. This must be initialized.
* \param data The buffer holding one block of data. This must be
* a readable buffer of length \c 128 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha512_process(
mbedtls_sha512_context *ctx,
const unsigned char data[128] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief This function calculates the SHA-512 or SHA-384
* checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-512 result is calculated as
* output = SHA-512(input buffer).
*
* \param input The buffer holding the input data. This must be
* a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-384 or SHA-512 checksum result.
* This must be a writable buffer of length \c 64 Bytes.
* \param is384 Determines which function to use. This must be either
* \c 0 for SHA-512, or \c 1 for SHA-384.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha512_ret( const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384 );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = SHA-512( input buffer )
* \brief This function calculates the SHA-512 or SHA-384
* checksum of a buffer.
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-384/512 checksum result
* \param is384 0 = use SHA512, 1 = use SHA384
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-512 result is calculated as
* output = SHA-512(input buffer).
*
* \deprecated Superseded by mbedtls_sha512_ret() in 2.7.0
*
* \param input The buffer holding the data. This must be a
* readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-384 or SHA-512 checksum result. This must
* be a writable buffer of length \c 64 Bytes.
* \param is384 Determines which function to use. This must be either
* \c 0 for SHA-512, or \c 1 for SHA-384.
*/
void mbedtls_sha512( const unsigned char *input, size_t ilen,
unsigned char output[64], int is384 );
MBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384 );
/**
* \brief Checkup routine
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief The SHA-384 or SHA-512 checkup routine.
*
* \return 0 if successful, or 1 if the test failed
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_sha512_self_test( int verbose );
/* Internal use */
void mbedtls_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,8 @@
* \file ssl_cache.h
*
* \brief SSL session cache implementation
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_SSL_CACHE_H
#define MBEDTLS_SSL_CACHE_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "ssl.h"
#if defined(MBEDTLS_THREADING_C)

View File

@ -2,7 +2,8 @@
* \file ssl_ciphersuites.h
*
* \brief SSL Ciphersuites for mbed TLS
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_SSL_CIPHERSUITES_H
#define MBEDTLS_SSL_CIPHERSUITES_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "pk.h"
#include "cipher.h"
#include "md.h"
@ -168,6 +175,45 @@ extern "C" {
#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 0xC03A /**< Weak! No SSL3! */
#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 0xC03B /**< Weak! No SSL3! */
#define MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 0xC03C /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 0xC03D /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC044 /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC045 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC048 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC049 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC04A /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC04B /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC04C /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC04D /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 0xC04E /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 0xC04F /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05E /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05F /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0xC062 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0xC063 /**< TLS 1.2 */
#define MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 0xC064 /**< TLS 1.2 */
#define MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 0xC065 /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC066 /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC067 /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 0xC068 /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 0xC069 /**< TLS 1.2 */
#define MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 0xC06A /**< TLS 1.2 */
#define MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 0xC06B /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0xC06C /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0xC06D /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0xC06E /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0xC06F /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC070 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC071 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC072 /**< Not in SSL3! */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC073 /**< Not in SSL3! */
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC074 /**< Not in SSL3! */
@ -231,6 +277,15 @@ extern "C" {
#define MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 0xC0FF /**< experimental */
/* RFC 7905 */
#define MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /**< TLS 1.2 */
#define MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAB /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAC /**< TLS 1.2 */
#define MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAD /**< TLS 1.2 */
#define MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAE /**< TLS 1.2 */
/* Reminder: update mbedtls_ssl_premaster_secret when adding a new key exchange.
* Reminder: update MBEDTLS_KEY_EXCHANGE__xxx below
*/
@ -260,6 +315,47 @@ typedef enum {
#define MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED
#endif
/* Key exchanges allowing client certificate requests */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED
#endif
/* Key exchanges involving server signature in ServerKeyExchange */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED
#endif
/* Key exchanges using ECDH */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED
#endif
/* Key exchanges that don't involve ephemeral keys */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED
#endif
/* Key exchanges that involve ephemeral keys */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED
#endif
/* Key exchanges using a PSK */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
@ -268,7 +364,13 @@ typedef enum {
#define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
#endif
/* Key exchanges using a ECDHE */
/* Key exchanges using DHE */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED
#endif
/* Key exchanges using ECDHE */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
@ -309,11 +411,128 @@ const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuit
#if defined(MBEDTLS_PK_C)
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info );
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info );
#endif
int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info );
int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)
static inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)
static inline int mbedtls_ssl_ciphersuite_no_pfs( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_PSK:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_ecdh( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */
static inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
return( 1 );
default:
return( 0 );
}
}
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_dhe( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED) */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_ecdhe( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED) */
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_server_signature( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
#ifdef __cplusplus
}
#endif

View File

@ -2,7 +2,8 @@
* \file ssl_cookie.h
*
* \brief DTLS cookie callbacks implementation
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_SSL_COOKIE_H
#define MBEDTLS_SSL_COOKIE_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "ssl.h"
#if defined(MBEDTLS_THREADING_C)
@ -49,7 +56,7 @@ extern "C" {
/**
* \brief Context for the default cookie functions.
*/
typedef struct
typedef struct mbedtls_ssl_cookie_ctx
{
mbedtls_md_context_t hmac_ctx; /*!< context for the HMAC portion */
#if !defined(MBEDTLS_HAVE_TIME)

View File

@ -1,8 +1,9 @@
/**
* \file ssl_ticket.h
* \file ssl_internal.h
*
* \brief Internal functions shared by the SSL modules
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,7 +24,14 @@
#ifndef MBEDTLS_SSL_INTERNAL_H
#define MBEDTLS_SSL_INTERNAL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "ssl.h"
#include "cipher.h"
#if defined(MBEDTLS_MD5_C)
#include "md5.h"
@ -69,6 +77,9 @@
#endif /* MBEDTLS_SSL_PROTO_TLS1 */
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
#define MBEDTLS_SSL_MIN_VALID_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1
#define MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3
/* Determine maximum supported version */
#define MBEDTLS_SSL_MAX_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3
@ -88,6 +99,14 @@
#endif /* MBEDTLS_SSL_PROTO_TLS1_1 */
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
/* Shorthand for restartable ECC */
#if defined(MBEDTLS_ECP_RESTARTABLE) && \
defined(MBEDTLS_SSL_CLI_C) && \
defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
#define MBEDTLS_SSL__ECP_RESTARTABLE
#endif
#define MBEDTLS_SSL_INITIAL_HANDSHAKE 0
#define MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS 1 /* In progress */
#define MBEDTLS_SSL_RENEGOTIATION_DONE 2 /* Done or aborted */
@ -138,12 +157,76 @@
#define MBEDTLS_SSL_PADDING_ADD 0
#endif
#define MBEDTLS_SSL_BUFFER_LEN ( MBEDTLS_SSL_MAX_CONTENT_LEN \
+ MBEDTLS_SSL_COMPRESSION_ADD \
+ 29 /* counter + header + IV */ \
+ MBEDTLS_SSL_MAC_ADD \
+ MBEDTLS_SSL_PADDING_ADD \
)
#define MBEDTLS_SSL_PAYLOAD_OVERHEAD ( MBEDTLS_SSL_COMPRESSION_ADD + \
MBEDTLS_MAX_IV_LENGTH + \
MBEDTLS_SSL_MAC_ADD + \
MBEDTLS_SSL_PADDING_ADD \
)
#define MBEDTLS_SSL_IN_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \
( MBEDTLS_SSL_IN_CONTENT_LEN ) )
#define MBEDTLS_SSL_OUT_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \
( MBEDTLS_SSL_OUT_CONTENT_LEN ) )
/* The maximum number of buffered handshake messages. */
#define MBEDTLS_SSL_MAX_BUFFERED_HS 4
/* Maximum length we can advertise as our max content length for
RFC 6066 max_fragment_length extension negotiation purposes
(the lesser of both sizes, if they are unequal.)
*/
#define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ( \
(MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN) \
? ( MBEDTLS_SSL_OUT_CONTENT_LEN ) \
: ( MBEDTLS_SSL_IN_CONTENT_LEN ) \
)
/*
* Check that we obey the standard's message size bounds
*/
#if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384
#error "Bad configuration - record content too large."
#endif
#if MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN
#error "Bad configuration - incoming record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN."
#endif
#if MBEDTLS_SSL_OUT_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN
#error "Bad configuration - outgoing record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN."
#endif
#if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048
#error "Bad configuration - incoming protected record payload too large."
#endif
#if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048
#error "Bad configuration - outgoing protected record payload too large."
#endif
/* Calculate buffer sizes */
/* Note: Even though the TLS record header is only 5 bytes
long, we're internally using 8 bytes to store the
implicit sequence number. */
#define MBEDTLS_SSL_HEADER_LEN 13
#define MBEDTLS_SSL_IN_BUFFER_LEN \
( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) )
#define MBEDTLS_SSL_OUT_BUFFER_LEN \
( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) )
#ifdef MBEDTLS_ZLIB_SUPPORT
/* Compression buffer holds both IN and OUT buffers, so should be size of the larger */
#define MBEDTLS_SSL_COMPRESS_BUFFER_LEN ( \
( MBEDTLS_SSL_IN_BUFFER_LEN > MBEDTLS_SSL_OUT_BUFFER_LEN ) \
? MBEDTLS_SSL_IN_BUFFER_LEN \
: MBEDTLS_SSL_OUT_BUFFER_LEN \
)
#endif
/*
* TLS extension flags (for extensions with outgoing ServerHello content
@ -157,6 +240,24 @@
extern "C" {
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
/*
* Abstraction for a grid of allowed signature-hash-algorithm pairs.
*/
struct mbedtls_ssl_sig_hash_set_t
{
/* At the moment, we only need to remember a single suitable
* hash algorithm per signature algorithm. As long as that's
* the case - and we don't need a general lookup function -
* we can implement the sig-hash-set as a map from signatures
* to hash algorithms. */
mbedtls_md_type_t rsa;
mbedtls_md_type_t ecdsa;
};
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
/*
* This structure contains the parameters only needed during handshake.
*/
@ -165,8 +266,11 @@ struct mbedtls_ssl_handshake_params
/*
* Handshake specific crypto variables
*/
int sig_alg; /*!< Hash algorithm for signature */
int verify_sig_alg; /*!< Signature algorithm for verify */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
mbedtls_ssl_sig_hash_set_t hash_algs; /*!< Set of suitable sig-hash pairs */
#endif
#if defined(MBEDTLS_DHM_C)
mbedtls_dhm_context dhm_ctx; /*!< DHM key exchange */
#endif
@ -179,7 +283,7 @@ struct mbedtls_ssl_handshake_params
unsigned char *ecjpake_cache; /*!< Cache for ClientHello ext */
size_t ecjpake_cache_len; /*!< Length of cached data */
#endif
#endif
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
const mbedtls_ecp_curve_info **curves; /*!< Supported elliptic curves */
@ -195,8 +299,20 @@ struct mbedtls_ssl_handshake_params
mbedtls_ssl_key_cert *sni_key_cert; /*!< key/cert list from SNI */
mbedtls_x509_crt *sni_ca_chain; /*!< trusted CAs from SNI callback */
mbedtls_x509_crl *sni_ca_crl; /*!< trusted CAs CRLs from SNI */
#endif
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
#endif /* MBEDTLS_X509_CRT_PARSE_C */
#if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
int ecrs_enabled; /*!< Handshake supports EC restart? */
mbedtls_x509_crt_restart_ctx ecrs_ctx; /*!< restart context */
enum { /* this complements ssl->state with info on intra-state operations */
ssl_ecrs_none = 0, /*!< nothing going on (yet) */
ssl_ecrs_crt_verify, /*!< Certificate: crt_verify() */
ssl_ecrs_ske_start_processing, /*!< ServerKeyExchange: pk_verify() */
ssl_ecrs_cke_ecdh_calc_secret, /*!< ClientKeyExchange: ECDH step 2 */
ssl_ecrs_crt_vrfy_sign, /*!< CertificateVerify: pk_sign() */
} ecrs_state; /*!< current (or last) operation */
size_t ecrs_n; /*!< place for saving a length */
#endif
#if defined(MBEDTLS_SSL_PROTO_DTLS)
unsigned int out_msg_seq; /*!< Outgoing handshake sequence number */
unsigned int in_msg_seq; /*!< Incoming handshake sequence number */
@ -206,19 +322,46 @@ struct mbedtls_ssl_handshake_params
unsigned char verify_cookie_len; /*!< Cli: cookie length
Srv: flag for sending a cookie */
unsigned char *hs_msg; /*!< Reassembled handshake message */
uint32_t retransmit_timeout; /*!< Current value of timeout */
unsigned char retransmit_state; /*!< Retransmission state */
mbedtls_ssl_flight_item *flight; /*!< Current outgoing flight */
mbedtls_ssl_flight_item *cur_msg; /*!< Current message in flight */
mbedtls_ssl_flight_item *flight; /*!< Current outgoing flight */
mbedtls_ssl_flight_item *cur_msg; /*!< Current message in flight */
unsigned char *cur_msg_p; /*!< Position in current message */
unsigned int in_flight_start_seq; /*!< Minimum message sequence in the
flight being received */
mbedtls_ssl_transform *alt_transform_out; /*!< Alternative transform for
resending messages */
unsigned char alt_out_ctr[8]; /*!< Alternative record epoch/counter
for resending messages */
#endif
struct
{
size_t total_bytes_buffered; /*!< Cumulative size of heap allocated
* buffers used for message buffering. */
uint8_t seen_ccs; /*!< Indicates if a CCS message has
* been seen in the current flight. */
struct mbedtls_ssl_hs_buffer
{
unsigned is_valid : 1;
unsigned is_fragmented : 1;
unsigned is_complete : 1;
unsigned char *data;
size_t data_len;
} hs[MBEDTLS_SSL_MAX_BUFFERED_HS];
struct
{
unsigned char *data;
size_t len;
unsigned epoch;
} future_record;
} buffering;
uint16_t mtu; /*!< Handshake mtu, used to fragment outgoing messages */
#endif /* MBEDTLS_SSL_PROTO_DTLS */
/*
* Checksum contexts
@ -261,8 +404,23 @@ struct mbedtls_ssl_handshake_params
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
int extended_ms; /*!< use Extended Master Secret? */
#endif
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
unsigned int async_in_progress : 1; /*!< an asynchronous operation is in progress */
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
/** Asynchronous operation context. This field is meant for use by the
* asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start,
* mbedtls_ssl_config::f_async_decrypt_start,
* mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel).
* The library does not use it internally. */
void *user_async_ctx;
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
};
typedef struct mbedtls_ssl_hs_buffer mbedtls_ssl_hs_buffer;
/*
* This structure contains a full set of runtime transform parameters
* either in negotiation or active.
@ -329,6 +487,28 @@ struct mbedtls_ssl_flight_item
};
#endif /* MBEDTLS_SSL_PROTO_DTLS */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
/* Find an entry in a signature-hash set matching a given hash algorithm. */
mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
mbedtls_pk_type_t sig_alg );
/* Add a signature-hash-pair to a signature-hash set */
void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
mbedtls_pk_type_t sig_alg,
mbedtls_md_type_t md_alg );
/* Allow exactly one hash algorithm for each signature. */
void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
mbedtls_md_type_t md_alg );
/* Setup an empty signature-hash set */
static inline void mbedtls_ssl_sig_hash_set_init( mbedtls_ssl_sig_hash_set_t *set )
{
mbedtls_ssl_sig_hash_set_const_hash( set, MBEDTLS_MD_NONE );
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
/**
* \brief Free referenced items in an SSL transform context and clear
@ -342,9 +522,9 @@ void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform );
* \brief Free referenced items in an SSL handshake context and clear
* memory
*
* \param handshake SSL handshake context
* \param ssl SSL context
*/
void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake );
void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl );
int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl );
int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl );
@ -355,15 +535,92 @@ int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl );
void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl );
int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl );
int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl );
int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl );
int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl );
void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl );
int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl );
/**
* \brief Update record layer
*
* This function roughly separates the implementation
* of the logic of (D)TLS from the implementation
* of the secure transport.
*
* \param ssl The SSL context to use.
* \param update_hs_digest This indicates if the handshake digest
* should be automatically updated in case
* a handshake message is found.
*
* \return 0 or non-zero error code.
*
* \note A clarification on what is called 'record layer' here
* is in order, as many sensible definitions are possible:
*
* The record layer takes as input an untrusted underlying
* transport (stream or datagram) and transforms it into
* a serially multiplexed, secure transport, which
* conceptually provides the following:
*
* (1) Three datagram based, content-agnostic transports
* for handshake, alert and CCS messages.
* (2) One stream- or datagram-based transport
* for application data.
* (3) Functionality for changing the underlying transform
* securing the contents.
*
* The interface to this functionality is given as follows:
*
* a Updating
* [Currently implemented by mbedtls_ssl_read_record]
*
* Check if and on which of the four 'ports' data is pending:
* Nothing, a controlling datagram of type (1), or application
* data (2). In any case data is present, internal buffers
* provide access to the data for the user to process it.
* Consumption of type (1) datagrams is done automatically
* on the next update, invalidating that the internal buffers
* for previous datagrams, while consumption of application
* data (2) is user-controlled.
*
* b Reading of application data
* [Currently manual adaption of ssl->in_offt pointer]
*
* As mentioned in the last paragraph, consumption of data
* is different from the automatic consumption of control
* datagrams (1) because application data is treated as a stream.
*
* c Tracking availability of application data
* [Currently manually through decreasing ssl->in_msglen]
*
* For efficiency and to retain datagram semantics for
* application data in case of DTLS, the record layer
* provides functionality for checking how much application
* data is still available in the internal buffer.
*
* d Changing the transformation securing the communication.
*
* Given an opaque implementation of the record layer in the
* above sense, it should be possible to implement the logic
* of (D)TLS on top of it without the need to know anything
* about the record layer's internals. This is done e.g.
* in all the handshake handling functions, and in the
* application data reading function mbedtls_ssl_read.
*
* \note The above tries to give a conceptual picture of the
* record layer, but the current implementation deviates
* from it in some places. For example, our implementation of
* the update functionality through mbedtls_ssl_read_record
* discards datagrams depending on the current state, which
* wouldn't fall under the record layer's responsibility
* following the above definition.
*
*/
int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
unsigned update_hs_digest );
int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want );
int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl );
int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl );
int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush );
int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl );
int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl );
@ -384,6 +641,7 @@ int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exch
#if defined(MBEDTLS_PK_C)
unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk );
unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type );
mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig );
#endif
@ -471,6 +729,7 @@ static inline size_t mbedtls_ssl_hs_hdr_len( const mbedtls_ssl_context *ssl )
void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl );
void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl );
int mbedtls_ssl_resend( mbedtls_ssl_context *ssl );
int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl );
#endif
/* Visible for testing purposes only */
@ -483,16 +742,39 @@ void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl );
static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n )
{
size_t i;
const unsigned char *A = (const unsigned char *) a;
const unsigned char *B = (const unsigned char *) b;
unsigned char diff = 0;
volatile const unsigned char *A = (volatile const unsigned char *) a;
volatile const unsigned char *B = (volatile const unsigned char *) b;
volatile unsigned char diff = 0;
for( i = 0; i < n; i++ )
diff |= A[i] ^ B[i];
{
/* Read volatile data in order before computing diff.
* This avoids IAR compiler warning:
* 'the order of volatile accesses is undefined ..' */
unsigned char x = A[i], y = B[i];
diff |= x ^ y;
}
return( diff );
}
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
unsigned char *output,
unsigned char *data, size_t data_len );
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
unsigned char *hash, size_t *hashlen,
unsigned char *data, size_t data_len,
mbedtls_md_type_t md_alg );
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
#ifdef __cplusplus
}
#endif

View File

@ -2,7 +2,8 @@
* \file ssl_ticket.h
*
* \brief TLS server ticket callbacks implementation
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -23,6 +24,12 @@
#ifndef MBEDTLS_SSL_TICKET_H
#define MBEDTLS_SSL_TICKET_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
/*
* This implementation of the session ticket callbacks includes key
* management, rotating the keys periodically in order to preserve forward
@ -43,7 +50,7 @@ extern "C" {
/**
* \brief Information for session ticket protection
*/
typedef struct
typedef struct mbedtls_ssl_ticket_key
{
unsigned char name[4]; /*!< random key identifier */
uint32_t generation_time; /*!< key generation timestamp (seconds) */
@ -54,7 +61,7 @@ mbedtls_ssl_ticket_key;
/**
* \brief Context for session ticket handling functions
*/
typedef struct
typedef struct mbedtls_ssl_ticket_context
{
mbedtls_ssl_ticket_key keys[2]; /*!< ticket protection keys */
unsigned char active; /*!< index of the currently active key */

View File

@ -2,7 +2,8 @@
* \file threading.h
*
* \brief Threading abstraction layer
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -35,13 +36,16 @@
extern "C" {
#endif
/* MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE is deprecated and should not be
* used. */
#define MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE -0x001A /**< The selected feature is not available. */
#define MBEDTLS_ERR_THREADING_BAD_INPUT_DATA -0x001C /**< Bad input parameters to function. */
#define MBEDTLS_ERR_THREADING_MUTEX_ERROR -0x001E /**< Locking / unlocking / free failed with error code. */
#if defined(MBEDTLS_THREADING_PTHREAD)
#include <pthread.h>
typedef struct
typedef struct mbedtls_threading_mutex_t
{
pthread_mutex_t mutex;
char is_valid;
@ -95,8 +99,20 @@ extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex );
/*
* Global mutexes
*/
#if defined(MBEDTLS_FS_IO)
extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex;
#endif
#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT)
/* This mutex may or may not be used in the default definition of
* mbedtls_platform_gmtime_r(), but in order to determine that,
* we need to check POSIX features, hence modify _POSIX_C_SOURCE.
* With the current approach, this declaration is orphaned, lacking
* an accompanying definition, in case mbedtls_platform_gmtime_r()
* doesn't need it, but that's not a problem. */
extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex;
#endif /* MBEDTLS_HAVE_TIME_DATE && !MBEDTLS_PLATFORM_GMTIME_R_ALT */
#endif /* MBEDTLS_THREADING_C */
#ifdef __cplusplus

View File

@ -1,8 +1,9 @@
/**
* \file timing.h
*
* \brief Portable interface to the CPU cycle counter
*
* \brief Portable interface to timeouts and to the CPU cycle counter
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -29,16 +30,16 @@
#include MBEDTLS_CONFIG_FILE
#endif
#if !defined(MBEDTLS_TIMING_ALT)
// Regular implementation
//
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_TIMING_ALT)
// Regular implementation
//
/**
* \brief timer structure
*/
@ -50,13 +51,17 @@ struct mbedtls_timing_hr_time
/**
* \brief Context for mbedtls_timing_set/get_delay()
*/
typedef struct
typedef struct mbedtls_timing_delay_context
{
struct mbedtls_timing_hr_time timer;
uint32_t int_ms;
uint32_t fin_ms;
} mbedtls_timing_delay_context;
#else /* MBEDTLS_TIMING_ALT */
#include "timing_alt.h"
#endif /* MBEDTLS_TIMING_ALT */
extern volatile int mbedtls_timing_alarmed;
/**
@ -65,6 +70,9 @@ extern volatile int mbedtls_timing_alarmed;
* \warning This is only a best effort! Do not rely on this!
* In particular, it is known to be unreliable on virtual
* machines.
*
* \note This value starts at an unspecified origin and
* may wrap around.
*/
unsigned long mbedtls_timing_hardclock( void );
@ -72,7 +80,18 @@ unsigned long mbedtls_timing_hardclock( void );
* \brief Return the elapsed time in milliseconds
*
* \param val points to a timer structure
* \param reset if set to 1, the timer is restarted
* \param reset If 0, query the elapsed time. Otherwise (re)start the timer.
*
* \return Elapsed time since the previous reset in ms. When
* restarting, this is always 0.
*
* \note To initialize a timer, call this function with reset=1.
*
* Determining the elapsed time and resetting the timer is not
* atomic on all platforms, so after the sequence
* `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 =
* get_timer(0) }` the value time1+time2 is only approximately
* the delay since the first reset.
*/
unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset );
@ -80,6 +99,7 @@ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int
* \brief Setup an alarm clock
*
* \param seconds delay before the "mbedtls_timing_alarmed" flag is set
* (must be >=0)
*
* \warning Only one alarm at a time is supported. In a threaded
* context, this means one for the whole process, not one per
@ -91,11 +111,15 @@ void mbedtls_set_alarm( int seconds );
* \brief Set a pair of delays to watch
* (See \c mbedtls_timing_get_delay().)
*
* \param data Pointer to timing data
* \param data Pointer to timing data.
* Must point to a valid \c mbedtls_timing_delay_context struct.
* \param int_ms First (intermediate) delay in milliseconds.
* The effect if int_ms > fin_ms is unspecified.
* \param fin_ms Second (final) delay in milliseconds.
* Pass 0 to cancel the current delay.
*
* \note To set a single delay, either use \c mbedtls_timing_set_timer
* directly or use this function with int_ms == fin_ms.
*/
void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
@ -106,25 +130,13 @@ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
* \param data Pointer to timing data
* Must point to a valid \c mbedtls_timing_delay_context struct.
*
* \return -1 if cancelled (fin_ms = 0)
* \return -1 if cancelled (fin_ms = 0),
* 0 if none of the delays are passed,
* 1 if only the intermediate delay is passed,
* 2 if the final delay is passed.
*/
int mbedtls_timing_get_delay( void *data );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_TIMING_ALT */
#include "timing_alt.h"
#endif /* MBEDTLS_TIMING_ALT */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine

View File

@ -2,7 +2,8 @@
* \file version.h
*
* \brief Run-time version information
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -38,7 +39,7 @@
* Major, Minor, Patchlevel
*/
#define MBEDTLS_VERSION_MAJOR 2
#define MBEDTLS_VERSION_MINOR 4
#define MBEDTLS_VERSION_MINOR 16
#define MBEDTLS_VERSION_PATCH 1
/**
@ -46,9 +47,9 @@
* MMNNPP00
* Major version | Minor version | Patch version
*/
#define MBEDTLS_VERSION_NUMBER 0x02040100
#define MBEDTLS_VERSION_STRING "2.4.1"
#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.4.1"
#define MBEDTLS_VERSION_NUMBER 0x02100100
#define MBEDTLS_VERSION_STRING "2.16.1"
#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.16.1"
#if defined(MBEDTLS_VERSION_C)

View File

@ -2,7 +2,8 @@
* \file x509.h
*
* \brief X.509 generic defines and structures
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -76,6 +77,7 @@
#define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880 /**< Allocation of memory failed. */
#define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900 /**< Read/write of file failed. */
#define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980 /**< Destination buffer is too small. */
#define MBEDTLS_ERR_X509_FATAL_ERROR -0x3000 /**< A fatal error occured, eg the chain is too long or the vrfy callback failed. */
/* \} name */
/**
@ -157,7 +159,7 @@
#define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY (1 << 13)
#define MBEDTLS_X509_EXT_FRESHEST_CRL (1 << 14)
#define MBEDTLS_X509_EXT_NS_CERT_TYPE (1 << 16) /* Parsed (and then ?) */
#define MBEDTLS_X509_EXT_NS_CERT_TYPE (1 << 16)
/*
* Storage format identifiers
@ -246,12 +248,12 @@ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *se
* \note Intended usage is "if( is_past( valid_to ) ) ERROR".
* Hence the return value of 1 if on internal errors.
*
* \param time mbedtls_x509_time to check
* \param to mbedtls_x509_time to check
*
* \return 1 if the given time is in the past or an error occured,
* 0 otherwise.
*/
int mbedtls_x509_time_is_past( const mbedtls_x509_time *time );
int mbedtls_x509_time_is_past( const mbedtls_x509_time *to );
/**
* \brief Check a given mbedtls_x509_time against the system time
@ -260,12 +262,14 @@ int mbedtls_x509_time_is_past( const mbedtls_x509_time *time );
* \note Intended usage is "if( is_future( valid_from ) ) ERROR".
* Hence the return value of 1 if on internal errors.
*
* \param time mbedtls_x509_time to check
* \param from mbedtls_x509_time to check
*
* \return 1 if the given time is in the future or an error occured,
* 0 otherwise.
*/
int mbedtls_x509_time_is_future( const mbedtls_x509_time *time );
int mbedtls_x509_time_is_future( const mbedtls_x509_time *from );
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
@ -274,6 +278,8 @@ int mbedtls_x509_time_is_future( const mbedtls_x509_time *time );
*/
int mbedtls_x509_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
/*
* Internal module functions. You probably do not want to use these unless you
* know you do.
@ -294,7 +300,7 @@ int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x50
mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
void **sig_opts );
int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
mbedtls_x509_time *time );
mbedtls_x509_time *t );
int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *serial );
int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,

View File

@ -2,7 +2,8 @@
* \file x509_crl.h
*
* \brief X.509 certificate revocation list parsing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*

View File

@ -2,7 +2,8 @@
* \file x509_crt.h
*
* \brief X.509 certificate parsing and writing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -104,7 +105,7 @@ mbedtls_x509_crt;
*
* All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG().
*/
typedef struct
typedef struct mbedtls_x509_crt_profile
{
uint32_t allowed_mds; /**< MDs for signatures */
uint32_t allowed_pks; /**< PK algs for signatures */
@ -142,6 +143,63 @@ typedef struct mbedtls_x509write_cert
}
mbedtls_x509write_cert;
/**
* Item in a verification chain: cert and flags for it
*/
typedef struct {
mbedtls_x509_crt *crt;
uint32_t flags;
} mbedtls_x509_crt_verify_chain_item;
/**
* Max size of verification chain: end-entity + intermediates + trusted root
*/
#define MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 )
/**
* Verification chain as built by \c mbedtls_crt_verify_chain()
*/
typedef struct
{
mbedtls_x509_crt_verify_chain_item items[MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE];
unsigned len;
} mbedtls_x509_crt_verify_chain;
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/**
* \brief Context for resuming X.509 verify operations
*/
typedef struct
{
/* for check_signature() */
mbedtls_pk_restart_ctx pk;
/* for find_parent_in() */
mbedtls_x509_crt *parent; /* non-null iff parent_in in progress */
mbedtls_x509_crt *fallback_parent;
int fallback_signature_is_good;
/* for find_parent() */
int parent_is_trusted; /* -1 if find_parent is not in progress */
/* for verify_chain() */
enum {
x509_crt_rs_none,
x509_crt_rs_find_parent,
} in_progress; /* none if no operation is in progress */
int self_cnt;
mbedtls_x509_crt_verify_chain ver_chain;
} mbedtls_x509_crt_restart_ctx;
#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/* Now we can declare functions that take a pointer to that */
typedef void mbedtls_x509_crt_restart_ctx;
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
#if defined(MBEDTLS_X509_CRT_PARSE_C)
/**
* Default security profile. Should provide a good balance between security
@ -174,19 +232,34 @@ int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *bu
size_t buflen );
/**
* \brief Parse one or more certificates and add them
* to the chained list. Parses permissively. If some
* certificates can be parsed, the result is the number
* of failed certificates it encountered. If none complete
* correctly, the first error is returned.
* \brief Parse one DER-encoded or one or more concatenated PEM-encoded
* certificates and add them to the chained list.
*
* \param chain points to the start of the chain
* \param buf buffer holding the certificate data in PEM or DER format
* \param buflen size of the buffer
* (including the terminating null byte for PEM data)
* For CRTs in PEM encoding, the function parses permissively:
* if at least one certificate can be parsed, the function
* returns the number of certificates for which parsing failed
* (hence \c 0 if all certificates were parsed successfully).
* If no certificate could be parsed, the function returns
* the first (negative) error encountered during parsing.
*
* PEM encoded certificates may be interleaved by other data
* such as human readable descriptions of their content, as
* long as the certificates are enclosed in the PEM specific
* '-----{BEGIN/END} CERTIFICATE-----' delimiters.
*
* \param chain The chain to which to add the parsed certificates.
* \param buf The buffer holding the certificate data in PEM or DER format.
* For certificates in PEM encoding, this may be a concatenation
* of multiple certificates; for DER encoding, the buffer must
* comprise exactly one certificate.
* \param buflen The size of \p buf, including the terminating \c NULL byte
* in case of PEM encoded data.
*
* \return \c 0 if all certificates were parsed successfully.
* \return The (positive) number of certificates that couldn't
* be parsed if parsing was partly successful (see above).
* \return A negative X509 or PEM error code otherwise.
*
* \return 0 if all certificates parsed successfully, a positive number
* if partly successful or a specific X509 or PEM error code
*/
int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen );
@ -267,7 +340,13 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
*
* All flags left after returning from the callback
* are also returned to the application. The function should
* return 0 for anything but a fatal error.
* return 0 for anything (including invalid certificates)
* other than fatal error, as a non-zero return code
* immediately aborts the verification process. For fatal
* errors, a specific error code should be used (different
* from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
* be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
* can be used if no better code is available.
*
* \note In case verification failed, the results can be displayed
* using \c mbedtls_x509_crt_verify_info()
@ -280,8 +359,15 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
* used to sign the certificate, CRL verification is skipped
* silently, that is *without* setting any flag.
*
* \note The \c trust_ca list can contain two types of certificates:
* (1) those of trusted root CAs, so that certificates
* chaining up to those CAs will be trusted, and (2)
* self-signed end-entity certificates to be trusted (for
* specific peers you know) - in that case, the self-signed
* certificate doesn't need to have the CA bit set.
*
* \param crt a certificate (chain) to be verified
* \param trust_ca the list of trusted CAs
* \param trust_ca the list of trusted CAs (see note above)
* \param ca_crl the list of CRLs for trusted CAs (see note above)
* \param cn expected Common Name (can be set to
* NULL if the CN must not be verified)
@ -289,12 +375,13 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
* \param f_vrfy verification function
* \param p_vrfy verification parameter
*
* \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
* in which case *flags will have one or more
* MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
* set,
* or another error in case of a fatal error encountered
* during the verification process.
* \return 0 (and flags set to 0) if the chain was verified and valid,
* MBEDTLS_ERR_X509_CERT_VERIFY_FAILED if the chain was verified
* but found to be invalid, in which case *flags will have one
* or more MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX
* flags set, or another error (and flags set to 0xffffffff)
* in case of a fatal error encountered during the
* verification process.
*/
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
@ -338,6 +425,37 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy );
/**
* \brief Restartable version of \c mbedtls_crt_verify_with_profile()
*
* \note Performs the same job as \c mbedtls_crt_verify_with_profile()
* but can return early and restart according to the limit
* set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
*
* \param crt a certificate (chain) to be verified
* \param trust_ca the list of trusted CAs
* \param ca_crl the list of CRLs for trusted CAs
* \param profile security profile for verification
* \param cn expected Common Name (can be set to
* NULL if the CN must not be verified)
* \param flags result of the verification
* \param f_vrfy verification function
* \param p_vrfy verification parameter
* \param rs_ctx restart context (NULL to disable restart)
*
* \return See \c mbedtls_crt_verify_with_profile(), or
* \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
* operations was reached: see \c mbedtls_ecp_set_max_ops().
*/
int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy,
mbedtls_x509_crt_restart_ctx *rs_ctx );
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
/**
* \brief Check usage of certificate against keyUsage extension.
@ -366,21 +484,22 @@ int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
/**
* \brief Check usage of certificate against extentedJeyUsage.
* \brief Check usage of certificate against extendedKeyUsage.
*
* \param crt Leaf certificate used.
* \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or MBEDTLS_OID_CLIENT_AUTH).
* \param crt Leaf certificate used.
* \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or
* MBEDTLS_OID_CLIENT_AUTH).
* \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
*
* \return 0 if this use of the certificate is allowed,
* MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
* \return 0 if this use of the certificate is allowed,
* MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
*
* \note Usually only makes sense on leaf certificates.
* \note Usually only makes sense on leaf certificates.
*/
int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
const char *usage_oid,
size_t usage_len );
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) */
const char *usage_oid,
size_t usage_len );
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/**
@ -408,6 +527,18 @@ void mbedtls_x509_crt_init( mbedtls_x509_crt *crt );
* \param crt Certificate chain to free
*/
void mbedtls_x509_crt_free( mbedtls_x509_crt *crt );
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/**
* \brief Initialize a restart context
*/
void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx );
/**
* \brief Free the components of a restart context
*/
void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx );
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
#endif /* MBEDTLS_X509_CRT_PARSE_C */
/* \} name */

View File

@ -2,7 +2,8 @@
* \file x509_csr.h
*
* \brief X.509 certificate signing request parsing and writing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -204,6 +205,14 @@ void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_ty
* \param key_usage key usage flags to set
*
* \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
*
* \note The <code>decipherOnly</code> flag from the Key Usage
* extension is represented by bit 8 (i.e.
* <code>0x8000</code>), which cannot typically be represented
* in an unsigned char. Therefore, the flag
* <code>decipherOnly</code> (i.e.
* #MBEDTLS_X509_KU_DECIPHER_ONLY) cannot be set using this
* function.
*/
int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage );

View File

@ -2,7 +2,8 @@
* \file xtea.h
*
* \brief XTEA block cipher (32-bit)
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
@ -37,23 +38,30 @@
#define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028 /**< The data input has an invalid length. */
#if !defined(MBEDTLS_XTEA_ALT)
// Regular implementation
//
/* MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED -0x0029 /**< XTEA hardware accelerator failed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_XTEA_ALT)
// Regular implementation
//
/**
* \brief XTEA context structure
*/
typedef struct
typedef struct mbedtls_xtea_context
{
uint32_t k[4]; /*!< key */
}
mbedtls_xtea_context;
#else /* MBEDTLS_XTEA_ALT */
#include "xtea_alt.h"
#endif /* MBEDTLS_XTEA_ALT */
/**
* \brief Initialize XTEA context
*
@ -113,17 +121,7 @@ int mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx,
unsigned char *output);
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_XTEA_ALT */
#include "xtea_alt.h"
#endif /* MBEDTLS_XTEA_ALT */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
@ -132,6 +130,8 @@ extern "C" {
*/
int mbedtls_xtea_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif

View File

@ -6,6 +6,7 @@ set(src_crypto
aes.c
aesni.c
arc4.c
aria.c
asn1parse.c
asn1write.c
base64.c
@ -13,6 +14,8 @@ set(src_crypto
blowfish.c
camellia.c
ccm.c
chacha20.c
chachapoly.c
cipher.c
cipher_wrap.c
cmac.c
@ -29,6 +32,7 @@ set(src_crypto
error.c
gcm.c
havege.c
hkdf.c
hmac_drbg.c
md.c
md2.c
@ -36,6 +40,7 @@ set(src_crypto
md5.c
md_wrap.c
memory_buffer_alloc.c
nist_kw.c
oid.c
padlock.c
pem.c
@ -46,8 +51,11 @@ set(src_crypto
pkparse.c
pkwrite.c
platform.c
platform_util.c
poly1305.c
ripemd160.c
rsa.c
rsa_internal.c
sha1.c
sha256.c
sha512.c
@ -90,10 +98,27 @@ if(CMAKE_COMPILER_IS_CLANG)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-declarations -Wmissing-prototypes -Wdocumentation -Wno-documentation-deprecated-sync -Wunreachable-code")
endif(CMAKE_COMPILER_IS_CLANG)
if(UNSAFE_BUILD)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error")
set(CMAKE_C_FLAGS_ASAN "${CMAKE_C_FLAGS_ASAN} -Wno-error")
set(CMAKE_C_FLAGS_ASANDBG "${CMAKE_C_FLAGS_ASANDBG} -Wno-error")
endif(UNSAFE_BUILD)
if(WIN32)
set(libs ${libs} ws2_32)
endif(WIN32)
if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
SET(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>")
SET(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>")
SET(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> -no_warning_for_no_symbols -c <TARGET>")
SET(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -no_warning_for_no_symbols -c <TARGET>")
endif()
if(HAIKU)
set(libs ${libs} network)
endif(HAIKU)
if(USE_PKCS11_HELPER_LIBRARY)
set(libs ${libs} pkcs11-helper)
endif(USE_PKCS11_HELPER_LIBRARY)
@ -140,15 +165,15 @@ endif(USE_STATIC_MBEDTLS_LIBRARY)
if(USE_SHARED_MBEDTLS_LIBRARY)
add_library(mbedcrypto SHARED ${src_crypto})
set_target_properties(mbedcrypto PROPERTIES VERSION 2.4.1 SOVERSION 0)
set_target_properties(mbedcrypto PROPERTIES VERSION 2.16.1 SOVERSION 3)
target_link_libraries(mbedcrypto ${libs})
add_library(mbedx509 SHARED ${src_x509})
set_target_properties(mbedx509 PROPERTIES VERSION 2.4.1 SOVERSION 0)
set_target_properties(mbedx509 PROPERTIES VERSION 2.16.1 SOVERSION 0)
target_link_libraries(mbedx509 ${libs} mbedcrypto)
add_library(mbedtls SHARED ${src_tls})
set_target_properties(mbedtls PROPERTIES VERSION 2.4.1 SOVERSION 10)
set_target_properties(mbedtls PROPERTIES VERSION 2.16.1 SOVERSION 12)
target_link_libraries(mbedtls ${libs} mbedx509)
install(TARGETS mbedtls mbedx509 mbedcrypto
@ -156,7 +181,7 @@ if(USE_SHARED_MBEDTLS_LIBRARY)
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
endif(USE_SHARED_MBEDTLS_LIBRARY)
#add_custom_target(lib DEPENDS mbedcrypto mbedx509 mbedtls)
#if(USE_STATIC_MBEDTLS_LIBRARY AND USE_SHARED_MBEDTLS_LIBRARY)
# add_dependencies(lib mbedcrypto_static mbedx509_static mbedtls_static)
#endif()
add_custom_target(lib DEPENDS mbedcrypto mbedx509 mbedtls)
if(USE_STATIC_MBEDTLS_LIBRARY AND USE_SHARED_MBEDTLS_LIBRARY)
add_dependencies(lib mbedcrypto_static mbedx509_static mbedtls_static)
endif()

View File

@ -21,6 +21,10 @@ endif
# if were running on Windows build for Windows
ifdef WINDOWS
WINDOWS_BUILD=1
else ifeq ($(shell uname -s),Darwin)
ifeq ($(AR),ar)
APPLE_BUILD ?= 1
endif
endif
# To compile as a shared library:
@ -31,37 +35,55 @@ LOCAL_CFLAGS += -fPIC -fpic
endif
endif
SOEXT_TLS=so.10
SOEXT_TLS=so.12
SOEXT_X509=so.0
SOEXT_CRYPTO=so.0
SOEXT_CRYPTO=so.3
DLEXT=so
# OSX shared library extension:
# DLEXT=dylib
# Set AR_DASH= (empty string) to use an ar implentation that does not accept
# the - prefix for command line options (e.g. llvm-ar)
AR_DASH ?= -
# Windows shared library extension:
ARFLAGS = $(AR_DASH)src
ifdef APPLE_BUILD
ifneq ($(APPLE_BUILD),0)
ARFLAGS = $(AR_DASH)Src
RLFLAGS = -no_warning_for_no_symbols -c
RL ?= ranlib
endif
endif
DLEXT ?= so
ifdef WINDOWS_BUILD
DLEXT=dll
# Windows shared library extension:
DLEXT = dll
else ifdef APPLE_BUILD
ifneq ($(APPLE_BUILD),0)
# Mac OS X shared library extension:
DLEXT = dylib
endif
endif
OBJS_CRYPTO= aes.o aesni.o arc4.o \
asn1parse.o asn1write.o base64.o \
bignum.o blowfish.o camellia.o \
ccm.o cipher.o cipher_wrap.o \
aria.o asn1parse.o asn1write.o \
base64.o bignum.o blowfish.o \
camellia.o ccm.o chacha20.o \
chachapoly.o cipher.o cipher_wrap.o \
cmac.o ctr_drbg.o des.o \
dhm.o ecdh.o ecdsa.o \
ecjpake.o ecp.o \
ecp_curves.o entropy.o entropy_poll.o \
error.o gcm.o havege.o \
hkdf.o \
hmac_drbg.o md.o md2.o \
md4.o md5.o md_wrap.o \
memory_buffer_alloc.o oid.o \
padlock.o pem.o pk.o \
pk_wrap.o pkcs12.o pkcs5.o \
pkparse.o pkwrite.o platform.o \
ripemd160.o rsa.o sha1.o \
sha256.o sha512.o threading.o \
timing.o version.o \
memory_buffer_alloc.o nist_kw.o \
oid.o padlock.o pem.o \
pk.o pk_wrap.o pkcs12.o \
pkcs5.o pkparse.o pkwrite.o \
platform.o platform_util.o poly1305.o \
ripemd160.o rsa_internal.o rsa.o \
sha1.o sha256.o sha512.o \
threading.o timing.o version.o \
version_features.o xtea.o
OBJS_X509= certs.o pkcs11.o x509.o \
@ -91,9 +113,13 @@ shared: libmbedcrypto.$(DLEXT) libmbedx509.$(DLEXT) libmbedtls.$(DLEXT)
# tls
libmbedtls.a: $(OBJS_TLS)
echo " AR $@"
$(AR) -rc $@ $(OBJS_TLS)
$(AR) $(ARFLAGS) $@ $(OBJS_TLS)
ifdef APPLE_BUILD
ifneq ($(APPLE_BUILD),0)
echo " RL $@"
$(AR) -s $@
$(RL) $(RLFLAGS) $@
endif
endif
libmbedtls.$(SOEXT_TLS): $(OBJS_TLS) libmbedx509.so
echo " LD $@"
@ -103,9 +129,9 @@ libmbedtls.so: libmbedtls.$(SOEXT_TLS)
echo " LN $@ -> $<"
ln -sf $< $@
libmbedtls.dylib: $(OBJS_TLS)
libmbedtls.dylib: $(OBJS_TLS) libmbedx509.dylib
echo " LD $@"
$(CC) -dynamiclib $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_TLS)
$(CC) -dynamiclib -L. -lmbedcrypto -lmbedx509 $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_TLS)
libmbedtls.dll: $(OBJS_TLS) libmbedx509.dll
echo " LD $@"
@ -114,9 +140,13 @@ libmbedtls.dll: $(OBJS_TLS) libmbedx509.dll
# x509
libmbedx509.a: $(OBJS_X509)
echo " AR $@"
$(AR) -rc $@ $(OBJS_X509)
$(AR) $(ARFLAGS) $@ $(OBJS_X509)
ifdef APPLE_BUILD
ifneq ($(APPLE_BUILD),0)
echo " RL $@"
$(AR) -s $@
$(RL) $(RLFLAGS) $@
endif
endif
libmbedx509.$(SOEXT_X509): $(OBJS_X509) libmbedcrypto.so
echo " LD $@"
@ -126,9 +156,9 @@ libmbedx509.so: libmbedx509.$(SOEXT_X509)
echo " LN $@ -> $<"
ln -sf $< $@
libmbedx509.dylib: $(OBJS_X509)
libmbedx509.dylib: $(OBJS_X509) libmbedcrypto.dylib
echo " LD $@"
$(CC) -dynamiclib $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_X509)
$(CC) -dynamiclib -L. -lmbedcrypto $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_X509)
libmbedx509.dll: $(OBJS_X509) libmbedcrypto.dll
echo " LD $@"
@ -137,9 +167,13 @@ libmbedx509.dll: $(OBJS_X509) libmbedcrypto.dll
# crypto
libmbedcrypto.a: $(OBJS_CRYPTO)
echo " AR $@"
$(AR) -rc $@ $(OBJS_CRYPTO)
$(AR) $(ARFLAGS) $@ $(OBJS_CRYPTO)
ifdef APPLE_BUILD
ifneq ($(APPLE_BUILD),0)
echo " RL $@"
$(AR) -s $@
$(RL) $(RLFLAGS) $@
endif
endif
libmbedcrypto.$(SOEXT_CRYPTO): $(OBJS_CRYPTO)
echo " LD $@"

File diff suppressed because it is too large Load Diff

View File

@ -32,6 +32,12 @@
#if defined(MBEDTLS_AESNI_C)
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
#warning "MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code."
#endif
#endif
#include "mbedtls/aesni.h"
#include <string.h>

View File

@ -33,6 +33,7 @@
#if defined(MBEDTLS_ARC4_C)
#include "mbedtls/arc4.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -47,11 +48,6 @@
#if !defined(MBEDTLS_ARC4_ALT)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
}
void mbedtls_arc4_init( mbedtls_arc4_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_arc4_context ) );
@ -62,7 +58,7 @@ void mbedtls_arc4_free( mbedtls_arc4_context *ctx )
if( ctx == NULL )
return;
mbedtls_zeroize( ctx, sizeof( mbedtls_arc4_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_arc4_context ) );
}
/*

1079
Externals/mbedtls/library/aria.c vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -28,6 +28,7 @@
#if defined(MBEDTLS_ASN1_PARSE_C)
#include "mbedtls/asn1.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -43,11 +44,6 @@
#define mbedtls_free free
#endif
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
}
/*
* ASN.1 DER decoding routines
*/
@ -313,7 +309,7 @@ int mbedtls_asn1_get_alg( unsigned char **p,
if( *p == end )
{
mbedtls_zeroize( params, sizeof(mbedtls_asn1_buf) );
mbedtls_platform_zeroize( params, sizeof(mbedtls_asn1_buf) );
return( 0 );
}
@ -358,7 +354,7 @@ void mbedtls_asn1_free_named_data( mbedtls_asn1_named_data *cur )
mbedtls_free( cur->oid.p );
mbedtls_free( cur->val.p );
mbedtls_zeroize( cur, sizeof( mbedtls_asn1_named_data ) );
mbedtls_platform_zeroize( cur, sizeof( mbedtls_asn1_named_data ) );
}
void mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head )

View File

@ -83,7 +83,9 @@ int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len
return( 4 );
}
#if SIZE_MAX > 0xFFFFFFFF
if( len <= 0xFFFFFFFF )
#endif
{
if( *p - start < 5 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
@ -96,7 +98,9 @@ int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len
return( 5 );
}
#if SIZE_MAX > 0xFFFFFFFF
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
#endif
}
int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, unsigned char tag )
@ -232,10 +236,6 @@ int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val )
int ret;
size_t len = 0;
// TODO negative values and values larger than 128
// DER format assumes 2s complement for numbers, so the leftmost bit
// should be 0 for positive numbers and 1 for negative numbers.
//
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
@ -257,56 +257,65 @@ int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val )
return( (int) len );
}
int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len )
int mbedtls_asn1_write_tagged_string( unsigned char **p, unsigned char *start, int tag,
const char *text, size_t text_len )
{
int ret;
size_t len = 0;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) text, text_len ) );
(const unsigned char *) text, text_len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_PRINTABLE_STRING ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, tag ) );
return( (int) len );
}
int mbedtls_asn1_write_utf8_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len )
{
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_UTF8_STRING, text, text_len) );
}
int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len )
{
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_PRINTABLE_STRING, text, text_len) );
}
int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len )
{
int ret;
size_t len = 0;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) text, text_len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_IA5_STRING ) );
return( (int) len );
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_IA5_STRING, text, text_len) );
}
int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t bits )
{
int ret;
size_t len = 0, size;
size_t len = 0;
size_t unused_bits, byte_len;
size = ( bits / 8 ) + ( ( bits % 8 ) ? 1 : 0 );
byte_len = ( bits + 7 ) / 8;
unused_bits = ( byte_len * 8 ) - bits;
// Calculate byte length
//
if( *p < start || (size_t)( *p - start ) < size + 1 )
if( *p < start || (size_t)( *p - start ) < byte_len + 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
len = size + 1;
(*p) -= size;
memcpy( *p, buf, size );
len = byte_len + 1;
// Write unused bits
//
*--(*p) = (unsigned char) (size * 8 - bits);
/* Write the bitstring. Ensure the unused bits are zeroed */
if( byte_len > 0 )
{
byte_len--;
*--( *p ) = buf[byte_len] & ~( ( 0x1 << unused_bits ) - 1 );
( *p ) -= byte_len;
memcpy( *p, buf, byte_len );
}
/* Write unused bits */
*--( *p ) = (unsigned char)unused_bits;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) );
@ -328,14 +337,36 @@ int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start,
return( (int) len );
}
mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( mbedtls_asn1_named_data **head,
/* This is a copy of the ASN.1 parsing function mbedtls_asn1_find_named_data(),
* which is replicated to avoid a dependency ASN1_WRITE_C on ASN1_PARSE_C. */
static mbedtls_asn1_named_data *asn1_find_named_data(
mbedtls_asn1_named_data *list,
const char *oid, size_t len )
{
while( list != NULL )
{
if( list->oid.len == len &&
memcmp( list->oid.p, oid, len ) == 0 )
{
break;
}
list = list->next;
}
return( list );
}
mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(
mbedtls_asn1_named_data **head,
const char *oid, size_t oid_len,
const unsigned char *val,
size_t val_len )
{
mbedtls_asn1_named_data *cur;
if( ( cur = mbedtls_asn1_find_named_data( *head, oid, oid_len ) ) == NULL )
if( ( cur = asn1_find_named_data( *head, oid, oid_len ) ) == NULL )
{
// Add new entry if not present yet based on OID
//

View File

@ -192,7 +192,11 @@ int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
return( 0 );
}
n = ( ( n * 6 ) + 7 ) >> 3;
/* The following expression is to calculate the following formula without
* risk of integer overflow in n:
* n = ( ( n * 6 ) + 7 ) >> 3;
*/
n = ( 6 * ( n >> 3 ) ) + ( ( 6 * ( n & 0x7 ) + 7 ) >> 3 );
n -= j;
if( dst == NULL || dlen < n )

File diff suppressed because it is too large Load Diff

View File

@ -34,15 +34,17 @@
#if defined(MBEDTLS_BLOWFISH_C)
#include "mbedtls/blowfish.h"
#include "mbedtls/platform_util.h"
#include <string.h>
#if !defined(MBEDTLS_BLOWFISH_ALT)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
}
/* Parameter validation macros */
#define BLOWFISH_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA )
#define BLOWFISH_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
/*
* 32-bit integer manipulation macros (big endian)
@ -157,6 +159,7 @@ static void blowfish_dec( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t
void mbedtls_blowfish_init( mbedtls_blowfish_context *ctx )
{
BLOWFISH_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_blowfish_context ) );
}
@ -165,22 +168,26 @@ void mbedtls_blowfish_free( mbedtls_blowfish_context *ctx )
if( ctx == NULL )
return;
mbedtls_zeroize( ctx, sizeof( mbedtls_blowfish_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_blowfish_context ) );
}
/*
* Blowfish key schedule
*/
int mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx, const unsigned char *key,
unsigned int keybits )
int mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx,
const unsigned char *key,
unsigned int keybits )
{
unsigned int i, j, k;
uint32_t data, datal, datar;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( key != NULL );
if( keybits < MBEDTLS_BLOWFISH_MIN_KEY_BITS || keybits > MBEDTLS_BLOWFISH_MAX_KEY_BITS ||
( keybits % 8 ) )
if( keybits < MBEDTLS_BLOWFISH_MIN_KEY_BITS ||
keybits > MBEDTLS_BLOWFISH_MAX_KEY_BITS ||
keybits % 8 != 0 )
{
return( MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH );
return( MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA );
}
keybits >>= 3;
@ -235,6 +242,11 @@ int mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx,
unsigned char output[MBEDTLS_BLOWFISH_BLOCKSIZE] )
{
uint32_t X0, X1;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT );
BLOWFISH_VALIDATE_RET( input != NULL );
BLOWFISH_VALIDATE_RET( output != NULL );
GET_UINT32_BE( X0, input, 0 );
GET_UINT32_BE( X1, input, 4 );
@ -267,6 +279,12 @@ int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
{
int i;
unsigned char temp[MBEDTLS_BLOWFISH_BLOCKSIZE];
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT );
BLOWFISH_VALIDATE_RET( iv != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || input != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || output != NULL );
if( length % MBEDTLS_BLOWFISH_BLOCKSIZE )
return( MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH );
@ -321,7 +339,19 @@ int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx,
unsigned char *output )
{
int c;
size_t n = *iv_off;
size_t n;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT );
BLOWFISH_VALIDATE_RET( iv != NULL );
BLOWFISH_VALIDATE_RET( iv_off != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || input != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || output != NULL );
n = *iv_off;
if( n >= 8 )
return( MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA );
if( mode == MBEDTLS_BLOWFISH_DECRYPT )
{
@ -369,7 +399,17 @@ int mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx,
unsigned char *output )
{
int c, i;
size_t n = *nc_off;
size_t n;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( nonce_counter != NULL );
BLOWFISH_VALIDATE_RET( stream_block != NULL );
BLOWFISH_VALIDATE_RET( nc_off != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || input != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || output != NULL );
n = *nc_off;
if( n >= 8 )
return( MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA );
while( length-- )
{

View File

@ -34,6 +34,7 @@
#if defined(MBEDTLS_CAMELLIA_C)
#include "mbedtls/camellia.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -48,10 +49,11 @@
#if !defined(MBEDTLS_CAMELLIA_ALT)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
}
/* Parameter validation macros */
#define CAMELLIA_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA )
#define CAMELLIA_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
/*
* 32-bit integer manipulation macros (big endian)
@ -325,6 +327,7 @@ static void camellia_feistel( const uint32_t x[2], const uint32_t k[2],
void mbedtls_camellia_init( mbedtls_camellia_context *ctx )
{
CAMELLIA_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_camellia_context ) );
}
@ -333,14 +336,15 @@ void mbedtls_camellia_free( mbedtls_camellia_context *ctx )
if( ctx == NULL )
return;
mbedtls_zeroize( ctx, sizeof( mbedtls_camellia_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_camellia_context ) );
}
/*
* Camellia key schedule (encryption)
*/
int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, const unsigned char *key,
unsigned int keybits )
int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx,
const unsigned char *key,
unsigned int keybits )
{
int idx;
size_t i;
@ -350,6 +354,9 @@ int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, const unsigned c
uint32_t KC[16];
uint32_t TK[20];
CAMELLIA_VALIDATE_RET( ctx != NULL );
CAMELLIA_VALIDATE_RET( key != NULL );
RK = ctx->rk;
memset( t, 0, 64 );
@ -360,7 +367,7 @@ int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, const unsigned c
case 128: ctx->nr = 3; idx = 0; break;
case 192:
case 256: ctx->nr = 4; idx = 1; break;
default : return( MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH );
default : return( MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA );
}
for( i = 0; i < keybits / 8; ++i )
@ -444,14 +451,17 @@ int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, const unsigned c
/*
* Camellia key schedule (decryption)
*/
int mbedtls_camellia_setkey_dec( mbedtls_camellia_context *ctx, const unsigned char *key,
unsigned int keybits )
int mbedtls_camellia_setkey_dec( mbedtls_camellia_context *ctx,
const unsigned char *key,
unsigned int keybits )
{
int idx, ret;
size_t i;
mbedtls_camellia_context cty;
uint32_t *RK;
uint32_t *SK;
CAMELLIA_VALIDATE_RET( ctx != NULL );
CAMELLIA_VALIDATE_RET( key != NULL );
mbedtls_camellia_init( &cty );
@ -499,6 +509,11 @@ int mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx,
{
int NR;
uint32_t *RK, X[4];
CAMELLIA_VALIDATE_RET( ctx != NULL );
CAMELLIA_VALIDATE_RET( mode == MBEDTLS_CAMELLIA_ENCRYPT ||
mode == MBEDTLS_CAMELLIA_DECRYPT );
CAMELLIA_VALIDATE_RET( input != NULL );
CAMELLIA_VALIDATE_RET( output != NULL );
( (void) mode );
@ -556,14 +571,20 @@ int mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx,
* Camellia-CBC buffer encryption/decryption
*/
int mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output )
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[16];
CAMELLIA_VALIDATE_RET( ctx != NULL );
CAMELLIA_VALIDATE_RET( mode == MBEDTLS_CAMELLIA_ENCRYPT ||
mode == MBEDTLS_CAMELLIA_DECRYPT );
CAMELLIA_VALIDATE_RET( iv != NULL );
CAMELLIA_VALIDATE_RET( length == 0 || input != NULL );
CAMELLIA_VALIDATE_RET( length == 0 || output != NULL );
if( length % 16 )
return( MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH );
@ -618,7 +639,18 @@ int mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx,
unsigned char *output )
{
int c;
size_t n = *iv_off;
size_t n;
CAMELLIA_VALIDATE_RET( ctx != NULL );
CAMELLIA_VALIDATE_RET( mode == MBEDTLS_CAMELLIA_ENCRYPT ||
mode == MBEDTLS_CAMELLIA_DECRYPT );
CAMELLIA_VALIDATE_RET( iv != NULL );
CAMELLIA_VALIDATE_RET( iv_off != NULL );
CAMELLIA_VALIDATE_RET( length == 0 || input != NULL );
CAMELLIA_VALIDATE_RET( length == 0 || output != NULL );
n = *iv_off;
if( n >= 16 )
return( MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA );
if( mode == MBEDTLS_CAMELLIA_DECRYPT )
{
@ -666,7 +698,17 @@ int mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx,
unsigned char *output )
{
int c, i;
size_t n = *nc_off;
size_t n;
CAMELLIA_VALIDATE_RET( ctx != NULL );
CAMELLIA_VALIDATE_RET( nonce_counter != NULL );
CAMELLIA_VALIDATE_RET( stream_block != NULL );
CAMELLIA_VALIDATE_RET( nc_off != NULL );
CAMELLIA_VALIDATE_RET( length == 0 || input != NULL );
CAMELLIA_VALIDATE_RET( length == 0 || output != NULL );
n = *nc_off;
if( n >= 16 )
return( MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA );
while( length-- )
{

View File

@ -37,6 +37,7 @@
#if defined(MBEDTLS_CCM_C)
#include "mbedtls/ccm.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -49,10 +50,12 @@
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
}
#if !defined(MBEDTLS_CCM_ALT)
#define CCM_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CCM_BAD_INPUT )
#define CCM_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1
@ -62,6 +65,7 @@ static void mbedtls_zeroize( void *v, size_t n ) {
*/
void mbedtls_ccm_init( mbedtls_ccm_context *ctx )
{
CCM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_ccm_context ) );
}
@ -73,6 +77,9 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
int ret;
const mbedtls_cipher_info_t *cipher_info;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( key != NULL );
cipher_info = mbedtls_cipher_info_from_values( cipher, keybits, MBEDTLS_MODE_ECB );
if( cipher_info == NULL )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
@ -99,8 +106,10 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
*/
void mbedtls_ccm_free( mbedtls_ccm_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_cipher_free( &ctx->cipher_ctx );
mbedtls_zeroize( ctx, sizeof( mbedtls_ccm_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) );
}
/*
@ -154,8 +163,10 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
* Check length requirements: SP800-38C A.1
* Additional requirement: a < 2^16 - 2^8 to simplify the code.
* 'length' checked later (when writing it to the first block)
*
* Also, loosen the requirements to enable support for CCM* (IEEE 802.15.4).
*/
if( tag_len < 4 || tag_len > 16 || tag_len % 2 != 0 )
if( tag_len == 2 || tag_len > 16 || tag_len % 2 != 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
/* Also implies q is within bounds */
@ -304,20 +315,45 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
/*
* Authenticated encryption
*/
int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
return( ccm_auth_crypt( ctx, CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len ) );
}
int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
return( ccm_auth_crypt( ctx, CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len ) );
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( tag_len == 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
return( mbedtls_ccm_star_encrypt_and_tag( ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len ) );
}
/*
* Authenticated decryption
*/
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
@ -328,6 +364,13 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
unsigned char i;
int diff;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( ( ret = ccm_auth_crypt( ctx, CCM_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, check_tag, tag_len ) ) != 0 )
@ -341,13 +384,33 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
if( diff != 0 )
{
mbedtls_zeroize( output, length );
mbedtls_platform_zeroize( output, length );
return( MBEDTLS_ERR_CCM_AUTH_FAILED );
}
return( 0 );
}
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( tag_len == 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
return( mbedtls_ccm_star_auth_decrypt( ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len ) );
}
#endif /* !MBEDTLS_CCM_ALT */
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/*
@ -355,7 +418,8 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
*/
#define NB_TESTS 3
#define CCM_SELFTEST_PT_MAX_LEN 24
#define CCM_SELFTEST_CT_MAX_LEN 32
/*
* The data is the same for all tests, only the used length changes
*/
@ -375,7 +439,7 @@ static const unsigned char ad[] = {
0x10, 0x11, 0x12, 0x13
};
static const unsigned char msg[] = {
static const unsigned char msg[CCM_SELFTEST_PT_MAX_LEN] = {
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
@ -386,7 +450,7 @@ static const size_t add_len[NB_TESTS] = { 8, 16, 20 };
static const size_t msg_len[NB_TESTS] = { 4, 16, 24 };
static const size_t tag_len[NB_TESTS] = { 4, 6, 8 };
static const unsigned char res[NB_TESTS][32] = {
static const unsigned char res[NB_TESTS][CCM_SELFTEST_CT_MAX_LEN] = {
{ 0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d },
{ 0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62,
0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d,
@ -400,7 +464,13 @@ static const unsigned char res[NB_TESTS][32] = {
int mbedtls_ccm_self_test( int verbose )
{
mbedtls_ccm_context ctx;
unsigned char out[32];
/*
* Some hardware accelerators require the input and output buffers
* would be in RAM, because the flash is not accessible.
* Use buffers on the stack to hold the test vectors data.
*/
unsigned char plaintext[CCM_SELFTEST_PT_MAX_LEN];
unsigned char ciphertext[CCM_SELFTEST_CT_MAX_LEN];
size_t i;
int ret;
@ -419,27 +489,32 @@ int mbedtls_ccm_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( " CCM-AES #%u: ", (unsigned int) i + 1 );
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
memset( ciphertext, 0, CCM_SELFTEST_CT_MAX_LEN );
memcpy( plaintext, msg, msg_len[i] );
ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len[i],
iv, iv_len[i], ad, add_len[i],
msg, out,
out + msg_len[i], tag_len[i] );
iv, iv_len[i], ad, add_len[i],
plaintext, ciphertext,
ciphertext + msg_len[i], tag_len[i] );
if( ret != 0 ||
memcmp( out, res[i], msg_len[i] + tag_len[i] ) != 0 )
memcmp( ciphertext, res[i], msg_len[i] + tag_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len[i],
iv, iv_len[i], ad, add_len[i],
res[i], out,
res[i] + msg_len[i], tag_len[i] );
iv, iv_len[i], ad, add_len[i],
ciphertext, plaintext,
ciphertext + msg_len[i], tag_len[i] );
if( ret != 0 ||
memcmp( out, msg, msg_len[i] ) != 0 )
memcmp( plaintext, msg, msg_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );

View File

@ -47,6 +47,7 @@
"uCjn8pwUOkABXK8Mss90fzCfCEOtIA==\r\n" \
"-----END CERTIFICATE-----\r\n"
const char mbedtls_test_ca_crt_ec[] = TEST_CA_CRT_EC;
const size_t mbedtls_test_ca_crt_ec_len = sizeof( mbedtls_test_ca_crt_ec );
const char mbedtls_test_ca_key_ec[] =
"-----BEGIN EC PRIVATE KEY-----\r\n"
@ -58,8 +59,10 @@ const char mbedtls_test_ca_key_ec[] =
"UsuWTITwJImcnlAs1gaRZ3sAWm7cOUidL0fo2G0fYUFNcYoCSLffCFTEHBuPnagb\r\n"
"a77x/sY1Bvii8S9/XhDTb6pTMx06wzrm\r\n"
"-----END EC PRIVATE KEY-----\r\n";
const size_t mbedtls_test_ca_key_ec_len = sizeof( mbedtls_test_ca_key_ec );
const char mbedtls_test_ca_pwd_ec[] = "PolarSSLTest";
const size_t mbedtls_test_ca_pwd_ec_len = sizeof( mbedtls_test_ca_pwd_ec ) - 1;
const char mbedtls_test_srv_crt_ec[] =
"-----BEGIN CERTIFICATE-----\r\n"
@ -76,6 +79,7 @@ const char mbedtls_test_srv_crt_ec[] =
"C12r0Lz3ri/moSEpNZWqPjkCMCE2f53GXcYLqyfyJR078c/xNSUU5+Xxl7VZ414V\r\n"
"fGa5kHvHARBPc8YAIVIqDvHH1Q==\r\n"
"-----END CERTIFICATE-----\r\n";
const size_t mbedtls_test_srv_crt_ec_len = sizeof( mbedtls_test_srv_crt_ec );
const char mbedtls_test_srv_key_ec[] =
"-----BEGIN EC PRIVATE KEY-----\r\n"
@ -83,6 +87,7 @@ const char mbedtls_test_srv_key_ec[] =
"AwEHoUQDQgAEN8xW2XYJHlpyPsdZLf8gbu58+QaRdNCtFLX3aCJZYpJO5QDYIxH/\r\n"
"6i/SNF1dFr2KiMJrdw1VzYoqDvoByLTt/w==\r\n"
"-----END EC PRIVATE KEY-----\r\n";
const size_t mbedtls_test_srv_key_ec_len = sizeof( mbedtls_test_srv_key_ec );
const char mbedtls_test_cli_crt_ec[] =
"-----BEGIN CERTIFICATE-----\r\n"
@ -99,6 +104,7 @@ const char mbedtls_test_cli_crt_ec[] =
"lgOsjnhw3fIOoLIWy2WOGsk/LGF++DzvrRzuNiACMQCd8iem1XS4JK7haj8xocpU\r\n"
"LwjQje5PDGHfd3h9tP38Qknu5bJqws0md2KOKHyeV0U=\r\n"
"-----END CERTIFICATE-----\r\n";
const size_t mbedtls_test_cli_crt_ec_len = sizeof( mbedtls_test_cli_crt_ec );
const char mbedtls_test_cli_key_ec[] =
"-----BEGIN EC PRIVATE KEY-----\r\n"
@ -106,20 +112,45 @@ const char mbedtls_test_cli_key_ec[] =
"AwEHoUQDQgAEV+WusXPf06y7k7iB/xKu7uZTrM5VU/Y0Dswu42MlC9+Y4vNcYDaW\r\n"
"wNUYFHDlf5/VS0UY5bBs1Vz4lo+HcKPkxw==\r\n"
"-----END EC PRIVATE KEY-----\r\n";
const size_t mbedtls_test_ca_crt_ec_len = sizeof( mbedtls_test_ca_crt_ec );
const size_t mbedtls_test_ca_key_ec_len = sizeof( mbedtls_test_ca_key_ec );
const size_t mbedtls_test_ca_pwd_ec_len = sizeof( mbedtls_test_ca_pwd_ec ) - 1;
const size_t mbedtls_test_srv_crt_ec_len = sizeof( mbedtls_test_srv_crt_ec );
const size_t mbedtls_test_srv_key_ec_len = sizeof( mbedtls_test_srv_key_ec );
const size_t mbedtls_test_cli_crt_ec_len = sizeof( mbedtls_test_cli_crt_ec );
const size_t mbedtls_test_cli_key_ec_len = sizeof( mbedtls_test_cli_key_ec );
#else
#define TEST_CA_CRT_EC
#endif /* MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_RSA_C)
#define TEST_CA_CRT_RSA \
#if defined(MBEDTLS_SHA256_C)
#define TEST_CA_CRT_RSA_SHA256 \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDhzCCAm+gAwIBAgIBADANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTcwNTA0MTY1NzAxWhcNMjcwNTA1MTY1NzAxWjA7MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\r\n" \
"CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\r\n" \
"mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\r\n" \
"50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\r\n" \
"YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\r\n" \
"R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\r\n" \
"KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\r\n" \
"gZUwgZIwHQYDVR0OBBYEFLRa5KWz3tJS9rnVppUP6z68x/3/MGMGA1UdIwRcMFqA\r\n" \
"FLRa5KWz3tJS9rnVppUP6z68x/3/oT+kPTA7MQswCQYDVQQGEwJOTDERMA8GA1UE\r\n" \
"CgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0GCAQAwDAYDVR0T\r\n" \
"BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAHK/HHrTZMnnVMpde1io+voAtql7j\r\n" \
"4sRhLrjD7o3THtwRbDa2diCvpq0Sq23Ng2LMYoXsOxoL/RQK3iN7UKxV3MKPEr0w\r\n" \
"XQS+kKQqiT2bsfrjnWMVHZtUOMpm6FNqcdGm/Rss3vKda2lcKl8kUnq/ylc1+QbB\r\n" \
"G6A6tUvQcr2ZyWfVg+mM5XkhTrOOXus2OLikb4WwEtJTJRNE0f+yPODSUz0/vT57\r\n" \
"ApH0CnB80bYJshYHPHHymOtleAB8KSYtqm75g/YNobjnjB6cm4HkW3OZRVIl6fYY\r\n" \
"n20NRVA1Vjs6GAROr4NqW4k/+LofY9y0LLDE+p0oIEKXIsIvhPr39swxSA==\r\n" \
"-----END CERTIFICATE-----\r\n"
const char mbedtls_test_ca_crt_rsa[] = TEST_CA_CRT_RSA_SHA256;
const size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa );
#define TEST_CA_CRT_RSA_SOME
static const char mbedtls_test_ca_crt_rsa_sha256[] = TEST_CA_CRT_RSA_SHA256;
#endif
#if !defined(TEST_CA_CRT_RSA_SOME) || defined(MBEDTLS_SHA1_C)
#define TEST_CA_CRT_RSA_SHA1 \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDhzCCAm+gAwIBAgIBADANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
@ -141,7 +172,15 @@ const size_t mbedtls_test_cli_key_ec_len = sizeof( mbedtls_test_cli_key_ec );
"m/UTSLBNFNHesiTZeH31NcxYGdHSme9Nc/gfidRa0FLOCfWxRlFqAI47zG9jAQCZ\r\n" \
"7Z2mCGDNMhjQc+BYcdnl0lPXjdDK6V0qCg1dVewhUBcW5gZKzV7e9+DpVA==\r\n" \
"-----END CERTIFICATE-----\r\n"
const char mbedtls_test_ca_crt_rsa[] = TEST_CA_CRT_RSA;
#if !defined (TEST_CA_CRT_RSA_SOME)
const char mbedtls_test_ca_crt_rsa[] = TEST_CA_CRT_RSA_SHA1;
const size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa );
#endif
static const char mbedtls_test_ca_crt_rsa_sha1[] = TEST_CA_CRT_RSA_SHA1;
#endif
const char mbedtls_test_ca_key_rsa[] =
"-----BEGIN RSA PRIVATE KEY-----\r\n"
@ -174,15 +213,18 @@ const char mbedtls_test_ca_key_rsa[] =
"wN48lslbHnqqagr6Xm1nNOSVl8C/6kbJEsMpLhAezfRtGwvOucoaE+WbeUNolGde\r\n"
"P/eQiddSf0brnpiLJRh7qZrl9XuqYdpUqnoEdMAfotDOID8OtV7gt8a48ad8VPW2\r\n"
"-----END RSA PRIVATE KEY-----\r\n";
const size_t mbedtls_test_ca_key_rsa_len = sizeof( mbedtls_test_ca_key_rsa );
const char mbedtls_test_ca_pwd_rsa[] = "PolarSSLTest";
const size_t mbedtls_test_ca_pwd_rsa_len = sizeof( mbedtls_test_ca_pwd_rsa ) - 1;
/* tests/data_files/server2.crt */
const char mbedtls_test_srv_crt_rsa[] =
"-----BEGIN CERTIFICATE-----\r\n"
"MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n"
"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n"
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n"
"MTEwMjEyMTQ0NDA2WhcNMjEwMjEyMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n"
"A1UEChMIUG9sYXJTU0wxEjAQBgNVBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n"
"A1UECgwIUG9sYXJTU0wxEjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n"
"AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\r\n"
"owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\r\n"
"NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\r\n"
@ -190,15 +232,17 @@ const char mbedtls_test_srv_crt_rsa[] =
"hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\r\n"
"HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\r\n"
"VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\r\n"
"FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAJxnXClY\r\n"
"oHkbp70cqBrsGXLybA74czbO5RdLEgFs7rHVS9r+c293luS/KdliLScZqAzYVylw\r\n"
"UfRWvKMoWhHYKp3dEIS4xTXk6/5zXxhv9Rw8SGc8qn6vITHk1S1mPevtekgasY5Y\r\n"
"iWQuM3h4YVlRH3HHEMAD1TnAexfXHHDFQGe+Bd1iAbz1/sH9H8l4StwX6egvTK3M\r\n"
"wXRwkKkvjKaEDA9ATbZx0mI8LGsxSuCqe9r9dyjmttd47J1p1Rulz3CLzaRcVIuS\r\n"
"RRQfaD8neM9c1S/iJ/amTVqJxA1KOdOS5780WhPfSArA+g4qAmSjelc3p4wWpha8\r\n"
"zhuYwjVuX6JHG0c=\r\n"
"FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAAFzC0rF\r\n"
"y6De8WMcdgQrEw3AhBHFjzqnxZw1ene4IBSC7lTw8rBSy3jOWQdPUWn+0y/pCeeF\r\n"
"kti6sevFdl1hLemGtd4q+T9TKEKGg3ND4ARfB5AUZZ9uEHq8WBkiwus5clGS17Qd\r\n"
"dS/TOisB59tQruLx1E1bPLtBKyqk4koC5WAULJwfpswGSyWJTpYwIpxcWE3D2tBu\r\n"
"UB6MZfXZFzWmWEOyKbeoXjXe8GBCGgHLywvYDsGQ36HSGtEsAvR2QaTLSxWYcfk1\r\n"
"fbDn4jSWkb4yZy1r01UEigFQtONieGwRFaUqEcFJHJvEEGVgh9keaVlOj2vrwf5r\r\n"
"4mN4lW7gLdenN6g=\r\n"
"-----END CERTIFICATE-----\r\n";
const size_t mbedtls_test_srv_crt_rsa_len = sizeof( mbedtls_test_srv_crt_rsa );
/* tests/data_files/server2.key */
const char mbedtls_test_srv_key_rsa[] =
"-----BEGIN RSA PRIVATE KEY-----\r\n"
"MIIEpAIBAAKCAQEAwU2j3efNHdEE10lyuJmsDnjkOjxKzzoTFtBa5M2jAIin7h5r\r\n"
@ -227,13 +271,15 @@ const char mbedtls_test_srv_key_rsa[] =
"4AgahOxIxXx2gxJnq3yfkJfIjwf0s2DyP0kY2y6Ua1OeomPeY9mrIS4tCuDQ6LrE\r\n"
"TB6l9VGoxJL4fyHnZb8L5gGvnB1bbD8cL6YPaDiOhcRseC9vBiEuVg==\r\n"
"-----END RSA PRIVATE KEY-----\r\n";
const size_t mbedtls_test_srv_key_rsa_len = sizeof( mbedtls_test_srv_key_rsa );
/* tests/data_files/cli-rsa-sha256.crt */
const char mbedtls_test_cli_crt_rsa[] =
"-----BEGIN CERTIFICATE-----\r\n"
"MIIDPzCCAiegAwIBAgIBBDANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n"
"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n"
"MTEwMjEyMTQ0NDA3WhcNMjEwMjEyMTQ0NDA3WjA8MQswCQYDVQQGEwJOTDERMA8G\r\n"
"A1UEChMIUG9sYXJTU0wxGjAYBgNVBAMTEVBvbGFyU1NMIENsaWVudCAyMIIBIjAN\r\n"
"MIIDPzCCAiegAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n"
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n"
"MTEwMjEyMTQ0NDA2WhcNMjEwMjEyMTQ0NDA2WjA8MQswCQYDVQQGEwJOTDERMA8G\r\n"
"A1UECgwIUG9sYXJTU0wxGjAYBgNVBAMMEVBvbGFyU1NMIENsaWVudCAyMIIBIjAN\r\n"
"BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6f\r\n"
"M60Nj4o8VmXl3ETZzGaFB9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu\r\n"
"1C93KYRhTYJQj6eVSHD1bk2y1RPD0hrt5kPqQhTrdOrA7R/UV06p86jt0uDBMHEw\r\n"
@ -241,15 +287,17 @@ const char mbedtls_test_cli_crt_rsa[] =
"4Jv4EFbMs44TFeY0BGbH7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx/\r\n"
"/DZrtenNLQNiTrM9AM+vdqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQAB\r\n"
"o00wSzAJBgNVHRMEAjAAMB0GA1UdDgQWBBRxoQBzckAvVHZeM/xSj7zx3WtGITAf\r\n"
"BgNVHSMEGDAWgBS0WuSls97SUva51aaVD+s+vMf9/zANBgkqhkiG9w0BAQUFAAOC\r\n"
"AQEAAn86isAM8X+mVwJqeItt6E9slhEQbAofyk+diH1Lh8Y9iLlWQSKbw/UXYjx5\r\n"
"LLPZcniovxIcARC/BjyZR9g3UwTHNGNm+rwrqa15viuNOFBchykX/Orsk02EH7NR\r\n"
"Alw5WLPorYjED6cdVQgBl9ot93HdJogRiXCxErM7NC8/eP511mjq+uLDjLKH8ZPQ\r\n"
"8I4ekHJnroLsDkIwXKGIsvIBHQy2ac/NwHLCQOK6mfum1pRx52V4Utu5dLLjD5bM\r\n"
"xOBC7KU4xZKuMXXZM6/93Yb51K/J4ahf1TxJlTWXtnzDr9saEYdNy2SKY/6ZiDNH\r\n"
"D+stpAKiQLAWaAusIWKYEyw9MQ==\r\n"
"BgNVHSMEGDAWgBS0WuSls97SUva51aaVD+s+vMf9/zANBgkqhkiG9w0BAQsFAAOC\r\n"
"AQEAlHabem2Tu69VUN7EipwnQn1dIHdgvT5i+iQHpSxY1crPnBbAeSdAXwsVEqLQ\r\n"
"gOOIAQD5VIITNuoGgo4i+4OpNh9u7ZkpRHla+/swsfrFWRRbBNP5Bcu74AGLstwU\r\n"
"zM8gIkBiyfM1Q1qDQISV9trlCG6O8vh8dp/rbI3rfzo99BOHXgFCrzXjCuW4vDsF\r\n"
"r+Dao26bX3sJ6UnEWg1H3o2x6PpUcvQ36h71/bz4TEbbUUEpe02V4QWuL+wrhHJL\r\n"
"U7o3SVE3Og7jPF8sat0a50YUWhwEFI256m02KAXLg89ueUyYKEr6rNwhcvXJpvU9\r\n"
"giIVvd0Sbjjnn7NC4VDbcXV8vw==\r\n"
"-----END CERTIFICATE-----\r\n";
const size_t mbedtls_test_cli_crt_rsa_len = sizeof( mbedtls_test_cli_crt_rsa );
/* tests/data_files/cli-rsa.key */
const char mbedtls_test_cli_key_rsa[] =
"-----BEGIN RSA PRIVATE KEY-----\r\n"
"MIIEpAIBAAKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6fM60Nj4o8VmXl3ETZzGaF\r\n"
@ -278,28 +326,32 @@ const char mbedtls_test_cli_key_rsa[] =
"bHFVW2r0dBTqegP2/KTOxKzaHfC1qf0RGDsUoJCNJrd1cwoCLG8P2EF4w3OBrKqv\r\n"
"8u4ytY0F+Vlanj5lm3TaoHSVF1+NWPyOTiwevIECGKwSxvlki4fDAA==\r\n"
"-----END RSA PRIVATE KEY-----\r\n";
const size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa );
const size_t mbedtls_test_ca_key_rsa_len = sizeof( mbedtls_test_ca_key_rsa );
const size_t mbedtls_test_ca_pwd_rsa_len = sizeof( mbedtls_test_ca_pwd_rsa ) - 1;
const size_t mbedtls_test_srv_crt_rsa_len = sizeof( mbedtls_test_srv_crt_rsa );
const size_t mbedtls_test_srv_key_rsa_len = sizeof( mbedtls_test_srv_key_rsa );
const size_t mbedtls_test_cli_crt_rsa_len = sizeof( mbedtls_test_cli_crt_rsa );
const size_t mbedtls_test_cli_key_rsa_len = sizeof( mbedtls_test_cli_key_rsa );
#else
#define TEST_CA_CRT_RSA
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_PEM_PARSE_C)
/* Concatenation of all available CA certificates */
const char mbedtls_test_cas_pem[] = TEST_CA_CRT_RSA TEST_CA_CRT_EC;
const char mbedtls_test_cas_pem[] =
#ifdef TEST_CA_CRT_RSA_SHA1
TEST_CA_CRT_RSA_SHA1
#endif
#ifdef TEST_CA_CRT_RSA_SHA256
TEST_CA_CRT_RSA_SHA256
#endif
#ifdef TEST_CA_CRT_EC
TEST_CA_CRT_EC
#endif
"";
const size_t mbedtls_test_cas_pem_len = sizeof( mbedtls_test_cas_pem );
#endif
/* List of all available CA certificates */
const char * mbedtls_test_cas[] = {
#if defined(MBEDTLS_RSA_C)
mbedtls_test_ca_crt_rsa,
#if defined(TEST_CA_CRT_RSA_SHA1)
mbedtls_test_ca_crt_rsa_sha1,
#endif
#if defined(TEST_CA_CRT_RSA_SHA256)
mbedtls_test_ca_crt_rsa_sha256,
#endif
#if defined(MBEDTLS_ECDSA_C)
mbedtls_test_ca_crt_ec,
@ -307,8 +359,11 @@ const char * mbedtls_test_cas[] = {
NULL
};
const size_t mbedtls_test_cas_len[] = {
#if defined(MBEDTLS_RSA_C)
sizeof( mbedtls_test_ca_crt_rsa ),
#if defined(TEST_CA_CRT_RSA_SHA1)
sizeof( mbedtls_test_ca_crt_rsa_sha1 ),
#endif
#if defined(TEST_CA_CRT_RSA_SHA256)
sizeof( mbedtls_test_ca_crt_rsa_sha256 ),
#endif
#if defined(MBEDTLS_ECDSA_C)
sizeof( mbedtls_test_ca_crt_ec ),
@ -317,7 +372,7 @@ const size_t mbedtls_test_cas_len[] = {
};
#if defined(MBEDTLS_RSA_C)
const char *mbedtls_test_ca_crt = mbedtls_test_ca_crt_rsa;
const char *mbedtls_test_ca_crt = mbedtls_test_ca_crt_rsa; /* SHA1 or SHA256 */
const char *mbedtls_test_ca_key = mbedtls_test_ca_key_rsa;
const char *mbedtls_test_ca_pwd = mbedtls_test_ca_pwd_rsa;
const char *mbedtls_test_srv_crt = mbedtls_test_srv_crt_rsa;

570
Externals/mbedtls/library/chacha20.c vendored Normal file
View File

@ -0,0 +1,570 @@
/**
* \file chacha20.c
*
* \brief ChaCha20 cipher.
*
* \author Daniel King <damaki.gh@gmail.com>
*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_CHACHA20_C)
#include "mbedtls/chacha20.h"
#include "mbedtls/platform_util.h"
#include <stddef.h>
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_CHACHA20_ALT)
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
#endif
/* Parameter validation macros */
#define CHACHA20_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA )
#define CHACHA20_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define BYTES_TO_U32_LE( data, offset ) \
( (uint32_t) data[offset] \
| (uint32_t) ( (uint32_t) data[( offset ) + 1] << 8 ) \
| (uint32_t) ( (uint32_t) data[( offset ) + 2] << 16 ) \
| (uint32_t) ( (uint32_t) data[( offset ) + 3] << 24 ) \
)
#define ROTL32( value, amount ) \
( (uint32_t) ( value << amount ) | ( value >> ( 32 - amount ) ) )
#define CHACHA20_CTR_INDEX ( 12U )
#define CHACHA20_BLOCK_SIZE_BYTES ( 4U * 16U )
/**
* \brief ChaCha20 quarter round operation.
*
* The quarter round is defined as follows (from RFC 7539):
* 1. a += b; d ^= a; d <<<= 16;
* 2. c += d; b ^= c; b <<<= 12;
* 3. a += b; d ^= a; d <<<= 8;
* 4. c += d; b ^= c; b <<<= 7;
*
* \param state ChaCha20 state to modify.
* \param a The index of 'a' in the state.
* \param b The index of 'b' in the state.
* \param c The index of 'c' in the state.
* \param d The index of 'd' in the state.
*/
static inline void chacha20_quarter_round( uint32_t state[16],
size_t a,
size_t b,
size_t c,
size_t d )
{
/* a += b; d ^= a; d <<<= 16; */
state[a] += state[b];
state[d] ^= state[a];
state[d] = ROTL32( state[d], 16 );
/* c += d; b ^= c; b <<<= 12 */
state[c] += state[d];
state[b] ^= state[c];
state[b] = ROTL32( state[b], 12 );
/* a += b; d ^= a; d <<<= 8; */
state[a] += state[b];
state[d] ^= state[a];
state[d] = ROTL32( state[d], 8 );
/* c += d; b ^= c; b <<<= 7; */
state[c] += state[d];
state[b] ^= state[c];
state[b] = ROTL32( state[b], 7 );
}
/**
* \brief Perform the ChaCha20 inner block operation.
*
* This function performs two rounds: the column round and the
* diagonal round.
*
* \param state The ChaCha20 state to update.
*/
static void chacha20_inner_block( uint32_t state[16] )
{
chacha20_quarter_round( state, 0, 4, 8, 12 );
chacha20_quarter_round( state, 1, 5, 9, 13 );
chacha20_quarter_round( state, 2, 6, 10, 14 );
chacha20_quarter_round( state, 3, 7, 11, 15 );
chacha20_quarter_round( state, 0, 5, 10, 15 );
chacha20_quarter_round( state, 1, 6, 11, 12 );
chacha20_quarter_round( state, 2, 7, 8, 13 );
chacha20_quarter_round( state, 3, 4, 9, 14 );
}
/**
* \brief Generates a keystream block.
*
* \param initial_state The initial ChaCha20 state (key, nonce, counter).
* \param keystream Generated keystream bytes are written to this buffer.
*/
static void chacha20_block( const uint32_t initial_state[16],
unsigned char keystream[64] )
{
uint32_t working_state[16];
size_t i;
memcpy( working_state,
initial_state,
CHACHA20_BLOCK_SIZE_BYTES );
for( i = 0U; i < 10U; i++ )
chacha20_inner_block( working_state );
working_state[ 0] += initial_state[ 0];
working_state[ 1] += initial_state[ 1];
working_state[ 2] += initial_state[ 2];
working_state[ 3] += initial_state[ 3];
working_state[ 4] += initial_state[ 4];
working_state[ 5] += initial_state[ 5];
working_state[ 6] += initial_state[ 6];
working_state[ 7] += initial_state[ 7];
working_state[ 8] += initial_state[ 8];
working_state[ 9] += initial_state[ 9];
working_state[10] += initial_state[10];
working_state[11] += initial_state[11];
working_state[12] += initial_state[12];
working_state[13] += initial_state[13];
working_state[14] += initial_state[14];
working_state[15] += initial_state[15];
for( i = 0U; i < 16; i++ )
{
size_t offset = i * 4U;
keystream[offset ] = (unsigned char)( working_state[i] );
keystream[offset + 1U] = (unsigned char)( working_state[i] >> 8 );
keystream[offset + 2U] = (unsigned char)( working_state[i] >> 16 );
keystream[offset + 3U] = (unsigned char)( working_state[i] >> 24 );
}
mbedtls_platform_zeroize( working_state, sizeof( working_state ) );
}
void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx )
{
CHACHA20_VALIDATE( ctx != NULL );
mbedtls_platform_zeroize( ctx->state, sizeof( ctx->state ) );
mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) );
/* Initially, there's no keystream bytes available */
ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES;
}
void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx )
{
if( ctx != NULL )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_chacha20_context ) );
}
}
int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx,
const unsigned char key[32] )
{
CHACHA20_VALIDATE_RET( ctx != NULL );
CHACHA20_VALIDATE_RET( key != NULL );
/* ChaCha20 constants - the string "expand 32-byte k" */
ctx->state[0] = 0x61707865;
ctx->state[1] = 0x3320646e;
ctx->state[2] = 0x79622d32;
ctx->state[3] = 0x6b206574;
/* Set key */
ctx->state[4] = BYTES_TO_U32_LE( key, 0 );
ctx->state[5] = BYTES_TO_U32_LE( key, 4 );
ctx->state[6] = BYTES_TO_U32_LE( key, 8 );
ctx->state[7] = BYTES_TO_U32_LE( key, 12 );
ctx->state[8] = BYTES_TO_U32_LE( key, 16 );
ctx->state[9] = BYTES_TO_U32_LE( key, 20 );
ctx->state[10] = BYTES_TO_U32_LE( key, 24 );
ctx->state[11] = BYTES_TO_U32_LE( key, 28 );
return( 0 );
}
int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx,
const unsigned char nonce[12],
uint32_t counter )
{
CHACHA20_VALIDATE_RET( ctx != NULL );
CHACHA20_VALIDATE_RET( nonce != NULL );
/* Counter */
ctx->state[12] = counter;
/* Nonce */
ctx->state[13] = BYTES_TO_U32_LE( nonce, 0 );
ctx->state[14] = BYTES_TO_U32_LE( nonce, 4 );
ctx->state[15] = BYTES_TO_U32_LE( nonce, 8 );
mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) );
/* Initially, there's no keystream bytes available */
ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES;
return( 0 );
}
int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,
size_t size,
const unsigned char *input,
unsigned char *output )
{
size_t offset = 0U;
size_t i;
CHACHA20_VALIDATE_RET( ctx != NULL );
CHACHA20_VALIDATE_RET( size == 0 || input != NULL );
CHACHA20_VALIDATE_RET( size == 0 || output != NULL );
/* Use leftover keystream bytes, if available */
while( size > 0U && ctx->keystream_bytes_used < CHACHA20_BLOCK_SIZE_BYTES )
{
output[offset] = input[offset]
^ ctx->keystream8[ctx->keystream_bytes_used];
ctx->keystream_bytes_used++;
offset++;
size--;
}
/* Process full blocks */
while( size >= CHACHA20_BLOCK_SIZE_BYTES )
{
/* Generate new keystream block and increment counter */
chacha20_block( ctx->state, ctx->keystream8 );
ctx->state[CHACHA20_CTR_INDEX]++;
for( i = 0U; i < 64U; i += 8U )
{
output[offset + i ] = input[offset + i ] ^ ctx->keystream8[i ];
output[offset + i+1] = input[offset + i+1] ^ ctx->keystream8[i+1];
output[offset + i+2] = input[offset + i+2] ^ ctx->keystream8[i+2];
output[offset + i+3] = input[offset + i+3] ^ ctx->keystream8[i+3];
output[offset + i+4] = input[offset + i+4] ^ ctx->keystream8[i+4];
output[offset + i+5] = input[offset + i+5] ^ ctx->keystream8[i+5];
output[offset + i+6] = input[offset + i+6] ^ ctx->keystream8[i+6];
output[offset + i+7] = input[offset + i+7] ^ ctx->keystream8[i+7];
}
offset += CHACHA20_BLOCK_SIZE_BYTES;
size -= CHACHA20_BLOCK_SIZE_BYTES;
}
/* Last (partial) block */
if( size > 0U )
{
/* Generate new keystream block and increment counter */
chacha20_block( ctx->state, ctx->keystream8 );
ctx->state[CHACHA20_CTR_INDEX]++;
for( i = 0U; i < size; i++)
{
output[offset + i] = input[offset + i] ^ ctx->keystream8[i];
}
ctx->keystream_bytes_used = size;
}
return( 0 );
}
int mbedtls_chacha20_crypt( const unsigned char key[32],
const unsigned char nonce[12],
uint32_t counter,
size_t data_len,
const unsigned char* input,
unsigned char* output )
{
mbedtls_chacha20_context ctx;
int ret;
CHACHA20_VALIDATE_RET( key != NULL );
CHACHA20_VALIDATE_RET( nonce != NULL );
CHACHA20_VALIDATE_RET( data_len == 0 || input != NULL );
CHACHA20_VALIDATE_RET( data_len == 0 || output != NULL );
mbedtls_chacha20_init( &ctx );
ret = mbedtls_chacha20_setkey( &ctx, key );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chacha20_starts( &ctx, nonce, counter );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chacha20_update( &ctx, data_len, input, output );
cleanup:
mbedtls_chacha20_free( &ctx );
return( ret );
}
#endif /* !MBEDTLS_CHACHA20_ALT */
#if defined(MBEDTLS_SELF_TEST)
static const unsigned char test_keys[2][32] =
{
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
},
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
}
};
static const unsigned char test_nonces[2][12] =
{
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
},
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02
}
};
static const uint32_t test_counters[2] =
{
0U,
1U
};
static const unsigned char test_input[2][375] =
{
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
},
{
0x41, 0x6e, 0x79, 0x20, 0x73, 0x75, 0x62, 0x6d,
0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x74,
0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x49, 0x45,
0x54, 0x46, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6e,
0x64, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74,
0x68, 0x65, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72,
0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x66,
0x6f, 0x72, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69,
0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61,
0x73, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x6f, 0x72,
0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66,
0x20, 0x61, 0x6e, 0x20, 0x49, 0x45, 0x54, 0x46,
0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65,
0x74, 0x2d, 0x44, 0x72, 0x61, 0x66, 0x74, 0x20,
0x6f, 0x72, 0x20, 0x52, 0x46, 0x43, 0x20, 0x61,
0x6e, 0x64, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x73,
0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e, 0x74,
0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x77, 0x69,
0x74, 0x68, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65,
0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74,
0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x20, 0x49,
0x45, 0x54, 0x46, 0x20, 0x61, 0x63, 0x74, 0x69,
0x76, 0x69, 0x74, 0x79, 0x20, 0x69, 0x73, 0x20,
0x63, 0x6f, 0x6e, 0x73, 0x69, 0x64, 0x65, 0x72,
0x65, 0x64, 0x20, 0x61, 0x6e, 0x20, 0x22, 0x49,
0x45, 0x54, 0x46, 0x20, 0x43, 0x6f, 0x6e, 0x74,
0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e,
0x22, 0x2e, 0x20, 0x53, 0x75, 0x63, 0x68, 0x20,
0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e,
0x74, 0x73, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75,
0x64, 0x65, 0x20, 0x6f, 0x72, 0x61, 0x6c, 0x20,
0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e,
0x74, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x49, 0x45,
0x54, 0x46, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69,
0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x61, 0x73, 0x20,
0x77, 0x65, 0x6c, 0x6c, 0x20, 0x61, 0x73, 0x20,
0x77, 0x72, 0x69, 0x74, 0x74, 0x65, 0x6e, 0x20,
0x61, 0x6e, 0x64, 0x20, 0x65, 0x6c, 0x65, 0x63,
0x74, 0x72, 0x6f, 0x6e, 0x69, 0x63, 0x20, 0x63,
0x6f, 0x6d, 0x6d, 0x75, 0x6e, 0x69, 0x63, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6d, 0x61,
0x64, 0x65, 0x20, 0x61, 0x74, 0x20, 0x61, 0x6e,
0x79, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x6f,
0x72, 0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x2c,
0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x61,
0x72, 0x65, 0x20, 0x61, 0x64, 0x64, 0x72, 0x65,
0x73, 0x73, 0x65, 0x64, 0x20, 0x74, 0x6f
}
};
static const unsigned char test_output[2][375] =
{
{
0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90,
0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28,
0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a,
0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7,
0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d,
0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37,
0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c,
0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86
},
{
0xa3, 0xfb, 0xf0, 0x7d, 0xf3, 0xfa, 0x2f, 0xde,
0x4f, 0x37, 0x6c, 0xa2, 0x3e, 0x82, 0x73, 0x70,
0x41, 0x60, 0x5d, 0x9f, 0x4f, 0x4f, 0x57, 0xbd,
0x8c, 0xff, 0x2c, 0x1d, 0x4b, 0x79, 0x55, 0xec,
0x2a, 0x97, 0x94, 0x8b, 0xd3, 0x72, 0x29, 0x15,
0xc8, 0xf3, 0xd3, 0x37, 0xf7, 0xd3, 0x70, 0x05,
0x0e, 0x9e, 0x96, 0xd6, 0x47, 0xb7, 0xc3, 0x9f,
0x56, 0xe0, 0x31, 0xca, 0x5e, 0xb6, 0x25, 0x0d,
0x40, 0x42, 0xe0, 0x27, 0x85, 0xec, 0xec, 0xfa,
0x4b, 0x4b, 0xb5, 0xe8, 0xea, 0xd0, 0x44, 0x0e,
0x20, 0xb6, 0xe8, 0xdb, 0x09, 0xd8, 0x81, 0xa7,
0xc6, 0x13, 0x2f, 0x42, 0x0e, 0x52, 0x79, 0x50,
0x42, 0xbd, 0xfa, 0x77, 0x73, 0xd8, 0xa9, 0x05,
0x14, 0x47, 0xb3, 0x29, 0x1c, 0xe1, 0x41, 0x1c,
0x68, 0x04, 0x65, 0x55, 0x2a, 0xa6, 0xc4, 0x05,
0xb7, 0x76, 0x4d, 0x5e, 0x87, 0xbe, 0xa8, 0x5a,
0xd0, 0x0f, 0x84, 0x49, 0xed, 0x8f, 0x72, 0xd0,
0xd6, 0x62, 0xab, 0x05, 0x26, 0x91, 0xca, 0x66,
0x42, 0x4b, 0xc8, 0x6d, 0x2d, 0xf8, 0x0e, 0xa4,
0x1f, 0x43, 0xab, 0xf9, 0x37, 0xd3, 0x25, 0x9d,
0xc4, 0xb2, 0xd0, 0xdf, 0xb4, 0x8a, 0x6c, 0x91,
0x39, 0xdd, 0xd7, 0xf7, 0x69, 0x66, 0xe9, 0x28,
0xe6, 0x35, 0x55, 0x3b, 0xa7, 0x6c, 0x5c, 0x87,
0x9d, 0x7b, 0x35, 0xd4, 0x9e, 0xb2, 0xe6, 0x2b,
0x08, 0x71, 0xcd, 0xac, 0x63, 0x89, 0x39, 0xe2,
0x5e, 0x8a, 0x1e, 0x0e, 0xf9, 0xd5, 0x28, 0x0f,
0xa8, 0xca, 0x32, 0x8b, 0x35, 0x1c, 0x3c, 0x76,
0x59, 0x89, 0xcb, 0xcf, 0x3d, 0xaa, 0x8b, 0x6c,
0xcc, 0x3a, 0xaf, 0x9f, 0x39, 0x79, 0xc9, 0x2b,
0x37, 0x20, 0xfc, 0x88, 0xdc, 0x95, 0xed, 0x84,
0xa1, 0xbe, 0x05, 0x9c, 0x64, 0x99, 0xb9, 0xfd,
0xa2, 0x36, 0xe7, 0xe8, 0x18, 0xb0, 0x4b, 0x0b,
0xc3, 0x9c, 0x1e, 0x87, 0x6b, 0x19, 0x3b, 0xfe,
0x55, 0x69, 0x75, 0x3f, 0x88, 0x12, 0x8c, 0xc0,
0x8a, 0xaa, 0x9b, 0x63, 0xd1, 0xa1, 0x6f, 0x80,
0xef, 0x25, 0x54, 0xd7, 0x18, 0x9c, 0x41, 0x1f,
0x58, 0x69, 0xca, 0x52, 0xc5, 0xb8, 0x3f, 0xa3,
0x6f, 0xf2, 0x16, 0xb9, 0xc1, 0xd3, 0x00, 0x62,
0xbe, 0xbc, 0xfd, 0x2d, 0xc5, 0xbc, 0xe0, 0x91,
0x19, 0x34, 0xfd, 0xa7, 0x9a, 0x86, 0xf6, 0xe6,
0x98, 0xce, 0xd7, 0x59, 0xc3, 0xff, 0x9b, 0x64,
0x77, 0x33, 0x8f, 0x3d, 0xa4, 0xf9, 0xcd, 0x85,
0x14, 0xea, 0x99, 0x82, 0xcc, 0xaf, 0xb3, 0x41,
0xb2, 0x38, 0x4d, 0xd9, 0x02, 0xf3, 0xd1, 0xab,
0x7a, 0xc6, 0x1d, 0xd2, 0x9c, 0x6f, 0x21, 0xba,
0x5b, 0x86, 0x2f, 0x37, 0x30, 0xe3, 0x7c, 0xfd,
0xc4, 0xfd, 0x80, 0x6c, 0x22, 0xf2, 0x21
}
};
static const size_t test_lengths[2] =
{
64U,
375U
};
#define ASSERT( cond, args ) \
do \
{ \
if( ! ( cond ) ) \
{ \
if( verbose != 0 ) \
mbedtls_printf args; \
\
return( -1 ); \
} \
} \
while( 0 )
int mbedtls_chacha20_self_test( int verbose )
{
unsigned char output[381];
unsigned i;
int ret;
for( i = 0U; i < 2U; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ChaCha20 test %u ", i );
ret = mbedtls_chacha20_crypt( test_keys[i],
test_nonces[i],
test_counters[i],
test_lengths[i],
test_input[i],
output );
ASSERT( 0 == ret, ( "error code: %i\n", ret ) );
ASSERT( 0 == memcmp( output, test_output[i], test_lengths[i] ),
( "failed (output)\n" ) );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* !MBEDTLS_CHACHA20_C */

540
Externals/mbedtls/library/chachapoly.c vendored Normal file
View File

@ -0,0 +1,540 @@
/**
* \file chachapoly.c
*
* \brief ChaCha20-Poly1305 AEAD construction based on RFC 7539.
*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
#include "mbedtls/chachapoly.h"
#include "mbedtls/platform_util.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_CHACHAPOLY_ALT)
/* Parameter validation macros */
#define CHACHAPOLY_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA )
#define CHACHAPOLY_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define CHACHAPOLY_STATE_INIT ( 0 )
#define CHACHAPOLY_STATE_AAD ( 1 )
#define CHACHAPOLY_STATE_CIPHERTEXT ( 2 ) /* Encrypting or decrypting */
#define CHACHAPOLY_STATE_FINISHED ( 3 )
/**
* \brief Adds nul bytes to pad the AAD for Poly1305.
*
* \param ctx The ChaCha20-Poly1305 context.
*/
static int chachapoly_pad_aad( mbedtls_chachapoly_context *ctx )
{
uint32_t partial_block_len = (uint32_t) ( ctx->aad_len % 16U );
unsigned char zeroes[15];
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
}
/**
* \brief Adds nul bytes to pad the ciphertext for Poly1305.
*
* \param ctx The ChaCha20-Poly1305 context.
*/
static int chachapoly_pad_ciphertext( mbedtls_chachapoly_context *ctx )
{
uint32_t partial_block_len = (uint32_t) ( ctx->ciphertext_len % 16U );
unsigned char zeroes[15];
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
}
void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx )
{
CHACHAPOLY_VALIDATE( ctx != NULL );
mbedtls_chacha20_init( &ctx->chacha20_ctx );
mbedtls_poly1305_init( &ctx->poly1305_ctx );
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_INIT;
ctx->mode = MBEDTLS_CHACHAPOLY_ENCRYPT;
}
void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_chacha20_free( &ctx->chacha20_ctx );
mbedtls_poly1305_free( &ctx->poly1305_ctx );
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_INIT;
ctx->mode = MBEDTLS_CHACHAPOLY_ENCRYPT;
}
int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,
const unsigned char key[32] )
{
int ret;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( key != NULL );
ret = mbedtls_chacha20_setkey( &ctx->chacha20_ctx, key );
return( ret );
}
int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
const unsigned char nonce[12],
mbedtls_chachapoly_mode_t mode )
{
int ret;
unsigned char poly1305_key[64];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
/* Set counter = 0, will be update to 1 when generating Poly1305 key */
ret = mbedtls_chacha20_starts( &ctx->chacha20_ctx, nonce, 0U );
if( ret != 0 )
goto cleanup;
/* Generate the Poly1305 key by getting the ChaCha20 keystream output with
* counter = 0. This is the same as encrypting a buffer of zeroes.
* Only the first 256-bits (32 bytes) of the key is used for Poly1305.
* The other 256 bits are discarded.
*/
memset( poly1305_key, 0, sizeof( poly1305_key ) );
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, sizeof( poly1305_key ),
poly1305_key, poly1305_key );
if( ret != 0 )
goto cleanup;
ret = mbedtls_poly1305_starts( &ctx->poly1305_ctx, poly1305_key );
if( ret == 0 )
{
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_AAD;
ctx->mode = mode;
}
cleanup:
mbedtls_platform_zeroize( poly1305_key, 64U );
return( ret );
}
int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,
const unsigned char *aad,
size_t aad_len )
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
if( ctx->state != CHACHAPOLY_STATE_AAD )
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
ctx->aad_len += aad_len;
return( mbedtls_poly1305_update( &ctx->poly1305_ctx, aad, aad_len ) );
}
int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,
size_t len,
const unsigned char *input,
unsigned char *output )
{
int ret;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || output != NULL );
if( ( ctx->state != CHACHAPOLY_STATE_AAD ) &&
( ctx->state != CHACHAPOLY_STATE_CIPHERTEXT ) )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
}
if( ctx->state == CHACHAPOLY_STATE_AAD )
{
ctx->state = CHACHAPOLY_STATE_CIPHERTEXT;
ret = chachapoly_pad_aad( ctx );
if( ret != 0 )
return( ret );
}
ctx->ciphertext_len += len;
if( ctx->mode == MBEDTLS_CHACHAPOLY_ENCRYPT )
{
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );
if( ret != 0 )
return( ret );
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, output, len );
if( ret != 0 )
return( ret );
}
else /* DECRYPT */
{
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, input, len );
if( ret != 0 )
return( ret );
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );
if( ret != 0 )
return( ret );
}
return( 0 );
}
int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
unsigned char mac[16] )
{
int ret;
unsigned char len_block[16];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( mac != NULL );
if( ctx->state == CHACHAPOLY_STATE_INIT )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
}
if( ctx->state == CHACHAPOLY_STATE_AAD )
{
ret = chachapoly_pad_aad( ctx );
if( ret != 0 )
return( ret );
}
else if( ctx->state == CHACHAPOLY_STATE_CIPHERTEXT )
{
ret = chachapoly_pad_ciphertext( ctx );
if( ret != 0 )
return( ret );
}
ctx->state = CHACHAPOLY_STATE_FINISHED;
/* The lengths of the AAD and ciphertext are processed by
* Poly1305 as the final 128-bit block, encoded as little-endian integers.
*/
len_block[ 0] = (unsigned char)( ctx->aad_len );
len_block[ 1] = (unsigned char)( ctx->aad_len >> 8 );
len_block[ 2] = (unsigned char)( ctx->aad_len >> 16 );
len_block[ 3] = (unsigned char)( ctx->aad_len >> 24 );
len_block[ 4] = (unsigned char)( ctx->aad_len >> 32 );
len_block[ 5] = (unsigned char)( ctx->aad_len >> 40 );
len_block[ 6] = (unsigned char)( ctx->aad_len >> 48 );
len_block[ 7] = (unsigned char)( ctx->aad_len >> 56 );
len_block[ 8] = (unsigned char)( ctx->ciphertext_len );
len_block[ 9] = (unsigned char)( ctx->ciphertext_len >> 8 );
len_block[10] = (unsigned char)( ctx->ciphertext_len >> 16 );
len_block[11] = (unsigned char)( ctx->ciphertext_len >> 24 );
len_block[12] = (unsigned char)( ctx->ciphertext_len >> 32 );
len_block[13] = (unsigned char)( ctx->ciphertext_len >> 40 );
len_block[14] = (unsigned char)( ctx->ciphertext_len >> 48 );
len_block[15] = (unsigned char)( ctx->ciphertext_len >> 56 );
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, len_block, 16U );
if( ret != 0 )
return( ret );
ret = mbedtls_poly1305_finish( &ctx->poly1305_ctx, mac );
return( ret );
}
static int chachapoly_crypt_and_tag( mbedtls_chachapoly_context *ctx,
mbedtls_chachapoly_mode_t mode,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16] )
{
int ret;
ret = mbedtls_chachapoly_starts( ctx, nonce, mode );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_update_aad( ctx, aad, aad_len );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_update( ctx, length, input, output );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_finish( ctx, tag );
cleanup:
return( ret );
}
int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16] )
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
return( chachapoly_crypt_and_tag( ctx, MBEDTLS_CHACHAPOLY_ENCRYPT,
length, nonce, aad, aad_len,
input, output, tag ) );
}
int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char tag[16],
const unsigned char *input,
unsigned char *output )
{
int ret;
unsigned char check_tag[16];
size_t i;
int diff;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
if( ( ret = chachapoly_crypt_and_tag( ctx,
MBEDTLS_CHACHAPOLY_DECRYPT, length, nonce,
aad, aad_len, input, output, check_tag ) ) != 0 )
{
return( ret );
}
/* Check tag in "constant-time" */
for( diff = 0, i = 0; i < sizeof( check_tag ); i++ )
diff |= tag[i] ^ check_tag[i];
if( diff != 0 )
{
mbedtls_platform_zeroize( output, length );
return( MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED );
}
return( 0 );
}
#endif /* MBEDTLS_CHACHAPOLY_ALT */
#if defined(MBEDTLS_SELF_TEST)
static const unsigned char test_key[1][32] =
{
{
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f
}
};
static const unsigned char test_nonce[1][12] =
{
{
0x07, 0x00, 0x00, 0x00, /* 32-bit common part */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 /* 64-bit IV */
}
};
static const unsigned char test_aad[1][12] =
{
{
0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7
}
};
static const size_t test_aad_len[1] =
{
12U
};
static const unsigned char test_input[1][114] =
{
{
0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61,
0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c,
0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73,
0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39,
0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63,
0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66,
0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f,
0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20,
0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75,
0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73,
0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f,
0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69,
0x74, 0x2e
}
};
static const unsigned char test_output[1][114] =
{
{
0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb,
0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2,
0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe,
0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6,
0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12,
0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b,
0x1a, 0x71, 0xde, 0x0a, 0x9e, 0x06, 0x0b, 0x29,
0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36,
0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c,
0x98, 0x03, 0xae, 0xe3, 0x28, 0x09, 0x1b, 0x58,
0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94,
0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc,
0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d,
0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b,
0x61, 0x16
}
};
static const size_t test_input_len[1] =
{
114U
};
static const unsigned char test_mac[1][16] =
{
{
0x1a, 0xe1, 0x0b, 0x59, 0x4f, 0x09, 0xe2, 0x6a,
0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x06, 0x91
}
};
#define ASSERT( cond, args ) \
do \
{ \
if( ! ( cond ) ) \
{ \
if( verbose != 0 ) \
mbedtls_printf args; \
\
return( -1 ); \
} \
} \
while( 0 )
int mbedtls_chachapoly_self_test( int verbose )
{
mbedtls_chachapoly_context ctx;
unsigned i;
int ret;
unsigned char output[200];
unsigned char mac[16];
for( i = 0U; i < 1U; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ChaCha20-Poly1305 test %u ", i );
mbedtls_chachapoly_init( &ctx );
ret = mbedtls_chachapoly_setkey( &ctx, test_key[i] );
ASSERT( 0 == ret, ( "setkey() error code: %i\n", ret ) );
ret = mbedtls_chachapoly_encrypt_and_tag( &ctx,
test_input_len[i],
test_nonce[i],
test_aad[i],
test_aad_len[i],
test_input[i],
output,
mac );
ASSERT( 0 == ret, ( "crypt_and_tag() error code: %i\n", ret ) );
ASSERT( 0 == memcmp( output, test_output[i], test_input_len[i] ),
( "failure (wrong output)\n" ) );
ASSERT( 0 == memcmp( mac, test_mac[i], 16U ),
( "failure (wrong MAC)\n" ) );
mbedtls_chachapoly_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_CHACHAPOLY_C */

View File

@ -33,10 +33,15 @@
#include "mbedtls/cipher.h"
#include "mbedtls/cipher_internal.h"
#include "mbedtls/platform_util.h"
#include <stdlib.h>
#include <string.h>
#if defined(MBEDTLS_CHACHAPOLY_C)
#include "mbedtls/chachapoly.h"
#endif
#if defined(MBEDTLS_GCM_C)
#include "mbedtls/gcm.h"
#endif
@ -45,6 +50,10 @@
#include "mbedtls/ccm.h"
#endif
#if defined(MBEDTLS_CHACHA20_C)
#include "mbedtls/chacha20.h"
#endif
#if defined(MBEDTLS_CMAC_C)
#include "mbedtls/cmac.h"
#endif
@ -56,14 +65,30 @@
#define mbedtls_free free
#endif
#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
#define MBEDTLS_CIPHER_MODE_STREAM
#endif
#define CIPHER_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA )
#define CIPHER_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
/* Compare the contents of two buffers in constant time.
* Returns 0 if the contents are bitwise identical, otherwise returns
* a non-zero value.
* This is currently only used by GCM and ChaCha20+Poly1305.
*/
static int mbedtls_constant_time_memcmp( const void *v1, const void *v2, size_t len )
{
const unsigned char *p1 = (const unsigned char*) v1;
const unsigned char *p2 = (const unsigned char*) v2;
size_t i;
unsigned char diff;
for( diff = 0, i = 0; i < len; i++ )
diff |= p1[i] ^ p2[i];
return( (int)diff );
}
#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
static int supported_init = 0;
@ -130,6 +155,7 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_ciph
void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx )
{
CIPHER_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
}
@ -141,7 +167,8 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx )
#if defined(MBEDTLS_CMAC_C)
if( ctx->cmac_ctx )
{
mbedtls_zeroize( ctx->cmac_ctx, sizeof( mbedtls_cmac_context_t ) );
mbedtls_platform_zeroize( ctx->cmac_ctx,
sizeof( mbedtls_cmac_context_t ) );
mbedtls_free( ctx->cmac_ctx );
}
#endif
@ -149,12 +176,13 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx )
if( ctx->cipher_ctx )
ctx->cipher_info->base->ctx_free_func( ctx->cipher_ctx );
mbedtls_zeroize( ctx, sizeof(mbedtls_cipher_context_t) );
mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) );
}
int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info )
{
if( NULL == cipher_info || NULL == ctx )
CIPHER_VALIDATE_RET( ctx != NULL );
if( cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
@ -178,10 +206,16 @@ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_in
return( 0 );
}
int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key,
int key_bitlen, const mbedtls_operation_t operation )
int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx,
const unsigned char *key,
int key_bitlen,
const mbedtls_operation_t operation )
{
if( NULL == ctx || NULL == ctx->cipher_info )
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( key != NULL );
CIPHER_VALIDATE_RET( operation == MBEDTLS_ENCRYPT ||
operation == MBEDTLS_DECRYPT );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN ) == 0 &&
@ -194,29 +228,33 @@ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *k
ctx->operation = operation;
/*
* For CFB and CTR mode always use the encryption key schedule
* For OFB, CFB and CTR mode always use the encryption key schedule
*/
if( MBEDTLS_ENCRYPT == operation ||
MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_CTR == ctx->cipher_info->mode )
{
return ctx->cipher_info->base->setkey_enc_func( ctx->cipher_ctx, key,
ctx->key_bitlen );
return( ctx->cipher_info->base->setkey_enc_func( ctx->cipher_ctx, key,
ctx->key_bitlen ) );
}
if( MBEDTLS_DECRYPT == operation )
return ctx->cipher_info->base->setkey_dec_func( ctx->cipher_ctx, key,
ctx->key_bitlen );
return( ctx->cipher_info->base->setkey_dec_func( ctx->cipher_ctx, key,
ctx->key_bitlen ) );
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
const unsigned char *iv, size_t iv_len )
const unsigned char *iv,
size_t iv_len )
{
size_t actual_iv_size;
if( NULL == ctx || NULL == ctx->cipher_info || NULL == iv )
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
/* avoid buffer overflow in ctx->iv */
@ -234,15 +272,31 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
memcpy( ctx->iv, iv, actual_iv_size );
ctx->iv_size = actual_iv_size;
#if defined(MBEDTLS_CHACHA20_C)
if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20 )
{
if ( 0 != mbedtls_chacha20_starts( (mbedtls_chacha20_context*)ctx->cipher_ctx,
iv,
0U ) ) /* Initial counter value */
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
}
#endif
if ( actual_iv_size != 0 )
{
memcpy( ctx->iv, iv, actual_iv_size );
ctx->iv_size = actual_iv_size;
}
return( 0 );
}
int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx )
{
if( NULL == ctx || NULL == ctx->cipher_info )
CIPHER_VALIDATE_RET( ctx != NULL );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
ctx->unprocessed_len = 0;
@ -250,33 +304,60 @@ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx )
return( 0 );
}
#if defined(MBEDTLS_GCM_C)
#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
const unsigned char *ad, size_t ad_len )
{
if( NULL == ctx || NULL == ctx->cipher_info )
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
#if defined(MBEDTLS_GCM_C)
if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
{
return mbedtls_gcm_starts( (mbedtls_gcm_context *) ctx->cipher_ctx, ctx->operation,
ctx->iv, ctx->iv_size, ad, ad_len );
return( mbedtls_gcm_starts( (mbedtls_gcm_context *) ctx->cipher_ctx, ctx->operation,
ctx->iv, ctx->iv_size, ad, ad_len ) );
}
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
{
int result;
mbedtls_chachapoly_mode_t mode;
mode = ( ctx->operation == MBEDTLS_ENCRYPT )
? MBEDTLS_CHACHAPOLY_ENCRYPT
: MBEDTLS_CHACHAPOLY_DECRYPT;
result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
ctx->iv,
mode );
if ( result != 0 )
return( result );
return( mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
ad, ad_len ) );
}
#endif
return( 0 );
}
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
size_t ilen, unsigned char *output, size_t *olen )
{
int ret;
size_t block_size = 0;
size_t block_size;
if( NULL == ctx || NULL == ctx->cipher_info || NULL == olen )
{
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
CIPHER_VALIDATE_RET( output != NULL );
CIPHER_VALIDATE_RET( olen != NULL );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
*olen = 0;
block_size = mbedtls_cipher_get_block_size( ctx );
@ -301,14 +382,23 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
if( ctx->cipher_info->mode == MBEDTLS_MODE_GCM )
{
*olen = ilen;
return mbedtls_gcm_update( (mbedtls_gcm_context *) ctx->cipher_ctx, ilen, input,
output );
return( mbedtls_gcm_update( (mbedtls_gcm_context *) ctx->cipher_ctx, ilen, input,
output ) );
}
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 )
{
*olen = ilen;
return( mbedtls_chachapoly_update( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
ilen, input, output ) );
}
#endif
if ( 0 == block_size )
{
return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT;
return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
}
if( input == output &&
@ -325,10 +415,12 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
/*
* If there is not enough data for a full block, cache it.
*/
if( ( ctx->operation == MBEDTLS_DECRYPT &&
ilen + ctx->unprocessed_len <= block_size ) ||
if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding &&
ilen <= block_size - ctx->unprocessed_len ) ||
( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding &&
ilen < block_size - ctx->unprocessed_len ) ||
( ctx->operation == MBEDTLS_ENCRYPT &&
ilen + ctx->unprocessed_len < block_size ) )
ilen < block_size - ctx->unprocessed_len ) )
{
memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
ilen );
@ -369,12 +461,20 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
{
if( 0 == block_size )
{
return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT;
return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
}
/* Encryption: only cache partial blocks
* Decryption w/ padding: always keep at least one whole block
* Decryption w/o padding: only cache partial blocks
*/
copy_len = ilen % block_size;
if( copy_len == 0 && ctx->operation == MBEDTLS_DECRYPT )
if( copy_len == 0 &&
ctx->operation == MBEDTLS_DECRYPT &&
NULL != ctx->add_padding)
{
copy_len = block_size;
}
memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
copy_len );
@ -417,6 +517,21 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
if( ctx->cipher_info->mode == MBEDTLS_MODE_OFB )
{
if( 0 != ( ret = ctx->cipher_info->base->ofb_func( ctx->cipher_ctx,
ilen, &ctx->unprocessed_len, ctx->iv, input, output ) ) )
{
return( ret );
}
*olen = ilen;
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
if( ctx->cipher_info->mode == MBEDTLS_MODE_CTR )
{
@ -433,6 +548,27 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
if( ctx->cipher_info->mode == MBEDTLS_MODE_XTS )
{
if( ctx->unprocessed_len > 0 ) {
/* We can only process an entire data unit at a time. */
return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
}
ret = ctx->cipher_info->base->xts_func( ctx->cipher_ctx,
ctx->operation, ilen, ctx->iv, input, output );
if( ret != 0 )
{
return( ret );
}
*olen = ilen;
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
if( ctx->cipher_info->mode == MBEDTLS_MODE_STREAM )
{
@ -516,14 +652,14 @@ static int get_one_and_zeros_padding( unsigned char *input, size_t input_len,
if( NULL == input || NULL == data_len )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
bad = 0xFF;
bad = 0x80;
*data_len = 0;
for( i = input_len; i > 0; i-- )
{
prev_done = done;
done |= ( input[i-1] != 0 );
done |= ( input[i - 1] != 0 );
*data_len |= ( i - 1 ) * ( done != prev_done );
bad &= ( input[i-1] ^ 0x80 ) | ( done == prev_done );
bad ^= input[i - 1] * ( done != prev_done );
}
return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
@ -626,19 +762,30 @@ static int get_no_padding( unsigned char *input, size_t input_len,
int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
unsigned char *output, size_t *olen )
{
if( NULL == ctx || NULL == ctx->cipher_info || NULL == olen )
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( output != NULL );
CIPHER_VALIDATE_RET( olen != NULL );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
*olen = 0;
if( MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_CTR == ctx->cipher_info->mode ||
MBEDTLS_MODE_GCM == ctx->cipher_info->mode ||
MBEDTLS_MODE_XTS == ctx->cipher_info->mode ||
MBEDTLS_MODE_STREAM == ctx->cipher_info->mode )
{
return( 0 );
}
if ( ( MBEDTLS_CIPHER_CHACHA20 == ctx->cipher_info->type ) ||
( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) )
{
return( 0 );
}
if( MBEDTLS_MODE_ECB == ctx->cipher_info->mode )
{
if( ctx->unprocessed_len != 0 )
@ -688,8 +835,8 @@ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
/* Set output size for decryption */
if( MBEDTLS_DECRYPT == ctx->operation )
return ctx->get_padding( output, mbedtls_cipher_get_block_size( ctx ),
olen );
return( ctx->get_padding( output, mbedtls_cipher_get_block_size( ctx ),
olen ) );
/* Set output size for encryption */
*olen = mbedtls_cipher_get_block_size( ctx );
@ -703,10 +850,12 @@ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
}
#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode )
int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx,
mbedtls_cipher_padding_t mode )
{
if( NULL == ctx ||
MBEDTLS_MODE_CBC != ctx->cipher_info->mode )
CIPHER_VALIDATE_RET( ctx != NULL );
if( NULL == ctx->cipher_info || MBEDTLS_MODE_CBC != ctx->cipher_info->mode )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
@ -750,18 +899,35 @@ int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_ciph
}
#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
#if defined(MBEDTLS_GCM_C)
#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
unsigned char *tag, size_t tag_len )
{
if( NULL == ctx || NULL == ctx->cipher_info || NULL == tag )
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if( MBEDTLS_ENCRYPT != ctx->operation )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
#if defined(MBEDTLS_GCM_C)
if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
return mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx, tag, tag_len );
return( mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx,
tag, tag_len ) );
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
{
/* Don't allow truncated MAC for Poly1305 */
if ( tag_len != 16U )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
return( mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
tag ) );
}
#endif
return( 0 );
}
@ -769,20 +935,22 @@ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
const unsigned char *tag, size_t tag_len )
{
unsigned char check_tag[16];
int ret;
if( NULL == ctx || NULL == ctx->cipher_info ||
MBEDTLS_DECRYPT != ctx->operation )
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( ctx->cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if( MBEDTLS_DECRYPT != ctx->operation )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
#if defined(MBEDTLS_GCM_C)
if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
{
unsigned char check_tag[16];
size_t i;
int diff;
if( tag_len > sizeof( check_tag ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
@ -793,18 +961,38 @@ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
}
/* Check the tag in "constant-time" */
for( diff = 0, i = 0; i < tag_len; i++ )
diff |= tag[i] ^ check_tag[i];
if( diff != 0 )
if( mbedtls_constant_time_memcmp( tag, check_tag, tag_len ) != 0 )
return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );
return( 0 );
}
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CHACHAPOLY_C)
if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
{
/* Don't allow truncated MAC for Poly1305 */
if ( tag_len != sizeof( check_tag ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
ret = mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
check_tag );
if ( ret != 0 )
{
return( ret );
}
/* Check the tag in "constant-time" */
if( mbedtls_constant_time_memcmp( tag, check_tag, tag_len ) != 0 )
return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );
return( 0 );
}
#endif /* MBEDTLS_CHACHAPOLY_C */
return( 0 );
}
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
/*
* Packet-oriented wrapper for non-AEAD modes
@ -817,6 +1005,12 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
int ret;
size_t finish_olen;
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
CIPHER_VALIDATE_RET( output != NULL );
CIPHER_VALIDATE_RET( olen != NULL );
if( ( ret = mbedtls_cipher_set_iv( ctx, iv, iv_len ) ) != 0 )
return( ret );
@ -845,6 +1039,14 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
unsigned char *output, size_t *olen,
unsigned char *tag, size_t tag_len )
{
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( iv != NULL );
CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
CIPHER_VALIDATE_RET( output != NULL );
CIPHER_VALIDATE_RET( olen != NULL );
CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
#if defined(MBEDTLS_GCM_C)
if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
{
@ -863,6 +1065,21 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
tag, tag_len ) );
}
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_CHACHAPOLY_C)
if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
{
/* ChachaPoly has fixed length nonce and MAC (tag) */
if ( ( iv_len != ctx->cipher_info->iv_size ) ||
( tag_len != 16U ) )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
*olen = ilen;
return( mbedtls_chachapoly_encrypt_and_tag( ctx->cipher_ctx,
ilen, iv, ad, ad_len, input, output, tag ) );
}
#endif /* MBEDTLS_CHACHAPOLY_C */
return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
}
@ -877,6 +1094,14 @@ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
unsigned char *output, size_t *olen,
const unsigned char *tag, size_t tag_len )
{
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( iv != NULL );
CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
CIPHER_VALIDATE_RET( output != NULL );
CIPHER_VALIDATE_RET( olen != NULL );
CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
#if defined(MBEDTLS_GCM_C)
if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
{
@ -909,6 +1134,28 @@ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
return( ret );
}
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_CHACHAPOLY_C)
if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
{
int ret;
/* ChachaPoly has fixed length nonce and MAC (tag) */
if ( ( iv_len != ctx->cipher_info->iv_size ) ||
( tag_len != 16U ) )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
*olen = ilen;
ret = mbedtls_chachapoly_auth_decrypt( ctx->cipher_ctx, ilen,
iv, ad, ad_len, tag, input, output );
if( ret == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED )
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
return( ret );
}
#endif /* MBEDTLS_CHACHAPOLY_C */
return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
}

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
/*
/**
* \file cmac.c
*
* \brief NIST SP800-38B compliant CMAC implementation for AES and 3DES
@ -49,6 +49,7 @@
#if defined(MBEDTLS_CMAC_C)
#include "mbedtls/cmac.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -62,13 +63,10 @@
#if defined(MBEDTLS_SELF_TEST)
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C || MBEDTLS_DES_C */
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_PLATFORM_C */
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
}
#if !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST)
/*
* Multiplication by u in the Galois field of GF(2^n)
@ -80,7 +78,7 @@ static void mbedtls_zeroize( void *v, size_t n ) {
* with R_64 = 0x1B and R_128 = 0x87
*
* Input and output MUST NOT point to the same buffer
* Block size must be 8 byes or 16 bytes - the block sizes for DES and AES.
* Block size must be 8 bytes or 16 bytes - the block sizes for DES and AES.
*/
static int cmac_multiply_by_u( unsigned char *output,
const unsigned char *input,
@ -105,7 +103,7 @@ static int cmac_multiply_by_u( unsigned char *output,
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
for( i = blocksize - 1; i >= 0; i-- )
for( i = (int)blocksize - 1; i >= 0; i-- )
{
output[i] = input[i] << 1 | overflow;
overflow = input[i] >> 7;
@ -142,7 +140,7 @@ static int cmac_generate_subkeys( mbedtls_cipher_context_t *ctx,
unsigned char L[MBEDTLS_CIPHER_BLKSIZE_MAX];
size_t olen, block_size;
mbedtls_zeroize( L, sizeof( L ) );
mbedtls_platform_zeroize( L, sizeof( L ) );
block_size = ctx->cipher_info->block_size;
@ -160,19 +158,21 @@ static int cmac_generate_subkeys( mbedtls_cipher_context_t *ctx,
goto exit;
exit:
mbedtls_zeroize( L, sizeof( L ) );
mbedtls_platform_zeroize( L, sizeof( L ) );
return( ret );
}
#endif /* !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST) */
#if !defined(MBEDTLS_CMAC_ALT)
static void cmac_xor_block( unsigned char *output, const unsigned char *input1,
const unsigned char *input2,
const size_t block_size )
{
size_t index;
size_t idx;
for( index = 0; index < block_size; index++ )
output[ index ] = input1[ index ] ^ input2[ index ];
for( idx = 0; idx < block_size; idx++ )
output[ idx ] = input1[ idx ] ^ input2[ idx ];
}
/*
@ -209,7 +209,7 @@ int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,
if( ctx == NULL || ctx->cipher_info == NULL || key == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if( ( retval = mbedtls_cipher_setkey( ctx, key, keybits,
if( ( retval = mbedtls_cipher_setkey( ctx, key, (int)keybits,
MBEDTLS_ENCRYPT ) ) != 0 )
return( retval );
@ -234,7 +234,7 @@ int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,
ctx->cmac_ctx = cmac_ctx;
mbedtls_zeroize( cmac_ctx->state, sizeof( cmac_ctx->state ) );
mbedtls_platform_zeroize( cmac_ctx->state, sizeof( cmac_ctx->state ) );
return 0;
}
@ -244,8 +244,8 @@ int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
{
mbedtls_cmac_context_t* cmac_ctx;
unsigned char *state;
int n, j, ret = 0;
size_t olen, block_size;
int ret = 0;
size_t n, j, olen, block_size;
if( ctx == NULL || ctx->cipher_info == NULL || input == NULL ||
ctx->cmac_ctx == NULL )
@ -280,8 +280,9 @@ int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
/* n is the number of blocks including any final partial block */
n = ( ilen + block_size - 1 ) / block_size;
/* Iterate across the input data in block sized chunks */
for( j = 0; j < n - 1; j++ )
/* Iterate across the input data in block sized chunks, excluding any
* final partial or complete block */
for( j = 1; j < n; j++ )
{
cmac_xor_block( state, input, state, block_size );
@ -325,8 +326,8 @@ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,
block_size = ctx->cipher_info->block_size;
state = cmac_ctx->state;
mbedtls_zeroize( K1, sizeof( K1 ) );
mbedtls_zeroize( K2, sizeof( K2 ) );
mbedtls_platform_zeroize( K1, sizeof( K1 ) );
mbedtls_platform_zeroize( K2, sizeof( K2 ) );
cmac_generate_subkeys( ctx, K1, K2 );
last_block = cmac_ctx->unprocessed_block;
@ -356,14 +357,14 @@ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,
exit:
/* Wipe the generated keys on the stack, and any other transients to avoid
* side channel leakage */
mbedtls_zeroize( K1, sizeof( K1 ) );
mbedtls_zeroize( K2, sizeof( K2 ) );
mbedtls_platform_zeroize( K1, sizeof( K1 ) );
mbedtls_platform_zeroize( K2, sizeof( K2 ) );
cmac_ctx->unprocessed_len = 0;
mbedtls_zeroize( cmac_ctx->unprocessed_block,
sizeof( cmac_ctx->unprocessed_block ) );
mbedtls_platform_zeroize( cmac_ctx->unprocessed_block,
sizeof( cmac_ctx->unprocessed_block ) );
mbedtls_zeroize( state, MBEDTLS_CIPHER_BLKSIZE_MAX );
mbedtls_platform_zeroize( state, MBEDTLS_CIPHER_BLKSIZE_MAX );
return( ret );
}
@ -378,10 +379,10 @@ int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx )
/* Reset the internal state */
cmac_ctx->unprocessed_len = 0;
mbedtls_zeroize( cmac_ctx->unprocessed_block,
sizeof( cmac_ctx->unprocessed_block ) );
mbedtls_zeroize( cmac_ctx->state,
sizeof( cmac_ctx->state ) );
mbedtls_platform_zeroize( cmac_ctx->unprocessed_block,
sizeof( cmac_ctx->unprocessed_block ) );
mbedtls_platform_zeroize( cmac_ctx->state,
sizeof( cmac_ctx->state ) );
return( 0 );
}
@ -461,12 +462,14 @@ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_length,
output );
exit:
mbedtls_zeroize( int_key, sizeof( int_key ) );
mbedtls_platform_zeroize( int_key, sizeof( int_key ) );
return( ret );
}
#endif /* MBEDTLS_AES_C */
#endif /* !MBEDTLS_CMAC_ALT */
#if defined(MBEDTLS_SELF_TEST)
/*
* CMAC test data for SP800-38B
@ -764,7 +767,7 @@ static int cmac_test_subkeys( int verbose,
int block_size,
int num_tests )
{
int i, ret;
int i, ret = 0;
mbedtls_cipher_context_t ctx;
const mbedtls_cipher_info_t *cipher_info;
unsigned char K1[MBEDTLS_CIPHER_BLKSIZE_MAX];
@ -825,6 +828,7 @@ static int cmac_test_subkeys( int verbose,
mbedtls_cipher_free( &ctx );
}
ret = 0;
goto exit;
cleanup:
@ -846,7 +850,7 @@ static int cmac_test_wth_cipher( int verbose,
int num_tests )
{
const mbedtls_cipher_info_t *cipher_info;
int i, ret;
int i, ret = 0;
unsigned char output[MBEDTLS_CIPHER_BLKSIZE_MAX];
cipher_info = mbedtls_cipher_info_from_type( cipher_type );
@ -880,6 +884,7 @@ static int cmac_test_wth_cipher( int verbose,
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
ret = 0;
exit:
return( ret );

View File

@ -19,7 +19,7 @@
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* The NIST SP 800-90 DRBGs are described in the following publucation.
* The NIST SP 800-90 DRBGs are described in the following publication.
*
* http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf
*/
@ -33,6 +33,7 @@
#if defined(MBEDTLS_CTR_DRBG_C)
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -49,11 +50,6 @@
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}
/*
* CTR_DRBG context initialization
*/
@ -70,6 +66,18 @@ void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx )
* Non-public function wrapped by mbedtls_ctr_drbg_seed(). Necessary to allow
* NIST tests to succeed (which require known length fixed entropy)
*/
/* CTR_DRBG_Instantiate with derivation function (SP 800-90A &sect;10.2.1.3.2)
* mbedtls_ctr_drbg_seed_entropy_len(ctx, f_entropy, p_entropy,
* custom, len, entropy_len)
* implements
* CTR_DRBG_Instantiate(entropy_input, nonce, personalization_string,
* security_strength) -> initial_working_state
* with inputs
* custom[:len] = nonce || personalization_string
* where entropy_input comes from f_entropy for entropy_len bytes
* and with outputs
* ctx = initial_working_state
*/
int mbedtls_ctr_drbg_seed_entropy_len(
mbedtls_ctr_drbg_context *ctx,
int (*f_entropy)(void *, unsigned char *, size_t),
@ -94,11 +102,15 @@ int mbedtls_ctr_drbg_seed_entropy_len(
/*
* Initialize with an empty key
*/
mbedtls_aes_setkey_enc( &ctx->aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS );
if( ( ret = mbedtls_aes_setkey_enc( &ctx->aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
{
return( ret );
}
if( ( ret = mbedtls_ctr_drbg_reseed( ctx, custom, len ) ) != 0 )
{
return( ret );
}
return( 0 );
}
@ -121,7 +133,7 @@ void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx )
mbedtls_mutex_free( &ctx->mutex );
#endif
mbedtls_aes_free( &ctx->aes_ctx );
mbedtls_zeroize( ctx, sizeof( mbedtls_ctr_drbg_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ctr_drbg_context ) );
}
void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx, int resistance )
@ -148,6 +160,7 @@ static int block_cipher_df( unsigned char *output,
unsigned char chain[MBEDTLS_CTR_DRBG_BLOCKSIZE];
unsigned char *p, *iv;
mbedtls_aes_context aes_ctx;
int ret = 0;
int i, j;
size_t buf_len, use_len;
@ -180,7 +193,10 @@ static int block_cipher_df( unsigned char *output,
for( i = 0; i < MBEDTLS_CTR_DRBG_KEYSIZE; i++ )
key[i] = i;
mbedtls_aes_setkey_enc( &aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS );
if( ( ret = mbedtls_aes_setkey_enc( &aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
{
goto exit;
}
/*
* Reduce data to MBEDTLS_CTR_DRBG_SEEDLEN bytes of data
@ -199,7 +215,10 @@ static int block_cipher_df( unsigned char *output,
use_len -= ( use_len >= MBEDTLS_CTR_DRBG_BLOCKSIZE ) ?
MBEDTLS_CTR_DRBG_BLOCKSIZE : use_len;
mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, chain, chain );
if( ( ret = mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, chain, chain ) ) != 0 )
{
goto exit;
}
}
memcpy( tmp + j, chain, MBEDTLS_CTR_DRBG_BLOCKSIZE );
@ -213,28 +232,57 @@ static int block_cipher_df( unsigned char *output,
/*
* Do final encryption with reduced data
*/
mbedtls_aes_setkey_enc( &aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS );
if( ( ret = mbedtls_aes_setkey_enc( &aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
{
goto exit;
}
iv = tmp + MBEDTLS_CTR_DRBG_KEYSIZE;
p = output;
for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )
{
mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, iv, iv );
if( ( ret = mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, iv, iv ) ) != 0 )
{
goto exit;
}
memcpy( p, iv, MBEDTLS_CTR_DRBG_BLOCKSIZE );
p += MBEDTLS_CTR_DRBG_BLOCKSIZE;
}
exit:
mbedtls_aes_free( &aes_ctx );
/*
* tidy up the stack
*/
mbedtls_platform_zeroize( buf, sizeof( buf ) );
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
mbedtls_platform_zeroize( key, sizeof( key ) );
mbedtls_platform_zeroize( chain, sizeof( chain ) );
if( 0 != ret )
{
/*
* wipe partial seed from memory
*/
mbedtls_platform_zeroize( output, MBEDTLS_CTR_DRBG_SEEDLEN );
}
return( 0 );
return( ret );
}
/* CTR_DRBG_Update (SP 800-90A &sect;10.2.1.2)
* ctr_drbg_update_internal(ctx, provided_data)
* implements
* CTR_DRBG_Update(provided_data, Key, V)
* with inputs and outputs
* ctx->aes_ctx = Key
* ctx->counter = V
*/
static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
const unsigned char data[MBEDTLS_CTR_DRBG_SEEDLEN] )
{
unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN];
unsigned char *p = tmp;
int i, j;
int ret = 0;
memset( tmp, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
@ -250,7 +298,8 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
/*
* Crypt counter block
*/
mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, p );
if( ( ret = mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, p ) ) != 0 )
goto exit;
p += MBEDTLS_CTR_DRBG_BLOCKSIZE;
}
@ -261,36 +310,81 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
/*
* Update key and counter
*/
mbedtls_aes_setkey_enc( &ctx->aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS );
if( ( ret = mbedtls_aes_setkey_enc( &ctx->aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
goto exit;
memcpy( ctx->counter, tmp + MBEDTLS_CTR_DRBG_KEYSIZE, MBEDTLS_CTR_DRBG_BLOCKSIZE );
return( 0 );
exit:
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
return( ret );
}
void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional, size_t add_len )
/* CTR_DRBG_Instantiate with derivation function (SP 800-90A &sect;10.2.1.3.2)
* mbedtls_ctr_drbg_update(ctx, additional, add_len)
* implements
* CTR_DRBG_Instantiate(entropy_input, nonce, personalization_string,
* security_strength) -> initial_working_state
* with inputs
* ctx->counter = all-bits-0
* ctx->aes_ctx = context from all-bits-0 key
* additional[:add_len] = entropy_input || nonce || personalization_string
* and with outputs
* ctx = initial_working_state
*/
int mbedtls_ctr_drbg_update_ret( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional,
size_t add_len )
{
unsigned char add_input[MBEDTLS_CTR_DRBG_SEEDLEN];
int ret;
if( add_len > 0 )
{
/* MAX_INPUT would be more logical here, but we have to match
* block_cipher_df()'s limits since we can't propagate errors */
if( add_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
add_len = MBEDTLS_CTR_DRBG_MAX_SEED_INPUT;
if( add_len == 0 )
return( 0 );
block_cipher_df( add_input, additional, add_len );
ctr_drbg_update_internal( ctx, add_input );
}
if( ( ret = block_cipher_df( add_input, additional, add_len ) ) != 0 )
goto exit;
if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )
goto exit;
exit:
mbedtls_platform_zeroize( add_input, sizeof( add_input ) );
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional,
size_t add_len )
{
/* MAX_INPUT would be more logical here, but we have to match
* block_cipher_df()'s limits since we can't propagate errors */
if( add_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
add_len = MBEDTLS_CTR_DRBG_MAX_SEED_INPUT;
(void) mbedtls_ctr_drbg_update_ret( ctx, additional, add_len );
}
#endif /* MBEDTLS_DEPRECATED_REMOVED */
/* CTR_DRBG_Reseed with derivation function (SP 800-90A &sect;10.2.1.4.2)
* mbedtls_ctr_drbg_reseed(ctx, additional, len)
* implements
* CTR_DRBG_Reseed(working_state, entropy_input, additional_input)
* -> new_working_state
* with inputs
* ctx contains working_state
* additional[:len] = additional_input
* and entropy_input comes from calling ctx->f_entropy
* and with output
* ctx contains new_working_state
*/
int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional, size_t len )
{
unsigned char seed[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT];
size_t seedlen = 0;
int ret;
if( ctx->entropy_len + len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
if( ctx->entropy_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT ||
len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - ctx->entropy_len )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
memset( seed, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT );
@ -318,17 +412,40 @@ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
/*
* Reduce to 384 bits
*/
block_cipher_df( seed, seed, seedlen );
if( ( ret = block_cipher_df( seed, seed, seedlen ) ) != 0 )
goto exit;
/*
* Update state
*/
ctr_drbg_update_internal( ctx, seed );
if( ( ret = ctr_drbg_update_internal( ctx, seed ) ) != 0 )
goto exit;
ctx->reseed_counter = 1;
return( 0 );
exit:
mbedtls_platform_zeroize( seed, sizeof( seed ) );
return( ret );
}
/* CTR_DRBG_Generate with derivation function (SP 800-90A &sect;10.2.1.5.2)
* mbedtls_ctr_drbg_random_with_add(ctx, output, output_len, additional, add_len)
* implements
* CTR_DRBG_Reseed(working_state, entropy_input, additional[:add_len])
* -> working_state_after_reseed
* if required, then
* CTR_DRBG_Generate(working_state_after_reseed,
* requested_number_of_bits, additional_input)
* -> status, returned_bits, new_working_state
* with inputs
* ctx contains working_state
* requested_number_of_bits = 8 * output_len
* additional[:add_len] = additional_input
* and entropy_input comes from calling ctx->f_entropy
* and with outputs
* status = SUCCESS (this function does the reseed internally)
* returned_bits = output[:output_len]
* ctx contains new_working_state
*/
int mbedtls_ctr_drbg_random_with_add( void *p_rng,
unsigned char *output, size_t output_len,
const unsigned char *additional, size_t add_len )
@ -353,15 +470,18 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
ctx->prediction_resistance )
{
if( ( ret = mbedtls_ctr_drbg_reseed( ctx, additional, add_len ) ) != 0 )
{
return( ret );
}
add_len = 0;
}
if( add_len > 0 )
{
block_cipher_df( add_input, additional, add_len );
ctr_drbg_update_internal( ctx, add_input );
if( ( ret = block_cipher_df( add_input, additional, add_len ) ) != 0 )
goto exit;
if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )
goto exit;
}
while( output_len > 0 )
@ -376,7 +496,8 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
/*
* Crypt counter block
*/
mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, tmp );
if( ( ret = mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, tmp ) ) != 0 )
goto exit;
use_len = ( output_len > MBEDTLS_CTR_DRBG_BLOCKSIZE ) ? MBEDTLS_CTR_DRBG_BLOCKSIZE :
output_len;
@ -388,10 +509,14 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
output_len -= use_len;
}
ctr_drbg_update_internal( ctx, add_input );
if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )
goto exit;
ctx->reseed_counter++;
exit:
mbedtls_platform_zeroize( add_input, sizeof( add_input ) );
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
return( 0 );
}
@ -429,47 +554,50 @@ int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char
goto exit;
if( fwrite( buf, 1, MBEDTLS_CTR_DRBG_MAX_INPUT, f ) != MBEDTLS_CTR_DRBG_MAX_INPUT )
{
ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;
goto exit;
}
ret = 0;
else
ret = 0;
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
fclose( f );
return( ret );
}
int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path )
{
FILE *f;
int ret = 0;
FILE *f = NULL;
size_t n;
unsigned char buf[ MBEDTLS_CTR_DRBG_MAX_INPUT ];
unsigned char c;
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR );
fseek( f, 0, SEEK_END );
n = (size_t) ftell( f );
fseek( f, 0, SEEK_SET );
if( n > MBEDTLS_CTR_DRBG_MAX_INPUT )
n = fread( buf, 1, sizeof( buf ), f );
if( fread( &c, 1, 1, f ) != 0 )
{
fclose( f );
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
ret = MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG;
goto exit;
}
if( fread( buf, 1, n, f ) != n )
if( n == 0 || ferror( f ) )
{
fclose( f );
return( MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR );
ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;
goto exit;
}
fclose( f );
f = NULL;
mbedtls_ctr_drbg_update( ctx, buf, n );
ret = mbedtls_ctr_drbg_update_ret( ctx, buf, n );
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
if( f != NULL )
fclose( f );
if( ret != 0 )
return( ret );
return( mbedtls_ctr_drbg_write_seed_file( ctx, path ) );
}
#endif /* MBEDTLS_FS_IO */

Some files were not shown because too many files have changed in this diff Show More