Merge patch series "Integrate MbedTLS v3.6 LTS with U-Boot"

Raymond Mao <raymond.mao@linaro.org> says:
Integrate MbedTLS v3.6 LTS (currently v3.6.0) with U-Boot.

Motivations:
------------

1. MbedTLS is well maintained with LTS versions.
2. LWIP is integrated with MbedTLS and easily to enable HTTPS.
3. MbedTLS recently switched license back to GPLv2.

Prerequisite:
-------------

This patch series requires mbedtls git repo to be added as a
subtree to the main U-Boot repo via:
    $ git subtree add --prefix lib/mbedtls/external/mbedtls \
          https://github.com/Mbed-TLS/mbedtls.git \
          v3.6.0 --squash
Moreover, due to the Windows-style files from mbedtls git repo,
we need to convert the CRLF endings to LF and do a commit manually:
    $ git add --renormalize .
    $ git commit

New Kconfig options:
--------------------

`MBEDTLS_LIB` is for MbedTLS general switch.
`MBEDTLS_LIB_CRYPTO` is for replacing original digest and crypto libs with
MbedTLS.
`MBEDTLS_LIB_CRYPTO_ALT` is for using original U-Boot crypto libs as
MbedTLS crypto alternatives.
`MBEDTLS_LIB_X509` is for replacing original X509, PKCS7, MSCode, ASN1,
and Pubkey parser with MbedTLS.
By default `MBEDTLS_LIB_CRYPTO_ALT` and `MBEDTLS_LIB_X509` are selected
when `MBEDTLS_LIB` is enabled.
`LEGACY_CRYPTO` is introduced as a main switch for legacy crypto library.
`LEGACY_CRYPTO_BASIC` is for the basic crypto functionalities and
`LEGACY_CRYPTO_CERT` is for the certificate related functionalities.
For each of the algorithm, a pair of `<alg>_LEGACY` and `<alg>_MBEDTLS`
Kconfig options are introduced. Meanwhile, `SPL_` Kconfig options are
introduced.

In this patch set, MBEDTLS_LIB, MBEDTLS_LIB_CRYPTO and MBEDTLS_LIB_X509
are by default enabled in qemu_arm64_defconfig and sandbox_defconfig
for testing purpose.

Patches for external MbedTLS project:
-------------------------------------

Since U-Boot uses Microsoft Authentication Code to verify PE/COFFs
executables which is not supported by MbedTLS at the moment,
addtional patches for MbedTLS are created to adapt with the EFI loader:
1. Decoding of Microsoft Authentication Code.
2. Decoding of PKCS#9 Authenticate Attributes.
3. Extending MbedTLS PKCS#7 lib to support multiple signer's certificates.
4. MbedTLS native test suites for PKCS#7 signer's info.

All above 4 patches (tagged with `mbedtls/external`) are submitted to
MbedTLS project and being reviewed, eventually they should be part of
MbedTLS LTS release.
But before that, please merge them into U-Boot, otherwise the building
will be broken when MBEDTLS_LIB_X509 is enabled.

See below PR link for the reference:
https://github.com/Mbed-TLS/mbedtls/pull/9001

Miscellaneous:
--------------

Optimized MbedTLS library size by tailoring the config file
and disabling all unnecessary features for EFI loader.
From v2, original libs (rsa, asn1_decoder, rsa_helper, md5, sha1, sha256,
sha512) are completely replaced when MbedTLS is enabled.
From v3, the size-growth is slightly reduced by refactoring Hash functions.
From v6, smaller implementations for SHA256 and SHA512 are enabled and
target size reduce significantly.
Target(QEMU arm64) size-growth when enabling MbedTLS:
v1: 6.03%
v2: 4.66%
v3 - v5: 4.55%
v6: 2.90%

Tests done:
-----------

EFI Secure Boot test (EFI variables loading and verifying, EFI signed image
verifying and booting) via U-Boot console.
EFI Secure Boot and Capsule sandbox test passed.

Known issues:
-------------

None.

Link: https://lore.kernel.org/u-boot/20241003215112.3103601-1-raymond.mao@linaro.org/
This commit is contained in:
Tom Rini 2024-10-14 13:34:06 -06:00
commit d467f359c4
1835 changed files with 628389 additions and 191 deletions

View File

@ -76,7 +76,8 @@ stages:
# have no matches.
- script: git grep -E '^#[[:blank:]]*(define|undef)[[:blank:]]*CONFIG_'
:^doc/ :^arch/arm/dts/ :^scripts/kconfig/lkc.h
:^include/linux/kconfig.h :^tools/ :^dts/upstream/ &&
:^include/linux/kconfig.h :^tools/ :^dts/upstream/
:^lib/mbedtls/external :^lib/mbedtls/mbedtls_def_config.h &&
exit 1 || exit 0
- job: docs

View File

@ -159,7 +159,8 @@ check for new CONFIG symbols outside Kconfig:
# have no matches.
- git grep -E '^#[[:blank:]]*(define|undef)[[:blank:]]*CONFIG_'
:^doc/ :^arch/arm/dts/ :^scripts/kconfig/lkc.h
:^include/linux/kconfig.h :^tools/ :^dts/upstream/ &&
:^include/linux/kconfig.h :^tools/ :^dts/upstream/
:^lib/mbedtls/external :^lib/mbedtls/mbedtls_def_config.h &&
exit 1 || exit 0
# build documentation

View File

@ -829,6 +829,12 @@ KBUILD_HOSTCFLAGS += $(if $(CONFIG_TOOLS_DEBUG),-g)
UBOOTINCLUDE := \
-Iinclude \
$(if $(KBUILD_SRC), -I$(srctree)/include) \
$(if $(CONFIG_MBEDTLS_LIB), \
"-DMBEDTLS_CONFIG_FILE=\"mbedtls_def_config.h\"" \
-I$(srctree)/lib/mbedtls \
-I$(srctree)/lib/mbedtls/port \
-I$(srctree)/lib/mbedtls/external/mbedtls \
-I$(srctree)/lib/mbedtls/external/mbedtls/include) \
$(if $(CONFIG_$(XPL_)SYS_THUMB_BUILD), \
$(if $(CONFIG_HAS_THUMB2), \
$(if $(CONFIG_CPU_V7M), \

View File

@ -264,7 +264,8 @@ static void make_ether_addr(u8 *addr)
hash[6] = readl(PHY_BASEADDR_ECID + 0x08);
hash[7] = readl(PHY_BASEADDR_ECID + 0x0c);
md5((unsigned char *)&hash[4], 64, (unsigned char *)hash);
md5_wd((unsigned char *)&hash[4], 64, (unsigned char *)hash,
MD5_DEF_CHUNK_SZ);
hash[0] ^= hash[2];
hash[1] ^= hash[3];

View File

@ -166,7 +166,7 @@ static int find_key(struct udevice *tpm, const uint8_t auth[20],
return -1;
if (err)
continue;
sha1_csum(buf, buf_len, digest);
sha1_csum_wd(buf, buf_len, digest, SHA1_DEF_CHUNK_SZ);
if (!memcmp(digest, pubkey_digest, 20)) {
*handle = key_handles[i];
return 0;

View File

@ -32,7 +32,8 @@ static void assign_serial(void)
if (!mmc)
return;
md5((unsigned char *)mmc->cid, sizeof(mmc->cid), ssn);
md5_wd((unsigned char *)mmc->cid, sizeof(mmc->cid), ssn,
MD5_DEF_CHUNK_SZ);
snprintf(usb0addr, sizeof(usb0addr), "02:00:86:%02x:%02x:%02x",
ssn[13], ssn[14], ssn[15]);

View File

@ -135,7 +135,7 @@ int zynq_validate_partition(u32 start_addr, u32 len, u32 chksum_off)
memcpy(&checksum[0], (u32 *)chksum_off, MD5_CHECKSUM_SIZE);
md5_wd((u8 *)start_addr, len, &calchecksum[0], 0x10000);
md5_wd((u8 *)start_addr, len, &calchecksum[0], MD5_DEF_CHUNK_SZ);
if (!memcmp(checksum, calchecksum, MD5_CHECKSUM_SIZE))
return 0;

View File

@ -69,4 +69,5 @@ CONFIG_TPM2_MMIO=y
CONFIG_USB_EHCI_HCD=y
CONFIG_USB_EHCI_PCI=y
CONFIG_SEMIHOSTING=y
CONFIG_MBEDTLS_LIB=y
CONFIG_TPM=y

View File

@ -353,6 +353,7 @@ CONFIG_FS_CBFS=y
CONFIG_FS_CRAMFS=y
CONFIG_ADDR_MAP=y
CONFIG_CMD_DHRYSTONE=y
CONFIG_MBEDTLS_LIB=y
CONFIG_ECDSA=y
CONFIG_ECDSA_VERIFY=y
CONFIG_TPM=y

View File

@ -130,6 +130,7 @@ config MMC_HW_PARTITIONING
config SUPPORT_EMMC_RPMB
bool "Support eMMC replay protected memory block (RPMB)"
imply CMD_MMC_RPMB
select SHA256
help
Enable support for reading, writing and programming the
key for the Replay Protection Memory Block partition in eMMC.

View File

@ -9,6 +9,10 @@
#ifndef __UBOOT__
#include <crypto/hash_info.h>
#endif
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
#include <mbedtls/asn1.h>
#include <mbedtls/oid.h>
#endif
struct pefile_context {
#ifndef __UBOOT__

View File

@ -11,6 +11,12 @@
#include <linux/oid_registry.h>
#include <crypto/pkcs7.h>
#include <crypto/x509_parser.h>
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
#include <mbedtls/pkcs7.h>
#include <library/x509_internal.h>
#include <mbedtls/asn1.h>
#include <mbedtls/oid.h>
#endif
#include <linux/printk.h>
#define kenter(FMT, ...) \
@ -18,7 +24,54 @@
#define kleave(FMT, ...) \
pr_devel("<== %s()"FMT"\n", __func__, ##__VA_ARGS__)
/* Backup the parsed MedTLS context that we need */
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
struct pkcs7_mbedtls_ctx {
void *content_data;
};
struct pkcs7_sinfo_mbedtls_ctx {
void *authattrs_data;
void *content_data_digest;
};
#endif
/*
* MbedTLS integration Notes:
*
* MbedTLS PKCS#7 library does not originally support parsing MicroSoft
* Authentication Code which is used for verifying the PE image digest.
*
* 1. Authenticated Attributes (authenticatedAttributes)
* MbedTLS assumes unauthenticatedAttributes and authenticatedAttributes
* fields not exist.
* See MbedTLS function 'pkcs7_get_signer_info' for details.
*
* 2. MicroSoft Authentication Code (mscode)
* MbedTLS only supports Content Data type defined as 1.2.840.113549.1.7.1
* (MBEDTLS_OID_PKCS7_DATA, aka OID_data).
* 1.3.6.1.4.1.311.2.1.4 (MicroSoft Authentication Code, aka
* OID_msIndirectData) is not supported.
* See MbedTLS function 'pkcs7_get_content_info_type' for details.
*
* But the EFI loader assumes that a PKCS#7 message with an EFI image always
* contains MicroSoft Authentication Code as Content Data (msg->data is NOT
* NULL), see function 'efi_signature_verify'.
*
* MbedTLS patch "0002-support-MicroSoft-authentication-code-in-PKCS7-lib.patch"
* is to support both above features by parsing the Content Data and
* Authenticate Attributes from a given PKCS#7 message.
*
* Other fields we don't need to populate from MbedTLS, which are used
* internally by pkcs7_verify:
* 'signer', 'unsupported_crypto', 'blacklisted'
* 'sig->digest' is used internally by pkcs7_digest to calculate the hash of
* Content Data or Authenticate Attributes.
*/
struct pkcs7_signed_info {
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
struct pkcs7_sinfo_mbedtls_ctx *mbedtls_ctx;
#endif
struct pkcs7_signed_info *next;
struct x509_certificate *signer; /* Signing certificate (in msg->certs) */
unsigned index;
@ -55,6 +108,9 @@ struct pkcs7_signed_info {
};
struct pkcs7_message {
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
struct pkcs7_mbedtls_ctx *mbedtls_ctx;
#endif
struct x509_certificate *certs; /* Certificate list */
struct x509_certificate *crl; /* Revocation list */
struct pkcs7_signed_info *signed_infos;

View File

@ -12,6 +12,12 @@
#ifdef __UBOOT__
#include <linux/types.h>
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
#include <library/common.h>
#include <mbedtls/pk.h>
#include <mbedtls/x509_crt.h>
#include <mbedtls/md.h>
#endif
#else
#include <linux/keyctl.h>
#endif

View File

@ -11,8 +11,35 @@
#include <linux/time.h>
#include <crypto/public_key.h>
#include <keys/asymmetric-type.h>
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
#include <image.h>
#include <mbedtls/error.h>
#include <mbedtls/asn1.h>
#endif
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
struct x509_cert_mbedtls_ctx {
void *tbs; /* Signed data */
void *raw_serial; /* Raw serial number in ASN.1 */
void *raw_issuer; /* Raw issuer name in ASN.1 */
void *raw_subject; /* Raw subject name in ASN.1 */
void *raw_skid; /* Raw subjectKeyId in ASN.1 */
};
#endif
/*
* MbedTLS integration Notes:
*
* Fields we don't need to populate from MbedTLS context:
* 'raw_sig' and 'raw_sig_size' are buffer for x509_parse_context,
* not needed for MbedTLS.
* 'signer' and 'seen' are used internally by pkcs7_verify.
* 'verified' is not in use.
*/
struct x509_certificate {
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
struct x509_cert_mbedtls_ctx *mbedtls_ctx;
#endif
struct x509_certificate *next;
struct x509_certificate *signer; /* Certificate that signed this one */
struct public_key *pub; /* Public key details */
@ -48,6 +75,32 @@ struct x509_certificate {
* x509_cert_parser.c
*/
extern void x509_free_certificate(struct x509_certificate *cert);
#if CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
/**
* x509_populate_pubkey() - Populate public key from MbedTLS context
*
* @cert: Pointer to MbedTLS X509 cert
* @pub_key: Pointer to the populated public key handle
* Return: 0 on succcess, error code on failure
*/
int x509_populate_pubkey(mbedtls_x509_crt *cert, struct public_key **pub_key);
/**
* x509_populate_cert() - Populate X509 cert from MbedTLS context
*
* @mbedtls_cert: Pointer to MbedTLS X509 cert
* @pcert: Pointer to the populated X509 cert handle
* Return: 0 on succcess, error code on failure
*/
int x509_populate_cert(mbedtls_x509_crt *mbedtls_cert,
struct x509_certificate **pcert);
/**
* x509_get_timestamp() - Translate timestamp from MbedTLS context
*
* @x509_time: Pointer to MbedTLS time
* Return: Time in time64_t format
*/
time64_t x509_get_timestamp(const mbedtls_x509_time *x509_time);
#endif
extern struct x509_certificate *x509_cert_parse(const void *data, size_t datalen);
extern int x509_decode_time(time64_t *_t, size_t hdrlen,
unsigned char tag,
@ -56,6 +109,8 @@ extern int x509_decode_time(time64_t *_t, size_t hdrlen,
/*
* x509_public_key.c
*/
#if !CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
extern int x509_get_sig_params(struct x509_certificate *cert);
#endif
extern int x509_check_for_self_signed(struct x509_certificate *cert);
#endif /* _X509_PARSER_H */

25
include/limits.h Normal file
View File

@ -0,0 +1,25 @@
/* SPDX-License-Identifier: GPL-2.0+ */
#ifndef _LIMITS_H
#define _LIMITS_H
#define INT_MAX 0x7fffffff
#define UINT_MAX 0xffffffffU
#define CHAR_BIT 8
#define UINT32_MAX 0xffffffffU
#define UINT64_MAX 0xffffffffffffffffULL
#ifdef CONFIG_64BIT
#define UINTPTR_MAX UINT64_MAX
#else
#define UINTPTR_MAX UINT32_MAX
#endif
#ifndef SIZE_MAX
#define SIZE_MAX UINTPTR_MAX
#endif
#ifndef SSIZE_MAX
#define SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1))
#endif
#endif /* _LIMITS_H */

View File

@ -3,25 +3,18 @@
#include <linux/types.h>
#include <linux/printk.h> /* for printf/pr_* utilities */
#include <limits.h>
#define USHRT_MAX ((u16)(~0U))
#define SHRT_MAX ((s16)(USHRT_MAX>>1))
#define SHRT_MIN ((s16)(-SHRT_MAX - 1))
#define INT_MAX ((int)(~0U>>1))
#define INT_MIN (-INT_MAX - 1)
#define UINT_MAX (~0U)
#define LONG_MAX ((long)(~0UL>>1))
#define LONG_MIN (-LONG_MAX - 1)
#define ULONG_MAX (~0UL)
#define LLONG_MAX ((long long)(~0ULL>>1))
#define LLONG_MIN (-LLONG_MAX - 1)
#define ULLONG_MAX (~0ULL)
#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif
#ifndef SSIZE_MAX
#define SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1))
#endif
#define U8_MAX ((u8)~0U)
#define S8_MAX ((s8)(U8_MAX>>1))
@ -36,10 +29,6 @@
#define S64_MAX ((s64)(U64_MAX>>1))
#define S64_MIN ((s64)(-S64_MAX - 1))
/* Aliases defined by stdint.h */
#define UINT32_MAX U32_MAX
#define UINT64_MAX U64_MAX
#define INT32_MAX S32_MAX
#define STACK_MAGIC 0xdeadbeef

View File

@ -7,5 +7,6 @@
#define __STDLIB_H_
#include <malloc.h>
#include <rand.h>
#endif /* __STDLIB_H_ */

View File

@ -6,10 +6,17 @@
#ifndef _MD5_H
#define _MD5_H
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
#include <mbedtls/md5.h>
#endif
#include "compiler.h"
#define MD5_SUM_LEN 16
#define MD5_DEF_CHUNK_SZ 0x10000
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
typedef mbedtls_md5_context MD5Context;
#else
typedef struct MD5Context {
__u32 buf[4];
__u32 bits[2];
@ -18,17 +25,12 @@ typedef struct MD5Context {
__u32 in32[16];
};
} MD5Context;
#endif
void MD5Init(MD5Context *ctx);
void MD5Update(MD5Context *ctx, unsigned char const *buf, unsigned int len);
void MD5Final(unsigned char digest[16], MD5Context *ctx);
/*
* Calculate and store in 'output' the MD5 digest of 'len' bytes at
* 'input'. 'output' must have enough space to hold 16 bytes.
*/
void md5 (unsigned char *input, int len, unsigned char output[16]);
/*
* Calculate and store in 'output' the MD5 digest of 'len' bytes at 'input'.
* 'output' must have enough space to hold 16 bytes. If 'chunk' Trigger the

View File

@ -16,6 +16,21 @@
#include <linux/types.h>
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
/*
* FIXME:
* MbedTLS define the members of "mbedtls_sha256_context" as private,
* but "state" needs to be access by arch/arm/cpu/armv8/sha1_ce_glue.
* MBEDTLS_ALLOW_PRIVATE_ACCESS needs to be enabled to allow the external
* access.
* Directly including <external/mbedtls/library/common.h> is not allowed,
* since this will include <malloc.h> and break the sandbox test.
*/
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include <mbedtls/sha1.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
@ -24,8 +39,17 @@ extern "C" {
#define SHA1_SUM_LEN 20
#define SHA1_DER_LEN 15
#define SHA1_DEF_CHUNK_SZ 0x10000
#define K_IPAD_VAL 0x36
#define K_OPAD_VAL 0x5C
#define K_PAD_LEN 64
extern const uint8_t sha1_der_prefix[];
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
typedef mbedtls_sha1_context sha1_context;
#else
/**
* \brief SHA-1 context structure
*/
@ -36,13 +60,14 @@ typedef struct
unsigned char buffer[64]; /*!< data block being processed */
}
sha1_context;
#endif
/**
* \brief SHA-1 context setup
*
* \param ctx SHA-1 context to be initialized
*/
void sha1_starts( sha1_context *ctx );
void sha1_starts(sha1_context *ctx);
/**
* \brief SHA-1 process buffer
@ -62,16 +87,6 @@ void sha1_update(sha1_context *ctx, const unsigned char *input,
*/
void sha1_finish( sha1_context *ctx, unsigned char output[20] );
/**
* \brief Output = SHA-1( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-1 checksum result
*/
void sha1_csum(const unsigned char *input, unsigned int ilen,
unsigned char *output);
/**
* \brief Output = SHA-1( input buffer ), with watchdog triggering
*

View File

@ -3,6 +3,22 @@
#include <linux/types.h>
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
/*
* FIXME:
* MbedTLS define the members of "mbedtls_sha256_context" as private,
* but "state" needs to be access by arch/arm/cpu/armv8/sha256_ce_glue.
* MBEDTLS_ALLOW_PRIVATE_ACCESS needs to be enabled to allow the external
* access.
* Directly including <external/mbedtls/library/common.h> is not allowed,
* since this will include <malloc.h> and break the sandbox test.
*/
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include <mbedtls/sha256.h>
#endif
#define SHA224_SUM_LEN 28
#define SHA256_SUM_LEN 32
#define SHA256_DER_LEN 19
@ -11,11 +27,15 @@ extern const uint8_t sha256_der_prefix[];
/* Reset watchdog each time we process this many bytes */
#define CHUNKSZ_SHA256 (64 * 1024)
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
typedef mbedtls_sha256_context sha256_context;
#else
typedef struct {
uint32_t total[2];
uint32_t state[8];
uint8_t buffer[64];
} sha256_context;
#endif
void sha256_starts(sha256_context * ctx);
void sha256_update(sha256_context *ctx, const uint8_t *input, uint32_t length);

View File

@ -3,6 +3,10 @@
#include <linux/types.h>
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
#include <mbedtls/sha512.h>
#endif
#define SHA384_SUM_LEN 48
#define SHA384_DER_LEN 19
#define SHA512_SUM_LEN 64
@ -12,11 +16,16 @@
#define CHUNKSZ_SHA384 (16 * 1024)
#define CHUNKSZ_SHA512 (16 * 1024)
#if defined(CONFIG_MBEDTLS_LIB_CRYPTO)
typedef mbedtls_sha512_context sha384_context;
typedef mbedtls_sha512_context sha512_context;
#else
typedef struct {
uint64_t state[SHA512_SUM_LEN / 8];
uint64_t count[2];
uint8_t buf[SHA512_BLOCK_SIZE];
} sha512_context;
#endif
extern const uint8_t sha512_der_prefix[];

View File

@ -419,6 +419,10 @@ config CIRCBUF
source "lib/dhry/Kconfig"
menu "Alternative crypto libraries"
source lib/mbedtls/Kconfig
endmenu
menu "Security support"
config AES

View File

@ -50,7 +50,6 @@ obj-$(CONFIG_XXHASH) += xxhash.o
obj-y += net_utils.o
obj-$(CONFIG_PHYSMEM) += physmem.o
obj-y += rc4.o
obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o
obj-$(CONFIG_RBTREE) += rbtree.o
obj-$(CONFIG_BITREVERSE) += bitrev.o
obj-y += list_sort.o
@ -71,16 +70,18 @@ obj-$(CONFIG_$(PHASE_)CRC16) += crc16.o
obj-y += crypto/
obj-$(CONFIG_$(PHASE_)ACPI) += acpi/
obj-$(CONFIG_$(XPL_)MD5) += md5.o
obj-$(CONFIG_ECDSA) += ecdsa/
obj-$(CONFIG_$(XPL_)RSA) += rsa/
obj-$(CONFIG_HASH) += hash-checksum.o
obj-$(CONFIG_BLAKE2) += blake2/blake2b.o
obj-$(CONFIG_$(XPL_)SHA1) += sha1.o
obj-$(CONFIG_$(XPL_)SHA256) += sha256.o
obj-$(CONFIG_$(XPL_)SHA512) += sha512.o
obj-$(CONFIG_$(XPL_)MD5_LEGACY) += md5.o
obj-$(CONFIG_$(XPL_)SHA1_LEGACY) += sha1.o
obj-$(CONFIG_$(XPL_)SHA256_LEGACY) += sha256.o
obj-$(CONFIG_$(XPL_)SHA512_LEGACY) += sha512.o
obj-$(CONFIG_CRYPT_PW) += crypt/
obj-$(CONFIG_$(XPL_)ASN1_DECODER) += asn1_decoder.o
obj-$(CONFIG_$(XPL_)ASN1_DECODER_LEGACY) += asn1_decoder.o
obj-$(CONFIG_$(XPL_)ZLIB) += zlib/
obj-$(CONFIG_$(XPL_)ZSTD) += zstd/
@ -96,6 +97,8 @@ obj-$(CONFIG_LIBAVB) += libavb/
obj-$(CONFIG_$(PHASE_)OF_LIBFDT) += libfdt/
obj-$(CONFIG_$(PHASE_)OF_REAL) += fdtdec_common.o fdtdec.o
obj-$(CONFIG_MBEDTLS_LIB) += mbedtls/
ifdef CONFIG_XPL_BUILD
obj-$(CONFIG_SPL_YMODEM_SUPPORT) += crc16-ccitt.o
obj-$(CONFIG_$(PHASE_)HASH) += crc16-ccitt.o

View File

@ -7,12 +7,13 @@ obj-$(CONFIG_$(XPL_)ASYMMETRIC_KEY_TYPE) += asymmetric_keys.o
asymmetric_keys-y := asymmetric_type.o
obj-$(CONFIG_$(XPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key.o
obj-$(CONFIG_$(XPL_)ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key_helper.o
obj-$(CONFIG_$(XPL_)ASYMMETRIC_PUBLIC_KEY_LEGACY) += public_key.o
#
# RSA public key parser
#
obj-$(CONFIG_$(XPL_)RSA_PUBLIC_KEY_PARSER) += rsa_public_key.o
obj-$(CONFIG_$(XPL_)RSA_PUBLIC_KEY_PARSER_LEGACY) += rsa_public_key.o
rsa_public_key-y := \
rsapubkey.asn1.o \
rsa_helper.o
@ -31,7 +32,8 @@ endif
# X.509 Certificate handling
#
obj-$(CONFIG_$(XPL_)X509_CERTIFICATE_PARSER) += x509_key_parser.o
x509_key_parser-y := \
x509_key_parser-y := x509_helper.o
x509_key_parser-$(CONFIG_$(XPL_)X509_CERTIFICATE_PARSER_LEGACY) += \
x509.asn1.o \
x509_akid.asn1.o \
x509_cert_parser.o \
@ -48,18 +50,20 @@ $(obj)/x509_akid.asn1.o: $(obj)/x509_akid.asn1.c $(obj)/x509_akid.asn1.h
# PKCS#7 message handling
#
obj-$(CONFIG_$(XPL_)PKCS7_MESSAGE_PARSER) += pkcs7_message.o
pkcs7_message-y := \
pkcs7_message-y := pkcs7_helper.o
pkcs7_message-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_LEGACY) += \
pkcs7.asn1.o \
pkcs7_parser.o
obj-$(CONFIG_$(XPL_)PKCS7_VERIFY) += pkcs7_verify.o
$(obj)/pkcs7_parser.o: $(obj)/pkcs7.asn1.h
$(obj)/pkcs7.asn1.o: $(obj)/pkcs7.asn1.c $(obj)/pkcs7.asn1.h
obj-$(CONFIG_$(XPL_)PKCS7_VERIFY) += pkcs7_verify.o
#
# Signed PE binary-wrapped key handling
#
obj-$(CONFIG_$(XPL_)MSCODE_PARSER) += mscode.o
obj-$(CONFIG_$(XPL_)MSCODE_PARSER_LEGACY) += mscode.o
mscode-y := \
mscode_parser.o \

View File

@ -12,7 +12,6 @@
#include <keys/asymmetric-subtype.h>
#include <keys/asymmetric-parser.h>
#endif
#include <crypto/public_key.h>
#ifdef __UBOOT__
#include <linux/bug.h>
#include <linux/compat.h>
@ -26,6 +25,7 @@
#include <linux/slab.h>
#include <linux/ctype.h>
#endif
#include <crypto/public_key.h>
#ifdef __UBOOT__
#include <keys/asymmetric-type.h>
#else

37
lib/crypto/pkcs7_helper.c Normal file
View File

@ -0,0 +1,37 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* PKCS7 helper functions
*
* Copyright (c) 2012 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*/
#include <linux/kernel.h>
#include <linux/err.h>
#include <crypto/pkcs7_parser.h>
/**
* pkcs7_get_content_data - Get access to the PKCS#7 content
* @pkcs7: The preparsed PKCS#7 message to access
* @_data: Place to return a pointer to the data
* @_data_len: Place to return the data length
* @_headerlen: Size of ASN.1 header not included in _data
*
* Get access to the data content of the PKCS#7 message. The size of the
* header of the ASN.1 object that contains it is also provided and can be used
* to adjust *_data and *_data_len to get the entire object.
*
* Returns -ENODATA if the data object was missing from the message.
*/
int pkcs7_get_content_data(const struct pkcs7_message *pkcs7,
const void **_data, size_t *_data_len,
size_t *_headerlen)
{
if (!pkcs7->data)
return -ENODATA;
*_data = pkcs7->data;
*_data_len = pkcs7->data_len;
if (_headerlen)
*_headerlen = pkcs7->data_hdrlen;
return 0;
}

View File

@ -182,34 +182,6 @@ out_no_ctx:
}
EXPORT_SYMBOL_GPL(pkcs7_parse_message);
/**
* pkcs7_get_content_data - Get access to the PKCS#7 content
* @pkcs7: The preparsed PKCS#7 message to access
* @_data: Place to return a pointer to the data
* @_data_len: Place to return the data length
* @_headerlen: Size of ASN.1 header not included in _data
*
* Get access to the data content of the PKCS#7 message. The size of the
* header of the ASN.1 object that contains it is also provided and can be used
* to adjust *_data and *_data_len to get the entire object.
*
* Returns -ENODATA if the data object was missing from the message.
*/
int pkcs7_get_content_data(const struct pkcs7_message *pkcs7,
const void **_data, size_t *_data_len,
size_t *_headerlen)
{
if (!pkcs7->data)
return -ENODATA;
*_data = pkcs7->data;
*_data_len = pkcs7->data_len;
if (_headerlen)
*_headerlen = pkcs7->data_hdrlen;
return 0;
}
EXPORT_SYMBOL_GPL(pkcs7_get_content_data);
/*
* Note an OID when we find one for later processing when we know how
* to interpret it.

View File

@ -51,38 +51,7 @@ static void public_key_describe(const struct key *asymmetric_key,
}
#endif
/*
* Destroy a public key algorithm key.
*/
void public_key_free(struct public_key *key)
{
if (key) {
kfree(key->key);
kfree(key->params);
kfree(key);
}
}
EXPORT_SYMBOL_GPL(public_key_free);
#ifdef __UBOOT__
/*
* from <linux>/crypto/asymmetric_keys/signature.c
*
* Destroy a public key signature.
*/
void public_key_signature_free(struct public_key_signature *sig)
{
int i;
if (sig) {
for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++)
free(sig->auth_ids[i]);
free(sig->s);
free(sig->digest);
free(sig);
}
}
EXPORT_SYMBOL_GPL(public_key_signature_free);
/**
* public_key_verify_signature - Verify a signature using a public key.

View File

@ -0,0 +1,39 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* X509 helper functions
*
* Copyright (c) 2012 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*/
#include <linux/compat.h>
#include <crypto/public_key.h>
/*
* Destroy a public key algorithm key.
*/
void public_key_free(struct public_key *key)
{
if (key) {
kfree(key->key);
kfree(key->params);
kfree(key);
}
}
/*
* from <linux>/crypto/asymmetric_keys/signature.c
*
* Destroy a public key signature.
*/
void public_key_signature_free(struct public_key_signature *sig)
{
int i;
if (sig) {
for (i = 0; i < ARRAY_SIZE(sig->auth_ids); i++)
kfree(sig->auth_ids[i]);
kfree(sig->s);
kfree(sig->digest);
kfree(sig);
}
}

64
lib/crypto/x509_helper.c Normal file
View File

@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* X509 helper functions
*
* Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*/
#include <linux/err.h>
#include <crypto/public_key.h>
#include <crypto/x509_parser.h>
/*
* Check for self-signedness in an X.509 cert and if found, check the signature
* immediately if we can.
*/
int x509_check_for_self_signed(struct x509_certificate *cert)
{
int ret = 0;
if (cert->raw_subject_size != cert->raw_issuer_size ||
memcmp(cert->raw_subject, cert->raw_issuer,
cert->raw_issuer_size))
goto not_self_signed;
if (cert->sig->auth_ids[0] || cert->sig->auth_ids[1]) {
/*
* If the AKID is present it may have one or two parts. If
* both are supplied, both must match.
*/
bool a = asymmetric_key_id_same(cert->skid,
cert->sig->auth_ids[1]);
bool b = asymmetric_key_id_same(cert->id,
cert->sig->auth_ids[0]);
if (!a && !b)
goto not_self_signed;
ret = -EKEYREJECTED;
if (((a && !b) || (b && !a)) &&
cert->sig->auth_ids[0] && cert->sig->auth_ids[1])
goto out;
}
ret = -EKEYREJECTED;
if (strcmp(cert->pub->pkey_algo, cert->sig->pkey_algo))
goto out;
ret = public_key_verify_signature(cert->pub, cert->sig);
if (ret == -ENOPKG) {
cert->unsupported_sig = true;
goto not_self_signed;
}
if (ret < 0)
goto out;
pr_devel("Cert Self-signature verified");
cert->self_signed = true;
out:
return ret;
not_self_signed:
return 0;
}

View File

@ -30,6 +30,8 @@
#include "x509_parser.h"
#endif
#if !CONFIG_IS_ENABLED(MBEDTLS_LIB_X509)
/*
* Set up the signature parameters in an X.509 certificate. This involves
* digesting the signed data and extracting the signature.
@ -139,61 +141,7 @@ error:
return ret;
}
/*
* Check for self-signedness in an X.509 cert and if found, check the signature
* immediately if we can.
*/
int x509_check_for_self_signed(struct x509_certificate *cert)
{
int ret = 0;
pr_devel("==>%s()\n", __func__);
if (cert->raw_subject_size != cert->raw_issuer_size ||
memcmp(cert->raw_subject, cert->raw_issuer,
cert->raw_issuer_size) != 0)
goto not_self_signed;
if (cert->sig->auth_ids[0] || cert->sig->auth_ids[1]) {
/* If the AKID is present it may have one or two parts. If
* both are supplied, both must match.
*/
bool a = asymmetric_key_id_same(cert->skid, cert->sig->auth_ids[1]);
bool b = asymmetric_key_id_same(cert->id, cert->sig->auth_ids[0]);
if (!a && !b)
goto not_self_signed;
ret = -EKEYREJECTED;
if (((a && !b) || (b && !a)) &&
cert->sig->auth_ids[0] && cert->sig->auth_ids[1])
goto out;
}
ret = -EKEYREJECTED;
if (strcmp(cert->pub->pkey_algo, cert->sig->pkey_algo) != 0)
goto out;
ret = public_key_verify_signature(cert->pub, cert->sig);
if (ret < 0) {
if (ret == -ENOPKG) {
cert->unsupported_sig = true;
ret = 0;
}
goto out;
}
pr_devel("Cert Self-signature verified");
cert->self_signed = true;
out:
pr_devel("<==%s() = %d\n", __func__, ret);
return ret;
not_self_signed:
pr_devel("<==%s() = 0 [not]\n", __func__);
return 0;
}
#endif /* !CONFIG_IS_ENABLED(MBEDTLS_LIB_X509) */
#ifndef __UBOOT__
/*

433
lib/mbedtls/Kconfig Normal file
View File

@ -0,0 +1,433 @@
choice
prompt "Select crypto libraries"
default LEGACY_CRYPTO
help
Select crypto libraries.
LEGACY_CRYPTO for legacy crypto libraries,
MBEDTLS_LIB for MbedTLS libraries.
config LEGACY_CRYPTO
bool "legacy crypto libraries"
select LEGACY_CRYPTO_BASIC
select LEGACY_CRYPTO_CERT
config MBEDTLS_LIB
bool "MbedTLS libraries"
select MBEDTLS_LIB_X509
endchoice
if LEGACY_CRYPTO || MBEDTLS_LIB_CRYPTO_ALT
config LEGACY_CRYPTO_BASIC
bool "legacy basic crypto libraries"
select MD5_LEGACY if MD5
select SHA1_LEGACY if SHA1
select SHA256_LEGACY if SHA256
select SHA512_LEGACY if SHA512
select SHA384_LEGACY if SHA384
select SPL_MD5_LEGACY if SPL_MD5
select SPL_SHA1_LEGACY if SPL_SHA1
select SPL_SHA256_LEGACY if SPL_SHA256
select SPL_SHA512_LEGACY if SPL_SHA512
select SPL_SHA384_LEGACY if SPL_SHA384
help
Enable legacy basic crypto libraries.
if LEGACY_CRYPTO_BASIC
config SHA1_LEGACY
bool "Enable SHA1 support with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SHA1
help
This option enables support of hashing using SHA1 algorithm
with legacy crypto library.
config SHA256_LEGACY
bool "Enable SHA256 support with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SHA256
help
This option enables support of hashing using SHA256 algorithm
with legacy crypto library.
config SHA512_LEGACY
bool "Enable SHA512 support with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SHA512
default y if TI_SECURE_DEVICE && FIT_SIGNATURE
help
This option enables support of hashing using SHA512 algorithm
with legacy crypto library.
config SHA384_LEGACY
bool "Enable SHA384 support with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SHA384
select SHA512_LEGACY
help
This option enables support of hashing using SHA384 algorithm
with legacy crypto library.
config MD5_LEGACY
bool "Enable MD5 support with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && MD5
help
This option enables support of hashing using MD5 algorithm
with legacy crypto library.
if SPL
config SPL_SHA1_LEGACY
bool "Enable SHA1 support in SPL with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SPL_SHA1
help
This option enables support of hashing using SHA1 algorithm
with legacy crypto library.
config SPL_SHA256_LEGACY
bool "Enable SHA256 support in SPL with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SPL_SHA256
help
This option enables support of hashing using SHA256 algorithm
with legacy crypto library.
config SPL_SHA512_LEGACY
bool "Enable SHA512 support in SPL with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SPL_SHA512
help
This option enables support of hashing using SHA512 algorithm
with legacy crypto library.
config SPL_SHA384_LEGACY
bool "Enable SHA384 support in SPL with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SPL_SHA384
select SPL_SHA512_LEGACY
help
This option enables support of hashing using SHA384 algorithm
with legacy crypto library.
config SPL_MD5_LEGACY
bool "Enable MD5 support in SPL with legacy crypto library"
depends on LEGACY_CRYPTO_BASIC && SPL_MD5
help
This option enables support of hashing using MD5 algorithm
with legacy crypto library.
endif # SPL
endif # LEGACY_CRYPTO_BASIC
config LEGACY_CRYPTO_CERT
bool "legacy certificate libraries"
select ASN1_DECODER_LEGACY if ASN1_DECODER
select ASYMMETRIC_PUBLIC_KEY_LEGACY if \
ASYMMETRIC_PUBLIC_KEY_SUBTYPE
select RSA_PUBLIC_KEY_PARSER_LEGACY if RSA_PUBLIC_KEY_PARSER
select X509_CERTIFICATE_PARSER_LEGACY if X509_CERTIFICATE_PARSER
select PKCS7_MESSAGE_PARSER_LEGACY if PKCS7_MESSAGE_PARSER
select MSCODE_PARSER_LEGACY if MSCODE_PARSER
select SPL_ASN1_DECODER_LEGACY if SPL_ASN1_DECODER
select SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY if \
SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE
select SPL_RSA_PUBLIC_KEY_PARSER_LEGACY if SPL_RSA_PUBLIC_KEY_PARSER
help
Enable legacy certificate libraries.
if LEGACY_CRYPTO_CERT
config ASN1_DECODER_LEGACY
bool "ASN1 decoder with legacy certificate library"
depends on LEGACY_CRYPTO_CERT && ASN1_DECODER
help
This option chooses legacy certificate library for ASN1 decoder.
config ASYMMETRIC_PUBLIC_KEY_LEGACY
bool "Asymmetric public key crypto with legacy certificate library"
depends on LEGACY_CRYPTO_CERT && ASYMMETRIC_PUBLIC_KEY_SUBTYPE
help
This option chooses legacy certificate library for asymmetric public
key crypto algorithm.
config RSA_PUBLIC_KEY_PARSER_LEGACY
bool "RSA public key parser with legacy certificate library"
depends on ASYMMETRIC_PUBLIC_KEY_LEGACY
select ASN1_DECODER_LEGACY
help
This option chooses legacy certificate library for RSA public key
parser.
config X509_CERTIFICATE_PARSER_LEGACY
bool "X.509 certificate parser with legacy certificate library"
depends on ASYMMETRIC_PUBLIC_KEY_LEGACY
select ASN1_DECODER_LEGACY
help
This option chooses legacy certificate library for X509 certificate
parser.
config PKCS7_MESSAGE_PARSER_LEGACY
bool "PKCS#7 message parser with legacy certificate library"
depends on X509_CERTIFICATE_PARSER_LEGACY
select ASN1_DECODER_LEGACY
help
This option chooses legacy certificate library for PKCS7 message
parser.
config MSCODE_PARSER_LEGACY
bool "MS authenticode parser with legacy certificate library"
depends on LEGACY_CRYPTO_CERT && MSCODE_PARSER
select ASN1_DECODER_LEGACY
help
This option chooses legacy certificate library for MS authenticode
parser.
if SPL
config SPL_ASN1_DECODER_LEGACY
bool "ASN1 decoder with legacy certificate library in SPL"
depends on LEGACY_CRYPTO_CERT && SPL_ASN1_DECODER
help
This option chooses legacy certificate library for ASN1 decoder in
SPL.
config SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY
bool "Asymmetric public key crypto with legacy certificate library in SPL"
depends on LEGACY_CRYPTO_CERT && SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE
help
This option chooses legacy certificate library for asymmetric public
key crypto algorithm in SPL.
config SPL_RSA_PUBLIC_KEY_PARSER_LEGACY
bool "RSA public key parser with legacy certificate library in SPL"
depends on SPL_ASYMMETRIC_PUBLIC_KEY_LEGACY
select SPL_ASN1_DECODER_LEGACY
help
This option chooses legacy certificate library for RSA public key
parser in SPL.
endif # SPL
endif # LEGACY_CRYPTO_CERT
endif # LEGACY_CRYPTO
if MBEDTLS_LIB
config MBEDTLS_LIB_CRYPTO_ALT
bool "MbedTLS crypto alternatives"
depends on MBEDTLS_LIB && !MBEDTLS_LIB_CRYPTO
select LEGACY_CRYPTO_BASIC
default y if MBEDTLS_LIB && !MBEDTLS_LIB_CRYPTO
help
Enable MbedTLS crypto alternatives.
Mutually incompatible with MBEDTLS_LIB_CRYPTO.
config MBEDTLS_LIB_CRYPTO
bool "MbedTLS crypto libraries"
select MD5_MBEDTLS if MD5
select SHA1_MBEDTLS if SHA1
select SHA256_MBEDTLS if SHA256
select SHA512_MBEDTLS if SHA512
select SHA384_MBEDTLS if SHA384
select SPL_MD5_MBEDTLS if SPL_MD5
select SPL_SHA1_MBEDTLS if SPL_SHA1
select SPL_SHA256_MBEDTLS if SPL_SHA256
select SPL_SHA512_MBEDTLS if SPL_SHA512
select SPL_SHA384_MBEDTLS if SPL_SHA384
help
Enable MbedTLS crypto libraries.
Mutually incompatible with MBEDTLS_LIB_CRYPTO_ALT.
if MBEDTLS_LIB_CRYPTO
config SHA1_MBEDTLS
bool "Enable SHA1 support with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SHA1
help
This option enables support of hashing using SHA1 algorithm
with MbedTLS crypto library.
config SHA256_MBEDTLS
bool "Enable SHA256 support with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SHA256
help
This option enables support of hashing using SHA256 algorithm
with MbedTLS crypto library.
if SHA256_MBEDTLS
config SHA256_SMALLER
bool "Enable SHA256 smaller implementation with MbedTLS crypto library"
depends on SHA256_MBEDTLS
default y if SHA256_MBEDTLS
help
This option enables support of hashing using SHA256 algorithm
smaller implementation with MbedTLS crypto library.
endif
config SHA512_MBEDTLS
bool "Enable SHA512 support with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SHA512
default y if TI_SECURE_DEVICE && FIT_SIGNATURE
help
This option enables support of hashing using SHA512 algorithm
with MbedTLS crypto library.
if SHA512_MBEDTLS
config SHA512_SMALLER
bool "Enable SHA512 smaller implementation with MbedTLS crypto library"
depends on SHA512_MBEDTLS
default y if SHA512_MBEDTLS
help
This option enables support of hashing using SHA512 algorithm
smaller implementation with MbedTLS crypto library.
endif
config SHA384_MBEDTLS
bool "Enable SHA384 support with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SHA384
select SHA512_MBEDTLS
help
This option enables support of hashing using SHA384 algorithm
with MbedTLS crypto library.
config MD5_MBEDTLS
bool "Enable MD5 support with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && MD5
help
This option enables support of hashing using MD5 algorithm
with MbedTLS crypto library.
if SPL
config SPL_SHA1_MBEDTLS
bool "Enable SHA1 support in SPL with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SPL_SHA1
help
This option enables support of hashing using SHA1 algorithm
with MbedTLS crypto library.
config SPL_SHA256_MBEDTLS
bool "Enable SHA256 support in SPL with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SPL_SHA256
help
This option enables support of hashing using SHA256 algorithm
with MbedTLS crypto library.
config SPL_SHA512_MBEDTLS
bool "Enable SHA512 support in SPL with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SPL_SHA512
help
This option enables support of hashing using SHA512 algorithm
with MbedTLS crypto library.
config SPL_SHA384_MBEDTLS
bool "Enable SHA384 support in SPL with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SPL_SHA384
select SPL_SHA512
help
This option enables support of hashing using SHA384 algorithm
with MbedTLS crypto library.
config SPL_MD5_MBEDTLS
bool "Enable MD5 support in SPL with MbedTLS crypto library"
depends on MBEDTLS_LIB_CRYPTO && SPL_MD5
help
This option enables support of hashing using MD5 algorithm
with MbedTLS crypto library.
endif # SPL
endif # MBEDTLS_LIB_CRYPTO
config MBEDTLS_LIB_X509
bool "MbedTLS certificate libraries"
select ASN1_DECODER_MBEDTLS if ASN1_DECODER
select ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \
ASYMMETRIC_PUBLIC_KEY_SUBTYPE
select RSA_PUBLIC_KEY_PARSER_MBEDTLS if RSA_PUBLIC_KEY_PARSER
select X509_CERTIFICATE_PARSER_MBEDTLS if X509_CERTIFICATE_PARSER
select PKCS7_MESSAGE_PARSER_MBEDTLS if PKCS7_MESSAGE_PARSER
select MSCODE_PARSER_MBEDTLS if MSCODE_PARSER
select SPL_ASN1_DECODER_MBEDTLS if SPL_ASN1_DECODER
select SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS if \
SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE
select SPL_RSA_PUBLIC_KEY_PARSER_MBEDTLS if SPL_RSA_PUBLIC_KEY_PARSER
help
Enable MbedTLS certificate libraries.
if MBEDTLS_LIB_X509
config ASN1_DECODER_MBEDTLS
bool "ASN1 decoder with MbedTLS certificate library"
depends on MBEDTLS_LIB_X509 && ASN1_DECODER
help
This option chooses MbedTLS certificate library for ASN1 decoder.
config ASYMMETRIC_PUBLIC_KEY_MBEDTLS
bool "Asymmetric public key crypto with MbedTLS certificate library"
depends on MBEDTLS_LIB_X509 && ASYMMETRIC_PUBLIC_KEY_SUBTYPE
help
This option chooses MbedTLS certificate library for asymmetric public
key crypto algorithm.
config RSA_PUBLIC_KEY_PARSER_MBEDTLS
bool "RSA public key parser with MbedTLS certificate library"
depends on ASYMMETRIC_PUBLIC_KEY_MBEDTLS
select ASN1_DECODER_MBEDTLS
help
This option chooses MbedTLS certificate library for RSA public key
parser.
config X509_CERTIFICATE_PARSER_MBEDTLS
bool "X.509 certificate parser with MbedTLS certificate library"
depends on ASYMMETRIC_PUBLIC_KEY_MBEDTLS
select ASN1_DECODER_MBEDTLS
help
This option chooses MbedTLS certificate library for X509 certificate
parser.
config PKCS7_MESSAGE_PARSER_MBEDTLS
bool "PKCS#7 message parser with MbedTLS certificate library"
depends on X509_CERTIFICATE_PARSER_MBEDTLS
select ASN1_DECODER_MBEDTLS
help
This option chooses MbedTLS certificate library for PKCS7 message
parser.
config MSCODE_PARSER_MBEDTLS
bool "MS authenticode parser with MbedTLS certificate library"
depends on MBEDTLS_LIB_X509 && MSCODE_PARSER
select ASN1_DECODER_MBEDTLS
help
This option chooses MbedTLS certificate library for MS authenticode
parser.
if SPL
config SPL_ASN1_DECODER_MBEDTLS
bool "ASN1 decoder with MbedTLS certificate library in SPL"
depends on MBEDTLS_LIB_X509 && SPL_ASN1_DECODER
help
This option chooses MbedTLS certificate library for ASN1 decoder in
SPL.
config SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS
bool "Asymmetric public key crypto with MbedTLS certificate library in SPL"
depends on MBEDTLS_LIB_X509 && SPL_ASYMMETRIC_PUBLIC_KEY_SUBTYPE
help
This option chooses MbedTLS certificate library for asymmetric public
key crypto algorithm in SPL.
config SPL_RSA_PUBLIC_KEY_PARSER_MBEDTLS
bool "RSA public key parser with MbedTLS certificate library in SPL"
depends on SPL_ASYMMETRIC_PUBLIC_KEY_MBEDTLS
select SPL_ASN1_DECODER_MBEDTLS
help
This option chooses MbedTLS certificate library for RSA public key
parser in SPL.
endif # SPL
endif # MBEDTLS_LIB_X509
endif # MBEDTLS_LIB

56
lib/mbedtls/Makefile Normal file
View File

@ -0,0 +1,56 @@
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright (c) 2024 Linaro Limited
# Author: Raymond Mao <raymond.mao@linaro.org>
MBEDTLS_LIB_DIR = external/mbedtls/library
# shim layer for hash
obj-$(CONFIG_$(SPL_)MD5_MBEDTLS) += md5.o
obj-$(CONFIG_$(SPL_)SHA1_MBEDTLS) += sha1.o
obj-$(CONFIG_$(SPL_)SHA256_MBEDTLS) += sha256.o
obj-$(CONFIG_$(SPL_)SHA512_MBEDTLS) += sha512.o
# x509 libraries
obj-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \
public_key.o
obj-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \
x509_cert_parser.o
obj-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_MBEDTLS) += pkcs7_parser.o
obj-$(CONFIG_$(SPL_)MSCODE_PARSER_MBEDTLS) += mscode_parser.o
obj-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER_MBEDTLS) += rsa_helper.o
# MbedTLS crypto library
obj-$(CONFIG_MBEDTLS_LIB) += mbedtls_lib_crypto.o
mbedtls_lib_crypto-y := \
$(MBEDTLS_LIB_DIR)/platform_util.o \
$(MBEDTLS_LIB_DIR)/constant_time.o \
$(MBEDTLS_LIB_DIR)/md.o
mbedtls_lib_crypto-$(CONFIG_$(SPL_)MD5_MBEDTLS) += $(MBEDTLS_LIB_DIR)/md5.o
mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA1_MBEDTLS) += $(MBEDTLS_LIB_DIR)/sha1.o
mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA256_MBEDTLS) += \
$(MBEDTLS_LIB_DIR)/sha256.o
mbedtls_lib_crypto-$(CONFIG_$(SPL_)SHA512_MBEDTLS) += \
$(MBEDTLS_LIB_DIR)/sha512.o
# MbedTLS X509 library
obj-$(CONFIG_MBEDTLS_LIB_X509) += mbedtls_lib_x509.o
mbedtls_lib_x509-y := $(MBEDTLS_LIB_DIR)/x509.o
mbedtls_lib_x509-$(CONFIG_$(SPL_)ASN1_DECODER_MBEDTLS) += \
$(MBEDTLS_LIB_DIR)/asn1parse.o \
$(MBEDTLS_LIB_DIR)/asn1write.o \
$(MBEDTLS_LIB_DIR)/oid.o
mbedtls_lib_x509-$(CONFIG_$(SPL_)RSA_PUBLIC_KEY_PARSER_MBEDTLS) += \
$(MBEDTLS_LIB_DIR)/bignum.o \
$(MBEDTLS_LIB_DIR)/bignum_core.o \
$(MBEDTLS_LIB_DIR)/rsa.o \
$(MBEDTLS_LIB_DIR)/rsa_alt_helpers.o
mbedtls_lib_x509-$(CONFIG_$(SPL_)ASYMMETRIC_PUBLIC_KEY_MBEDTLS) += \
$(MBEDTLS_LIB_DIR)/pk.o \
$(MBEDTLS_LIB_DIR)/pk_wrap.o \
$(MBEDTLS_LIB_DIR)/pkparse.o
mbedtls_lib_x509-$(CONFIG_$(SPL_)X509_CERTIFICATE_PARSER_MBEDTLS) += \
$(MBEDTLS_LIB_DIR)/x509_crl.o \
$(MBEDTLS_LIB_DIR)/x509_crt.o
mbedtls_lib_x509-$(CONFIG_$(SPL_)PKCS7_MESSAGE_PARSER_MBEDTLS) += \
$(MBEDTLS_LIB_DIR)/pkcs7.o

View File

@ -0,0 +1,2 @@
# Classify all '.function' files as C for syntax highlighting purposes
*.function linguist-language=C

View File

@ -0,0 +1,35 @@
---
name: Bug report
about: To report a bug, please fill this form.
title: ''
labels: ''
assignees: ''
---
### Summary
### System information
Mbed TLS version (number or commit id):
Operating system and version:
Configuration (if not default, please attach `mbedtls_config.h`):
Compiler and options (if you used a pre-built binary, please indicate how you obtained it):
Additional environment information:
### Expected behavior
### Actual behavior
### Steps to reproduce
### Additional information

View File

@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Mbed TLS security team
url: mailto:mbed-tls-security@lists.trustedfirmware.org
about: Report a security vulnerability.
- name: Mbed TLS mailing list
url: https://lists.trustedfirmware.org/mailman3/lists/mbed-tls.lists.trustedfirmware.org
about: Mbed TLS community support and general discussion.

View File

@ -0,0 +1,17 @@
---
name: Enhancement request
about: To request an enhancement, please fill this form.
title: ''
labels: ''
assignees: ''
---
### Suggested enhancement
### Justification
Mbed TLS needs this because

View File

@ -0,0 +1,27 @@
## Description
Please write a few sentences describing the overall goals of the pull request's commits.
## PR checklist
Please tick as appropriate and edit the reasons (e.g.: "backport: not needed because this is a new feature")
- [ ] **changelog** provided, or not required
- [ ] **backport** done, or not required
- [ ] **tests** provided, or not required
## Notes for the submitter
Please refer to the [contributing guidelines](https://github.com/Mbed-TLS/mbedtls/blob/development/CONTRIBUTING.md), especially the
checklist for PR contributors.
Help make review efficient:
* Multiple simple commits
- please structure your PR into a series of small commits, each of which does one thing
* Avoid force-push
- please do not force-push to update your PR - just add new commit(s)
* See our [Guidelines for Contributors](https://mbed-tls.readthedocs.io/en/latest/reviews/review-for-contributors/) for more details about the review process.

69
lib/mbedtls/external/mbedtls/.gitignore vendored Normal file
View File

@ -0,0 +1,69 @@
# Random seed file created by test scripts and sample programs
seedfile
# MBEDTLS_PSA_INJECT_ENTROPY seed file created by the test framework
00000000ffffff52.psa_its
# CMake build artifacts:
CMakeCache.txt
CMakeFiles
CTestTestfile.cmake
cmake_install.cmake
Testing
# CMake generates *.dir/ folders for in-tree builds (used by MSVC projects), ignore all of those:
*.dir/
# MSVC files generated by CMake:
/*.sln
/*.vcxproj
/*.filters
# Test coverage build artifacts:
Coverage
*.gcno
*.gcda
coverage-summary.txt
# generated by scripts/memory.sh
massif-*
# Eclipse project files
.cproject
.project
/.settings
# Unix-like build artifacts:
*.o
# MSVC build artifacts:
*.exe
*.pdb
*.ilk
*.lib
# Python build artifacts:
*.pyc
# CMake generates *.dir/ folders for in-tree builds (used by MSVC projects), ignore all of those:
*.dir/
# Microsoft CMake extension for Visual Studio Code generates a build directory by default
/build/
# Generated documentation:
/apidoc
# PSA Crypto compliance test repo, cloned by test_psa_compliance.py
/psa-arch-tests
# Editor navigation files:
/GPATH
/GRTAGS
/GSYMS
/GTAGS
/TAGS
/cscope*.out
/tags
# clangd compilation database
compile_commands.json
# clangd index files
/.cache/clangd/index/

View File

@ -0,0 +1,3 @@
[submodule "framework"]
path = framework
url = https://github.com/Mbed-TLS/mbedtls-framework

View File

@ -0,0 +1,3 @@
default:\
:langmap=c\:.c.h.function:\

View File

@ -0,0 +1,4 @@
[mypy]
mypy_path = scripts
namespace_packages = True
warn_unused_configs = True

80
lib/mbedtls/external/mbedtls/.pylintrc vendored Normal file
View File

@ -0,0 +1,80 @@
[MASTER]
init-hook='import sys; sys.path.append("scripts")'
min-similarity-lines=10
[BASIC]
# We're ok with short funtion argument names.
# [invalid-name]
argument-rgx=[a-z_][a-z0-9_]*$
# Allow filter and map.
# [bad-builtin]
bad-functions=input
# We prefer docstrings, but we don't require them on all functions.
# Require them only on long functions (for some value of long).
# [missing-docstring]
docstring-min-length=10
# No upper limit on method names. Pylint <2.1.0 has an upper limit of 30.
# [invalid-name]
method-rgx=[a-z_][a-z0-9_]{2,}$
# Allow module names containing a dash (but no underscore or uppercase letter).
# They are whole programs, not meant to be included by another module.
# [invalid-name]
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+)|[a-z][-0-9a-z]+)$
# Some functions don't need docstrings.
# [missing-docstring]
no-docstring-rgx=(run_)?main$
# We're ok with short local or global variable names.
# [invalid-name]
variable-rgx=[a-z_][a-z0-9_]*$
[DESIGN]
# Allow more than the default 7 attributes.
# [too-many-instance-attributes]
max-attributes=15
[FORMAT]
# Allow longer modules than the default recommended maximum.
# [too-many-lines]
max-module-lines=2000
[MESSAGES CONTROL]
# * locally-disabled, locally-enabled: If we disable or enable a message
# locally, it's by design. There's no need to clutter the Pylint output
# with this information.
# * logging-format-interpolation: Pylint warns about things like
# ``log.info('...'.format(...))``. It insists on ``log.info('...', ...)``.
# This is of minor utility (mainly a performance gain when there are
# many messages that use formatting and are below the log level).
# Some versions of Pylint (including 1.8, which is the version on
# Ubuntu 18.04) only recognize old-style format strings using '%',
# and complain about something like ``log.info('{}', foo)`` with
# logging-too-many-args (Pylint supports new-style formatting if
# declared globally with logging_format_style under [LOGGING] but
# this requires Pylint >=2.2).
# * no-else-return: Allow the perfectly reasonable idiom
# if condition1:
# return value1
# else:
# return value2
# * unnecessary-pass: If we take the trouble of adding a line with "pass",
# it's because we think the code is clearer that way.
disable=locally-disabled,locally-enabled,logging-format-interpolation,no-else-return,unnecessary-pass
[REPORTS]
# Don't diplay statistics. Just the facts.
reports=no
[VARIABLES]
# Allow unused variables if their name starts with an underscore.
# [unused-argument]
dummy-variables-rgx=_.*
[SIMILARITIES]
# Ignore imports when computing similarities.
ignore-imports=yes

View File

@ -0,0 +1,37 @@
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Include the framework submodule in the build
submodules:
include:
- framework
# Set the version of Python and other tools you might need
build:
os: ubuntu-20.04
tools:
python: "3.9"
jobs:
pre_build:
- ./scripts/apidoc_full.sh
- breathe-apidoc -o docs/api apidoc/xml
post_build:
- |
# Work around Readthedocs bug: Command parsing fails if the 'if' statement is on the first line
if [ "$READTHEDOCS_VERSION" = "development" ]; then
"$READTHEDOCS_VIRTUALENV_PATH/bin/rtd" projects "Mbed TLS API" redirects sync --wet-run -f docs/redirects.yaml
fi
# Build documentation in the docs/ directory with Sphinx
sphinx:
builder: dirhtml
configuration: docs/conf.py
# Optionally declare the Python requirements required to build your docs
python:
install:
- requirements: docs/requirements.txt

View File

@ -0,0 +1,28 @@
# Declare python as our language. This way we get our chosen Python version,
# and pip is available. Gcc and clang are available anyway.
dist: jammy
os: linux
language: python
python: 3.10
cache: ccache
branches:
only:
coverity_scan
install:
- $PYTHON scripts/min_requirements.py
env:
global:
- SEED=1
- secure: "GF/Fde5fkm15T/RNykrjrPV5Uh1KJ70cP308igL6Xkk3eJmqkkmWCe9JqRH12J3TeWw2fu9PYPHt6iFSg6jasgqysfUyg+W03knRT5QNn3h5eHgt36cQJiJr6t3whPrRaiM6U9omE0evm+c0cAwlkA3GGSMw8Z+na4EnKI6OFCo="
addons:
coverity_scan:
project:
name: "ARMmbed/mbedtls"
notification_email: support-mbedtls@arm.com
build_command_prepend:
build_command: make
branch_pattern: coverity_scan

View File

@ -0,0 +1,240 @@
# Configuration options for Uncrustify specifying the Mbed TLS code style.
#
# Note: The code style represented by this file has not yet been introduced
# to Mbed TLS.
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# Wrap lines at 100 characters
code_width = 100
# Allow splitting long for statements between the condition statements
ls_for_split_full = true
# Allow splitting function calls between arguments
ls_func_split_full = true
input_tab_size = 4
# Spaces-only indentation
indent_with_tabs = 0
indent_columns = 4
# Indent 'case' 1 level from 'switch'
indent_switch_case = indent_columns
# Line-up strings broken by '\'
indent_align_string = true
# Braces on the same line (Egyptian-style braces)
nl_enum_brace = remove
nl_union_brace = remove
nl_struct_brace = remove
nl_do_brace = remove
nl_if_brace = remove
nl_for_brace = remove
nl_else_brace = remove
nl_while_brace = remove
nl_switch_brace = remove
# Braces on same line as keywords that follow them - 'else' and the 'while' in 'do {} while ()';
nl_brace_else = remove
nl_brace_while = remove
# Space before else on the same line
sp_brace_else = add
# If else is on the same line as '{', force exactly 1 space between them
sp_else_brace = force
# Functions are the exception and have braces on the next line
nl_fcall_brace = add
nl_fdef_brace = add
# Force exactly one space between ')' and '{' in statements
sp_sparen_brace = force
# At least 1 space around assignment
sp_assign = add
# Remove spaces around the preprocessor '##' token-concatenate
sp_pp_concat = ignore
# At least 1 space around '||' and '&&'
sp_bool = add
# But no space after the '!' operator
sp_not = remove
# No space after the bitwise-not '~' operator
sp_inv = remove
# No space after the addressof '&' operator
sp_addr = remove
# No space around the member '.' and '->' operators
sp_member = remove
# No space after the dereference '*' operator
sp_deref = remove
# No space after a unary negation '-'
sp_sign = remove
# No space between the '++'/'--' operator and its operand
sp_incdec = remove
# At least 1 space around comparison operators
sp_compare = add
# Remove spaces inside all kinds of parentheses:
# Remove spaces inside parentheses
sp_inside_paren = remove
# No spaces inside statement parentheses
sp_inside_sparen = remove
# No spaces inside cast parentheses '( char )x' -> '(char)x'
sp_inside_paren_cast = remove
# No spaces inside function parentheses
sp_inside_fparen = remove
# (The case where the function has no parameters/arguments)
sp_inside_fparens = remove
# No spaces inside the first parentheses in a function type
sp_inside_tparen = remove
# (Uncrustify >= 0.74.0) No spaces inside parens in for statements
sp_inside_for = remove
# Remove spaces between nested parentheses '( (' -> '(('
sp_paren_paren = remove
# (Uncrustify >= 0.74.0)
sp_sparen_paren = remove
# Remove spaces between ')' and adjacent '('
sp_cparen_oparen = remove
# (Uncrustify >= 0.73.0) space between 'do' and '{'
sp_do_brace_open = force
# (Uncrustify >= 0.73.0) space between '}' and 'while'
sp_brace_close_while = force
# At least 1 space before a '*' pointer star
sp_before_ptr_star = add
# Remove spaces between pointer stars
sp_between_ptr_star = remove
# No space after a pointer star
sp_after_ptr_star = remove
# But allow a space in the case of e.g. char * const x;
sp_after_ptr_star_qualifier = ignore
# Remove space after star in a function return type
sp_after_ptr_star_func = remove
# At least 1 space after a type in variable definition etc
sp_after_type = add
# Force exactly 1 space between a statement keyword (e.g. 'if') and an opening parenthesis
sp_before_sparen = force
# Remove a space before a ';'
sp_before_semi = remove
# (Uncrustify >= 0.73.0) Remove space before a semi in a non-empty for
sp_before_semi_for = remove
# (Uncrustify >= 0.73.0) Remove space in empty first statement of a for
sp_before_semi_for_empty = remove
# (Uncrustify >= 0.74.0) Remove space in empty middle statement of a for
sp_between_semi_for_empty = remove
# Add a space after a ';' (unless a comment follows)
sp_after_semi = add
# (Uncrustify >= 0.73.0) Add a space after a semi in non-empty for statements
sp_after_semi_for = add
# (Uncrustify >= 0.73.0) No space after final semi in empty for statements
sp_after_semi_for_empty = remove
# Remove spaces on the inside of square brackets '[]'
sp_inside_square = remove
# Must have at least 1 space after a comma
sp_after_comma = add
# Must not have a space before a comma
sp_before_comma = remove
# No space before the ':' in a case statement
sp_before_case_colon = remove
# Must have space after a cast - '(char)x' -> '(char) x'
sp_after_cast = add
# No space between 'sizeof' and '('
sp_sizeof_paren = remove
# At least 1 space inside '{ }'
sp_inside_braces = add
# At least 1 space inside '{ }' in an enum
sp_inside_braces_enum = add
# At least 1 space inside '{ }' in a struct
sp_inside_braces_struct = add
# At least 1 space between a function return type and the function name
sp_type_func = add
# No space between a function name and its arguments/parameters
sp_func_proto_paren = remove
sp_func_def_paren = remove
sp_func_call_paren = remove
# No space between '__attribute__' and '('
sp_attribute_paren = remove
# No space between 'defined' and '(' in preprocessor conditions
sp_defined_paren = remove
# At least 1 space between a macro's name and its definition
sp_macro = add
sp_macro_func = add
# Force exactly 1 space between a '}' and the name of a typedef if on the same line
sp_brace_typedef = force
# At least 1 space before a '\' line continuation
sp_before_nl_cont = add
# At least 1 space around '?' and ':' in ternary statements
sp_cond_colon = add
sp_cond_question = add
# Space between #else/#endif and comment afterwards
sp_endif_cmt = add
# Remove newlines at the start of a file
nl_start_of_file = remove
# At least 1 newline at the end of a file
nl_end_of_file = add
nl_end_of_file_min = 1
# Add braces in single-line statements
mod_full_brace_do = add
mod_full_brace_for = add
mod_full_brace_if = add
mod_full_brace_while = add
# Remove parentheses from return statements
mod_paren_on_return = remove
# Disable removal of leading spaces in a multi-line comment if the first and
# last lines are the same length
cmt_multi_check_last = false

View File

@ -0,0 +1 @@
/Makefile

View File

@ -0,0 +1,2 @@
add_subdirectory(everest)
add_subdirectory(p256-m)

View File

@ -0,0 +1,3 @@
THIRDPARTY_DIR := $(dir $(lastword $(MAKEFILE_LIST)))
include $(THIRDPARTY_DIR)/everest/Makefile.inc
include $(THIRDPARTY_DIR)/p256-m/Makefile.inc

View File

@ -0,0 +1 @@
Makefile

View File

@ -0,0 +1,42 @@
set(everest_target "${MBEDTLS_TARGET_PREFIX}everest")
add_library(${everest_target}
library/everest.c
library/x25519.c
library/Hacl_Curve25519_joined.c)
target_include_directories(${everest_target}
PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<BUILD_INTERFACE:${MBEDTLS_DIR}/include>
$<INSTALL_INTERFACE:include>
PRIVATE include/everest
include/everest/kremlib
${MBEDTLS_DIR}/library/)
# Pass-through MBEDTLS_CONFIG_FILE and MBEDTLS_USER_CONFIG_FILE
# This must be duplicated from library/CMakeLists.txt because
# everest is not directly linked against any mbedtls targets
# so does not inherit the compile definitions.
if(MBEDTLS_CONFIG_FILE)
target_compile_definitions(${everest_target}
PUBLIC MBEDTLS_CONFIG_FILE="${MBEDTLS_CONFIG_FILE}")
endif()
if(MBEDTLS_USER_CONFIG_FILE)
target_compile_definitions(${everest_target}
PUBLIC MBEDTLS_USER_CONFIG_FILE="${MBEDTLS_USER_CONFIG_FILE}")
endif()
if(INSTALL_MBEDTLS_HEADERS)
install(DIRECTORY include/everest
DESTINATION include
FILE_PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
FILES_MATCHING PATTERN "*.h")
endif(INSTALL_MBEDTLS_HEADERS)
install(TARGETS ${everest_target}
EXPORT MbedTLSTargets
DESTINATION ${CMAKE_INSTALL_LIBDIR}
PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)

View File

@ -0,0 +1,6 @@
THIRDPARTY_INCLUDES+=-I$(THIRDPARTY_DIR)/everest/include -I$(THIRDPARTY_DIR)/everest/include/everest -I$(THIRDPARTY_DIR)/everest/include/everest/kremlib
THIRDPARTY_CRYPTO_OBJECTS+= \
$(THIRDPARTY_DIR)/everest/library/everest.o \
$(THIRDPARTY_DIR)/everest/library/x25519.o \
$(THIRDPARTY_DIR)/everest/library/Hacl_Curve25519_joined.o

View File

@ -0,0 +1,5 @@
The files in this directory stem from [Project Everest](https://project-everest.github.io/) and are distributed under the Apache 2.0 license.
This is a formally verified implementation of Curve25519-based handshakes. The C code is automatically derived from the (verified) [original implementation](https://github.com/project-everest/hacl-star/tree/master/code/curve25519) in the [F* language](https://github.com/fstarlang/fstar) by [KreMLin](https://github.com/fstarlang/kremlin). In addition to the improved safety and security of the implementation, it is also significantly faster than the default implementation of Curve25519 in mbedTLS.
The caveat is that not all platforms are supported, although the version in `everest/library/legacy` should work on most systems. The main issue is that some platforms do not provide a 128-bit integer type and KreMLin therefore has to use additional (also verified) code to simulate them, resulting in less of a performance gain overall. Explicitly supported platforms are currently `x86` and `x86_64` using gcc or clang, and Visual C (2010 and later).

View File

@ -0,0 +1,21 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fbuiltin-uint128 -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __Hacl_Curve25519_H
#define __Hacl_Curve25519_H
#include "kremlib.h"
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint);
#define __Hacl_Curve25519_H_DEFINED
#endif

View File

@ -0,0 +1,234 @@
/*
* Interface to code from Project Everest
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* 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_EVEREST_H
#define MBEDTLS_EVEREST_H
#include "everest/x25519.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Defines the source of the imported EC key.
*/
typedef enum
{
MBEDTLS_EVEREST_ECDH_OURS, /**< Our key. */
MBEDTLS_EVEREST_ECDH_THEIRS, /**< The key of the peer. */
} mbedtls_everest_ecdh_side;
typedef struct {
mbedtls_x25519_context ctx;
} mbedtls_ecdh_context_everest;
/**
* \brief This function sets up the ECDH context with the information
* given.
*
* 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.
* \param grp_id The group id of the group to set up the context for.
*
* \return \c 0 on success.
*/
int mbedtls_everest_setup( mbedtls_ecdh_context_everest *ctx, int grp_id );
/**
* \brief This function frees a context.
*
* \param ctx The context to free.
*/
void mbedtls_everest_free( mbedtls_ecdh_context_everest *ctx );
/**
* \brief This function generates a public key and a TLS
* ServerKeyExchange payload.
*
* 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 the ECP group (grp) of the
* \p ctx context has already been properly set,
* for example, using mbedtls_ecp_group_load().
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param olen The number of characters written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_make_params( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng );
/**
* \brief This function parses and processes a TLS ServerKeyExchange
* payload.
*
* This is the first function used by a TLS client for ECDHE
* ciphersuites.
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param buf The pointer to the start of the input buffer.
* \param end The address for one Byte past the end of the buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_everest_read_params( mbedtls_ecdh_context_everest *ctx,
const unsigned char **buf, const unsigned char *end );
/**
* \brief This function parses and processes a TLS ServerKeyExchange
* payload.
*
* This is the first function used by a TLS client for ECDHE
* ciphersuites.
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param buf The pointer to the start of the input buffer.
* \param end The address for one Byte past the end of the buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_everest_read_params( mbedtls_ecdh_context_everest *ctx,
const unsigned char **buf, const unsigned char *end );
/**
* \brief This function sets up an ECDH context from an EC key.
*
* 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.
* \param key The EC key to use.
* \param side Defines the source of the key: 1: Our key, or
* 0: The key of the peer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_everest_get_params( mbedtls_ecdh_context_everest *ctx, const mbedtls_ecp_keypair *key,
mbedtls_everest_ecdh_side side );
/**
* \brief This function generates a public key and a TLS
* ClientKeyExchange payload.
*
* This is the second function used by a TLS client for ECDH(E)
* ciphersuites.
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The size of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_make_public( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng );
/**
* \brief This function parses and processes a TLS ClientKeyExchange
* payload.
*
* 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().)
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param buf The start of the input buffer.
* \param blen The length of the input buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_read_public( mbedtls_ecdh_context_everest *ctx,
const unsigned char *buf, size_t blen );
/**
* \brief This function derives and exports the shared secret.
*
* This is the last function used by both TLS client
* and servers.
*
* \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.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_calc_secret( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng );
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_EVEREST_H */

View File

@ -0,0 +1,29 @@
/*
* Copyright 2016-2018 INRIA and Microsoft Corporation
*
* 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) and
* originated from Project Everest (https://project-everest.github.io/)
*/
#ifndef __KREMLIB_H
#define __KREMLIB_H
#include "kremlin/internal/target.h"
#include "kremlin/internal/types.h"
#include "kremlin/c_endianness.h"
#endif /* __KREMLIB_H */

View File

@ -0,0 +1,124 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir dist/uint128 -skip-compilation -extract-uints -add-include <inttypes.h> -add-include <stdbool.h> -add-include "kremlin/internal/types.h" -bundle FStar.UInt128=* extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __FStar_UInt128_H
#define __FStar_UInt128_H
#include <inttypes.h>
#include <stdbool.h>
#include "kremlin/internal/types.h"
uint64_t FStar_UInt128___proj__Mkuint128__item__low(FStar_UInt128_uint128 projectee);
uint64_t FStar_UInt128___proj__Mkuint128__item__high(FStar_UInt128_uint128 projectee);
typedef FStar_UInt128_uint128 FStar_UInt128_t;
FStar_UInt128_uint128 FStar_UInt128_add(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128
FStar_UInt128_add_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_add_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_sub(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128
FStar_UInt128_sub_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_sub_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_logand(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_logxor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_logor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_lognot(FStar_UInt128_uint128 a);
FStar_UInt128_uint128 FStar_UInt128_shift_left(FStar_UInt128_uint128 a, uint32_t s);
FStar_UInt128_uint128 FStar_UInt128_shift_right(FStar_UInt128_uint128 a, uint32_t s);
bool FStar_UInt128_eq(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_gt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_lt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_gte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_lte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_eq_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_gte_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_uint64_to_uint128(uint64_t a);
uint64_t FStar_UInt128_uint128_to_uint64(FStar_UInt128_uint128 a);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Question_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Question_Hat)(
FStar_UInt128_uint128 x0,
FStar_UInt128_uint128 x1
);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Amp_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Hat_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Bar_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Less_Less_Hat)(FStar_UInt128_uint128 x0, uint32_t x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Greater_Greater_Hat)(FStar_UInt128_uint128 x0, uint32_t x1);
extern bool (*FStar_UInt128_op_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool
(*FStar_UInt128_op_Greater_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool (*FStar_UInt128_op_Less_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool
(*FStar_UInt128_op_Greater_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool
(*FStar_UInt128_op_Less_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
FStar_UInt128_uint128 FStar_UInt128_mul32(uint64_t x, uint32_t y);
FStar_UInt128_uint128 FStar_UInt128_mul_wide(uint64_t x, uint64_t y);
#define __FStar_UInt128_H_DEFINED
#endif

View File

@ -0,0 +1,280 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir dist/minimal -skip-compilation -extract-uints -add-include <inttypes.h> -add-include <stdbool.h> -add-include "kremlin/internal/compat.h" -add-include "kremlin/internal/types.h" -bundle FStar.UInt64+FStar.UInt32+FStar.UInt16+FStar.UInt8=* extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8_H
#define __FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8_H
#include <inttypes.h>
#include <stdbool.h>
#include "kremlin/internal/compat.h"
#include "kremlin/internal/types.h"
extern Prims_int FStar_UInt64_n;
extern Prims_int FStar_UInt64_v(uint64_t x0);
extern uint64_t FStar_UInt64_uint_to_t(Prims_int x0);
extern uint64_t FStar_UInt64_add(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_add_underspec(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_add_mod(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_sub(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_sub_underspec(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_sub_mod(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul_underspec(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul_mod(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul_div(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_div(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_rem(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_logand(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_logxor(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_logor(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_lognot(uint64_t x0);
extern uint64_t FStar_UInt64_shift_right(uint64_t x0, uint32_t x1);
extern uint64_t FStar_UInt64_shift_left(uint64_t x0, uint32_t x1);
extern bool FStar_UInt64_eq(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_gt(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_gte(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_lt(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_lte(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_minus(uint64_t x0);
extern uint32_t FStar_UInt64_n_minus_one;
uint64_t FStar_UInt64_eq_mask(uint64_t a, uint64_t b);
uint64_t FStar_UInt64_gte_mask(uint64_t a, uint64_t b);
extern Prims_string FStar_UInt64_to_string(uint64_t x0);
extern uint64_t FStar_UInt64_of_string(Prims_string x0);
extern Prims_int FStar_UInt32_n;
extern Prims_int FStar_UInt32_v(uint32_t x0);
extern uint32_t FStar_UInt32_uint_to_t(Prims_int x0);
extern uint32_t FStar_UInt32_add(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_add_underspec(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_add_mod(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_sub(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_sub_underspec(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_sub_mod(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul_underspec(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul_mod(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul_div(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_div(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_rem(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_logand(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_logxor(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_logor(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_lognot(uint32_t x0);
extern uint32_t FStar_UInt32_shift_right(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_shift_left(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_eq(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_gt(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_gte(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_lt(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_lte(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_minus(uint32_t x0);
extern uint32_t FStar_UInt32_n_minus_one;
uint32_t FStar_UInt32_eq_mask(uint32_t a, uint32_t b);
uint32_t FStar_UInt32_gte_mask(uint32_t a, uint32_t b);
extern Prims_string FStar_UInt32_to_string(uint32_t x0);
extern uint32_t FStar_UInt32_of_string(Prims_string x0);
extern Prims_int FStar_UInt16_n;
extern Prims_int FStar_UInt16_v(uint16_t x0);
extern uint16_t FStar_UInt16_uint_to_t(Prims_int x0);
extern uint16_t FStar_UInt16_add(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_add_underspec(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_add_mod(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_sub(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_sub_underspec(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_sub_mod(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul_underspec(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul_mod(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul_div(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_div(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_rem(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_logand(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_logxor(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_logor(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_lognot(uint16_t x0);
extern uint16_t FStar_UInt16_shift_right(uint16_t x0, uint32_t x1);
extern uint16_t FStar_UInt16_shift_left(uint16_t x0, uint32_t x1);
extern bool FStar_UInt16_eq(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_gt(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_gte(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_lt(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_lte(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_minus(uint16_t x0);
extern uint32_t FStar_UInt16_n_minus_one;
uint16_t FStar_UInt16_eq_mask(uint16_t a, uint16_t b);
uint16_t FStar_UInt16_gte_mask(uint16_t a, uint16_t b);
extern Prims_string FStar_UInt16_to_string(uint16_t x0);
extern uint16_t FStar_UInt16_of_string(Prims_string x0);
extern Prims_int FStar_UInt8_n;
extern Prims_int FStar_UInt8_v(uint8_t x0);
extern uint8_t FStar_UInt8_uint_to_t(Prims_int x0);
extern uint8_t FStar_UInt8_add(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_add_underspec(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_add_mod(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_sub(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_sub_underspec(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_sub_mod(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul_underspec(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul_mod(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul_div(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_div(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_rem(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_logand(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_logxor(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_logor(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_lognot(uint8_t x0);
extern uint8_t FStar_UInt8_shift_right(uint8_t x0, uint32_t x1);
extern uint8_t FStar_UInt8_shift_left(uint8_t x0, uint32_t x1);
extern bool FStar_UInt8_eq(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_gt(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_gte(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_lt(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_lte(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_minus(uint8_t x0);
extern uint32_t FStar_UInt8_n_minus_one;
uint8_t FStar_UInt8_eq_mask(uint8_t a, uint8_t b);
uint8_t FStar_UInt8_gte_mask(uint8_t a, uint8_t b);
extern Prims_string FStar_UInt8_to_string(uint8_t x0);
extern uint8_t FStar_UInt8_of_string(Prims_string x0);
typedef uint8_t FStar_UInt8_byte;
#define __FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8_H_DEFINED
#endif

View File

@ -0,0 +1,204 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_ENDIAN_H
#define __KREMLIN_ENDIAN_H
#include <string.h>
#include <inttypes.h>
/******************************************************************************/
/* Implementing C.fst (part 2: endian-ness macros) */
/******************************************************************************/
/* ... for Linux */
#if defined(__linux__) || defined(__CYGWIN__)
# include <endian.h>
/* ... for OSX */
#elif defined(__APPLE__)
# include <libkern/OSByteOrder.h>
# define htole64(x) OSSwapHostToLittleInt64(x)
# define le64toh(x) OSSwapLittleToHostInt64(x)
# define htobe64(x) OSSwapHostToBigInt64(x)
# define be64toh(x) OSSwapBigToHostInt64(x)
# define htole16(x) OSSwapHostToLittleInt16(x)
# define le16toh(x) OSSwapLittleToHostInt16(x)
# define htobe16(x) OSSwapHostToBigInt16(x)
# define be16toh(x) OSSwapBigToHostInt16(x)
# define htole32(x) OSSwapHostToLittleInt32(x)
# define le32toh(x) OSSwapLittleToHostInt32(x)
# define htobe32(x) OSSwapHostToBigInt32(x)
# define be32toh(x) OSSwapBigToHostInt32(x)
/* ... for Solaris */
#elif defined(__sun__)
# include <sys/byteorder.h>
# define htole64(x) LE_64(x)
# define le64toh(x) LE_64(x)
# define htobe64(x) BE_64(x)
# define be64toh(x) BE_64(x)
# define htole16(x) LE_16(x)
# define le16toh(x) LE_16(x)
# define htobe16(x) BE_16(x)
# define be16toh(x) BE_16(x)
# define htole32(x) LE_32(x)
# define le32toh(x) LE_32(x)
# define htobe32(x) BE_32(x)
# define be32toh(x) BE_32(x)
/* ... for the BSDs */
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
# include <sys/endian.h>
#elif defined(__OpenBSD__)
# include <endian.h>
/* ... for Windows (MSVC)... not targeting XBOX 360! */
#elif defined(_MSC_VER)
# include <stdlib.h>
# define htobe16(x) _byteswap_ushort(x)
# define htole16(x) (x)
# define be16toh(x) _byteswap_ushort(x)
# define le16toh(x) (x)
# define htobe32(x) _byteswap_ulong(x)
# define htole32(x) (x)
# define be32toh(x) _byteswap_ulong(x)
# define le32toh(x) (x)
# define htobe64(x) _byteswap_uint64(x)
# define htole64(x) (x)
# define be64toh(x) _byteswap_uint64(x)
# define le64toh(x) (x)
/* ... for Windows (GCC-like, e.g. mingw or clang) */
#elif (defined(_WIN32) || defined(_WIN64)) && \
(defined(__GNUC__) || defined(__clang__))
# define htobe16(x) __builtin_bswap16(x)
# define htole16(x) (x)
# define be16toh(x) __builtin_bswap16(x)
# define le16toh(x) (x)
# define htobe32(x) __builtin_bswap32(x)
# define htole32(x) (x)
# define be32toh(x) __builtin_bswap32(x)
# define le32toh(x) (x)
# define htobe64(x) __builtin_bswap64(x)
# define htole64(x) (x)
# define be64toh(x) __builtin_bswap64(x)
# define le64toh(x) (x)
/* ... generic big-endian fallback code */
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
/* byte swapping code inspired by:
* https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/utility/EndianUtil.h
* */
# define htobe32(x) (x)
# define be32toh(x) (x)
# define htole32(x) \
(__extension__({ \
uint32_t _temp = (x); \
((_temp >> 24) & 0x000000FF) | ((_temp >> 8) & 0x0000FF00) | \
((_temp << 8) & 0x00FF0000) | ((_temp << 24) & 0xFF000000); \
}))
# define le32toh(x) (htole32((x)))
# define htobe64(x) (x)
# define be64toh(x) (x)
# define htole64(x) \
(__extension__({ \
uint64_t __temp = (x); \
uint32_t __low = htobe32((uint32_t)__temp); \
uint32_t __high = htobe32((uint32_t)(__temp >> 32)); \
(((uint64_t)__low) << 32) | __high; \
}))
# define le64toh(x) (htole64((x)))
/* ... generic little-endian fallback code */
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define htole32(x) (x)
# define le32toh(x) (x)
# define htobe32(x) \
(__extension__({ \
uint32_t _temp = (x); \
((_temp >> 24) & 0x000000FF) | ((_temp >> 8) & 0x0000FF00) | \
((_temp << 8) & 0x00FF0000) | ((_temp << 24) & 0xFF000000); \
}))
# define be32toh(x) (htobe32((x)))
# define htole64(x) (x)
# define le64toh(x) (x)
# define htobe64(x) \
(__extension__({ \
uint64_t __temp = (x); \
uint32_t __low = htobe32((uint32_t)__temp); \
uint32_t __high = htobe32((uint32_t)(__temp >> 32)); \
(((uint64_t)__low) << 32) | __high; \
}))
# define be64toh(x) (htobe64((x)))
/* ... couldn't determine endian-ness of the target platform */
#else
# error "Please define __BYTE_ORDER__!"
#endif /* defined(__linux__) || ... */
/* Loads and stores. These avoid undefined behavior due to unaligned memory
* accesses, via memcpy. */
inline static uint16_t load16(uint8_t *b) {
uint16_t x;
memcpy(&x, b, 2);
return x;
}
inline static uint32_t load32(uint8_t *b) {
uint32_t x;
memcpy(&x, b, 4);
return x;
}
inline static uint64_t load64(uint8_t *b) {
uint64_t x;
memcpy(&x, b, 8);
return x;
}
inline static void store16(uint8_t *b, uint16_t i) {
memcpy(b, &i, 2);
}
inline static void store32(uint8_t *b, uint32_t i) {
memcpy(b, &i, 4);
}
inline static void store64(uint8_t *b, uint64_t i) {
memcpy(b, &i, 8);
}
#define load16_le(b) (le16toh(load16(b)))
#define store16_le(b, i) (store16(b, htole16(i)))
#define load16_be(b) (be16toh(load16(b)))
#define store16_be(b, i) (store16(b, htobe16(i)))
#define load32_le(b) (le32toh(load32(b)))
#define store32_le(b, i) (store32(b, htole32(i)))
#define load32_be(b) (be32toh(load32(b)))
#define store32_be(b, i) (store32(b, htobe32(i)))
#define load64_le(b) (le64toh(load64(b)))
#define store64_le(b, i) (store64(b, htole64(i)))
#define load64_be(b) (be64toh(load64(b)))
#define store64_be(b, i) (store64(b, htobe64(i)))
#endif

View File

@ -0,0 +1,16 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_BUILTIN_H
#define __KREMLIN_BUILTIN_H
/* For alloca, when using KreMLin's -falloca */
#if (defined(_WIN32) || defined(_WIN64))
# include <malloc.h>
#endif
/* If some globals need to be initialized before the main, then kremlin will
* generate and try to link last a function with this type: */
void kremlinit_globals(void);
#endif

View File

@ -0,0 +1,46 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_CALLCONV_H
#define __KREMLIN_CALLCONV_H
/******************************************************************************/
/* Some macros to ease compatibility */
/******************************************************************************/
/* We want to generate __cdecl safely without worrying about it being undefined.
* When using MSVC, these are always defined. When using MinGW, these are
* defined too. They have no meaning for other platforms, so we define them to
* be empty macros in other situations. */
#ifndef _MSC_VER
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __fastcall
#define __fastcall
#endif
#endif
/* Since KreMLin emits the inline keyword unconditionally, we follow the
* guidelines at https://gcc.gnu.org/onlinedocs/gcc/Inline.html and make this
* __inline__ to ensure the code compiles with -std=c90 and earlier. */
#ifdef __GNUC__
# define inline __inline__
#endif
/* GCC-specific attribute syntax; everyone else gets the standard C inline
* attribute. */
#ifdef __GNU_C__
# ifndef __clang__
# define force_inline inline __attribute__((always_inline))
# else
# define force_inline inline
# endif
#else
# define force_inline inline
#endif
#endif

View File

@ -0,0 +1,34 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef KRML_COMPAT_H
#define KRML_COMPAT_H
#include <inttypes.h>
/* A series of macros that define C implementations of types that are not Low*,
* to facilitate porting programs to Low*. */
typedef const char *Prims_string;
typedef struct {
uint32_t length;
const char *data;
} FStar_Bytes_bytes;
typedef int32_t Prims_pos, Prims_nat, Prims_nonzero, Prims_int,
krml_checked_int_t;
#define RETURN_OR(x) \
do { \
int64_t __ret = x; \
if (__ret < INT32_MIN || INT32_MAX < __ret) { \
KRML_HOST_PRINTF( \
"Prims.{int,nat,pos} integer overflow at %s:%d\n", __FILE__, \
__LINE__); \
KRML_HOST_EXIT(252); \
} \
return (int32_t)__ret; \
} while (0)
#endif

View File

@ -0,0 +1,57 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_DEBUG_H
#define __KREMLIN_DEBUG_H
#include <inttypes.h>
#include "kremlin/internal/target.h"
/******************************************************************************/
/* Debugging helpers - intended only for KreMLin developers */
/******************************************************************************/
/* In support of "-wasm -d force-c": we might need this function to be
* forward-declared, because the dependency on WasmSupport appears very late,
* after SimplifyWasm, and sadly, after the topological order has been done. */
void WasmSupport_check_buffer_size(uint32_t s);
/* A series of GCC atrocities to trace function calls (kremlin's [-d c-calls]
* option). Useful when trying to debug, say, Wasm, to compare traces. */
/* clang-format off */
#ifdef __GNUC__
#define KRML_FORMAT(X) _Generic((X), \
uint8_t : "0x%08" PRIx8, \
uint16_t: "0x%08" PRIx16, \
uint32_t: "0x%08" PRIx32, \
uint64_t: "0x%08" PRIx64, \
int8_t : "0x%08" PRIx8, \
int16_t : "0x%08" PRIx16, \
int32_t : "0x%08" PRIx32, \
int64_t : "0x%08" PRIx64, \
default : "%s")
#define KRML_FORMAT_ARG(X) _Generic((X), \
uint8_t : X, \
uint16_t: X, \
uint32_t: X, \
uint64_t: X, \
int8_t : X, \
int16_t : X, \
int32_t : X, \
int64_t : X, \
default : "unknown")
/* clang-format on */
# define KRML_DEBUG_RETURN(X) \
({ \
__auto_type _ret = (X); \
KRML_HOST_PRINTF("returning: "); \
KRML_HOST_PRINTF(KRML_FORMAT(_ret), KRML_FORMAT_ARG(_ret)); \
KRML_HOST_PRINTF(" \n"); \
_ret; \
})
#endif
#endif

View File

@ -0,0 +1,102 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_TARGET_H
#define __KREMLIN_TARGET_H
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
#include <limits.h>
#include "kremlin/internal/callconv.h"
/******************************************************************************/
/* Macros that KreMLin will generate. */
/******************************************************************************/
/* For "bare" targets that do not have a C stdlib, the user might want to use
* [-add-early-include '"mydefinitions.h"'] and override these. */
#ifndef KRML_HOST_PRINTF
# define KRML_HOST_PRINTF printf
#endif
#if ( \
(defined __STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
(!(defined KRML_HOST_EPRINTF)))
# define KRML_HOST_EPRINTF(...) fprintf(stderr, __VA_ARGS__)
#endif
#ifndef KRML_HOST_EXIT
# define KRML_HOST_EXIT exit
#endif
#ifndef KRML_HOST_MALLOC
# define KRML_HOST_MALLOC malloc
#endif
#ifndef KRML_HOST_CALLOC
# define KRML_HOST_CALLOC calloc
#endif
#ifndef KRML_HOST_FREE
# define KRML_HOST_FREE free
#endif
#ifndef KRML_HOST_TIME
# include <time.h>
/* Prims_nat not yet in scope */
inline static int32_t krml_time() {
return (int32_t)time(NULL);
}
# define KRML_HOST_TIME krml_time
#endif
/* In statement position, exiting is easy. */
#define KRML_EXIT \
do { \
KRML_HOST_PRINTF("Unimplemented function at %s:%d\n", __FILE__, __LINE__); \
KRML_HOST_EXIT(254); \
} while (0)
/* In expression position, use the comma-operator and a malloc to return an
* expression of the right size. KreMLin passes t as the parameter to the macro.
*/
#define KRML_EABORT(t, msg) \
(KRML_HOST_PRINTF("KreMLin abort at %s:%d\n%s\n", __FILE__, __LINE__, msg), \
KRML_HOST_EXIT(255), *((t *)KRML_HOST_MALLOC(sizeof(t))))
/* In FStar.Buffer.fst, the size of arrays is uint32_t, but it's a number of
* *elements*. Do an ugly, run-time check (some of which KreMLin can eliminate).
*/
#ifdef __GNUC__
# define _KRML_CHECK_SIZE_PRAGMA \
_Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
#else
# define _KRML_CHECK_SIZE_PRAGMA
#endif
#define KRML_CHECK_SIZE(size_elt, sz) \
do { \
_KRML_CHECK_SIZE_PRAGMA \
if (((size_t)(sz)) > ((size_t)(SIZE_MAX / (size_elt)))) { \
KRML_HOST_PRINTF( \
"Maximum allocatable size exceeded, aborting before overflow at " \
"%s:%d\n", \
__FILE__, __LINE__); \
KRML_HOST_EXIT(253); \
} \
} while (0)
#if defined(_MSC_VER) && _MSC_VER < 1900
# define KRML_HOST_SNPRINTF(buf, sz, fmt, arg) _snprintf_s(buf, sz, _TRUNCATE, fmt, arg)
#else
# define KRML_HOST_SNPRINTF(buf, sz, fmt, arg) snprintf(buf, sz, fmt, arg)
#endif
#endif

View File

@ -0,0 +1,61 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef KRML_TYPES_H
#define KRML_TYPES_H
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
/* Types which are either abstract, meaning that have to be implemented in C, or
* which are models, meaning that they are swapped out at compile-time for
* hand-written C types (in which case they're marked as noextract). */
typedef uint64_t FStar_UInt64_t, FStar_UInt64_t_;
typedef int64_t FStar_Int64_t, FStar_Int64_t_;
typedef uint32_t FStar_UInt32_t, FStar_UInt32_t_;
typedef int32_t FStar_Int32_t, FStar_Int32_t_;
typedef uint16_t FStar_UInt16_t, FStar_UInt16_t_;
typedef int16_t FStar_Int16_t, FStar_Int16_t_;
typedef uint8_t FStar_UInt8_t, FStar_UInt8_t_;
typedef int8_t FStar_Int8_t, FStar_Int8_t_;
/* Only useful when building Kremlib, because it's in the dependency graph of
* FStar.Int.Cast. */
typedef uint64_t FStar_UInt63_t, FStar_UInt63_t_;
typedef int64_t FStar_Int63_t, FStar_Int63_t_;
typedef double FStar_Float_float;
typedef uint32_t FStar_Char_char;
typedef FILE *FStar_IO_fd_read, *FStar_IO_fd_write;
typedef void *FStar_Dyn_dyn;
typedef const char *C_String_t, *C_String_t_;
typedef int exit_code;
typedef FILE *channel;
typedef unsigned long long TestLib_cycles;
typedef uint64_t FStar_Date_dateTime, FStar_Date_timeSpan;
/* The uint128 type is a special case since we offer several implementations of
* it, depending on the compiler and whether the user wants the verified
* implementation or not. */
#if !defined(KRML_VERIFIED_UINT128) && defined(_MSC_VER) && defined(_M_X64)
# include <emmintrin.h>
typedef __m128i FStar_UInt128_uint128;
#elif !defined(KRML_VERIFIED_UINT128) && !defined(_MSC_VER)
typedef unsigned __int128 FStar_UInt128_uint128;
#else
typedef struct FStar_UInt128_uint128_s {
uint64_t low;
uint64_t high;
} FStar_UInt128_uint128;
#endif
typedef FStar_UInt128_uint128 FStar_UInt128_t, FStar_UInt128_t_, uint128_t;
#endif

View File

@ -0,0 +1,5 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file is automatically included when compiling with -wasm -d force-c */
#define WasmSupport_check_buffer_size(X)

View File

@ -0,0 +1,21 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __Hacl_Curve25519_H
#define __Hacl_Curve25519_H
#include "kremlib.h"
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint);
#define __Hacl_Curve25519_H_DEFINED
#endif

View File

@ -0,0 +1,36 @@
/*
* Custom inttypes.h for VS2010 KreMLin requires these definitions,
* but VS2010 doesn't provide them.
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* 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 _INTTYPES_H_VS2010
#define _INTTYPES_H_VS2010
#include <stdint.h>
#ifdef _MSC_VER
#define inline __inline
#endif
/* VS2010 unsigned long == 8 bytes */
#define PRIu64 "I64u"
#endif

View File

@ -0,0 +1,31 @@
/*
* Custom stdbool.h for VS2010 KreMLin requires these definitions,
* but VS2010 doesn't provide them.
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* 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 _STDBOOL_H_VS2010
#define _STDBOOL_H_VS2010
typedef int bool;
static bool true = 1;
static bool false = 0;
#endif

View File

@ -0,0 +1,190 @@
/*
* ECDH with curve-optimized implementation multiplexing
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* 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_X25519_H
#define MBEDTLS_X25519_H
#ifdef __cplusplus
extern "C" {
#endif
#define MBEDTLS_ECP_TLS_CURVE25519 0x1d
#define MBEDTLS_X25519_KEY_SIZE_BYTES 32
/**
* Defines the source of the imported EC key.
*/
typedef enum
{
MBEDTLS_X25519_ECDH_OURS, /**< Our key. */
MBEDTLS_X25519_ECDH_THEIRS, /**< The key of the peer. */
} mbedtls_x25519_ecdh_side;
/**
* \brief The x25519 context structure.
*/
typedef struct
{
unsigned char our_secret[MBEDTLS_X25519_KEY_SIZE_BYTES];
unsigned char peer_point[MBEDTLS_X25519_KEY_SIZE_BYTES];
} mbedtls_x25519_context;
/**
* \brief This function initializes an x25519 context.
*
* \param ctx The x25519 context to initialize.
*/
void mbedtls_x25519_init( mbedtls_x25519_context *ctx );
/**
* \brief This function frees a context.
*
* \param ctx The context to free.
*/
void mbedtls_x25519_free( mbedtls_x25519_context *ctx );
/**
* \brief This function generates a public key and a TLS
* ServerKeyExchange payload.
*
* This is the first function used by a TLS server for x25519.
*
*
* \param ctx The x25519 context.
* \param olen The number of characters written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_make_params( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief This function parses and processes a TLS ServerKeyExchange
* payload.
*
*
* \param ctx The x25519 context.
* \param buf The pointer to the start of the input buffer.
* \param end The address for one Byte past the end of the buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_x25519_read_params( mbedtls_x25519_context *ctx,
const unsigned char **buf, const unsigned char *end );
/**
* \brief This function sets up an x25519 context from an EC key.
*
* 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 x25519 context to set up.
* \param key The EC key to use.
* \param side Defines the source of the key: 1: Our key, or
* 0: The key of the peer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_x25519_get_params( mbedtls_x25519_context *ctx, const mbedtls_ecp_keypair *key,
mbedtls_x25519_ecdh_side side );
/**
* \brief This function derives and exports the shared secret.
*
* This is the last function used by both TLS client
* and servers.
*
*
* \param ctx The x25519 context.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_calc_secret( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief This function generates a public key and a TLS
* ClientKeyExchange payload.
*
* This is the second function used by a TLS client for x25519.
*
* \see ecp.h
*
* \param ctx The x25519 context.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The size of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_make_public( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief This function parses and processes a TLS ClientKeyExchange
* payload.
*
* This is the second function used by a TLS server for x25519.
*
* \see ecp.h
*
* \param ctx The x25519 context.
* \param buf The start of the input buffer.
* \param blen The length of the input buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_read_public( mbedtls_x25519_context *ctx,
const unsigned char *buf, size_t blen );
#ifdef __cplusplus
}
#endif
#endif /* x25519.h */

View File

@ -0,0 +1,760 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fbuiltin-uint128 -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "Hacl_Curve25519.h"
extern uint64_t FStar_UInt64_eq_mask(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_gte_mask(uint64_t x0, uint64_t x1);
extern uint128_t FStar_UInt128_add(uint128_t x0, uint128_t x1);
extern uint128_t FStar_UInt128_add_mod(uint128_t x0, uint128_t x1);
extern uint128_t FStar_UInt128_logand(uint128_t x0, uint128_t x1);
extern uint128_t FStar_UInt128_shift_right(uint128_t x0, uint32_t x1);
extern uint128_t FStar_UInt128_uint64_to_uint128(uint64_t x0);
extern uint64_t FStar_UInt128_uint128_to_uint64(uint128_t x0);
extern uint128_t FStar_UInt128_mul_wide(uint64_t x0, uint64_t x1);
static void Hacl_Bignum_Modulo_carry_top(uint64_t *b)
{
uint64_t b4 = b[4U];
uint64_t b0 = b[0U];
uint64_t b4_ = b4 & (uint64_t)0x7ffffffffffffU;
uint64_t b0_ = b0 + (uint64_t)19U * (b4 >> (uint32_t)51U);
b[4U] = b4_;
b[0U] = b0_;
}
inline static void Hacl_Bignum_Fproduct_copy_from_wide_(uint64_t *output, uint128_t *input)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint128_t xi = input[i];
output[i] = (uint64_t)xi;
}
}
inline static void
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(uint128_t *output, uint64_t *input, uint64_t s)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint128_t xi = output[i];
uint64_t yi = input[i];
output[i] = xi + (uint128_t)yi * s;
}
}
inline static void Hacl_Bignum_Fproduct_carry_wide_(uint128_t *tmp)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = i;
uint128_t tctr = tmp[ctr];
uint128_t tctrp1 = tmp[ctr + (uint32_t)1U];
uint64_t r0 = (uint64_t)tctr & (uint64_t)0x7ffffffffffffU;
uint128_t c = tctr >> (uint32_t)51U;
tmp[ctr] = (uint128_t)r0;
tmp[ctr + (uint32_t)1U] = tctrp1 + c;
}
}
inline static void Hacl_Bignum_Fmul_shift_reduce(uint64_t *output)
{
uint64_t tmp = output[4U];
uint64_t b0;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = (uint32_t)5U - i - (uint32_t)1U;
uint64_t z = output[ctr - (uint32_t)1U];
output[ctr] = z;
}
}
output[0U] = tmp;
b0 = output[0U];
output[0U] = (uint64_t)19U * b0;
}
static void
Hacl_Bignum_Fmul_mul_shift_reduce_(uint128_t *output, uint64_t *input, uint64_t *input2)
{
uint32_t i;
uint64_t input2i;
{
uint32_t i0;
for (i0 = (uint32_t)0U; i0 < (uint32_t)4U; i0 = i0 + (uint32_t)1U)
{
uint64_t input2i0 = input2[i0];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i0);
Hacl_Bignum_Fmul_shift_reduce(input);
}
}
i = (uint32_t)4U;
input2i = input2[i];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i);
}
inline static void Hacl_Bignum_Fmul_fmul(uint64_t *output, uint64_t *input, uint64_t *input2)
{
uint64_t tmp[5U] = { 0U };
memcpy(tmp, input, (uint32_t)5U * sizeof input[0U]);
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = (uint128_t)(uint64_t)0U;
}
{
uint128_t b4;
uint128_t b0;
uint128_t b4_;
uint128_t b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fmul_mul_shift_reduce_(t, tmp, input2);
Hacl_Bignum_Fproduct_carry_wide_(t);
b4 = t[4U];
b0 = t[0U];
b4_ = b4 & (uint128_t)(uint64_t)0x7ffffffffffffU;
b0_ = b0 + (uint128_t)(uint64_t)19U * (uint64_t)(b4 >> (uint32_t)51U);
t[4U] = b4_;
t[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, t);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
}
}
inline static void Hacl_Bignum_Fsquare_fsquare__(uint128_t *tmp, uint64_t *output)
{
uint64_t r0 = output[0U];
uint64_t r1 = output[1U];
uint64_t r2 = output[2U];
uint64_t r3 = output[3U];
uint64_t r4 = output[4U];
uint64_t d0 = r0 * (uint64_t)2U;
uint64_t d1 = r1 * (uint64_t)2U;
uint64_t d2 = r2 * (uint64_t)2U * (uint64_t)19U;
uint64_t d419 = r4 * (uint64_t)19U;
uint64_t d4 = d419 * (uint64_t)2U;
uint128_t s0 = (uint128_t)r0 * r0 + (uint128_t)d4 * r1 + (uint128_t)d2 * r3;
uint128_t s1 = (uint128_t)d0 * r1 + (uint128_t)d4 * r2 + (uint128_t)(r3 * (uint64_t)19U) * r3;
uint128_t s2 = (uint128_t)d0 * r2 + (uint128_t)r1 * r1 + (uint128_t)d4 * r3;
uint128_t s3 = (uint128_t)d0 * r3 + (uint128_t)d1 * r2 + (uint128_t)r4 * d419;
uint128_t s4 = (uint128_t)d0 * r4 + (uint128_t)d1 * r3 + (uint128_t)r2 * r2;
tmp[0U] = s0;
tmp[1U] = s1;
tmp[2U] = s2;
tmp[3U] = s3;
tmp[4U] = s4;
}
inline static void Hacl_Bignum_Fsquare_fsquare_(uint128_t *tmp, uint64_t *output)
{
uint128_t b4;
uint128_t b0;
uint128_t b4_;
uint128_t b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fsquare_fsquare__(tmp, output);
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = b4 & (uint128_t)(uint64_t)0x7ffffffffffffU;
b0_ = b0 + (uint128_t)(uint64_t)19U * (uint64_t)(b4 >> (uint32_t)51U);
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
static void
Hacl_Bignum_Fsquare_fsquare_times_(uint64_t *input, uint128_t *tmp, uint32_t count1)
{
uint32_t i;
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
for (i = (uint32_t)1U; i < count1; i = i + (uint32_t)1U)
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
}
inline static void
Hacl_Bignum_Fsquare_fsquare_times(uint64_t *output, uint64_t *input, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = (uint128_t)(uint64_t)0U;
}
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Fsquare_fsquare_times_inplace(uint64_t *output, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = (uint128_t)(uint64_t)0U;
}
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Crecip_crecip(uint64_t *out, uint64_t *z)
{
uint64_t buf[20U] = { 0U };
uint64_t *a0 = buf;
uint64_t *t00 = buf + (uint32_t)5U;
uint64_t *b0 = buf + (uint32_t)10U;
uint64_t *t01;
uint64_t *b1;
uint64_t *c0;
uint64_t *a;
uint64_t *t0;
uint64_t *b;
uint64_t *c;
Hacl_Bignum_Fsquare_fsquare_times(a0, z, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)2U);
Hacl_Bignum_Fmul_fmul(b0, t00, z);
Hacl_Bignum_Fmul_fmul(a0, b0, a0);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)1U);
Hacl_Bignum_Fmul_fmul(b0, t00, b0);
Hacl_Bignum_Fsquare_fsquare_times(t00, b0, (uint32_t)5U);
t01 = buf + (uint32_t)5U;
b1 = buf + (uint32_t)10U;
c0 = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(c0, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, c0, (uint32_t)20U);
Hacl_Bignum_Fmul_fmul(t01, t01, c0);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t01, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)50U);
a = buf;
t0 = buf + (uint32_t)5U;
b = buf + (uint32_t)10U;
c = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(c, t0, b);
Hacl_Bignum_Fsquare_fsquare_times(t0, c, (uint32_t)100U);
Hacl_Bignum_Fmul_fmul(t0, t0, c);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)50U);
Hacl_Bignum_Fmul_fmul(t0, t0, b);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)5U);
Hacl_Bignum_Fmul_fmul(out, t0, a);
}
inline static void Hacl_Bignum_fsum(uint64_t *a, uint64_t *b)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = b[i];
a[i] = xi + yi;
}
}
inline static void Hacl_Bignum_fdifference(uint64_t *a, uint64_t *b)
{
uint64_t tmp[5U] = { 0U };
uint64_t b0;
uint64_t b1;
uint64_t b2;
uint64_t b3;
uint64_t b4;
memcpy(tmp, b, (uint32_t)5U * sizeof b[0U]);
b0 = tmp[0U];
b1 = tmp[1U];
b2 = tmp[2U];
b3 = tmp[3U];
b4 = tmp[4U];
tmp[0U] = b0 + (uint64_t)0x3fffffffffff68U;
tmp[1U] = b1 + (uint64_t)0x3ffffffffffff8U;
tmp[2U] = b2 + (uint64_t)0x3ffffffffffff8U;
tmp[3U] = b3 + (uint64_t)0x3ffffffffffff8U;
tmp[4U] = b4 + (uint64_t)0x3ffffffffffff8U;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = tmp[i];
a[i] = yi - xi;
}
}
}
inline static void Hacl_Bignum_fscalar(uint64_t *output, uint64_t *b, uint64_t s)
{
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t tmp[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
tmp[_i] = (uint128_t)(uint64_t)0U;
}
{
uint128_t b4;
uint128_t b0;
uint128_t b4_;
uint128_t b0_;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = b[i];
tmp[i] = (uint128_t)xi * s;
}
}
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = b4 & (uint128_t)(uint64_t)0x7ffffffffffffU;
b0_ = b0 + (uint128_t)(uint64_t)19U * (uint64_t)(b4 >> (uint32_t)51U);
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
}
}
}
inline static void Hacl_Bignum_fmul(uint64_t *output, uint64_t *a, uint64_t *b)
{
Hacl_Bignum_Fmul_fmul(output, a, b);
}
inline static void Hacl_Bignum_crecip(uint64_t *output, uint64_t *input)
{
Hacl_Bignum_Crecip_crecip(output, input);
}
static void
Hacl_EC_Point_swap_conditional_step(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
uint32_t i = ctr - (uint32_t)1U;
uint64_t ai = a[i];
uint64_t bi = b[i];
uint64_t x = swap1 & (ai ^ bi);
uint64_t ai1 = ai ^ x;
uint64_t bi1 = bi ^ x;
a[i] = ai1;
b[i] = bi1;
}
static void
Hacl_EC_Point_swap_conditional_(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
if (!(ctr == (uint32_t)0U))
{
uint32_t i;
Hacl_EC_Point_swap_conditional_step(a, b, swap1, ctr);
i = ctr - (uint32_t)1U;
Hacl_EC_Point_swap_conditional_(a, b, swap1, i);
}
}
static void Hacl_EC_Point_swap_conditional(uint64_t *a, uint64_t *b, uint64_t iswap)
{
uint64_t swap1 = (uint64_t)0U - iswap;
Hacl_EC_Point_swap_conditional_(a, b, swap1, (uint32_t)5U);
Hacl_EC_Point_swap_conditional_(a + (uint32_t)5U, b + (uint32_t)5U, swap1, (uint32_t)5U);
}
static void Hacl_EC_Point_copy(uint64_t *output, uint64_t *input)
{
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
memcpy(output + (uint32_t)5U,
input + (uint32_t)5U,
(uint32_t)5U * sizeof (input + (uint32_t)5U)[0U]);
}
static void Hacl_EC_Format_fexpand(uint64_t *output, uint8_t *input)
{
uint64_t i0 = load64_le(input);
uint8_t *x00 = input + (uint32_t)6U;
uint64_t i1 = load64_le(x00);
uint8_t *x01 = input + (uint32_t)12U;
uint64_t i2 = load64_le(x01);
uint8_t *x02 = input + (uint32_t)19U;
uint64_t i3 = load64_le(x02);
uint8_t *x0 = input + (uint32_t)24U;
uint64_t i4 = load64_le(x0);
uint64_t output0 = i0 & (uint64_t)0x7ffffffffffffU;
uint64_t output1 = i1 >> (uint32_t)3U & (uint64_t)0x7ffffffffffffU;
uint64_t output2 = i2 >> (uint32_t)6U & (uint64_t)0x7ffffffffffffU;
uint64_t output3 = i3 >> (uint32_t)1U & (uint64_t)0x7ffffffffffffU;
uint64_t output4 = i4 >> (uint32_t)12U & (uint64_t)0x7ffffffffffffU;
output[0U] = output0;
output[1U] = output1;
output[2U] = output2;
output[3U] = output3;
output[4U] = output4;
}
static void Hacl_EC_Format_fcontract_first_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_first_carry_full(uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
}
static void Hacl_EC_Format_fcontract_second_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_second_carry_full(uint64_t *input)
{
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_EC_Format_fcontract_second_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
i0 = input[0U];
i1 = input[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
input[0U] = i0_;
input[1U] = i1_;
}
static void Hacl_EC_Format_fcontract_trim(uint64_t *input)
{
uint64_t a0 = input[0U];
uint64_t a1 = input[1U];
uint64_t a2 = input[2U];
uint64_t a3 = input[3U];
uint64_t a4 = input[4U];
uint64_t mask0 = FStar_UInt64_gte_mask(a0, (uint64_t)0x7ffffffffffedU);
uint64_t mask1 = FStar_UInt64_eq_mask(a1, (uint64_t)0x7ffffffffffffU);
uint64_t mask2 = FStar_UInt64_eq_mask(a2, (uint64_t)0x7ffffffffffffU);
uint64_t mask3 = FStar_UInt64_eq_mask(a3, (uint64_t)0x7ffffffffffffU);
uint64_t mask4 = FStar_UInt64_eq_mask(a4, (uint64_t)0x7ffffffffffffU);
uint64_t mask = (((mask0 & mask1) & mask2) & mask3) & mask4;
uint64_t a0_ = a0 - ((uint64_t)0x7ffffffffffedU & mask);
uint64_t a1_ = a1 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a2_ = a2 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a3_ = a3 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a4_ = a4 - ((uint64_t)0x7ffffffffffffU & mask);
input[0U] = a0_;
input[1U] = a1_;
input[2U] = a2_;
input[3U] = a3_;
input[4U] = a4_;
}
static void Hacl_EC_Format_fcontract_store(uint8_t *output, uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t o0 = t1 << (uint32_t)51U | t0;
uint64_t o1 = t2 << (uint32_t)38U | t1 >> (uint32_t)13U;
uint64_t o2 = t3 << (uint32_t)25U | t2 >> (uint32_t)26U;
uint64_t o3 = t4 << (uint32_t)12U | t3 >> (uint32_t)39U;
uint8_t *b0 = output;
uint8_t *b1 = output + (uint32_t)8U;
uint8_t *b2 = output + (uint32_t)16U;
uint8_t *b3 = output + (uint32_t)24U;
store64_le(b0, o0);
store64_le(b1, o1);
store64_le(b2, o2);
store64_le(b3, o3);
}
static void Hacl_EC_Format_fcontract(uint8_t *output, uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_full(input);
Hacl_EC_Format_fcontract_second_carry_full(input);
Hacl_EC_Format_fcontract_trim(input);
Hacl_EC_Format_fcontract_store(output, input);
}
static void Hacl_EC_Format_scalar_of_point(uint8_t *scalar, uint64_t *point)
{
uint64_t *x = point;
uint64_t *z = point + (uint32_t)5U;
uint64_t buf[10U] = { 0U };
uint64_t *zmone = buf;
uint64_t *sc = buf + (uint32_t)5U;
Hacl_Bignum_crecip(zmone, z);
Hacl_Bignum_fmul(sc, x, zmone);
Hacl_EC_Format_fcontract(scalar, sc);
}
static void
Hacl_EC_AddAndDouble_fmonty(
uint64_t *pp,
uint64_t *ppq,
uint64_t *p,
uint64_t *pq,
uint64_t *qmqp
)
{
uint64_t *qx = qmqp;
uint64_t *x2 = pp;
uint64_t *z2 = pp + (uint32_t)5U;
uint64_t *x3 = ppq;
uint64_t *z3 = ppq + (uint32_t)5U;
uint64_t *x = p;
uint64_t *z = p + (uint32_t)5U;
uint64_t *xprime = pq;
uint64_t *zprime = pq + (uint32_t)5U;
uint64_t buf[40U] = { 0U };
uint64_t *origx = buf;
uint64_t *origxprime0 = buf + (uint32_t)5U;
uint64_t *xxprime0 = buf + (uint32_t)25U;
uint64_t *zzprime0 = buf + (uint32_t)30U;
uint64_t *origxprime;
uint64_t *xx0;
uint64_t *zz0;
uint64_t *xxprime;
uint64_t *zzprime;
uint64_t *zzzprime;
uint64_t *zzz;
uint64_t *xx;
uint64_t *zz;
uint64_t scalar;
memcpy(origx, x, (uint32_t)5U * sizeof x[0U]);
Hacl_Bignum_fsum(x, z);
Hacl_Bignum_fdifference(z, origx);
memcpy(origxprime0, xprime, (uint32_t)5U * sizeof xprime[0U]);
Hacl_Bignum_fsum(xprime, zprime);
Hacl_Bignum_fdifference(zprime, origxprime0);
Hacl_Bignum_fmul(xxprime0, xprime, z);
Hacl_Bignum_fmul(zzprime0, x, zprime);
origxprime = buf + (uint32_t)5U;
xx0 = buf + (uint32_t)15U;
zz0 = buf + (uint32_t)20U;
xxprime = buf + (uint32_t)25U;
zzprime = buf + (uint32_t)30U;
zzzprime = buf + (uint32_t)35U;
memcpy(origxprime, xxprime, (uint32_t)5U * sizeof xxprime[0U]);
Hacl_Bignum_fsum(xxprime, zzprime);
Hacl_Bignum_fdifference(zzprime, origxprime);
Hacl_Bignum_Fsquare_fsquare_times(x3, xxprime, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zzzprime, zzprime, (uint32_t)1U);
Hacl_Bignum_fmul(z3, zzzprime, qx);
Hacl_Bignum_Fsquare_fsquare_times(xx0, x, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zz0, z, (uint32_t)1U);
zzz = buf + (uint32_t)10U;
xx = buf + (uint32_t)15U;
zz = buf + (uint32_t)20U;
Hacl_Bignum_fmul(x2, xx, zz);
Hacl_Bignum_fdifference(zz, xx);
scalar = (uint64_t)121665U;
Hacl_Bignum_fscalar(zzz, zz, scalar);
Hacl_Bignum_fsum(zzz, xx);
Hacl_Bignum_fmul(z2, zzz, zz);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint64_t bit0 = (uint64_t)(byt >> (uint32_t)7U);
uint64_t bit;
Hacl_EC_Point_swap_conditional(nq, nqpq, bit0);
Hacl_EC_AddAndDouble_fmonty(nq2, nqpq2, nq, nqpq, q);
bit = (uint64_t)(byt >> (uint32_t)7U);
Hacl_EC_Point_swap_conditional(nq2, nqpq2, bit);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint8_t byt1;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq, nqpq, nq2, nqpq2, q, byt);
byt1 = byt << (uint32_t)1U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq2, nqpq2, nq, nqpq, q, byt1);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i_ = i - (uint32_t)1U;
uint8_t byt_;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(nq, nqpq, nq2, nqpq2, q, byt);
byt_ = byt << (uint32_t)2U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byt_, i_);
}
}
static void
Hacl_EC_Ladder_BigLoop_cmult_big_loop(
uint8_t *n1,
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i1 = i - (uint32_t)1U;
uint8_t byte = n1[i1];
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byte, (uint32_t)4U);
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, i1);
}
}
static void Hacl_EC_Ladder_cmult(uint64_t *result, uint8_t *n1, uint64_t *q)
{
uint64_t point_buf[40U] = { 0U };
uint64_t *nq = point_buf;
uint64_t *nqpq = point_buf + (uint32_t)10U;
uint64_t *nq2 = point_buf + (uint32_t)20U;
uint64_t *nqpq2 = point_buf + (uint32_t)30U;
Hacl_EC_Point_copy(nqpq, q);
nq[0U] = (uint64_t)1U;
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, (uint32_t)32U);
Hacl_EC_Point_copy(result, nq);
}
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint)
{
uint64_t buf0[10U] = { 0U };
uint64_t *x0 = buf0;
uint64_t *z = buf0 + (uint32_t)5U;
uint64_t *q;
Hacl_EC_Format_fexpand(x0, basepoint);
z[0U] = (uint64_t)1U;
q = buf0;
{
uint8_t e[32U] = { 0U };
uint8_t e0;
uint8_t e31;
uint8_t e01;
uint8_t e311;
uint8_t e312;
uint8_t *scalar;
memcpy(e, secret, (uint32_t)32U * sizeof secret[0U]);
e0 = e[0U];
e31 = e[31U];
e01 = e0 & (uint8_t)248U;
e311 = e31 & (uint8_t)127U;
e312 = e311 | (uint8_t)64U;
e[0U] = e01;
e[31U] = e312;
scalar = e;
{
uint64_t buf[15U] = { 0U };
uint64_t *nq = buf;
uint64_t *x = nq;
x[0U] = (uint64_t)1U;
Hacl_EC_Ladder_cmult(nq, scalar, q);
Hacl_EC_Format_scalar_of_point(mypublic, nq);
}
}
}

View File

@ -0,0 +1,50 @@
/*
* Interface to code from Project Everest
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* 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 _BSD_SOURCE
/* Required to get htole64() from gcc/glibc's endian.h (older systems)
* when we compile with -std=c99 */
#define _BSD_SOURCE
#endif
#ifndef _DEFAULT_SOURCE
/* (modern version of _BSD_SOURCE) */
#define _DEFAULT_SOURCE
#endif
#include "common.h"
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
#if defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16)
#define MBEDTLS_HAVE_INT128
#endif
#if defined(MBEDTLS_HAVE_INT128)
#include "Hacl_Curve25519.c"
#else
#define KRML_VERIFIED_UINT128
#include "kremlib/FStar_UInt128_extracted.c"
#include "legacy/Hacl_Curve25519.c"
#endif
#include "kremlib/FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.c"
#endif /* defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) */

View File

@ -0,0 +1,102 @@
/*
* Interface to code from Project Everest
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* 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).
*/
#include "common.h"
#include <string.h>
#include "mbedtls/ecdh.h"
#include "everest/x25519.h"
#include "everest/everest.h"
#include "mbedtls/platform.h"
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
int mbedtls_everest_setup( mbedtls_ecdh_context_everest *ctx, int grp_id )
{
if( grp_id != MBEDTLS_ECP_DP_CURVE25519 )
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
mbedtls_x25519_init( &ctx->ctx );
return 0;
}
void mbedtls_everest_free( mbedtls_ecdh_context_everest *ctx )
{
mbedtls_x25519_free( &ctx->ctx );
}
int mbedtls_everest_make_params( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_make_params( x25519_ctx, olen, buf, blen, f_rng, p_rng );
}
int mbedtls_everest_read_params( mbedtls_ecdh_context_everest *ctx,
const unsigned char **buf,
const unsigned char *end )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_read_params( x25519_ctx, buf, end );
}
int mbedtls_everest_get_params( mbedtls_ecdh_context_everest *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_everest_ecdh_side side )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
mbedtls_x25519_ecdh_side s = side == MBEDTLS_EVEREST_ECDH_OURS ?
MBEDTLS_X25519_ECDH_OURS :
MBEDTLS_X25519_ECDH_THEIRS;
return mbedtls_x25519_get_params( x25519_ctx, key, s );
}
int mbedtls_everest_make_public( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_make_public( x25519_ctx, olen, buf, blen, f_rng, p_rng );
}
int mbedtls_everest_read_public( mbedtls_ecdh_context_everest *ctx,
const unsigned char *buf, size_t blen )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_read_public ( x25519_ctx, buf, blen );
}
int mbedtls_everest_calc_secret( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_calc_secret( x25519_ctx, olen, buf, blen, f_rng, p_rng );
}
#endif /* MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED */

View File

@ -0,0 +1,413 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir extracted -warn-error +9+11 -skip-compilation -extract-uints -add-include <inttypes.h> -add-include "kremlib.h" -add-include "kremlin/internal/compat.h" extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "FStar_UInt128.h"
#include "kremlin/c_endianness.h"
#include "FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.h"
uint64_t FStar_UInt128___proj__Mkuint128__item__low(FStar_UInt128_uint128 projectee)
{
return projectee.low;
}
uint64_t FStar_UInt128___proj__Mkuint128__item__high(FStar_UInt128_uint128 projectee)
{
return projectee.high;
}
static uint64_t FStar_UInt128_constant_time_carry(uint64_t a, uint64_t b)
{
return (a ^ ((a ^ b) | ((a - b) ^ b))) >> (uint32_t)63U;
}
static uint64_t FStar_UInt128_carry(uint64_t a, uint64_t b)
{
return FStar_UInt128_constant_time_carry(a, b);
}
FStar_UInt128_uint128 FStar_UInt128_add(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low + b.low, a.high + b.high + FStar_UInt128_carry(a.low + b.low, b.low) };
return flat;
}
FStar_UInt128_uint128
FStar_UInt128_add_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low + b.low, a.high + b.high + FStar_UInt128_carry(a.low + b.low, b.low) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_add_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low + b.low, a.high + b.high + FStar_UInt128_carry(a.low + b.low, b.low) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_sub(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low - b.low, a.high - b.high - FStar_UInt128_carry(a.low, a.low - b.low) };
return flat;
}
FStar_UInt128_uint128
FStar_UInt128_sub_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low - b.low, a.high - b.high - FStar_UInt128_carry(a.low, a.low - b.low) };
return flat;
}
static FStar_UInt128_uint128
FStar_UInt128_sub_mod_impl(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low - b.low, a.high - b.high - FStar_UInt128_carry(a.low, a.low - b.low) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_sub_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return FStar_UInt128_sub_mod_impl(a, b);
}
FStar_UInt128_uint128 FStar_UInt128_logand(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128 flat = { a.low & b.low, a.high & b.high };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_logxor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128 flat = { a.low ^ b.low, a.high ^ b.high };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_logor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128 flat = { a.low | b.low, a.high | b.high };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_lognot(FStar_UInt128_uint128 a)
{
FStar_UInt128_uint128 flat = { ~a.low, ~a.high };
return flat;
}
static uint32_t FStar_UInt128_u32_64 = (uint32_t)64U;
static uint64_t FStar_UInt128_add_u64_shift_left(uint64_t hi, uint64_t lo, uint32_t s)
{
return (hi << s) + (lo >> (FStar_UInt128_u32_64 - s));
}
static uint64_t FStar_UInt128_add_u64_shift_left_respec(uint64_t hi, uint64_t lo, uint32_t s)
{
return FStar_UInt128_add_u64_shift_left(hi, lo, s);
}
static FStar_UInt128_uint128
FStar_UInt128_shift_left_small(FStar_UInt128_uint128 a, uint32_t s)
{
if (s == (uint32_t)0U)
{
return a;
}
else
{
FStar_UInt128_uint128
flat = { a.low << s, FStar_UInt128_add_u64_shift_left_respec(a.high, a.low, s) };
return flat;
}
}
static FStar_UInt128_uint128
FStar_UInt128_shift_left_large(FStar_UInt128_uint128 a, uint32_t s)
{
FStar_UInt128_uint128 flat = { (uint64_t)0U, a.low << (s - FStar_UInt128_u32_64) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_shift_left(FStar_UInt128_uint128 a, uint32_t s)
{
if (s < FStar_UInt128_u32_64)
{
return FStar_UInt128_shift_left_small(a, s);
}
else
{
return FStar_UInt128_shift_left_large(a, s);
}
}
static uint64_t FStar_UInt128_add_u64_shift_right(uint64_t hi, uint64_t lo, uint32_t s)
{
return (lo >> s) + (hi << (FStar_UInt128_u32_64 - s));
}
static uint64_t FStar_UInt128_add_u64_shift_right_respec(uint64_t hi, uint64_t lo, uint32_t s)
{
return FStar_UInt128_add_u64_shift_right(hi, lo, s);
}
static FStar_UInt128_uint128
FStar_UInt128_shift_right_small(FStar_UInt128_uint128 a, uint32_t s)
{
if (s == (uint32_t)0U)
{
return a;
}
else
{
FStar_UInt128_uint128
flat = { FStar_UInt128_add_u64_shift_right_respec(a.high, a.low, s), a.high >> s };
return flat;
}
}
static FStar_UInt128_uint128
FStar_UInt128_shift_right_large(FStar_UInt128_uint128 a, uint32_t s)
{
FStar_UInt128_uint128 flat = { a.high >> (s - FStar_UInt128_u32_64), (uint64_t)0U };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_shift_right(FStar_UInt128_uint128 a, uint32_t s)
{
if (s < FStar_UInt128_u32_64)
{
return FStar_UInt128_shift_right_small(a, s);
}
else
{
return FStar_UInt128_shift_right_large(a, s);
}
}
bool FStar_UInt128_eq(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.low == b.low && a.high == b.high;
}
bool FStar_UInt128_gt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high > b.high || (a.high == b.high && a.low > b.low);
}
bool FStar_UInt128_lt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high < b.high || (a.high == b.high && a.low < b.low);
}
bool FStar_UInt128_gte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high > b.high || (a.high == b.high && a.low >= b.low);
}
bool FStar_UInt128_lte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high < b.high || (a.high == b.high && a.low <= b.low);
}
FStar_UInt128_uint128 FStar_UInt128_eq_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat =
{
FStar_UInt64_eq_mask(a.low,
b.low)
& FStar_UInt64_eq_mask(a.high, b.high),
FStar_UInt64_eq_mask(a.low,
b.low)
& FStar_UInt64_eq_mask(a.high, b.high)
};
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_gte_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat =
{
(FStar_UInt64_gte_mask(a.high, b.high) & ~FStar_UInt64_eq_mask(a.high, b.high))
| (FStar_UInt64_eq_mask(a.high, b.high) & FStar_UInt64_gte_mask(a.low, b.low)),
(FStar_UInt64_gte_mask(a.high, b.high) & ~FStar_UInt64_eq_mask(a.high, b.high))
| (FStar_UInt64_eq_mask(a.high, b.high) & FStar_UInt64_gte_mask(a.low, b.low))
};
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_uint64_to_uint128(uint64_t a)
{
FStar_UInt128_uint128 flat = { a, (uint64_t)0U };
return flat;
}
uint64_t FStar_UInt128_uint128_to_uint64(FStar_UInt128_uint128 a)
{
return a.low;
}
FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_add;
FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Question_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_add_underspec;
FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_add_mod;
FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_sub;
FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Question_Hat)(
FStar_UInt128_uint128 x0,
FStar_UInt128_uint128 x1
) = FStar_UInt128_sub_underspec;
FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_sub_mod;
FStar_UInt128_uint128
(*FStar_UInt128_op_Amp_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_logand;
FStar_UInt128_uint128
(*FStar_UInt128_op_Hat_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_logxor;
FStar_UInt128_uint128
(*FStar_UInt128_op_Bar_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_logor;
FStar_UInt128_uint128
(*FStar_UInt128_op_Less_Less_Hat)(FStar_UInt128_uint128 x0, uint32_t x1) =
FStar_UInt128_shift_left;
FStar_UInt128_uint128
(*FStar_UInt128_op_Greater_Greater_Hat)(FStar_UInt128_uint128 x0, uint32_t x1) =
FStar_UInt128_shift_right;
bool
(*FStar_UInt128_op_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_eq;
bool
(*FStar_UInt128_op_Greater_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_gt;
bool
(*FStar_UInt128_op_Less_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_lt;
bool
(*FStar_UInt128_op_Greater_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_gte;
bool
(*FStar_UInt128_op_Less_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_lte;
static uint64_t FStar_UInt128_u64_mod_32(uint64_t a)
{
return a & (uint64_t)0xffffffffU;
}
static uint32_t FStar_UInt128_u32_32 = (uint32_t)32U;
static uint64_t FStar_UInt128_u32_combine(uint64_t hi, uint64_t lo)
{
return lo + (hi << FStar_UInt128_u32_32);
}
FStar_UInt128_uint128 FStar_UInt128_mul32(uint64_t x, uint32_t y)
{
FStar_UInt128_uint128
flat =
{
FStar_UInt128_u32_combine((x >> FStar_UInt128_u32_32)
* (uint64_t)y
+ (FStar_UInt128_u64_mod_32(x) * (uint64_t)y >> FStar_UInt128_u32_32),
FStar_UInt128_u64_mod_32(FStar_UInt128_u64_mod_32(x) * (uint64_t)y)),
((x >> FStar_UInt128_u32_32)
* (uint64_t)y
+ (FStar_UInt128_u64_mod_32(x) * (uint64_t)y >> FStar_UInt128_u32_32))
>> FStar_UInt128_u32_32
};
return flat;
}
typedef struct K___uint64_t_uint64_t_uint64_t_uint64_t_s
{
uint64_t fst;
uint64_t snd;
uint64_t thd;
uint64_t f3;
}
K___uint64_t_uint64_t_uint64_t_uint64_t;
static K___uint64_t_uint64_t_uint64_t_uint64_t
FStar_UInt128_mul_wide_impl_t_(uint64_t x, uint64_t y)
{
K___uint64_t_uint64_t_uint64_t_uint64_t
flat =
{
FStar_UInt128_u64_mod_32(x),
FStar_UInt128_u64_mod_32(FStar_UInt128_u64_mod_32(x) * FStar_UInt128_u64_mod_32(y)),
x
>> FStar_UInt128_u32_32,
(x >> FStar_UInt128_u32_32)
* FStar_UInt128_u64_mod_32(y)
+ (FStar_UInt128_u64_mod_32(x) * FStar_UInt128_u64_mod_32(y) >> FStar_UInt128_u32_32)
};
return flat;
}
static uint64_t FStar_UInt128_u32_combine_(uint64_t hi, uint64_t lo)
{
return lo + (hi << FStar_UInt128_u32_32);
}
static FStar_UInt128_uint128 FStar_UInt128_mul_wide_impl(uint64_t x, uint64_t y)
{
K___uint64_t_uint64_t_uint64_t_uint64_t scrut = FStar_UInt128_mul_wide_impl_t_(x, y);
uint64_t u1 = scrut.fst;
uint64_t w3 = scrut.snd;
uint64_t x_ = scrut.thd;
uint64_t t_ = scrut.f3;
FStar_UInt128_uint128
flat =
{
FStar_UInt128_u32_combine_(u1 * (y >> FStar_UInt128_u32_32) + FStar_UInt128_u64_mod_32(t_),
w3),
x_
* (y >> FStar_UInt128_u32_32)
+ (t_ >> FStar_UInt128_u32_32)
+ ((u1 * (y >> FStar_UInt128_u32_32) + FStar_UInt128_u64_mod_32(t_)) >> FStar_UInt128_u32_32)
};
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_mul_wide(uint64_t x, uint64_t y)
{
return FStar_UInt128_mul_wide_impl(x, y);
}

View File

@ -0,0 +1,100 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir dist/minimal -skip-compilation -extract-uints -add-include <inttypes.h> -add-include <stdbool.h> -add-include "kremlin/internal/compat.h" -add-include "kremlin/internal/types.h" -bundle FStar.UInt64+FStar.UInt32+FStar.UInt16+FStar.UInt8=* extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.h"
uint64_t FStar_UInt64_eq_mask(uint64_t a, uint64_t b)
{
uint64_t x = a ^ b;
uint64_t minus_x = ~x + (uint64_t)1U;
uint64_t x_or_minus_x = x | minus_x;
uint64_t xnx = x_or_minus_x >> (uint32_t)63U;
return xnx - (uint64_t)1U;
}
uint64_t FStar_UInt64_gte_mask(uint64_t a, uint64_t b)
{
uint64_t x = a;
uint64_t y = b;
uint64_t x_xor_y = x ^ y;
uint64_t x_sub_y = x - y;
uint64_t x_sub_y_xor_y = x_sub_y ^ y;
uint64_t q = x_xor_y | x_sub_y_xor_y;
uint64_t x_xor_q = x ^ q;
uint64_t x_xor_q_ = x_xor_q >> (uint32_t)63U;
return x_xor_q_ - (uint64_t)1U;
}
uint32_t FStar_UInt32_eq_mask(uint32_t a, uint32_t b)
{
uint32_t x = a ^ b;
uint32_t minus_x = ~x + (uint32_t)1U;
uint32_t x_or_minus_x = x | minus_x;
uint32_t xnx = x_or_minus_x >> (uint32_t)31U;
return xnx - (uint32_t)1U;
}
uint32_t FStar_UInt32_gte_mask(uint32_t a, uint32_t b)
{
uint32_t x = a;
uint32_t y = b;
uint32_t x_xor_y = x ^ y;
uint32_t x_sub_y = x - y;
uint32_t x_sub_y_xor_y = x_sub_y ^ y;
uint32_t q = x_xor_y | x_sub_y_xor_y;
uint32_t x_xor_q = x ^ q;
uint32_t x_xor_q_ = x_xor_q >> (uint32_t)31U;
return x_xor_q_ - (uint32_t)1U;
}
uint16_t FStar_UInt16_eq_mask(uint16_t a, uint16_t b)
{
uint16_t x = a ^ b;
uint16_t minus_x = ~x + (uint16_t)1U;
uint16_t x_or_minus_x = x | minus_x;
uint16_t xnx = x_or_minus_x >> (uint32_t)15U;
return xnx - (uint16_t)1U;
}
uint16_t FStar_UInt16_gte_mask(uint16_t a, uint16_t b)
{
uint16_t x = a;
uint16_t y = b;
uint16_t x_xor_y = x ^ y;
uint16_t x_sub_y = x - y;
uint16_t x_sub_y_xor_y = x_sub_y ^ y;
uint16_t q = x_xor_y | x_sub_y_xor_y;
uint16_t x_xor_q = x ^ q;
uint16_t x_xor_q_ = x_xor_q >> (uint32_t)15U;
return x_xor_q_ - (uint16_t)1U;
}
uint8_t FStar_UInt8_eq_mask(uint8_t a, uint8_t b)
{
uint8_t x = a ^ b;
uint8_t minus_x = ~x + (uint8_t)1U;
uint8_t x_or_minus_x = x | minus_x;
uint8_t xnx = x_or_minus_x >> (uint32_t)7U;
return xnx - (uint8_t)1U;
}
uint8_t FStar_UInt8_gte_mask(uint8_t a, uint8_t b)
{
uint8_t x = a;
uint8_t y = b;
uint8_t x_xor_y = x ^ y;
uint8_t x_sub_y = x - y;
uint8_t x_sub_y_xor_y = x_sub_y ^ y;
uint8_t q = x_xor_y | x_sub_y_xor_y;
uint8_t x_xor_q = x ^ q;
uint8_t x_xor_q_ = x_xor_q >> (uint32_t)7U;
return x_xor_q_ - (uint8_t)1U;
}

View File

@ -0,0 +1,805 @@
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "Hacl_Curve25519.h"
extern uint64_t FStar_UInt64_eq_mask(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_gte_mask(uint64_t x0, uint64_t x1);
extern FStar_UInt128_uint128
FStar_UInt128_add(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
FStar_UInt128_add_mod(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
FStar_UInt128_logand(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128 FStar_UInt128_shift_right(FStar_UInt128_uint128 x0, uint32_t x1);
extern FStar_UInt128_uint128 FStar_UInt128_uint64_to_uint128(uint64_t x0);
extern uint64_t FStar_UInt128_uint128_to_uint64(FStar_UInt128_uint128 x0);
extern FStar_UInt128_uint128 FStar_UInt128_mul_wide(uint64_t x0, uint64_t x1);
static void Hacl_Bignum_Modulo_carry_top(uint64_t *b)
{
uint64_t b4 = b[4U];
uint64_t b0 = b[0U];
uint64_t b4_ = b4 & (uint64_t)0x7ffffffffffffU;
uint64_t b0_ = b0 + (uint64_t)19U * (b4 >> (uint32_t)51U);
b[4U] = b4_;
b[0U] = b0_;
}
inline static void
Hacl_Bignum_Fproduct_copy_from_wide_(uint64_t *output, FStar_UInt128_uint128 *input)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
FStar_UInt128_uint128 xi = input[i];
output[i] = FStar_UInt128_uint128_to_uint64(xi);
}
}
inline static void
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(
FStar_UInt128_uint128 *output,
uint64_t *input,
uint64_t s
)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
FStar_UInt128_uint128 xi = output[i];
uint64_t yi = input[i];
output[i] = FStar_UInt128_add_mod(xi, FStar_UInt128_mul_wide(yi, s));
}
}
inline static void Hacl_Bignum_Fproduct_carry_wide_(FStar_UInt128_uint128 *tmp)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = i;
FStar_UInt128_uint128 tctr = tmp[ctr];
FStar_UInt128_uint128 tctrp1 = tmp[ctr + (uint32_t)1U];
uint64_t r0 = FStar_UInt128_uint128_to_uint64(tctr) & (uint64_t)0x7ffffffffffffU;
FStar_UInt128_uint128 c = FStar_UInt128_shift_right(tctr, (uint32_t)51U);
tmp[ctr] = FStar_UInt128_uint64_to_uint128(r0);
tmp[ctr + (uint32_t)1U] = FStar_UInt128_add(tctrp1, c);
}
}
inline static void Hacl_Bignum_Fmul_shift_reduce(uint64_t *output)
{
uint64_t tmp = output[4U];
uint64_t b0;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = (uint32_t)5U - i - (uint32_t)1U;
uint64_t z = output[ctr - (uint32_t)1U];
output[ctr] = z;
}
}
output[0U] = tmp;
b0 = output[0U];
output[0U] = (uint64_t)19U * b0;
}
static void
Hacl_Bignum_Fmul_mul_shift_reduce_(
FStar_UInt128_uint128 *output,
uint64_t *input,
uint64_t *input2
)
{
uint32_t i;
uint64_t input2i;
{
uint32_t i0;
for (i0 = (uint32_t)0U; i0 < (uint32_t)4U; i0 = i0 + (uint32_t)1U)
{
uint64_t input2i0 = input2[i0];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i0);
Hacl_Bignum_Fmul_shift_reduce(input);
}
}
i = (uint32_t)4U;
input2i = input2[i];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i);
}
inline static void Hacl_Bignum_Fmul_fmul(uint64_t *output, uint64_t *input, uint64_t *input2)
{
uint64_t tmp[5U] = { 0U };
memcpy(tmp, input, (uint32_t)5U * sizeof input[0U]);
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
{
FStar_UInt128_uint128 b4;
FStar_UInt128_uint128 b0;
FStar_UInt128_uint128 b4_;
FStar_UInt128_uint128 b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fmul_mul_shift_reduce_(t, tmp, input2);
Hacl_Bignum_Fproduct_carry_wide_(t);
b4 = t[4U];
b0 = t[0U];
b4_ = FStar_UInt128_logand(b4, FStar_UInt128_uint64_to_uint128((uint64_t)0x7ffffffffffffU));
b0_ =
FStar_UInt128_add(b0,
FStar_UInt128_mul_wide((uint64_t)19U,
FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(b4, (uint32_t)51U))));
t[4U] = b4_;
t[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, t);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
}
}
inline static void Hacl_Bignum_Fsquare_fsquare__(FStar_UInt128_uint128 *tmp, uint64_t *output)
{
uint64_t r0 = output[0U];
uint64_t r1 = output[1U];
uint64_t r2 = output[2U];
uint64_t r3 = output[3U];
uint64_t r4 = output[4U];
uint64_t d0 = r0 * (uint64_t)2U;
uint64_t d1 = r1 * (uint64_t)2U;
uint64_t d2 = r2 * (uint64_t)2U * (uint64_t)19U;
uint64_t d419 = r4 * (uint64_t)19U;
uint64_t d4 = d419 * (uint64_t)2U;
FStar_UInt128_uint128
s0 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(r0, r0),
FStar_UInt128_mul_wide(d4, r1)),
FStar_UInt128_mul_wide(d2, r3));
FStar_UInt128_uint128
s1 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r1),
FStar_UInt128_mul_wide(d4, r2)),
FStar_UInt128_mul_wide(r3 * (uint64_t)19U, r3));
FStar_UInt128_uint128
s2 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r2),
FStar_UInt128_mul_wide(r1, r1)),
FStar_UInt128_mul_wide(d4, r3));
FStar_UInt128_uint128
s3 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r3),
FStar_UInt128_mul_wide(d1, r2)),
FStar_UInt128_mul_wide(r4, d419));
FStar_UInt128_uint128
s4 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r4),
FStar_UInt128_mul_wide(d1, r3)),
FStar_UInt128_mul_wide(r2, r2));
tmp[0U] = s0;
tmp[1U] = s1;
tmp[2U] = s2;
tmp[3U] = s3;
tmp[4U] = s4;
}
inline static void Hacl_Bignum_Fsquare_fsquare_(FStar_UInt128_uint128 *tmp, uint64_t *output)
{
FStar_UInt128_uint128 b4;
FStar_UInt128_uint128 b0;
FStar_UInt128_uint128 b4_;
FStar_UInt128_uint128 b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fsquare_fsquare__(tmp, output);
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = FStar_UInt128_logand(b4, FStar_UInt128_uint64_to_uint128((uint64_t)0x7ffffffffffffU));
b0_ =
FStar_UInt128_add(b0,
FStar_UInt128_mul_wide((uint64_t)19U,
FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(b4, (uint32_t)51U))));
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
static void
Hacl_Bignum_Fsquare_fsquare_times_(
uint64_t *input,
FStar_UInt128_uint128 *tmp,
uint32_t count1
)
{
uint32_t i;
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
for (i = (uint32_t)1U; i < count1; i = i + (uint32_t)1U)
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
}
inline static void
Hacl_Bignum_Fsquare_fsquare_times(uint64_t *output, uint64_t *input, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Fsquare_fsquare_times_inplace(uint64_t *output, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Crecip_crecip(uint64_t *out, uint64_t *z)
{
uint64_t buf[20U] = { 0U };
uint64_t *a0 = buf;
uint64_t *t00 = buf + (uint32_t)5U;
uint64_t *b0 = buf + (uint32_t)10U;
uint64_t *t01;
uint64_t *b1;
uint64_t *c0;
uint64_t *a;
uint64_t *t0;
uint64_t *b;
uint64_t *c;
Hacl_Bignum_Fsquare_fsquare_times(a0, z, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)2U);
Hacl_Bignum_Fmul_fmul(b0, t00, z);
Hacl_Bignum_Fmul_fmul(a0, b0, a0);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)1U);
Hacl_Bignum_Fmul_fmul(b0, t00, b0);
Hacl_Bignum_Fsquare_fsquare_times(t00, b0, (uint32_t)5U);
t01 = buf + (uint32_t)5U;
b1 = buf + (uint32_t)10U;
c0 = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(c0, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, c0, (uint32_t)20U);
Hacl_Bignum_Fmul_fmul(t01, t01, c0);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t01, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)50U);
a = buf;
t0 = buf + (uint32_t)5U;
b = buf + (uint32_t)10U;
c = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(c, t0, b);
Hacl_Bignum_Fsquare_fsquare_times(t0, c, (uint32_t)100U);
Hacl_Bignum_Fmul_fmul(t0, t0, c);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)50U);
Hacl_Bignum_Fmul_fmul(t0, t0, b);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)5U);
Hacl_Bignum_Fmul_fmul(out, t0, a);
}
inline static void Hacl_Bignum_fsum(uint64_t *a, uint64_t *b)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = b[i];
a[i] = xi + yi;
}
}
inline static void Hacl_Bignum_fdifference(uint64_t *a, uint64_t *b)
{
uint64_t tmp[5U] = { 0U };
uint64_t b0;
uint64_t b1;
uint64_t b2;
uint64_t b3;
uint64_t b4;
memcpy(tmp, b, (uint32_t)5U * sizeof b[0U]);
b0 = tmp[0U];
b1 = tmp[1U];
b2 = tmp[2U];
b3 = tmp[3U];
b4 = tmp[4U];
tmp[0U] = b0 + (uint64_t)0x3fffffffffff68U;
tmp[1U] = b1 + (uint64_t)0x3ffffffffffff8U;
tmp[2U] = b2 + (uint64_t)0x3ffffffffffff8U;
tmp[3U] = b3 + (uint64_t)0x3ffffffffffff8U;
tmp[4U] = b4 + (uint64_t)0x3ffffffffffff8U;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = tmp[i];
a[i] = yi - xi;
}
}
}
inline static void Hacl_Bignum_fscalar(uint64_t *output, uint64_t *b, uint64_t s)
{
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 tmp[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
tmp[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
{
FStar_UInt128_uint128 b4;
FStar_UInt128_uint128 b0;
FStar_UInt128_uint128 b4_;
FStar_UInt128_uint128 b0_;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = b[i];
tmp[i] = FStar_UInt128_mul_wide(xi, s);
}
}
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = FStar_UInt128_logand(b4, FStar_UInt128_uint64_to_uint128((uint64_t)0x7ffffffffffffU));
b0_ =
FStar_UInt128_add(b0,
FStar_UInt128_mul_wide((uint64_t)19U,
FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(b4, (uint32_t)51U))));
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
}
}
}
inline static void Hacl_Bignum_fmul(uint64_t *output, uint64_t *a, uint64_t *b)
{
Hacl_Bignum_Fmul_fmul(output, a, b);
}
inline static void Hacl_Bignum_crecip(uint64_t *output, uint64_t *input)
{
Hacl_Bignum_Crecip_crecip(output, input);
}
static void
Hacl_EC_Point_swap_conditional_step(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
uint32_t i = ctr - (uint32_t)1U;
uint64_t ai = a[i];
uint64_t bi = b[i];
uint64_t x = swap1 & (ai ^ bi);
uint64_t ai1 = ai ^ x;
uint64_t bi1 = bi ^ x;
a[i] = ai1;
b[i] = bi1;
}
static void
Hacl_EC_Point_swap_conditional_(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
if (!(ctr == (uint32_t)0U))
{
uint32_t i;
Hacl_EC_Point_swap_conditional_step(a, b, swap1, ctr);
i = ctr - (uint32_t)1U;
Hacl_EC_Point_swap_conditional_(a, b, swap1, i);
}
}
static void Hacl_EC_Point_swap_conditional(uint64_t *a, uint64_t *b, uint64_t iswap)
{
uint64_t swap1 = (uint64_t)0U - iswap;
Hacl_EC_Point_swap_conditional_(a, b, swap1, (uint32_t)5U);
Hacl_EC_Point_swap_conditional_(a + (uint32_t)5U, b + (uint32_t)5U, swap1, (uint32_t)5U);
}
static void Hacl_EC_Point_copy(uint64_t *output, uint64_t *input)
{
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
memcpy(output + (uint32_t)5U,
input + (uint32_t)5U,
(uint32_t)5U * sizeof (input + (uint32_t)5U)[0U]);
}
static void Hacl_EC_Format_fexpand(uint64_t *output, uint8_t *input)
{
uint64_t i0 = load64_le(input);
uint8_t *x00 = input + (uint32_t)6U;
uint64_t i1 = load64_le(x00);
uint8_t *x01 = input + (uint32_t)12U;
uint64_t i2 = load64_le(x01);
uint8_t *x02 = input + (uint32_t)19U;
uint64_t i3 = load64_le(x02);
uint8_t *x0 = input + (uint32_t)24U;
uint64_t i4 = load64_le(x0);
uint64_t output0 = i0 & (uint64_t)0x7ffffffffffffU;
uint64_t output1 = i1 >> (uint32_t)3U & (uint64_t)0x7ffffffffffffU;
uint64_t output2 = i2 >> (uint32_t)6U & (uint64_t)0x7ffffffffffffU;
uint64_t output3 = i3 >> (uint32_t)1U & (uint64_t)0x7ffffffffffffU;
uint64_t output4 = i4 >> (uint32_t)12U & (uint64_t)0x7ffffffffffffU;
output[0U] = output0;
output[1U] = output1;
output[2U] = output2;
output[3U] = output3;
output[4U] = output4;
}
static void Hacl_EC_Format_fcontract_first_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_first_carry_full(uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
}
static void Hacl_EC_Format_fcontract_second_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_second_carry_full(uint64_t *input)
{
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_EC_Format_fcontract_second_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
i0 = input[0U];
i1 = input[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
input[0U] = i0_;
input[1U] = i1_;
}
static void Hacl_EC_Format_fcontract_trim(uint64_t *input)
{
uint64_t a0 = input[0U];
uint64_t a1 = input[1U];
uint64_t a2 = input[2U];
uint64_t a3 = input[3U];
uint64_t a4 = input[4U];
uint64_t mask0 = FStar_UInt64_gte_mask(a0, (uint64_t)0x7ffffffffffedU);
uint64_t mask1 = FStar_UInt64_eq_mask(a1, (uint64_t)0x7ffffffffffffU);
uint64_t mask2 = FStar_UInt64_eq_mask(a2, (uint64_t)0x7ffffffffffffU);
uint64_t mask3 = FStar_UInt64_eq_mask(a3, (uint64_t)0x7ffffffffffffU);
uint64_t mask4 = FStar_UInt64_eq_mask(a4, (uint64_t)0x7ffffffffffffU);
uint64_t mask = (((mask0 & mask1) & mask2) & mask3) & mask4;
uint64_t a0_ = a0 - ((uint64_t)0x7ffffffffffedU & mask);
uint64_t a1_ = a1 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a2_ = a2 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a3_ = a3 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a4_ = a4 - ((uint64_t)0x7ffffffffffffU & mask);
input[0U] = a0_;
input[1U] = a1_;
input[2U] = a2_;
input[3U] = a3_;
input[4U] = a4_;
}
static void Hacl_EC_Format_fcontract_store(uint8_t *output, uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t o0 = t1 << (uint32_t)51U | t0;
uint64_t o1 = t2 << (uint32_t)38U | t1 >> (uint32_t)13U;
uint64_t o2 = t3 << (uint32_t)25U | t2 >> (uint32_t)26U;
uint64_t o3 = t4 << (uint32_t)12U | t3 >> (uint32_t)39U;
uint8_t *b0 = output;
uint8_t *b1 = output + (uint32_t)8U;
uint8_t *b2 = output + (uint32_t)16U;
uint8_t *b3 = output + (uint32_t)24U;
store64_le(b0, o0);
store64_le(b1, o1);
store64_le(b2, o2);
store64_le(b3, o3);
}
static void Hacl_EC_Format_fcontract(uint8_t *output, uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_full(input);
Hacl_EC_Format_fcontract_second_carry_full(input);
Hacl_EC_Format_fcontract_trim(input);
Hacl_EC_Format_fcontract_store(output, input);
}
static void Hacl_EC_Format_scalar_of_point(uint8_t *scalar, uint64_t *point)
{
uint64_t *x = point;
uint64_t *z = point + (uint32_t)5U;
uint64_t buf[10U] = { 0U };
uint64_t *zmone = buf;
uint64_t *sc = buf + (uint32_t)5U;
Hacl_Bignum_crecip(zmone, z);
Hacl_Bignum_fmul(sc, x, zmone);
Hacl_EC_Format_fcontract(scalar, sc);
}
static void
Hacl_EC_AddAndDouble_fmonty(
uint64_t *pp,
uint64_t *ppq,
uint64_t *p,
uint64_t *pq,
uint64_t *qmqp
)
{
uint64_t *qx = qmqp;
uint64_t *x2 = pp;
uint64_t *z2 = pp + (uint32_t)5U;
uint64_t *x3 = ppq;
uint64_t *z3 = ppq + (uint32_t)5U;
uint64_t *x = p;
uint64_t *z = p + (uint32_t)5U;
uint64_t *xprime = pq;
uint64_t *zprime = pq + (uint32_t)5U;
uint64_t buf[40U] = { 0U };
uint64_t *origx = buf;
uint64_t *origxprime0 = buf + (uint32_t)5U;
uint64_t *xxprime0 = buf + (uint32_t)25U;
uint64_t *zzprime0 = buf + (uint32_t)30U;
uint64_t *origxprime;
uint64_t *xx0;
uint64_t *zz0;
uint64_t *xxprime;
uint64_t *zzprime;
uint64_t *zzzprime;
uint64_t *zzz;
uint64_t *xx;
uint64_t *zz;
uint64_t scalar;
memcpy(origx, x, (uint32_t)5U * sizeof x[0U]);
Hacl_Bignum_fsum(x, z);
Hacl_Bignum_fdifference(z, origx);
memcpy(origxprime0, xprime, (uint32_t)5U * sizeof xprime[0U]);
Hacl_Bignum_fsum(xprime, zprime);
Hacl_Bignum_fdifference(zprime, origxprime0);
Hacl_Bignum_fmul(xxprime0, xprime, z);
Hacl_Bignum_fmul(zzprime0, x, zprime);
origxprime = buf + (uint32_t)5U;
xx0 = buf + (uint32_t)15U;
zz0 = buf + (uint32_t)20U;
xxprime = buf + (uint32_t)25U;
zzprime = buf + (uint32_t)30U;
zzzprime = buf + (uint32_t)35U;
memcpy(origxprime, xxprime, (uint32_t)5U * sizeof xxprime[0U]);
Hacl_Bignum_fsum(xxprime, zzprime);
Hacl_Bignum_fdifference(zzprime, origxprime);
Hacl_Bignum_Fsquare_fsquare_times(x3, xxprime, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zzzprime, zzprime, (uint32_t)1U);
Hacl_Bignum_fmul(z3, zzzprime, qx);
Hacl_Bignum_Fsquare_fsquare_times(xx0, x, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zz0, z, (uint32_t)1U);
zzz = buf + (uint32_t)10U;
xx = buf + (uint32_t)15U;
zz = buf + (uint32_t)20U;
Hacl_Bignum_fmul(x2, xx, zz);
Hacl_Bignum_fdifference(zz, xx);
scalar = (uint64_t)121665U;
Hacl_Bignum_fscalar(zzz, zz, scalar);
Hacl_Bignum_fsum(zzz, xx);
Hacl_Bignum_fmul(z2, zzz, zz);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint64_t bit0 = (uint64_t)(byt >> (uint32_t)7U);
uint64_t bit;
Hacl_EC_Point_swap_conditional(nq, nqpq, bit0);
Hacl_EC_AddAndDouble_fmonty(nq2, nqpq2, nq, nqpq, q);
bit = (uint64_t)(byt >> (uint32_t)7U);
Hacl_EC_Point_swap_conditional(nq2, nqpq2, bit);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint8_t byt1;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq, nqpq, nq2, nqpq2, q, byt);
byt1 = byt << (uint32_t)1U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq2, nqpq2, nq, nqpq, q, byt1);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i_ = i - (uint32_t)1U;
uint8_t byt_;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(nq, nqpq, nq2, nqpq2, q, byt);
byt_ = byt << (uint32_t)2U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byt_, i_);
}
}
static void
Hacl_EC_Ladder_BigLoop_cmult_big_loop(
uint8_t *n1,
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i1 = i - (uint32_t)1U;
uint8_t byte = n1[i1];
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byte, (uint32_t)4U);
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, i1);
}
}
static void Hacl_EC_Ladder_cmult(uint64_t *result, uint8_t *n1, uint64_t *q)
{
uint64_t point_buf[40U] = { 0U };
uint64_t *nq = point_buf;
uint64_t *nqpq = point_buf + (uint32_t)10U;
uint64_t *nq2 = point_buf + (uint32_t)20U;
uint64_t *nqpq2 = point_buf + (uint32_t)30U;
Hacl_EC_Point_copy(nqpq, q);
nq[0U] = (uint64_t)1U;
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, (uint32_t)32U);
Hacl_EC_Point_copy(result, nq);
}
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint)
{
uint64_t buf0[10U] = { 0U };
uint64_t *x0 = buf0;
uint64_t *z = buf0 + (uint32_t)5U;
uint64_t *q;
Hacl_EC_Format_fexpand(x0, basepoint);
z[0U] = (uint64_t)1U;
q = buf0;
{
uint8_t e[32U] = { 0U };
uint8_t e0;
uint8_t e31;
uint8_t e01;
uint8_t e311;
uint8_t e312;
uint8_t *scalar;
memcpy(e, secret, (uint32_t)32U * sizeof secret[0U]);
e0 = e[0U];
e31 = e[31U];
e01 = e0 & (uint8_t)248U;
e311 = e31 & (uint8_t)127U;
e312 = e311 | (uint8_t)64U;
e[0U] = e01;
e[31U] = e312;
scalar = e;
{
uint64_t buf[15U] = { 0U };
uint64_t *nq = buf;
uint64_t *x = nq;
x[0U] = (uint64_t)1U;
Hacl_EC_Ladder_cmult(nq, scalar, q);
Hacl_EC_Format_scalar_of_point(mypublic, nq);
}
}
}

View File

@ -0,0 +1,186 @@
/*
* ECDH with curve-optimized implementation multiplexing
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* 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)
*/
#include "common.h"
#if defined(MBEDTLS_ECDH_C) && defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
#include <mbedtls/ecdh.h>
#if !(defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16))
#define KRML_VERIFIED_UINT128
#endif
#include <Hacl_Curve25519.h>
#include <mbedtls/platform_util.h>
#include "x25519.h"
#include <string.h>
/*
* Initialize context
*/
void mbedtls_x25519_init( mbedtls_x25519_context *ctx )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x25519_context ) );
}
/*
* Free context
*/
void mbedtls_x25519_free( mbedtls_x25519_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES );
mbedtls_platform_zeroize( ctx->peer_point, MBEDTLS_X25519_KEY_SIZE_BYTES );
}
int mbedtls_x25519_make_params( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = 0;
uint8_t base[MBEDTLS_X25519_KEY_SIZE_BYTES] = {0};
if( ( ret = f_rng( p_rng, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES ) ) != 0 )
return ret;
*olen = MBEDTLS_X25519_KEY_SIZE_BYTES + 4;
if( blen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
*buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
*buf++ = MBEDTLS_ECP_TLS_CURVE25519 >> 8;
*buf++ = MBEDTLS_ECP_TLS_CURVE25519 & 0xFF;
*buf++ = MBEDTLS_X25519_KEY_SIZE_BYTES;
base[0] = 9;
Hacl_Curve25519_crypto_scalarmult( buf, ctx->our_secret, base );
base[0] = 0;
if( memcmp( buf, base, MBEDTLS_X25519_KEY_SIZE_BYTES) == 0 )
return MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( 0 );
}
int mbedtls_x25519_read_params( mbedtls_x25519_context *ctx,
const unsigned char **buf, const unsigned char *end )
{
if( end - *buf < MBEDTLS_X25519_KEY_SIZE_BYTES + 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if( ( *(*buf)++ != MBEDTLS_X25519_KEY_SIZE_BYTES ) )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
memcpy( ctx->peer_point, *buf, MBEDTLS_X25519_KEY_SIZE_BYTES );
*buf += MBEDTLS_X25519_KEY_SIZE_BYTES;
return( 0 );
}
int mbedtls_x25519_get_params( mbedtls_x25519_context *ctx, const mbedtls_ecp_keypair *key,
mbedtls_x25519_ecdh_side side )
{
size_t olen = 0;
switch( side ) {
case MBEDTLS_X25519_ECDH_THEIRS:
return mbedtls_ecp_point_write_binary( &key->grp, &key->Q, MBEDTLS_ECP_PF_COMPRESSED, &olen, ctx->peer_point, MBEDTLS_X25519_KEY_SIZE_BYTES );
case MBEDTLS_X25519_ECDH_OURS:
return mbedtls_mpi_write_binary_le( &key->d, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES );
default:
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
}
int mbedtls_x25519_calc_secret( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng )
{
/* f_rng and p_rng are not used here because this implementation does not
need blinding since it has constant trace. */
(( void )f_rng);
(( void )p_rng);
*olen = MBEDTLS_X25519_KEY_SIZE_BYTES;
if( blen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
Hacl_Curve25519_crypto_scalarmult( buf, ctx->our_secret, ctx->peer_point);
/* Wipe the DH secret and don't let the peer chose a small subgroup point */
mbedtls_platform_zeroize( ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES );
if( memcmp( buf, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES) == 0 )
return MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( 0 );
}
int mbedtls_x25519_make_public( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = 0;
unsigned char base[MBEDTLS_X25519_KEY_SIZE_BYTES] = { 0 };
if( ctx == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if( ( ret = f_rng( p_rng, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES ) ) != 0 )
return ret;
*olen = MBEDTLS_X25519_KEY_SIZE_BYTES + 1;
if( blen < *olen )
return(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
*buf++ = MBEDTLS_X25519_KEY_SIZE_BYTES;
base[0] = 9;
Hacl_Curve25519_crypto_scalarmult( buf, ctx->our_secret, base );
base[0] = 0;
if( memcmp( buf, base, MBEDTLS_X25519_KEY_SIZE_BYTES ) == 0 )
return MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( ret );
}
int mbedtls_x25519_read_public( mbedtls_x25519_context *ctx,
const unsigned char *buf, size_t blen )
{
if( blen < MBEDTLS_X25519_KEY_SIZE_BYTES + 1 )
return(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
if( (*buf++ != MBEDTLS_X25519_KEY_SIZE_BYTES) )
return(MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
memcpy( ctx->peer_point, buf, MBEDTLS_X25519_KEY_SIZE_BYTES );
return( 0 );
}
#endif /* MBEDTLS_ECDH_C && MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED */

View File

@ -0,0 +1,40 @@
set(p256m_target ${MBEDTLS_TARGET_PREFIX}p256m)
add_library(${p256m_target}
p256-m_driver_entrypoints.c
p256-m/p256-m.c)
target_include_directories(${p256m_target}
PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/p256-m>
$<BUILD_INTERFACE:${MBEDTLS_DIR}/include>
$<INSTALL_INTERFACE:include>
PRIVATE ${MBEDTLS_DIR}/library/)
# Pass-through MBEDTLS_CONFIG_FILE and MBEDTLS_USER_CONFIG_FILE
# This must be duplicated from library/CMakeLists.txt because
# p256m is not directly linked against any mbedtls targets
# so does not inherit the compile definitions.
if(MBEDTLS_CONFIG_FILE)
target_compile_definitions(${p256m_target}
PUBLIC MBEDTLS_CONFIG_FILE="${MBEDTLS_CONFIG_FILE}")
endif()
if(MBEDTLS_USER_CONFIG_FILE)
target_compile_definitions(${p256m_target}
PUBLIC MBEDTLS_USER_CONFIG_FILE="${MBEDTLS_USER_CONFIG_FILE}")
endif()
if(INSTALL_MBEDTLS_HEADERS)
install(DIRECTORY :${CMAKE_CURRENT_SOURCE_DIR}
DESTINATION include
FILE_PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
FILES_MATCHING PATTERN "*.h")
endif(INSTALL_MBEDTLS_HEADERS)
install(TARGETS ${p256m_target}
EXPORT MbedTLSTargets
DESTINATION ${CMAKE_INSTALL_LIBDIR}
PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)

View File

@ -0,0 +1,5 @@
THIRDPARTY_INCLUDES+=-I$(THIRDPARTY_DIR)/p256-m/p256-m/include -I$(THIRDPARTY_DIR)/p256-m/p256-m/include/p256-m -I$(THIRDPARTY_DIR)/p256-m/p256-m_driver_interface
THIRDPARTY_CRYPTO_OBJECTS+= \
$(THIRDPARTY_DIR)/p256-m//p256-m_driver_entrypoints.o \
$(THIRDPARTY_DIR)/p256-m//p256-m/p256-m.o

View File

@ -0,0 +1,4 @@
The files within the `p256-m/` subdirectory originate from the [p256-m GitHub repository](https://github.com/mpg/p256-m). They are distributed here under a dual Apache-2.0 OR GPL-2.0-or-later license. They are authored by Manuel Pégourié-Gonnard. p256-m is a minimalistic implementation of ECDH and ECDSA on NIST P-256, especially suited to constrained 32-bit environments. Mbed TLS documentation for integrating drivers uses p256-m as an example of a software accelerator, and describes how it can be integrated alongside Mbed TLS. It should be noted that p256-m files in the Mbed TLS repo will not be updated regularly, so they may not have fixes and improvements present in the upstream project.
The files `p256-m.c`, `p256-m.h` and `README.md` have been taken from the `p256-m` repository.
It should be noted that p256-m deliberately does not supply its own cryptographically secure RNG function. As a result, the PSA RNG is used, with `p256_generate_random()` wrapping `psa_generate_random()`.

View File

@ -0,0 +1,544 @@
*This is the original README for the p256-m repository. Please note that as
only a subset of p256-m's files are present in Mbed TLS, this README may refer
to files that are not present/relevant here.*
p256-m is a minimalistic implementation of ECDH and ECDSA on NIST P-256,
especially suited to constrained 32-bit environments. It's written in standard
C, with optional bits of assembly for Arm Cortex-M and Cortex-A CPUs.
Its design is guided by the following goals in this order:
1. correctness & security;
2. low code size & RAM usage;
3. runtime performance.
Most cryptographic implementations care more about speed than footprint, and
some might even risk weakening security for more speed. p256-m was written
because I wanted to see what happened when reversing the usual emphasis.
The result is a full implementation of ECDH and ECDSA in **less than 3KiB of
code**, using **less than 768 bytes of RAM**, with comparable performance
to existing implementations (see below) - in less than 700 LOC.
_Contents of this Readme:_
- [Correctness](#correctness)
- [Security](#security)
- [Code size](#code-size)
- [RAM usage](#ram-usage)
- [Runtime performance](#runtime-performance)
- [Comparison with other implementations](#comparison-with-other-implementations)
- [Design overview](#design-overview)
- [Notes about other curves](#notes-about-other-curves)
- [Notes about other platforms](#notes-about-other-platforms)
## Correctness
**API design:**
- The API is minimal: only 4 public functions.
- Each public function fully validates its inputs and returns specific errors.
- The API uses arrays of octets for all input and output.
**Testing:**
- p256-m is validated against multiple test vectors from various RFCs and
NIST.
- In addition, crafted inputs are used for negative testing and to reach
corner cases.
- Two test suites are provided: one for closed-box testing (using only the
public API), one for open-box testing (for unit-testing internal functions,
and reaching more error cases by exploiting knowledge of how the RNG is used).
- The resulting branch coverage is maximal: closed-box testing reaches all
branches except four; three of them are reached by open-box testing using a
rigged RNG; the last branch could only be reached by computing a discrete log
on P-256... See `coverage.sh`.
- Testing also uses dynamic analysis: valgrind, ASan, MemSan, UBSan.
**Code quality:**
- The code is standard C99; it builds without warnings with `clang
-Weverything` and `gcc -Wall -Wextra -pedantic`.
- The code is small and well documented, including internal APIs: with the
header file, it's less than 700 lines of code, and more lines of comments
than of code.
- However it _has not been reviewed_ independently so far, as this is a
personal project.
**Short Weierstrass pitfalls:**
Its has been [pointed out](https://safecurves.cr.yp.to/) that the NIST curves,
and indeed all Short Weierstrass curves, have a number of pitfalls including
risk for the implementation to:
- "produce incorrect results for some rare curve points" - this is avoided by
carefully checking the validity domain of formulas used throughout the code;
- "leak secret data when the input isn't a curve point" - this is avoided by
validating that points lie on the curve every time a point is deserialized.
## Security
In addition to the above correctness claims, p256-m has the following
properties:
- it has no branch depending (even indirectly) on secret data;
- it has no memory access depending (even indirectly) on secret data.
These properties are checked using valgrind and MemSan with the ideas
behind [ctgrind](https://github.com/agl/ctgrind), see `consttime.sh`.
In addition to avoiding branches and memory accesses depending on secret data,
p256-m also avoid instructions (or library functions) whose execution time
depends on the value of operands on cores of interest. Namely, it never uses
integer division, and for multiplication by default it only uses 16x16->32 bit
unsigned multiplication. On cores which have a constant-time 32x32->64 bit
unsigned multiplication instruction, the symbol `MUL64_IS_CONSTANT_TIME` can
be defined by the user at compile-time to take advantage of it in order to
improve performance and code size. (On Cortex-M and Cortex-A cores wtih GCC or
Clang this is not necessary, since inline assembly is used instead.)
As a result, p256-m should be secure against the following classes of attackers:
1. attackers who can only manipulate the input and observe the output;
2. attackers who can also measure the total computation time of the operation;
3. attackers who can also observe and manipulate micro-architectural features
such as the cache or branch predictor with arbitrary precision.
However, p256-m makes no attempt to protect against:
4. passive physical attackers who can record traces of physical emissions
(power, EM, sound) of the CPU while it manipulates secrets;
5. active physical attackers who can also inject faults in the computation.
(Note: p256-m should actually be secure against SPA, by virtue of being fully
constant-flow, but is not expected to resist any other physical attack.)
**Warning:** p256-m requires an externally-provided RNG function. If that
function is not cryptographically secure, then neither is p256-m's key
generation or ECDSA signature generation.
_Note:_ p256-m also follows best practices such as securely erasing secret
data on the stack before returning.
## Code size
Compiled with
[ARM-GCC 9](https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads),
with `-mthumb -Os`, here are samples of code sizes reached on selected cores:
- Cortex-M0: 2988 bytes
- Cortex-M4: 2900 bytes
- Cortex-A7: 2924 bytes
Clang was also tried but tends to generate larger code (by about 10%). For
details, see `sizes.sh`.
**What's included:**
- Full input validation and (de)serialisation of input/outputs to/from bytes.
- Cleaning up secret values from the stack before returning from a function.
- The code has no dependency on libc functions or the toolchain's runtime
library (such as helpers for long multiply); this can be checked for the
Arm-GCC toolchain with the `deps.sh` script.
**What's excluded:**
- A secure RNG function needs to be provided externally, see
`p256_generate_random()` in `p256-m.h`.
## RAM usage
p256-m doesn't use any dynamic memory (on the heap), only the stack. Here's
how much stack is used by each of its 4 public functions on selected cores:
| Function | Cortex-M0 | Cortex-M4 | Cortex-A7 |
| ------------------------- | --------: | --------: | --------: |
| `p256_gen_keypair` | 608 | 564 | 564 |
| `p256_ecdh_shared_secret` | 640 | 596 | 596 |
| `p256_ecdsa_sign` | 664 | 604 | 604 |
| `p256_ecdsa_verify` | 752 | 700 | 700 |
For details, see `stack.sh`, `wcs.py` and `libc.msu` (the above figures assume
that the externally-provided RNG function uses at most 384 bytes of stack).
## Runtime performance
Here are the timings of each public function in milliseconds measured on
platforms based on a selection of cores:
- Cortex-M0 at 48 MHz: STM32F091 board running Mbed OS 6
- Cortex-M4 at 100 MHz: STM32F411 board running Mbed OS 6
- Cortex-A7 at 900 MHz: Raspberry Pi 2B running Raspbian Buster
| Function | Cortex-M0 | Cortex-M4 | Cortex-A7 |
| ------------------------- | --------: | --------: | --------: |
| `p256_gen_keypair` | 921 | 145 | 11 |
| `p256_ecdh_shared_secret` | 922 | 144 | 11 |
| `p256_ecdsa_sign` | 990 | 155 | 12 |
| `p256_ecdsa_verify` | 1976 | 309 | 24 |
| Sum of the above | 4809 | 753 | 59 |
The sum of these operations corresponds to a TLS handshake using ECDHE-ECDSA
with mutual authentication based on raw public keys or directly-trusted
certificates (otherwise, add one 'verify' for each link in the peer's
certificate chain).
_Note_: the above figures where obtained by compiling with GCC, which is able
to use inline assembly. Without that inline assembly (22 lines for Cortex-M0,
1 line for Cortex-M4), the code would be roughly 2 times slower on those
platforms. (The effect is much less important on the Cortex-A7 core.)
For details, see `bench.sh`, `benchmark.c` and `on-target-benchmark/`.
## Comparison with other implementations
The most relevant/convenient implementation for comparisons is
[TinyCrypt](https://github.com/intel/tinycrypt), as it's also a standalone
implementation of ECDH and ECDSA on P-256 only, that also targets constrained
devices. Other implementations tend to implement many curves and build on a
shared bignum/MPI module (possibly also supporting RSA), which makes fair
comparisons less convenient.
The scripts used for TinyCrypt measurements are available in [this
branch](https://github.com/mpg/tinycrypt/tree/measurements), based on version
0.2.8.
**Code size**
| Core | p256-m | TinyCrypt |
| --------- | -----: | --------: |
| Cortex-M0 | 2988 | 6134 |
| Cortex-M4 | 2900 | 5934 |
| Cortex-A7 | 2924 | 5934 |
**RAM usage**
TinyCrypto also uses no heap, only the stack. Here's the RAM used by each
operation on a Cortex-M0 core:
| operation | p256-m | TinyCrypt |
| ------------------ | -----: | --------: |
| key generation | 608 | 824 |
| ECDH shared secret | 640 | 728 |
| ECDSA sign | 664 | 880 |
| ECDSA verify | 752 | 824 |
On a Cortex-M4 or Cortex-A7 core (identical numbers):
| operation | p256-m | TinyCrypt |
| ------------------ | -----: | --------: |
| key generation | 564 | 796 |
| ECDH shared secret | 596 | 700 |
| ECDSA sign | 604 | 844 |
| ECDSA verify | 700 | 808 |
**Runtime performance**
Here are the timings of each operation in milliseconds measured on
platforms based on a selection of cores:
_Cortex-M0_ at 48 MHz: STM32F091 board running Mbed OS 6
| Operation | p256-m | TinyCrypt |
| ------------------ | -----: | --------: |
| Key generation | 921 | 979 |
| ECDH shared secret | 922 | 975 |
| ECDSA sign | 990 | 1009 |
| ECDSA verify | 1976 | 1130 |
| Sum of those 4 | 4809 | 4093 |
_Cortex-M4_ at 100 MHz: STM32F411 board running Mbed OS 6
| Operation | p256-m | TinyCrypt |
| ------------------ | -----: | --------: |
| Key generation | 145 | 178 |
| ECDH shared secret | 144 | 177 |
| ECDSA sign | 155 | 188 |
| ECDSA verify | 309 | 210 |
| Sum of those 4 | 753 | 753 |
_Cortex-A7_ at 900 MHz: Raspberry Pi 2B running Raspbian Buster
| Operation | p256-m | TinyCrypt |
| ------------------ | -----: | --------: |
| Key generation | 11 | 13 |
| ECDH shared secret | 11 | 13 |
| ECDSA sign | 12 | 14 |
| ECDSA verify | 24 | 15 |
| Sum of those 4 | 59 | 55 |
_64-bit Intel_ (i7-6500U at 2.50GHz) laptop running Ubuntu 20.04
Note: results in microseconds (previous benchmarks in milliseconds)
| Operation | p256-m | TinyCrypt |
| ------------------ | -----: | --------: |
| Key generation | 1060 | 1627 |
| ECDH shared secret | 1060 | 1611 |
| ECDSA sign | 1136 | 1712 |
| ECDSA verify | 2279 | 1888 |
| Sum of those 4 | 5535 | 6838 |
**Other differences**
- While p256-m fully validates all inputs, Tinycrypt's ECDH shared secret
function doesn't include validation of the peer's public key, which should be
done separately by the user for static ECDH (there are attacks [when users
forget](https://link.springer.com/chapter/10.1007/978-3-319-24174-6_21)).
- The two implementations have slightly different security characteristics:
p256-m is fully constant-time from the ground up so should be more robust
than TinyCrypt against powerful local attackers (such as an untrusted OS
attacking a secure enclave); on the other hand TinyCrypt includes coordinate
randomisation which protects against some passive physical attacks (such as
DPA, see Table 3, column C9 of [this
paper](https://www.esat.kuleuven.be/cosic/publications/article-2293.pdf#page=12)),
which p256-m completely ignores.
- TinyCrypt's code looks like it could easily be expanded to support other
curves, while p256-m has much more hard-coded to minimize code size (see
"Notes about other curves" below).
- TinyCrypt uses a specialised routine for reduction modulo the curve prime,
exploiting its structure as a Solinas prime, which should be faster than the
generic Montgomery reduction used by p256-m, but other factors appear to
compensate for that.
- TinyCrypt uses Co-Z Jacobian formulas for point operation, which should be
faster (though a bit larger) than the mixed affine-Jacobian formulas
used by p256-m, but again other factors appear to compensate for that.
- p256-m uses bits of inline assembly for 64-bit multiplication on the
platforms used for benchmarking, while TinyCrypt uses only C (and the
compiler's runtime library).
- TinyCrypt uses a specialised routine based on Shamir's trick for
ECDSA verification, which gives much better performance than the generic
code that p256-m uses in order to minimize code size.
## Design overview
The implementation is contained in a single file to keep most functions static
and allow for more optimisations. It is organized in multiple layers:
- Fixed-width multi-precision arithmetic
- Fixed-width modular arithmetic
- Operations on curve points
- Operations with scalars
- The public API
**Multi-precision arithmetic.**
Large integers are represented as arrays of `uint32_t` limbs. When carries may
occur, casts to `uint64_t` are used to nudge the compiler towards using the
CPU's carry flag. When overflow may occur, functions return a carry flag.
This layer contains optional assembly for Cortex-M and Cortex-A cores, for the
internal `u32_muladd64()` function, as well as two pure C versions of this
function, depending on whether `MUL64_IS_CONSTANT_TIME`.
This layer's API consists of:
- addition, subtraction;
- multiply-and-add, shift by one limb (for Montgomery multiplication);
- conditional assignment, assignment of a small value;
- comparison of two values for equality, comparison to 0 for equality;
- (de)serialization as big-endian arrays of bytes.
**Modular arithmetic.**
All modular operations are done in the Montgomery domain, that is x is
represented by `x * 2^256 mod m`; integers need to be converted to that domain
before computations, and back from it afterwards. Montgomery constants
associated to the curve's p and n are pre-computed and stored in static
structures.
Modular inversion is computed using Fermat's little theorem to get
constant-time behaviour with respect to the value being inverted.
This layer's API consists of:
- the curve's constants p and n (and associated Montgomery constants);
- modular addition, subtraction, multiplication, and inversion;
- assignment of a small value;
- conversion to/from Montgomery domain;
- (de)serialization to/from bytes with integrated range checking and
Montgomery domain conversion.
**Operations on curve points.**
Curve points are represented using either affine or Jacobian coordinates;
affine coordinates are extended to represent 0 as (0,0). Individual
coordinates are always in the Montgomery domain.
Not all formulas associated with affine or Jacobian coordinates are complete;
great care is taken to document and satisfy each function's pre-conditions.
This layer's API consists of:
- curve constants: b from the equation, the base point's coordinates;
- point validity check (on the curve and not 0);
- Jacobian to affine coordinate conversion;
- point doubling in Jacobian coordinates (complete formulas);
- point addition in mixed affine-Jacobian coordinates (P not in {0, Q, -Q});
- point addition-or-doubling in affine coordinates (leaky version, only used
for ECDSA verify where all data is public);
- (de)serialization to/from bytes with integrated validity checking
**Scalar operations.**
The crucial function here is scalar multiplication. It uses a signed binary
ladder, which is a variant of the good old double-and-add algorithm where an
addition/subtraction is performed at each step. Again, care is taken to make
sure the pre-conditions for the addition formulas are always satisfied. The
signed binary ladder only works if the scalar is odd; this is ensured by
negating both the scalar (mod n) and the input point if necessary.
This layer's API consists of:
- scalar multiplication
- de-serialization from bytes with integrated range checking
- generation of a scalar and its associated public key
**Public API.**
This layer builds on the others, but unlike them, all inputs and outputs are
byte arrays. Key generation and ECDH shared secret computation are thin
wrappers around internal functions, just taking care of format conversions and
errors. The ECDSA functions have more non-trivial logic.
This layer's API consists of:
- key-pair generation
- ECDH shared secret computation
- ECDSA signature creation
- ECDSA signature verification
**Testing.**
A self-contained, straightforward, pure-Python implementation was first
produced as a warm-up and to help check intermediate values. Test vectors from
various sources are embedded and used to validate the implementation.
This implementation, `p256.py`, is used by a second Python script,
`gen-test-data.py`, to generate additional data for both positive and negative
testing, available from a C header file, that is then used by the closed-box
and open-box test programs.
p256-m can be compiled with extra instrumentation to mark secret data and
allow either valgrind or MemSan to check that no branch or memory access
depends on it (even indirectly). Macros are defined for this purpose near the
top of the file.
**Tested platforms.**
There are 4 versions of the internal function `u32_muladd64`: two assembly
versions, for Cortex-M/A cores with or without the DSP extension, and two
pure-C versions, depending on whether `MUL64_IS_CONSTANT_TIME`.
Tests are run on the following platforms:
- `make` on x64 tests the pure-C version without `MUL64_IS_CONSTANT_TIME`
(with Clang).
- `./consttime.sh` on x64 tests both pure-C versions (with Clang).
- `make` on Arm v7-A (Raspberry Pi 2) tests the Arm-DSP assembly version (with
Clang).
- `on-target-*box` on boards based on Cortex-M0 and M4 cores test both
assembly versions (with GCC).
In addition:
- `sizes.sh` builds the code for three Arm cores with GCC and Clang.
- `deps.sh` checks for external dependencies with GCC.
## Notes about other curves
It should be clear that minimal code size can only be reached by specializing
the implementation to the curve at hand. Here's a list of things in the
implementation that are specific to the NIST P-256 curve, and how the
implementation could be changed to expand to other curves, layer by layer (see
"Design Overview" above).
**Fixed-width multi-precision arithmetic:**
- The number of limbs is hard-coded to 8. For other 256-bit curves, nothing to
change. For a curve of another size, hard-code to another value. For multiple
curves of various sizes, add a parameter to each function specifying the
number of limbs; when declaring arrays, always use the maximum number of
limbs.
**Fixed-width modular arithmetic:**
- The values of the curve's constant p and n, and their associated Montgomery
constants, are hard-coded. For another curve, just hard-code the new constants.
For multiple other curves, define all the constants, and from this layer's API
only keep the functions that already accept a `mod` parameter (that is, remove
convenience functions `m256_xxx_p()`).
- The number of limbs is again hard-coded to 8. See above, but it order to
support multiple sizes there is no need to add a new parameter to functions
in this layer: the existing `mod` parameter can include the number of limbs as
well.
**Operations on curve points:**
- The values of the curve's constants b (constant term from the equation) and
gx, gy (coordinates of the base point) are hard-coded. For another curve,
hard-code the other values. For multiple curves, define each curve's value and
add a "curve id" parameter to all functions in this layer.
- The value of the curve's constant a is implicitly hard-coded to `-3` by using
a standard optimisation to save one multiplication in the first step of
`point_double()`. For curves that don't have a == -3, replace that with the
normal computation.
- The fact that b != 0 in the curve equation is used indirectly, to ensure
that (0, 0) is not a point on the curve and re-use that value to represent
the point 0. As far as I know, all Short Weierstrass curves standardized so
far have b != 0.
- The shape of the curve is assumed to be Short Weierstrass. For other curve
shapes (Montgomery, (twisted) Edwards), this layer would probably look very
different (both implementation and API).
**Scalar operations:**
- If multiple curves are to be supported, all function in this layer need to
gain a new "curve id" parameter.
- This layer assumes that the bit size of the curve's order n is the same as
that of the modulus p. This is true of most curves standardized so far, the
only exception being secp224k1. If that curve were to be supported, the
representation of `n` and scalars would need adapting to allow for an extra
limb.
- The bit size of the curve's order is hard-coded in `scalar_mult()`. For
multiple curves, this should be deduced from the "curve id" parameter.
- The `scalar_mult()` function exploits the fact that the second least
significant bit of the curve's order n is set in order to avoid a special
case. For curve orders that don't meet this criterion, we can just handle that
special case (multiplication by +-2) separately (always compute that and
conditionally assign it to the result).
- The shape of the curve is again assumed to be Short Weierstrass. For other curve
shapes (Montgomery, (twisted) Edwards), this layer would probably have a
very different implementation.
**Public API:**
- For multiple curves, all functions in this layer would need to gain a "curve
id" parameter and handle variable-sized input/output.
- The shape of the curve is again assumed to be Short Weierstrass. For other curve
shapes (Montgomery, (twisted) Edwards), the ECDH API would probably look
quite similar (with differences in the size of public keys), but the ECDSA API
wouldn't apply and an EdDSA API would look pretty different.
## Notes about other platforms
While p256-m is standard C99, it is written with constrained 32-bit platforms
in mind and makes a few assumptions about the platform:
- The types `uint8_t`, `uint16_t`, `uint32_t` and `uint64_t` exist.
- 32-bit unsigned addition and subtraction with carry are constant time.
- 16x16->32-bit unsigned multiplication is available and constant time.
Also, on platforms on which 64-bit addition and subtraction with carry, or
even 64x64->128-bit multiplication, are available, p256-m makes no use of
them, though they could significantly improve performance.
This could be improved by replacing uses of arrays of `uint32_t` with a
defined type throughout the internal APIs, and then on 64-bit platforms define
that type to be an array of `uint64_t` instead, and making the obvious
adaptations in the multi-precision arithmetic layer.
Finally, the optional assembly code (which boosts performance by a factor 2 on
tested Cortex-M CPUs, while slightly reducing code size and stack usage) is
currently only available with compilers that support GCC's extended asm
syntax (which includes GCC and Clang).

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,135 @@
/*
* Interface of curve P-256 (ECDH and ECDSA)
*
* Copyright The Mbed TLS Contributors
* Author: Manuel Pégourié-Gonnard.
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef P256_M_H
#define P256_M_H
#include <stdint.h>
#include <stddef.h>
/* Status codes */
#define P256_SUCCESS 0
#define P256_RANDOM_FAILED -1
#define P256_INVALID_PUBKEY -2
#define P256_INVALID_PRIVKEY -3
#define P256_INVALID_SIGNATURE -4
#ifdef __cplusplus
extern "C" {
#endif
/*
* RNG function - must be provided externally and be cryptographically secure.
*
* in: output - must point to a writable buffer of at least output_size bytes.
* output_size - the number of random bytes to write to output.
* out: output is filled with output_size random bytes.
* return 0 on success, non-zero on errors.
*/
extern int p256_generate_random(uint8_t * output, unsigned output_size);
/*
* ECDH/ECDSA generate key pair
*
* [in] draws from p256_generate_random()
* [out] priv: on success, holds the private key, as a big-endian integer
* [out] pub: on success, holds the public key, as two big-endian integers
*
* return: P256_SUCCESS on success
* P256_RANDOM_FAILED on failure
*/
int p256_gen_keypair(uint8_t priv[32], uint8_t pub[64]);
/*
* ECDH compute shared secret
*
* [out] secret: on success, holds the shared secret, as a big-endian integer
* [in] priv: our private key as a big-endian integer
* [in] pub: the peer's public key, as two big-endian integers
*
* return: P256_SUCCESS on success
* P256_INVALID_PRIVKEY if priv is invalid
* P256_INVALID_PUBKEY if pub is invalid
*/
int p256_ecdh_shared_secret(uint8_t secret[32],
const uint8_t priv[32], const uint8_t pub[64]);
/*
* ECDSA sign
*
* [in] draws from p256_generate_random()
* [out] sig: on success, holds the signature, as two big-endian integers
* [in] priv: our private key as a big-endian integer
* [in] hash: the hash of the message to be signed
* [in] hlen: the size of hash in bytes
*
* return: P256_SUCCESS on success
* P256_RANDOM_FAILED on failure
* P256_INVALID_PRIVKEY if priv is invalid
*/
int p256_ecdsa_sign(uint8_t sig[64], const uint8_t priv[32],
const uint8_t *hash, size_t hlen);
/*
* ECDSA verify
*
* [in] sig: the signature to be verified, as two big-endian integers
* [in] pub: the associated public key, as two big-endian integers
* [in] hash: the hash of the message that was signed
* [in] hlen: the size of hash in bytes
*
* return: P256_SUCCESS on success - the signature was verified as valid
* P256_INVALID_PUBKEY if pub is invalid
* P256_INVALID_SIGNATURE if the signature was found to be invalid
*/
int p256_ecdsa_verify(const uint8_t sig[64], const uint8_t pub[64],
const uint8_t *hash, size_t hlen);
/*
* Public key validation
*
* Note: you never need to call this function, as all other functions always
* validate their input; however it's availabe if you want to validate the key
* without performing an operation.
*
* [in] pub: the public key, as two big-endian integers
*
* return: P256_SUCCESS if the key is valid
* P256_INVALID_PUBKEY if pub is invalid
*/
int p256_validate_pubkey(const uint8_t pub[64]);
/*
* Private key validation
*
* Note: you never need to call this function, as all other functions always
* validate their input; however it's availabe if you want to validate the key
* without performing an operation.
*
* [in] priv: the private key, as a big-endian integer
*
* return: P256_SUCCESS if the key is valid
* P256_INVALID_PRIVKEY if priv is invalid
*/
int p256_validate_privkey(const uint8_t priv[32]);
/*
* Compute public key from private key
*
* [out] pub: the associated public key, as two big-endian integers
* [in] priv: the private key, as a big-endian integer
*
* return: P256_SUCCESS on success
* P256_INVALID_PRIVKEY if priv is invalid
*/
int p256_public_from_private(uint8_t pub[64], const uint8_t priv[32]);
#ifdef __cplusplus
}
#endif
#endif /* P256_M_H */

View File

@ -0,0 +1,312 @@
/*
* Driver entry points for p256-m
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/platform.h"
#include "p256-m_driver_entrypoints.h"
#include "p256-m/p256-m.h"
#include "psa/crypto.h"
#include <stddef.h>
#include <string.h>
#include "psa_crypto_driver_wrappers_no_static.h"
#if defined(MBEDTLS_PSA_P256M_DRIVER_ENABLED)
/* INFORMATION ON PSA KEY EXPORT FORMATS:
*
* PSA exports SECP256R1 keys in two formats:
* 1. Keypair format: 32 byte string which is just the private key (public key
* can be calculated from the private key)
* 2. Public Key format: A leading byte 0x04 (indicating uncompressed format),
* followed by the 64 byte public key. This results in a
* total of 65 bytes.
*
* p256-m's internal format for private keys matches PSA. Its format for public
* keys is only 64 bytes: the same as PSA but without the leading byte (0x04).
* Hence, when passing public keys from PSA to p256-m, the leading byte is
* removed.
*
* Shared secret and signature have the same format between PSA and p256-m.
*/
#define PSA_PUBKEY_SIZE 65
#define PSA_PUBKEY_HEADER_BYTE 0x04
#define P256_PUBKEY_SIZE 64
#define PRIVKEY_SIZE 32
#define SHARED_SECRET_SIZE 32
#define SIGNATURE_SIZE 64
#define CURVE_BITS 256
/* Convert between p256-m and PSA error codes */
static psa_status_t p256_to_psa_error(int ret)
{
switch (ret) {
case P256_SUCCESS:
return PSA_SUCCESS;
case P256_INVALID_PUBKEY:
case P256_INVALID_PRIVKEY:
return PSA_ERROR_INVALID_ARGUMENT;
case P256_INVALID_SIGNATURE:
return PSA_ERROR_INVALID_SIGNATURE;
case P256_RANDOM_FAILED:
default:
return PSA_ERROR_GENERIC_ERROR;
}
}
psa_status_t p256_transparent_import_key(const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length,
size_t *bits)
{
/* Check the key size */
if (*bits != 0 && *bits != CURVE_BITS) {
return PSA_ERROR_NOT_SUPPORTED;
}
/* Validate the key (and its type and size) */
psa_key_type_t type = psa_get_key_type(attributes);
if (type == PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1)) {
if (data_length != PSA_PUBKEY_SIZE) {
return *bits == 0 ? PSA_ERROR_NOT_SUPPORTED : PSA_ERROR_INVALID_ARGUMENT;
}
/* See INFORMATION ON PSA KEY EXPORT FORMATS near top of file */
if (p256_validate_pubkey(data + 1) != P256_SUCCESS) {
return PSA_ERROR_INVALID_ARGUMENT;
}
} else if (type == PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)) {
if (data_length != PRIVKEY_SIZE) {
return *bits == 0 ? PSA_ERROR_NOT_SUPPORTED : PSA_ERROR_INVALID_ARGUMENT;
}
if (p256_validate_privkey(data) != P256_SUCCESS) {
return PSA_ERROR_INVALID_ARGUMENT;
}
} else {
return PSA_ERROR_NOT_SUPPORTED;
}
*bits = CURVE_BITS;
/* We only support the export format for input, so just copy. */
if (key_buffer_size < data_length) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
memcpy(key_buffer, data, data_length);
*key_buffer_length = data_length;
return PSA_SUCCESS;
}
psa_status_t p256_transparent_export_public_key(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
uint8_t *data,
size_t data_size,
size_t *data_length)
{
/* Is this the right curve? */
size_t bits = psa_get_key_bits(attributes);
psa_key_type_t type = psa_get_key_type(attributes);
if (bits != CURVE_BITS || type != PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)) {
return PSA_ERROR_NOT_SUPPORTED;
}
/* Validate sizes, as p256-m expects fixed-size buffers */
if (key_buffer_size != PRIVKEY_SIZE) {
return PSA_ERROR_INVALID_ARGUMENT;
}
if (data_size < PSA_PUBKEY_SIZE) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
/* See INFORMATION ON PSA KEY EXPORT FORMATS near top of file */
data[0] = PSA_PUBKEY_HEADER_BYTE;
int ret = p256_public_from_private(data + 1, key_buffer);
if (ret == P256_SUCCESS) {
*data_length = PSA_PUBKEY_SIZE;
}
return p256_to_psa_error(ret);
}
psa_status_t p256_transparent_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length)
{
/* We don't use this argument, but the specification mandates the signature
* of driver entry-points. (void) used to avoid compiler warning. */
(void) attributes;
/* Validate sizes, as p256-m expects fixed-size buffers */
if (key_buffer_size != PRIVKEY_SIZE) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
/*
* p256-m's keypair generation function outputs both public and private
* keys. Allocate a buffer to which the public key will be written. The
* private key will be written to key_buffer, which is passed to this
* function as an argument. */
uint8_t public_key_buffer[P256_PUBKEY_SIZE];
int ret = p256_gen_keypair(key_buffer, public_key_buffer);
if (ret == P256_SUCCESS) {
*key_buffer_length = PRIVKEY_SIZE;
}
return p256_to_psa_error(ret);
}
psa_status_t p256_transparent_key_agreement(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length)
{
/* We don't use these arguments, but the specification mandates the
* sginature of driver entry-points. (void) used to avoid compiler
* warning. */
(void) attributes;
(void) alg;
/* Validate sizes, as p256-m expects fixed-size buffers */
if (key_buffer_size != PRIVKEY_SIZE || peer_key_length != PSA_PUBKEY_SIZE) {
return PSA_ERROR_INVALID_ARGUMENT;
}
if (shared_secret_size < SHARED_SECRET_SIZE) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
/* See INFORMATION ON PSA KEY EXPORT FORMATS near top of file */
const uint8_t *peer_key_p256m = peer_key + 1;
int ret = p256_ecdh_shared_secret(shared_secret, key_buffer, peer_key_p256m);
if (ret == P256_SUCCESS) {
*shared_secret_length = SHARED_SECRET_SIZE;
}
return p256_to_psa_error(ret);
}
psa_status_t p256_transparent_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length)
{
/* We don't use these arguments, but the specification mandates the
* sginature of driver entry-points. (void) used to avoid compiler
* warning. */
(void) attributes;
(void) alg;
/* Validate sizes, as p256-m expects fixed-size buffers */
if (key_buffer_size != PRIVKEY_SIZE) {
return PSA_ERROR_INVALID_ARGUMENT;
}
if (signature_size < SIGNATURE_SIZE) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
int ret = p256_ecdsa_sign(signature, key_buffer, hash, hash_length);
if (ret == P256_SUCCESS) {
*signature_length = SIGNATURE_SIZE;
}
return p256_to_psa_error(ret);
}
/* This function expects the key buffer to contain a PSA public key,
* as exported by psa_export_public_key() */
static psa_status_t p256_verify_hash_with_public_key(
const uint8_t *key_buffer,
size_t key_buffer_size,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length)
{
/* Validate sizes, as p256-m expects fixed-size buffers */
if (key_buffer_size != PSA_PUBKEY_SIZE || *key_buffer != PSA_PUBKEY_HEADER_BYTE) {
return PSA_ERROR_INVALID_ARGUMENT;
}
if (signature_length != SIGNATURE_SIZE) {
return PSA_ERROR_INVALID_SIGNATURE;
}
/* See INFORMATION ON PSA KEY EXPORT FORMATS near top of file */
const uint8_t *public_key_p256m = key_buffer + 1;
int ret = p256_ecdsa_verify(signature, public_key_p256m, hash, hash_length);
return p256_to_psa_error(ret);
}
psa_status_t p256_transparent_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length)
{
/* We don't use this argument, but the specification mandates the signature
* of driver entry-points. (void) used to avoid compiler warning. */
(void) alg;
psa_status_t status;
uint8_t public_key_buffer[PSA_PUBKEY_SIZE];
size_t public_key_buffer_size = PSA_PUBKEY_SIZE;
size_t public_key_length = PSA_PUBKEY_SIZE;
/* As p256-m doesn't require dynamic allocation, we want to avoid it in
* the entrypoint functions as well. psa_driver_wrapper_export_public_key()
* requires size_t*, so we use a pointer to a stack variable. */
size_t *public_key_length_ptr = &public_key_length;
/* The contents of key_buffer may either be the 32 byte private key
* (keypair format), or 0x04 followed by the 64 byte public key (public
* key format). To ensure the key is in the latter format, the public key
* is exported. */
status = psa_driver_wrapper_export_public_key(
attributes,
key_buffer,
key_buffer_size,
public_key_buffer,
public_key_buffer_size,
public_key_length_ptr);
if (status != PSA_SUCCESS) {
goto exit;
}
status = p256_verify_hash_with_public_key(
public_key_buffer,
public_key_buffer_size,
hash,
hash_length,
signature,
signature_length);
exit:
return status;
}
#endif /* MBEDTLS_PSA_P256M_DRIVER_ENABLED */

View File

@ -0,0 +1,219 @@
/*
* Driver entry points for p256-m
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef P256M_DRIVER_ENTRYPOINTS_H
#define P256M_DRIVER_ENTRYPOINTS_H
#if defined(MBEDTLS_PSA_P256M_DRIVER_ENABLED)
#ifndef PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT
#define PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
#endif /* MBEDTLS_PSA_P256M_DRIVER_ENABLED */
#include "psa/crypto_types.h"
/** Import SECP256R1 key.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] data The raw key material. For private keys
* this must be a big-endian integer of 32
* bytes; for public key this must be an
* uncompressed ECPoint (65 bytes).
* \param[in] data_length The size of the raw key material.
* \param[out] key_buffer The buffer to contain the key data in
* output format upon successful return.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[out] key_buffer_length The length of the data written in \p
* key_buffer in bytes.
* \param[out] bits The bitsize of the key.
*
* \retval #PSA_SUCCESS
* Success. Keypair generated and stored in buffer.
* \retval #PSA_ERROR_NOT_SUPPORTED
* The input is not supported by this driver (not SECP256R1).
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The input is invalid.
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* \p key_buffer_size is too small.
*/
psa_status_t p256_transparent_import_key(const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length,
size_t *bits);
/** Export SECP256R1 public key, from the private key.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] key_buffer The private key in the export format.
* \param[in] key_buffer_size The size of the private key in bytes.
* \param[out] data The buffer to contain the public key in
* the export format upon successful return.
* \param[in] data_size The size of the \p data buffer in bytes.
* \param[out] data_length The length written to \p data in bytes.
*
* \retval #PSA_SUCCESS
* Success. Keypair generated and stored in buffer.
* \retval #PSA_ERROR_NOT_SUPPORTED
* The input is not supported by this driver (not SECP256R1).
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The input is invalid.
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* \p key_buffer_size is too small.
*/
psa_status_t p256_transparent_export_public_key(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
uint8_t *data,
size_t data_size,
size_t *data_length);
/** Generate SECP256R1 ECC Key Pair.
* Interface function which calls the p256-m key generation function and
* places it in the key buffer provided by the caller (Mbed TLS) in the
* correct format. For a SECP256R1 curve this is the 32 bit private key.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[out] key_buffer The buffer to contain the key data in
* output format upon successful return.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[out] key_buffer_length The length of the data written in \p
* key_buffer in bytes.
*
* \retval #PSA_SUCCESS
* Success. Keypair generated and stored in buffer.
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* \p key_buffer_size is too small.
* \retval #PSA_ERROR_GENERIC_ERROR
* The internal RNG failed.
*/
psa_status_t p256_transparent_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length);
/** Perform raw key agreement using p256-m's ECDH implementation
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] key_buffer The buffer containing the private key
* in the format specified by PSA.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg A key agreement algorithm that is
* compatible with the type of the key.
* \param[in] peer_key The buffer containing the peer's public
* key in format specified by PSA.
* \param[in] peer_key_length Size of the \p peer_key buffer in
* bytes.
* \param[out] shared_secret The buffer to which the shared secret
* is to be written.
* \param[in] shared_secret_size Size of the \p shared_secret buffer in
* bytes.
* \param[out] shared_secret_length On success, the number of bytes that
* make up the returned shared secret.
* \retval #PSA_SUCCESS
* Success. Shared secret successfully calculated.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The input is invalid.
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* \p shared_secret_size is too small.
*/
psa_status_t p256_transparent_key_agreement(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length);
/** Sign an already-calculated hash with a private key using p256-m's ECDSA
* implementation
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] key_buffer The buffer containing the private key
* in the format specified by PSA.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg A signature algorithm that is compatible
* with the type of the key.
* \param[in] hash The hash to sign.
* \param[in] hash_length Size of the \p hash buffer in bytes.
* \param[out] signature Buffer where signature is to be written.
* \param[in] signature_size Size of the \p signature buffer in bytes.
* \param[out] signature_length On success, the number of bytes
* that make up the returned signature value.
*
* \retval #PSA_SUCCESS
* Success. Hash was signed successfully.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The input is invalid.
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* \p signature_size is too small.
* \retval #PSA_ERROR_GENERIC_ERROR
* The internal RNG failed.
*/
psa_status_t p256_transparent_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length);
/** Verify the signature of a hash using a SECP256R1 public key using p256-m's
* ECDSA implementation.
*
* \note p256-m expects a 64 byte public key, but the contents of the key
buffer may be the 32 byte keypair representation or the 65 byte
public key representation. As a result, this function calls
psa_driver_wrapper_export_public_key() to ensure the public key
can be passed to p256-m.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
*
* \param[in] key_buffer The buffer containing the key
* in the format specified by PSA.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg A signature algorithm that is compatible with
* the type of the key.
* \param[in] hash The hash whose signature is to be
* verified.
* \param[in] hash_length Size of the \p hash buffer in bytes.
* \param[in] signature Buffer containing the signature to verify.
* \param[in] signature_length Size of the \p signature buffer in bytes.
*
* \retval #PSA_SUCCESS
* The signature is valid.
* \retval #PSA_ERROR_INVALID_SIGNATURE
* The calculation was performed successfully, but the passed
* signature is not a valid signature.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The input is invalid.
*/
psa_status_t p256_transparent_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length);
#endif /* P256M_DRIVER_ENTRYPOINTS_H */

115
lib/mbedtls/external/mbedtls/BRANCHES.md vendored Normal file
View File

@ -0,0 +1,115 @@
# Maintained branches
At any point in time, we have a number of maintained branches, currently consisting of:
- The [`main`](https://github.com/Mbed-TLS/mbedtls/tree/main) branch:
this always contains the latest release, including all publicly available
security fixes.
- The [`development`](https://github.com/Mbed-TLS/mbedtls/tree/development) branch:
this is where the next major version of Mbed TLS (version 4.0) is being
prepared. It has API changes that make it incompatible with Mbed TLS 3.x,
as well as all the new features and bug fixes and security fixes.
- One or more long-time support (LTS) branches: these only get bug fixes and
security fixes. Currently, the supported LTS branches are:
- [`mbedtls-2.28`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-2.28).
- [`mbedtls-3.6`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-3.6).
We retain a number of historical branches, whose names are prefixed by `archive/`,
such as [`archive/mbedtls-2.7`](https://github.com/Mbed-TLS/mbedtls/tree/archive/mbedtls-2.7).
These branches will not receive any changes or updates.
We use [Semantic Versioning](https://semver.org/). In particular, we maintain
API compatibility in the `main` branch across minor version changes (e.g.
the API of 3.(x+1) is backward compatible with 3.x). We only break API
compatibility on major version changes (e.g. from 3.x to 4.0). We also maintain
ABI compatibility within LTS branches; see the next section for details.
We will make regular LTS releases on an 18-month cycle, each of which will have
a 3 year support lifetime. On this basis, 3.6 LTS (released March 2024) will be
supported until March 2027. The next LTS release will be a 4.x release, which is
planned for September 2025.
## Backwards Compatibility for application code
We maintain API compatibility in released versions of Mbed TLS. If you have
code that's working and secure with Mbed TLS x.y.z and does not rely on
undocumented features, then you should be able to re-compile it without
modification with any later release x.y'.z' with the same major version
number, and your code will still build, be secure, and work.
Note that this guarantee only applies if you either use the default
compile-time configuration (`mbedtls/mbedtls_config.h`) or the same modified
compile-time configuration. Changing compile-time configuration options can
result in an incompatible API or ABI, although features will generally not
affect unrelated features (for example, enabling or disabling a
cryptographic algorithm does not break code that does not use that
algorithm).
Note that new releases of Mbed TLS may extend the API. Here are some
examples of changes that are common in minor releases of Mbed TLS, and are
not considered API compatibility breaks:
* Adding or reordering fields in a structure or union.
* Removing a field from a structure, unless the field is documented as public.
* Adding items to an enum.
* Returning an error code that was not previously documented for a function
when a new error condition arises.
* Changing which error code is returned in a case where multiple error
conditions apply.
* Changing the behavior of a function from failing to succeeding, when the
change is a reasonable extension of the current behavior, i.e. the
addition of a new feature.
There are rare exceptions where we break API compatibility: code that was
relying on something that became insecure in the meantime (for example,
crypto that was found to be weak) may need to be changed. In case security
comes in conflict with backwards compatibility, we will put security first,
but always attempt to provide a compatibility option.
## Backward compatibility for the key store
We maintain backward compatibility with previous versions of the
PSA Crypto persistent storage since Mbed TLS 2.25.0, provided that the
storage backend (PSA ITS implementation) is configured in a compatible way.
We intend to maintain this backward compatibility throughout a major version
of Mbed TLS (for example, all Mbed TLS 3.y versions will be able to read
keys written under any Mbed TLS 3.x with x <= y).
Mbed TLS 3.x can also read keys written by Mbed TLS 2.25.0 through 2.28.x
LTS, but future major version upgrades (for example from 2.28.x/3.x to 4.y)
may require the use of an upgrade tool.
Note that this guarantee does not currently fully extend to drivers, which
are an experimental feature. We intend to maintain compatibility with the
basic use of drivers from Mbed TLS 2.28.0 onwards, even if driver APIs
change. However, for more experimental parts of the driver interface, such
as the use of driver state, we do not yet guarantee backward compatibility.
## Long-time support branches
For the LTS branches, additionally we try very hard to also maintain ABI
compatibility (same definition as API except with re-linking instead of
re-compiling) and to avoid any increase in code size or RAM usage, or in the
minimum version of tools needed to build the code. The only exception, as
before, is in case those goals would conflict with fixing a security issue, we
will put security first but provide a compatibility option. (So far we never
had to break ABI compatibility in an LTS branch, but we occasionally had to
increase code size for a security fix.)
For contributors, see the [Backwards Compatibility section of
CONTRIBUTING](CONTRIBUTING.md#backwards-compatibility).
## Current Branches
The following branches are currently maintained:
- [main](https://github.com/Mbed-TLS/mbedtls/tree/main)
- [`development`](https://github.com/Mbed-TLS/mbedtls/)
- [`mbedtls-3.6`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-3.6)
maintained until March 2027, see
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v3.6.0>.
- [`mbedtls-2.28`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-2.28)
maintained until the end of 2024, see
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v2.28.8>.
Users are urged to always use the latest version of a maintained branch.

20
lib/mbedtls/external/mbedtls/BUGS.md vendored Normal file
View File

@ -0,0 +1,20 @@
## Known issues
Known issues in Mbed TLS are [tracked on GitHub](https://github.com/Mbed-TLS/mbedtls/issues).
## Reporting a bug
If you think you've found a bug in Mbed TLS, please follow these steps:
1. Make sure you're using the latest version of a
[maintained branch](BRANCHES.md): `main`, `development`,
or a long-time support branch.
2. Check [GitHub](https://github.com/Mbed-TLS/mbedtls/issues) to see if
your issue has already been reported. If not, …
3. If the issue is a security risk (for example: buffer overflow,
data leak), please report it confidentially as described in
[`SECURITY.md`](SECURITY.md). If not, …
4. Please [create an issue on on GitHub](https://github.com/Mbed-TLS/mbedtls/issues).
Please do not use GitHub for support questions. If you want to know
how to do something with Mbed TLS, please see [`SUPPORT.md`](SUPPORT.md) for available documentation and support channels.

View File

@ -0,0 +1,429 @@
#
# CMake build system design considerations:
#
# - Include directories:
# + Do not define include directories globally using the include_directories
# command but rather at the target level using the
# target_include_directories command. That way, it is easier to guarantee
# that targets are built using the proper list of include directories.
# + Use the PUBLIC and PRIVATE keywords to specify the scope of include
# directories. That way, a target linking to a library (using the
# target_link_libraries command) inherits from the library PUBLIC include
# directories and not from the PRIVATE ones.
# - MBEDTLS_TARGET_PREFIX: CMake targets are designed to be alterable by calling
# CMake in order to avoid target name clashes, via the use of
# MBEDTLS_TARGET_PREFIX. The value of this variable is prefixed to the
# mbedtls, mbedx509, mbedcrypto and apidoc targets.
#
# We specify a minimum requirement of 3.10.2, but for now use 3.5.1 here
# until our infrastructure catches up.
cmake_minimum_required(VERSION 3.5.1)
include(CMakePackageConfigHelpers)
# https://cmake.org/cmake/help/latest/policy/CMP0011.html
# Setting this policy is required in CMake >= 3.18.0, otherwise a warning is generated. The OLD
# policy setting is deprecated, and will be removed in future versions.
cmake_policy(SET CMP0011 NEW)
# https://cmake.org/cmake/help/latest/policy/CMP0012.html
# Setting the CMP0012 policy to NEW is required for FindPython3 to work with CMake 3.18.2
# (there is a bug in this particular version), otherwise, setting the CMP0012 policy is required
# for CMake versions >= 3.18.3 otherwise a deprecated warning is generated. The OLD policy setting
# is deprecated and will be removed in future versions.
cmake_policy(SET CMP0012 NEW)
if(TEST_CPP)
project("Mbed TLS"
LANGUAGES C CXX
VERSION 3.6.0
)
else()
project("Mbed TLS"
LANGUAGES C
VERSION 3.6.0
)
endif()
include(GNUInstallDirs)
# Determine if Mbed TLS is being built as a subproject using add_subdirectory()
if(NOT DEFINED MBEDTLS_AS_SUBPROJECT)
set(MBEDTLS_AS_SUBPROJECT ON)
if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(MBEDTLS_AS_SUBPROJECT OFF)
endif()
endif()
# Set the project root directory.
set(MBEDTLS_DIR ${CMAKE_CURRENT_SOURCE_DIR})
option(ENABLE_PROGRAMS "Build Mbed TLS programs." ON)
option(UNSAFE_BUILD "Allow unsafe builds. These builds ARE NOT SECURE." OFF)
option(MBEDTLS_FATAL_WARNINGS "Compiler warnings treated as errors" ON)
if(CMAKE_HOST_WIN32)
# N.B. The comment on the next line is significant! If you change it,
# edit the sed command in prepare_release.sh that modifies
# CMakeLists.txt.
option(GEN_FILES "Generate the auto-generated files as needed" OFF) # off in development
else()
option(GEN_FILES "Generate the auto-generated files as needed" OFF)
endif()
option(DISABLE_PACKAGE_CONFIG_AND_INSTALL "Disable package configuration, target export and installation" ${MBEDTLS_AS_SUBPROJECT})
string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${CMAKE_C_COMPILER_ID}")
string(REGEX MATCH "GNU" CMAKE_COMPILER_IS_GNU "${CMAKE_C_COMPILER_ID}")
string(REGEX MATCH "IAR" CMAKE_COMPILER_IS_IAR "${CMAKE_C_COMPILER_ID}")
string(REGEX MATCH "MSVC" CMAKE_COMPILER_IS_MSVC "${CMAKE_C_COMPILER_ID}")
# the test suites currently have compile errors with MSVC
if(CMAKE_COMPILER_IS_MSVC)
option(ENABLE_TESTING "Build Mbed TLS tests." OFF)
else()
option(ENABLE_TESTING "Build Mbed TLS tests." ON)
endif()
# Warning string - created as a list for compatibility with CMake 2.8
set(CTR_DRBG_128_BIT_KEY_WARN_L1 "**** WARNING! MBEDTLS_CTR_DRBG_USE_128_BIT_KEY defined!\n")
set(CTR_DRBG_128_BIT_KEY_WARN_L2 "**** Using 128-bit keys for CTR_DRBG limits the security of generated\n")
set(CTR_DRBG_128_BIT_KEY_WARN_L3 "**** keys and operations that use random values generated to 128-bit security\n")
set(CTR_DRBG_128_BIT_KEY_WARNING "${WARNING_BORDER}"
"${CTR_DRBG_128_BIT_KEY_WARN_L1}"
"${CTR_DRBG_128_BIT_KEY_WARN_L2}"
"${CTR_DRBG_128_BIT_KEY_WARN_L3}"
"${WARNING_BORDER}")
# Python 3 is only needed here to check for configuration warnings.
if(NOT CMAKE_VERSION VERSION_LESS 3.15.0)
set(Python3_FIND_STRATEGY LOCATION)
find_package(Python3 COMPONENTS Interpreter)
if(Python3_Interpreter_FOUND)
set(MBEDTLS_PYTHON_EXECUTABLE ${Python3_EXECUTABLE})
endif()
else()
find_package(PythonInterp 3)
if(PYTHONINTERP_FOUND)
set(MBEDTLS_PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE})
endif()
endif()
if(MBEDTLS_PYTHON_EXECUTABLE)
# If 128-bit keys are configured for CTR_DRBG, display an appropriate warning
execute_process(COMMAND ${MBEDTLS_PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/config.py -f ${CMAKE_CURRENT_SOURCE_DIR}/include/mbedtls/mbedtls_config.h get MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
RESULT_VARIABLE result)
if(${result} EQUAL 0)
message(WARNING ${CTR_DRBG_128_BIT_KEY_WARNING})
endif()
endif()
# We now potentially need to link all executables against PThreads, if available
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads)
# If this is the root project add longer list of available CMAKE_BUILD_TYPE values
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}
CACHE STRING "Choose the type of build: None Debug Release Coverage ASan ASanDbg MemSan MemSanDbg Check CheckFull TSan TSanDbg"
FORCE)
endif()
# Make MBEDTLS_CONFIG_FILE and MBEDTLS_USER_CONFIG_FILE into PATHs
set(MBEDTLS_CONFIG_FILE "" CACHE FILEPATH "Mbed TLS config file (overrides default).")
set(MBEDTLS_USER_CONFIG_FILE "" CACHE FILEPATH "Mbed TLS user config file (appended to default).")
# Create a symbolic link from ${base_name} in the binary directory
# to the corresponding path in the source directory.
# Note: Copies the file(s) on Windows.
function(link_to_source base_name)
set(link "${CMAKE_CURRENT_BINARY_DIR}/${base_name}")
set(target "${CMAKE_CURRENT_SOURCE_DIR}/${base_name}")
# Linking to non-existent file is not desirable. At best you will have a
# dangling link, but when building in tree, this can create a symbolic link
# to itself.
if (EXISTS ${target} AND NOT EXISTS ${link})
if (CMAKE_HOST_UNIX)
execute_process(COMMAND ln -s ${target} ${link}
RESULT_VARIABLE result
ERROR_VARIABLE output)
if (NOT ${result} EQUAL 0)
message(FATAL_ERROR "Could not create symbolic link for: ${target} --> ${output}")
endif()
else()
if (IS_DIRECTORY ${target})
file(GLOB_RECURSE files FOLLOW_SYMLINKS LIST_DIRECTORIES false RELATIVE ${target} "${target}/*")
foreach(file IN LISTS files)
configure_file("${target}/${file}" "${link}/${file}" COPYONLY)
endforeach(file)
else()
configure_file(${target} ${link} COPYONLY)
endif()
endif()
endif()
endfunction(link_to_source)
# Get the filename without the final extension (i.e. convert "a.b.c" to "a.b")
function(get_name_without_last_ext dest_var full_name)
# Split into a list on '.' (but a cmake list is just a ';'-separated string)
string(REPLACE "." ";" ext_parts "${full_name}")
# Remove the last item if there are more than one
list(LENGTH ext_parts ext_parts_len)
if (${ext_parts_len} GREATER "1")
math(EXPR ext_parts_last_item "${ext_parts_len} - 1")
list(REMOVE_AT ext_parts ${ext_parts_last_item})
endif()
# Convert back to a string by replacing separators with '.'
string(REPLACE ";" "." no_ext_name "${ext_parts}")
# Copy into the desired variable
set(${dest_var} ${no_ext_name} PARENT_SCOPE)
endfunction(get_name_without_last_ext)
string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${CMAKE_C_COMPILER_ID}")
include(CheckCCompilerFlag)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_C_STANDARD 99)
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
OUTPUT_VARIABLE GCC_VERSION)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Wwrite-strings")
if (GCC_VERSION VERSION_GREATER 3.0 OR GCC_VERSION VERSION_EQUAL 3.0)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat=2 -Wno-format-nonliteral")
endif()
if (GCC_VERSION VERSION_GREATER 4.3 OR GCC_VERSION VERSION_EQUAL 4.3)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wvla")
endif()
if (GCC_VERSION VERSION_GREATER 4.5 OR GCC_VERSION VERSION_EQUAL 4.5)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wlogical-op")
endif()
if (GCC_VERSION VERSION_GREATER 4.8 OR GCC_VERSION VERSION_EQUAL 4.8)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wshadow")
endif()
if (GCC_VERSION VERSION_GREATER 5.0)
CHECK_C_COMPILER_FLAG("-Wformat-signedness" C_COMPILER_SUPPORTS_WFORMAT_SIGNEDNESS)
if(C_COMPILER_SUPPORTS_WFORMAT_SIGNEDNESS)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-signedness")
endif()
endif()
if (GCC_VERSION VERSION_GREATER 7.0 OR GCC_VERSION VERSION_EQUAL 7.0)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat-overflow=2 -Wformat-truncation")
endif()
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 "-fsanitize=address -fno-common -fsanitize=undefined -fno-sanitize-recover=all -O3")
set(CMAKE_C_FLAGS_ASANDBG "-fsanitize=address -fno-common -fsanitize=undefined -fno-sanitize-recover=all -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls")
set(CMAKE_C_FLAGS_TSAN "-fsanitize=thread -O3")
set(CMAKE_C_FLAGS_TSANDBG "-fsanitize=thread -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls")
set(CMAKE_C_FLAGS_CHECK "-Os")
set(CMAKE_C_FLAGS_CHECKFULL "${CMAKE_C_FLAGS_CHECK} -Wcast-qual")
endif(CMAKE_COMPILER_IS_GNU)
if(CMAKE_COMPILER_IS_CLANG)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Wwrite-strings -Wpointer-arith -Wimplicit-fallthrough -Wshadow -Wvla -Wformat=2 -Wno-format-nonliteral")
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 "-fsanitize=address -fno-common -fsanitize=undefined -fno-sanitize-recover=all -O3")
set(CMAKE_C_FLAGS_ASANDBG "-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 "-fsanitize=memory -O3")
set(CMAKE_C_FLAGS_MEMSANDBG "-fsanitize=memory -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls -fsanitize-memory-track-origins=2")
set(CMAKE_C_FLAGS_TSAN "-fsanitize=thread -O3")
set(CMAKE_C_FLAGS_TSANDBG "-fsanitize=thread -O1 -g3 -fno-omit-frame-pointer -fno-optimize-sibling-calls")
set(CMAKE_C_FLAGS_CHECK "-Os")
endif(CMAKE_COMPILER_IS_CLANG)
if(CMAKE_COMPILER_IS_IAR)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --warn_about_c_style_casts")
set(CMAKE_C_FLAGS_RELEASE "-Ohz")
set(CMAKE_C_FLAGS_DEBUG "--debug -On")
endif(CMAKE_COMPILER_IS_IAR)
if(CMAKE_COMPILER_IS_MSVC)
# Strictest warnings, UTF-8 source and execution charset
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W3 /utf-8")
endif(CMAKE_COMPILER_IS_MSVC)
if(MBEDTLS_FATAL_WARNINGS)
if(CMAKE_COMPILER_IS_MSVC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX")
endif(CMAKE_COMPILER_IS_MSVC)
if(CMAKE_COMPILER_IS_CLANG OR CMAKE_COMPILER_IS_GNU)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
if(UNSAFE_BUILD)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error=cpp")
set(CMAKE_C_FLAGS_ASAN "${CMAKE_C_FLAGS_ASAN} -Wno-error=cpp")
set(CMAKE_C_FLAGS_ASANDBG "${CMAKE_C_FLAGS_ASANDBG} -Wno-error=cpp")
endif(UNSAFE_BUILD)
endif(CMAKE_COMPILER_IS_CLANG OR CMAKE_COMPILER_IS_GNU)
if (CMAKE_COMPILER_IS_IAR)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --warnings_are_errors")
endif(CMAKE_COMPILER_IS_IAR)
endif(MBEDTLS_FATAL_WARNINGS)
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)
set(CMAKE_INSTALL_LIBDIR "${LIB_INSTALL_DIR}")
endif()
if (NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/framework/CMakeLists.txt")
message(FATAL_ERROR "${CMAKE_CURRENT_SOURCE_DIR}/framework/CMakeLists.txt not found. Run `git submodule update --init` from the source tree to fetch the submodule contents.")
endif()
add_subdirectory(framework)
add_subdirectory(include)
add_subdirectory(3rdparty)
add_subdirectory(library)
add_subdirectory(pkgconfig)
#
# The C files in tests/src directory contain test code shared among test suites
# and programs. This shared test code is compiled and linked to test suites and
# programs objects as a set of compiled objects. The compiled objects are NOT
# built into a library that the test suite and program objects would link
# against as they link against the mbedcrypto, mbedx509 and mbedtls libraries.
# The reason is that such library is expected to have mutual dependencies with
# the aforementioned libraries and that there is as of today no portable way of
# handling such dependencies (only toolchain specific solutions).
#
# Thus the below definition of the `mbedtls_test` CMake library of objects
# target. This library of objects is used by tests and programs CMake files
# to define the test executables.
#
if(ENABLE_TESTING OR ENABLE_PROGRAMS)
file(GLOB MBEDTLS_TEST_FILES
${CMAKE_CURRENT_SOURCE_DIR}/tests/src/*.c
${CMAKE_CURRENT_SOURCE_DIR}/tests/src/drivers/*.c)
add_library(mbedtls_test OBJECT ${MBEDTLS_TEST_FILES})
target_include_directories(mbedtls_test
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests/include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/library)
# Request C11, needed for memory poisoning tests
set_target_properties(mbedtls_test PROPERTIES C_STANDARD 11)
file(GLOB MBEDTLS_TEST_HELPER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/tests/src/test_helpers/*.c)
add_library(mbedtls_test_helpers OBJECT ${MBEDTLS_TEST_HELPER_FILES})
target_include_directories(mbedtls_test_helpers
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests/include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/library
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/everest/include)
# Pass-through MBEDTLS_CONFIG_FILE and MBEDTLS_USER_CONFIG_FILE
if(MBEDTLS_CONFIG_FILE)
target_compile_definitions(mbedtls_test
PUBLIC MBEDTLS_CONFIG_FILE="${MBEDTLS_CONFIG_FILE}")
target_compile_definitions(mbedtls_test_helpers
PUBLIC MBEDTLS_CONFIG_FILE="${MBEDTLS_CONFIG_FILE}")
endif()
if(MBEDTLS_USER_CONFIG_FILE)
target_compile_definitions(mbedtls_test
PUBLIC MBEDTLS_USER_CONFIG_FILE="${MBEDTLS_USER_CONFIG_FILE}")
target_compile_definitions(mbedtls_test_helpers
PUBLIC MBEDTLS_USER_CONFIG_FILE="${MBEDTLS_USER_CONFIG_FILE}")
endif()
endif()
if(ENABLE_PROGRAMS)
add_subdirectory(programs)
endif()
ADD_CUSTOM_TARGET(${MBEDTLS_TARGET_PREFIX}apidoc
COMMAND doxygen mbedtls.doxyfile
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doxygen)
if(ENABLE_TESTING)
enable_testing()
add_subdirectory(tests)
# additional convenience targets for Unix only
if(UNIX)
# For coverage testing:
# 1. Build with:
# cmake -D CMAKE_BUILD_TYPE=Coverage /path/to/source && make
# 2. Run the relevant tests for the part of the code you're interested in.
# For the reference coverage measurement, see
# tests/scripts/basic-build-test.sh
# 3. Run scripts/lcov.sh to generate an HTML report.
ADD_CUSTOM_TARGET(lcov
COMMAND scripts/lcov.sh
)
ADD_CUSTOM_TARGET(memcheck
COMMAND sed -i.bak s+/usr/bin/valgrind+`which valgrind`+ DartConfiguration.tcl
COMMAND ctest -O memcheck.log -D ExperimentalMemCheck
COMMAND tail -n1 memcheck.log | grep 'Memory checking results:' > /dev/null
COMMAND rm -f memcheck.log
COMMAND mv DartConfiguration.tcl.bak DartConfiguration.tcl
)
endif(UNIX)
# Make scripts needed for testing available in an out-of-source build.
if (NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
link_to_source(scripts)
# Copy (don't link) DartConfiguration.tcl, needed for memcheck, to
# keep things simple with the sed commands in the memcheck target.
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/DartConfiguration.tcl
${CMAKE_CURRENT_BINARY_DIR}/DartConfiguration.tcl COPYONLY)
endif()
endif()
if(NOT DISABLE_PACKAGE_CONFIG_AND_INSTALL)
configure_package_config_file(
"cmake/MbedTLSConfig.cmake.in"
"cmake/MbedTLSConfig.cmake"
INSTALL_DESTINATION "cmake")
write_basic_package_version_file(
"cmake/MbedTLSConfigVersion.cmake"
COMPATIBILITY SameMajorVersion
VERSION 3.6.0)
install(
FILES "${CMAKE_CURRENT_BINARY_DIR}/cmake/MbedTLSConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/cmake/MbedTLSConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/MbedTLS")
export(
EXPORT MbedTLSTargets
NAMESPACE MbedTLS::
FILE "cmake/MbedTLSTargets.cmake")
install(
EXPORT MbedTLSTargets
NAMESPACE MbedTLS::
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/MbedTLS"
FILE "MbedTLSTargets.cmake")
if(CMAKE_VERSION VERSION_GREATER 3.15 OR CMAKE_VERSION VERSION_EQUAL 3.15)
# Do not export the package by default
cmake_policy(SET CMP0090 NEW)
# Make this package visible to the system
export(PACKAGE MbedTLS)
endif()
endif()

View File

@ -0,0 +1,97 @@
Contributing
============
We gratefully accept bug reports and contributions from the community. All PRs are reviewed by the project team / community, and may need some modifications to
be accepted.
Quick Checklist for PR contributors
-----------------------------------
More details on all of these points may be found in the sections below.
- [Sign-off](#license-and-copyright): all commits must be signed off.
- [Tests](#tests): please ensure the PR includes adequate tests.
- [Changelog](#documentation): if needed, please provide a changelog entry.
- [Backports](#long-term-support-branches): provide a backport if needed (it's fine to wait until the main PR is accepted).
Coding Standards
----------------
- Contributions should include tests, as mentioned in the [Tests](#tests) and [Continuous Integration](#continuous-integration-tests) sections. Please check that your contribution passes basic tests before submission, and check the CI results after making a pull request.
- The code should be written in a clean and readable style, and must follow [our coding standards](https://mbed-tls.readthedocs.io/en/latest/kb/development/mbedtls-coding-standards/).
- The code should be written in a portable generic way, that will benefit the whole community, and not only your own needs.
- The code should be secure, and will be reviewed from a security point of view as well.
Making a Contribution
---------------------
1. [Check for open issues](https://github.com/Mbed-TLS/mbedtls/issues) or [start a discussion](https://lists.trustedfirmware.org/mailman3/lists/mbed-tls.lists.trustedfirmware.org) around a feature idea or a bug.
1. Fork the [Mbed TLS repository on GitHub](https://github.com/Mbed-TLS/mbedtls) to start making your changes. As a general rule, you should use the ["development" branch](https://github.com/Mbed-TLS/mbedtls/tree/development) as a basis.
1. Write a test which shows that the bug was fixed or that the feature works as expected.
1. Send a pull request (PR) and work with us until it gets merged and published. Contributions may need some modifications, so a few rounds of review and fixing may be necessary. See our [review process guidelines](https://mbed-tls.readthedocs.io/en/latest/reviews/review-for-contributors/).
1. For quick merging, the contribution should be short, and concentrated on a single feature or topic. The larger the contribution is, the longer it would take to review it and merge it.
Backwards Compatibility
-----------------------
The project aims to minimise the impact on users upgrading to newer versions of the library and it should not be necessary for a user to make any changes to their own code to work with a newer version of the library. Unless the user has made an active decision to use newer features, a newer generation of the library or a change has been necessary due to a security issue or other significant software defect, no modifications to their own code should be necessary. To achieve this, API compatibility is maintained between different versions of Mbed TLS on the main development branch and in LTS (Long Term Support) branches, as described in [BRANCHES.md](BRANCHES.md).
To minimise such disruption to users, where a change to the interface is required, all changes to the ABI or API, even on the main development branch where new features are added, need to be justifiable by either being a significant enhancement, new feature or bug fix which is best resolved by an interface change. If there is an API change, the contribution, if accepted, will be merged only when there is a major release.
No changes are permitted to the definition of functions in the public interface which will change the API. Instead the interface can only be changed by its extension. Where changes to an existing interface are necessary, functions in the public interface which need to be changed are marked as 'deprecated'. If there is a strong reason to replace an existing function with one that has a slightly different interface (different prototype, or different documented behavior), create a new function with a new name with the desired interface. Keep the old function, but mark it as deprecated.
Periodically, the library will remove deprecated functions from the library which will be a breaking change in the API, but such changes will be made only in a planned, structured way that gives sufficient notice to users of the library.
Long Term Support Branches
--------------------------
Mbed TLS maintains several LTS (Long Term Support) branches, which are maintained continuously for a given period. The LTS branches are provided to allow users of the library to have a maintained, stable version of the library which contains only security fixes and fixes for other defects, without encountering additional features or API extensions which may introduce issues or change the code size or RAM usage, which can be significant considerations on some platforms. To allow users to take advantage of the LTS branches, these branches maintain backwards compatibility for both the public API and ABI.
When backporting to these branches please observe the following rules:
1. Any change to the library which changes the API or ABI cannot be backported.
1. All bug fixes that correct a defect that is also present in an LTS branch must be backported to that LTS branch. If a bug fix introduces a change to the API such as a new function, the fix should be reworked to avoid the API change. API changes without very strong justification are unlikely to be accepted.
1. If a contribution is a new feature or enhancement, no backporting is required. Exceptions to this may be additional test cases or quality improvements such as changes to build or test scripts.
It would be highly appreciated if contributions are backported to LTS branches in addition to the [development branch](https://github.com/Mbed-TLS/mbedtls/tree/development) by contributors.
The list of maintained branches can be found in the [Current Branches section
of BRANCHES.md](BRANCHES.md#current-branches).
Tests
-----
As mentioned, tests that show the correctness of the feature or bug fix should be added to the pull request, if no such tests exist.
Mbed TLS includes a comprehensive set of test suites in the `tests/` directory that are dynamically generated to produce the actual test source files (e.g. `test_suite_rsa.c`). These files are generated from a `function file` (e.g. `suites/test_suite_rsa.function`) and a `data file` (e.g. `suites/test_suite_rsa.data`). The function file contains the test functions. The data file contains the test cases, specified as parameters that will be passed to the test function.
[A Knowledge Base article describing how to add additional tests is available on the Mbed TLS website](https://mbed-tls.readthedocs.io/en/latest/kb/development/test_suites/).
A test script `tests/scripts/basic-build-test.sh` is available to show test coverage of the library. New code contributions should provide a similar level of code coverage to that which already exists for the library.
Sample applications, if needed, should be modified as well.
Continuous Integration Tests
----------------------------
Once a PR has been made, the Continuous Integration (CI) tests are triggered and run. You should follow the result of the CI tests, and fix failures.
It is advised to enable the [githooks scripts](https://github.com/Mbed-TLS/mbedtls/tree/development/tests/git-scripts) prior to pushing your changes, for catching some of the issues as early as possible.
Documentation
-------------
Mbed TLS is well documented, but if you think documentation is needed, speak out!
1. All interfaces should be documented through Doxygen. New APIs should introduce Doxygen documentation.
1. Complex parts in the code should include comments.
1. If needed, a Readme file is advised.
1. If a [Knowledge Base (KB)](https://mbed-tls.readthedocs.io/en/latest/kb/) article should be added, write this as a comment in the PR description.
1. A [ChangeLog](https://github.com/Mbed-TLS/mbedtls/blob/development/ChangeLog.d/00README.md) entry should be added for this contribution.
License and Copyright
---------------------
Unless specifically indicated otherwise in a file, Mbed TLS files are provided under a dual [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) OR [GPL-2.0-or-later](https://spdx.org/licenses/GPL-2.0-or-later.html) license. See the [LICENSE](LICENSE) file for the full text of these licenses. This means that users may choose which of these licenses they take the code under.
Contributors must accept that their contributions are made under both the Apache-2.0 AND [GPL-2.0-or-later](https://spdx.org/licenses/GPL-2.0-or-later.html) licenses.
All new files should include the standard SPDX license identifier where possible, i.e. "SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later".
The copyright on contributions is retained by the original authors of the code. Where possible for new files, this should be noted in a comment at the top of the file in the form: "Copyright The Mbed TLS Contributors".
When contributing code to us, the committer and all authors are required to make the submission under the terms of the [Developer Certificate of Origin](dco.txt), confirming that the code submitted can (legally) become part of the project, and is submitted under both the Apache-2.0 AND GPL-2.0-or-later licenses.
This is done by including the standard Git `Signed-off-by:` line in every commit message. If more than one person contributed to the commit, they should also add their own `Signed-off-by:` line.

6108
lib/mbedtls/external/mbedtls/ChangeLog vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,91 @@
# Pending changelog entry directory
This directory contains changelog entries that have not yet been merged
to the changelog file ([`../ChangeLog`](../ChangeLog)).
## What requires a changelog entry?
Write a changelog entry if there is a user-visible change. This includes:
* Bug fixes in the library or in sample programs: fixing a security hole,
fixing broken behavior, fixing the build in some configuration or on some
platform, etc.
* New features in the library, new sample programs, or new platform support.
* Changes in existing behavior. These should be rare. Changes in features
that are documented as experimental may or may not be announced, depending
on the extent of the change and how widely we expect the feature to be used.
We generally don't include changelog entries for:
* Documentation improvements.
* Performance improvements, unless they are particularly significant.
* Changes to parts of the code base that users don't interact with directly,
such as test code and test data.
* Fixes for compiler warnings. Releases typically contain a number of fixes
of this kind, so we will only mention them in the Changelog if they are
particularly significant.
Until Mbed TLS 2.24.0, we required changelog entries in more cases.
Looking at older changelog entries is good practice for how to write a
changelog entry, but not for deciding whether to write one.
## Changelog entry file format
A changelog entry file must have the extension `*.txt` and must have the
following format:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Security
* Change description.
* Another change description.
Features
* Yet another change description. This is a long change description that
spans multiple lines.
* Yet again another change description.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The permitted changelog entry categories are as follows:
<!-- Keep this synchronized with STANDARD_CATEGORIES in assemble_changelog.py! -->
API changes
Default behavior changes
Requirement changes
New deprecations
Removals
Features
Security
Bugfix
Changes
Use “Changes” for anything that doesn't fit in the other categories.
## How to write a changelog entry
Each entry starts with three spaces, an asterisk and a space. Continuation
lines start with 5 spaces. Lines wrap at 79 characters.
Write full English sentences with proper capitalization and punctuation. Use
the present tense. Use the imperative where applicable. For example: “Fix a
bug in mbedtls_xxx() ….”
Include GitHub issue numbers where relevant. Use the format “#1234” for an
Mbed TLS issue. Add other external references such as CVE numbers where
applicable.
Credit bug reporters where applicable.
**Explain why, not how**. Remember that the audience is the users of the
library, not its developers. In particular, for a bug fix, explain the
consequences of the bug, not how the bug was fixed. For a new feature, explain
why one might be interested in the feature. For an API change or a deprecation,
explain how to update existing applications.
See [existing entries](../ChangeLog) for examples.
## How `ChangeLog` is updated
Run [`../scripts/assemble_changelog.py`](../scripts/assemble_changelog.py)
from a Git working copy
to move the entries from files in `ChangeLog.d` to the main `ChangeLog` file.

View File

@ -0,0 +1,4 @@
Site: localhost
BuildName: Mbed TLS-test
CoverageCommand: /usr/bin/gcov
MemoryCheckCommand: /usr/bin/valgrind

553
lib/mbedtls/external/mbedtls/LICENSE vendored Normal file
View File

@ -0,0 +1,553 @@
Mbed TLS files are provided under a dual [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html)
OR [GPL-2.0-or-later](https://spdx.org/licenses/GPL-2.0-or-later.html) license.
This means that users may choose which of these licenses they take the code
under.
The full text of each of these licenses is given below.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
===============================================================================
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

217
lib/mbedtls/external/mbedtls/Makefile vendored Normal file
View File

@ -0,0 +1,217 @@
DESTDIR=/usr/local
PREFIX=mbedtls_
PERL ?= perl
ifneq (,$(filter-out lib library/%,$(or $(MAKECMDGOALS),all)))
ifeq (,$(wildcard framework/exported.make))
# Use the define keyword to get a multi-line message.
# GNU make appends ". Stop.", so tweak the ending of our message accordingly.
define error_message
$(MBEDTLS_PATH)/framework/exported.make not found.
Run `git submodule update --init` to fetch the submodule contents.
This is a fatal error
endef
$(error $(error_message))
endif
include framework/exported.make
endif
.SILENT:
.PHONY: all no_test programs lib tests install uninstall clean test check lcov apidoc apidoc_clean
all: programs tests
$(MAKE) post_build
no_test: programs
programs: lib mbedtls_test
$(MAKE) -C programs
lib:
$(MAKE) -C library
tests: lib mbedtls_test
$(MAKE) -C tests
mbedtls_test:
$(MAKE) -C tests mbedtls_test
library/%:
$(MAKE) -C library $*
programs/%:
$(MAKE) -C programs $*
tests/%:
$(MAKE) -C tests $*
.PHONY: generated_files
generated_files: library/generated_files
generated_files: programs/generated_files
generated_files: tests/generated_files
generated_files: visualc_files
# Set GEN_FILES to the empty string to disable dependencies on generated
# source files. Then `make generated_files` will only build files that
# are missing, it will not rebuilt files that are present but out of date.
# This is useful, for example, if you have a source tree where
# `make generated_files` has already run and file timestamps reflect the
# time the files were copied or extracted, and you are now in an environment
# that lacks some of the necessary tools to re-generate the files.
# If $(GEN_FILES) is non-empty, the generated source files' dependencies
# are treated ordinarily, based on file timestamps.
GEN_FILES ?=
# In dependencies where the target is a configuration-independent generated
# file, use `TARGET: $(gen_file_dep) DEPENDENCY1 DEPENDENCY2 ...`
# rather than directly `TARGET: DEPENDENCY1 DEPENDENCY2 ...`. This
# enables the re-generation to be turned off when GEN_FILES is disabled.
ifdef GEN_FILES
gen_file_dep =
else
# Order-only dependency: generate the target if it's absent, but don't
# re-generate it if it's present but older than its dependencies.
gen_file_dep = |
endif
.PHONY: visualc_files
VISUALC_FILES = visualc/VS2017/mbedTLS.sln visualc/VS2017/mbedTLS.vcxproj
# TODO: $(app).vcxproj for each $(app) in programs/
visualc_files: $(VISUALC_FILES)
# Ensure that the .c files that generate_visualc_files.pl enumerates are
# present before it runs. It doesn't matter if the files aren't up-to-date,
# they just need to be present.
$(VISUALC_FILES): | library/generated_files
$(VISUALC_FILES): $(gen_file_dep) scripts/generate_visualc_files.pl
$(VISUALC_FILES): $(gen_file_dep) scripts/data_files/vs2017-app-template.vcxproj
$(VISUALC_FILES): $(gen_file_dep) scripts/data_files/vs2017-main-template.vcxproj
$(VISUALC_FILES): $(gen_file_dep) scripts/data_files/vs2017-sln-template.sln
# TODO: also the list of .c and .h source files, but not their content
$(VISUALC_FILES):
echo " Gen $@ ..."
$(PERL) scripts/generate_visualc_files.pl
ifndef WINDOWS
install: no_test
mkdir -p $(DESTDIR)/include/mbedtls
cp -rp include/mbedtls $(DESTDIR)/include
mkdir -p $(DESTDIR)/include/psa
cp -rp include/psa $(DESTDIR)/include
mkdir -p $(DESTDIR)/lib
cp -RP library/libmbedtls.* $(DESTDIR)/lib
cp -RP library/libmbedx509.* $(DESTDIR)/lib
cp -RP library/libmbedcrypto.* $(DESTDIR)/lib
mkdir -p $(DESTDIR)/bin
for p in programs/*/* ; do \
if [ -x $$p ] && [ ! -d $$p ] ; \
then \
f=$(PREFIX)`basename $$p` ; \
cp $$p $(DESTDIR)/bin/$$f ; \
fi \
done
uninstall:
rm -rf $(DESTDIR)/include/mbedtls
rm -rf $(DESTDIR)/include/psa
rm -f $(DESTDIR)/lib/libmbedtls.*
rm -f $(DESTDIR)/lib/libmbedx509.*
rm -f $(DESTDIR)/lib/libmbedcrypto.*
for p in programs/*/* ; do \
if [ -x $$p ] && [ ! -d $$p ] ; \
then \
f=$(PREFIX)`basename $$p` ; \
rm -f $(DESTDIR)/bin/$$f ; \
fi \
done
endif
WARNING_BORDER_LONG =**********************************************************************************\n
CTR_DRBG_128_BIT_KEY_WARN_L1=**** WARNING! MBEDTLS_CTR_DRBG_USE_128_BIT_KEY defined! ****\n
CTR_DRBG_128_BIT_KEY_WARN_L2=**** Using 128-bit keys for CTR_DRBG limits the security of generated ****\n
CTR_DRBG_128_BIT_KEY_WARN_L3=**** keys and operations that use random values generated to 128-bit security ****\n
CTR_DRBG_128_BIT_KEY_WARNING=\n$(WARNING_BORDER_LONG)$(CTR_DRBG_128_BIT_KEY_WARN_L1)$(CTR_DRBG_128_BIT_KEY_WARN_L2)$(CTR_DRBG_128_BIT_KEY_WARN_L3)$(WARNING_BORDER_LONG)
# Post build steps
post_build:
ifndef WINDOWS
# If 128-bit keys are configured for CTR_DRBG, display an appropriate warning
-scripts/config.py get MBEDTLS_CTR_DRBG_USE_128_BIT_KEY && ([ $$? -eq 0 ]) && \
echo '$(CTR_DRBG_128_BIT_KEY_WARNING)'
endif
clean: clean_more_on_top
$(MAKE) -C library clean
$(MAKE) -C programs clean
$(MAKE) -C tests clean
clean_more_on_top:
ifndef WINDOWS
find . \( -name \*.gcno -o -name \*.gcda -o -name \*.info \) -exec rm {} +
endif
neat: clean_more_on_top
$(MAKE) -C library neat
$(MAKE) -C programs neat
$(MAKE) -C tests neat
ifndef WINDOWS
rm -f visualc/VS2017/*.vcxproj visualc/VS2017/mbedTLS.sln
else
if exist visualc\VS2017\*.vcxproj del /Q /F visualc\VS2017\*.vcxproj
if exist visualc\VS2017\mbedTLS.sln del /Q /F visualc\VS2017\mbedTLS.sln
endif
check: lib tests
$(MAKE) -C tests check
test: check
ifndef WINDOWS
# For coverage testing:
# 1. Build with:
# make CFLAGS='--coverage -g3 -O0' LDFLAGS='--coverage'
# 2. Run the relevant tests for the part of the code you're interested in.
# For the reference coverage measurement, see
# tests/scripts/basic-build-test.sh
# 3. Run scripts/lcov.sh to generate an HTML report.
lcov:
scripts/lcov.sh
apidoc:
mkdir -p apidoc
cd doxygen && doxygen mbedtls.doxyfile
apidoc_clean:
rm -rf apidoc
endif
## Editor navigation files
C_SOURCE_FILES = $(wildcard \
3rdparty/*/include/*/*.h 3rdparty/*/include/*/*/*.h 3rdparty/*/include/*/*/*/*.h \
3rdparty/*/*.c 3rdparty/*/*/*.c 3rdparty/*/*/*/*.c 3rdparty/*/*/*/*/*.c \
include/*/*.h \
library/*.[hc] \
programs/*/*.[hc] \
tests/include/*/*.h tests/include/*/*/*.h \
tests/src/*.c tests/src/*/*.c \
tests/suites/*.function \
)
# Exuberant-ctags invocation. Other ctags implementations may require different options.
CTAGS = ctags --langmap=c:+.h.function --line-directives=no -o
tags: $(C_SOURCE_FILES)
$(CTAGS) $@ $(C_SOURCE_FILES)
TAGS: $(C_SOURCE_FILES)
etags --no-line-directive -o $@ $(C_SOURCE_FILES)
global: GPATH GRTAGS GSYMS GTAGS
GPATH GRTAGS GSYMS GTAGS: $(C_SOURCE_FILES)
ls $(C_SOURCE_FILES) | gtags -f - --gtagsconf .globalrc
cscope: cscope.in.out cscope.po.out cscope.out
cscope.in.out cscope.po.out cscope.out: $(C_SOURCE_FILES)
cscope -bq -u -Iinclude -Ilibrary $(patsubst %,-I%,$(wildcard 3rdparty/*/include)) -Itests/include $(C_SOURCE_FILES)
.PHONY: cscope global

333
lib/mbedtls/external/mbedtls/README.md vendored Normal file
View File

@ -0,0 +1,333 @@
README for Mbed TLS
===================
Mbed TLS is a C library that implements cryptographic primitives, X.509 certificate manipulation and the SSL/TLS and DTLS protocols. Its small code footprint makes it suitable for embedded systems.
Mbed TLS includes a reference implementation of the [PSA Cryptography API](#psa-cryptography-api). This is currently a preview for evaluation purposes only.
Configuration
-------------
Mbed TLS should build out of the box on most systems. Some platform specific options are available in the fully documented configuration file `include/mbedtls/mbedtls_config.h`, which is also the place where features can be selected. This file can be edited manually, or in a more programmatic way using the Python 3 script `scripts/config.py` (use `--help` for usage instructions).
Compiler options can be set using conventional environment variables such as `CC` and `CFLAGS` when using the Make and CMake build system (see below).
We provide some non-standard configurations focused on specific use cases in the `configs/` directory. You can read more about those in `configs/README.txt`
Documentation
-------------
The main Mbed TLS documentation is available via [ReadTheDocs](https://mbed-tls.readthedocs.io/).
Documentation for the PSA Cryptography API is available [on GitHub](https://arm-software.github.io/psa-api/crypto/).
To generate a local copy of the library documentation in HTML format, tailored to your compile-time configuration:
1. Make sure that [Doxygen](http://www.doxygen.nl/) is installed.
1. Run `make apidoc`.
1. Browse `apidoc/index.html` or `apidoc/modules.html`.
For other sources of documentation, see the [SUPPORT](SUPPORT.md) document.
Compiling
---------
There are currently three active build systems used within Mbed TLS releases:
- GNU Make
- CMake
- Microsoft Visual Studio
The main systems used for development are CMake and GNU Make. Those systems are always complete and up-to-date. The others should reflect all changes present in the CMake and Make build system, although features may not be ported there automatically.
The Make and CMake build systems create three libraries: libmbedcrypto, libmbedx509, and libmbedtls. Note that libmbedtls depends on libmbedx509 and libmbedcrypto, and libmbedx509 depends on libmbedcrypto. As a result, some linkers will expect flags to be in a specific order, for example the GNU linker wants `-lmbedtls -lmbedx509 -lmbedcrypto`.
### Tool versions
You need the following tools to build the library with the provided makefiles:
* GNU Make 3.82 or a build tool that CMake supports.
* A C99 toolchain (compiler, linker, archiver). We actively test with GCC 5.4, Clang 3.8, Arm Compiler 6, IAR 8 and Visual Studio 2017. More recent versions should work. Slightly older versions may work.
* Python 3.8 to generate the test code. Python is also needed to integrate PSA drivers and to build the development branch (see next section).
* Perl to run the tests, and to generate some source files in the development branch.
* CMake 3.10.2 or later (if using CMake).
* Microsoft Visual Studio 2017 or later (if using Visual Studio).
* Doxygen 1.8.11 or later (if building the documentation; slightly older versions should work).
### Git usage
The `development` branch and the `mbedtls-3.6` long-term support branch of Mbed TLS use a [Git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules#_cloning_submodules) ([framework](https://github.com/Mbed-TLS/mbedtls-framework)). This is not needed to merely compile the library at a release tag. This is not needed to consume a release archive (zip or tar).
### Generated source files in the development branch
The source code of Mbed TLS includes some files that are automatically generated by scripts and whose content depends only on the Mbed TLS source, not on the platform or on the library configuration. These files are not included in the development branch of Mbed TLS, but the generated files are included in official releases. This section explains how to generate the missing files in the development branch.
The following tools are required:
* Perl, for some library source files and for Visual Studio build files.
* Python 3.8 and some Python packages, for some library source files, sample programs and test data. To install the necessary packages, run:
```
python3 -m pip install --user -r scripts/basic.requirements.txt
```
Depending on your Python installation, you may need to invoke `python` instead of `python3`. To install the packages system-wide, omit the `--user` option.
* A C compiler for the host platform, for some test data.
If you are cross-compiling, you must set the `CC` environment variable to a C compiler for the host platform when generating the configuration-independent files.
Any of the following methods are available to generate the configuration-independent files:
* If not cross-compiling, running `make` with any target, or just `make`, will automatically generate required files.
* On non-Windows systems, when not cross-compiling, CMake will generate the required files automatically.
* Run `make generated_files` to generate all the configuration-independent files.
* On Unix/POSIX systems, run `tests/scripts/check-generated-files.sh -u` to generate all the configuration-independent files.
* On Windows, run `scripts\make_generated_files.bat` to generate all the configuration-independent files.
### Make
We require GNU Make. To build the library and the sample programs, GNU Make and a C compiler are sufficient. Some of the more advanced build targets require some Unix/Linux tools.
We intentionally only use a minimum of functionality in the makefiles in order to keep them as simple and independent of different toolchains as possible, to allow users to more easily move between different platforms. Users who need more features are recommended to use CMake.
In order to build from the source code using GNU Make, just enter at the command line:
make
In order to run the tests, enter:
make check
The tests need Python to be built and Perl to be run. If you don't have one of them installed, you can skip building the tests with:
make no_test
You'll still be able to run a much smaller set of tests with:
programs/test/selftest
In order to build for a Windows platform, you should use `WINDOWS_BUILD=1` if the target is Windows but the build environment is Unix-like (for instance when cross-compiling, or compiling from an MSYS shell), and `WINDOWS=1` if the build environment is a Windows shell (for instance using mingw32-make) (in that case some targets will not be available).
Setting the variable `SHARED` in your environment will build shared libraries in addition to the static libraries. Setting `DEBUG` gives you a debug build. You can override `CFLAGS` and `LDFLAGS` by setting them in your environment or on the make command line; compiler warning options may be overridden separately using `WARNING_CFLAGS`. Some directory-specific options (for example, `-I` directives) are still preserved.
Please note that setting `CFLAGS` overrides its default value of `-O2` and setting `WARNING_CFLAGS` overrides its default value (starting with `-Wall -Wextra`), so if you just want to add some warning options to the default ones, you can do so by setting `CFLAGS=-O2 -Werror` for example. Setting `WARNING_CFLAGS` is useful when you want to get rid of its default content (for example because your compiler doesn't accept `-Wall` as an option). Directory-specific options cannot be overridden from the command line.
Depending on your platform, you might run into some issues. Please check the Makefiles in `library/`, `programs/` and `tests/` for options to manually add or remove for specific platforms. You can also check [the Mbed TLS Knowledge Base](https://mbed-tls.readthedocs.io/en/latest/kb/) for articles on your platform or issue.
In case you find that you need to do something else as well, please let us know what, so we can add it to the [Mbed TLS Knowledge Base](https://mbed-tls.readthedocs.io/en/latest/kb/).
### CMake
In order to build the source using CMake in a separate directory (recommended), just enter at the command line:
mkdir /path/to/build_dir && cd /path/to/build_dir
cmake /path/to/mbedtls_source
cmake --build .
In order to run the tests, enter:
ctest
The test suites need Python to be built and Perl to be executed. If you don't have one of these installed, you'll want to disable the test suites with:
cmake -DENABLE_TESTING=Off /path/to/mbedtls_source
If you disabled the test suites, but kept the programs enabled, you can still run a much smaller set of tests with:
programs/test/selftest
To configure CMake for building shared libraries, use:
cmake -DUSE_SHARED_MBEDTLS_LIBRARY=On /path/to/mbedtls_source
There are many different build modes available within the CMake buildsystem. Most of them are available for gcc and clang, though some are compiler-specific:
- `Release`. This generates the default code without any unnecessary information in the binary files.
- `Debug`. This generates debug information and disables optimization of the code.
- `Coverage`. This generates code coverage information in addition to debug information.
- `ASan`. This instruments the code with AddressSanitizer to check for memory errors. (This includes LeakSanitizer, with recent version of gcc and clang.) (With recent version of clang, this mode also instruments the code with UndefinedSanitizer to check for undefined behaviour.)
- `ASanDbg`. Same as ASan but slower, with debug information and better stack traces.
- `MemSan`. This instruments the code with MemorySanitizer to check for uninitialised memory reads. Experimental, needs recent clang on Linux/x86\_64.
- `MemSanDbg`. Same as MemSan but slower, with debug information, better stack traces and origin tracking.
- `Check`. This activates the compiler warnings that depend on optimization and treats all warnings as errors.
Switching build modes in CMake is simple. For debug mode, enter at the command line:
cmake -D CMAKE_BUILD_TYPE=Debug /path/to/mbedtls_source
To list other available CMake options, use:
cmake -LH
Note that, with CMake, you can't adjust the compiler or its flags after the
initial invocation of cmake. This means that `CC=your_cc make` and `make
CC=your_cc` will *not* work (similarly with `CFLAGS` and other variables).
These variables need to be adjusted when invoking cmake for the first time,
for example:
CC=your_cc cmake /path/to/mbedtls_source
If you already invoked cmake and want to change those settings, you need to
remove the build directory and create it again.
Note that it is possible to build in-place; this will however overwrite the
provided Makefiles (see `scripts/tmp_ignore_makefiles.sh` if you want to
prevent `git status` from showing them as modified). In order to do so, from
the Mbed TLS source directory, use:
cmake .
make
If you want to change `CC` or `CFLAGS` afterwards, you will need to remove the
CMake cache. This can be done with the following command using GNU find:
find . -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} +
You can now make the desired change:
CC=your_cc cmake .
make
Regarding variables, also note that if you set CFLAGS when invoking cmake,
your value of CFLAGS doesn't override the content provided by cmake (depending
on the build mode as seen above), it's merely prepended to it.
#### Consuming Mbed TLS
Mbed TLS provides a package config file for consumption as a dependency in other
CMake projects. You can include Mbed TLS's CMake targets yourself with:
find_package(MbedTLS)
If prompted, set `MbedTLS_DIR` to `${YOUR_MBEDTLS_INSTALL_DIR}/cmake`. This
creates the following targets:
- `MbedTLS::mbedcrypto` (Crypto library)
- `MbedTLS::mbedtls` (TLS library)
- `MbedTLS::mbedx509` (X509 library)
You can then use these directly through `target_link_libraries()`:
add_executable(xyz)
target_link_libraries(xyz
PUBLIC MbedTLS::mbedtls
MbedTLS::mbedcrypto
MbedTLS::mbedx509)
This will link the Mbed TLS libraries to your library or application, and add
its include directories to your target (transitively, in the case of `PUBLIC` or
`INTERFACE` link libraries).
#### Mbed TLS as a subproject
Mbed TLS supports being built as a CMake subproject. One can
use `add_subdirectory()` from a parent CMake project to include Mbed TLS as a
subproject.
### Microsoft Visual Studio
The build files for Microsoft Visual Studio are generated for Visual Studio 2017.
The solution file `mbedTLS.sln` contains all the basic projects needed to build the library and all the programs. The files in tests are not generated and compiled, as these need Python and perl environments as well. However, the selftest program in `programs/test/` is still available.
In the development branch of Mbed TLS, the Visual Studio solution files need to be generated first as described in [“Generated source files in the development branch”](#generated-source-files-in-the-development-branch).
Example programs
----------------
We've included example programs for a lot of different features and uses in [`programs/`](programs/README.md).
Please note that the goal of these sample programs is to demonstrate specific features of the library, and the code may need to be adapted to build a real-world application.
Tests
-----
Mbed TLS includes an elaborate test suite in `tests/` that initially requires Python to generate the tests files (e.g. `test\_suite\_mpi.c`). These files are generated from a `function file` (e.g. `suites/test\_suite\_mpi.function`) and a `data file` (e.g. `suites/test\_suite\_mpi.data`). The `function file` contains the test functions. The `data file` contains the test cases, specified as parameters that will be passed to the test function.
For machines with a Unix shell and OpenSSL (and optionally GnuTLS) installed, additional test scripts are available:
- `tests/ssl-opt.sh` runs integration tests for various TLS options (renegotiation, resumption, etc.) and tests interoperability of these options with other implementations.
- `tests/compat.sh` tests interoperability of every ciphersuite with other implementations.
- `tests/scripts/test-ref-configs.pl` test builds in various reduced configurations.
- `tests/scripts/depends.py` test builds in configurations with a single curve, key exchange, hash, cipher, or pkalg on.
- `tests/scripts/all.sh` runs a combination of the above tests, plus some more, with various build options (such as ASan, full `mbedtls_config.h`, etc).
Instead of manually installing the required versions of all tools required for testing, it is possible to use the Docker images from our CI systems, as explained in [our testing infrastructure repository](https://github.com/Mbed-TLS/mbedtls-test/blob/main/README.md#quick-start).
Porting Mbed TLS
----------------
Mbed TLS can be ported to many different architectures, OS's and platforms. Before starting a port, you may find the following Knowledge Base articles useful:
- [Porting Mbed TLS to a new environment or OS](https://mbed-tls.readthedocs.io/en/latest/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS/)
- [What external dependencies does Mbed TLS rely on?](https://mbed-tls.readthedocs.io/en/latest/kb/development/what-external-dependencies-does-mbedtls-rely-on/)
- [How do I configure Mbed TLS](https://mbed-tls.readthedocs.io/en/latest/kb/compiling-and-building/how-do-i-configure-mbedtls/)
Mbed TLS is mostly written in portable C99; however, it has a few platform requirements that go beyond the standard, but are met by most modern architectures:
- Bytes must be 8 bits.
- All-bits-zero must be a valid representation of a null pointer.
- Signed integers must be represented using two's complement.
- `int` and `size_t` must be at least 32 bits wide.
- The types `uint8_t`, `uint16_t`, `uint32_t` and their signed equivalents must be available.
- Mixed-endian platforms are not supported.
- SIZE_MAX must be at least as big as INT_MAX and UINT_MAX.
PSA cryptography API
--------------------
### PSA API
Arm's [Platform Security Architecture (PSA)](https://developer.arm.com/architectures/security-architectures/platform-security-architecture) is a holistic set of threat models, security analyses, hardware and firmware architecture specifications, and an open source firmware reference implementation. PSA provides a recipe, based on industry best practice, that allows security to be consistently designed in, at both a hardware and firmware level.
The [PSA cryptography API](https://arm-software.github.io/psa-api/crypto/) provides access to a set of cryptographic primitives. It has a dual purpose. First, it can be used in a PSA-compliant platform to build services, such as secure boot, secure storage and secure communication. Second, it can also be used independently of other PSA components on any platform.
The design goals of the PSA cryptography API include:
* The API distinguishes caller memory from internal memory, which allows the library to be implemented in an isolated space for additional security. Library calls can be implemented as direct function calls if isolation is not desired, and as remote procedure calls if isolation is desired.
* The structure of internal data is hidden to the application, which allows substituting alternative implementations at build time or run time, for example, in order to take advantage of hardware accelerators.
* All access to the keys happens through key identifiers, which allows support for external cryptoprocessors that is transparent to applications.
* The interface to algorithms is generic, favoring algorithm agility.
* The interface is designed to be easy to use and hard to accidentally misuse.
Arm welcomes feedback on the design of the API. If you think something could be improved, please open an issue on our Github repository. Alternatively, if you prefer to provide your feedback privately, please email us at [`mbed-crypto@arm.com`](mailto:mbed-crypto@arm.com). All feedback received by email is treated confidentially.
### PSA implementation in Mbed TLS
Mbed TLS includes a reference implementation of the PSA Cryptography API.
However, it does not aim to implement the whole specification; in particular it does not implement all the algorithms.
The X.509 and TLS code can use PSA cryptography for most operations. To enable this support, activate the compilation option `MBEDTLS_USE_PSA_CRYPTO` in `mbedtls_config.h`. Note that TLS 1.3 uses PSA cryptography for most operations regardless of this option. See `docs/use-psa-crypto.md` for details.
### PSA drivers
Mbed TLS supports drivers for cryptographic accelerators, secure elements and random generators. This is work in progress. Please note that the driver interfaces are not fully stable yet and may change without notice. We intend to preserve backward compatibility for application code (using the PSA Crypto API), but the code of the drivers may have to change in future minor releases of Mbed TLS.
Please see the [PSA driver example and guide](docs/psa-driver-example-and-guide.md) for information on writing a driver.
When using drivers, you will generally want to enable two compilation options (see the reference manual for more information):
* `MBEDTLS_USE_PSA_CRYPTO` is necessary so that the X.509 and TLS code calls the PSA drivers rather than the built-in software implementation.
* `MBEDTLS_PSA_CRYPTO_CONFIG` allows you to enable PSA cryptographic mechanisms without including the code of the corresponding software implementation. This is not yet supported for all mechanisms.
License
-------
Unless specifically indicated otherwise in a file, Mbed TLS files are provided under a dual [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) OR [GPL-2.0-or-later](https://spdx.org/licenses/GPL-2.0-or-later.html) license. See the [LICENSE](LICENSE) file for the full text of these licenses, and [the 'License and Copyright' section in the contributing guidelines](CONTRIBUTING.md#License-and-Copyright) for more information.
### Third-party code included in Mbed TLS
This project contains code from other projects. This code is located within the `3rdparty/` directory. The original license text is included within project subdirectories, where it differs from the normal Mbed TLS license, and/or in source files. The projects are listed below:
* `3rdparty/everest/`: Files stem from [Project Everest](https://project-everest.github.io/) and are distributed under the Apache 2.0 license.
* `3rdparty/p256-m/p256-m/`: Files have been taken from the [p256-m](https://github.com/mpg/p256-m) repository. The code in the original repository is distributed under the Apache 2.0 license. It is distributed in Mbed TLS under a dual Apache-2.0 OR GPL-2.0-or-later license with permission from the author.
Contributing
------------
We gratefully accept bug reports and contributions from the community. Please see the [contributing guidelines](CONTRIBUTING.md) for details on how to do this.
Contact
-------
* To report a security vulnerability in Mbed TLS, please email <mbed-tls-security@lists.trustedfirmware.org>. For more information, see [`SECURITY.md`](SECURITY.md).
* To report a bug or request a feature in Mbed TLS, please [file an issue on GitHub](https://github.com/Mbed-TLS/mbedtls/issues/new/choose).
* Please see [`SUPPORT.md`](SUPPORT.md) for other channels for discussion and support about Mbed TLS.

146
lib/mbedtls/external/mbedtls/SECURITY.md vendored Normal file
View File

@ -0,0 +1,146 @@
## Reporting Vulnerabilities
If you think you have found an Mbed TLS security vulnerability, then please
send an email to the security team at
<mbed-tls-security@lists.trustedfirmware.org>.
## Security Incident Handling Process
Our security process is detailed in our
[security
center](https://developer.trustedfirmware.org/w/mbed-tls/security-center/).
Its primary goal is to ensure fixes are ready to be deployed when the issue
goes public.
## Maintained branches
Only the maintained branches, as listed in [`BRANCHES.md`](BRANCHES.md),
get security fixes.
Users are urged to always use the latest version of a maintained branch.
## Threat model
We classify attacks based on the capabilities of the attacker.
### Remote attacks
In this section, we consider an attacker who can observe and modify data sent
over the network. This includes observing the content and timing of individual
packets, as well as suppressing or delaying legitimate messages, and injecting
messages.
Mbed TLS aims to fully protect against remote attacks and to enable the user
application in providing full protection against remote attacks. Said
protection is limited to providing security guarantees offered by the protocol
being implemented. (For example Mbed TLS alone won't guarantee that the
messages will arrive without delay, as the TLS protocol doesn't guarantee that
either.)
**Warning!** Block ciphers do not yet achieve full protection against attackers
who can measure the timing of packets with sufficient precision. For details
and workarounds see the [Block Ciphers](#block-ciphers) section.
### Local attacks
In this section, we consider an attacker who can run software on the same
machine. The attacker has insufficient privileges to directly access Mbed TLS
assets such as memory and files.
#### Timing attacks
The attacker is able to observe the timing of instructions executed by Mbed TLS
by leveraging shared hardware that both Mbed TLS and the attacker have access
to. Typical attack vectors include cache timings, memory bus contention and
branch prediction.
Mbed TLS provides limited protection against timing attacks. The cost of
protecting against timing attacks widely varies depending on the granularity of
the measurements and the noise present. Therefore the protection in Mbed TLS is
limited. We are only aiming to provide protection against **publicly
documented attack techniques**.
As attacks keep improving, so does Mbed TLS's protection. Mbed TLS is moving
towards a model of fully timing-invariant code, but has not reached this point
yet.
**Remark:** Timing information can be observed over the network or through
physical side channels as well. Remote and physical timing attacks are covered
in the [Remote attacks](remote-attacks) and [Physical
attacks](physical-attacks) sections respectively.
**Warning!** Block ciphers do not yet achieve full protection. For
details and workarounds see the [Block Ciphers](#block-ciphers) section.
#### Local non-timing side channels
The attacker code running on the platform has access to some sensor capable of
picking up information on the physical state of the hardware while Mbed TLS is
running. This could for example be an analogue-to-digital converter on the
platform that is located unfortunately enough to pick up the CPU noise.
Mbed TLS doesn't make any security guarantees against local non-timing-based
side channel attacks. If local non-timing attacks are present in a use case or
a user application's threat model, they need to be mitigated by the platform.
#### Local fault injection attacks
Software running on the same hardware can affect the physical state of the
device and introduce faults.
Mbed TLS doesn't make any security guarantees against local fault injection
attacks. If local fault injection attacks are present in a use case or a user
application's threat model, they need to be mitigated by the platform.
### Physical attacks
In this section, we consider an attacker who has access to physical information
about the hardware Mbed TLS is running on and/or can alter the physical state
of the hardware (e.g. power analysis, radio emissions or fault injection).
Mbed TLS doesn't make any security guarantees against physical attacks. If
physical attacks are present in a use case or a user application's threat
model, they need to be mitigated by physical countermeasures.
### Caveats
#### Out-of-scope countermeasures
Mbed TLS has evolved organically and a well defined threat model hasn't always
been present. Therefore, Mbed TLS might have countermeasures against attacks
outside the above defined threat model.
The presence of such countermeasures don't mean that Mbed TLS provides
protection against a class of attacks outside of the above described threat
model. Neither does it mean that the failure of such a countermeasure is
considered a vulnerability.
#### Block ciphers
Currently there are four block ciphers in Mbed TLS: AES, CAMELLIA, ARIA and
DES. The pure software implementation in Mbed TLS implementation uses lookup
tables, which are vulnerable to timing attacks.
These timing attacks can be physical, local or depending on network latency
even a remote. The attacks can result in key recovery.
**Workarounds:**
- Turn on hardware acceleration for AES. This is supported only on selected
architectures and currently only available for AES. See configuration options
`MBEDTLS_AESCE_C`, `MBEDTLS_AESNI_C` and `MBEDTLS_PADLOCK_C` for details.
- Add a secure alternative implementation (typically hardware acceleration) for
the vulnerable cipher. See the [Alternative Implementations
Guide](docs/architecture/alternative-implementations.md) for more information.
- Use cryptographic mechanisms that are not based on block ciphers. In
particular, for authenticated encryption, use ChaCha20/Poly1305 instead of
block cipher modes. For random generation, use HMAC\_DRBG instead of CTR\_DRBG.
#### Everest
The HACL* implementation of X25519 taken from the Everest project only protects
against remote timing attacks. (See their [Security
Policy](https://github.com/hacl-star/hacl-star/blob/main/SECURITY.md).)
The Everest variant is only used when `MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED`
configuration option is defined. This option is off by default.

16
lib/mbedtls/external/mbedtls/SUPPORT.md vendored Normal file
View File

@ -0,0 +1,16 @@
## Documentation
Here are some useful sources of information about using Mbed TLS:
- [ReadTheDocs](https://mbed-tls.readthedocs.io/);
- API documentation, see the [Documentation section of the
README](README.md#documentation);
- the `docs` directory in the source tree;
- the [Mbed TLS Knowledge Base](https://mbed-tls.readthedocs.io/en/latest/kb/);
- the [Mbed TLS mailing-list
archives](https://lists.trustedfirmware.org/archives/list/mbed-tls@lists.trustedfirmware.org/).
## Asking Questions
If you can't find your answer in the above sources, please use the [Mbed TLS
mailing list](https://lists.trustedfirmware.org/mailman3/lists/mbed-tls.lists.trustedfirmware.org).

View File

@ -0,0 +1,3 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/MbedTLSTargets.cmake")

View File

@ -0,0 +1,24 @@
This directory contains example configuration files.
The examples are generally focused on a particular usage case (eg, support for
a restricted number of ciphersuites) and aim at minimizing resource usage for
this target. They can be used as a basis for custom configurations.
These files are complete replacements for the default mbedtls_config.h. To use one of
them, you can pick one of the following methods:
1. Replace the default file include/mbedtls/mbedtls_config.h with the chosen one.
2. Define MBEDTLS_CONFIG_FILE and adjust the include path accordingly.
For example, using make:
CFLAGS="-I$PWD/configs -DMBEDTLS_CONFIG_FILE='<foo.h>'" make
Or, using cmake:
find . -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} +
CFLAGS="-I$PWD/configs -DMBEDTLS_CONFIG_FILE='<foo.h>'" cmake .
make
Note that the second method also works if you want to keep your custom
configuration file outside the Mbed TLS tree.

View File

@ -0,0 +1,92 @@
/**
* \file config-ccm-psk-dtls1_2.h
*
* \brief Small configuration for DTLS 1.2 with PSK and AES-CCM ciphersuites
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
/*
* Minimal configuration for DTLS 1.2 with PSK and AES-CCM ciphersuites
*
* Distinguishing features:
* - Optimized for small code size, low bandwidth (on an unreliable transport),
* and low RAM usage.
* - No asymmetric cryptography (no certificates, no Diffie-Hellman key
* exchange).
* - Fully modern and secure (provided the pre-shared keys are generated and
* stored securely).
* - Very low record overhead with CCM-8.
* - Includes several optional DTLS features typically used in IoT.
*
* See README.txt for usage instructions.
*/
/* System support */
//#define MBEDTLS_HAVE_TIME /* Optionally used in Hello messages */
/* Other MBEDTLS_HAVE_XXX flags irrelevant for this configuration */
/* Mbed TLS modules */
#define MBEDTLS_AES_C
#define MBEDTLS_CCM_C
#define MBEDTLS_CIPHER_C
#define MBEDTLS_CTR_DRBG_C
#define MBEDTLS_ENTROPY_C
#define MBEDTLS_MD_C
#define MBEDTLS_NET_C
#define MBEDTLS_SHA256_C
#define MBEDTLS_SSL_CLI_C
#define MBEDTLS_SSL_COOKIE_C
#define MBEDTLS_SSL_SRV_C
#define MBEDTLS_SSL_TLS_C
#define MBEDTLS_TIMING_C
/* TLS protocol feature support */
#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
#define MBEDTLS_SSL_PROTO_TLS1_2
#define MBEDTLS_SSL_PROTO_DTLS
#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
#define MBEDTLS_SSL_DTLS_CONNECTION_ID
#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
/*
* Use only CCM_8 ciphersuites, and
* save ROM and a few bytes of RAM by specifying our own ciphersuite list
*/
#define MBEDTLS_SSL_CIPHERSUITES \
MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8, \
MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8
/*
* Save RAM at the expense of interoperability: do this only if you control
* both ends of the connection! (See comments in "mbedtls/ssl.h".)
* The optimal size here depends on the typical size of records.
*/
#define MBEDTLS_SSL_IN_CONTENT_LEN 256
#define MBEDTLS_SSL_OUT_CONTENT_LEN 256
/* Save RAM at the expense of ROM */
#define MBEDTLS_AES_ROM_TABLES
/* Save some RAM by adjusting to your exact needs */
#define MBEDTLS_PSK_MAX_LEN 16 /* 128-bits keys are generally enough */
/*
* You should adjust this to the exact number of sources you're using: default
* is the "platform_entropy_poll" source, but you may want to add other ones
* Minimum is 2 for the entropy test suite.
*/
#define MBEDTLS_ENTROPY_MAX_SOURCES 2
/* These defines are present so that the config modifying scripts can enable
* them during tests/scripts/test-ref-configs.pl */
//#define MBEDTLS_USE_PSA_CRYPTO
//#define MBEDTLS_PSA_CRYPTO_C
/* Error messages and TLS debugging traces
* (huge code size increase, needed for tests/ssl-opt.sh) */
//#define MBEDTLS_DEBUG_C
//#define MBEDTLS_ERROR_C

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