Add SNI support to redbean and improve SSL perf

This change makes SSL virtual hosting possible. You can now load
multiple certificates for multiple domains and redbean will just
figure out which one to use, even if you only have 1 ip address.
You can also use a jumbo certificate that lists all your domains
in the the subject alternative names.

This change also makes performance improvements to MbedTLS. Here
are some benchmarks vs. cc1920749e

                                   BEFORE    AFTER   (microsecs)
suite_ssl.com                     2512881   191738 13.11x faster
suite_pkparse.com                   36291     3295 11.01x faster
suite_x509parse.com                854669   120293  7.10x faster
suite_pkwrite.com                    6549     1265  5.18x faster
suite_ecdsa.com                     53347    18778  2.84x faster
suite_pk.com                        49051    18717  2.62x faster
suite_ecdh.com                      19535     9502  2.06x faster
suite_shax.com                      15848     7965  1.99x faster
suite_rsa.com                      353257   184828  1.91x faster
suite_x509write.com                162646    85733  1.90x faster
suite_ecp.com                       20503    11050  1.86x faster
suite_hmac_drbg.no_reseed.com       19528    11417  1.71x faster
suite_hmac_drbg.nopr.com            12460     8010  1.56x faster
suite_mpi.com                      687124   442661  1.55x faster
suite_hmac_drbg.pr.com              11890     7752  1.53x faster

There aren't any special tricks to the performance imporvements.
It's mostly due to code cleanup, assembly and intel instructions
like mulx, adox, and adcx.
This commit is contained in:
Justine Tunney 2021-07-19 14:55:20 -07:00
parent f3e28aa192
commit 398f0c16fb
190 changed files with 14367 additions and 8928 deletions

View file

@ -49,6 +49,8 @@ LOCAL CHANGES
- Fix mbedtls_mpi_sub_abs() to not call malloc/free/memcpy since
it's called 11,124 times during as SSL handshake.
- Make P-256 and P-384 modulus goes 5x faster.
- Make chacha20 26% faster.
- Make base64 100x faster.

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "libc/nexgen32e/x86feature.h"
#include "third_party/mbedtls/aes.h"
@ -11,32 +28,15 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* FIPS-197 compliant AES implementation
*
* Copyright The Mbed TLS Contributors
* 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.
*/
/*
* The AES block cipher was designed by Vincent Rijmen and Joan Daemen.
/**
* @fileoverview FIPS-197 compliant AES implementation
*
* http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf
* http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
* The AES block cipher was designed by Vincent Rijmen and Joan Daemen.
*
* @see http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf
* @see http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
*/
#if defined(MBEDTLS_AES_C)
@ -485,7 +485,7 @@ void mbedtls_aes_init( mbedtls_aes_context *ctx )
{
AES_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_aes_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aes_context ) );
}
void mbedtls_aes_free( mbedtls_aes_context *ctx )
@ -733,7 +733,7 @@ int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx,
const unsigned char *key,
unsigned int keybits)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const unsigned char *key1, *key2;
unsigned int key1bits, key2bits;
@ -758,7 +758,7 @@ int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx,
const unsigned char *key,
unsigned int keybits)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const unsigned char *key1, *key2;
unsigned int key1bits, key2bits;
@ -1100,7 +1100,7 @@ int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t blocks = length / 16;
size_t leftover = length % 16;
unsigned char tweak[16];
@ -1349,12 +1349,12 @@ exit:
* AES-CTR buffer encryption/decryption
*/
int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[16],
unsigned char stream_block[16],
const unsigned char *input,
unsigned char *output )
size_t length,
size_t *nc_off,
unsigned char nonce_counter[16],
unsigned char stream_block[16],
const unsigned char *input,
unsigned char *output )
{
int c, i;
size_t n;
@ -1734,7 +1734,7 @@ int mbedtls_aes_self_test( int verbose )
#endif
mbedtls_aes_context ctx;
memset( key, 0, 32 );
mbedtls_platform_zeroize( key, 32 );
mbedtls_aes_init( &ctx );
/*
@ -1750,7 +1750,7 @@ int mbedtls_aes_self_test( int verbose )
mbedtls_printf( " AES-ECB-%3u (%s): ", keybits,
( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
memset( buf, 0, 16 );
mbedtls_platform_zeroize( buf, 16 );
if( mode == MBEDTLS_AES_DECRYPT )
{
@ -1797,9 +1797,9 @@ int mbedtls_aes_self_test( int verbose )
mbedtls_printf( " AES-CBC-%3u (%s): ", keybits,
( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
memset( iv , 0, 16 );
memset( prv, 0, 16 );
memset( buf, 0, 16 );
mbedtls_platform_zeroize( iv , 16 );
mbedtls_platform_zeroize( prv, 16 );
mbedtls_platform_zeroize( buf, 16 );
if( mode == MBEDTLS_AES_DECRYPT )
{
@ -2042,7 +2042,7 @@ int mbedtls_aes_self_test( int verbose )
mbedtls_printf( " AES-XTS-128 (%s): ",
( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
memset( key, 0, sizeof( key ) );
mbedtls_platform_zeroize( key, sizeof( key ) );
memcpy( key, aes_test_xts_key[u], 32 );
data_unit = aes_test_xts_data_unit[u];

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/aesni.h"
@ -10,25 +27,6 @@ Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* AES-NI support functions
*
* Copyright The Mbed TLS Contributors
* 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.
*/
/*
* [AES-WP] http://software.intel.com/en-us/articles/intel-advanced-encryption-standard-aes-instructions-set
* [CLMUL-WP] http://software.intel.com/en-us/articles/intel-carry-less-multiplication-instruction-and-its-usage-for-computing-the-gcm-mode/
@ -91,22 +89,22 @@ int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,
"1: \n\t" // encryption loop
"movdqu (%1), %%xmm1 \n\t" // load round key
AESENC xmm1_xmm0 "\n\t" // do round
"aesenc %%xmm1, %%xmm0 \n\t" // do round
"add $16, %1 \n\t" // point to next round key
"subl $1, %0 \n\t" // loop
"jnz 1b \n\t"
"movdqu (%1), %%xmm1 \n\t" // load round key
AESENCLAST xmm1_xmm0 "\n\t" // last round
"aesenclast %%xmm1, %%xmm0 \n\t" // last round
"jmp 3f \n\t"
"2: \n\t" // decryption loop
"movdqu (%1), %%xmm1 \n\t"
AESDEC xmm1_xmm0 "\n\t" // do round
"aesdec %%xmm1, %%xmm0 \n\t" // do round
"add $16, %1 \n\t"
"subl $1, %0 \n\t"
"jnz 2b \n\t"
"movdqu (%1), %%xmm1 \n\t" // load round key
AESDECLAST xmm1_xmm0 "\n\t" // last round
"aesdeclast %%xmm1,%%xmm0 \n\t" // last round
"3: \n\t"
"movdqu %%xmm0, (%4) \n\t" // export output

View file

@ -175,9 +175,19 @@ mbedtls_asn1_named_data;
* would end beyond \p end.
* \return #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the length is unparseable.
*/
int mbedtls_asn1_get_len( unsigned char **p,
const unsigned char *end,
size_t *len );
forceinline int mbedtls_asn1_get_len( unsigned char **p,
const unsigned char *end,
size_t *len ) {
int mbedtls_asn1_get_len_impl( unsigned char **, const unsigned char *, size_t * );
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
if( **p & 0x80 )
return( mbedtls_asn1_get_len_impl( p, end, len ) );
*len = *(*p)++;
if( *len > (size_t) ( end - *p ) )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
return( 0 );
}
/**
* \brief Get the tag and length of the element.
@ -200,9 +210,17 @@ int mbedtls_asn1_get_len( unsigned char **p,
* would end beyond \p end.
* \return #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the length is unparseable.
*/
int mbedtls_asn1_get_tag( unsigned char **p,
const unsigned char *end,
size_t *len, int tag );
forceinline int mbedtls_asn1_get_tag( unsigned char **p,
const unsigned char *end,
size_t *len, int tag )
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
if( **p != tag )
return( MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
(*p)++;
return( mbedtls_asn1_get_len( p, end, len ) );
}
/**
* \brief Retrieve a boolean ASN.1 tag and its value.

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/asn1.h"
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/common.h"
@ -9,39 +26,19 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* Generic ASN.1 parsing
*
* Copyright The Mbed TLS Contributors
* 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.
*/
#if defined(MBEDTLS_ASN1_PARSE_C)
/*
* ASN.1 DER decoding routines
*/
int mbedtls_asn1_get_len( unsigned char **p,
const unsigned char *end,
size_t *len )
int mbedtls_asn1_get_len_impl( unsigned char **p,
const unsigned char *end,
size_t *len )
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
if( ( **p & 0x80 ) == 0 )
*len = *(*p)++;
else
@ -51,79 +48,50 @@ int mbedtls_asn1_get_len( unsigned char **p,
case 1:
if( ( end - *p ) < 2 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
*len = (*p)[1];
(*p) += 2;
break;
case 2:
if( ( end - *p ) < 3 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
*len = ( (size_t)(*p)[1] << 8 ) | (*p)[2];
(*p) += 3;
break;
case 3:
if( ( end - *p ) < 4 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
*len = ( (size_t)(*p)[1] << 16 ) |
( (size_t)(*p)[2] << 8 ) | (*p)[3];
(*p) += 4;
break;
case 4:
if( ( end - *p ) < 5 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
*len = ( (size_t)(*p)[1] << 24 ) | ( (size_t)(*p)[2] << 16 ) |
( (size_t)(*p)[3] << 8 ) | (*p)[4];
(*p) += 5;
break;
default:
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
}
}
if( *len > (size_t) ( end - *p ) )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
return( 0 );
}
int mbedtls_asn1_get_tag( unsigned char **p,
const unsigned char *end,
size_t *len, int tag )
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
if( **p != tag )
return( MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
(*p)++;
return( mbedtls_asn1_get_len( p, end, len ) );
}
int mbedtls_asn1_get_bool( unsigned char **p,
const unsigned char *end,
int *val )
const unsigned char *end,
int *val )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_BOOLEAN ) ) != 0 )
return( ret );
if( len != 1 )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
*val = ( **p != 0 ) ? 1 : 0;
(*p)++;
return( 0 );
}
@ -131,12 +99,10 @@ static int asn1_get_tagged_int( unsigned char **p,
const unsigned char *end,
int tag, int *val )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, tag ) ) != 0 )
return( ret );
/*
* len==0 is malformed (0 must be represented as 020100 for INTEGER,
* or 0A0100 for ENUMERATED tags
@ -146,28 +112,24 @@ static int asn1_get_tagged_int( unsigned char **p,
/* This is a cryptography library. Reject negative integers. */
if( ( **p & 0x80 ) != 0 )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Skip leading zeros. */
while( len > 0 && **p == 0 )
{
++( *p );
--len;
}
/* Reject integers that don't fit in an int. This code assumes that
* the int type has no padding bit. */
if( len > sizeof( int ) )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
if( len == sizeof( int ) && ( **p & 0x80 ) != 0 )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
*val = 0;
while( len-- > 0 )
{
*val = ( *val << 8 ) | **p;
(*p)++;
}
return( 0 );
}
@ -185,52 +147,41 @@ int mbedtls_asn1_get_enum( unsigned char **p,
return( asn1_get_tagged_int( p, end, MBEDTLS_ASN1_ENUMERATED, val) );
}
#if defined(MBEDTLS_BIGNUM_C)
int mbedtls_asn1_get_mpi( unsigned char **p,
const unsigned char *end,
mbedtls_mpi *X )
const unsigned char *end,
mbedtls_mpi *X )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
return( ret );
ret = mbedtls_mpi_read_binary( X, *p, len );
*p += len;
return( ret );
}
#endif /* MBEDTLS_BIGNUM_C */
int mbedtls_asn1_get_bitstring( unsigned char **p, const unsigned char *end,
mbedtls_asn1_bitstring *bs)
int mbedtls_asn1_get_bitstring( unsigned char **p,
const unsigned char *end,
mbedtls_asn1_bitstring *bs)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
/* Certificate type is a single byte bitstring */
if( ( ret = mbedtls_asn1_get_tag( p, end, &bs->len, MBEDTLS_ASN1_BIT_STRING ) ) != 0 )
return( ret );
/* Check length, subtract one for actual bit string length */
if( bs->len < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
bs->len -= 1;
/* Get number of unused bits, ensure unused bits <= 7 */
bs->unused_bits = **p;
if( bs->unused_bits > 7 )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
(*p)++;
/* Get actual bitstring */
bs->p = *p;
*p += bs->len;
if( *p != end )
return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
@ -249,68 +200,57 @@ int mbedtls_asn1_traverse_sequence_of(
{
int ret;
size_t len;
/* Get main sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
return( ret );
}
if( *p + len != end )
return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
while( *p < end )
{
unsigned char const tag = *(*p)++;
if( ( tag & tag_must_mask ) != tag_must_val )
return( MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
if( ( ret = mbedtls_asn1_get_len( p, end, &len ) ) != 0 )
return( ret );
if( ( tag & tag_may_mask ) == tag_may_val )
{
if( cb != NULL )
if( cb )
{
ret = cb( ctx, tag, *p, len );
if( ret != 0 )
return( ret );
}
}
*p += len;
}
return( 0 );
}
/*
* Get a bit string without unused bits
*/
int mbedtls_asn1_get_bitstring_null( unsigned char **p, const unsigned char *end,
size_t *len )
int mbedtls_asn1_get_bitstring_null( unsigned char **p,
const unsigned char *end,
size_t *len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( ( ret = mbedtls_asn1_get_tag( p, end, len, MBEDTLS_ASN1_BIT_STRING ) ) != 0 )
return( ret );
if( *len == 0 )
if( !*len )
return( MBEDTLS_ERR_ASN1_INVALID_DATA );
--( *len );
if( **p != 0 )
return( MBEDTLS_ERR_ASN1_INVALID_DATA );
++( *p );
return( 0 );
}
void mbedtls_asn1_sequence_free( mbedtls_asn1_sequence *seq )
{
while( seq != NULL )
while( seq )
{
mbedtls_asn1_sequence *next = seq->next;
mbedtls_platform_zeroize( seq, sizeof( *seq ) );
@ -334,22 +274,17 @@ static int asn1_get_sequence_of_cb( void *ctx,
(asn1_get_sequence_of_cb_ctx_t *) ctx;
mbedtls_asn1_sequence *cur =
cb_ctx->cur;
if( cur->buf.p != NULL )
if( cur->buf.p )
{
cur->next =
mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
if( cur->next == NULL )
if( !cur->next )
return( MBEDTLS_ERR_ASN1_ALLOC_FAILED );
cur = cur->next;
}
cur->buf.p = start;
cur->buf.len = len;
cur->buf.tag = tag;
cb_ctx->cur = cur;
return( 0 );
}
@ -358,58 +293,48 @@ static int asn1_get_sequence_of_cb( void *ctx,
* Parses and splits an ASN.1 "SEQUENCE OF <tag>"
*/
int mbedtls_asn1_get_sequence_of( unsigned char **p,
const unsigned char *end,
mbedtls_asn1_sequence *cur,
int tag)
const unsigned char *end,
mbedtls_asn1_sequence *cur,
int tag)
{
asn1_get_sequence_of_cb_ctx_t cb_ctx = { tag, cur };
memset( cur, 0, sizeof( mbedtls_asn1_sequence ) );
mbedtls_platform_zeroize( cur, sizeof( mbedtls_asn1_sequence ) );
return( mbedtls_asn1_traverse_sequence_of(
p, end, 0xFF, tag, 0, 0,
asn1_get_sequence_of_cb, &cb_ctx ) );
}
int mbedtls_asn1_get_alg( unsigned char **p,
const unsigned char *end,
mbedtls_asn1_buf *alg, mbedtls_asn1_buf *params )
const unsigned char *end,
mbedtls_asn1_buf *alg,
mbedtls_asn1_buf *params )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( ret );
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
alg->tag = **p;
end = *p + len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &alg->len, MBEDTLS_ASN1_OID ) ) != 0 )
return( ret );
alg->p = *p;
*p += alg->len;
if( *p == end )
{
mbedtls_platform_zeroize( params, sizeof(mbedtls_asn1_buf) );
return( 0 );
}
params->tag = **p;
(*p)++;
if( ( ret = mbedtls_asn1_get_len( p, end, &params->len ) ) != 0 )
return( ret );
params->p = *p;
*p += params->len;
if( *p != end )
return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
@ -417,36 +342,29 @@ int mbedtls_asn1_get_alg_null( unsigned char **p,
const unsigned char *end,
mbedtls_asn1_buf *alg )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_asn1_buf params;
memset( &params, 0, sizeof(mbedtls_asn1_buf) );
mbedtls_platform_zeroize( &params, sizeof(mbedtls_asn1_buf) );
if( ( ret = mbedtls_asn1_get_alg( p, end, alg, &params ) ) != 0 )
return( ret );
if( ( params.tag != MBEDTLS_ASN1_NULL && params.tag != 0 ) || params.len != 0 )
return( MBEDTLS_ERR_ASN1_INVALID_DATA );
return( 0 );
}
void mbedtls_asn1_free_named_data( mbedtls_asn1_named_data *cur )
{
if( cur == NULL )
if( !cur )
return;
mbedtls_free( cur->oid.p );
mbedtls_free( cur->val.p );
mbedtls_platform_zeroize( cur, sizeof( mbedtls_asn1_named_data ) );
}
void mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head )
{
mbedtls_asn1_named_data *cur;
while( ( cur = *head ) != NULL )
while( ( cur = *head ) )
{
*head = cur->next;
mbedtls_asn1_free_named_data( cur );
@ -454,20 +372,19 @@ void mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head )
}
}
mbedtls_asn1_named_data *mbedtls_asn1_find_named_data( mbedtls_asn1_named_data *list,
const char *oid, size_t len )
mbedtls_asn1_named_data *
mbedtls_asn1_find_named_data(mbedtls_asn1_named_data *list,
const char *oid, size_t len )
{
while( list != NULL )
while( list )
{
if( list->oid.len == len &&
memcmp( list->oid.p, oid, len ) == 0 )
{
break;
}
list = list->next;
}
return( list );
}

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/asn1write.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
@ -8,25 +25,10 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* ASN.1 buffer writing functionality
*
* Copyright The Mbed TLS Contributors
* 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.
/**
* @fileoverview ASN.1 buffer writing functionality
*/
#if defined(MBEDTLS_ASN1_WRITE_C)
@ -49,51 +51,42 @@ int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = (unsigned char) len;
return( 1 );
}
if( len <= 0xFF )
{
if( *p - start < 2 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = (unsigned char) len;
*--(*p) = 0x81;
return( 2 );
}
if( len <= 0xFFFF )
{
if( *p - start < 3 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = ( len ) & 0xFF;
*--(*p) = ( len >> 8 ) & 0xFF;
*--(*p) = 0x82;
return( 3 );
}
if( len <= 0xFFFFFF )
{
if( *p - start < 4 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = ( len ) & 0xFF;
*--(*p) = ( len >> 8 ) & 0xFF;
*--(*p) = ( len >> 16 ) & 0xFF;
*--(*p) = 0x83;
return( 4 );
}
#if SIZE_MAX > 0xFFFFFFFF
if( len <= 0xFFFFFFFF )
#endif
{
if( *p - start < 5 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = ( len ) & 0xFF;
*--(*p) = ( len >> 8 ) & 0xFF;
*--(*p) = ( len >> 16 ) & 0xFF;
@ -101,7 +94,6 @@ int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len
*--(*p) = 0x84;
return( 5 );
}
#if SIZE_MAX > 0xFFFFFFFF
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
#endif
@ -123,9 +115,7 @@ int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, unsigned ch
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = tag;
return( 1 );
}
@ -146,14 +136,11 @@ int mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t size )
{
size_t len = 0;
if( *p < start || (size_t)( *p - start ) < size )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
len = size;
(*p) -= len;
memcpy( *p, buf, len );
return( (int) len );
}
@ -174,19 +161,15 @@ int mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start,
*/
int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, const mbedtls_mpi *X )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
// Write the MPI
//
len = mbedtls_mpi_size( X );
if( *p < start || (size_t)( *p - start ) < len )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
(*p) -= len;
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( X, *p, len ) );
// DER format assumes 2s complement for numbers, so the leftmost bit
// should be 0 for positive numbers and 1 for negative numbers.
//
@ -194,16 +177,12 @@ int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, const mbedt
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = 0x00;
len += 1;
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_INTEGER ) );
ret = (int) len;
cleanup:
return( ret );
}
@ -223,14 +202,12 @@ cleanup:
*/
int mbedtls_asn1_write_null( unsigned char **p, unsigned char *start )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
// Write NULL
//
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, 0) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_NULL ) );
return( (int) len );
}
@ -251,14 +228,12 @@ int mbedtls_asn1_write_null( unsigned char **p, unsigned char *start )
int mbedtls_asn1_write_oid( unsigned char **p, unsigned char *start,
const char *oid, size_t oid_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) oid, oid_len ) );
MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OID ) );
return( (int) len );
}
@ -281,20 +256,16 @@ int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, unsigned char *s
const char *oid, size_t oid_len,
size_t par_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
if( par_len == 0 )
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_null( p, start ) );
else
len += par_len;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );
return( (int) len );
}
@ -313,26 +284,21 @@ int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, unsigned char *s
*/
int mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, int boolean )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
*--(*p) = (boolean) ? 255 : 0;
len++;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BOOLEAN ) );
return( (int) len );
}
static int asn1_write_tagged_int( unsigned char **p, unsigned char *start, int val, int tag )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
do
{
if( *p - start < 1 )
@ -342,7 +308,6 @@ static int asn1_write_tagged_int( unsigned char **p, unsigned char *start, int v
val >>= 8;
}
while( val > 0 );
if( **p & 0x80 )
{
if( *p - start < 1 )
@ -350,10 +315,8 @@ static int asn1_write_tagged_int( unsigned char **p, unsigned char *start, int v
*--(*p) = 0x00;
len += 1;
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, tag ) );
return( (int) len );
}
@ -414,15 +377,12 @@ int mbedtls_asn1_write_enum( unsigned char **p, unsigned char *start, int val )
int mbedtls_asn1_write_tagged_string( unsigned char **p, unsigned char *start,
int tag, const char *text, size_t text_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) text, text_len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, tag ) );
return( (int) len );
}
@ -515,37 +475,30 @@ int mbedtls_asn1_write_named_bitstring( unsigned char **p,
const unsigned char *cur_byte;
unsigned char cur_byte_shifted;
unsigned char bit;
byte_len = ( bits + 7 ) / 8;
unused_bits = ( byte_len * 8 ) - bits;
/*
* Named bitstrings require that trailing 0s are excluded in the encoding
* of the bitstring. Trailing 0s are considered part of the 'unused' bits
* when encoding this value in the first content octet
*/
if( bits != 0 )
if( bits )
{
cur_byte = buf + byte_len - 1;
cur_byte_shifted = *cur_byte >> unused_bits;
for( ; ; )
{
bit = cur_byte_shifted & 0x1;
cur_byte_shifted >>= 1;
if( bit != 0 )
if( bit )
break;
bits--;
if( bits == 0 )
break;
if( bits % 8 == 0 )
cur_byte_shifted = *--cur_byte;
}
}
return( mbedtls_asn1_write_bitstring( p, start, buf, bits ) );
}
@ -566,18 +519,14 @@ int mbedtls_asn1_write_named_bitstring( unsigned char **p,
int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t bits )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
size_t unused_bits, byte_len;
byte_len = ( bits + 7 ) / 8;
unused_bits = ( byte_len * 8 ) - bits;
if( *p < start || (size_t)( *p - start ) < byte_len + 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
len = byte_len + 1;
/* Write the bitstring. Ensure the unused bits are zeroed */
if( byte_len > 0 )
{
@ -586,13 +535,10 @@ int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
( *p ) -= byte_len;
memcpy( *p, buf, byte_len );
}
/* Write unused bits */
*--( *p ) = (unsigned char)unused_bits;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) );
return( (int) len );
}
@ -613,35 +559,29 @@ int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t size )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, buf, size ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OCTET_STRING ) );
return( (int) len );
}
/* This is a copy of the ASN.1 parsing function mbedtls_asn1_find_named_data(),
* which is replicated to avoid a dependency ASN1_WRITE_C on ASN1_PARSE_C. */
static mbedtls_asn1_named_data *asn1_find_named_data(
mbedtls_asn1_named_data *list,
const char *oid, size_t len )
{
while( list != NULL )
while( list )
{
if( list->oid.len == len &&
memcmp( list->oid.p, oid, len ) == 0 )
{
break;
}
list = list->next;
}
return( list );
}
@ -672,38 +612,33 @@ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(mbedtls_asn1_named_data *
size_t val_len )
{
mbedtls_asn1_named_data *cur;
if( ( cur = asn1_find_named_data( *head, oid, oid_len ) ) == NULL )
{
// Add new entry if not present yet based on OID
//
cur = (mbedtls_asn1_named_data*)mbedtls_calloc( 1,
sizeof(mbedtls_asn1_named_data) );
if( cur == NULL )
if( !cur )
return( NULL );
cur->oid.len = oid_len;
cur->oid.p = mbedtls_calloc( 1, oid_len );
if( cur->oid.p == NULL )
if( !cur->oid.p )
{
mbedtls_free( cur );
return( NULL );
}
memcpy( cur->oid.p, oid, oid_len );
cur->val.len = val_len;
if( val_len != 0 )
if( val_len )
{
cur->val.p = mbedtls_calloc( 1, val_len );
if( cur->val.p == NULL )
if( !cur->val.p )
{
mbedtls_free( cur->oid.p );
mbedtls_free( cur );
return( NULL );
}
}
cur->next = *head;
*head = cur;
}
@ -720,17 +655,15 @@ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(mbedtls_asn1_named_data *
* a consistent state in case allocation fails.
*/
void *p = mbedtls_calloc( 1, val_len );
if( p == NULL )
if( !p )
return( NULL );
mbedtls_free( cur->val.p );
cur->val.p = p;
cur->val.len = val_len;
}
if( val != NULL )
if( val )
memcpy( cur->val.p, val, val_len );
return( cur );
}
#endif /* MBEDTLS_ASN1_WRITE_C */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/base64.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/platform.h"
@ -7,28 +24,7 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* RFC 1521 base64 encoding/decoding
*
* Copyright The Mbed TLS Contributors
* 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.
*/
#if defined(MBEDTLS_BASE64_C)
#define ENC "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
@ -187,7 +183,6 @@ int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
uint32_t j, x;
unsigned char *p;
unsigned char dec_map_lookup;
/* First pass: check for validity and get output length */
for( i = n = j = 0; i < slen; i++ )
{
@ -198,65 +193,49 @@ int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
++i;
++x;
}
/* Spaces at end of buffer are OK */
if( i == slen )
break;
if( ( slen - i ) >= 2 &&
src[i] == '\r' && src[i + 1] == '\n' )
continue;
if( src[i] == '\n' )
continue;
/* Space inside a line is an error */
if( x != 0 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( src[i] == '=' && ++j > 2 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
dec_map_lookup = mbedtls_base64_table_lookup( base64_dec_map, sizeof( base64_dec_map ), src[i] );
if( src[i] > 127 || dec_map_lookup == 127 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( dec_map_lookup < 64 && j != 0 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
n++;
}
if( n == 0 )
{
*olen = 0;
return( 0 );
}
/* The following expression is to calculate the following formula without
* risk of integer overflow in n:
* n = ( ( n * 6 ) + 7 ) >> 3;
*/
n = ( 6 * ( n >> 3 ) ) + ( ( 6 * ( n & 0x7 ) + 7 ) >> 3 );
n -= j;
if( dst == NULL || dlen < n )
{
*olen = n;
return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
}
for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )
{
if( *src == '\r' || *src == '\n' || *src == ' ' )
continue;
dec_map_lookup = mbedtls_base64_table_lookup( base64_dec_map, sizeof( base64_dec_map ), *src );
mbedtls_base64_cond_assign_uint32( &j, j - 1, mbedtls_base64_eq( dec_map_lookup, 64 ) );
x = ( x << 6 ) | ( dec_map_lookup & 0x3F );
if( ++n == 4 )
{
n = 0;
@ -265,9 +244,7 @@ int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
if( j > 2 ) *p++ = (unsigned char)( x );
}
}
*olen = p - dst;
return( 0 );
}
@ -299,41 +276,29 @@ int mbedtls_base64_self_test( int verbose )
size_t len;
const unsigned char *src;
unsigned char buffer[128];
if( verbose != 0 )
mbedtls_printf( " Base64 encoding test: " );
src = base64_test_dec;
if( mbedtls_base64_encode( buffer, sizeof( buffer ), &len, src, 64 ) != 0 ||
memcmp( base64_test_enc, buffer, 88 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
if( verbose != 0 )
mbedtls_printf( "passed\n Base64 decoding test: " );
src = base64_test_enc;
if( mbedtls_base64_decode( buffer, sizeof( buffer ), &len, src, 88 ) != 0 ||
memcmp( base64_test_dec, buffer, 64 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
if( verbose != 0 )
mbedtls_printf( "passed\n\n" );
return( 0 );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_BASE64_C */

285
third_party/mbedtls/bigmul.c vendored Normal file
View file

@ -0,0 +1,285 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "libc/log/backtrace.internal.h"
#include "libc/log/check.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/bsr.h"
#include "libc/nexgen32e/x86feature.h"
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/profile.h"
/* clang-format off */
void Mul(uint64_t *c, uint64_t *A, unsigned n, uint64_t *B, unsigned m)
{
if (!m--) return;
mbedtls_platform_zeroize(c, m * ciL);
mbedtls_mpi_mul_hlp1(n, A, c + m, B[m]);
for (; m > 0; m--)
mbedtls_mpi_mul_hlp(n, A, c + m - 1, B[m - 1]);
}
/**
* Computes inner loop of multiplication algorithm.
*/
void mbedtls_mpi_mul_hlp1(size_t n, const uint64_t *s, uint64_t *d, uint64_t b)
{
size_t i;
uint128_t x;
uint64_t c, t;
i = c = 0;
#ifdef __x86_64__
#define MULXADOX(i) \
"mulx\t" #i "*8(%2),%%rax,%%r9\n\t" \
"adox\t%0,%%rax\n\t" \
"mov\t%%rax," #i "*8(%1)\n\t" \
"mov\t%%r9,%0\n\t"
if (X86_HAVE(BMI2) && X86_HAVE(ADX))
{
for (; n >= 8; n -= 8, s += 8, d += 8)
{
asm volatile("xor\t%%r8d,%%r8d\n\t" //
MULXADOX(0) //
MULXADOX(1) //
MULXADOX(2) //
MULXADOX(3) //
MULXADOX(4) //
MULXADOX(5) //
MULXADOX(6) //
MULXADOX(7) //
"adcx\t%%r8,%0\n" //
"adox\t%%r8,%0" //
: "+r"(c)
: "r"(d), "S"(s), "d"(b)
: "rax", "r8", "r9", "memory", "cc");
}
for (; n >= 4; n -= 4, s += 4, d += 4)
{
asm volatile("xor\t%%r8d,%%r8d\n\t" //
MULXADOX(0) //
MULXADOX(1) //
MULXADOX(2) //
MULXADOX(3) //
"adcx\t%%r8,%0\n" //
"adox\t%%r8,%0" //
: "+r"(c)
: "r"(d), "S"(s), "d"(b)
: "rax", "r8", "r9", "memory", "cc");
}
}
#undef MULXADOX
#endif
for (; i < n; ++i)
{
x = s[i];
x *= b;
x += c;
c = x >> 64;
d[i] = x;
}
d[i] = c;
}
/**
* Computes inner loop of multiplication algorithm.
*/
void mbedtls_mpi_mul_hlp(size_t n, uint64_t *s, uint64_t *d, uint64_t b)
{
size_t i;
uint128_t x;
uint64_t c, l, h, t;
i = c = 0;
#ifdef __x86_64__
#define MULADDC(i) \
"mulx\t" #i "*8(%2),%%rax,%%r9\n\t" \
"adcx\t" #i "*8(%1),%%rax\n\t" \
"adox\t%0,%%rax\n\t" \
"mov\t%%rax," #i "*8(%1)\n\t" \
"mov\t%%r9,%0\n\t"
if (X86_HAVE(BMI2) && X86_HAVE(ADX))
{
for (; n >= 8; n -= 8, s += 8, d += 8)
{
asm volatile("xor\t%%r8d,%%r8d\n\t" //
MULADDC(0) //
MULADDC(1) //
MULADDC(2) //
MULADDC(3) //
MULADDC(4) //
MULADDC(5) //
MULADDC(6) //
MULADDC(7) //
"adcx\t%%r8,%0\n" //
"adox\t%%r8,%0" //
: "+r"(c)
: "r"(d), "S"(s), "d"(b)
: "rax", "r8", "r9", "memory", "cc");
}
for (; n >= 4; n -= 4, s += 4, d += 4)
{
asm volatile("xor\t%%r8d,%%r8d\n\t" //
MULADDC(0) //
MULADDC(1) //
MULADDC(2) //
MULADDC(3) //
"adcx\t%%r8,%0\n" //
"adox\t%%r8,%0" //
: "+r"(c)
: "r"(d), "S"(s), "d"(b)
: "rax", "r8", "r9", "memory", "cc");
}
}
#undef MULADDC
#endif
for (; i < n; ++i)
{
x = s[i];
x *= b;
x += c;
l = x;
h = x >> 64;
t = d[i];
d[i] = t + l;
c = (t + l < t) + h;
}
do
{
d[i] += c;
} while ((c = d[i++] < c));
}
/**
* Multiplies big number with unsigned scalar: X = A × b
*
* @param X receives result w/ aliasing permitted
* @param A is left-hand side big number
* @param B is left-hand side unsigned scalar
* @return 0 on success or negative on error
*/
int mbedtls_mpi_mul_int(mbedtls_mpi *X, const mbedtls_mpi *A,
mbedtls_mpi_uint b)
{
int r;
size_t n;
MPI_VALIDATE_RET(X);
MPI_VALIDATE_RET(A);
n = mbedtls_mpi_limbs(A);
if ((r = mbedtls_mpi_grow(X, n + 1))) return r;
mbedtls_mpi_mul_hlp1(n, A->p, X->p, b);
X->s = A->s;
X->n = n + 1;
return 0;
}
/**
* Multiplies big numbers: X = A * B
*
* @param X is destination mpi
* @param A is first factor
* @param B is second factor
* @return 0 on success or <0 on error
*/
int mbedtls_mpi_mul_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
const mbedtls_mpi *B)
{
int i, j, t, k, ret;
mbedtls_mpi_uint *K;
mbedtls_mpi TA, TB, *T;
MPI_VALIDATE_RET(X);
MPI_VALIDATE_RET(A);
MPI_VALIDATE_RET(B);
i = mbedtls_mpi_limbs(A);
j = mbedtls_mpi_limbs(B);
if (!i || !j)
return mbedtls_mpi_lset(X, 0);
if( j > i )
T = A,
A = B,
B = T,
t = i,
i = j,
j = t;
if (!IsTiny() && j == 1) {
if (X->n < i + 1)
if ((ret = mbedtls_mpi_grow(X, i + 1))) return ret;
else if (X->n > i + 1)
mbedtls_platform_zeroize(X->p + i + 1, (X->n - (i + 1)) * ciL);
mbedtls_mpi_mul_hlp1(i, A->p, X->p, B->p[0]);
X->s = A->s * B->s;
return 0;
}
if (!IsTiny() && i == j) {
if (X->n < i * 2)
if ((ret = mbedtls_mpi_grow(X, i * 2))) return ret;
else if (X->n > i * 2)
mbedtls_platform_zeroize(X->p + i * 2, (X->n - (i * 2)) * ciL);
if (i == 4) {
Mul4x4(X->p, A->p, B->p);
X->s = A->s * B->s;
return 0;
} else if (i == 6 && X86_HAVE(BMI2) && X86_HAVE(ADX)) {
Mul6x6Adx(X->p, A->p, B->p);
X->s = A->s * B->s;
return 0;
} else if (i == 8 && X86_HAVE(BMI2) && X86_HAVE(ADX)) {
Mul8x8Adx(X->p, A->p, B->p);
X->s = A->s * B->s;
return 0;
}
}
mbedtls_mpi_init( &TA );
mbedtls_mpi_init( &TB );
if (X->n < i + j)
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + j ) );
else if (X->n > i + j)
mbedtls_platform_zeroize( X->p + i + j, (X->n - (i + j)) * ciL );
if (X == A) {
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) );
A = &TA;
}
if (X == B) {
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );
B = &TB;
}
if (!IsTiny() &&
i >= 16 && i == j && !(i & (i - 1)) &&
X86_HAVE(BMI2) && X86_HAVE(ADX) &&
(K = malloc(i * 4 * sizeof(*K)))) {
Karatsuba(X->p, A->p, B->p, i, K);
free(K);
} else {
Mul(X->p, A->p, i, B->p, j);
}
X->s = A->s * B->s;
ret = 0;
cleanup:
mbedtls_mpi_free(&TB);
mbedtls_mpi_free(&TA);
return ret;
}

75
third_party/mbedtls/bigmul4.c vendored Normal file
View file

@ -0,0 +1,75 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/nexgen32e/x86feature.h"
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/math.h"
/* clang-format off */
/**
* Computes 512-bit product of 256-bit and 256-bit numbers.
*
* @param C receives 8 quadword result
* @param A is left hand side which must have 4 quadwords
* @param B is right hand side which must have 4 quadwords
* @note words are host endian while array is little endian
* @mayalias
*/
void (*Mul4x4)(uint64_t C[8], const uint64_t A[4], const uint64_t B[4]);
static textstartup void Mul4x4Init()
{
Mul4x4 = X86_HAVE(ADX) && X86_HAVE(BMI2) ? Mul4x4Adx : Mul4x4Pure;
}
const void *const Mul4x4Ctor[] initarray = {Mul4x4Init};
void Mul4x4Pure(uint64_t C[8], const uint64_t A[4], const uint64_t B[4])
{
uint128_t t;
uint64_t h, c1, c2, c3;
uint64_t r0, r1, r2, r3;
c1 = c2 = c3 = 0;
MADD(A[0], B[0], c1, c2, c3);
r0 = c1, c1 = 0;
MADD(A[0], B[1], c2, c3, c1);
MADD(A[1], B[0], c2, c3, c1);
r1 = c2, c2 = 0;
MADD(A[2], B[0], c3, c1, c2);
MADD(A[1], B[1], c3, c1, c2);
MADD(A[0], B[2], c3, c1, c2);
r2 = c3, c3 = 0;
MADD(A[0], B[3], c1, c2, c3);
MADD(A[1], B[2], c1, c2, c3);
MADD(A[2], B[1], c1, c2, c3);
MADD(A[3], B[0], c1, c2, c3);
C[0] = r0;
r3 = c1, c1 = 0;
MADD(A[3], B[1], c2, c3, c1);
MADD(A[2], B[2], c2, c3, c1);
MADD(A[1], B[3], c2, c3, c1);
C[1] = r1;
C[4] = c2, c2 = 0;
MADD(A[2], B[3], c3, c1, c2);
MADD(A[3], B[2], c3, c1, c2);
C[2] = r2;
C[5] = c3, c3 = 0;
MADD(A[3], B[3], c1, c2, c3);
C[3] = r3;
C[6] = c1;
C[7] = c2;
}

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,9 @@
#ifndef MBEDTLS_BIGNUM_H_
#define MBEDTLS_BIGNUM_H_
#include "libc/stdio/stdio.h"
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/config.h"
#include "third_party/mbedtls/platform.h"
COSMOPOLITAN_C_START_
/* clang-format off */
@ -16,7 +18,7 @@ COSMOPOLITAN_C_START_
#define MBEDTLS_MPI_CHK(f) \
do \
{ \
if( ( ret = (f) ) != 0 ) \
if( ( ret = (f) ) ) \
goto cleanup; \
} while( 0 )
@ -81,11 +83,11 @@ typedef uint64_t mbedtls_mpi_uint;
*/
typedef struct mbedtls_mpi
{
int s; /*!< Sign: -1 if the mpi is negative, 1 otherwise */
size_t n; /*!< total # of limbs */
int s; /*!< Sign: -1 if the mpi is negative, 1 otherwise */
unsigned n; /*!< total # of limbs */
mbedtls_mpi_uint *p; /*!< pointer to limbs */
}
mbedtls_mpi;
mbedtls_mpi forcealign(16);
/**
* \brief Flags for mbedtls_mpi_gen_prime()
@ -98,53 +100,92 @@ typedef enum {
MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR = 0x0002, /**< lower error rate from 2<sup>-80</sup> to 2<sup>-128</sup> */
} mbedtls_mpi_gen_prime_flag_t;
void mbedtls_mpi_init( mbedtls_mpi * );
void mbedtls_mpi_free( mbedtls_mpi * );
int mbedtls_mpi_grow( mbedtls_mpi *, size_t );
int mbedtls_mpi_shrink( mbedtls_mpi *, size_t );
int mbedtls_mpi_copy( mbedtls_mpi *, const mbedtls_mpi * );
void mbedtls_mpi_swap( mbedtls_mpi *, mbedtls_mpi * );
int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *, const mbedtls_mpi *, unsigned char );
int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *, mbedtls_mpi *, unsigned char );
int mbedtls_mpi_lset( mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_get_bit( const mbedtls_mpi *, size_t );
int mbedtls_mpi_set_bit( mbedtls_mpi *, size_t, unsigned char );
size_t mbedtls_mpi_lsb( const mbedtls_mpi * );
size_t mbedtls_mpi_bitlen( const mbedtls_mpi * );
size_t mbedtls_mpi_size( const mbedtls_mpi * );
int mbedtls_mpi_read_string( mbedtls_mpi *, int, const char * );
int mbedtls_mpi_write_string( const mbedtls_mpi *, int, char *, size_t, size_t * );
int mbedtls_mpi_read_file( mbedtls_mpi *, int, FILE * );
int mbedtls_mpi_write_file( const char *, const mbedtls_mpi *, int, FILE * );
int mbedtls_mpi_read_binary( mbedtls_mpi *, const unsigned char *, size_t );
int mbedtls_mpi_read_binary_le( mbedtls_mpi *, const unsigned char *, size_t );
int mbedtls_mpi_write_binary( const mbedtls_mpi *, unsigned char *, size_t );
int mbedtls_mpi_write_binary_le( const mbedtls_mpi *, unsigned char *, size_t );
int mbedtls_mpi_shift_l( mbedtls_mpi *, size_t );
int mbedtls_mpi_shift_r( mbedtls_mpi *, size_t );
int mbedtls_mpi_cmp_abs( const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *, const mbedtls_mpi *, unsigned * );
int mbedtls_mpi_cmp_int( const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_add_abs( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_sub_abs( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_add_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_sub_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_add_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_sub_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_mul_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_mul_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_uint );
int mbedtls_mpi_div_mpi( mbedtls_mpi *, mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_add_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_cmp_abs( const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_cmp_int( const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_copy( mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_div_int( mbedtls_mpi *, mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_mod_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_mod_int( mbedtls_mpi_uint *, const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_div_mpi( mbedtls_mpi *, mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_exp_mod( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi * );
int mbedtls_mpi_fill_random( mbedtls_mpi *, size_t, int (*)(void *, unsigned char *, size_t), void * );
int mbedtls_mpi_gcd( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_gen_prime( mbedtls_mpi *, size_t, int, int (*)(void *, unsigned char *, size_t), void * );
int mbedtls_mpi_get_bit( const mbedtls_mpi *, size_t );
int mbedtls_mpi_grow( mbedtls_mpi *, size_t );
int mbedtls_mpi_inv_mod( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *, int, int (*)(void *, unsigned char *, size_t), void * );
int mbedtls_mpi_gen_prime( mbedtls_mpi *, size_t, int, int (*)(void *, unsigned char *, size_t), void * );
int mbedtls_mpi_lset( mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *, const mbedtls_mpi *, unsigned * );
int mbedtls_mpi_mod_int( mbedtls_mpi_uint *, const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_mod_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_mul_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_uint );
int mbedtls_mpi_mul_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_read_binary( mbedtls_mpi *, const unsigned char *, size_t );
int mbedtls_mpi_read_binary_le( mbedtls_mpi *, const unsigned char *, size_t );
int mbedtls_mpi_read_file( mbedtls_mpi *, int, FILE * );
int mbedtls_mpi_read_string( mbedtls_mpi *, int, const char * );
int mbedtls_mpi_resize( mbedtls_mpi *, size_t );
int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *, const mbedtls_mpi *, unsigned char );
int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *, mbedtls_mpi *, unsigned char );
int mbedtls_mpi_self_test( int );
int mbedtls_mpi_set_bit( mbedtls_mpi *, size_t, unsigned char );
int mbedtls_mpi_shift_l( mbedtls_mpi *, size_t );
int mbedtls_mpi_shift_r( mbedtls_mpi *, size_t );
int mbedtls_mpi_shrink( mbedtls_mpi *, size_t );
int mbedtls_mpi_sub_abs( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_sub_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_sint );
int mbedtls_mpi_sub_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * );
int mbedtls_mpi_write_binary( const mbedtls_mpi *, unsigned char *, size_t );
int mbedtls_mpi_write_binary_le( const mbedtls_mpi *, unsigned char *, size_t );
int mbedtls_mpi_write_file( const char *, const mbedtls_mpi *, int, FILE * );
int mbedtls_mpi_write_string( const mbedtls_mpi *, int, char *, size_t, size_t * );
size_t mbedtls_mpi_bitlen( const mbedtls_mpi * );
size_t mbedtls_mpi_lsb( const mbedtls_mpi * );
size_t mbedtls_mpi_size( const mbedtls_mpi * );
void mbedtls_mpi_free( mbedtls_mpi * );
void mbedtls_mpi_swap( mbedtls_mpi *, mbedtls_mpi * );
/**
* \brief Initialize an MPI context.
*
* This makes the MPI ready to be set or freed,
* but does not define a value for the MPI.
*
* \param X The MPI context to initialize. This must not be \c NULL.
*/
forceinline void mbedtls_mpi_init(mbedtls_mpi *X)
{
MBEDTLS_INTERNAL_VALIDATE(X);
typedef int mbedtls_mpi_lol
__attribute__((__vector_size__(16), __aligned__(16)));
*(mbedtls_mpi_lol *)X = (mbedtls_mpi_lol){1};
}
forceinline size_t mbedtls_mpi_limbs(const mbedtls_mpi *X) {
size_t i;
for (i = X->n; i; i--) {
if (X->p[i - 1]) {
break;
}
}
return i;
}
static inline bool mbedtls_mpi_is_zero(const mbedtls_mpi *X)
{
if (X->n && *X->p) return false;
if (!mbedtls_mpi_limbs(X)) return true;
return false;
}
static inline bool mbedtls_mpi_is_one(const mbedtls_mpi *X)
{
if (!X->n || *X->p != 1 || X->s != 1) return false;
return mbedtls_mpi_limbs(X) == 1;
}
COSMOPOLITAN_C_END_
#endif /* MBEDTLS_BIGNUM_H_ */

41
third_party/mbedtls/bignum_internal.h vendored Normal file
View file

@ -0,0 +1,41 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_BIGNUM_INTERNAL_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_BIGNUM_INTERNAL_H_
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/platform.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define MPI_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA)
#define MPI_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE(cond)
#define ciL (sizeof(mbedtls_mpi_uint)) /* chars in limb */
#define biL (ciL << 3) /* bits in limb */
#define biH (ciL << 2) /* half limb size */
#define MPI_SIZE_T_MAX ((size_t)-1) /* SIZE_T_MAX is not standard */
/*
* Convert between bits/chars and number of limbs
* Divide first in order to avoid potential overflows
*/
#define BITS_TO_LIMBS(i) ((i) / biL + ((i) % biL != 0))
#define CHARS_TO_LIMBS(i) ((i) / ciL + ((i) % ciL != 0))
extern void (*Mul4x4)(uint64_t[8], const uint64_t[4], const uint64_t[4]);
extern void (*ShiftRight)(uint64_t *, size_t, unsigned char);
void ShiftRightAvx(uint64_t *, size_t, unsigned char);
void ShiftRightPure(uint64_t *, size_t, unsigned char);
void Mul4x4Adx(uint64_t[8], const uint64_t[4], const uint64_t[4]);
void Mul6x6Adx(uint64_t[12], const uint64_t[6], const uint64_t[6]);
void Mul8x8Adx(uint64_t[16], const uint64_t[8], const uint64_t[8]);
void Mul4x4Pure(uint64_t[16], const uint64_t[8], const uint64_t[8]);
void Mul(uint64_t *, uint64_t *, unsigned, uint64_t *, unsigned);
void Karatsuba(uint64_t *, uint64_t *, uint64_t *, size_t, uint64_t *);
void mbedtls_mpi_mul_hlp(size_t, uint64_t *, uint64_t *, uint64_t);
void mbedtls_mpi_mul_hlp1(size_t, const uint64_t *, uint64_t *, uint64_t);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_BIGNUM_INTERNAL_H_ */

121
third_party/mbedtls/bigshift.c vendored Normal file
View file

@ -0,0 +1,121 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/assert.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/platform.h"
/* clang-format off */
typedef long long xmm_t __attribute__((__vector_size__(16), __aligned__(1)));
static inline void shrd(mbedtls_mpi_uint *p, size_t n, size_t j, size_t m,
char k)
{
mbedtls_mpi_uint x, y, *e, *f;
f = p + m;
if (n)
{
y = 0;
x = p[j];
e = p + n;
for (; ++p < e; x = y)
{
y = p[j];
p[-1] = x >> k | y << (biL - k);
}
p[-1] = x >> k;
}
while (p < f)
*p++ = 0;
}
static inline void shld(mbedtls_mpi_uint *p, size_t n, size_t m, char k)
{
size_t i;
mbedtls_mpi_uint x, y;
MBEDTLS_ASSERT(n > m);
i = n - 1;
y = p[i - m];
for (; i - m > 0; --i, y = x)
{
x = p[i - m - 1];
p[i] = y << k | x >> (64 - k);
}
p[i] = y << k;
while (i)
{
p[--i] = 0;
}
}
/**
* Performs left shift on big number: X <<= k
*/
int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t k)
{
int r;
size_t b, n, m, l, z;
MPI_VALIDATE_RET(X);
l = mbedtls_mpi_bitlen(X);
b = l + k;
n = BITS_TO_LIMBS(b);
m = k / biL;
k = k % biL;
z = X->n;
if (n > X->n && (r = mbedtls_mpi_grow(X, n)))
return r;
if (k)
{
shld(X->p, X->n, m, k);
}
else if (m)
{
memmove_pure(X->p + m, X->p, (X->n - m) * ciL);
mbedtls_platform_zeroize(X->p, m * ciL);
}
return 0;
}
/**
* Performs right arithmetic shift on big number: X >>= k
*/
int mbedtls_mpi_shift_r(mbedtls_mpi *X, size_t k)
{
size_t n;
mbedtls_mpi_uint x, y;
MPI_VALIDATE_RET(X);
k = MIN(k, X->n * biL);
n = k / biL;
k = k % biL;
if (k)
{
if (!n)
ShiftRight(X->p, X->n, k);
else
shrd(X->p, X->n - n, n, X->n, k);
}
else if (n)
{
memmove_pure(X->p, X->p + n, (X->n - n) * ciL);
mbedtls_platform_zeroize(X->p + X->n - n, n * ciL);
}
return 0;
}

View file

@ -1,907 +0,0 @@
#ifndef MBEDTLS_BN_MUL_H
#define MBEDTLS_BN_MUL_H
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/config.h"
/* clang-format off */
#if defined(MBEDTLS_HAVE_ASM)
#ifndef asm
#define asm __asm
#endif
/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */
#if defined(__GNUC__) && \
( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 )
/*
* Disable use of the i386 assembly code below if option -O0, to disable all
* compiler optimisations, is passed, detected with __OPTIMIZE__
* This is done as the number of registers used in the assembly code doesn't
* work with the -O0 option.
*/
#if defined(__i386__) && defined(__OPTIMIZE__)
#define MULADDC_INIT \
asm( \
"movl %%ebx, %0 \n\t" \
"movl %5, %%esi \n\t" \
"movl %6, %%edi \n\t" \
"movl %7, %%ecx \n\t" \
"movl %8, %%ebx \n\t"
#define MULADDC_CORE \
"lodsl \n\t" \
"mull %%ebx \n\t" \
"addl %%ecx, %%eax \n\t" \
"adcl $0, %%edx \n\t" \
"addl (%%edi), %%eax \n\t" \
"adcl $0, %%edx \n\t" \
"movl %%edx, %%ecx \n\t" \
"stosl \n\t"
#if defined(MBEDTLS_HAVE_SSE2)
#define MULADDC_HUIT \
"movd %%ecx, %%mm1 \n\t" \
"movd %%ebx, %%mm0 \n\t" \
"movd (%%edi), %%mm3 \n\t" \
"paddq %%mm3, %%mm1 \n\t" \
"movd (%%esi), %%mm2 \n\t" \
"pmuludq %%mm0, %%mm2 \n\t" \
"movd 4(%%esi), %%mm4 \n\t" \
"pmuludq %%mm0, %%mm4 \n\t" \
"movd 8(%%esi), %%mm6 \n\t" \
"pmuludq %%mm0, %%mm6 \n\t" \
"movd 12(%%esi), %%mm7 \n\t" \
"pmuludq %%mm0, %%mm7 \n\t" \
"paddq %%mm2, %%mm1 \n\t" \
"movd 4(%%edi), %%mm3 \n\t" \
"paddq %%mm4, %%mm3 \n\t" \
"movd 8(%%edi), %%mm5 \n\t" \
"paddq %%mm6, %%mm5 \n\t" \
"movd 12(%%edi), %%mm4 \n\t" \
"paddq %%mm4, %%mm7 \n\t" \
"movd %%mm1, (%%edi) \n\t" \
"movd 16(%%esi), %%mm2 \n\t" \
"pmuludq %%mm0, %%mm2 \n\t" \
"psrlq $32, %%mm1 \n\t" \
"movd 20(%%esi), %%mm4 \n\t" \
"pmuludq %%mm0, %%mm4 \n\t" \
"paddq %%mm3, %%mm1 \n\t" \
"movd 24(%%esi), %%mm6 \n\t" \
"pmuludq %%mm0, %%mm6 \n\t" \
"movd %%mm1, 4(%%edi) \n\t" \
"psrlq $32, %%mm1 \n\t" \
"movd 28(%%esi), %%mm3 \n\t" \
"pmuludq %%mm0, %%mm3 \n\t" \
"paddq %%mm5, %%mm1 \n\t" \
"movd 16(%%edi), %%mm5 \n\t" \
"paddq %%mm5, %%mm2 \n\t" \
"movd %%mm1, 8(%%edi) \n\t" \
"psrlq $32, %%mm1 \n\t" \
"paddq %%mm7, %%mm1 \n\t" \
"movd 20(%%edi), %%mm5 \n\t" \
"paddq %%mm5, %%mm4 \n\t" \
"movd %%mm1, 12(%%edi) \n\t" \
"psrlq $32, %%mm1 \n\t" \
"paddq %%mm2, %%mm1 \n\t" \
"movd 24(%%edi), %%mm5 \n\t" \
"paddq %%mm5, %%mm6 \n\t" \
"movd %%mm1, 16(%%edi) \n\t" \
"psrlq $32, %%mm1 \n\t" \
"paddq %%mm4, %%mm1 \n\t" \
"movd 28(%%edi), %%mm5 \n\t" \
"paddq %%mm5, %%mm3 \n\t" \
"movd %%mm1, 20(%%edi) \n\t" \
"psrlq $32, %%mm1 \n\t" \
"paddq %%mm6, %%mm1 \n\t" \
"movd %%mm1, 24(%%edi) \n\t" \
"psrlq $32, %%mm1 \n\t" \
"paddq %%mm3, %%mm1 \n\t" \
"movd %%mm1, 28(%%edi) \n\t" \
"addl $32, %%edi \n\t" \
"addl $32, %%esi \n\t" \
"psrlq $32, %%mm1 \n\t" \
"movd %%mm1, %%ecx \n\t"
#define MULADDC_STOP \
"emms \n\t" \
"movl %4, %%ebx \n\t" \
"movl %%ecx, %1 \n\t" \
"movl %%edi, %2 \n\t" \
"movl %%esi, %3 \n\t" \
: "=m" (t), "=m" (c), "=m" (d), "=m" (s) \
: "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \
: "eax", "ebx", "ecx", "edx", "esi", "edi" \
);
#else
#define MULADDC_STOP \
"movl %4, %%ebx \n\t" \
"movl %%ecx, %1 \n\t" \
"movl %%edi, %2 \n\t" \
"movl %%esi, %3 \n\t" \
: "=m" (t), "=m" (c), "=m" (d), "=m" (s) \
: "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \
: "eax", "ebx", "ecx", "edx", "esi", "edi" \
);
#endif /* SSE2 */
#endif /* i386 */
#if defined(__amd64__) || defined (__x86_64__)
#if 1
#define MULADDC_INIT \
asm( \
"xorq %%r8, %%r8\n"
#define MULADDC_CORE \
"movq (%%rsi), %%rax\n" \
"mulq %%rbx\n" \
"addq $8, %%rsi\n" \
"addq %%rcx, %%rax\n" \
"movq %%r8, %%rcx\n" \
"adcq $0, %%rdx\n" \
"nop \n" \
"addq %%rax, (%%rdi)\n" \
"adcq %%rdx, %%rcx\n" \
"addq $8, %%rdi\n"
#define MULADDC_STOP \
: "+c" (c), "+D" (d), "+S" (s) \
: "b" (b) \
: "rax", "rdx", "r8" \
);
#else
#define MULADDC_INIT
#define MULADDC_STOP
#define MULADDC_CORE \
ax = *s++; \
axdx = (uint128_t)ax * b + c; \
t = *d; \
*d++ = t + (uint64_t)axdx; \
c = (t + (uint64_t)axdx < t) + (uint64_t)(axdx >> 64);
#endif
#endif /* AMD64 */
#if defined(__aarch64__)
#define MULADDC_INIT \
asm(
#define MULADDC_CORE \
"ldr x4, [%2], #8 \n\t" \
"ldr x5, [%1] \n\t" \
"mul x6, x4, %3 \n\t" \
"umulh x7, x4, %3 \n\t" \
"adds x5, x5, x6 \n\t" \
"adc x7, x7, xzr \n\t" \
"adds x5, x5, %0 \n\t" \
"adc %0, x7, xzr \n\t" \
"str x5, [%1], #8 \n\t"
#define MULADDC_STOP \
: "+r" (c), "+r" (d), "+r" (s) \
: "r" (b) \
: "x4", "x5", "x6", "x7", "cc" \
);
#endif /* Aarch64 */
#if defined(__mc68020__) || defined(__mcpu32__)
#define MULADDC_INIT \
asm( \
"movl %3, %%a2 \n\t" \
"movl %4, %%a3 \n\t" \
"movl %5, %%d3 \n\t" \
"movl %6, %%d2 \n\t" \
"moveq #0, %%d0 \n\t"
#define MULADDC_CORE \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d4:%%d1 \n\t" \
"addl %%d3, %%d1 \n\t" \
"addxl %%d0, %%d4 \n\t" \
"moveq #0, %%d3 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"addxl %%d4, %%d3 \n\t"
#define MULADDC_STOP \
"movl %%d3, %0 \n\t" \
"movl %%a3, %1 \n\t" \
"movl %%a2, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "d0", "d1", "d2", "d3", "d4", "a2", "a3" \
);
#define MULADDC_HUIT \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d4:%%d1 \n\t" \
"addxl %%d3, %%d1 \n\t" \
"addxl %%d0, %%d4 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d3:%%d1 \n\t" \
"addxl %%d4, %%d1 \n\t" \
"addxl %%d0, %%d3 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d4:%%d1 \n\t" \
"addxl %%d3, %%d1 \n\t" \
"addxl %%d0, %%d4 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d3:%%d1 \n\t" \
"addxl %%d4, %%d1 \n\t" \
"addxl %%d0, %%d3 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d4:%%d1 \n\t" \
"addxl %%d3, %%d1 \n\t" \
"addxl %%d0, %%d4 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d3:%%d1 \n\t" \
"addxl %%d4, %%d1 \n\t" \
"addxl %%d0, %%d3 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d4:%%d1 \n\t" \
"addxl %%d3, %%d1 \n\t" \
"addxl %%d0, %%d4 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"movel %%a2@+, %%d1 \n\t" \
"mulul %%d2, %%d3:%%d1 \n\t" \
"addxl %%d4, %%d1 \n\t" \
"addxl %%d0, %%d3 \n\t" \
"addl %%d1, %%a3@+ \n\t" \
"addxl %%d0, %%d3 \n\t"
#endif /* MC68000 */
#if defined(__powerpc64__) || defined(__ppc64__)
#if defined(__MACH__) && defined(__APPLE__)
#define MULADDC_INIT \
asm( \
"ld r3, %3 \n\t" \
"ld r4, %4 \n\t" \
"ld r5, %5 \n\t" \
"ld r6, %6 \n\t" \
"addi r3, r3, -8 \n\t" \
"addi r4, r4, -8 \n\t" \
"addic r5, r5, 0 \n\t"
#define MULADDC_CORE \
"ldu r7, 8(r3) \n\t" \
"mulld r8, r7, r6 \n\t" \
"mulhdu r9, r7, r6 \n\t" \
"adde r8, r8, r5 \n\t" \
"ld r7, 8(r4) \n\t" \
"addze r5, r9 \n\t" \
"addc r8, r8, r7 \n\t" \
"stdu r8, 8(r4) \n\t"
#define MULADDC_STOP \
"addze r5, r5 \n\t" \
"addi r4, r4, 8 \n\t" \
"addi r3, r3, 8 \n\t" \
"std r5, %0 \n\t" \
"std r4, %1 \n\t" \
"std r3, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r3", "r4", "r5", "r6", "r7", "r8", "r9" \
);
#else /* __MACH__ && __APPLE__ */
#define MULADDC_INIT \
asm( \
"ld %%r3, %3 \n\t" \
"ld %%r4, %4 \n\t" \
"ld %%r5, %5 \n\t" \
"ld %%r6, %6 \n\t" \
"addi %%r3, %%r3, -8 \n\t" \
"addi %%r4, %%r4, -8 \n\t" \
"addic %%r5, %%r5, 0 \n\t"
#define MULADDC_CORE \
"ldu %%r7, 8(%%r3) \n\t" \
"mulld %%r8, %%r7, %%r6 \n\t" \
"mulhdu %%r9, %%r7, %%r6 \n\t" \
"adde %%r8, %%r8, %%r5 \n\t" \
"ld %%r7, 8(%%r4) \n\t" \
"addze %%r5, %%r9 \n\t" \
"addc %%r8, %%r8, %%r7 \n\t" \
"stdu %%r8, 8(%%r4) \n\t"
#define MULADDC_STOP \
"addze %%r5, %%r5 \n\t" \
"addi %%r4, %%r4, 8 \n\t" \
"addi %%r3, %%r3, 8 \n\t" \
"std %%r5, %0 \n\t" \
"std %%r4, %1 \n\t" \
"std %%r3, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r3", "r4", "r5", "r6", "r7", "r8", "r9" \
);
#endif /* __MACH__ && __APPLE__ */
#elif defined(__powerpc__) || defined(__ppc__) /* end PPC64/begin PPC32 */
#if defined(__MACH__) && defined(__APPLE__)
#define MULADDC_INIT \
asm( \
"lwz r3, %3 \n\t" \
"lwz r4, %4 \n\t" \
"lwz r5, %5 \n\t" \
"lwz r6, %6 \n\t" \
"addi r3, r3, -4 \n\t" \
"addi r4, r4, -4 \n\t" \
"addic r5, r5, 0 \n\t"
#define MULADDC_CORE \
"lwzu r7, 4(r3) \n\t" \
"mullw r8, r7, r6 \n\t" \
"mulhwu r9, r7, r6 \n\t" \
"adde r8, r8, r5 \n\t" \
"lwz r7, 4(r4) \n\t" \
"addze r5, r9 \n\t" \
"addc r8, r8, r7 \n\t" \
"stwu r8, 4(r4) \n\t"
#define MULADDC_STOP \
"addze r5, r5 \n\t" \
"addi r4, r4, 4 \n\t" \
"addi r3, r3, 4 \n\t" \
"stw r5, %0 \n\t" \
"stw r4, %1 \n\t" \
"stw r3, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r3", "r4", "r5", "r6", "r7", "r8", "r9" \
);
#else /* __MACH__ && __APPLE__ */
#define MULADDC_INIT \
asm( \
"lwz %%r3, %3 \n\t" \
"lwz %%r4, %4 \n\t" \
"lwz %%r5, %5 \n\t" \
"lwz %%r6, %6 \n\t" \
"addi %%r3, %%r3, -4 \n\t" \
"addi %%r4, %%r4, -4 \n\t" \
"addic %%r5, %%r5, 0 \n\t"
#define MULADDC_CORE \
"lwzu %%r7, 4(%%r3) \n\t" \
"mullw %%r8, %%r7, %%r6 \n\t" \
"mulhwu %%r9, %%r7, %%r6 \n\t" \
"adde %%r8, %%r8, %%r5 \n\t" \
"lwz %%r7, 4(%%r4) \n\t" \
"addze %%r5, %%r9 \n\t" \
"addc %%r8, %%r8, %%r7 \n\t" \
"stwu %%r8, 4(%%r4) \n\t"
#define MULADDC_STOP \
"addze %%r5, %%r5 \n\t" \
"addi %%r4, %%r4, 4 \n\t" \
"addi %%r3, %%r3, 4 \n\t" \
"stw %%r5, %0 \n\t" \
"stw %%r4, %1 \n\t" \
"stw %%r3, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r3", "r4", "r5", "r6", "r7", "r8", "r9" \
);
#endif /* __MACH__ && __APPLE__ */
#endif /* PPC32 */
/*
* The Sparc(64) assembly is reported to be broken.
* Disable it for now, until we're able to fix it.
*/
#if 0 && defined(__sparc__)
#if defined(__sparc64__)
#define MULADDC_INIT \
asm( \
"ldx %3, %%o0 \n\t" \
"ldx %4, %%o1 \n\t" \
"ld %5, %%o2 \n\t" \
"ld %6, %%o3 \n\t"
#define MULADDC_CORE \
"ld [%%o0], %%o4 \n\t" \
"inc 4, %%o0 \n\t" \
"ld [%%o1], %%o5 \n\t" \
"umul %%o3, %%o4, %%o4 \n\t" \
"addcc %%o4, %%o2, %%o4 \n\t" \
"rd %%y, %%g1 \n\t" \
"addx %%g1, 0, %%g1 \n\t" \
"addcc %%o4, %%o5, %%o4 \n\t" \
"st %%o4, [%%o1] \n\t" \
"addx %%g1, 0, %%o2 \n\t" \
"inc 4, %%o1 \n\t"
#define MULADDC_STOP \
"st %%o2, %0 \n\t" \
"stx %%o1, %1 \n\t" \
"stx %%o0, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "g1", "o0", "o1", "o2", "o3", "o4", \
"o5" \
);
#else /* __sparc64__ */
#define MULADDC_INIT \
asm( \
"ld %3, %%o0 \n\t" \
"ld %4, %%o1 \n\t" \
"ld %5, %%o2 \n\t" \
"ld %6, %%o3 \n\t"
#define MULADDC_CORE \
"ld [%%o0], %%o4 \n\t" \
"inc 4, %%o0 \n\t" \
"ld [%%o1], %%o5 \n\t" \
"umul %%o3, %%o4, %%o4 \n\t" \
"addcc %%o4, %%o2, %%o4 \n\t" \
"rd %%y, %%g1 \n\t" \
"addx %%g1, 0, %%g1 \n\t" \
"addcc %%o4, %%o5, %%o4 \n\t" \
"st %%o4, [%%o1] \n\t" \
"addx %%g1, 0, %%o2 \n\t" \
"inc 4, %%o1 \n\t"
#define MULADDC_STOP \
"st %%o2, %0 \n\t" \
"st %%o1, %1 \n\t" \
"st %%o0, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "g1", "o0", "o1", "o2", "o3", "o4", \
"o5" \
);
#endif /* __sparc64__ */
#endif /* __sparc__ */
#if defined(__microblaze__) || defined(microblaze)
#define MULADDC_INIT \
asm( \
"lwi r3, %3 \n\t" \
"lwi r4, %4 \n\t" \
"lwi r5, %5 \n\t" \
"lwi r6, %6 \n\t" \
"andi r7, r6, 0xffff \n\t" \
"bsrli r6, r6, 16 \n\t"
#define MULADDC_CORE \
"lhui r8, r3, 0 \n\t" \
"addi r3, r3, 2 \n\t" \
"lhui r9, r3, 0 \n\t" \
"addi r3, r3, 2 \n\t" \
"mul r10, r9, r6 \n\t" \
"mul r11, r8, r7 \n\t" \
"mul r12, r9, r7 \n\t" \
"mul r13, r8, r6 \n\t" \
"bsrli r8, r10, 16 \n\t" \
"bsrli r9, r11, 16 \n\t" \
"add r13, r13, r8 \n\t" \
"add r13, r13, r9 \n\t" \
"bslli r10, r10, 16 \n\t" \
"bslli r11, r11, 16 \n\t" \
"add r12, r12, r10 \n\t" \
"addc r13, r13, r0 \n\t" \
"add r12, r12, r11 \n\t" \
"addc r13, r13, r0 \n\t" \
"lwi r10, r4, 0 \n\t" \
"add r12, r12, r10 \n\t" \
"addc r13, r13, r0 \n\t" \
"add r12, r12, r5 \n\t" \
"addc r5, r13, r0 \n\t" \
"swi r12, r4, 0 \n\t" \
"addi r4, r4, 4 \n\t"
#define MULADDC_STOP \
"swi r5, %0 \n\t" \
"swi r4, %1 \n\t" \
"swi r3, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r3", "r4", "r5", "r6", "r7", "r8", \
"r9", "r10", "r11", "r12", "r13" \
);
#endif /* MicroBlaze */
#if defined(__tricore__)
#define MULADDC_INIT \
asm( \
"ld.a %%a2, %3 \n\t" \
"ld.a %%a3, %4 \n\t" \
"ld.w %%d4, %5 \n\t" \
"ld.w %%d1, %6 \n\t" \
"xor %%d5, %%d5 \n\t"
#define MULADDC_CORE \
"ld.w %%d0, [%%a2+] \n\t" \
"madd.u %%e2, %%e4, %%d0, %%d1 \n\t" \
"ld.w %%d0, [%%a3] \n\t" \
"addx %%d2, %%d2, %%d0 \n\t" \
"addc %%d3, %%d3, 0 \n\t" \
"mov %%d4, %%d3 \n\t" \
"st.w [%%a3+], %%d2 \n\t"
#define MULADDC_STOP \
"st.w %0, %%d4 \n\t" \
"st.a %1, %%a3 \n\t" \
"st.a %2, %%a2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "d0", "d1", "e2", "d4", "a2", "a3" \
);
#endif /* TriCore */
/*
* Note, gcc -O0 by default uses r7 for the frame pointer, so it complains about
* our use of r7 below, unless -fomit-frame-pointer is passed.
*
* On the other hand, -fomit-frame-pointer is implied by any -Ox options with
* x !=0, which we can detect using __OPTIMIZE__ (which is also defined by
* clang and armcc5 under the same conditions).
*
* So, only use the optimized assembly below for optimized build, which avoids
* the build error and is pretty reasonable anyway.
*/
#if defined(__GNUC__) && !defined(__OPTIMIZE__)
#define MULADDC_CANNOT_USE_R7
#endif
#if defined(__arm__) && !defined(MULADDC_CANNOT_USE_R7)
#if defined(__thumb__) && !defined(__thumb2__)
#define MULADDC_INIT \
asm( \
"ldr r0, %3 \n\t" \
"ldr r1, %4 \n\t" \
"ldr r2, %5 \n\t" \
"ldr r3, %6 \n\t" \
"lsr r7, r3, #16 \n\t" \
"mov r9, r7 \n\t" \
"lsl r7, r3, #16 \n\t" \
"lsr r7, r7, #16 \n\t" \
"mov r8, r7 \n\t"
#define MULADDC_CORE \
"ldmia r0!, {r6} \n\t" \
"lsr r7, r6, #16 \n\t" \
"lsl r6, r6, #16 \n\t" \
"lsr r6, r6, #16 \n\t" \
"mov r4, r8 \n\t" \
"mul r4, r6 \n\t" \
"mov r3, r9 \n\t" \
"mul r6, r3 \n\t" \
"mov r5, r9 \n\t" \
"mul r5, r7 \n\t" \
"mov r3, r8 \n\t" \
"mul r7, r3 \n\t" \
"lsr r3, r6, #16 \n\t" \
"add r5, r5, r3 \n\t" \
"lsr r3, r7, #16 \n\t" \
"add r5, r5, r3 \n\t" \
"add r4, r4, r2 \n\t" \
"mov r2, #0 \n\t" \
"adc r5, r2 \n\t" \
"lsl r3, r6, #16 \n\t" \
"add r4, r4, r3 \n\t" \
"adc r5, r2 \n\t" \
"lsl r3, r7, #16 \n\t" \
"add r4, r4, r3 \n\t" \
"adc r5, r2 \n\t" \
"ldr r3, [r1] \n\t" \
"add r4, r4, r3 \n\t" \
"adc r2, r5 \n\t" \
"stmia r1!, {r4} \n\t"
#define MULADDC_STOP \
"str r2, %0 \n\t" \
"str r1, %1 \n\t" \
"str r0, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r0", "r1", "r2", "r3", "r4", "r5", \
"r6", "r7", "r8", "r9", "cc" \
);
#elif (__ARM_ARCH >= 6) && \
defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1)
#define MULADDC_INIT \
asm(
#define MULADDC_CORE \
"ldr r0, [%0], #4 \n\t" \
"ldr r1, [%1] \n\t" \
"umaal r1, %2, %3, r0 \n\t" \
"str r1, [%1], #4 \n\t"
#define MULADDC_STOP \
: "=r" (s), "=r" (d), "=r" (c) \
: "r" (b), "0" (s), "1" (d), "2" (c) \
: "r0", "r1", "memory" \
);
#else
#define MULADDC_INIT \
asm( \
"ldr r0, %3 \n\t" \
"ldr r1, %4 \n\t" \
"ldr r2, %5 \n\t" \
"ldr r3, %6 \n\t"
#define MULADDC_CORE \
"ldr r4, [r0], #4 \n\t" \
"mov r5, #0 \n\t" \
"ldr r6, [r1] \n\t" \
"umlal r2, r5, r3, r4 \n\t" \
"adds r7, r6, r2 \n\t" \
"adc r2, r5, #0 \n\t" \
"str r7, [r1], #4 \n\t"
#define MULADDC_STOP \
"str r2, %0 \n\t" \
"str r1, %1 \n\t" \
"str r0, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r0", "r1", "r2", "r3", "r4", "r5", \
"r6", "r7", "cc" \
);
#endif /* Thumb */
#endif /* ARMv3 */
#if defined(__alpha__)
#define MULADDC_INIT \
asm( \
"ldq $1, %3 \n\t" \
"ldq $2, %4 \n\t" \
"ldq $3, %5 \n\t" \
"ldq $4, %6 \n\t"
#define MULADDC_CORE \
"ldq $6, 0($1) \n\t" \
"addq $1, 8, $1 \n\t" \
"mulq $6, $4, $7 \n\t" \
"umulh $6, $4, $6 \n\t" \
"addq $7, $3, $7 \n\t" \
"cmpult $7, $3, $3 \n\t" \
"ldq $5, 0($2) \n\t" \
"addq $7, $5, $7 \n\t" \
"cmpult $7, $5, $5 \n\t" \
"stq $7, 0($2) \n\t" \
"addq $2, 8, $2 \n\t" \
"addq $6, $3, $3 \n\t" \
"addq $5, $3, $3 \n\t"
#define MULADDC_STOP \
"stq $3, %0 \n\t" \
"stq $2, %1 \n\t" \
"stq $1, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "$1", "$2", "$3", "$4", "$5", "$6", "$7" \
);
#endif /* Alpha */
#if defined(__mips__) && !defined(__mips64)
#define MULADDC_INIT \
asm( \
"lw $10, %3 \n\t" \
"lw $11, %4 \n\t" \
"lw $12, %5 \n\t" \
"lw $13, %6 \n\t"
#define MULADDC_CORE \
"lw $14, 0($10) \n\t" \
"multu $13, $14 \n\t" \
"addi $10, $10, 4 \n\t" \
"mflo $14 \n\t" \
"mfhi $9 \n\t" \
"addu $14, $12, $14 \n\t" \
"lw $15, 0($11) \n\t" \
"sltu $12, $14, $12 \n\t" \
"addu $15, $14, $15 \n\t" \
"sltu $14, $15, $14 \n\t" \
"addu $12, $12, $9 \n\t" \
"sw $15, 0($11) \n\t" \
"addu $12, $12, $14 \n\t" \
"addi $11, $11, 4 \n\t"
#define MULADDC_STOP \
"sw $12, %0 \n\t" \
"sw $11, %1 \n\t" \
"sw $10, %2 \n\t" \
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "$9", "$10", "$11", "$12", "$13", "$14", "$15", "lo", "hi" \
);
#endif /* MIPS */
#endif /* GNUC */
#if (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
#define MULADDC_INIT \
__asm mov esi, s \
__asm mov edi, d \
__asm mov ecx, c \
__asm mov ebx, b
#define MULADDC_CORE \
__asm lodsd \
__asm mul ebx \
__asm add eax, ecx \
__asm adc edx, 0 \
__asm add eax, [edi] \
__asm adc edx, 0 \
__asm mov ecx, edx \
__asm stosd
#if defined(MBEDTLS_HAVE_SSE2)
#define EMIT __asm _emit
#define MULADDC_HUIT \
EMIT 0x0F EMIT 0x6E EMIT 0xC9 \
EMIT 0x0F EMIT 0x6E EMIT 0xC3 \
EMIT 0x0F EMIT 0x6E EMIT 0x1F \
EMIT 0x0F EMIT 0xD4 EMIT 0xCB \
EMIT 0x0F EMIT 0x6E EMIT 0x16 \
EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \
EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x04 \
EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \
EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x08 \
EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \
EMIT 0x0F EMIT 0x6E EMIT 0x7E EMIT 0x0C \
EMIT 0x0F EMIT 0xF4 EMIT 0xF8 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCA \
EMIT 0x0F EMIT 0x6E EMIT 0x5F EMIT 0x04 \
EMIT 0x0F EMIT 0xD4 EMIT 0xDC \
EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x08 \
EMIT 0x0F EMIT 0xD4 EMIT 0xEE \
EMIT 0x0F EMIT 0x6E EMIT 0x67 EMIT 0x0C \
EMIT 0x0F EMIT 0xD4 EMIT 0xFC \
EMIT 0x0F EMIT 0x7E EMIT 0x0F \
EMIT 0x0F EMIT 0x6E EMIT 0x56 EMIT 0x10 \
EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x14 \
EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCB \
EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x18 \
EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \
EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x04 \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0x6E EMIT 0x5E EMIT 0x1C \
EMIT 0x0F EMIT 0xF4 EMIT 0xD8 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCD \
EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x10 \
EMIT 0x0F EMIT 0xD4 EMIT 0xD5 \
EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x08 \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCF \
EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x14 \
EMIT 0x0F EMIT 0xD4 EMIT 0xE5 \
EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x0C \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCA \
EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x18 \
EMIT 0x0F EMIT 0xD4 EMIT 0xF5 \
EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x10 \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCC \
EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x1C \
EMIT 0x0F EMIT 0xD4 EMIT 0xDD \
EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x14 \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCE \
EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x18 \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0xD4 EMIT 0xCB \
EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x1C \
EMIT 0x83 EMIT 0xC7 EMIT 0x20 \
EMIT 0x83 EMIT 0xC6 EMIT 0x20 \
EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
EMIT 0x0F EMIT 0x7E EMIT 0xC9
#define MULADDC_STOP \
EMIT 0x0F EMIT 0x77 \
__asm mov c, ecx \
__asm mov d, edi \
__asm mov s, esi \
#else
#define MULADDC_STOP \
__asm mov c, ecx \
__asm mov d, edi \
__asm mov s, esi \
#endif /* SSE2 */
#endif /* MSVC */
#endif /* MBEDTLS_HAVE_ASM */
#if !defined(MULADDC_CORE)
#if defined(MBEDTLS_HAVE_UDBL)
#define MULADDC_INIT \
{ \
mbedtls_t_udbl r; \
mbedtls_mpi_uint r0, r1;
#define MULADDC_CORE \
r = *(s++) * (mbedtls_t_udbl) b; \
r0 = (mbedtls_mpi_uint) r; \
r1 = (mbedtls_mpi_uint)( r >> biL ); \
r0 += c; r1 += (r0 < c); \
r0 += *d; r1 += (r0 < *d); \
c = r1; *(d++) = r0;
#define MULADDC_STOP \
}
#else
#define MULADDC_INIT \
{ \
mbedtls_mpi_uint s0, s1, b0, b1; \
mbedtls_mpi_uint r0, r1, rx, ry; \
b0 = ( b << biH ) >> biH; \
b1 = ( b >> biH );
#define MULADDC_CORE \
s0 = ( *s << biH ) >> biH; \
s1 = ( *s >> biH ); s++; \
rx = s0 * b1; r0 = s0 * b0; \
ry = s1 * b0; r1 = s1 * b1; \
r1 += ( rx >> biH ); \
r1 += ( ry >> biH ); \
rx <<= biH; ry <<= biH; \
r0 += rx; r1 += (r0 < rx); \
r0 += ry; r1 += (r0 < ry); \
r0 += c; r1 += (r0 < c); \
r0 += *d; r1 += (r0 < *d); \
c = r1; *(d++) = r0;
#define MULADDC_STOP \
}
#endif /* C (generic) */
#endif /* C (longlong) */
#endif /* bn_mul.h */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/ccm.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
@ -8,32 +25,13 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* NIST SP800-38C compliant CCM implementation
*
* Copyright The Mbed TLS Contributors
* 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.
*/
/**
* \file ccm.c
* @fileoverview NIST SP800-38C compliant CCM implementation
*
* \brief This file provides an API for the CCM authenticated encryption
* mode for block ciphers.
* This file provides an API for the CCM authenticated encryption mode
* for block ciphers.
*
* CCM combines Counter mode encryption with CBC-MAC authentication
* for 128-bit block ciphers.
@ -76,8 +74,8 @@ asm(".include \"libc/disclaimer.inc\"");
*/
void mbedtls_ccm_init( mbedtls_ccm_context *ctx )
{
CCM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_ccm_context ) );
CCM_VALIDATE( ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) );
}
/**
@ -98,31 +96,24 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
const unsigned char *key,
unsigned int keybits )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const mbedtls_cipher_info_t *cipher_info;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( key != NULL );
CCM_VALIDATE_RET( ctx );
CCM_VALIDATE_RET( key );
cipher_info = mbedtls_cipher_info_from_values( cipher, keybits,
MBEDTLS_MODE_ECB );
if( cipher_info == NULL )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if( cipher_info->block_size != 16 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
mbedtls_cipher_free( &ctx->cipher_ctx );
if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )
return( ret );
if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,
MBEDTLS_ENCRYPT ) ) != 0 )
{
return( ret );
}
return( 0 );
}
@ -184,7 +175,7 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char i;
unsigned char q;
size_t len_left, olen;
@ -395,12 +386,12 @@ int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
CCM_VALIDATE_RET( ctx );
CCM_VALIDATE_RET( iv );
CCM_VALIDATE_RET( add_len == 0 || add );
CCM_VALIDATE_RET( length == 0 || input );
CCM_VALIDATE_RET( length == 0 || output );
CCM_VALIDATE_RET( tag_len == 0 || tag );
return( ccm_auth_crypt( ctx, CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len ) );
}
@ -447,12 +438,12 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
CCM_VALIDATE_RET( ctx );
CCM_VALIDATE_RET( iv );
CCM_VALIDATE_RET( add_len == 0 || add );
CCM_VALIDATE_RET( length == 0 || input );
CCM_VALIDATE_RET( length == 0 || output );
CCM_VALIDATE_RET( tag_len == 0 || tag );
if( tag_len == 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
@ -505,17 +496,17 @@ int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char check_tag[16];
unsigned char i;
int diff;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
CCM_VALIDATE_RET( ctx );
CCM_VALIDATE_RET( iv );
CCM_VALIDATE_RET( add_len == 0 || add );
CCM_VALIDATE_RET( length == 0 || input );
CCM_VALIDATE_RET( length == 0 || output );
CCM_VALIDATE_RET( tag_len == 0 || tag );
if( ( ret = ccm_auth_crypt( ctx, CCM_DECRYPT, length,
iv, iv_len, add, add_len,
@ -569,21 +560,19 @@ int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
* match. \return A cipher-specific error code on calculation failure.
*/
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( tag_len == 0 )
CCM_VALIDATE_RET( ctx );
CCM_VALIDATE_RET( iv );
CCM_VALIDATE_RET( add || !add_len );
CCM_VALIDATE_RET( input || !length );
CCM_VALIDATE_RET( output || !length );
CCM_VALIDATE_RET( tag || !tag_len );
if( !tag_len )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
return( mbedtls_ccm_star_auth_decrypt( ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len ) );
}
@ -654,7 +643,7 @@ int mbedtls_ccm_self_test( int verbose )
unsigned char plaintext[CCM_SELFTEST_PT_MAX_LEN];
unsigned char ciphertext[CCM_SELFTEST_CT_MAX_LEN];
size_t i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ccm_init( &ctx );
@ -672,8 +661,8 @@ int mbedtls_ccm_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( " CCM-AES #%u: ", (unsigned int) i + 1 );
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
memset( ciphertext, 0, CCM_SELFTEST_CT_MAX_LEN );
mbedtls_platform_zeroize( plaintext, CCM_SELFTEST_PT_MAX_LEN );
mbedtls_platform_zeroize( ciphertext, CCM_SELFTEST_CT_MAX_LEN );
memcpy( plaintext, msg_test_data, msg_len_test_data[i] );
ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len_test_data[i],
@ -692,7 +681,7 @@ int mbedtls_ccm_self_test( int verbose )
return( 1 );
}
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
mbedtls_platform_zeroize( plaintext, CCM_SELFTEST_PT_MAX_LEN );
ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len_test_data[i],
iv_test_data, iv_len_test_data[i],

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/certs.h"
#include "third_party/mbedtls/common.h"
@ -6,26 +23,7 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* X.509 test certificates
*
* Copyright The Mbed TLS Contributors
* 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.
*/
#if defined(MBEDTLS_CERTS_C)

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "libc/stdio/stdio.h"
#include "third_party/mbedtls/chacha20.h"
@ -10,30 +27,7 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/**
* \file chacha20.c
*
* \brief ChaCha20 cipher.
*
* \author Daniel King <damaki.gh@gmail.com>
*
* Copyright The Mbed TLS Contributors
* 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.
*/
/* Parameter validation macros */
#define CHACHA20_VALIDATE_RET( cond ) \
@ -384,7 +378,7 @@ int mbedtls_chacha20_crypt( const unsigned char key[32],
unsigned char* output )
{
mbedtls_chacha20_context ctx;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
CHACHA20_VALIDATE_RET( key != NULL );
CHACHA20_VALIDATE_RET( nonce != NULL );
@ -602,7 +596,7 @@ int mbedtls_chacha20_self_test( int verbose )
{
unsigned char output[381];
unsigned i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
for( i = 0U; i < 2U; i++ )
{

View file

@ -1,4 +1,22 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/chachapoly.h"
#include "third_party/mbedtls/chk.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/platform.h"
@ -8,27 +26,10 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/**
* \file chachapoly.c
*
* \brief ChaCha20-Poly1305 AEAD construction based on RFC 7539.
*
* Copyright The Mbed TLS Contributors
* 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.
* @fileoverview ChaCha20-Poly1305 AEAD construction based on RFC 7539.
*/
#if defined(MBEDTLS_CHACHAPOLY_C)
@ -59,7 +60,7 @@ static int chachapoly_pad_aad( mbedtls_chachapoly_context *ctx )
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
mbedtls_platform_zeroize( zeroes, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
@ -79,7 +80,7 @@ static int chachapoly_pad_ciphertext( mbedtls_chachapoly_context *ctx )
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
mbedtls_platform_zeroize( zeroes, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
@ -87,7 +88,7 @@ static int chachapoly_pad_ciphertext( mbedtls_chachapoly_context *ctx )
void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx )
{
CHACHAPOLY_VALIDATE( ctx != NULL );
CHACHAPOLY_VALIDATE( ctx );
mbedtls_chacha20_init( &ctx->chacha20_ctx );
mbedtls_poly1305_init( &ctx->poly1305_ctx );
@ -113,12 +114,10 @@ void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx )
int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,
const unsigned char key[32] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( key != NULL );
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
CHACHAPOLY_VALIDATE_RET( ctx );
CHACHAPOLY_VALIDATE_RET( key );
ret = mbedtls_chacha20_setkey( &ctx->chacha20_ctx, key );
return( ret );
}
@ -126,26 +125,22 @@ int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
const unsigned char nonce[12],
mbedtls_chachapoly_mode_t mode )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char poly1305_key[64];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( ctx );
CHACHAPOLY_VALIDATE_RET( nonce );
/* Set counter = 0, will be update to 1 when generating Poly1305 key */
ret = mbedtls_chacha20_starts( &ctx->chacha20_ctx, nonce, 0U );
if( ret != 0 )
goto cleanup;
MBEDTLS_CHK( mbedtls_chacha20_starts( &ctx->chacha20_ctx, nonce, 0U ) );
/* Generate the Poly1305 key by getting the ChaCha20 keystream output with
* counter = 0. This is the same as encrypting a buffer of zeroes.
* Only the first 256-bits (32 bytes) of the key is used for Poly1305.
* The other 256 bits are discarded.
*/
memset( poly1305_key, 0, sizeof( poly1305_key ) );
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, sizeof( poly1305_key ),
poly1305_key, poly1305_key );
if( ret != 0 )
goto cleanup;
mbedtls_platform_zeroize( poly1305_key, sizeof( poly1305_key ) );
MBEDTLS_CHK( mbedtls_chacha20_update( &ctx->chacha20_ctx, sizeof( poly1305_key ),
poly1305_key, poly1305_key ) );
ret = mbedtls_poly1305_starts( &ctx->poly1305_ctx, poly1305_key );
@ -166,8 +161,8 @@ int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,
const unsigned char *aad,
size_t aad_len )
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( ctx );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad );
if( ctx->state != CHACHAPOLY_STATE_AAD )
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
@ -182,10 +177,10 @@ int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || output != NULL );
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
CHACHAPOLY_VALIDATE_RET( ctx );
CHACHAPOLY_VALIDATE_RET( len == 0 || input );
CHACHAPOLY_VALIDATE_RET( len == 0 || output );
if( ( ctx->state != CHACHAPOLY_STATE_AAD ) &&
( ctx->state != CHACHAPOLY_STATE_CIPHERTEXT ) )
@ -231,16 +226,14 @@ int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,
int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
unsigned char mac[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char len_block[16];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( mac != NULL );
CHACHAPOLY_VALIDATE_RET( ctx );
CHACHAPOLY_VALIDATE_RET( mac );
if( ctx->state == CHACHAPOLY_STATE_INIT )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
}
if( ctx->state == CHACHAPOLY_STATE_AAD )
{
ret = chachapoly_pad_aad( ctx );
@ -253,9 +246,7 @@ int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
if( ret != 0 )
return( ret );
}
ctx->state = CHACHAPOLY_STATE_FINISHED;
/* The lengths of the AAD and ciphertext are processed by
* Poly1305 as the final 128-bit block, encoded as little-endian integers.
*/
@ -275,13 +266,10 @@ int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
len_block[13] = (unsigned char)( ctx->ciphertext_len >> 40 );
len_block[14] = (unsigned char)( ctx->ciphertext_len >> 48 );
len_block[15] = (unsigned char)( ctx->ciphertext_len >> 56 );
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, len_block, 16U );
if( ret != 0 )
return( ret );
ret = mbedtls_poly1305_finish( &ctx->poly1305_ctx, mac );
return( ret );
}
@ -295,22 +283,11 @@ static int chachapoly_crypt_and_tag( mbedtls_chachapoly_context *ctx,
unsigned char *output,
unsigned char tag[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_chachapoly_starts( ctx, nonce, mode );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_update_aad( ctx, aad, aad_len );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_update( ctx, length, input, output );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_finish( ctx, tag );
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
MBEDTLS_CHK( mbedtls_chachapoly_starts( ctx, nonce, mode ) );
MBEDTLS_CHK( mbedtls_chachapoly_update_aad( ctx, aad, aad_len ) );
MBEDTLS_CHK( mbedtls_chachapoly_update( ctx, length, input, output ) );
MBEDTLS_CHK( mbedtls_chachapoly_finish( ctx, tag ) );
cleanup:
return( ret );
}
@ -324,13 +301,12 @@ int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,
unsigned char *output,
unsigned char tag[16] )
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
CHACHAPOLY_VALIDATE_RET( ctx );
CHACHAPOLY_VALIDATE_RET( nonce );
CHACHAPOLY_VALIDATE_RET( tag );
CHACHAPOLY_VALIDATE_RET( aad || !aad_len );
CHACHAPOLY_VALIDATE_RET( input || !length );
CHACHAPOLY_VALIDATE_RET( output || !length );
return( chachapoly_crypt_and_tag( ctx, MBEDTLS_CHACHAPOLY_ENCRYPT,
length, nonce, aad, aad_len,
input, output, tag ) );
@ -345,34 +321,30 @@ int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char check_tag[16];
size_t i;
int diff;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
CHACHAPOLY_VALIDATE_RET( ctx );
CHACHAPOLY_VALIDATE_RET( nonce );
CHACHAPOLY_VALIDATE_RET( tag );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad );
CHACHAPOLY_VALIDATE_RET( length == 0 || input );
CHACHAPOLY_VALIDATE_RET( length == 0 || output );
if( ( ret = chachapoly_crypt_and_tag( ctx,
MBEDTLS_CHACHAPOLY_DECRYPT, length, nonce,
aad, aad_len, input, output, check_tag ) ) != 0 )
{
return( ret );
}
/* Check tag in "constant-time" */
for( diff = 0, i = 0; i < sizeof( check_tag ); i++ )
diff |= tag[i] ^ check_tag[i];
if( diff != 0 )
{
mbedtls_platform_zeroize( output, length );
return( MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED );
}
return( 0 );
}
@ -486,20 +458,16 @@ int mbedtls_chachapoly_self_test( int verbose )
{
mbedtls_chachapoly_context ctx;
unsigned i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char output[200];
unsigned char mac[16];
for( i = 0U; i < 1U; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ChaCha20-Poly1305 test %u ", i );
mbedtls_chachapoly_init( &ctx );
ret = mbedtls_chachapoly_setkey( &ctx, test_key[i] );
ASSERT( 0 == ret, ( "setkey() error code: %i\n", ret ) );
ret = mbedtls_chachapoly_encrypt_and_tag( &ctx,
test_input_len[i],
test_nonce[i],
@ -508,24 +476,17 @@ int mbedtls_chachapoly_self_test( int verbose )
test_input[i],
output,
mac );
ASSERT( 0 == ret, ( "crypt_and_tag() error code: %i\n", ret ) );
ASSERT( 0 == memcmp( output, test_output[i], test_input_len[i] ),
( "failure (wrong output)\n" ) );
ASSERT( 0 == memcmp( mac, test_mac[i], 16U ),
( "failure (wrong MAC)\n" ) );
mbedtls_chachapoly_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
}

9
third_party/mbedtls/chk.h vendored Normal file
View file

@ -0,0 +1,9 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_CHK_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_CHK_H_
#define MBEDTLS_CHK(f) \
do { \
if ((ret = (f))) goto cleanup; \
} while (0)
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_CHK_H_ */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/ccm.h"
#include "third_party/mbedtls/chacha20.h"
#include "third_party/mbedtls/chachapoly.h"
@ -14,30 +31,7 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/**
* \file cipher.c
*
* \brief Generic cipher wrapper for mbed TLS
*
* \author Adriaan de Jong <dejong@fox-it.com>
*
* Copyright The Mbed TLS Contributors
* 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.
*/
#if defined(MBEDTLS_CIPHER_C)
@ -136,7 +130,7 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values(
void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx )
{
CIPHER_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_cipher_context_t ) );
}
void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx )
@ -189,7 +183,7 @@ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx,
if( cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_cipher_context_t ) );
if( NULL == ( ctx->cipher_ctx = cipher_info->base->ctx_alloc_func() ) )
return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );
@ -229,7 +223,7 @@ int mbedtls_cipher_setup_psa( mbedtls_cipher_context_t *ctx,
if( mbedtls_psa_translate_cipher_type( cipher_info->type ) == 0 )
return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_cipher_context_t ) );
cipher_psa = mbedtls_calloc( 1, sizeof(mbedtls_cipher_context_psa ) );
if( cipher_psa == NULL )
@ -471,7 +465,7 @@ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
size_t ilen, unsigned char *output, size_t *olen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t block_size;
CIPHER_VALIDATE_RET( ctx != NULL );
@ -495,8 +489,9 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
*olen = ilen;
if( 0 != ( ret = ctx->cipher_info->base->ecb_func( ctx->cipher_ctx,
ctx->operation, input, output ) ) )
if( ( ret = ctx->cipher_info->base->ecb_func( ctx->cipher_ctx,
ctx->operation,
input, output ) ) )
{
return( ret );
}
@ -1085,7 +1080,7 @@ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
const unsigned char *tag, size_t tag_len )
{
unsigned char check_tag[16];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
CIPHER_VALIDATE_RET( ctx != NULL );
CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
@ -1162,7 +1157,7 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t finish_olen;
CIPHER_VALIDATE_RET( ctx != NULL );
@ -1254,11 +1249,11 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
* mbedtls_cipher_auth_encrypt() and mbedtls_cipher_auth_encrypt_ext().
*/
static int mbedtls_cipher_aead_encrypt( mbedtls_cipher_context_t *ctx,
const unsigned char *iv, size_t iv_len,
const unsigned char *ad, size_t ad_len,
const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen,
unsigned char *tag, size_t tag_len )
const unsigned char *iv, size_t iv_len,
const unsigned char *ad, size_t ad_len,
const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen,
unsigned char *tag, size_t tag_len )
{
#if defined(MBEDTLS_USE_PSA_CRYPTO)
if( ctx->psa_enabled == 1 )
@ -1270,14 +1265,11 @@ static int mbedtls_cipher_aead_encrypt( mbedtls_cipher_context_t *ctx,
* below will gracefully fail. */
mbedtls_cipher_context_psa * const cipher_psa =
(mbedtls_cipher_context_psa *) ctx->cipher_ctx;
psa_status_t status;
/* PSA Crypto API always writes the authentication tag
* at the end of the encrypted message. */
if( output == NULL || tag != output + ilen )
return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
status = psa_aead_encrypt( cipher_psa->slot,
cipher_psa->alg,
iv, iv_len,
@ -1286,7 +1278,6 @@ static int mbedtls_cipher_aead_encrypt( mbedtls_cipher_context_t *ctx,
output, ilen + tag_len, olen );
if( status != PSA_SUCCESS )
return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
*olen -= tag_len;
return( 0 );
}
@ -1376,7 +1367,7 @@ static int mbedtls_cipher_aead_decrypt( mbedtls_cipher_context_t *ctx,
#if defined(MBEDTLS_GCM_C)
if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
*olen = ilen;
ret = mbedtls_gcm_auth_decrypt( ctx->cipher_ctx, ilen,
@ -1392,7 +1383,7 @@ static int mbedtls_cipher_aead_decrypt( mbedtls_cipher_context_t *ctx,
#if defined(MBEDTLS_CCM_C)
if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
*olen = ilen;
ret = mbedtls_ccm_auth_decrypt( ctx->cipher_ctx, ilen,
@ -1408,7 +1399,7 @@ static int mbedtls_cipher_aead_decrypt( mbedtls_cipher_context_t *ctx,
#if defined(MBEDTLS_CHACHAPOLY_C)
if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
/* ChachaPoly has fixed length nonce and MAC (tag) */
if ( ( iv_len != ctx->cipher_info->iv_size ) ||
@ -1527,8 +1518,8 @@ int mbedtls_cipher_auth_encrypt_ext( mbedtls_cipher_context_t *ctx,
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
int ret = mbedtls_cipher_aead_encrypt( ctx, iv, iv_len, ad, ad_len,
input, ilen, output, olen,
output + ilen, tag_len );
input, ilen, output, olen,
output + ilen, tag_len );
*olen += tag_len;
return( ret );
#else

View file

@ -411,7 +411,6 @@ static inline unsigned int mbedtls_cipher_get_block_size(
MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 );
if( ctx->cipher_info == NULL )
return 0;
return ctx->cipher_info->block_size;
}
@ -430,7 +429,6 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode(
MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, MBEDTLS_MODE_NONE );
if( ctx->cipher_info == NULL )
return MBEDTLS_MODE_NONE;
return ctx->cipher_info->mode;
}

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/mem/mem.h"
#include "third_party/mbedtls/aes.h"
#include "third_party/mbedtls/ccm.h"
@ -16,30 +33,8 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/**
* \file cipher_wrap.c
*
* \brief Generic cipher wrapper for mbed TLS
*
* \author Adriaan de Jong <dejong@fox-it.com>
*
* Copyright The Mbed TLS Contributors
* 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.
*/
#if defined(MBEDTLS_CIPHER_C)
#if defined(MBEDTLS_GCM_C)
@ -48,7 +43,7 @@ static void *gcm_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_gcm_context ) );
if( ctx != NULL )
if( ctx )
mbedtls_gcm_init( (mbedtls_gcm_context *) ctx );
return( ctx );
@ -67,7 +62,7 @@ static void *ccm_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ccm_context ) );
if( ctx != NULL )
if( ctx )
mbedtls_ccm_init( (mbedtls_ccm_context *) ctx );
return( ctx );
@ -82,21 +77,6 @@ static void ccm_ctx_free( void *ctx )
#if defined(MBEDTLS_AES_C)
static int aes_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
{
return mbedtls_aes_crypt_ecb( (mbedtls_aes_context *) ctx, operation, input, output );
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int aes_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return mbedtls_aes_crypt_cbc( (mbedtls_aes_context *) ctx, operation, length, iv, input,
output );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static int aes_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
@ -169,7 +149,7 @@ static void * aes_ctx_alloc( void )
{
mbedtls_aes_context *aes = mbedtls_calloc( 1, sizeof( mbedtls_aes_context ) );
if( aes == NULL )
if( !aes )
return( NULL );
mbedtls_aes_init( aes );
@ -185,9 +165,9 @@ static void aes_ctx_free( void *ctx )
static const mbedtls_cipher_base_t aes_info = {
MBEDTLS_CIPHER_ID_AES,
aes_crypt_ecb_wrap,
(void *)mbedtls_aes_crypt_ecb,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
aes_crypt_cbc_wrap,
(void *)mbedtls_aes_crypt_cbc,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
aes_crypt_cfb128_wrap,
@ -1041,7 +1021,7 @@ static int chacha20_stream_wrap( void *ctx, size_t length,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
ret = mbedtls_chacha20_update( ctx, length, input, output );
if( ret == MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA )

View file

@ -1,5 +1,6 @@
#ifndef MBEDTLS_CONFIG_H_
#define MBEDTLS_CONFIG_H_
#include "libc/dce.h"
/* protocols */
#define MBEDTLS_SSL_PROTO_TLS1_2
@ -46,8 +47,8 @@
/* block modes */
#define MBEDTLS_GCM_C
#ifndef TINY
/*#define MBEDTLS_CCM_C*/
#define MBEDTLS_CIPHER_MODE_CBC
/*#define MBEDTLS_CCM_C*/
/*#define MBEDTLS_CIPHER_MODE_CFB*/
/*#define MBEDTLS_CIPHER_MODE_CTR*/
/*#define MBEDTLS_CIPHER_MODE_OFB*/
@ -60,9 +61,9 @@
#ifndef TINY
#define MBEDTLS_ECP_C
#define MBEDTLS_ECDH_C
#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
#define MBEDTLS_ECDSA_C
#define MBEDTLS_ECDSA_DETERMINISTIC
#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
/*#define MBEDTLS_DHM_C*/
@ -113,7 +114,7 @@
#endif
#endif
#ifndef NDEBUG
#if IsModeDbg()
#define MBEDTLS_CHECK_PARAMS
#endif
@ -121,11 +122,10 @@
#define MBEDTLS_SHA1_SMALLER
#define MBEDTLS_SHA256_SMALLER
#define MBEDTLS_SHA512_SMALLER
#define MBEDTLS_ECP_NIST_OPTIM
#ifdef TINY
#define MBEDTLS_AES_ROM_TABLES
#define MBEDTLS_AES_FEWER_TABLES
#else
#define MBEDTLS_ECP_NIST_OPTIM
#endif
#define MBEDTLS_PLATFORM_C
@ -793,7 +793,7 @@
*
* Comment this macro to disable support for server name indication in SSL
*/
/*#define MBEDTLS_SSL_SERVER_NAME_INDICATION*/
#define MBEDTLS_SSL_SERVER_NAME_INDICATION
/**
* \def MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH
@ -1205,7 +1205,6 @@
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. If possible, we recommend avoiding dependencies
* on it, and considering stronger message digests instead.
*
*/
/*#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES*/
@ -1223,7 +1222,11 @@
* a security risk. If possible, we recommend avoiding dependencies
* on it, and considering stronger message digests instead.
*/
/*#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE*/
#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE
#define mbedtls_t_udbl uint128_t
#define MBEDTLS_HAVE_UDBL
#include "libc/dce.h"
#include "third_party/mbedtls/check.h"
#endif /* MBEDTLS_CONFIG_H_ */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/common.h"
@ -12,28 +29,12 @@ Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/*
* CTR_DRBG implementation based on AES-256 (NIST SP 800-90)
/**
* @fileoverview CTR_DRBG implementation based on AES-256 (NIST SP 800-90)
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
* The NIST SP 800-90 DRBGs are described in the following publication.
*
* 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.
*/
/*
* The NIST SP 800-90 DRBGs are described in the following publication.
*
* http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf
* http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf
*/
/**
@ -50,7 +51,7 @@ asm(".include \"libc/disclaimer.inc\"");
*/
void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_ctr_drbg_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ctr_drbg_context ) );
/* Indicate that the entropy nonce length is not set explicitly.
* See mbedtls_ctr_drbg_set_nonce_len(). */
ctx->reseed_counter = -1;
@ -134,7 +135,7 @@ static int block_cipher_df( unsigned char *output,
if( data_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
memset( buf, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT +
mbedtls_platform_zeroize( buf, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT +
MBEDTLS_CTR_DRBG_BLOCKSIZE + 16 );
mbedtls_aes_init( &aes_ctx );
@ -172,7 +173,7 @@ static int block_cipher_df( unsigned char *output,
for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )
{
p = buf;
memset( chain, 0, MBEDTLS_CTR_DRBG_BLOCKSIZE );
mbedtls_platform_zeroize( chain, MBEDTLS_CTR_DRBG_BLOCKSIZE );
use_len = buf_len;
while( use_len > 0 )
@ -248,14 +249,14 @@ exit:
* ctx->counter = V
*/
static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
const unsigned char data[MBEDTLS_CTR_DRBG_SEEDLEN] )
const unsigned char data[MBEDTLS_CTR_DRBG_SEEDLEN] )
{
unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN];
unsigned char *p = tmp;
int i, j;
int ret = 0;
memset( tmp, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
mbedtls_platform_zeroize( tmp, MBEDTLS_CTR_DRBG_SEEDLEN );
for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )
{
@ -314,7 +315,7 @@ int mbedtls_ctr_drbg_update_ret( mbedtls_ctr_drbg_context *ctx,
size_t add_len )
{
unsigned char add_input[MBEDTLS_CTR_DRBG_SEEDLEN];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( add_len == 0 )
return( 0 );
@ -349,7 +350,7 @@ static int mbedtls_ctr_drbg_reseed_internal( mbedtls_ctr_drbg_context *ctx,
{
unsigned char seed[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT];
size_t seedlen = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( ctx->entropy_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
@ -358,7 +359,7 @@ static int mbedtls_ctr_drbg_reseed_internal( mbedtls_ctr_drbg_context *ctx,
if( len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - ctx->entropy_len - nonce_len )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
memset( seed, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT );
mbedtls_platform_zeroize( seed, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT );
/* Gather entropy_len bytes of entropy to seed state. */
if( 0 != ctx->f_entropy( ctx->p_entropy, seed, ctx->entropy_len ) )
@ -399,7 +400,7 @@ exit:
}
int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional, size_t len )
const void *additional, size_t len )
{
return( mbedtls_ctr_drbg_reseed_internal( ctx, additional, len, 0 ) );
}
@ -434,11 +435,11 @@ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
const void *custom,
size_t len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char key[MBEDTLS_CTR_DRBG_KEYSIZE];
size_t nonce_len;
memset( key, 0, MBEDTLS_CTR_DRBG_KEYSIZE );
mbedtls_platform_zeroize( key, MBEDTLS_CTR_DRBG_KEYSIZE );
mbedtls_aes_init( &ctx->aes_ctx );
@ -508,7 +509,7 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
if( add_len > MBEDTLS_CTR_DRBG_MAX_INPUT )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
memset( add_input, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
mbedtls_platform_zeroize( add_input, MBEDTLS_CTR_DRBG_SEEDLEN );
if( ctx->reseed_counter > ctx->reseed_interval ||
ctx->prediction_resistance )

View file

@ -356,7 +356,7 @@ void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx,
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
*/
int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
const unsigned char *additional, size_t len );
const void *additional, size_t len );
/**
* \brief This function updates the state of the CTR_DRBG context.

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/debug.h"
#include "third_party/mbedtls/error.h"
@ -8,26 +25,7 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* Debugging routines
*
* Copyright The Mbed TLS Contributors
* 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.
*/
char mbedtls_debug_threshold;
@ -57,7 +55,7 @@ void mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level,
{
va_list argp;
char str[DEBUG_BUF_SIZE];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( NULL == ssl ||
NULL == ssl->conf ||
@ -129,7 +127,7 @@ void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,
debug_send_line( ssl, level, file, line, str );
idx = 0;
memset( txt, 0, sizeof( txt ) );
mbedtls_platform_zeroize( txt, sizeof( txt ) );
for( i = 0; i < len; i++ )
{
if( i >= 4096 )
@ -143,7 +141,7 @@ void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,
debug_send_line( ssl, level, file, line, str );
idx = 0;
memset( txt, 0, sizeof( txt ) );
mbedtls_platform_zeroize( txt, sizeof( txt ) );
}
idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, "%04x: ",
@ -273,7 +271,7 @@ static void debug_print_pk( const mbedtls_ssl_context *ssl, int level,
mbedtls_pk_debug_item items[MBEDTLS_PK_DEBUG_MAX_ITEMS];
char name[16];
memset( items, 0, sizeof( items ) );
mbedtls_platform_zeroize( items, sizeof( items ) );
if( mbedtls_pk_debug( pk, items ) != 0 )
{

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/common.h"
@ -10,31 +27,15 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* FIPS-46-3 compliant Triple-DES implementation
/**
* @fileoverview FIPS-46-3 compliant Triple-DES implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
* DES, on which TDES is based, was originally designed by Horst Feistel
* at IBM in 1974, and was adopted as a standard by NIST (formerly NBS).
*
* 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.
*/
/*
* DES, on which TDES is based, was originally designed by Horst Feistel
* at IBM in 1974, and was adopted as a standard by NIST (formerly NBS).
*
* http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
* http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
*/
/*
@ -276,7 +277,7 @@ static const uint32_t RHs[16] =
void mbedtls_des_init( mbedtls_des_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des_context ) );
}
void mbedtls_des_free( mbedtls_des_context *ctx )
@ -289,7 +290,7 @@ void mbedtls_des_free( mbedtls_des_context *ctx )
void mbedtls_des3_init( mbedtls_des3_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des3_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des3_context ) );
}
void mbedtls_des3_free( mbedtls_des3_context *ctx )

View file

@ -254,8 +254,8 @@ int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
* \return 0 if successful
*/
int mbedtls_des3_crypt_ecb( mbedtls_des3_context *ctx,
const unsigned char input[8],
unsigned char output[8] );
const unsigned char input[8],
unsigned char output[8] );
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/**

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/calls/calls.h"
#include "third_party/mbedtls/asn1.h"
#include "third_party/mbedtls/common.h"
@ -11,34 +28,16 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* Diffie-Hellman-Merkle key exchange
*
* Copyright The Mbed TLS Contributors
* 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.
*/
/*
* The following sources were referenced in the design of this implementation
* of the Diffie-Hellman-Merkle algorithm:
/**
* @fileoverview Diffie-Hellman-Merkle key exchange
*
* [1] Handbook of Applied Cryptography - 1997, Chapter 12
* Menezes, van Oorschot and Vanstone
* The following sources were referenced in the design of this
* implementation of the Diffie-Hellman-Merkle algorithm:
*
* [1] Handbook of Applied Cryptography - 1997, Chapter 12
* Menezes, van Oorschot and Vanstone
*/
#if defined(MBEDTLS_DHM_C)
@ -112,7 +111,7 @@ cleanup:
void mbedtls_dhm_init( mbedtls_dhm_context *ctx )
{
DHM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_dhm_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_dhm_context ) );
}
/*
@ -122,7 +121,7 @@ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,
unsigned char **p,
const unsigned char *end )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( p != NULL && *p != NULL );
DHM_VALIDATE_RET( end != NULL );
@ -167,7 +166,7 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );
mbedtls_mpi_shift_r( &ctx->X, 1 );
if( count++ > 10 )
return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED );
@ -224,7 +223,7 @@ int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,
const mbedtls_mpi *P,
const mbedtls_mpi *G )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( P != NULL );
DHM_VALIDATE_RET( G != NULL );
@ -245,7 +244,7 @@ int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,
int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx,
const unsigned char *input, size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( input != NULL );
@ -285,7 +284,7 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );
mbedtls_mpi_shift_r( &ctx->X, 1 );
if( count++ > 10 )
return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED );
@ -323,7 +322,7 @@ static int dhm_random_below( mbedtls_mpi *R, const mbedtls_mpi *M,
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( R, mbedtls_mpi_size( M ), f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( R, M ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( R, 1 ) );
mbedtls_mpi_shift_r( &R, 1 );
if( count++ > 10 )
return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
@ -367,7 +366,7 @@ static int dhm_update_blinding( mbedtls_dhm_context *ctx,
* Ok, we need blinding. Can we re-use existing values?
* If yes, just update them by squaring them.
*/
if( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) != 0 )
if( !mbedtls_mpi_is_one( &ctx->Vi ) )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->P ) );
@ -411,7 +410,7 @@ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi GYb;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( output != NULL );
@ -488,7 +487,7 @@ void mbedtls_dhm_free( mbedtls_dhm_context *ctx )
int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
size_t dhminlen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len;
unsigned char *p, *end;
#if defined(MBEDTLS_PEM_PARSE_C)
@ -642,7 +641,7 @@ static int load_file( const char *path, unsigned char **buf, size_t *n )
*/
int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t n;
unsigned char *buf;
DHM_VALIDATE_RET( dhm != NULL );
@ -694,7 +693,7 @@ static const size_t mbedtls_test_dhm_params_len = sizeof( mbedtls_test_dhm_param
*/
int mbedtls_dhm_self_test( int verbose )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_dhm_context dhm;
mbedtls_dhm_init( &dhm );

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/ecdh.h"
#include "third_party/mbedtls/error.h"
@ -8,32 +25,13 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* Elliptic curve Diffie-Hellman
*
* Copyright The Mbed TLS Contributors
* 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.
*/
/*
* References:
/**
* @fileoverview Elliptic curve Diffie-Hellman
*
* SEC1 http://www.secg.org/index.php?action=secg,docs_secg
* RFC 4492
* @see SEC1 http://www.secg.org/index.php?action=secg,docs_secg
* @see RFC4492
*/
#if defined(MBEDTLS_ECDH_C)
@ -73,16 +71,16 @@ int mbedtls_ecdh_can_do( mbedtls_ecp_group_id gid )
* acceptable for a public function but is OK here as we control call sites.
*/
static int ecdh_gen_public_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
/* If multiplication is in progress, we already generated a privkey */
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx == NULL || rs_ctx->rsm == NULL )
if( !rs_ctx || !rs_ctx->rsm )
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
@ -97,8 +95,8 @@ cleanup:
* Generate public key
*/
int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ECDH_VALIDATE_RET( grp != NULL );
ECDH_VALIDATE_RET( d != NULL );
@ -119,7 +117,7 @@ static int ecdh_compute_shared_restartable( mbedtls_ecp_group *grp,
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ecp_point P;
mbedtls_ecp_point_init( &P );
@ -184,7 +182,7 @@ void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx )
mbedtls_ecp_point_init( &ctx->Vf );
mbedtls_mpi_init( &ctx->_d );
#else
memset( ctx, 0, sizeof( mbedtls_ecdh_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ecdh_context ) );
ctx->var = MBEDTLS_ECDH_VARIANT_NONE;
#endif
@ -197,7 +195,7 @@ void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx )
static int ecdh_setup_internal( mbedtls_ecdh_context_mbed *ctx,
mbedtls_ecp_group_id grp_id )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
ret = mbedtls_ecp_group_load( &ctx->grp, grp_id );
if( ret != 0 )
@ -305,7 +303,7 @@ static int ecdh_make_params_internal( mbedtls_ecdh_context_mbed *ctx,
void *p_rng,
int restart_enabled )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t grp_len, pt_len;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
@ -412,7 +410,7 @@ int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
const unsigned char **buf,
const unsigned char *end )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ecp_group_id grp_id;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( buf != NULL );
@ -449,7 +447,7 @@ static int ecdh_get_params_internal( mbedtls_ecdh_context_mbed *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
/* If it's not our key, just import the public part as Qp */
if( side == MBEDTLS_ECDH_THEIRS )
@ -473,7 +471,7 @@ int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( key != NULL );
ECDH_VALIDATE_RET( side == MBEDTLS_ECDH_OURS ||
@ -528,7 +526,7 @@ static int ecdh_make_public_internal( mbedtls_ecdh_context_mbed *ctx,
void *p_rng,
int restart_enabled )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif
@ -600,7 +598,7 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
static int ecdh_read_public_internal( mbedtls_ecdh_context_mbed *ctx,
const unsigned char *buf, size_t blen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const unsigned char *p = buf;
if( ( ret = mbedtls_ecp_tls_read_point( &ctx->grp, &ctx->Qp, &p,
@ -650,7 +648,7 @@ static int ecdh_calc_secret_internal( mbedtls_ecdh_context_mbed *ctx,
void *p_rng,
int restart_enabled )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif

View file

@ -1,9 +1,27 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/asn1write.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/ecdsa.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/hmac_drbg.h"
#include "third_party/mbedtls/platform.h"
#include "third_party/mbedtls/profile.h"
asm(".ident\t\"\\n\\n\
Mbed TLS (Apache 2.0)\\n\
@ -219,7 +237,7 @@ static void ecdsa_restart_det_free( mbedtls_ecdsa_restart_det_ctx *ctx )
static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x,
const unsigned char *buf, size_t blen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t n_size = ( grp->nbits + 7 ) / 8;
size_t use_size = blen > n_size ? n_size : blen;
@ -421,7 +439,7 @@ static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp,
void *p_rng_blind,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_hmac_drbg_context rng_ctx;
mbedtls_hmac_drbg_context *p_rng = &rng_ctx;
unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];
@ -576,7 +594,7 @@ static int ecdsa_verify_restartable( mbedtls_ecp_group *grp,
const mbedtls_mpi *r, const mbedtls_mpi *s,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi e, s_inv, u1, u2;
mbedtls_ecp_point R;
mbedtls_mpi *pu1 = &u1, *pu2 = &u2;
@ -700,7 +718,7 @@ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s,
unsigned char *sig, size_t *slen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char buf[MBEDTLS_ECDSA_MAX_LEN];
unsigned char *p = buf + sizeof( buf );
size_t len = 0;
@ -729,7 +747,7 @@ int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx,
void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi r, s;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
@ -808,7 +826,7 @@ int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx,
const unsigned char *sig, size_t slen,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *p = (unsigned char *) sig;
const unsigned char *end = sig + slen;
size_t len;
@ -870,7 +888,7 @@ cleanup:
* Generate key pair
*/
int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = 0;
ECDSA_VALIDATE_RET( ctx != NULL );
@ -890,7 +908,7 @@ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
*/
int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( key != NULL );

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,6 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ECP_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ECP_H_
#include "libc/log/backtrace.internal.h"
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/config.h"
COSMOPOLITAN_C_START_
@ -350,6 +351,7 @@ int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *, mbedtls_ecp_point *,
int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *, size_t *, unsigned char *, size_t );
int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *, const mbedtls_ecp_point *, int, size_t *, unsigned char *, size_t );
int mbedtls_ecp_write_key( mbedtls_ecp_keypair *, unsigned char *, size_t );
int mbedtls_mpi_shift_l_mod( const mbedtls_ecp_group *, mbedtls_mpi * );
mbedtls_ecp_curve_type mbedtls_ecp_get_type( const mbedtls_ecp_group * );
void mbedtls_ecp_group_free( mbedtls_ecp_group * );
void mbedtls_ecp_group_init( mbedtls_ecp_group * );
@ -361,5 +363,8 @@ void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx * );
void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx * );
void mbedtls_ecp_set_max_ops( unsigned );
int ecp_mod_p256(mbedtls_mpi *);
int ecp_mod_p384(mbedtls_mpi *);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ECP_H_ */

673
third_party/mbedtls/ecp256.c vendored Normal file
View file

@ -0,0 +1,673 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/log/check.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/runtime/gc.internal.h"
#include "libc/runtime/runtime.h"
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/ecp.h"
#include "third_party/mbedtls/ecp_internal.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/math.h"
#include "third_party/mbedtls/profile.h"
#include "third_party/mbedtls/traceme.h"
/* clang-format off */
static inline bool
mbedtls_p256_isz( uint64_t p[4] )
{
return( !p[0] & !p[1] & !p[2] & !p[3] );
}
static inline bool
mbedtls_p256_gte( uint64_t p[5] )
{
return( (p[4] ||
p[3] > 0xffffffff00000001 ||
(p[3] == 0xffffffff00000001 &&
p[2] > 0x0000000000000000 ||
(p[2] == 0x0000000000000000 &&
p[1] > 0x00000000ffffffff ||
(p[1] == 0x00000000ffffffff &&
p[0] > 0xffffffffffffffff ||
(p[0] == 0xffffffffffffffff))))) );
}
static int
mbedtls_p256_cmp( const uint64_t a[5],
const uint64_t b[5] )
{
if( a[4] < b[4] ) return -1;
if( a[4] > b[4] ) return 1;
if( a[3] < b[3] ) return -1;
if( a[3] > b[3] ) return 1;
if( a[2] < b[2] ) return -1;
if( a[2] > b[2] ) return 1;
if( a[1] < b[1] ) return -1;
if( a[1] > b[1] ) return 1;
if( a[0] < b[0] ) return -1;
if( a[0] > b[0] ) return 1;
return 0;
}
static inline void
mbedtls_p256_red( uint64_t p[5] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("subq\t%1,%0\n\t"
"sbbq\t%2,8+%0\n\t"
"sbbq\t%3,16+%0\n\t"
"sbbq\t%4,24+%0\n\t"
"sbbq\t$0,32+%0"
: "+o"(*p)
: "i"(0xffffffffffffffffl), "r"(0x00000000ffffffffl),
"i"(0x0000000000000000l), "r"(0xffffffff00000001l)
: "memory", "cc");
#else
uint64_t c;
SBB( p[0], p[0], 0xffffffffffffffff, 0, c );
SBB( p[1], p[1], 0x00000000ffffffff, c, c );
SBB( p[2], p[2], 0x0000000000000000, c, c );
SBB( p[3], p[3], 0xffffffff00000001, c, c );
SBB( p[4], p[4], 0, c, c );
#endif
}
static noinline void
mbedtls_p256_gro( uint64_t p[5] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("addq\t%1,%0\n\t"
"adcq\t%2,8+%0\n\t"
"adcq\t%3,16+%0\n\t"
"adcq\t%4,24+%0\n\t"
"adcq\t$0,32+%0"
: "+o"(*p)
: "i"(0xffffffffffffffffl), "r"(0x00000000ffffffffl),
"i"(0x0000000000000000l), "r"(0xffffffff00000001l)
: "memory", "cc");
#else
uint64_t c;
ADC( p[0], p[0], 0xffffffffffffffff, 0, c );
ADC( p[1], p[1], 0x00000000ffffffff, c, c );
ADC( p[2], p[2], 0x0000000000000000, c, c );
ADC( p[3], p[3], 0xffffffff00000001, c, c );
ADC( p[4], p[4], 0, c, c );
#endif
}
static void
mbedtls_p256_rum( uint64_t p[5] )
{
while( mbedtls_p256_gte( p ) )
mbedtls_p256_red( p );
}
static inline void
mbedtls_p256_sar( uint64_t p[5] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("sarq\t32+%0\n\t"
"rcrq\t24+%0\n\t"
"rcrq\t16+%0\n\t"
"rcrq\t8+%0\n\t"
"rcrq\t%0\n\t"
: "+o"(*p)
: /* no inputs */
: "memory", "cc");
#else
p[0] = p[0] >> 1 | p[1] << 63;
p[1] = p[1] >> 1 | p[2] << 63;
p[2] = p[2] >> 1 | p[3] << 63;
p[3] = p[3] >> 1 | p[4] << 63;
p[4] = (int64_t)p[4] >> 1;
#endif
}
static inline void
mbedtls_p256_shl( uint64_t p[5] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("shlq\t%0\n\t"
"rclq\t8+%0\n\t"
"rclq\t16+%0\n\t"
"rclq\t24+%0\n\t"
"rclq\t32+%0\n\t"
: "+o"(*p)
: /* no inputs */
: "memory", "cc");
#else
p[4] = p[3] >> 63;
p[3] = p[3] << 1 | p[2] >> 63;
p[2] = p[2] << 1 | p[1] >> 63;
p[1] = p[1] << 1 | p[0] >> 63;
p[0] = p[0] << 1;
#endif
mbedtls_p256_rum( p );
}
static inline void
mbedtls_p256_jam( uint64_t p[5] )
{
secp256r1( p );
if( (int64_t)p[4] < 0 )
do
mbedtls_p256_gro( p );
while( (int64_t)p[4] < 0 );
else
mbedtls_p256_rum( p );
}
static void
mbedtls_p256_mul_1x1( uint64_t X[8],
const uint64_t A[4], size_t n,
const uint64_t B[4], size_t m )
{
uint128_t t;
t = A[0];
t *= B[0];
X[ 0] = t;
X[ 1] = t >> 64;
X[ 2] = 0;
X[ 3] = 0;
X[ 4] = 0;
X[ 5] = 0;
X[ 6] = 0;
X[ 7] = 0;
}
static void
mbedtls_p256_mul_nx1( uint64_t X[8],
const uint64_t A[4], size_t n,
const uint64_t B[4], size_t m )
{
mbedtls_mpi_mul_hlp1(n, A, X, B[0]);
mbedtls_platform_zeroize( X + n + m, ( 8 - n - m ) * 8 );
if ( n + m >= 4 )
mbedtls_p256_jam( X );
}
static void
mbedtls_p256_mul_4x4( uint64_t X[8],
const uint64_t A[4], size_t n,
const uint64_t B[4], size_t m )
{
Mul4x4( X, A, B );
mbedtls_p256_jam( X );
}
static void
mbedtls_p256_mul_nxm( uint64_t X[8],
const uint64_t A[4], size_t n,
const uint64_t B[4], size_t m )
{
if (A == X) A = gc(memcpy(malloc(4 * 8), A, 4 * 8));
if (B == X) B = gc(memcpy(malloc(4 * 8), B, 4 * 8));
Mul( X, A, n, B, m );
mbedtls_platform_zeroize( X + n + m, (8 - n - m) * 8 );
if ( n + m >= 4 )
mbedtls_p256_jam( X );
}
static void
mbedtls_p256_mul( uint64_t X[8],
const uint64_t A[4], size_t n,
const uint64_t B[4], size_t m )
{
if( n == 4 && m == 4 )
mbedtls_p256_mul_4x4( X, A, n, B, m );
else if( m == 1 && n == 1 )
mbedtls_p256_mul_1x1( X, A, n, B, m );
else if( m == 1 )
mbedtls_p256_mul_nx1( X, A, n, B, m );
else
mbedtls_p256_mul_nxm( X, A, n, B, m );
}
static void
mbedtls_p256_add( uint64_t X[5],
const uint64_t A[4],
const uint64_t B[4] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("xor\t%%rcx,%%rcx\n\t"
"mov\t%1,%%rax\n\t"
"add\t%2,%%rax\n\t"
"mov\t%%rax,%0\n\t"
"mov\t8+%1,%%rax\n\t"
"adc\t8+%2,%%rax\n\t"
"mov\t%%rax,8+%0\n\t"
"mov\t16+%1,%%rax\n\t"
"adc\t16+%2,%%rax\n\t"
"mov\t%%rax,16+%0\n\t"
"mov\t24+%1,%%rax\n\t"
"adc\t24+%2,%%rax\n\t"
"mov\t%%rax,24+%0\n\t"
"adc\t$0,%%rcx\n\t"
"mov\t%%rcx,32+%0"
: "+o"(*X)
: "o"(*A), "o"(*B)
: "rax", "rcx", "memory", "cc");
#else
uint64_t c;
ADC( X[0], A[0], B[0], 0, c );
ADC( X[1], A[1], B[1], c, c );
ADC( X[2], A[2], B[2], c, c );
ADC( X[3], A[3], B[3], c, X[4] );
#endif
mbedtls_p256_rum( X );
DCHECK_EQ( 0, X[4] );
}
static void
mbedtls_p256_sub( uint64_t X[5],
const uint64_t A[4],
const uint64_t B[4] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("xor\t%%rcx,%%rcx\n\t"
"mov\t%1,%%rax\n\t"
"sub\t%2,%%rax\n\t"
"mov\t%%rax,%0\n\t"
"mov\t8+%1,%%rax\n\t"
"sbb\t8+%2,%%rax\n\t"
"mov\t%%rax,8+%0\n\t"
"mov\t16+%1,%%rax\n\t"
"sbb\t16+%2,%%rax\n\t"
"mov\t%%rax,16+%0\n\t"
"mov\t24+%1,%%rax\n\t"
"sbb\t24+%2,%%rax\n\t"
"mov\t%%rax,24+%0\n\t"
"sbb\t$0,%%rcx\n\t"
"mov\t%%rcx,32+%0"
: "+o"(*X)
: "o"(*A), "o"(*B)
: "rax", "rcx", "memory", "cc");
#else
uint64_t c;
SBB( X[0], A[0], B[0], 0, c );
SBB( X[1], A[1], B[1], c, c );
SBB( X[2], A[2], B[2], c, c );
SBB( X[3], A[3], B[3], c, c );
X[4] = -c;
#endif
while( (int64_t)X[4] < 0 )
mbedtls_p256_gro( X );
DCHECK_EQ( 0, X[4] );
}
static void
mbedtls_p256_hub( uint64_t A[5],
const uint64_t B[4] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("xor\t%%rcx,%%rcx\n\t"
"mov\t%1,%%rax\n\t"
"sub\t%%rax,%0\n\t"
"mov\t8+%1,%%rax\n\t"
"sbb\t%%rax,8+%0\n\t"
"mov\t16+%1,%%rax\n\t"
"sbb\t%%rax,16+%0\n\t"
"mov\t24+%1,%%rax\n\t"
"sbb\t%%rax,24+%0\n\t"
"sbb\t$0,%%rcx\n\t"
"mov\t%%rcx,32+%0"
: "+o"(*A)
: "o"(*B)
: "rax", "rcx", "memory", "cc");
while( (int64_t)A[4] < 0 )
mbedtls_p256_gro( A );
DCHECK_EQ( 0, A[4] );
#else
mbedtls_p256_sub( A, A, B );
#endif
}
static inline void
mbedtls_p256_cop( uint64_t X[4],
const uint64_t Y[4] )
{
memcpy( X, Y, 4 * 8 );
}
static int
mbedtls_p256_dim( mbedtls_ecp_point *R )
{
int ret;
if( R->X.n < 4 && ( ret = mbedtls_mpi_grow( &R->X, 4 ) ) ) return ret;
if( R->Y.n < 4 && ( ret = mbedtls_mpi_grow( &R->Y, 4 ) ) ) return ret;
if( R->Z.n < 4 && ( ret = mbedtls_mpi_grow( &R->Z, 4 ) ) ) return ret;
return 0;
}
int mbedtls_p256_double_jac( const mbedtls_ecp_group *G,
const mbedtls_ecp_point *P,
mbedtls_ecp_point *R )
{
int ret;
struct {
uint64_t X[4], Y[4], Z[4];
uint64_t M[8], S[8], T[8], U[8];
size_t Xn, Yn, Zn;
} s;
MBEDTLS_ASSERT( G->A.p == 0 );
MBEDTLS_ASSERT( P->X.s == 1 );
MBEDTLS_ASSERT( P->Y.s == 1 );
MBEDTLS_ASSERT( P->Z.s == 1 );
MBEDTLS_ASSERT( G->P.p[0] == 0xffffffffffffffff );
MBEDTLS_ASSERT( G->P.p[1] == 0x00000000ffffffff );
MBEDTLS_ASSERT( G->P.p[2] == 0x0000000000000000 );
MBEDTLS_ASSERT( G->P.p[3] == 0xffffffff00000001 );
if ( ( ret = mbedtls_p256_dim( R ) ) ) return ret;
mbedtls_platform_zeroize(&s, sizeof(s));
s.Xn = mbedtls_mpi_limbs( &P->X );
s.Yn = mbedtls_mpi_limbs( &P->Y );
s.Zn = mbedtls_mpi_limbs( &P->Z );
CHECK_LE( s.Xn, 4 );
CHECK_LE( s.Yn, 4 );
CHECK_LE( s.Zn, 4 );
memcpy( s.X, P->X.p, s.Xn * 8 );
memcpy( s.Y, P->Y.p, s.Yn * 8 );
memcpy( s.Z, P->Z.p, s.Zn * 8 );
mbedtls_p256_mul( s.S, s.Z, s.Zn, s.Z, s.Zn );
mbedtls_p256_add( s.T, s.X, s.S );
mbedtls_p256_sub( s.U, s.X, s.S );
mbedtls_p256_mul( s.S, s.T, 4, s.U, 4 );
mbedtls_mpi_mul_hlp1( 4, s.S, s.M, 3 );
mbedtls_p256_rum( s.M );
mbedtls_p256_mul( s.T, s.Y, s.Yn, s.Y, s.Yn );
mbedtls_p256_shl( s.T );
mbedtls_p256_mul( s.S, s.X, s.Xn, s.T, 4 );
mbedtls_p256_shl( s.S );
mbedtls_p256_mul( s.U, s.T, 4, s.T, 4 );
mbedtls_p256_shl( s.U );
mbedtls_p256_mul( s.T, s.M, 4, s.M, 4 );
mbedtls_p256_hub( s.T, s.S );
mbedtls_p256_hub( s.T, s.S );
mbedtls_p256_hub( s.S, s.T );
mbedtls_p256_mul( s.S, s.S, 4, s.M, 4 );
mbedtls_p256_hub( s.S, s.U );
mbedtls_p256_mul( s.U, s.Y, s.Yn, s.Z, s.Zn );
mbedtls_p256_shl( s.U );
mbedtls_p256_cop( R->X.p, s.T );
mbedtls_p256_cop( R->Y.p, s.S );
mbedtls_p256_cop( R->Z.p, s.U );
mbedtls_platform_zeroize( &s, sizeof(s) );
return 0;
}
int mbedtls_p256_add_mixed( const mbedtls_ecp_group *G,
const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q,
mbedtls_ecp_point *R )
{
int ret;
struct {
uint64_t X[8], Y[8], Z[8];
uint64_t T1[8], T2[8], T3[8], T4[8];
size_t Xn, Yn, Zn, QXn, QYn;
} s;
MBEDTLS_ASSERT( P->X.s == 1 );
MBEDTLS_ASSERT( P->Y.s == 1 );
MBEDTLS_ASSERT( P->Z.s == 1 );
MBEDTLS_ASSERT( Q->X.s == 1 );
MBEDTLS_ASSERT( Q->Y.s == 1 );
if ( ( ret = mbedtls_p256_dim( R ) ) ) return ret;
mbedtls_platform_zeroize(&s, sizeof(s));
s.Xn = mbedtls_mpi_limbs( &P->X );
s.Yn = mbedtls_mpi_limbs( &P->Y );
s.Zn = mbedtls_mpi_limbs( &P->Z );
s.QXn = mbedtls_mpi_limbs( &Q->X );
s.QYn = mbedtls_mpi_limbs( &Q->Y );
CHECK_LE( s.Xn, 4 );
CHECK_LE( s.Yn, 4 );
CHECK_LE( s.Zn, 4 );
CHECK_LE( s.QXn, 4 );
CHECK_LE( s.QYn, 4 );
memcpy( s.X, P->X.p, s.Xn * 8 );
memcpy( s.Y, P->Y.p, s.Yn * 8 );
memcpy( s.Z, P->Z.p, s.Zn * 8 );
mbedtls_p256_mul( s.T1, s.Z, s.Zn, s.Z, s.Zn );
mbedtls_p256_mul( s.T2, s.T1, 4, s.Z, s.Zn );
mbedtls_p256_mul( s.T1, s.T1, 4, Q->X.p, s.QXn );
mbedtls_p256_mul( s.T2, s.T2, 4, Q->Y.p, s.QYn );
mbedtls_p256_hub( s.T1, s.X );
mbedtls_p256_hub( s.T2, s.Y );
if( mbedtls_p256_isz( s.T1 ) )
{
if( mbedtls_p256_isz( s.T2 ) )
return mbedtls_p256_double_jac( G, P, R );
else
return mbedtls_ecp_set_zero( R );
}
mbedtls_p256_mul( s.Z, s.Z, s.Zn, s.T1, 4 );
mbedtls_p256_mul( s.T3, s.T1, 4, s.T1, 4 );
mbedtls_p256_mul( s.T4, s.T3, 4, s.T1, 4 );
mbedtls_p256_mul( s.T3, s.T3, 4, s.X, s.Xn );
mbedtls_p256_cop( s.T1, s.T3 );
mbedtls_p256_shl( s.T1 );
mbedtls_p256_mul( s.X, s.T2, 4, s.T2, 4 );
mbedtls_p256_hub( s.X, s.T1 );
mbedtls_p256_hub( s.X, s.T4 );
mbedtls_p256_hub( s.T3, s.X );
mbedtls_p256_mul( s.T3, s.T3, 4, s.T2, 4 );
mbedtls_p256_mul( s.T4, s.T4, 4, s.Y, s.Yn );
mbedtls_p256_sub( s.Y, s.T3, s.T4 );
mbedtls_p256_cop( R->X.p, s.X );
mbedtls_p256_cop( R->Y.p, s.Y );
mbedtls_p256_cop( R->Z.p, s.Z );
mbedtls_platform_zeroize(&s, sizeof(s));
return 0;
}
static int mbedtls_p256_inv(mbedtls_mpi *X,
const mbedtls_mpi *A,
const mbedtls_mpi *B)
{
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
MBEDTLS_ASSERT( A->s == 1 );
MBEDTLS_ASSERT( B->s == 1 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs(X) <= 4 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs(A) <= 4 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs(B) <= 4 );
MBEDTLS_ASSERT( mbedtls_mpi_cmp_int(B, 1) > 0 );
mbedtls_mpi_init( &TA );
mbedtls_mpi_init( &TU );
mbedtls_mpi_init( &U1 );
mbedtls_mpi_init( &U2 );
mbedtls_mpi_init( &G );
mbedtls_mpi_init( &TB );
mbedtls_mpi_init( &TV );
mbedtls_mpi_init( &V1 );
mbedtls_mpi_init( &V2 );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TA, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TU, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &U1, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &U2, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &G, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TB, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TV, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &V1, 5 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &V2, 5 ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd( &G, A, B ));
if (!mbedtls_mpi_is_one( &G ))
{
ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &TA, A, B ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TU, &TA ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TV, B ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U1, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U2, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V2, 1 ) );
do
{
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TU ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U1 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U2 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TV ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V2 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V1 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &G ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TA ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TB ) <= 5 );
while (!(TU.p[0] & 1))
{
mbedtls_p256_sar(TU.p);
if ((U1.p[0] & 1) || (U2.p[0] & 1))
{
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi(&U1, &U1, &TB) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi(&U2, &U2, &TA) );
}
mbedtls_p256_sar(U1.p);
mbedtls_p256_sar(U2.p);
}
while (!(TV.p[0] & 1))
{
mbedtls_p256_sar(TV.p);
if ((V1.p[0] & 1) || (V2.p[0] & 1))
{
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi(&V1, &V1, &TB) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi(&V2, &V2, &TA) );
}
mbedtls_p256_sar( V1.p );
mbedtls_p256_sar( V2.p );
}
if (mbedtls_mpi_cmp_mpi( &TU, &TV ) >= 0)
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TU, &TU, &TV ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U1, &U1, &V1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &V2 ) );
}
else
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TV, &TV, &TU ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, &U1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &U2 ) );
}
} while ( TU.p[0] | TU.p[1] | TU.p[2] | TU.p[3] );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TU ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U1 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U2 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TV ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V2 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V1 ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &G ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TA ) <= 5 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TB ) <= 5 );
while (V1.s < 0)
MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi( &V1, &V1, B ));
while (mbedtls_mpi_cmp_mpi( &V1, B ) >= 0)
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi( &V1, &V1, B ));
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &V1 ) );
cleanup:
mbedtls_mpi_free( &TA );
mbedtls_mpi_free( &TU );
mbedtls_mpi_free( &U1 );
mbedtls_mpi_free( &U2 );
mbedtls_mpi_free( &G );
mbedtls_mpi_free( &TB );
mbedtls_mpi_free( &TV );
mbedtls_mpi_free( &V1 );
mbedtls_mpi_free( &V2 );
return ret;
}
int mbedtls_p256_normalize_jac_many( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *T[], size_t T_size )
{
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i;
uint64_t ta[8];
mbedtls_mpi *c, u, Zi, ZZi;
if( !( c = mbedtls_calloc( T_size, sizeof( mbedtls_mpi ) ) ) )
return( MBEDTLS_ERR_ECP_ALLOC_FAILED );
mbedtls_mpi_init( &u );
mbedtls_mpi_init( &Zi );
mbedtls_mpi_init( &ZZi );
for( i = 0; i < T_size; i++ )
{
CHECK_EQ( 4, T[i]->X.n );
CHECK_EQ( 4, T[i]->Y.n );
CHECK_EQ( 4, T[i]->Z.n );
mbedtls_mpi_init( c + i );
}
for( i = 0; i < T_size; i++ )
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( c + i, 8 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &u, 8 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &Zi, 8 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &ZZi, 8 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( c, &T[0]->Z ) );
for( i = 1; i < T_size; i++ )
mbedtls_p256_mul( c[i].p, c[i-1].p, 4, T[i]->Z.p, 4 );
/* mbedtls_mpi_inv_mod( &u, &c[T_size-1], &grp->P ); */
MBEDTLS_MPI_CHK( mbedtls_p256_inv( &u, c + T_size - 1, &grp->P ) );
for( i = T_size - 1; ; i-- )
{
if( !i )
memcpy( Zi.p, u.p, 4 * 8 );
else
{
mbedtls_p256_mul( Zi.p, u.p, 4, c[i-1].p, 4 );
mbedtls_p256_mul( u.p, u.p, 4, T[i]->Z.p, 4 );
}
mbedtls_p256_mul( ZZi.p, Zi.p, 4, Zi.p, 4 );
mbedtls_p256_mul( ta, T[i]->X.p, 4, ZZi.p, 4 );
memcpy( T[i]->X.p, ta, 4 * 8 );
mbedtls_p256_mul( ta, T[i]->Y.p, 4, ZZi.p, 4 );
mbedtls_p256_mul( ta, ta, 4, Zi.p, 4 );
memcpy( T[i]->Y.p, ta, 4 * 8 );
mbedtls_mpi_free( &T[i]->Z );
if( !i ) break;
}
cleanup:
mbedtls_platform_zeroize( ta, sizeof(ta) );
for( i = 0; i < T_size; i++ )
mbedtls_mpi_free( c + i );
mbedtls_mpi_free( &ZZi );
mbedtls_mpi_free( &Zi );
mbedtls_mpi_free( &u );
mbedtls_free( c );
return( ret );
}
int mbedtls_p256_normalize_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt )
{
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi Zi, ZZi;
mbedtls_mpi_init( &Zi );
mbedtls_mpi_init( &ZZi );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &Zi, 8 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &ZZi, 8 ) );
mbedtls_p256_inv( &Zi, &pt->Z, &grp->P );
mbedtls_p256_mul( ZZi.p, Zi.p, 4, Zi.p, 4 );
mbedtls_p256_mul( pt->X.p, pt->X.p, 4, ZZi.p, 4 );
mbedtls_p256_mul( pt->Y.p, pt->Y.p, 4, ZZi.p, 4 );
mbedtls_p256_mul( pt->Y.p, pt->Y.p, 4, Zi.p, 4 );
mbedtls_mpi_lset( &pt->Z, 1 );
cleanup:
mbedtls_mpi_free( &ZZi );
mbedtls_mpi_free( &Zi );
return( ret );
}

701
third_party/mbedtls/ecp384.c vendored Normal file
View file

@ -0,0 +1,701 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/log/check.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/runtime/gc.internal.h"
#include "libc/runtime/runtime.h"
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/ecp.h"
#include "third_party/mbedtls/ecp_internal.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/math.h"
#include "third_party/mbedtls/profile.h"
#include "third_party/mbedtls/traceme.h"
/* clang-format off */
static inline bool
mbedtls_p384_isz( uint64_t p[6] )
{
return( !p[0] & !p[1] & !p[2] & !p[3] & !p[4] & !p[5] );
}
static inline bool
mbedtls_p384_gte( uint64_t p[7] )
{
return( (p[6] ||
p[5] > 0xffffffffffffffff ||
(p[5] == 0xffffffffffffffff &&
p[4] > 0xffffffffffffffff ||
(p[4] == 0xffffffffffffffff &&
p[3] > 0xffffffffffffffff ||
(p[3] == 0xffffffffffffffff &&
p[2] > 0xfffffffffffffffe ||
(p[2] == 0xfffffffffffffffe &&
p[1] > 0xffffffff00000000 ||
(p[1] == 0xffffffff00000000 &&
p[0] > 0x00000000ffffffff ||
(p[0] == 0x00000000ffffffff))))))) );
}
static int
mbedtls_p384_cmp( const uint64_t a[7],
const uint64_t b[7] )
{
if( a[6] < b[6] ) return -1;
if( a[6] > b[6] ) return 1;
if( a[5] < b[5] ) return -1;
if( a[5] > b[5] ) return 1;
if( a[4] < b[4] ) return -1;
if( a[4] > b[4] ) return 1;
if( a[3] < b[3] ) return -1;
if( a[3] > b[3] ) return 1;
if( a[2] < b[2] ) return -1;
if( a[2] > b[2] ) return 1;
if( a[1] < b[1] ) return -1;
if( a[1] > b[1] ) return 1;
if( a[0] < b[0] ) return -1;
if( a[0] > b[0] ) return 1;
return 0;
}
static inline void
mbedtls_p384_red( uint64_t p[7] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("subq\t%1,%0\n\t"
"sbbq\t%2,8+%0\n\t"
"sbbq\t%3,16+%0\n\t"
"sbbq\t%4,24+%0\n\t"
"sbbq\t%4,32+%0\n\t"
"sbbq\t%4,40+%0\n\t"
"sbbq\t$0,48+%0"
: "+o"(*p)
: "r"(0x00000000ffffffffl), "r"(0xffffffff00000000),
"i"(0xfffffffffffffffel), "i"(0xffffffffffffffff)
: "memory", "cc");
#else
uint64_t c;
SBB( p[0], p[0], 0x00000000ffffffff, 0, c );
SBB( p[1], p[1], 0xffffffff00000000, c, c );
SBB( p[2], p[2], 0xfffffffffffffffe, c, c );
SBB( p[3], p[3], 0xffffffffffffffff, c, c );
SBB( p[4], p[4], 0xffffffffffffffff, c, c );
SBB( p[5], p[5], 0xffffffffffffffff, c, c );
SBB( p[6], p[6], 0, c, c );
#endif
}
static noinline void
mbedtls_p384_gro( uint64_t p[7] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("addq\t%1,%0\n\t"
"adcq\t%2,8+%0\n\t"
"adcq\t%3,16+%0\n\t"
"adcq\t%4,24+%0\n\t"
"adcq\t%4,32+%0\n\t"
"adcq\t%4,40+%0\n\t"
"adcq\t$0,48+%0"
: "+o"(*p)
: "r"(0x00000000ffffffffl), "r"(0xffffffff00000000),
"i"(0xfffffffffffffffel), "i"(0xffffffffffffffff)
: "memory", "cc");
#else
uint64_t c;
ADC( p[0], p[0], 0x00000000ffffffff, 0, c );
ADC( p[1], p[1], 0xffffffff00000000, c, c );
ADC( p[2], p[2], 0xfffffffffffffffe, c, c );
ADC( p[3], p[3], 0xffffffffffffffff, c, c );
ADC( p[4], p[4], 0xffffffffffffffff, c, c );
ADC( p[5], p[5], 0xffffffffffffffff, c, c );
ADC( p[6], p[6], 0, c, c );
#endif
}
static void
mbedtls_p384_rum( uint64_t p[7] )
{
while( mbedtls_p384_gte( p ) )
mbedtls_p384_red( p );
}
static inline void
mbedtls_p384_sar( uint64_t p[7] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("sarq\t48+%0\n\t"
"rcrq\t40+%0\n\t"
"rcrq\t32+%0\n\t"
"rcrq\t24+%0\n\t"
"rcrq\t16+%0\n\t"
"rcrq\t8+%0\n\t"
"rcrq\t%0\n\t"
: "+o"(*p)
: /* no inputs */
: "memory", "cc");
#else
p[0] = p[0] >> 1 | p[1] << 63;
p[1] = p[1] >> 1 | p[2] << 63;
p[2] = p[2] >> 1 | p[3] << 63;
p[3] = p[3] >> 1 | p[4] << 63;
p[4] = p[4] >> 1 | p[5] << 63;
p[5] = p[5] >> 1 | p[6] << 63;
p[6] = (int64_t)p[6] >> 1;
#endif
}
static inline void
mbedtls_p384_shl( uint64_t p[7] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("shlq\t%0\n\t"
"rclq\t8+%0\n\t"
"rclq\t16+%0\n\t"
"rclq\t24+%0\n\t"
"rclq\t32+%0\n\t"
"rclq\t40+%0\n\t"
"rclq\t48+%0\n\t"
: "+o"(*p)
: /* no inputs */
: "memory", "cc");
#else
p[6] = p[5] >> 63;
p[5] = p[5] << 1 | p[4] >> 63;
p[4] = p[4] << 1 | p[3] >> 63;
p[3] = p[3] << 1 | p[2] >> 63;
p[2] = p[2] << 1 | p[1] >> 63;
p[1] = p[1] << 1 | p[0] >> 63;
p[0] = p[0] << 1;
#endif
mbedtls_p384_rum( p );
}
static inline void
mbedtls_p384_jam( uint64_t p[7] )
{
secp384r1( p );
if( (int64_t)p[6] < 0 )
do
mbedtls_p384_gro( p );
while( (int64_t)p[6] < 0 );
else
mbedtls_p384_rum( p );
}
static void
mbedtls_p384_mul_1x1( uint64_t X[12],
const uint64_t A[6], size_t n,
const uint64_t B[6], size_t m )
{
uint128_t t;
t = A[0];
t *= B[0];
X[ 0] = t;
X[ 1] = t >> 64;
X[ 2] = 0;
X[ 3] = 0;
X[ 4] = 0;
X[ 5] = 0;
X[ 6] = 0;
X[ 7] = 0;
X[ 8] = 0;
X[ 9] = 0;
X[10] = 0;
X[11] = 0;
}
static void
mbedtls_p384_mul_nx1( uint64_t X[12],
const uint64_t A[6], size_t n,
const uint64_t B[6], size_t m )
{
mbedtls_mpi_mul_hlp1(n, A, X, B[0]);
mbedtls_platform_zeroize( X + n + m, ( 12 - n - m ) * 8 );
if ( n + m >= 6 )
mbedtls_p384_jam( X );
}
static void
mbedtls_p384_mul_6x6( uint64_t X[12],
const uint64_t A[6], size_t n,
const uint64_t B[6], size_t m )
{
Mul6x6Adx( X, A, B );
mbedtls_p384_jam( X );
}
static void
mbedtls_p384_mul_nxm( uint64_t X[12],
const uint64_t A[6], size_t n,
const uint64_t B[6], size_t m )
{
if (A == X) A = gc(memcpy(malloc(6 * 8), A, 6 * 8));
if (B == X) B = gc(memcpy(malloc(6 * 8), B, 6 * 8));
Mul( X, A, n, B, m );
mbedtls_platform_zeroize( X + n + m, (12 - n - m) * 8 );
if ( n + m >= 6 )
mbedtls_p384_jam( X );
}
static void
mbedtls_p384_mul( uint64_t X[12],
const uint64_t A[6], size_t n,
const uint64_t B[6], size_t m )
{
if( n == 6 && m == 6 && X86_HAVE(ADX) && X86_HAVE(BMI2) )
mbedtls_p384_mul_6x6( X, A, n, B, m );
else if( m == 1 && n == 1 )
mbedtls_p384_mul_1x1( X, A, n, B, m );
else if( m == 1 )
mbedtls_p384_mul_nx1( X, A, n, B, m );
else
mbedtls_p384_mul_nxm( X, A, n, B, m );
}
static void
mbedtls_p384_add( uint64_t X[7],
const uint64_t A[6],
const uint64_t B[6] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("xor\t%%rcx,%%rcx\n\t"
"mov\t%1,%%rax\n\t"
"add\t%2,%%rax\n\t"
"mov\t%%rax,%0\n\t"
"mov\t8+%1,%%rax\n\t"
"adc\t8+%2,%%rax\n\t"
"mov\t%%rax,8+%0\n\t"
"mov\t16+%1,%%rax\n\t"
"adc\t16+%2,%%rax\n\t"
"mov\t%%rax,16+%0\n\t"
"mov\t24+%1,%%rax\n\t"
"adc\t24+%2,%%rax\n\t"
"mov\t%%rax,24+%0\n\t"
"mov\t32+%1,%%rax\n\t"
"adc\t32+%2,%%rax\n\t"
"mov\t%%rax,32+%0\n\t"
"mov\t40+%1,%%rax\n\t"
"adc\t40+%2,%%rax\n\t"
"mov\t%%rax,40+%0\n\t"
"adc\t$0,%%rcx\n\t"
"mov\t%%rcx,48+%0"
: "+o"(*X)
: "o"(*A), "o"(*B)
: "rax", "rcx", "memory", "cc");
#else
uint64_t c;
ADC( X[0], A[0], B[0], 0, c );
ADC( X[1], A[1], B[1], c, c );
ADC( X[2], A[2], B[2], c, c );
ADC( X[3], A[3], B[3], c, c );
ADC( X[4], A[4], B[4], c, c );
ADC( X[5], A[5], B[5], c, X[6] );
#endif
mbedtls_p384_rum( X );
DCHECK_EQ(0, X[6]);
}
static void
mbedtls_p384_sub( uint64_t X[7],
const uint64_t A[6],
const uint64_t B[6] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("xor\t%%rcx,%%rcx\n\t"
"mov\t%1,%%rax\n\t"
"sub\t%2,%%rax\n\t"
"mov\t%%rax,%0\n\t"
"mov\t8+%1,%%rax\n\t"
"sbb\t8+%2,%%rax\n\t"
"mov\t%%rax,8+%0\n\t"
"mov\t16+%1,%%rax\n\t"
"sbb\t16+%2,%%rax\n\t"
"mov\t%%rax,16+%0\n\t"
"mov\t24+%1,%%rax\n\t"
"sbb\t24+%2,%%rax\n\t"
"mov\t%%rax,24+%0\n\t"
"mov\t32+%1,%%rax\n\t"
"sbb\t32+%2,%%rax\n\t"
"mov\t%%rax,32+%0\n\t"
"mov\t40+%1,%%rax\n\t"
"sbb\t40+%2,%%rax\n\t"
"mov\t%%rax,40+%0\n\t"
"sbb\t$0,%%rcx\n\t"
"mov\t%%rcx,48+%0"
: "+o"(*X)
: "o"(*A), "o"(*B)
: "rax", "rcx", "memory", "cc");
#else
uint64_t c;
SBB( X[0], A[0], B[0], 0, c );
SBB( X[1], A[1], B[1], c, c );
SBB( X[2], A[2], B[2], c, c );
SBB( X[3], A[3], B[3], c, c );
SBB( X[4], A[4], B[4], c, c );
SBB( X[5], A[5], B[5], c, c );
X[6] = -c;
#endif
while( (int64_t)X[6] < 0 )
mbedtls_p384_gro( X );
DCHECK_EQ(0, X[6]);
}
static void
mbedtls_p384_hub( uint64_t A[7],
const uint64_t B[6] )
{
#if defined(__x86_64__) && !defined(__STRICT_ANSI__)
asm("xor\t%%rcx,%%rcx\n\t"
"mov\t%1,%%rax\n\t"
"sub\t%%rax,%0\n\t"
"mov\t8+%1,%%rax\n\t"
"sbb\t%%rax,8+%0\n\t"
"mov\t16+%1,%%rax\n\t"
"sbb\t%%rax,16+%0\n\t"
"mov\t24+%1,%%rax\n\t"
"sbb\t%%rax,24+%0\n\t"
"mov\t32+%1,%%rax\n\t"
"sbb\t%%rax,32+%0\n\t"
"mov\t40+%1,%%rax\n\t"
"sbb\t%%rax,40+%0\n\t"
"sbb\t$0,%%rcx\n\t"
"mov\t%%rcx,48+%0"
: "+o"(*A)
: "o"(*B)
: "rax", "rcx", "memory", "cc");
while( (int64_t)A[6] < 0 )
mbedtls_p384_gro( A );
DCHECK_EQ(0, A[6]);
#else
mbedtls_p384_sub(A, A, B);
#endif
}
static inline void
mbedtls_p384_cop( uint64_t X[6],
const uint64_t Y[6] )
{
memcpy( X, Y, 6 * 8 );
}
static int
mbedtls_p384_dim( mbedtls_ecp_point *R )
{
int ret;
if( R->X.n < 6 && ( ret = mbedtls_mpi_grow( &R->X, 6 ) ) ) return ret;
if( R->Y.n < 6 && ( ret = mbedtls_mpi_grow( &R->Y, 6 ) ) ) return ret;
if( R->Z.n < 6 && ( ret = mbedtls_mpi_grow( &R->Z, 6 ) ) ) return ret;
return 0;
}
int mbedtls_p384_double_jac( const mbedtls_ecp_group *G,
const mbedtls_ecp_point *P,
mbedtls_ecp_point *R )
{
int ret;
struct {
uint64_t X[6], Y[6], Z[6];
uint64_t M[12], S[12], T[12], U[12];
size_t Xn, Yn, Zn;
} s;
MBEDTLS_ASSERT( G->A.p == 0 );
MBEDTLS_ASSERT( P->X.s == 1 );
MBEDTLS_ASSERT( P->Y.s == 1 );
MBEDTLS_ASSERT( P->Z.s == 1 );
MBEDTLS_ASSERT( G->P.p[0] == 0x00000000ffffffff );
MBEDTLS_ASSERT( G->P.p[1] == 0xffffffff00000000 );
MBEDTLS_ASSERT( G->P.p[2] == 0xfffffffffffffffe );
MBEDTLS_ASSERT( G->P.p[3] == 0xffffffffffffffff );
MBEDTLS_ASSERT( G->P.p[4] == 0xffffffffffffffff );
MBEDTLS_ASSERT( G->P.p[5] == 0xffffffffffffffff );
if ( ( ret = mbedtls_p384_dim( R ) ) ) return ret;
mbedtls_platform_zeroize( &s, sizeof( s ) );
s.Xn = mbedtls_mpi_limbs( &P->X );
s.Yn = mbedtls_mpi_limbs( &P->Y );
s.Zn = mbedtls_mpi_limbs( &P->Z );
CHECK_LE( s.Xn, 6 );
CHECK_LE( s.Yn, 6 );
CHECK_LE( s.Zn, 6 );
memcpy( s.X, P->X.p, s.Xn * 8 );
memcpy( s.Y, P->Y.p, s.Yn * 8 );
memcpy( s.Z, P->Z.p, s.Zn * 8 );
mbedtls_p384_mul( s.S, s.Z, s.Zn, s.Z, s.Zn );
mbedtls_p384_add( s.T, s.X, s.S );
mbedtls_p384_sub( s.U, s.X, s.S );
mbedtls_p384_mul( s.S, s.T, 6, s.U, 6 );
mbedtls_mpi_mul_hlp1( 6, s.S, s.M, 3 );
mbedtls_p384_rum( s.M );
mbedtls_p384_mul( s.T, s.Y, s.Yn, s.Y, s.Yn );
mbedtls_p384_shl( s.T );
mbedtls_p384_mul( s.S, s.X, s.Xn, s.T, 6 );
mbedtls_p384_shl( s.S );
mbedtls_p384_mul( s.U, s.T, 6, s.T, 6 );
mbedtls_p384_shl( s.U );
mbedtls_p384_mul( s.T, s.M, 6, s.M, 6 );
mbedtls_p384_hub( s.T, s.S );
mbedtls_p384_hub( s.T, s.S );
mbedtls_p384_hub( s.S, s.T );
mbedtls_p384_mul( s.S, s.S, 6, s.M, 6 );
mbedtls_p384_hub( s.S, s.U );
mbedtls_p384_mul( s.U, s.Y, s.Yn, s.Z, s.Zn );
mbedtls_p384_shl( s.U );
mbedtls_p384_cop( R->X.p, s.T );
mbedtls_p384_cop( R->Y.p, s.S );
mbedtls_p384_cop( R->Z.p, s.U );
mbedtls_platform_zeroize( &s, sizeof(s) );
return 0;
}
int mbedtls_p384_add_mixed( const mbedtls_ecp_group *G,
const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q,
mbedtls_ecp_point *R )
{
int ret;
struct {
uint64_t X[12], Y[12], Z[12];
uint64_t T1[12], T2[12], T3[12], T4[12];
size_t Xn, Yn, Zn, QXn, QYn;
} s;
MBEDTLS_ASSERT( P->X.s == 1 );
MBEDTLS_ASSERT( P->Y.s == 1 );
MBEDTLS_ASSERT( P->Z.s == 1 );
MBEDTLS_ASSERT( Q->X.s == 1 );
MBEDTLS_ASSERT( Q->Y.s == 1 );
if ( ( ret = mbedtls_p384_dim( R ) ) ) return ret;
mbedtls_platform_zeroize(&s, sizeof(s));
s.Xn = mbedtls_mpi_limbs( &P->X );
s.Yn = mbedtls_mpi_limbs( &P->Y );
s.Zn = mbedtls_mpi_limbs( &P->Z );
s.QXn = mbedtls_mpi_limbs( &Q->X );
s.QYn = mbedtls_mpi_limbs( &Q->Y );
CHECK_LE( s.Xn, 6 );
CHECK_LE( s.Yn, 6 );
CHECK_LE( s.Zn, 6 );
CHECK_LE( s.QXn, 6 );
CHECK_LE( s.QYn, 6 );
memcpy( s.X, P->X.p, s.Xn * 8 );
memcpy( s.Y, P->Y.p, s.Yn * 8 );
memcpy( s.Z, P->Z.p, s.Zn * 8 );
mbedtls_p384_mul( s.T1, s.Z, s.Zn, s.Z, s.Zn );
mbedtls_p384_mul( s.T2, s.T1, 6, s.Z, s.Zn );
mbedtls_p384_mul( s.T1, s.T1, 6, Q->X.p, s.QXn );
mbedtls_p384_mul( s.T2, s.T2, 6, Q->Y.p, s.QYn );
mbedtls_p384_hub( s.T1, s.X );
mbedtls_p384_hub( s.T2, s.Y );
if( mbedtls_p384_isz( s.T1 ) )
{
if( mbedtls_p384_isz( s.T2 ) )
return mbedtls_p384_double_jac( G, P, R );
else
return mbedtls_ecp_set_zero( R );
}
mbedtls_p384_mul( s.Z, s.Z, s.Zn, s.T1, 6 );
mbedtls_p384_mul( s.T3, s.T1, 6, s.T1, 6 );
mbedtls_p384_mul( s.T4, s.T3, 6, s.T1, 6 );
mbedtls_p384_mul( s.T3, s.T3, 6, s.X, s.Xn );
mbedtls_p384_cop( s.T1, s.T3 );
mbedtls_p384_shl( s.T1 );
mbedtls_p384_mul( s.X, s.T2, 6, s.T2, 6 );
mbedtls_p384_hub( s.X, s.T1 );
mbedtls_p384_hub( s.X, s.T4 );
mbedtls_p384_hub( s.T3, s.X );
mbedtls_p384_mul( s.T3, s.T3, 6, s.T2, 6 );
mbedtls_p384_mul( s.T4, s.T4, 6, s.Y, s.Yn );
mbedtls_p384_sub( s.Y, s.T3, s.T4 );
mbedtls_p384_cop( R->X.p, s.X );
mbedtls_p384_cop( R->Y.p, s.Y );
mbedtls_p384_cop( R->Z.p, s.Z );
mbedtls_platform_zeroize( &s, sizeof( s ) );
return 0;
}
static int mbedtls_p384_inv_mod(mbedtls_mpi *X,
const mbedtls_mpi *A,
const mbedtls_mpi *N)
{
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
MBEDTLS_ASSERT( A->s == 1 );
MBEDTLS_ASSERT( N->s == 1 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( X ) <= 6 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( A ) <= 6 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( N ) <= 6 );
MBEDTLS_ASSERT( mbedtls_mpi_cmp_int( N, 1 ) > 0 );
mbedtls_mpi_init( &TA );
mbedtls_mpi_init( &TU );
mbedtls_mpi_init( &U1 );
mbedtls_mpi_init( &U2 );
mbedtls_mpi_init( &G );
mbedtls_mpi_init( &TB );
mbedtls_mpi_init( &TV );
mbedtls_mpi_init( &V1 );
mbedtls_mpi_init( &V2 );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TA, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TU, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &U1, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &U2, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &G, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TB, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &TV, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &V1, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &V2, 7 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, A, N ) );
if (!mbedtls_mpi_is_one( &G ))
{
ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &TA, A, N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TU, &TA ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TV, N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U1, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U2, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V2, 1 ) );
do
{
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TU ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U1 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U2 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TV ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V2 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V1 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &G ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TA ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TB ) <= 7 );
while ( !( TU.p[0] & 1 ) )
{
mbedtls_p384_sar( TU.p );
if ((U1.p[0] & 1) || (U2.p[0] & 1))
{
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &U1, &U1, &TB ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &TA ) );
}
mbedtls_p384_sar(U1.p);
mbedtls_p384_sar(U2.p);
}
while ( !( TV.p[0] & 1 ) )
{
mbedtls_p384_sar(TV.p);
if ((V1.p[0] & 1) || (V2.p[0] & 1))
{
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, &TB ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &TA ) );
}
mbedtls_p384_sar( V1.p );
mbedtls_p384_sar( V2.p );
}
if (mbedtls_mpi_cmp_mpi( &TU, &TV ) >= 0)
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TU, &TU, &TV ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U1, &U1, &V1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &V2 ) );
}
else
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TV, &TV, &TU ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, &U1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &U2 ) );
}
} while ( TU.p[0] | TU.p[1] | TU.p[2] | TU.p[3] | TU.p[4] | TU.p[5] );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TU ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U1 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &U2 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TV ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V2 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &V1 ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &G ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TA ) <= 7 );
MBEDTLS_ASSERT( mbedtls_mpi_limbs( &TB ) <= 7 );
while (V1.s < 0)
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, N ) );
while (mbedtls_mpi_cmp_mpi( &V1, N ) >= 0)
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &V1 ) );
cleanup:
mbedtls_mpi_free( &TA );
mbedtls_mpi_free( &TU );
mbedtls_mpi_free( &U1 );
mbedtls_mpi_free( &U2 );
mbedtls_mpi_free( &G );
mbedtls_mpi_free( &TB );
mbedtls_mpi_free( &TV );
mbedtls_mpi_free( &V1 );
mbedtls_mpi_free( &V2 );
return ret;
}
int mbedtls_p384_normalize_jac_many( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *T[], size_t T_size )
{
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i;
uint64_t ta[12];
mbedtls_mpi *c, u, Zi, ZZi;
if( !( c = mbedtls_calloc( T_size, sizeof( mbedtls_mpi ) ) ) )
return( MBEDTLS_ERR_ECP_ALLOC_FAILED );
mbedtls_mpi_init( &u );
mbedtls_mpi_init( &Zi );
mbedtls_mpi_init( &ZZi );
for( i = 0; i < T_size; i++ )
{
CHECK_EQ( 6, T[i]->X.n );
CHECK_EQ( 6, T[i]->Y.n );
CHECK_EQ( 6, T[i]->Z.n );
mbedtls_mpi_init( c + i );
}
for( i = 0; i < T_size; i++ )
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( c + i, 12 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &u, 12 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &Zi, 12 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &ZZi, 12 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( c, &T[0]->Z ) );
for( i = 1; i < T_size; i++ )
mbedtls_p384_mul( c[i].p, c[i-1].p, 6, T[i]->Z.p, 6 );
MBEDTLS_MPI_CHK( mbedtls_p384_inv_mod( &u, c + T_size - 1, &grp->P ) );
for( i = T_size - 1; ; i-- )
{
if( !i )
memcpy( Zi.p, u.p, 6 * 8 );
else
{
mbedtls_p384_mul( Zi.p, u.p, 6, c[i-1].p, 6 );
mbedtls_p384_mul( u.p, u.p, 6, T[i]->Z.p, 6 );
}
mbedtls_p384_mul( ZZi.p, Zi.p, 6, Zi.p, 6 );
mbedtls_p384_mul( ta, T[i]->X.p, 6, ZZi.p, 6 );
memcpy( T[i]->X.p, ta, 6 * 8 );
mbedtls_p384_mul( ta, T[i]->Y.p, 6, ZZi.p, 6 );
mbedtls_p384_mul( ta, ta, 6, Zi.p, 6 );
memcpy( T[i]->Y.p, ta, 6 * 8 );
mbedtls_mpi_free( &T[i]->Z );
if( !i ) break;
}
cleanup:
mbedtls_platform_zeroize( ta, sizeof( ta ) );
for( i = 0; i < T_size; i++ )
mbedtls_mpi_free( c + i );
mbedtls_mpi_free( &ZZi );
mbedtls_mpi_free( &Zi );
mbedtls_mpi_free( &u );
mbedtls_free( c );
return( ret );
}

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/ecp.h"
#include "third_party/mbedtls/error.h"
@ -29,7 +46,7 @@ asm(".include \"libc/disclaimer.inc\"");
* limitations under the License.
*/
#if defined(MBEDTLS_ECP_C)
/* #if defined(MBEDTLS_ECP_C) */
#if !defined(MBEDTLS_ECP_ALT)
@ -618,29 +635,23 @@ static int ecp_group_load( mbedtls_ecp_group *grp,
#endif /* ECP_LOAD_GROUP */
#if defined(MBEDTLS_ECP_NIST_OPTIM)
/* Forward declarations */
#define NIST_MODP( P ) grp->modp = ecp_mod_ ## P;
#else
#define NIST_MODP( P )
#endif
#if defined(MBEDTLS_ECP_NIST_OPTIM)
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
static int ecp_mod_p192( mbedtls_mpi * );
#endif
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
static int ecp_mod_p224( mbedtls_mpi * );
#endif
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
static int ecp_mod_p256( mbedtls_mpi * );
#endif
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
static int ecp_mod_p384( mbedtls_mpi * );
#endif
#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
static int ecp_mod_p521( mbedtls_mpi * );
#endif
#define NIST_MODP( P ) grp->modp = ecp_mod_ ## P;
#else
#define NIST_MODP( P )
#endif /* MBEDTLS_ECP_NIST_OPTIM */
/* Additional forward declarations */
#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
static int ecp_mod_p255( mbedtls_mpi * );
#endif
@ -681,7 +692,7 @@ static int ecp_mod_p256k1( mbedtls_mpi * );
*/
static int ecp_use_curve25519( mbedtls_ecp_group *grp )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
/* Actually ( A + 2 ) / 4 */
MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->A, 16, "01DB42" ) );
@ -721,7 +732,7 @@ cleanup:
static int ecp_use_curve448( mbedtls_ecp_group *grp )
{
mbedtls_mpi Ns;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi_init( &Ns );
@ -760,6 +771,8 @@ cleanup:
}
#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */
#if defined(MBEDTLS_ECP_C)
/**
* \brief This function sets up an ECP group context
* from a standardized set of domain parameters.
@ -866,6 +879,7 @@ int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id )
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
}
}
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_ECP_NIST_OPTIM)
/*
@ -878,7 +892,6 @@ int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id )
* MPI remains loose, since these functions can be deactivated at will.
*/
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
/*
* Compared to the way things are presented in FIPS 186-3 D.2,
* we proceed in columns, from right (least significant chunk) to left,
@ -926,20 +939,16 @@ static inline void carry64( mbedtls_mpi_uint *dst, mbedtls_mpi_uint *carry )
*/
static int ecp_mod_p192( mbedtls_mpi *N )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi_uint c = 0;
mbedtls_mpi_uint *p, *end;
/* Make sure we have enough blocks so that A(5) is legal */
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( N, 6 * WIDTH ) );
p = N->p;
end = p + N->n;
ADD( 3 ); ADD( 5 ); NEXT; // A0 += A3 + A5
ADD( 3 ); ADD( 4 ); ADD( 5 ); NEXT; // A1 += A3 + A4 + A5
ADD( 4 ); ADD( 5 ); LAST; // A2 += A4 + A5
cleanup:
return( ret );
}
@ -949,11 +958,7 @@ cleanup:
#undef ADD
#undef NEXT
#undef LAST
#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
/*
* The reader is advised to first understand ecp_mod_p192() since the same
* general structure is used here, but with additional complications:
@ -1017,7 +1022,7 @@ static inline void sub32( uint32_t *dst, uint32_t src, signed char *carry )
* (see fix_negative for the motivation of C)
*/
#define INIT( b ) \
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; \
int ret = MBEDTLS_ERR_THIS_CORRUPTION; \
signed char c = 0, cc; \
uint32_t cur; \
size_t i = 0, bits = (b); \
@ -1053,8 +1058,7 @@ static inline void sub32( uint32_t *dst, uint32_t src, signed char *carry )
*/
static inline int fix_negative( mbedtls_mpi *N, signed char c, mbedtls_mpi *C, size_t bits )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
/* C = - c * 2^(bits + 32) */
#if !defined(MBEDTLS_HAVE_INT64)
((void) bits);
@ -1064,24 +1068,19 @@ static inline int fix_negative( mbedtls_mpi *N, signed char c, mbedtls_mpi *C, s
else
#endif
C->p[ C->n - 1 ] = (mbedtls_mpi_uint) -c;
/* N = - ( C - N ) */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, C, N ) );
N->s = -1;
cleanup:
return( ret );
}
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
/*
* Fast quasi-reduction modulo p224 (FIPS 186-3 D.2.2)
*/
static int ecp_mod_p224( mbedtls_mpi *N )
{
INIT( 224 );
SUB( 7 ); SUB( 11 ); NEXT; // A0 += -A7 - A11
SUB( 8 ); SUB( 12 ); NEXT; // A1 += -A8 - A12
SUB( 9 ); SUB( 13 ); NEXT; // A2 += -A9 - A13
@ -1089,97 +1088,9 @@ static int ecp_mod_p224( mbedtls_mpi *N )
SUB( 11 ); ADD( 8 ); ADD( 12 ); NEXT; // A4 += -A11 + A8 + A12
SUB( 12 ); ADD( 9 ); ADD( 13 ); NEXT; // A5 += -A12 + A9 + A13
SUB( 13 ); ADD( 10 ); LAST; // A6 += -A13 + A10
cleanup:
return( ret );
}
#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
/*
* Fast quasi-reduction modulo p256 (FIPS 186-3 D.2.3)
*/
static int ecp_mod_p256( mbedtls_mpi *N )
{
INIT( 256 );
ADD( 8 ); ADD( 9 );
SUB( 11 ); SUB( 12 ); SUB( 13 ); SUB( 14 ); NEXT; // A0
ADD( 9 ); ADD( 10 );
SUB( 12 ); SUB( 13 ); SUB( 14 ); SUB( 15 ); NEXT; // A1
ADD( 10 ); ADD( 11 );
SUB( 13 ); SUB( 14 ); SUB( 15 ); NEXT; // A2
ADD( 11 ); ADD( 11 ); ADD( 12 ); ADD( 12 ); ADD( 13 );
SUB( 15 ); SUB( 8 ); SUB( 9 ); NEXT; // A3
ADD( 12 ); ADD( 12 ); ADD( 13 ); ADD( 13 ); ADD( 14 );
SUB( 9 ); SUB( 10 ); NEXT; // A4
ADD( 13 ); ADD( 13 ); ADD( 14 ); ADD( 14 ); ADD( 15 );
SUB( 10 ); SUB( 11 ); NEXT; // A5
ADD( 14 ); ADD( 14 ); ADD( 15 ); ADD( 15 ); ADD( 14 ); ADD( 13 );
SUB( 8 ); SUB( 9 ); NEXT; // A6
ADD( 15 ); ADD( 15 ); ADD( 15 ); ADD( 8 );
SUB( 10 ); SUB( 11 ); SUB( 12 ); SUB( 13 ); LAST; // A7
cleanup:
return( ret );
}
#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
/*
* Fast quasi-reduction modulo p384 (FIPS 186-3 D.2.4)
*/
static int ecp_mod_p384( mbedtls_mpi *N )
{
INIT( 384 );
ADD( 12 ); ADD( 21 ); ADD( 20 );
SUB( 23 ); NEXT; // A0
ADD( 13 ); ADD( 22 ); ADD( 23 );
SUB( 12 ); SUB( 20 ); NEXT; // A2
ADD( 14 ); ADD( 23 );
SUB( 13 ); SUB( 21 ); NEXT; // A2
ADD( 15 ); ADD( 12 ); ADD( 20 ); ADD( 21 );
SUB( 14 ); SUB( 22 ); SUB( 23 ); NEXT; // A3
ADD( 21 ); ADD( 21 ); ADD( 16 ); ADD( 13 ); ADD( 12 ); ADD( 20 ); ADD( 22 );
SUB( 15 ); SUB( 23 ); SUB( 23 ); NEXT; // A4
ADD( 22 ); ADD( 22 ); ADD( 17 ); ADD( 14 ); ADD( 13 ); ADD( 21 ); ADD( 23 );
SUB( 16 ); NEXT; // A5
ADD( 23 ); ADD( 23 ); ADD( 18 ); ADD( 15 ); ADD( 14 ); ADD( 22 );
SUB( 17 ); NEXT; // A6
ADD( 19 ); ADD( 16 ); ADD( 15 ); ADD( 23 );
SUB( 18 ); NEXT; // A7
ADD( 20 ); ADD( 17 ); ADD( 16 );
SUB( 19 ); NEXT; // A8
ADD( 21 ); ADD( 18 ); ADD( 17 );
SUB( 20 ); NEXT; // A9
ADD( 22 ); ADD( 19 ); ADD( 18 );
SUB( 21 ); NEXT; // A10
ADD( 23 ); ADD( 20 ); ADD( 19 );
SUB( 22 ); LAST; // A11
cleanup:
return( ret );
}
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
#undef A
#undef LOAD32
@ -1189,10 +1100,6 @@ cleanup:
#undef NEXT
#undef LAST
#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED ||
MBEDTLS_ECP_DP_SECP256R1_ENABLED ||
MBEDTLS_ECP_DP_SECP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
/*
* Here we have an actual Mersenne prime, so things are more straightforward.
@ -1211,7 +1118,7 @@ cleanup:
*/
static int ecp_mod_p521( mbedtls_mpi *N )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i;
mbedtls_mpi M;
mbedtls_mpi_uint Mp[P521_WIDTH + 1];
@ -1249,8 +1156,6 @@ cleanup:
#endif /* MBEDTLS_ECP_NIST_OPTIM */
#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
/* Size of p255 in terms of mbedtls_mpi_uint */
#define P255_WIDTH ( 255 / 8 / sizeof( mbedtls_mpi_uint ) + 1 )
@ -1260,38 +1165,32 @@ cleanup:
*/
static int ecp_mod_p255( mbedtls_mpi *N )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i;
mbedtls_mpi M;
mbedtls_mpi_uint Mp[P255_WIDTH + 2];
if( N->n < P255_WIDTH )
return( 0 );
/* M = A1 */
M.s = 1;
M.n = N->n - ( P255_WIDTH - 1 );
if( M.n > P255_WIDTH + 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
M.p = Mp;
memset( Mp, 0, sizeof Mp );
mbedtls_platform_zeroize( Mp, sizeof Mp );
memcpy( Mp, N->p + P255_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 255 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) );
M.n++; /* Make room for multiplication by 19 */
/* N = A0 */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( N, 255, 0 ) );
for( i = P255_WIDTH; i < N->n; i++ )
N->p[i] = 0;
/* N = A0 + 19 * A1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &M, 19 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) );
cleanup:
return( ret );
}
#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */
#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
@ -1317,7 +1216,7 @@ cleanup:
*/
static int ecp_mod_p448( mbedtls_mpi *N )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i;
mbedtls_mpi M, Q;
mbedtls_mpi_uint Mp[P448_WIDTH + 1], Qp[P448_WIDTH];
@ -1332,7 +1231,7 @@ static int ecp_mod_p448( mbedtls_mpi *N )
/* Shouldn't be called with N larger than 2^896! */
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
M.p = Mp;
memset( Mp, 0, sizeof( Mp ) );
mbedtls_platform_zeroize( Mp, sizeof( Mp ) );
memcpy( Mp, N->p + P448_WIDTH, M.n * sizeof( mbedtls_mpi_uint ) );
/* N = A0 */
@ -1379,7 +1278,7 @@ cleanup:
static inline int ecp_mod_koblitz( mbedtls_mpi *N, mbedtls_mpi_uint *Rp, size_t p_limbs,
size_t adjust, size_t shift, mbedtls_mpi_uint mask )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i;
mbedtls_mpi M, R;
mbedtls_mpi_uint Mp[P_KOBLITZ_MAX + P_KOBLITZ_R + 1];
@ -1400,7 +1299,7 @@ static inline int ecp_mod_koblitz( mbedtls_mpi *N, mbedtls_mpi_uint *Rp, size_t
M.n = N->n - ( p_limbs - adjust );
if( M.n > p_limbs + adjust )
M.n = p_limbs + adjust;
memset( Mp, 0, sizeof Mp );
mbedtls_platform_zeroize( Mp, sizeof Mp );
memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );
if( shift != 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) );
@ -1422,7 +1321,7 @@ static inline int ecp_mod_koblitz( mbedtls_mpi *N, mbedtls_mpi_uint *Rp, size_t
M.n = N->n - ( p_limbs - adjust );
if( M.n > p_limbs + adjust )
M.n = p_limbs + adjust;
memset( Mp, 0, sizeof Mp );
mbedtls_platform_zeroize( Mp, sizeof Mp );
memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );
if( shift != 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) );
@ -1493,4 +1392,4 @@ static int ecp_mod_p256k1( mbedtls_mpi *N )
#endif /* !MBEDTLS_ECP_ALT */
#endif /* MBEDTLS_ECP_C */
/* #endif /\* MBEDTLS_ECP_C *\/ */

View file

@ -1,6 +1,7 @@
#ifndef MBEDTLS_ECP_INTERNAL_H
#define MBEDTLS_ECP_INTERNAL_H
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ECP_INTERNAL_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ECP_INTERNAL_H_
#include "third_party/mbedtls/config.h"
#include "third_party/mbedtls/ecp.h"
/* clang-format off */
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
@ -105,8 +106,9 @@ int mbedtls_internal_ecp_randomize_jac( const mbedtls_ecp_group *grp,
* \return 0 if successful.
*/
int mbedtls_internal_ecp_add_mixed( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q );
mbedtls_ecp_point *R,
const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q );
#endif
/**
@ -178,7 +180,7 @@ int mbedtls_internal_ecp_normalize_jac_many( const mbedtls_ecp_group *grp,
*/
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
int mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt );
mbedtls_ecp_point *pt );
#endif
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
@ -208,8 +210,9 @@ int mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp,
*/
#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
int mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
mbedtls_ecp_point *P,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
#endif
/**
@ -224,12 +227,36 @@ int mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp,
*/
#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
int mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P );
mbedtls_ecp_point *P );
#endif
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
#endif /* MBEDTLS_ECP_INTERNAL_ALT */
#endif /* ecp_internal.h */
void secp256r1( uint64_t[8] );
void secp384r1( uint64_t[12] );
int mbedtls_p256_double_jac( const mbedtls_ecp_group *,
const mbedtls_ecp_point *,
mbedtls_ecp_point * );
int mbedtls_p256_add_mixed( const mbedtls_ecp_group *,
const mbedtls_ecp_point *,
const mbedtls_ecp_point *,
mbedtls_ecp_point * );
int mbedtls_p256_normalize_jac( const mbedtls_ecp_group *,
mbedtls_ecp_point * );
int mbedtls_p256_normalize_jac_many( const mbedtls_ecp_group *,
mbedtls_ecp_point *[], size_t );
int mbedtls_p384_double_jac( const mbedtls_ecp_group *,
const mbedtls_ecp_point *,
mbedtls_ecp_point * );
int mbedtls_p384_add_mixed( const mbedtls_ecp_group *,
const mbedtls_ecp_point *,
const mbedtls_ecp_point *,
mbedtls_ecp_point * );
int mbedtls_p384_normalize_jac_many( const mbedtls_ecp_group *,
mbedtls_ecp_point *[], size_t );
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ECP_INTERNAL_H_ */

105
third_party/mbedtls/ecpshl.c vendored Normal file
View file

@ -0,0 +1,105 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/ecp.h"
#include "third_party/mbedtls/math.h"
/* clang-format off */
static void mbedtls_mpi_shift_l_mod_p256( const mbedtls_ecp_group *G,
mbedtls_mpi *X )
{
bool c;
MBEDTLS_ASSERT( G->P.n == 4 );
MBEDTLS_ASSERT( mbedtls_mpi_bitlen( X ) <= 256 );
MBEDTLS_ASSERT( mbedtls_mpi_bitlen( &G->P ) <= 256 );
X->p[4] = X->p[3] >> 63;
X->p[3] = X->p[3] << 1 | X->p[2] >> 63;
X->p[2] = X->p[2] << 1 | X->p[1] >> 63;
X->p[1] = X->p[1] << 1 | X->p[0] >> 63;
X->p[0] = X->p[0] << 1;
if( (X->p[4] ||
X->p[3] > G->P.p[3] ||
(X->p[3] == G->P.p[3] &&
X->p[2] > G->P.p[2] ||
(X->p[2] == G->P.p[2] &&
X->p[0] > G->P.p[0] ||
(X->p[0] == G->P.p[0])))) )
{
SBB(X->p[0], X->p[0], G->P.p[0], 0, c);
SBB(X->p[1], X->p[1], G->P.p[1], c, c);
SBB(X->p[2], X->p[2], G->P.p[2], c, c);
SBB(X->p[3], X->p[3], G->P.p[3], c, c);
SBB(X->p[4], X->p[4], 0, c, c);
}
}
static void mbedtls_mpi_shift_l_mod_p384( const mbedtls_ecp_group *G,
mbedtls_mpi *X )
{
bool c;
MBEDTLS_ASSERT( G->P.n == 6 );
MBEDTLS_ASSERT( mbedtls_mpi_bitlen( X ) <= 384 );
MBEDTLS_ASSERT( mbedtls_mpi_bitlen( &G->P ) <= 384 );
X->p[6] = X->p[5] >> 63;
X->p[5] = X->p[5] << 1 | X->p[4] >> 63;
X->p[4] = X->p[4] << 1 | X->p[3] >> 63;
X->p[3] = X->p[3] << 1 | X->p[2] >> 63;
X->p[2] = X->p[2] << 1 | X->p[1] >> 63;
X->p[1] = X->p[1] << 1 | X->p[0] >> 63;
X->p[0] = X->p[0] << 1;
if( (X->p[6] ||
X->p[5] > G->P.p[5] ||
(X->p[5] == G->P.p[5] &&
X->p[4] > G->P.p[4] ||
(X->p[4] == G->P.p[4] &&
X->p[3] > G->P.p[3] ||
(X->p[3] == G->P.p[3] &&
X->p[2] > G->P.p[2] ||
(X->p[2] == G->P.p[2] &&
X->p[0] > G->P.p[0] ||
(X->p[0] == G->P.p[0])))))) )
{
SBB(X->p[0], X->p[0], G->P.p[0], 0, c);
SBB(X->p[1], X->p[1], G->P.p[1], c, c);
SBB(X->p[2], X->p[2], G->P.p[2], c, c);
SBB(X->p[3], X->p[3], G->P.p[3], c, c);
SBB(X->p[4], X->p[4], G->P.p[4], c, c);
SBB(X->p[5], X->p[5], G->P.p[5], c, c);
SBB(X->p[6], X->p[6], 0, c, c);
}
}
int mbedtls_mpi_shift_l_mod( const mbedtls_ecp_group *G, mbedtls_mpi *X )
{
int ret = 0;
MBEDTLS_ASSERT( mbedtls_mpi_cmp_int( X, 0 ) >= 0 );
MBEDTLS_ASSERT( mbedtls_mpi_cmp_mpi( X, &G->P ) < 0 );
if( X->n == 8 )
mbedtls_mpi_shift_l_mod_p256( G, X );
else if( X->n == 12 )
mbedtls_mpi_shift_l_mod_p384( G, X );
else
{
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( X, 1 ) );
if( mbedtls_mpi_cmp_mpi( X, &G->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, X, &G->P ) );
}
MBEDTLS_ASSERT( mbedtls_mpi_cmp_mpi( X, &G->P ) < 0 );
MBEDTLS_ASSERT( mbedtls_mpi_cmp_int( X, 0 ) >= 0 );
cleanup:
return( ret );
}

View file

@ -43,6 +43,21 @@
OuT + 8; \
})
#define Write64le(P, V) \
({ \
uint64_t VaL = (V); \
uint8_t *OuT = (P); \
OuT[0] = (0x00000000000000FF & VaL) >> 000; \
OuT[1] = (0x000000000000FF00 & VaL) >> 010; \
OuT[2] = (0x0000000000FF0000 & VaL) >> 020; \
OuT[3] = (0x00000000FF000000 & VaL) >> 030; \
OuT[4] = (0x000000FF00000000 & VaL) >> 040; \
OuT[5] = (0x0000FF0000000000 & VaL) >> 050; \
OuT[6] = (0x00FF000000000000 & VaL) >> 060; \
OuT[7] = (0xFF00000000000000 & VaL) >> 070; \
OuT + 8; \
})
#define GET_UINT32_BE(n, b, i) (n) = Read32be((b) + (i))
#define PUT_UINT32_BE(n, b, i) Write32be((b) + (i), n)
#define GET_UINT64_BE(n, b, i) (n) = Read64be((b) + (i))

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/calls/calls.h"
#include "libc/stdio/stdio.h"
#include "third_party/mbedtls/common.h"
@ -50,7 +67,7 @@ asm(".include \"libc/disclaimer.inc\"");
void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
{
ctx->source_count = 0;
memset( ctx->source, 0, sizeof( ctx->source ) );
mbedtls_platform_zeroize( ctx->source, sizeof( ctx->source ) );
ctx->accumulator_started = 0;
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
@ -315,7 +332,7 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
}
while( ! thresholds_reached || strong_size < MBEDTLS_ENTROPY_BLOCK_SIZE );
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
mbedtls_platform_zeroize( buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
/*
@ -398,7 +415,7 @@ int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )
if( mbedtls_nv_seed_write( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )
return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
/* Manually update the remaining stream with a separator value to diverge */
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
mbedtls_platform_zeroize( buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
ret = mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
return( ret );
}
@ -581,8 +598,8 @@ int mbedtls_entropy_source_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( " ENTROPY_BIAS test: " );
memset( buf0, 0x00, sizeof( buf0 ) );
memset( buf1, 0x00, sizeof( buf1 ) );
mbedtls_platform_zeroize( buf0, sizeof( buf0 ) );
mbedtls_platform_zeroize( buf1, sizeof( buf1 ) );
if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 )
goto cleanup;

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/nexgen32e/rdtsc.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/entropy_poll.h"

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/fmt/fmt.h"
#include "third_party/mbedtls/aes.h"
#include "third_party/mbedtls/asn1.h"
@ -544,7 +561,7 @@ const char * mbedtls_low_level_strerr( int error_code )
#if defined(MBEDTLS_ERROR_C)
case -(MBEDTLS_ERR_ERROR_GENERIC_ERROR):
return( "ERROR - Generic error" );
case -(MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED):
case -(MBEDTLS_ERR_THIS_CORRUPTION):
return( "ERROR - This is a bug in the library" );
#endif /* MBEDTLS_ERROR_C */
@ -637,7 +654,7 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
if( buflen == 0 )
return;
memset( buf, 0x00, buflen );
mbedtls_platform_zeroize( buf, buflen );
if( ret < 0 )
ret = -ret;

View file

@ -85,7 +85,7 @@ extern "C" {
#endif
#define MBEDTLS_ERR_ERROR_GENERIC_ERROR -0x0001 /**< Generic error */
#define MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED -0x006E /**< This is a bug in the library */
#define MBEDTLS_ERR_THIS_CORRUPTION -0x006E /**< This is a bug in the library */
/**
* \brief Translate a mbed TLS error code into a string representation,

File diff suppressed because it is too large Load diff

34
third_party/mbedtls/fastdiv.h vendored Normal file
View file

@ -0,0 +1,34 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_FASTDIV_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_FASTDIV_H_
#include "libc/macros.internal.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct Divisor {
uint64_t m;
uint8_t s;
uint8_t t;
};
static inline struct Divisor GetDivisor(uint64_t d) {
int b;
uint128_t x;
b = __builtin_clzll(d) ^ 63;
x = -d & (((1ull << b) - 1) | (1ull << b));
return (struct Divisor){(x << 64) / d + 1, MIN(1, b + 1), MAX(0, b)};
}
forceinline uint64_t Divide(uint64_t x, struct Divisor d) {
uint128_t t;
uint64_t l, h;
t = d.m;
t *= x;
l = t;
h = t >> 64;
l = (x - h) >> d.s;
return (h + l) >> d.t;
}
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_FASTDIV_H_ */

View file

@ -1,10 +1,29 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "libc/bits/likely.h"
#include "libc/log/log.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/aes.h"
#include "third_party/mbedtls/aesni.h"
#include "third_party/mbedtls/cipher.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/endian.h"
#include "third_party/mbedtls/error.h"
@ -69,7 +88,7 @@ asm(".include \"libc/disclaimer.inc\"");
void mbedtls_gcm_init( mbedtls_gcm_context *ctx )
{
GCM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_gcm_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_gcm_context ) );
}
/*
@ -87,7 +106,7 @@ static int gcm_gen_table( mbedtls_gcm_context *ctx )
uint64_t vl, vh;
unsigned char h[16];
size_t olen = 0;
memset( h, 0, 16 );
mbedtls_platform_zeroize( h, 16 );
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, h, 16, h, &olen ) ) != 0 )
return( ret );
vh = READ64BE( h + 0 );
@ -146,7 +165,7 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
const unsigned char *key,
unsigned int keybits )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const mbedtls_cipher_info_t *cipher_info;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( key != NULL );
@ -158,10 +177,11 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
if( cipher_info->block_size != 16 )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
mbedtls_cipher_free( &ctx->cipher_ctx );
ctx->cipher = cipher;
if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )
return( ret );
if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,
MBEDTLS_ENCRYPT ) ) != 0 ) {
MBEDTLS_ENCRYPT ) ) != 0 ) {
return( ret );
}
if( ( ret = gcm_gen_table( ctx ) ) != 0 )
@ -250,7 +270,7 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
const unsigned char *p;
size_t use_len, olen = 0;
unsigned char work_buf[16];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( iv != NULL );
GCM_VALIDATE_RET( add_len == 0 || add != NULL );
@ -261,8 +281,8 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
( (uint64_t) add_len ) >> 61 != 0 ) {
return( MBEDTLS_ERR_GCM_BAD_INPUT );
}
memset( ctx->y, 0x00, sizeof(ctx->y) );
memset( ctx->buf, 0x00, sizeof(ctx->buf) );
mbedtls_platform_zeroize( ctx->y, sizeof(ctx->y) );
mbedtls_platform_zeroize( ctx->buf, sizeof(ctx->buf) );
ctx->mode = mode;
ctx->len = 0;
ctx->add_len = 0;
@ -270,7 +290,7 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
memcpy( ctx->y, iv, iv_len );
ctx->y[15] = 1;
} else {
memset( work_buf, 0x00, 16 );
mbedtls_platform_zeroize( work_buf, 16 );
PUT_UINT32_BE( iv_len * 8, work_buf, 12 );
p = iv;
while( iv_len > 0 ) {
@ -334,14 +354,14 @@ int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
{
size_t i, j;
uint64_t a, b;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char ectr[16];
const unsigned char *p;
unsigned char *q, *out_p = output;
size_t olen = 0;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( length == 0 || input != NULL );
GCM_VALIDATE_RET( length == 0 || output != NULL );
GCM_VALIDATE_RET( ctx );
GCM_VALIDATE_RET( !length || input );
GCM_VALIDATE_RET( !length || output );
if( output > input && (size_t) ( output - input ) < length )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
/* Total length is restricted to 2^39 - 256 bits, ie 2^36 - 2^5 bytes
@ -529,7 +549,7 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
size_t tag_len,
unsigned char *tag )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( iv != NULL );
GCM_VALIDATE_RET( add_len == 0 || add != NULL );
@ -589,7 +609,7 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char check_tag[16];
size_t i;
int diff;

View file

@ -22,6 +22,7 @@ typedef struct mbedtls_gcm_context {
uint64_t H8[2]; /*!< For AES-NI. */
uint64_t HL[16]; /*!< Precalculated HTable low. */
uint64_t HH[16]; /*!< Precalculated HTable high. */
mbedtls_cipher_id_t cipher; /*!< The cipher being used. */
} mbedtls_gcm_context;
void mbedtls_gcm_init( mbedtls_gcm_context * );

View file

@ -1,20 +1,19 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Copyright The Mbed TLS Contributors
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
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
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
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.
*/
#include "libc/fmt/itoa.h"
#include "third_party/mbedtls/iana.h"

53
third_party/mbedtls/getciphersuite.c vendored Normal file
View file

@ -0,0 +1,53 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "third_party/mbedtls/ssl_ciphersuites.h"
#define S32(S) (S[0] << 24 | S[1] << 16 | S[2] << 8 | S[3])
/**
* Returns ciphersuite info by IANA name.
*
* This API provides some wiggle room for naming, e.g.
*
* - ECDHE-ECDSA-AES256-GCM-SHA384 (preferred)
* - ECDHE-ECDSA-WITH-AES-256-GCM-SHA384
* - TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384
* - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (canonical)
*
* All of the above are acceptable names for 0xC02C.
*/
const mbedtls_ssl_ciphersuite_t *GetCipherSuite(const char *s) {
int i, j;
char b[50];
uint32_t w;
unsigned char c;
for (i = j = w = 0; (c = s[i++]);) {
if (c == '_') c = '-'; // _ → -
if ('a' <= c && c <= 'z') c -= 'a' - 'A'; // a-z → A-Z
if (c == '-' && w == S32("WITH")) j -= 5; // WITH- → -
if (w == S32("TLS-")) j -= 4; // TLS- →
w = w << 8 | c; // ------- ------
if (w == S32("AES-")) continue; // AES-XXX → AESXXX
if (w == S32("SHA1")) continue; // SHA1 → SHA
if (!(0 <= j && j + 1 < sizeof(b))) return 0;
b[j++] = c;
}
b[j++] = 0;
return mbedtls_ssl_ciphersuite_from_string(b);
}

View file

@ -1,20 +1,19 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Copyright The Mbed TLS Contributors
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
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
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
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.
*/
#include "third_party/mbedtls/iana.h"

64
third_party/mbedtls/getsslstatename.c vendored Normal file
View file

@ -0,0 +1,64 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "third_party/mbedtls/ssl.h"
const char *GetSslStateName(mbedtls_ssl_states x) {
switch (x) {
case MBEDTLS_SSL_HELLO_REQUEST:
return "HELLO_REQUEST";
case MBEDTLS_SSL_CLIENT_HELLO:
return "CLIENT_HELLO";
case MBEDTLS_SSL_SERVER_HELLO:
return "SERVER_HELLO";
case MBEDTLS_SSL_SERVER_CERTIFICATE:
return "SERVER_CERTIFICATE";
case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
return "SERVER_KEY_EXCHANGE";
case MBEDTLS_SSL_CERTIFICATE_REQUEST:
return "CERTIFICATE_REQUEST";
case MBEDTLS_SSL_SERVER_HELLO_DONE:
return "SERVER_HELLO_DONE";
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
return "CLIENT_CERTIFICATE";
case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
return "CLIENT_KEY_EXCHANGE";
case MBEDTLS_SSL_CERTIFICATE_VERIFY:
return "CERTIFICATE_VERIFY";
case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
return "CLIENT_CHANGE_CIPHER_SPEC";
case MBEDTLS_SSL_CLIENT_FINISHED:
return "CLIENT_FINISHED";
case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
return "SERVER_CHANGE_CIPHER_SPEC";
case MBEDTLS_SSL_SERVER_FINISHED:
return "SERVER_FINISHED";
case MBEDTLS_SSL_FLUSH_BUFFERS:
return "FLUSH_BUFFERS";
case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
return "HANDSHAKE_WRAPUP";
case MBEDTLS_SSL_HANDSHAKE_OVER:
return "HANDSHAKE_OVER";
case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
return "SERVER_NEW_SESSION_TICKET";
case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
return "SERVER_HELLO_VERIFY_REQUEST_SENT";
default:
return NULL;
}
}

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/str/str.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
@ -35,7 +52,7 @@ int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char prk[MBEDTLS_MD_MAX_SIZE];
ret = mbedtls_hkdf_extract( md, salt, salt_len, ikm, ikm_len, prk );
@ -135,7 +152,7 @@ int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
goto exit;
}
memset( t, 0, hash_len );
mbedtls_platform_zeroize( t, hash_len );
/*
* Compute T = T(1) | T(2) | T(3) | ... | T(N)

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/common.h"
@ -53,7 +70,7 @@ asm(".include \"libc/disclaimer.inc\"");
*/
void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_hmac_drbg_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_hmac_drbg_context ) );
ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;
}
@ -141,7 +158,7 @@ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,
const mbedtls_md_info_t * md_info,
const unsigned char *data, size_t data_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )
return( ret );
@ -173,7 +190,7 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
{
unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT];
size_t seedlen = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
{
size_t total_entropy_len;
@ -191,7 +208,7 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
}
}
memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT );
mbedtls_platform_zeroize( seed, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT );
/* IV. Gather entropy_len bytes of entropy for the seed */
if( ( ret = ctx->f_entropy( ctx->p_entropy,
@ -338,7 +355,7 @@ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
const unsigned char *custom,
size_t len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t md_size;
if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )
@ -466,7 +483,7 @@ int mbedtls_hmac_drbg_random_with_add( void *p_rng,
unsigned char *output, size_t out_len,
const unsigned char *additional, size_t add_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;
size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info );
size_t left = out_len;
@ -584,7 +601,7 @@ void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx )
*/
int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
FILE *f;
unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];

View file

@ -1,20 +1,19 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Copyright The Mbed TLS Contributors
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
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
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
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.
*/
#include "third_party/mbedtls/iana.h"

146
third_party/mbedtls/karatsuba.c vendored Normal file
View file

@ -0,0 +1,146 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/assert.h"
#include "libc/log/check.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/platform.h"
forceinline int Cmp(uint64_t *a, uint64_t *b, size_t n) {
size_t i;
uint64_t x, y;
while (n--) {
x = a[n];
y = b[n];
if (x != y) {
return x > y ? 1 : -1;
}
}
return 0;
}
forceinline bool Sub(uint64_t *C, uint64_t *A, uint64_t *B, size_t n) {
bool cf;
uint64_t c, i;
asm volatile("xor\t%1,%1\n\t"
".align\t16\n1:\t"
"mov\t(%5,%3,8),%1\n\t"
"sbb\t(%6,%3,8),%1\n\t"
"mov\t%1,(%4,%3,8)\n\t"
"lea\t1(%3),%3\n\t"
"dec\t%2\n\t"
"jnz\t1b"
: "=@ccb"(cf), "=&r"(c), "+c"(n), "=r"(i)
: "r"(C), "r"(A), "r"(B), "3"(0)
: "cc", "memory");
return cf;
}
forceinline bool Add(uint64_t *C, uint64_t *A, uint64_t *B, size_t n) {
bool cf;
uint64_t c, i;
asm volatile("xor\t%1,%1\n\t"
".align\t16\n1:\t"
"mov\t(%5,%3,8),%1\n\t"
"adc\t(%6,%3,8),%1\n\t"
"mov\t%1,(%4,%3,8)\n\t"
"lea\t1(%3),%3\n\t"
"dec\t%2\n\t"
"jnz\t1b"
: "=@ccc"(cf), "=&r"(c), "+c"(n), "=r"(i)
: "r"(C), "r"(A), "r"(B), "3"(0)
: "cc", "memory");
return cf;
}
/**
* Multiplies huge numbers faster.
*
* For 4096 bit numbers it's twice as fast.
* For 16384 bit numbers it's thrice as fast.
*/
void Karatsuba(uint64_t *C, uint64_t *A, uint64_t *B, size_t n, uint64_t *K) {
int q, r;
size_t i;
uint64_t c, t;
uint64_t *x, *y;
if (n == 8) {
Mul8x8Adx(C, A, B);
return;
}
switch (Cmp(A, A + n / 2, n / 2) * 3 + Cmp(B + n / 2, B, n / 2)) {
case -1 * 3 + +0:
case +0 * 3 + -1:
case +0 * 3 + +0:
case +0 * 3 + +1:
case +1 * 3 + +0:
Karatsuba(C, A, B, n / 2, K + n * 2);
Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2);
c = Add(K, C, C + n, n);
c += Add(C + n / 2, C + n / 2, K, n);
break;
case -1 * 3 + -1:
Sub(K, A + n / 2, A, n / 2);
Sub(K + n / 2, B, B + n / 2, n / 2);
Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2);
Karatsuba(C, A, B, n / 2, K + n * 2);
Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2);
c = Add(K, C, C + n, n);
c += Add(K + n, K, K + n, n);
c += Add(C + n / 2, C + n / 2, K + n, n);
break;
case -1 * 3 + +1:
Sub(K, A + n / 2, A, n / 2);
Sub(K + n / 2, B + n / 2, B, n / 2);
Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2);
Karatsuba(C, A, B, n / 2, K + n * 2);
Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2);
c = Add(K, C, C + n, n);
c -= Sub(K + n, K, K + n, n);
c += Add(C + n / 2, C + n / 2, K + n, n);
break;
case +1 * 3 + -1:
Sub(K, A, A + n / 2, n / 2);
Sub(K + n / 2, B, B + n / 2, n / 2);
Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2);
Karatsuba(C, A, B, n / 2, K + n * 2);
Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2);
c = Add(K, C, C + n, n);
c -= Sub(K + n, K, K + n, n);
c += Add(C + n / 2, C + n / 2, K + n, n);
break;
case +1 * 3 + +1:
Sub(K, A, A + n / 2, n / 2);
Sub(K + n / 2, B + n / 2, B, n / 2);
Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2);
Karatsuba(C, A, B, n / 2, K + n * 2);
Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2);
c = Add(K, C, C + n, n);
c += Add(K + n, K, K + n, n);
c += Add(C + n / 2, C + n / 2, K + n, n);
break;
default:
unreachable;
}
for (i = n / 2 + n; c && i < n + n; i++) {
t = C[i];
c = (C[i] = t + c) < t;
}
}

32
third_party/mbedtls/math.h vendored Normal file
View file

@ -0,0 +1,32 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MATH_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MATH_H_
#define ADC(R, A, B, CI, CO) \
do { \
uint64_t Ta = A; \
uint64_t Tb = B; \
CO = (Ta += CI) < CI; \
CO += (Ta += Tb) < Tb; \
R = Ta; \
} while (0)
#define SBB(R, A, B, CI, CO) \
do { \
uint64_t Ta = A; \
uint64_t Tb = B; \
uint64_t Tc = Ta < CI; \
Ta -= CI; \
CO = (Ta < Tb) + Tc; \
Ta -= Tb; \
R = Ta; \
} while (0)
#define MADD(a, b, c0, c1, c2) \
t = (uint128_t)a * b; \
t += c0; \
c0 = t; \
h = t >> 64; \
c1 += h; \
if (c1 < h) c2++
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MATH_H_ */

View file

@ -16,13 +16,16 @@ THIRD_PARTY_MBEDTLS_A_CHECKS = \
$(THIRD_PARTY_MBEDTLS_A_HDRS:%=o/$(MODE)/%.ok)
THIRD_PARTY_MBEDTLS_A_DIRECTDEPS = \
LIBC_BITS \
LIBC_CALLS \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_RAND \
LIBC_RUNTIME \
LIBC_SOCK \
LIBC_LOG \
LIBC_STDIO \
LIBC_STR \
@ -50,16 +53,23 @@ $(THIRD_PARTY_MBEDTLS_A_OBJS): \
-fdata-sections \
-ffunction-sections
o/$(MODE)/third_party/mbedtls/bignum.o \
o/$(MODE)/third_party/mbedtls/ecp.o \
o/$(MODE)/third_party/mbedtls/ecp_curves.o: \
OVERRIDE_CFLAGS += \
-O3
o/$(MODE)/third_party/mbedtls/everest.o: \
OVERRIDE_CFLAGS += \
-Os
o/$(MODE)/third_party/mbedtls/bigmul4.o \
o/$(MODE)/third_party/mbedtls/bigmul6.o: \
OVERRIDE_CFLAGS += \
-O2
o/$(MODE)/third_party/mbedtls/shiftright-avx.o: \
OVERRIDE_CFLAGS += \
-O3 -mavx
o/$(MODE)/third_party/mbedtls/shiftright2-avx.o: \
OVERRIDE_CFLAGS += \
-O3 -mavx
# tail recursion is so important because everest was written in f*
o/$(MODE)/third_party/mbedtls/everest.o: \
OVERRIDE_CFLAGS += \

View file

@ -1,10 +1,26 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/mem/mem.h"
#include "libc/stdio/stdio.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/md.h"
#include "third_party/mbedtls/md5.h"
#include "third_party/mbedtls/md_internal.h"
#include "third_party/mbedtls/platform.h"
#include "third_party/mbedtls/sha1.h"
#include "third_party/mbedtls/sha256.h"
@ -42,109 +58,39 @@ asm(".include \"libc/disclaimer.inc\"");
#if defined(MBEDTLS_MD_C)
#if defined(MBEDTLS_MD2_C)
const mbedtls_md_info_t mbedtls_md2_info = {
"MD2",
MBEDTLS_MD_MD2,
16,
16,
};
#endif
#if defined(MBEDTLS_MD4_C)
const mbedtls_md_info_t mbedtls_md4_info = {
"MD4",
MBEDTLS_MD_MD4,
16,
64,
};
#endif
#if defined(MBEDTLS_MD5_C)
const mbedtls_md_info_t mbedtls_md5_info = {
"MD5",
MBEDTLS_MD_MD5,
16,
64,
};
#endif
#if defined(MBEDTLS_SHA1_C)
const mbedtls_md_info_t mbedtls_sha1_info = {
"SHA1",
MBEDTLS_MD_SHA1,
20,
64,
};
#endif
#if defined(MBEDTLS_SHA256_C)
const mbedtls_md_info_t mbedtls_sha224_info = {
"SHA224",
MBEDTLS_MD_SHA224,
28,
64,
};
const mbedtls_md_info_t mbedtls_sha256_info = {
"SHA256",
MBEDTLS_MD_SHA256,
32,
64,
};
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
const mbedtls_md_info_t mbedtls_sha384_info = {
"SHA384",
MBEDTLS_MD_SHA384,
48,
128,
};
#endif
const mbedtls_md_info_t mbedtls_sha512_info = {
"SHA512",
MBEDTLS_MD_SHA512,
64,
128,
};
#endif
#define CHECK(f) \
do \
{ \
if( ( ret = (f) ) ) \
goto cleanup; \
} while( 0 )
/*
* Reminder: update profiles in x509_crt.c when adding a new hash!
*/
static const uint8_t supported_digests[] = {
#if defined(MBEDTLS_SHA512_C)
MBEDTLS_MD_SHA512,
#if !defined(MBEDTLS_SHA512_NO_SHA384)
MBEDTLS_MD_SHA384,
#endif
#endif
#if defined(MBEDTLS_SHA256_C)
MBEDTLS_MD_SHA256,
MBEDTLS_MD_SHA224,
#endif
#if defined(MBEDTLS_SHA1_C)
MBEDTLS_MD_SHA1,
#endif
#if defined(MBEDTLS_MD5_C)
MBEDTLS_MD_MD5,
#endif
#if defined(MBEDTLS_MD4_C)
MBEDTLS_MD_MD4,
#endif
#if defined(MBEDTLS_MD2_C)
MBEDTLS_MD_MD2,
#endif
MBEDTLS_MD_NONE
};
@ -157,7 +103,6 @@ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name )
{
if( NULL == md_name )
return( NULL );
/* Get the appropriate digest information */
#if defined(MBEDTLS_MD2_C)
if( !strcmp( "MD2", md_name ) )
@ -231,492 +176,199 @@ const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type )
}
}
static int16_t GetMdContextSize(mbedtls_md_type_t t)
{
switch( t )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
return sizeof(mbedtls_md2_context);
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
return sizeof(mbedtls_md4_context);
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return sizeof(mbedtls_md5_context);
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return sizeof(mbedtls_sha1_context);
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
case MBEDTLS_MD_SHA256:
return sizeof(mbedtls_sha256_context);
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
#endif
case MBEDTLS_MD_SHA512:
return sizeof(mbedtls_sha512_context);
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
}
void mbedtls_md_init( mbedtls_md_context_t *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md_context_t ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md_context_t ) );
}
void mbedtls_md_free( mbedtls_md_context_t *ctx )
{
if( ctx == NULL || ctx->md_info == NULL )
int16_t csize;
if( !ctx || !ctx->md_info )
return;
if( ctx->md_ctx != NULL )
if( ctx->md_ctx )
{
switch( ctx->md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
mbedtls_md2_free( ctx->md_ctx );
break;
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
mbedtls_md4_free( ctx->md_ctx );
break;
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
mbedtls_md5_free( ctx->md_ctx );
break;
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
mbedtls_sha1_free( ctx->md_ctx );
break;
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
case MBEDTLS_MD_SHA256:
mbedtls_sha256_free( ctx->md_ctx );
break;
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
#endif
case MBEDTLS_MD_SHA512:
mbedtls_sha512_free( ctx->md_ctx );
break;
#endif
default:
/* Shouldn't happen */
break;
}
if ( ( csize = GetMdContextSize( ctx->md_info->type ) ) > 0 )
mbedtls_platform_zeroize( ctx->md_ctx, csize );
mbedtls_free( ctx->md_ctx );
}
if( ctx->hmac_ctx != NULL )
if( ctx->hmac_ctx )
{
mbedtls_platform_zeroize( ctx->hmac_ctx,
2 * ctx->md_info->block_size );
mbedtls_free( ctx->hmac_ctx );
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md_context_t ) );
}
int mbedtls_md_clone( mbedtls_md_context_t *dst,
const mbedtls_md_context_t *src )
{
if( dst == NULL || dst->md_info == NULL ||
src == NULL || src->md_info == NULL ||
dst->md_info != src->md_info )
int16_t csize;
if( !dst || !dst->md_info ||
!src || !src->md_info ||
dst->md_info != src->md_info ||
( csize = GetMdContextSize( src->md_info->type ) ) < 0)
{
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
switch( src->md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
mbedtls_md2_clone( dst->md_ctx, src->md_ctx );
break;
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
mbedtls_md4_clone( dst->md_ctx, src->md_ctx );
break;
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
mbedtls_md5_clone( dst->md_ctx, src->md_ctx );
break;
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
mbedtls_sha1_clone( dst->md_ctx, src->md_ctx );
break;
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
case MBEDTLS_MD_SHA256:
mbedtls_sha256_clone( dst->md_ctx, src->md_ctx );
break;
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
#endif
case MBEDTLS_MD_SHA512:
mbedtls_sha512_clone( dst->md_ctx, src->md_ctx );
break;
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
memcpy( dst->md_ctx, src->md_ctx, csize );
return( 0 );
}
#define ALLOC( type ) \
do { \
ctx->md_ctx = mbedtls_calloc( 1, sizeof( mbedtls_##type##_context ) ); \
if( ctx->md_ctx == NULL ) \
if( !ctx->md_ctx ) \
return( MBEDTLS_ERR_MD_ALLOC_FAILED ); \
mbedtls_##type##_init( ctx->md_ctx ); \
} \
while( 0 )
int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac )
{
if( md_info == NULL || ctx == NULL )
int16_t csize;
if( !md_info || !ctx )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
ctx->md_info = md_info;
ctx->md_ctx = NULL;
ctx->hmac_ctx = NULL;
switch( md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
ALLOC( md2 );
break;
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
ALLOC( md4 );
break;
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
ALLOC( md5 );
break;
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
ALLOC( sha1 );
break;
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
case MBEDTLS_MD_SHA256:
ALLOC( sha256 );
break;
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
#endif
case MBEDTLS_MD_SHA512:
ALLOC( sha512 );
break;
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
if( hmac != 0 )
if ((csize = GetMdContextSize(md_info->type)) < 0)
return( csize );
if( !( ctx->md_ctx = mbedtls_calloc( 1, csize ) ) )
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
if( hmac )
{
ctx->hmac_ctx = mbedtls_calloc( 2, md_info->block_size );
if( ctx->hmac_ctx == NULL )
if( !ctx->hmac_ctx )
{
mbedtls_md_free( ctx );
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
}
}
return( 0 );
}
#undef ALLOC
int mbedtls_md_starts( mbedtls_md_context_t *ctx )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
switch( ctx->md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
return( mbedtls_md2_starts_ret( ctx->md_ctx ) );
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
return( mbedtls_md4_starts_ret( ctx->md_ctx ) );
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5_starts_ret( ctx->md_ctx ) );
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1_starts_ret( ctx->md_ctx ) );
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
return( mbedtls_sha256_starts_ret( ctx->md_ctx, 1 ) );
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256_starts_ret( ctx->md_ctx, 0 ) );
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
return( mbedtls_sha512_starts_ret( ctx->md_ctx, 1 ) );
#endif
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512_starts_ret( ctx->md_ctx, 0 ) );
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
}
int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
switch( ctx->md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
return( mbedtls_md2_update_ret( ctx->md_ctx, input, ilen ) );
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
return( mbedtls_md4_update_ret( ctx->md_ctx, input, ilen ) );
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5_update_ret( ctx->md_ctx, input, ilen ) );
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1_update_ret( ctx->md_ctx, input, ilen ) );
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256_update_ret( ctx->md_ctx, input, ilen ) );
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
#endif
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512_update_ret( ctx->md_ctx, input, ilen ) );
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
}
int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
switch( ctx->md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
return( mbedtls_md2_finish_ret( ctx->md_ctx, output ) );
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
return( mbedtls_md4_finish_ret( ctx->md_ctx, output ) );
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5_finish_ret( ctx->md_ctx, output ) );
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1_finish_ret( ctx->md_ctx, output ) );
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256_finish_ret( ctx->md_ctx, output ) );
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
#endif
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512_finish_ret( ctx->md_ctx, output ) );
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
}
int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
unsigned char *output )
{
if( md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
switch( md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
return( mbedtls_md2_ret( input, ilen, output ) );
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
return( mbedtls_md4_ret( input, ilen, output ) );
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5_ret( input, ilen, output ) );
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1_ret( input, ilen, output ) );
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
return( mbedtls_sha256_ret( input, ilen, output, 1 ) );
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256_ret( input, ilen, output, 0 ) );
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
return( mbedtls_sha512_ret( input, ilen, output, 1 ) );
#endif
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512_ret( input, ilen, output, 0 ) );
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
}
#if defined(MBEDTLS_FS_IO)
int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
FILE *f;
size_t n;
mbedtls_md_context_t ctx;
unsigned char buf[1024];
if( md_info == NULL )
if( !md_info )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if( ( f = fopen( path, "rb" ) ) == NULL )
if( !( f = fopen( path, "rb" ) ) )
return( MBEDTLS_ERR_MD_FILE_IO_ERROR );
mbedtls_md_init( &ctx );
if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
goto cleanup;
if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
goto cleanup;
CHECK( mbedtls_md_setup( &ctx, md_info, 0 ) );
CHECK( mbedtls_md_starts( &ctx ) );
while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
if( ( ret = mbedtls_md_update( &ctx, buf, n ) ) != 0 )
goto cleanup;
if( ferror( f ) != 0 )
CHECK( mbedtls_md_update( &ctx, buf, n ) );
if( ferror( f ) )
ret = MBEDTLS_ERR_MD_FILE_IO_ERROR;
else
ret = mbedtls_md_finish( &ctx, output );
cleanup:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
fclose( f );
mbedtls_md_free( &ctx );
fclose( f );
return( ret );
}
#endif /* MBEDTLS_FS_IO */
int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char sum[MBEDTLS_MD_MAX_SIZE];
unsigned char *ipad, *opad;
size_t i;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
if( !ctx || !ctx->md_info || !ctx->hmac_ctx )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if( keylen > (size_t) ctx->md_info->block_size )
{
if( ( ret = mbedtls_md_starts( ctx ) ) != 0 )
goto cleanup;
if( ( ret = mbedtls_md_update( ctx, key, keylen ) ) != 0 )
goto cleanup;
if( ( ret = mbedtls_md_finish( ctx, sum ) ) != 0 )
goto cleanup;
CHECK( mbedtls_md_starts( ctx ) );
CHECK( mbedtls_md_update( ctx, key, keylen ) );
CHECK( mbedtls_md_finish( ctx, sum ) );
keylen = ctx->md_info->size;
key = sum;
}
ipad = (unsigned char *) ctx->hmac_ctx;
opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;
memset( ipad, 0x36, ctx->md_info->block_size );
memset( opad, 0x5C, ctx->md_info->block_size );
for( i = 0; i < keylen; i++ )
{
ipad[i] = (unsigned char)( ipad[i] ^ key[i] );
opad[i] = (unsigned char)( opad[i] ^ key[i] );
}
if( ( ret = mbedtls_md_starts( ctx ) ) != 0 )
goto cleanup;
if( ( ret = mbedtls_md_update( ctx, ipad,
ctx->md_info->block_size ) ) != 0 )
goto cleanup;
CHECK( mbedtls_md_starts( ctx ) );
CHECK( mbedtls_md_update( ctx, ipad, ctx->md_info->block_size ) );
cleanup:
mbedtls_platform_zeroize( sum, sizeof( sum ) );
return( ret );
}
int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )
{
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_update( ctx, input, ilen ) );
}
int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char tmp[MBEDTLS_MD_MAX_SIZE];
unsigned char *opad;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
if( !ctx || !ctx->md_info || !ctx->hmac_ctx )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;
if( ( ret = mbedtls_md_finish( ctx, tmp ) ) != 0 )
return( ret );
if( ( ret = mbedtls_md_starts( ctx ) ) != 0 )
return( ret );
if( ( ret = mbedtls_md_update( ctx, opad,
ctx->md_info->block_size ) ) != 0 )
return( ret );
if( ( ret = mbedtls_md_update( ctx, tmp,
ctx->md_info->size ) ) != 0 )
return( ret );
CHECK( mbedtls_md_finish( ctx, tmp ) );
CHECK( mbedtls_md_starts( ctx ) );
CHECK( mbedtls_md_update( ctx, opad, ctx->md_info->block_size ) );
CHECK( mbedtls_md_update( ctx, tmp, ctx->md_info->size ) );
return( mbedtls_md_finish( ctx, output ) );
cleanup:
return( ret );
}
int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *ipad;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
if( !ctx || !ctx->md_info || !ctx->hmac_ctx )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
ipad = (unsigned char *) ctx->hmac_ctx;
if( ( ret = mbedtls_md_starts( ctx ) ) != 0 )
if( ( ret = mbedtls_md_starts( ctx ) ) )
return( ret );
return( mbedtls_md_update( ctx, ipad, ctx->md_info->block_size ) );
}
@ -727,91 +379,35 @@ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info,
unsigned char *output )
{
mbedtls_md_context_t ctx;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( md_info == NULL )
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( !md_info )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
mbedtls_md_init( &ctx );
if( ( ret = mbedtls_md_setup( &ctx, md_info, 1 ) ) != 0 )
goto cleanup;
if( ( ret = mbedtls_md_hmac_starts( &ctx, key, keylen ) ) != 0 )
goto cleanup;
if( ( ret = mbedtls_md_hmac_update( &ctx, input, ilen ) ) != 0 )
goto cleanup;
if( ( ret = mbedtls_md_hmac_finish( &ctx, output ) ) != 0 )
goto cleanup;
CHECK( mbedtls_md_setup( &ctx, md_info, 1 ) );
CHECK( mbedtls_md_hmac_starts( &ctx, key, keylen ) );
CHECK( mbedtls_md_hmac_update( &ctx, input, ilen ) );
CHECK( mbedtls_md_hmac_finish( &ctx, output ) );
cleanup:
mbedtls_md_free( &ctx );
return( ret );
}
int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
switch( ctx->md_info->type )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
return( mbedtls_internal_md2_process( ctx->md_ctx ) );
const mbedtls_md_info_t mbedtls_md2_info = {
"MD2",
MBEDTLS_MD_MD2,
16,
16,
};
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
return( mbedtls_internal_md4_process( ctx->md_ctx, data ) );
const mbedtls_md_info_t mbedtls_md4_info = {
"MD4",
MBEDTLS_MD_MD4,
16,
64,
};
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_internal_md5_process( ctx->md_ctx, data ) );
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_internal_sha1_process( ctx->md_ctx, data ) );
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
case MBEDTLS_MD_SHA256:
return( mbedtls_internal_sha256_process( ctx->md_ctx, data ) );
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
case MBEDTLS_MD_SHA384:
#endif
case MBEDTLS_MD_SHA512:
return( mbedtls_internal_sha512_process( ctx->md_ctx, data ) );
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
}
unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info )
{
if( md_info == NULL )
return( 0 );
return md_info->size;
}
mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info )
{
if( md_info == NULL )
return( MBEDTLS_MD_NONE );
return md_info->type;
}
const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info )
{
if( md_info == NULL )
return( NULL );
return md_info->name;
}
#endif /* MBEDTLS_MD_C */

View file

@ -22,15 +22,15 @@ COSMOPOLITAN_C_START_
*/
typedef enum {
MBEDTLS_MD_NONE=0, /**< None. */
MBEDTLS_MD_MD2, /**< The MD2 message digest. */
MBEDTLS_MD_MD4, /**< The MD4 message digest. */
MBEDTLS_MD_MD5, /**< The MD5 message digest. */
MBEDTLS_MD_SHA1, /**< The SHA-1 message digest. */
MBEDTLS_MD_SHA224, /**< The SHA-224 message digest. */
MBEDTLS_MD_SHA256, /**< The SHA-256 message digest. */
MBEDTLS_MD_SHA384, /**< The SHA-384 message digest. */
MBEDTLS_MD_SHA512, /**< The SHA-512 message digest. */
MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */
MBEDTLS_MD_MD2, /**< The MD2 message digest. */
MBEDTLS_MD_MD4, /**< The MD4 message digest. */
MBEDTLS_MD_MD5, /**< The MD5 message digest. */
} mbedtls_md_type_t;
#if defined(MBEDTLS_SHA512_C)
@ -46,23 +46,28 @@ typedef enum {
#endif
/**
* Opaque struct defined in md_internal.h.
* Message digest information.
* Allows message digest functions to be called in a generic way.
*/
typedef struct mbedtls_md_info_t mbedtls_md_info_t;
typedef struct mbedtls_md_info_t {
const char * name; /** Name of the message digest */
mbedtls_md_type_t type; /** Digest identifier */
unsigned char size; /** Output length of the digest function in bytes */
unsigned char block_size; /** Block length of the digest function in bytes */
int (*f_starts)(void *);
int (*f_update)(void *, const void *, size_t);
int (*f_process)(void *, const void *);
int (*f_finish)(void *, void *);
int (*f_md)(const void *, size_t, void *);
} mbedtls_md_info_t;
/**
* The generic message-digest context.
*/
typedef struct mbedtls_md_context_t
{
/** Information about the associated message digest. */
const mbedtls_md_info_t *md_info;
/** The digest-specific context. */
void *md_ctx;
/** The HMAC part of the context. */
void *hmac_ctx;
typedef struct mbedtls_md_context_t {
const mbedtls_md_info_t *md_info; /** Information about the associated message digest. */
void *md_ctx; /** The digest-specific context. */
void *hmac_ctx; /** The HMAC part of the context. */
} mbedtls_md_context_t;
/**
@ -177,7 +182,12 @@ int mbedtls_md_clone( mbedtls_md_context_t *dst,
*
* \return The size of the message-digest output in Bytes.
*/
unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info );
forceinline unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info )
{
if( !md_info )
return( 0 );
return md_info->size;
}
/**
* \brief This function extracts the message-digest type from the
@ -188,7 +198,12 @@ unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info );
*
* \return The type of the message digest.
*/
mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info );
forceinline mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info )
{
if( !md_info )
return( MBEDTLS_MD_NONE );
return md_info->type;
}
/**
* \brief This function extracts the message-digest name from the
@ -199,7 +214,12 @@ mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info );
*
* \return The name of the message digest.
*/
const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info );
forceinline const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info )
{
if( !md_info )
return( NULL );
return md_info->name;
}
/**
* \brief This function starts a message-digest computation.
@ -214,7 +234,12 @@ const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info );
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_starts( mbedtls_md_context_t *ctx );
forceinline int mbedtls_md_starts( mbedtls_md_context_t *ctx )
{
if( !ctx || !ctx->md_info )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return ctx->md_info->f_starts( ctx->md_ctx );
}
/**
* \brief This function feeds an input buffer into an ongoing
@ -232,7 +257,13 @@ int mbedtls_md_starts( mbedtls_md_context_t *ctx );
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen );
forceinline int mbedtls_md_update( mbedtls_md_context_t *ctx,
const unsigned char *input, size_t ilen )
{
if( !ctx || !ctx->md_info )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return ctx->md_info->f_update( ctx->md_ctx, input, ilen );
}
/**
* \brief This function finishes the digest operation,
@ -252,7 +283,13 @@ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, si
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
forceinline int mbedtls_md_finish( mbedtls_md_context_t *ctx,
unsigned char *output )
{
if( !ctx || !ctx->md_info )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return ctx->md_info->f_finish( ctx->md_ctx, output );
}
/**
* \brief This function calculates the message-digest of a buffer,
@ -272,10 +309,15 @@ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
unsigned char *output );
forceinline int mbedtls_md( const mbedtls_md_info_t *md_info,
const unsigned char *input, size_t ilen,
unsigned char *output )
{
if( !md_info )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return md_info->f_md(input, ilen, output );
}
#if defined(MBEDTLS_FS_IO)
/**
* \brief This function calculates the message-digest checksum
* result of the contents of the provided file.
@ -295,7 +337,6 @@ int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, si
*/
int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path,
unsigned char *output );
#endif /* MBEDTLS_FS_IO */
/**
* \brief This function sets the HMAC key and prepares to
@ -337,8 +378,14 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input,
size_t ilen );
forceinline int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx,
const unsigned char *input,
size_t ilen )
{
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_update( ctx, input, ilen ) );
}
/**
* \brief This function finishes the HMAC operation, and writes
@ -403,10 +450,23 @@ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key,
const unsigned char *input, size_t ilen,
unsigned char *output );
/* Internal use */
int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data );
forceinline int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )
{
if( !ctx || !ctx->md_info )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return ctx->md_info->f_process( ctx->md_ctx, data );
}
const char *mbedtls_md_type_name(mbedtls_md_type_t);
extern const mbedtls_md_info_t mbedtls_md2_info;
extern const mbedtls_md_info_t mbedtls_md4_info;
extern const mbedtls_md_info_t mbedtls_md5_info;
extern const mbedtls_md_info_t mbedtls_sha1_info;
extern const mbedtls_md_info_t mbedtls_sha224_info;
extern const mbedtls_md_info_t mbedtls_sha256_info;
extern const mbedtls_md_info_t mbedtls_sha384_info;
extern const mbedtls_md_info_t mbedtls_sha512_info;
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MD_H_ */

View file

@ -1,6 +1,24 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/md.h"
#include "third_party/mbedtls/md5.h"
#include "third_party/mbedtls/platform.h"
@ -40,35 +58,6 @@ asm(".include \"libc/disclaimer.inc\"");
#define GET_UINT32_LE(n,b,i) (n) = READ32LE((b) + (i))
#define PUT_UINT32_LE(n,b,i) WRITE32LE((b) + (i), n)
/**
* \brief Initialize MD5 context
*
* \param ctx MD5 context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*/
void mbedtls_md5_init( mbedtls_md5_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md5_context ) );
}
/**
* \brief Clear MD5 context
*
* \param ctx MD5 context to be cleared
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*/
void mbedtls_md5_free( mbedtls_md5_context *ctx )
{
if( !ctx ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) );
}
/**
* \brief Clone (the state of) an MD5 context
*
@ -250,7 +239,7 @@ int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t fill;
uint32_t left;
@ -309,7 +298,7 @@ int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
unsigned char output[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
uint32_t used;
uint32_t high, low;
@ -323,17 +312,17 @@ int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
if( used <= 56 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 56 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 64 - used );
if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 56 );
mbedtls_platform_zeroize( ctx->buffer, 56 );
}
/*
@ -379,7 +368,7 @@ int mbedtls_md5_ret( const void *input,
size_t ilen,
unsigned char output[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_md5_context ctx;
mbedtls_md5_init( &ctx );
@ -399,6 +388,18 @@ exit:
return( ret );
}
const mbedtls_md_info_t mbedtls_md5_info = {
"MD5",
MBEDTLS_MD_MD5,
16,
64,
(void *)mbedtls_md5_starts_ret,
(void *)mbedtls_md5_update_ret,
(void *)mbedtls_internal_md5_process,
(void *)mbedtls_md5_finish_ret,
(void *)mbedtls_md5_ret,
};
#if defined(MBEDTLS_SELF_TEST)
/*
* RFC 1321 test vectors

View file

@ -1,6 +1,7 @@
#ifndef MBEDTLS_MD5_H_
#define MBEDTLS_MD5_H_
#include "third_party/mbedtls/config.h"
#include "third_party/mbedtls/platform.h"
COSMOPOLITAN_C_START_
/* clang-format off */
@ -22,8 +23,6 @@ typedef struct mbedtls_md5_context
}
mbedtls_md5_context;
void mbedtls_md5_init( mbedtls_md5_context * );
void mbedtls_md5_free( mbedtls_md5_context * );
void mbedtls_md5_clone( mbedtls_md5_context *, const mbedtls_md5_context * );
int mbedtls_md5_starts_ret( mbedtls_md5_context * );
int mbedtls_md5_update_ret( mbedtls_md5_context *, const unsigned char *, size_t );
@ -32,5 +31,34 @@ int mbedtls_internal_md5_process( mbedtls_md5_context *, const unsigned char[64]
int mbedtls_md5_ret( const void *, size_t, unsigned char[16] );
int mbedtls_md5_self_test( int );
/**
* \brief Initialize MD5 context
*
* \param ctx MD5 context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*/
static inline void mbedtls_md5_init( mbedtls_md5_context *ctx )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) );
}
/**
* \brief Clear MD5 context
*
* \param ctx MD5 context to be cleared
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*/
static inline void mbedtls_md5_free( mbedtls_md5_context *ctx )
{
if( !ctx ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) );
}
COSMOPOLITAN_C_END_
#endif /* MBEDTLS_MD5_H_ */

View file

@ -1,57 +0,0 @@
#ifndef MBEDTLS_MD_WRAP_H
#define MBEDTLS_MD_WRAP_H
#include "third_party/mbedtls/config.h"
#include "third_party/mbedtls/md.h"
/* clang-format off */
#ifdef __cplusplus
extern "C" {
#endif
/**
* Message digest information.
* Allows message digest functions to be called in a generic way.
*/
struct mbedtls_md_info_t
{
/** Name of the message digest */
const char * name;
/** Digest identifier */
mbedtls_md_type_t type;
/** Output length of the digest function in bytes */
unsigned char size;
/** Block length of the digest function in bytes */
unsigned char block_size;
};
#if defined(MBEDTLS_MD2_C)
extern const mbedtls_md_info_t mbedtls_md2_info;
#endif
#if defined(MBEDTLS_MD4_C)
extern const mbedtls_md_info_t mbedtls_md4_info;
#endif
#if defined(MBEDTLS_MD5_C)
extern const mbedtls_md_info_t mbedtls_md5_info;
#endif
#if defined(MBEDTLS_SHA1_C)
extern const mbedtls_md_info_t mbedtls_sha1_info;
#endif
#if defined(MBEDTLS_SHA256_C)
extern const mbedtls_md_info_t mbedtls_sha224_info;
extern const mbedtls_md_info_t mbedtls_sha256_info;
#endif
#if defined(MBEDTLS_SHA512_C)
#if !defined(MBEDTLS_SHA512_NO_SHA384)
extern const mbedtls_md_info_t mbedtls_sha384_info;
#endif
extern const mbedtls_md_info_t mbedtls_sha512_info;
#endif
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_MD_WRAP_H */

View file

@ -1,20 +1,19 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Copyright The Mbed TLS Contributors
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
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
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
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.
*/
#include "third_party/mbedtls/md.h"

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/memory_buffer_alloc.h"
#include "third_party/mbedtls/platform.h"
@ -299,7 +316,7 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
mbedtls_exit( 1 );
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
mbedtls_platform_zeroize( ret, original_len );
return( ret );
}
@ -357,7 +374,7 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
mbedtls_exit( 1 );
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
mbedtls_platform_zeroize( ret, original_len );
return( ret );
}
@ -422,7 +439,7 @@ static void buffer_alloc_free( void *ptr )
if( hdr->next != NULL )
hdr->next->prev = hdr;
memset( old, 0, sizeof(memory_header) );
mbedtls_platform_zeroize( old, sizeof(memory_header) );
}
// Regroup with block after
@ -461,7 +478,7 @@ static void buffer_alloc_free( void *ptr )
if( hdr->next != NULL )
hdr->next->prev = hdr;
memset( old, 0, sizeof(memory_header) );
mbedtls_platform_zeroize( old, sizeof(memory_header) );
}
// Prepend to free_list if we have not merged
@ -533,7 +550,7 @@ void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks )
void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len )
{
memset( &heap, 0, sizeof( buffer_alloc_ctx ) );
mbedtls_platform_zeroize( &heap, sizeof( buffer_alloc_ctx ) );
mbedtls_platform_set_calloc_free( buffer_alloc_calloc, buffer_alloc_free );
if( len < sizeof( memory_header ) + MBEDTLS_MEMORY_ALIGN_MULTIPLE )
@ -547,7 +564,7 @@ void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len )
- (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
}
memset( buf, 0, len );
mbedtls_platform_zeroize( buf, len );
heap.buf = buf;
heap.len = len;

516
third_party/mbedtls/net_sockets.c vendored Normal file
View file

@ -0,0 +1,516 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sockaddr6.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/sock/select.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/msg.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/consts/sol.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/net_sockets.h"
#include "third_party/mbedtls/ssl.h"
#define IS_EINTR(ret) ((ret) == EINTR)
static int net_prepare(void) {
signal(SIGPIPE, SIG_IGN);
return 0;
}
/**
* \brief Initialize a context
* Just makes the context ready to be used or freed safely.
*
* \param ctx Context to initialize
*/
void mbedtls_net_init(mbedtls_net_context *ctx) {
ctx->fd = -1;
}
/**
* \brief Initiate a connection with host:port in the given protocol
*
* \param ctx Socket to use
* \param host Host to connect to
* \param port Port to connect to
* \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
*
* \return 0 if successful, or one of:
* MBEDTLS_ERR_NET_SOCKET_FAILED,
* MBEDTLS_ERR_NET_UNKNOWN_HOST,
* MBEDTLS_ERR_NET_CONNECT_FAILED
*
* \note Sets the socket in connected mode even with UDP.
*/
int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host,
const char *port, int proto) {
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
struct addrinfo hints, *addr_list, *cur;
if ((ret = net_prepare()) != 0) return ret;
/* Do name resolution with both IPv6 and IPv4 */
mbedtls_platform_zeroize(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_protocol =
proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
if (getaddrinfo(host, port, &hints, &addr_list) != 0)
return MBEDTLS_ERR_NET_UNKNOWN_HOST;
/* Try the sockaddrs until a connection succeeds */
ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
for (cur = addr_list; cur != NULL; cur = cur->ai_next) {
ctx->fd = (int)socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
if (ctx->fd < 0) {
ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
continue;
}
if (connect(ctx->fd, cur->ai_addr, cur->ai_addrlen) == 0) {
ret = 0;
break;
}
close(ctx->fd);
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}
freeaddrinfo(addr_list);
return ret;
}
/**
* \brief Create a receiving socket on bind_ip:port in the chosen
* protocol. If bind_ip == NULL, all interfaces are bound.
*
* \param ctx Socket to use
* \param bind_ip IP to bind to, can be NULL
* \param port Port number to use
* \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
*
* \return 0 if successful, or one of:
* MBEDTLS_ERR_NET_SOCKET_FAILED,
* MBEDTLS_ERR_NET_UNKNOWN_HOST,
* MBEDTLS_ERR_NET_BIND_FAILED,
* MBEDTLS_ERR_NET_LISTEN_FAILED
*
* \note Regardless of the protocol, opens the sockets and binds it.
* In addition, make the socket listening if protocol is TCP.
*/
int mbedtls_net_bind(mbedtls_net_context *ctx, const char *bind_ip,
const char *port, int proto) {
int n, ret;
struct addrinfo hints, *addr_list, *cur;
if ((ret = net_prepare()) != 0) return ret;
/* Bind to IPv6 and/or IPv4, but only in the desired protocol */
mbedtls_platform_zeroize(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_protocol =
proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
if (bind_ip == NULL) hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(bind_ip, port, &hints, &addr_list) != 0)
return MBEDTLS_ERR_NET_UNKNOWN_HOST;
/* Try the sockaddrs until a binding succeeds */
ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
for (cur = addr_list; cur != NULL; cur = cur->ai_next) {
ctx->fd = (int)socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
if (ctx->fd < 0) {
ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
continue;
}
n = 1;
if (setsockopt(ctx->fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&n,
sizeof(n)) != 0) {
close(ctx->fd);
ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
continue;
}
if (bind(ctx->fd, cur->ai_addr, cur->ai_addrlen) != 0) {
close(ctx->fd);
ret = MBEDTLS_ERR_NET_BIND_FAILED;
continue;
}
/* Listen only makes sense for TCP */
if (proto == MBEDTLS_NET_PROTO_TCP) {
if (listen(ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG) != 0) {
close(ctx->fd);
ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
continue;
}
}
/* Bind was successful */
ret = 0;
break;
}
freeaddrinfo(addr_list);
return ret;
}
/*
* Check if the requested operation would be blocking on a non-blocking socket
* and thus 'failed' with a negative return value.
*
* Note: on a blocking socket this function always returns 0!
*/
static int net_would_block(const mbedtls_net_context *ctx) {
int err = errno;
/*
* Never return 'WOULD BLOCK' on a blocking socket
*/
if ((fcntl(ctx->fd, F_GETFL) & O_NONBLOCK) != O_NONBLOCK) {
errno = err;
return 0;
}
errno = err;
if (err == EAGAIN || err == EWOULDBLOCK) return 1;
return 0;
}
/**
* \brief Accept a connection from a remote client
*
* \param bind_ctx Relevant socket
* \param client_ctx Will contain the connected client socket
* \param client_ip Will contain the client IP address, can be NULL
* \param buf_size Size of the client_ip buffer
* \param ip_len Will receive the size of the client IP written,
* can be NULL if client_ip is null
*
* \return 0 if successful, or
* MBEDTLS_ERR_NET_SOCKET_FAILED,
* MBEDTLS_ERR_NET_BIND_FAILED,
* MBEDTLS_ERR_NET_ACCEPT_FAILED, or
* MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small,
* MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to
* non-blocking and accept() would block.
*/
int mbedtls_net_accept(mbedtls_net_context *bind_ctx,
mbedtls_net_context *client_ctx, void *client_ip,
size_t buf_size, size_t *ip_len) {
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
int type;
struct sockaddr_storage client_addr;
#if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \
defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t) || \
defined(socklen_t) || \
(defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L)
socklen_t n = (socklen_t)sizeof(client_addr);
socklen_t type_len = (socklen_t)sizeof(type);
#else
int n = (int)sizeof(client_addr);
int type_len = (int)sizeof(type);
#endif
/* Is this a TCP or UDP socket? */
if (getsockopt(bind_ctx->fd, SOL_SOCKET, SO_TYPE, (void *)&type, &type_len) !=
0 ||
(type != SOCK_STREAM && type != SOCK_DGRAM)) {
return MBEDTLS_ERR_NET_ACCEPT_FAILED;
}
if (type == SOCK_STREAM) {
/* TCP: actual accept() */
ret = client_ctx->fd =
(int)accept(bind_ctx->fd, (struct sockaddr *)&client_addr, &n);
} else {
/* UDP: wait for a message, but keep it in the queue */
char buf[1] = {0};
ret = (int)recvfrom(bind_ctx->fd, buf, sizeof(buf), MSG_PEEK,
(struct sockaddr *)&client_addr, &n);
#if defined(_WIN32)
if (ret == SOCKET_ERROR && WSAGetLastError() == WSAEMSGSIZE) {
/* We know buf is too small, thanks, just peeking here */
ret = 0;
}
#endif
}
if (ret < 0) {
if (net_would_block(bind_ctx) != 0) return MBEDTLS_ERR_SSL_WANT_READ;
return MBEDTLS_ERR_NET_ACCEPT_FAILED;
}
/* UDP: hijack the listening socket to communicate with the client,
* then bind a new socket to accept new connections */
if (type != SOCK_STREAM) {
struct sockaddr_storage local_addr;
int one = 1;
if (connect(bind_ctx->fd, (struct sockaddr *)&client_addr, n) != 0)
return MBEDTLS_ERR_NET_ACCEPT_FAILED;
client_ctx->fd = bind_ctx->fd;
bind_ctx->fd = -1; /* In case we exit early */
n = sizeof(struct sockaddr_storage);
if (getsockname(client_ctx->fd, (struct sockaddr *)&local_addr, &n) != 0 ||
(bind_ctx->fd =
(int)socket(local_addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)) < 0 ||
setsockopt(bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&one,
sizeof(one)) != 0) {
return MBEDTLS_ERR_NET_SOCKET_FAILED;
}
if (bind(bind_ctx->fd, (struct sockaddr *)&local_addr, n) != 0) {
return MBEDTLS_ERR_NET_BIND_FAILED;
}
}
if (client_ip != NULL) {
if (client_addr.ss_family == AF_INET) {
struct sockaddr_in *addr4 = (struct sockaddr_in *)&client_addr;
*ip_len = sizeof(addr4->sin_addr.s_addr);
if (buf_size < *ip_len) return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL;
memcpy(client_ip, &addr4->sin_addr.s_addr, *ip_len);
} else {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&client_addr;
*ip_len = sizeof(addr6->sin6_addr.s6_addr);
if (buf_size < *ip_len) return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL;
memcpy(client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
}
}
return 0;
}
/**
* \brief Set the socket blocking
*
* \param ctx Socket to set
*
* \return 0 if successful, or a non-zero error code
*/
int mbedtls_net_set_block(mbedtls_net_context *ctx) {
return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) & ~O_NONBLOCK);
}
/**
* \brief Set the socket non-blocking
*
* \param ctx Socket to set
*
* \return 0 if successful, or a non-zero error code
*/
int mbedtls_net_set_nonblock(mbedtls_net_context *ctx) {
return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) | O_NONBLOCK);
}
/**
* \brief Check and wait for the context to be ready for read/write
*
* \note The current implementation of this function uses
* select() and returns an error if the file descriptor
* is \c FD_SETSIZE or greater.
*
* \param ctx Socket to check
* \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and
* MBEDTLS_NET_POLL_WRITE specifying the events
* to wait for:
* - If MBEDTLS_NET_POLL_READ is set, the function
* will return as soon as the net context is available
* for reading.
* - If MBEDTLS_NET_POLL_WRITE is set, the function
* will return as soon as the net context is available
* for writing.
* \param timeout Maximal amount of time to wait before returning,
* in milliseconds. If \c timeout is zero, the
* function returns immediately. If \c timeout is
* -1u, the function blocks potentially indefinitely.
*
* \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE
* on success or timeout, or a negative return code otherwise.
*/
int mbedtls_net_poll(mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout) {
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
struct timeval tv;
fd_set read_fds;
fd_set write_fds;
int fd = ctx->fd;
if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT;
/* A limitation of select() is that it only works with file descriptors
* that are strictly less than FD_SETSIZE. This is a limitation of the
* fd_set type. Error out early, because attempting to call FD_SET on a
* large file descriptor is a buffer overflow on typical platforms. */
if (fd >= FD_SETSIZE) return MBEDTLS_ERR_NET_POLL_FAILED;
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
/* Ensure that memory sanitizers consider read_fds and write_fds as
* initialized even on platforms such as Glibc/x86_64 where FD_ZERO
* is implemented in assembly. */
mbedtls_platform_zeroize(&read_fds, sizeof(read_fds));
mbedtls_platform_zeroize(&write_fds, sizeof(write_fds));
#endif
#endif
FD_ZERO(&read_fds);
if (rw & MBEDTLS_NET_POLL_READ) {
rw &= ~MBEDTLS_NET_POLL_READ;
FD_SET(fd, &read_fds);
}
FD_ZERO(&write_fds);
if (rw & MBEDTLS_NET_POLL_WRITE) {
rw &= ~MBEDTLS_NET_POLL_WRITE;
FD_SET(fd, &write_fds);
}
if (rw != 0) return MBEDTLS_ERR_NET_BAD_INPUT_DATA;
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
do {
ret = select(fd + 1, &read_fds, &write_fds, NULL,
timeout == (uint32_t)-1 ? NULL : &tv);
} while (IS_EINTR(ret));
if (ret < 0) return MBEDTLS_ERR_NET_POLL_FAILED;
ret = 0;
if (FD_ISSET(fd, &read_fds)) ret |= MBEDTLS_NET_POLL_READ;
if (FD_ISSET(fd, &write_fds)) ret |= MBEDTLS_NET_POLL_WRITE;
return ret;
}
/**
* \brief Portable usleep helper
*
* \param usec Amount of microseconds to sleep
*
* \note Real amount of time slept will not be less than
* select()'s timeout granularity (typically, 10ms).
*/
void mbedtls_net_usleep(unsigned long usec) {
usleep(usec);
}
/**
* \brief Read at most 'len' characters. If no error occurs,
* the actual amount read is returned.
*
* \param ctx Socket
* \param buf The buffer to write to
* \param len Maximum length of the buffer
*
* \return the number of bytes received,
* or a non-zero error code; with a non-blocking socket,
* MBEDTLS_ERR_SSL_WANT_READ indicates read() would block.
*/
int mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len) {
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
int fd = ((mbedtls_net_context *)ctx)->fd;
if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT;
ret = (int)read(fd, buf, len);
if (ret < 0) {
if (net_would_block(ctx) != 0) return MBEDTLS_ERR_SSL_WANT_READ;
if (errno == EPIPE || errno == ECONNRESET)
return MBEDTLS_ERR_NET_CONN_RESET;
if (errno == EINTR) return MBEDTLS_ERR_SSL_WANT_READ;
return MBEDTLS_ERR_NET_RECV_FAILED;
}
return ret;
}
/**
* \brief Read at most 'len' characters, blocking for at most
* 'timeout' seconds. If no error occurs, the actual amount
* read is returned.
*
* \note The current implementation of this function uses
* select() and returns an error if the file descriptor
* is \c FD_SETSIZE or greater.
*
* \param ctx Socket
* \param buf The buffer to write to
* \param len Maximum length of the buffer
* \param timeout Maximum number of milliseconds to wait for data
* 0 means no timeout (wait forever)
*
* \return The number of bytes received if successful.
* MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out.
* MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
* Another negative error code (MBEDTLS_ERR_NET_xxx)
* for other failures.
*
* \note This function will block (until data becomes available or
* timeout is reached) even if the socket is set to
* non-blocking. Handling timeouts with non-blocking reads
* requires a different strategy.
*/
int mbedtls_net_recv_timeout(void *ctx, unsigned char *buf, size_t len,
uint32_t timeout) {
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
struct timeval tv;
fd_set read_fds;
int fd = ((mbedtls_net_context *)ctx)->fd;
if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT;
/* A limitation of select() is that it only works with file descriptors
* that are strictly less than FD_SETSIZE. This is a limitation of the
* fd_set type. Error out early, because attempting to call FD_SET on a
* large file descriptor is a buffer overflow on typical platforms. */
if (fd >= FD_SETSIZE) return (MBEDTLS_ERR_NET_POLL_FAILED);
FD_ZERO(&read_fds);
FD_SET(fd, &read_fds);
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
ret = select(fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv);
/* Zero fds ready means we timed out */
if (ret == 0) return MBEDTLS_ERR_SSL_TIMEOUT;
if (ret < 0) {
if (errno == EINTR) return MBEDTLS_ERR_SSL_WANT_READ;
return MBEDTLS_ERR_NET_RECV_FAILED;
}
/* This call will not block */
return mbedtls_net_recv(ctx, buf, len);
}
/**
* \brief Write at most 'len' characters. If no error occurs,
* the actual amount read is returned.
*
* \param ctx Socket
* \param buf The buffer to read from
* \param len The length of the buffer
*
* \return the number of bytes sent,
* or a non-zero error code; with a non-blocking socket,
* MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block.
*/
int mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len) {
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
int fd = ((mbedtls_net_context *)ctx)->fd;
if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT;
ret = (int)write(fd, buf, len);
if (ret < 0) {
if (net_would_block(ctx) != 0) return MBEDTLS_ERR_SSL_WANT_WRITE;
if (errno == EPIPE || errno == ECONNRESET)
return MBEDTLS_ERR_NET_CONN_RESET;
if (errno == EINTR) return MBEDTLS_ERR_SSL_WANT_WRITE;
return MBEDTLS_ERR_NET_SEND_FAILED;
}
return ret;
}
/**
* \brief Closes down the connection and free associated data
*
* \param ctx The context to close
*/
void mbedtls_net_close(mbedtls_net_context *ctx) {
if (ctx->fd == -1) return;
close(ctx->fd);
ctx->fd = -1;
}
/**
* \brief Gracefully shutdown the connection and free associated data
*
* \param ctx The context to free
*/
void mbedtls_net_free(mbedtls_net_context *ctx) {
if (ctx->fd == -1) return;
shutdown(ctx->fd, 2);
close(ctx->fd);
ctx->fd = -1;
}

58
third_party/mbedtls/net_sockets.h vendored Normal file
View file

@ -0,0 +1,58 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_NET_SOCKETS_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_NET_SOCKETS_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/* clang-format off */
#define MBEDTLS_ERR_NET_SOCKET_FAILED -0x0042 /**< Failed to open a socket. */
#define MBEDTLS_ERR_NET_CONNECT_FAILED -0x0044 /**< The connection to the given server / port failed. */
#define MBEDTLS_ERR_NET_BIND_FAILED -0x0046 /**< Binding of the socket failed. */
#define MBEDTLS_ERR_NET_LISTEN_FAILED -0x0048 /**< Could not listen on the socket. */
#define MBEDTLS_ERR_NET_ACCEPT_FAILED -0x004A /**< Could not accept the incoming connection. */
#define MBEDTLS_ERR_NET_RECV_FAILED -0x004C /**< Reading information from the socket failed. */
#define MBEDTLS_ERR_NET_SEND_FAILED -0x004E /**< Sending information through the socket failed. */
#define MBEDTLS_ERR_NET_CONN_RESET -0x0050 /**< Connection was reset by peer. */
#define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /**< Failed to get an IP address for the given hostname. */
#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /**< Buffer is too small to hold the data. */
#define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /**< The context is invalid, eg because it was free()ed. */
#define MBEDTLS_ERR_NET_POLL_FAILED -0x0047 /**< Polling the net context failed. */
#define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049 /**< Input invalid. */
#define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */
#define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */
#define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */
#define MBEDTLS_NET_POLL_READ 1 /**< Used in \c mbedtls_net_poll to check for pending data */
#define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */
/**
* Wrapper type for sockets.
*
* Currently backed by just a file descriptor, but might be more in the future
* (eg two file descriptors for combined IPv4 + IPv6 support, or additional
* structures for hand-made UDP demultiplexing).
*/
typedef struct mbedtls_net_context
{
int fd; /**< The underlying file descriptor */
}
mbedtls_net_context;
int mbedtls_net_accept( mbedtls_net_context *, mbedtls_net_context *, void *, size_t, size_t * );
int mbedtls_net_bind( mbedtls_net_context *, const char *, const char *, int );
int mbedtls_net_connect( mbedtls_net_context *, const char *, const char *, int );
int mbedtls_net_poll( mbedtls_net_context *, uint32_t, uint32_t );
int mbedtls_net_recv( void *, unsigned char *, size_t );
int mbedtls_net_recv_timeout( void *, unsigned char *, size_t, uint32_t );
int mbedtls_net_send( void *, const unsigned char *, size_t );
int mbedtls_net_set_block( mbedtls_net_context * );
int mbedtls_net_set_nonblock( mbedtls_net_context * );
void mbedtls_net_close( mbedtls_net_context * );
void mbedtls_net_free( mbedtls_net_context * );
void mbedtls_net_init( mbedtls_net_context * );
void mbedtls_net_usleep( unsigned long );
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_NET_SOCKETS_H_ */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/endian.h"
#include "third_party/mbedtls/error.h"
@ -75,7 +92,7 @@ static const unsigned char NIST_KW_ICV2[] = {0xA6, 0x59, 0x59, 0xA6};
*/
void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_nist_kw_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_nist_kw_context ) );
}
int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,
@ -84,7 +101,7 @@ int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,
unsigned int keybits,
const int is_wrap )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const mbedtls_cipher_info_t *cipher_info;
cipher_info = mbedtls_cipher_info_from_values( cipher,
@ -275,7 +292,7 @@ cleanup:
if( ret != 0)
{
memset( output, 0, semiblocks * KW_SEMIBLOCK_LENGTH );
mbedtls_platform_zeroize( output, semiblocks * KW_SEMIBLOCK_LENGTH );
}
mbedtls_platform_zeroize( inbuff, KW_SEMIBLOCK_LENGTH * 2 );
mbedtls_platform_zeroize( outbuff, KW_SEMIBLOCK_LENGTH * 2 );
@ -341,7 +358,7 @@ static int unwrap( mbedtls_nist_kw_context *ctx,
cleanup:
if( ret != 0)
memset( output, 0, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
mbedtls_platform_zeroize( output, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
mbedtls_platform_zeroize( inbuff, sizeof( inbuff ) );
mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) );
@ -477,7 +494,7 @@ int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx,
{
goto cleanup;
}
memset( output + Plen, 0, padlen );
mbedtls_platform_zeroize( output + Plen, padlen );
*out_len = Plen;
}
else
@ -489,7 +506,7 @@ int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx,
cleanup:
if( ret != 0 )
{
memset( output, 0, *out_len );
mbedtls_platform_zeroize( output, *out_len );
*out_len = 0;
}

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/fmt/fmt.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
@ -10,27 +27,10 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/**
* \file oid.c
*
* \brief Object Identifier (OID) database
*
* Copyright The Mbed TLS Contributors
* 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.
* @fileoverview Object Identifier (OID) database
*/
#if defined(MBEDTLS_OID_C)
@ -718,9 +718,9 @@ FN_OID_GET_ATTR2(mbedtls_oid_get_pkcs12_pbe_alg, oid_pkcs12_pbe_alg_t, pkcs12_pb
/* Return the x.y.z.... style numeric string for the given OID */
int mbedtls_oid_get_numeric_string( char *buf, size_t size,
const mbedtls_asn1_buf *oid )
const mbedtls_asn1_buf *oid )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i, n;
unsigned int value;
char *p;

View file

@ -1,6 +1,24 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/mem/mem.h"
#include "third_party/mbedtls/aes.h"
#include "third_party/mbedtls/base64.h"
#include "third_party/mbedtls/chk.h"
#include "third_party/mbedtls/cipher.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/des.h"
@ -16,30 +34,16 @@ Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/*
* Privacy Enhanced Mail (PEM) decoding
*
* Copyright The Mbed TLS Contributors
* 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.
/**
* @fileoverview Privacy Enhanced Mail (PEM) decoding
*/
#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
#if defined(MBEDTLS_PEM_PARSE_C)
void mbedtls_pem_init( mbedtls_pem_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_pem_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) );
}
#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \
@ -51,21 +55,16 @@ static int pem_get_iv( const unsigned char *s, unsigned char *iv,
size_t iv_len )
{
size_t i, j, k;
memset( iv, 0, iv_len );
mbedtls_platform_zeroize( iv, iv_len );
for( i = 0; i < iv_len * 2; i++, s++ )
{
if( *s >= '0' && *s <= '9' ) j = *s - '0'; else
if( *s >= 'A' && *s <= 'F' ) j = *s - '7'; else
if( *s >= 'a' && *s <= 'f' ) j = *s - 'W'; else
return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
k = ( ( i & 1 ) != 0 ) ? j : j << 4;
iv[i >> 1] = (unsigned char)( iv[i >> 1] | k );
}
return( 0 );
}
@ -76,54 +75,36 @@ static int pem_pbkdf1( unsigned char *key, size_t keylen,
mbedtls_md5_context md5_ctx;
unsigned char md5sum[16];
size_t use_len;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_md5_init( &md5_ctx );
/*
* key[ 0..15] = MD5(pwd || IV)
*/
if( ( ret = mbedtls_md5_starts_ret( &md5_ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )
goto exit;
MBEDTLS_CHK( mbedtls_md5_starts_ret( &md5_ctx ) );
MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) );
MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) );
MBEDTLS_CHK( mbedtls_md5_finish_ret( &md5_ctx, md5sum ) );
if( keylen <= 16 )
{
memcpy( key, md5sum, keylen );
goto exit;
goto cleanup;
}
memcpy( key, md5sum, 16 );
/*
* key[16..23] = MD5(key[ 0..15] || pwd || IV])
*/
if( ( ret = mbedtls_md5_starts_ret( &md5_ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, md5sum, 16 ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )
goto exit;
MBEDTLS_CHK( mbedtls_md5_starts_ret( &md5_ctx ) );
MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, md5sum, 16 ) );
MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) );
MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) );
MBEDTLS_CHK( mbedtls_md5_finish_ret( &md5_ctx, md5sum ) );
use_len = 16;
if( keylen < 32 )
use_len = keylen - 16;
memcpy( key + 16, md5sum, use_len );
exit:
cleanup:
mbedtls_md5_free( &md5_ctx );
mbedtls_platform_zeroize( md5sum, 16 );
return( ret );
}
@ -137,22 +118,17 @@ static int pem_des_decrypt( unsigned char des_iv[8],
{
mbedtls_des_context des_ctx;
unsigned char des_key[8];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_des_init( &des_ctx );
if( ( ret = pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_des_setkey_dec( &des_ctx, des_key ) ) != 0 )
goto exit;
ret = mbedtls_des_crypt_cbc( &des_ctx, MBEDTLS_DES_DECRYPT, buflen,
des_iv, buf, buf );
exit:
mbedtls_des_free( &des_ctx );
mbedtls_platform_zeroize( des_key, 8 );
return( ret );
}
@ -165,22 +141,17 @@ static int pem_des3_decrypt( unsigned char des3_iv[8],
{
mbedtls_des3_context des3_ctx;
unsigned char des3_key[24];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_des3_init( &des3_ctx );
if( ( ret = pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_des3_set3key_dec( &des3_ctx, des3_key ) ) != 0 )
goto exit;
ret = mbedtls_des3_crypt_cbc( &des3_ctx, MBEDTLS_DES_DECRYPT, buflen,
des3_iv, buf, buf );
exit:
mbedtls_des3_free( &des3_ctx );
mbedtls_platform_zeroize( des3_key, 24 );
return( ret );
}
#endif /* MBEDTLS_DES_C */
@ -195,22 +166,17 @@ static int pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen,
{
mbedtls_aes_context aes_ctx;
unsigned char aes_key[32];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_aes_init( &aes_ctx );
if( ( ret = pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_aes_setkey_dec( &aes_ctx, aes_key, keylen * 8 ) ) != 0 )
goto exit;
ret = mbedtls_aes_crypt_cbc( &aes_ctx, MBEDTLS_AES_DECRYPT, buflen,
aes_iv, buf, buf );
exit:
mbedtls_aes_free( &aes_ctx );
mbedtls_platform_zeroize( aes_key, keylen );
return( ret );
}
#endif /* MBEDTLS_AES_C */
@ -235,70 +201,54 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
((void) pwdlen);
#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
if( ctx == NULL )
if( !ctx )
return( MBEDTLS_ERR_PEM_BAD_INPUT_DATA );
s1 = (unsigned char *) strstr( (const char *) data, header );
if( s1 == NULL )
if( !s1 )
return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
s2 = (unsigned char *) strstr( (const char *) data, footer );
if( s2 == NULL || s2 <= s1 )
if( !s2 || s2 <= s1 )
return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
s1 += strlen( header );
if( *s1 == ' ' ) s1++;
if( *s1 == '\r' ) s1++;
if( *s1 == '\n' ) s1++;
else return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
end = s2;
end += strlen( footer );
if( *end == ' ' ) end++;
if( *end == '\r' ) end++;
if( *end == '\n' ) end++;
*use_len = end - data;
enc = 0;
if( s2 - s1 >= 22 && memcmp( s1, "Proc-Type: 4,ENCRYPTED", 22 ) == 0 )
{
#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \
( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
enc++;
s1 += 22;
if( *s1 == '\r' ) s1++;
if( *s1 == '\n' ) s1++;
else return( MBEDTLS_ERR_PEM_INVALID_DATA );
#if defined(MBEDTLS_DES_C)
if( s2 - s1 >= 23 && memcmp( s1, "DEK-Info: DES-EDE3-CBC,", 23 ) == 0 )
{
enc_alg = MBEDTLS_CIPHER_DES_EDE3_CBC;
s1 += 23;
if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8 ) != 0 )
return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
s1 += 16;
}
else if( s2 - s1 >= 18 && memcmp( s1, "DEK-Info: DES-CBC,", 18 ) == 0 )
{
enc_alg = MBEDTLS_CIPHER_DES_CBC;
s1 += 18;
if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8) != 0 )
return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
s1 += 16;
}
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_AES_C)
if( s2 - s1 >= 14 && memcmp( s1, "DEK-Info: AES-", 14 ) == 0 )
{
@ -312,18 +262,14 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
enc_alg = MBEDTLS_CIPHER_AES_256_CBC;
else
return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
s1 += 22;
if( s2 - s1 < 32 || pem_get_iv( s1, pem_iv, 16 ) != 0 )
return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
s1 += 32;
}
#endif /* MBEDTLS_AES_C */
if( enc_alg == MBEDTLS_CIPHER_NONE )
return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
if( *s1 == '\r' ) s1++;
if( *s1 == '\n' ) s1++;
else return( MBEDTLS_ERR_PEM_INVALID_DATA );
@ -332,25 +278,19 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
}
if( s1 >= s2 )
return( MBEDTLS_ERR_PEM_INVALID_DATA );
ret = mbedtls_base64_decode( NULL, 0, &len, s1, s2 - s1 );
if( ret == MBEDTLS_ERR_BASE64_INVALID_CHARACTER )
return( MBEDTLS_ERR_PEM_INVALID_DATA + ret );
if( ( buf = mbedtls_calloc( 1, len ) ) == NULL )
return( MBEDTLS_ERR_PEM_ALLOC_FAILED );
if( ( ret = mbedtls_base64_decode( buf, len, &len, s1, s2 - s1 ) ) != 0 )
{
mbedtls_platform_zeroize( buf, len );
mbedtls_free( buf );
return( MBEDTLS_ERR_PEM_INVALID_DATA + ret );
}
if( enc != 0 )
{
#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \
@ -361,16 +301,13 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
mbedtls_free( buf );
return( MBEDTLS_ERR_PEM_PASSWORD_REQUIRED );
}
ret = 0;
#if defined(MBEDTLS_DES_C)
if( enc_alg == MBEDTLS_CIPHER_DES_EDE3_CBC )
ret = pem_des3_decrypt( pem_iv, buf, len, pwd, pwdlen );
else if( enc_alg == MBEDTLS_CIPHER_DES_CBC )
ret = pem_des_decrypt( pem_iv, buf, len, pwd, pwdlen );
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_AES_C)
if( enc_alg == MBEDTLS_CIPHER_AES_128_CBC )
ret = pem_aes_decrypt( pem_iv, 16, buf, len, pwd, pwdlen );
@ -379,13 +316,11 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
else if( enc_alg == MBEDTLS_CIPHER_AES_256_CBC )
ret = pem_aes_decrypt( pem_iv, 32, buf, len, pwd, pwdlen );
#endif /* MBEDTLS_AES_C */
if( ret != 0 )
{
mbedtls_free( buf );
return( ret );
}
/*
* The result will be ASN.1 starting with a SEQUENCE tag, with 1 to 3
* length bytes (allow 4 to be sure) in all known use cases.
@ -405,22 +340,19 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
}
ctx->buf = buf;
ctx->buflen = len;
return( 0 );
}
void mbedtls_pem_free( mbedtls_pem_context *ctx )
{
if ( ctx->buf != NULL )
if ( ctx->buf )
{
mbedtls_platform_zeroize( ctx->buf, ctx->buflen );
mbedtls_free( ctx->buf );
}
mbedtls_free( ctx->info );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) );
}
#endif /* MBEDTLS_PEM_PARSE_C */
@ -430,34 +362,28 @@ int mbedtls_pem_write_buffer( const char *header, const char *footer,
const unsigned char *der_data, size_t der_len,
unsigned char *buf, size_t buf_len, size_t *olen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *encode_buf = NULL, *c, *p = buf;
size_t len = 0, use_len, add_len = 0;
mbedtls_base64_encode( NULL, 0, &use_len, der_data, der_len );
add_len = strlen( header ) + strlen( footer ) + ( use_len / 64 ) + 1;
if( use_len + add_len > buf_len )
{
*olen = use_len + add_len;
return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
}
if( use_len != 0 &&
( ( encode_buf = mbedtls_calloc( 1, use_len ) ) == NULL ) )
return( MBEDTLS_ERR_PEM_ALLOC_FAILED );
if( ( ret = mbedtls_base64_encode( encode_buf, use_len, &use_len, der_data,
der_len ) ) != 0 )
{
mbedtls_free( encode_buf );
return( ret );
}
memcpy( p, header, strlen( header ) );
p += strlen( header );
c = encode_buf;
while( use_len )
{
len = ( use_len > 64 ) ? 64 : use_len;
@ -467,19 +393,16 @@ int mbedtls_pem_write_buffer( const char *header, const char *footer,
c += len;
*p++ = '\n';
}
memcpy( p, footer, strlen( footer ) );
p += strlen( footer );
*p++ = '\0';
*olen = p - buf;
/* Clean any remaining data previously written to the buffer */
memset( buf + *olen, 0, buf_len - *olen );
mbedtls_platform_zeroize( buf + *olen, buf_len - *olen );
mbedtls_free( encode_buf );
return( 0 );
}
#endif /* MBEDTLS_PEM_WRITE_C */
#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/ecdsa.h"
#include "third_party/mbedtls/ecp.h"
@ -12,25 +29,10 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* Public Key abstraction layer
*
* Copyright The Mbed TLS Contributors
* 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.
/**
* @fileoverview Public Key abstraction layer
*/
#if defined(MBEDTLS_PK_C)
@ -48,8 +50,7 @@ asm(".include \"libc/disclaimer.inc\"");
*/
void mbedtls_pk_init( mbedtls_pk_context *ctx )
{
PK_VALIDATE( ctx != NULL );
PK_VALIDATE( ctx );
ctx->pk_info = NULL;
ctx->pk_ctx = NULL;
}
@ -69,7 +70,7 @@ void mbedtls_pk_free( mbedtls_pk_context *ctx )
{
if( ctx == NULL )
return;
if ( ctx->pk_info != NULL )
if ( ctx->pk_info )
ctx->pk_info->ctx_free_func( ctx->pk_ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pk_context ) );
}
@ -83,7 +84,7 @@ void mbedtls_pk_free( mbedtls_pk_context *ctx )
*/
void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx )
{
PK_VALIDATE( ctx != NULL );
PK_VALIDATE( ctx );
ctx->pk_info = NULL;
ctx->rs_ctx = NULL;
}
@ -154,8 +155,8 @@ const mbedtls_pk_info_t * mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type )
*/
int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info )
{
PK_VALIDATE_RET( ctx != NULL );
if( info == NULL || ctx->pk_info != NULL )
PK_VALIDATE_RET( ctx );
if( info == NULL || ctx->pk_info )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )
@ -189,8 +190,8 @@ int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,
mbedtls_rsa_alt_context *rsa_alt;
const mbedtls_pk_info_t *info = &mbedtls_rsa_alt_info;
PK_VALIDATE_RET( ctx != NULL );
if( ctx->pk_info != NULL )
PK_VALIDATE_RET( ctx );
if( ctx->pk_info )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )
@ -252,7 +253,7 @@ static int pk_restart_setup( mbedtls_pk_restart_ctx *ctx,
const mbedtls_pk_info_t *info )
{
/* Don't do anything if already set up or invalid */
if( ctx == NULL || ctx->pk_info != NULL )
if( ctx == NULL || ctx->pk_info )
return( 0 );
/* Should never happen when we're called */
@ -294,10 +295,10 @@ int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx,
const unsigned char *sig, size_t sig_len,
mbedtls_pk_restart_ctx *rs_ctx )
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( ctx );
PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) ||
hash != NULL );
PK_VALIDATE_RET( sig != NULL );
hash );
PK_VALIDATE_RET( sig );
if( ctx->pk_info == NULL ||
pk_hashlen_helper( md_alg, &hash_len ) != 0 )
@ -305,11 +306,11 @@ int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx,
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/* optimization: use non-restartable version if restart disabled */
if( rs_ctx != NULL &&
if( rs_ctx &&
mbedtls_ecp_restart_is_enabled() &&
ctx->pk_info->verify_rs_func != NULL )
ctx->pk_info->verify_rs_func )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 )
return( ret );
@ -399,10 +400,10 @@ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len )
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( ctx );
PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) ||
hash != NULL );
PK_VALIDATE_RET( sig != NULL );
hash );
PK_VALIDATE_RET( sig );
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if( ! mbedtls_pk_can_do( ctx, type ) )
@ -410,7 +411,7 @@ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
if( type == MBEDTLS_PK_RSASSA_PSS )
{
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21)
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const mbedtls_pk_rsassa_pss_options *pss_opts;
#if SIZE_MAX > UINT_MAX
if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
@ -437,7 +438,7 @@ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
#endif /* MBEDTLS_RSA_C && MBEDTLS_PKCS1_V21 */
}
/* General case: no options */
if( options != NULL )
if( options )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
return( mbedtls_pk_verify( ctx, md_alg, hash, hash_len, sig, sig_len ) );
}
@ -471,47 +472,39 @@ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
* operations was reached: see \c mbedtls_ecp_set_max_ops().
*/
int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_pk_restart_ctx *rs_ctx )
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, mbedtls_pk_restart_ctx *rs_ctx )
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( ctx );
PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) ||
hash != NULL );
PK_VALIDATE_RET( sig != NULL );
hash );
PK_VALIDATE_RET( sig );
if( ctx->pk_info == NULL ||
pk_hashlen_helper( md_alg, &hash_len ) != 0 )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/* optimization: use non-restartable version if restart disabled */
if( rs_ctx != NULL &&
if( rs_ctx &&
mbedtls_ecp_restart_is_enabled() &&
ctx->pk_info->sign_rs_func != NULL )
ctx->pk_info->sign_rs_func )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 )
return( ret );
ret = ctx->pk_info->sign_rs_func( ctx->pk_ctx, md_alg,
hash, hash_len, sig, sig_len, f_rng, p_rng, rs_ctx->rs_ctx );
if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
mbedtls_pk_restart_free( rs_ctx );
return( ret );
}
#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
(void) rs_ctx;
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
if( ctx->pk_info->sign_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
return( ctx->pk_info->sign_func( ctx->pk_ctx, md_alg, hash, hash_len,
sig, sig_len, f_rng, p_rng ) );
}
@ -577,17 +570,14 @@ int mbedtls_pk_decrypt( mbedtls_pk_context *ctx,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( input != NULL || ilen == 0 );
PK_VALIDATE_RET( output != NULL || osize == 0 );
PK_VALIDATE_RET( olen != NULL );
PK_VALIDATE_RET( ctx );
PK_VALIDATE_RET( input || ilen == 0 );
PK_VALIDATE_RET( output || osize == 0 );
PK_VALIDATE_RET( olen );
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if( ctx->pk_info->decrypt_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
return( ctx->pk_info->decrypt_func( ctx->pk_ctx, input, ilen,
output, olen, osize, f_rng, p_rng ) );
}
@ -613,17 +603,14 @@ int mbedtls_pk_encrypt( mbedtls_pk_context *ctx,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( input != NULL || ilen == 0 );
PK_VALIDATE_RET( output != NULL || osize == 0 );
PK_VALIDATE_RET( olen != NULL );
PK_VALIDATE_RET( ctx );
PK_VALIDATE_RET( input || ilen == 0 );
PK_VALIDATE_RET( output || osize == 0 );
PK_VALIDATE_RET( olen );
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if( ctx->pk_info->encrypt_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
return( ctx->pk_info->encrypt_func( ctx->pk_ctx, input, ilen,
output, olen, osize, f_rng, p_rng ) );
}
@ -643,18 +630,15 @@ int mbedtls_pk_encrypt( mbedtls_pk_context *ctx,
*/
int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv )
{
PK_VALIDATE_RET( pub != NULL );
PK_VALIDATE_RET( prv != NULL );
PK_VALIDATE_RET( pub );
PK_VALIDATE_RET( prv );
if( pub->pk_info == NULL ||
prv->pk_info == NULL )
{
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
}
if( prv->pk_info->check_pair_func == NULL )
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
if( prv->pk_info->type == MBEDTLS_PK_RSA_ALT )
{
if( pub->pk_info->type != MBEDTLS_PK_RSA )
@ -665,7 +649,6 @@ int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_conte
if( pub->pk_info != prv->pk_info )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
}
return( prv->pk_info->check_pair_func( pub->pk_ctx, prv->pk_ctx ) );
}
@ -695,13 +678,11 @@ size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx )
*/
int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items )
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( ctx );
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if( ctx->pk_info->debug_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
ctx->pk_info->debug_func( ctx->pk_ctx, items );
return( 0 );
}

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/asn1.h"
#include "third_party/mbedtls/asn1write.h"
#include "third_party/mbedtls/common.h"
@ -13,30 +30,16 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* Public Key abstraction layer: wrapper functions
*
* Copyright The Mbed TLS Contributors
* 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.
/**
* @fileoverview Public Key abstraction layer: wrapper functions
*/
#if defined(MBEDTLS_PK_C)
#if defined(MBEDTLS_RSA_C)
static int rsa_can_do( mbedtls_pk_type_t type )
{
return( type == MBEDTLS_PK_RSA ||
@ -53,7 +56,7 @@ static int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
size_t rsa_len = mbedtls_rsa_get_len( rsa );
#if SIZE_MAX > UINT_MAX
@ -202,7 +205,7 @@ static int eckey_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ecdsa_context ecdsa;
mbedtls_ecdsa_init( &ecdsa );
@ -216,11 +219,11 @@ static int eckey_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
}
static int eckey_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ecdsa_context ecdsa;
mbedtls_ecdsa_init( &ecdsa );
@ -237,15 +240,15 @@ static int eckey_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
#if defined(MBEDTLS_ECP_RESTARTABLE)
/* Forward declarations */
static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx );
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx );
static int ecdsa_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
void *rs_ctx );
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
void *rs_ctx );
/*
* Restart context for ECDSA operations with ECKEY context
@ -262,74 +265,61 @@ typedef struct
static void *eckey_rs_alloc( void )
{
eckey_restart_ctx *rs_ctx;
void *ctx = mbedtls_calloc( 1, sizeof( eckey_restart_ctx ) );
if( ctx != NULL )
{
rs_ctx = ctx;
mbedtls_ecdsa_restart_init( &rs_ctx->ecdsa_rs );
mbedtls_ecdsa_init( &rs_ctx->ecdsa_ctx );
}
return( ctx );
}
static void eckey_rs_free( void *ctx )
{
eckey_restart_ctx *rs_ctx;
if( ctx == NULL)
return;
rs_ctx = ctx;
mbedtls_ecdsa_restart_free( &rs_ctx->ecdsa_rs );
mbedtls_ecdsa_free( &rs_ctx->ecdsa_ctx );
mbedtls_free( ctx );
}
static int eckey_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx )
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
eckey_restart_ctx *rs = rs_ctx;
/* Should never happen */
if( rs == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
/* set up our own sub-context if needed (that is, on first run) */
if( rs->ecdsa_ctx.grp.pbits == 0 )
MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) );
MBEDTLS_MPI_CHK( ecdsa_verify_rs_wrap( &rs->ecdsa_ctx,
md_alg, hash, hash_len,
sig, sig_len, &rs->ecdsa_rs ) );
cleanup:
return( ret );
}
static int eckey_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
void *rs_ctx )
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, void *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
eckey_restart_ctx *rs = rs_ctx;
/* Should never happen */
if( rs == NULL )
if( !rs )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
/* set up our own sub-context if needed (that is, on first run) */
if( rs->ecdsa_ctx.grp.pbits == 0 )
MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) );
MBEDTLS_MPI_CHK( ecdsa_sign_rs_wrap( &rs->ecdsa_ctx, md_alg,
hash, hash_len, sig, sig_len,
f_rng, p_rng, &rs->ecdsa_rs ) );
@ -438,7 +428,7 @@ static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
((void) md_alg);
ret = mbedtls_ecdsa_read_signature( (mbedtls_ecdsa_context *) ctx,
hash, hash_len, sig, sig_len );
@ -462,7 +452,7 @@ static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *sig, size_t sig_len,
void *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
((void) md_alg);
ret = mbedtls_ecdsa_read_signature_restartable(
@ -596,7 +586,7 @@ static int rsa_alt_check_pair( const void *pub, const void *prv )
unsigned char sig[MBEDTLS_MPI_MAX_SIZE];
unsigned char hash[32];
size_t sig_len = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( rsa_alt_get_bitlen( prv ) != rsa_get_bitlen( pub ) )
return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
memset( hash, 0x2a, sizeof( hash ) );
@ -619,7 +609,7 @@ static void *rsa_alt_alloc_wrap( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_rsa_alt_context ) );
if( ctx != NULL )
memset( ctx, 0, sizeof( mbedtls_rsa_alt_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_alt_context ) );
return( ctx );
}

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/asn1.h"
#include "third_party/mbedtls/cipher.h"
#include "third_party/mbedtls/common.h"
@ -49,7 +66,7 @@ static int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params,
mbedtls_asn1_buf *salt, int *iterations,
int *keylen, mbedtls_md_type_t *md_type )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_asn1_buf prf_alg_oid;
unsigned char *p = params->p;
const unsigned char *end = params->p + params->len;
@ -216,7 +233,7 @@ int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx,
unsigned int iteration_count,
uint32_t key_length, unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
int j;
unsigned int i;
unsigned char md1[MBEDTLS_MD_MAX_SIZE];

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/calls/calls.h"
#include "third_party/mbedtls/asn1.h"
#include "third_party/mbedtls/common.h"
@ -125,7 +142,7 @@ int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n )
int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
const char *path, const char *pwd )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t n;
unsigned char *buf;
PK_VALIDATE_RET( ctx != NULL );
@ -160,7 +177,7 @@ int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
*/
int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t n;
unsigned char *buf;
PK_VALIDATE_RET( ctx != NULL );
@ -186,7 +203,7 @@ int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path )
static int pk_get_ecparams( unsigned char **p, const unsigned char *end,
mbedtls_asn1_buf *params )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if ( end - *p < 1 )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
@ -235,7 +252,7 @@ static int pk_get_ecparams( unsigned char **p, const unsigned char *end,
*/
static int pk_group_from_specified( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *p = params->p;
const unsigned char * const end = params->p + params->len;
const unsigned char *end_field, *end_curve;
@ -392,7 +409,7 @@ cleanup:
static int pk_group_id_from_specified( const mbedtls_asn1_buf *params,
mbedtls_ecp_group_id *grp_id )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ecp_group grp;
mbedtls_ecp_group_init( &grp );
@ -419,7 +436,7 @@ cleanup:
*/
static int pk_use_ecparams( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ecp_group_id grp_id;
if( params->tag == MBEDTLS_ASN1_OID )
@ -459,7 +476,7 @@ static int pk_use_ecparams( const mbedtls_asn1_buf *params, mbedtls_ecp_group *g
static int pk_get_ecpubkey( unsigned char **p, const unsigned char *end,
mbedtls_ecp_keypair *key )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( ( ret = mbedtls_ecp_point_read_binary( &key->grp, &key->Q,
(const unsigned char *) *p, end - *p ) ) == 0 )
@ -487,7 +504,7 @@ static int pk_get_rsapubkey( unsigned char **p,
const unsigned char *end,
mbedtls_rsa_context *rsa )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
@ -542,10 +559,10 @@ static int pk_get_pk_alg( unsigned char **p,
const unsigned char *end,
mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_asn1_buf alg_oid;
memset( params, 0, sizeof(mbedtls_asn1_buf) );
mbedtls_platform_zeroize( params, sizeof(mbedtls_asn1_buf) );
if( ( ret = mbedtls_asn1_get_alg( p, end, &alg_oid, params ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_ALG + ret );
@ -583,7 +600,7 @@ static int pk_get_pk_alg( unsigned char **p,
int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,
mbedtls_pk_context *pk )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len;
mbedtls_asn1_buf alg_params;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
@ -835,7 +852,7 @@ static int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck,
const unsigned char *key,
size_t keylen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
int version, pubkey_done;
size_t len;
mbedtls_asn1_buf params;
@ -1213,7 +1230,7 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
const unsigned char *key, size_t keylen,
const unsigned char *pwd, size_t pwdlen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const mbedtls_pk_info_t *pk_info;
#if defined(MBEDTLS_PEM_PARSE_C)
size_t len;
@ -1443,7 +1460,7 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,
const unsigned char *key, size_t keylen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *p;
#if defined(MBEDTLS_RSA_C)
const mbedtls_pk_info_t *pk_info;

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/asn1write.h"
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/common.h"
@ -54,7 +71,7 @@ asm(".include \"libc/disclaimer.inc\"");
static int pk_write_rsa_pubkey( unsigned char **p, unsigned char *start,
mbedtls_rsa_context *rsa )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
mbedtls_mpi T;
@ -93,7 +110,7 @@ end_of_export:
static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
unsigned char buf[MBEDTLS_ECP_MAX_PT_LEN];
@ -121,7 +138,7 @@ static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,
static int pk_write_ec_param( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
const char *oid;
size_t oid_len;
@ -140,7 +157,7 @@ static int pk_write_ec_param( unsigned char **p, unsigned char *start,
static int pk_write_ec_private( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t byte_length = ( ec->grp.pbits + 7 ) / 8;
unsigned char tmp[MBEDTLS_ECP_MAX_BYTES];
@ -168,7 +185,7 @@ exit:
int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,
const mbedtls_pk_context *key )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len = 0;
PK_VALIDATE_RET( p != NULL );
@ -229,7 +246,7 @@ int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,
*/
int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, size_t size )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *c;
size_t len = 0, par_len = 0, oid_len;
mbedtls_pk_type_t pk_type;
@ -330,7 +347,7 @@ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, si
*/
int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_t size )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *c;
size_t len = 0;
@ -583,7 +600,7 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
*/
int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *key, unsigned char *buf, size_t size )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char output_buf[PUB_DER_MAX_BYTES];
size_t olen = 0;
@ -618,7 +635,7 @@ int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *key, unsigned char *buf, si
*/
int mbedtls_pk_write_key_pem( mbedtls_pk_context *key, unsigned char *buf, size_t size )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *output_buf;
const char *begin, *end;
size_t olen = 0;

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/platform.h"
int mbedtls_platform_setup(mbedtls_platform_context *ctx) {

View file

@ -49,6 +49,13 @@ COSMOPOLITAN_C_START_
} \
} while (0)
#if IsModeDbg()
#define MBEDTLS_ASSERT(EXPR) \
((void)((EXPR) || (__assert_fail(#EXPR, __FILE__, __LINE__), 0)))
#else
#define MBEDTLS_ASSERT(EXPR) (void)0
#endif
typedef struct mbedtls_platform_context {
char dummy;
} mbedtls_platform_context;

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/common.h"
@ -411,7 +428,7 @@ int mbedtls_poly1305_mac( const unsigned char key[32],
unsigned char mac[16] )
{
mbedtls_poly1305_context ctx;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
POLY1305_VALIDATE_RET( key != NULL );
POLY1305_VALIDATE_RET( mac != NULL );
POLY1305_VALIDATE_RET( ilen == 0 || input != NULL );
@ -520,7 +537,7 @@ int mbedtls_poly1305_self_test( int verbose )
{
unsigned char mac[16];
unsigned i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
for( i = 0U; i < 2U; i++ )
{

44
third_party/mbedtls/profile.h vendored Normal file
View file

@ -0,0 +1,44 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_PROFILE_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_PROFILE_H_
#include "libc/bits/safemacros.internal.h"
#include "libc/log/log.h"
#include "libc/nexgen32e/bench.h"
#include "libc/nexgen32e/rdtsc.h"
#include "libc/time/time.h"
#if 1
#define START() \
{ \
volatile uint64_t Time = __startbench()
#define STOP(x) \
fprintf(stderr, "PROFILE %,10ldc %s\n", \
unsignedsubtract(__endbench(), Time), #x); \
}
#define PROFILE(x) \
({ \
typeof(x) Res; \
START(); \
Res = (x); \
STOP(x); \
Res; \
})
#define PROFILS(x) \
do { \
START(); \
x; \
STOP(x); \
} while (0)
#define PRINT() \
fprintf(stderr, "PRINT %s called by %s\n", __FUNCTION__, GetCallerName(0))
#else
#define PRINT() ((void)0)
#define PROFILE(x) x
#define PROFILS(x) x
#define START() ((void)0)
#define STOP(x) ((void)0)
#endif
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_PROFILE_H_ */

View file

@ -16,6 +16,7 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/nexgen32e/x86feature.h"
#include "libc/rand/rand.h"
#include "libc/sysv/consts/grnd.h"
#include "third_party/mbedtls/entropy_poll.h"

View file

@ -1,9 +1,28 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/rand/rand.h"
#include "libc/runtime/runtime.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/md.h"
#include "third_party/mbedtls/oid.h"
#include "third_party/mbedtls/platform.h"
#include "third_party/mbedtls/profile.h"
#include "third_party/mbedtls/rsa.h"
#include "third_party/mbedtls/rsa_internal.h"
#include "third_party/mbedtls/sha1.h"
@ -83,7 +102,7 @@ int mbedtls_rsa_import( mbedtls_rsa_context *ctx,
const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *E )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
RSA_VALIDATE_RET( ctx != NULL );
if( ( N != NULL && ( ret = mbedtls_mpi_copy( &ctx->N, N ) ) != 0 ) ||
@ -386,7 +405,7 @@ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx,
mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
mbedtls_mpi *D, mbedtls_mpi *E )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
int is_priv;
RSA_VALIDATE_RET( ctx != NULL );
@ -430,7 +449,7 @@ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx,
int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,
mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
int is_priv;
RSA_VALIDATE_RET( ctx != NULL );
@ -474,7 +493,7 @@ void mbedtls_rsa_init( mbedtls_rsa_context *ctx,
RSA_VALIDATE( ctx != NULL );
RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 ||
padding == MBEDTLS_RSA_PKCS_V21 );
memset( ctx, 0, sizeof( mbedtls_rsa_context ) );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_context ) );
mbedtls_rsa_set_padding( ctx, padding, hash_id );
}
@ -511,11 +530,11 @@ size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx )
* FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
*/
int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
unsigned int nbits, int exponent )
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
unsigned int nbits, int exponent )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_mpi H, G, L;
int prime_quality = 0;
RSA_VALIDATE_RET( ctx != NULL );
@ -571,7 +590,7 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,
/* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H ) );
if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
if( !mbedtls_mpi_is_one( &G ) )
continue;
/* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
@ -709,15 +728,15 @@ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub,
* Do an RSA public key operation
*/
int mbedtls_rsa_public( mbedtls_rsa_context *ctx,
const unsigned char *input,
unsigned char *output )
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t olen;
mbedtls_mpi T;
RSA_VALIDATE_RET( ctx != NULL );
RSA_VALIDATE_RET( input != NULL );
RSA_VALIDATE_RET( output != NULL );
RSA_VALIDATE_RET( ctx );
RSA_VALIDATE_RET( input );
RSA_VALIDATE_RET( output );
if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
@ -745,6 +764,10 @@ cleanup:
return( 0 );
}
/*
* TODO(jart): Why is MbedTLS release source so different from Git source?
* This function takes 806us to execute.
*/
/*
* Generate or update blinding values, see section 10 of:
* KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
@ -752,13 +775,12 @@ cleanup:
* Berlin Heidelberg, 1996. p. 104-113.
*/
static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret, count = 0;
mbedtls_mpi R;
mbedtls_mpi_init( &R );
if( ctx->Vf.p != NULL )
{
/* We already have blinding values, just update them by squaring */
@ -766,10 +788,8 @@ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) );
goto cleanup;
}
/* Unblinding value: Vf = random number, invertible mod N */
do {
if( count++ > 10 )
@ -777,14 +797,11 @@ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
ret = MBEDTLS_ERR_RSA_RNG_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) );
/* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, ctx->len - 1, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vf, &R ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
/* At this point, Vi is invertible mod N if and only if both Vf and R
* are invertible mod N. If one of them isn't, we don't need to know
* which one, we just loop and choose new values for both of them.
@ -792,21 +809,15 @@ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
ret = mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vi, &ctx->N );
if( ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
goto cleanup;
} while( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
/* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &R ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
/* Blinding value: Vi = Vf^(-e) mod N
* (Vi already contains Vf^-1 at this point) */
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) );
cleanup:
mbedtls_mpi_free( &R );
return( ret );
}
@ -840,7 +851,7 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t olen;
/* Temporary holding the result */
@ -922,6 +933,7 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
if( f_rng != NULL )
{
/*
* Blinding
* T = T * Vi mod N
@ -947,6 +959,7 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D ) );
D = &D_blind;
#else
/*
* DP_blind = ( P - 1 ) * R + DP
@ -956,7 +969,6 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind,
&ctx->DP ) );
DP = &DP_blind;
/*
@ -969,19 +981,20 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
&ctx->DQ ) );
DQ = &DQ_blind;
#endif /* MBEDTLS_RSA_NO_CRT */
}
#if defined(MBEDTLS_RSA_NO_CRT)
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N, &ctx->RN ) );
#else
/*
* Faster decryption using the CRT
*
* TP = input ^ dP mod P
* TQ = input ^ dQ mod Q
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P, &ctx->RP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q, &ctx->RQ ) );
@ -1071,7 +1084,7 @@ static int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src,
size_t i, use_len;
int ret = 0;
memset( mask, 0, MBEDTLS_MD_MAX_SIZE );
mbedtls_platform_zeroize( mask, MBEDTLS_MD_MAX_SIZE );
memset( counter, 0, 4 );
hlen = mbedtls_md_get_size( md_ctx->md_info );
@ -1121,7 +1134,7 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
unsigned char *output )
{
size_t olen;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *p = output;
unsigned int hlen;
const mbedtls_md_info_t *md_info;
@ -1151,7 +1164,7 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
memset( output, 0, olen );
mbedtls_platform_zeroize( output, olen );
*p++ = 0;
@ -1207,7 +1220,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,
unsigned char *output )
{
size_t nb_pad, olen;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *p = output;
RSA_VALIDATE_RET( ctx != NULL );
@ -1316,7 +1329,7 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
unsigned char *output,
size_t output_max_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t ilen, i, pad_len;
unsigned char *p, bad, pad_done;
unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
@ -1449,12 +1462,13 @@ cleanup:
}
#if defined(MBEDTLS_PKCS1_V15)
/** Turn zero-or-nonzero into zero-or-all-bits-one, without branches.
/**
* Does -!!value without branches.
*
* \param value The value to analyze.
* \return Zero if \p value is zero, otherwise all-bits-one.
*/
static unsigned all_or_nothing_int( unsigned value )
forceinline unsigned all_or_nothing_int( unsigned value )
{
/* MSVC has a warning about unary minus on unsigned, but this is
* well-defined and precisely what we want to do here */
@ -1478,7 +1492,7 @@ static unsigned all_or_nothing_int( unsigned value )
* \return \c 0 if `size <= max`.
* \return \c 1 if `size > max`.
*/
static unsigned size_greater_than( size_t size, size_t max )
forceinline unsigned size_greater_than( size_t size, size_t max )
{
/* Return the sign bit (1 for negative) of (max - size). */
return( ( max - size ) >> ( sizeof( size_t ) * 8 - 1 ) );
@ -1494,13 +1508,15 @@ static unsigned size_greater_than( size_t size, size_t max )
* \param if0 Value to use if \p cond is zero.
* \return \c if1 if \p cond is nonzero, otherwise \c if0.
*/
static unsigned if_int( unsigned cond, unsigned if1, unsigned if0 )
forceinline unsigned if_int( unsigned cond, unsigned if1, unsigned if0 )
{
unsigned mask = all_or_nothing_int( cond );
return( ( mask & if1 ) | (~mask & if0 ) );
return( ( CONCEAL( "r", mask ) & if1 ) |
( CONCEAL( "r", ~mask ) & if0 ) );
}
/** Shift some data towards the left inside a buffer without leaking
/**
* Shift some data towards the left inside a buffer without leaking
* the length of the data through side channels.
*
* `mem_move_to_left(start, total, offset)` is functionally equivalent to
@ -1551,7 +1567,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
unsigned char *output,
size_t output_max_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t ilen, i, plaintext_max_size;
unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
/* The following variables take sensitive values: their value must
@ -1766,7 +1782,7 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
unsigned char *p = sig;
unsigned char salt[MBEDTLS_MD_MAX_SIZE];
size_t slen, min_slen, hlen, offset = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t msb;
const mbedtls_md_info_t *md_info;
mbedtls_md_context_t md_ctx;
@ -1816,7 +1832,7 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
else
slen = olen - hlen - 2;
memset( sig, 0, olen );
mbedtls_platform_zeroize( sig, olen );
/* Generate salt of length slen */
if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )
@ -2020,7 +2036,7 @@ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
const unsigned char *hash,
unsigned char *sig )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *sig_try = NULL, *verif = NULL;
RSA_VALIDATE_RET( ctx != NULL );
@ -2141,7 +2157,7 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
int expected_salt_len,
const unsigned char *sig )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t siglen;
unsigned char *p;
unsigned char *hash_start;
@ -2437,7 +2453,7 @@ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,
*/
int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
RSA_VALIDATE_RET( dst != NULL );
RSA_VALIDATE_RET( src != NULL );

View file

@ -1,5 +1,23 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/profile.h"
#include "third_party/mbedtls/rsa.h"
#include "third_party/mbedtls/rsa_internal.h"
@ -138,7 +156,7 @@ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
/* Check if gcd(K,N) = 1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );
if( mbedtls_mpi_cmp_int( P, 1 ) != 0 )
if( !mbedtls_mpi_is_one( P ) )
continue;
/* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ...
@ -151,7 +169,7 @@ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
{
/* If we reach 1 prematurely, there's no point
* in continuing to square K */
if( mbedtls_mpi_cmp_int( &K, 1 ) == 0 )
if( mbedtls_mpi_is_one( &K ) )
break;
MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) );
@ -181,7 +199,7 @@ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
* Check if that's the case and abort if not, to avoid very long,
* yet eventually failing, computations if N,D,E were not sane.
*/
if( mbedtls_mpi_cmp_int( &K, 1 ) != 0 )
if( !mbedtls_mpi_is_one( &K ) )
{
break;
}

211
third_party/mbedtls/secp256r1.c vendored Normal file
View file

@ -0,0 +1,211 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/log/check.h"
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/math.h"
#include "third_party/mbedtls/platform.h"
#define Q(i) p[i >> 1]
#define L(w) (w & 0x00000000ffffffff)
#define H(w) (w & 0xffffffff00000000)
/**
* Fastest quasi-reduction modulo NIST P-256.
*
* p = 2² - 2²² + 2¹² + 2 - 1
* B = T + 2×S + 2×S + S + S D D D D mod p
* T = ( A A A A A A A A )
* S = ( A A A A A 0 0 0 )
* S = ( 0 A A A A 0 0 0 )
* S = ( A A 0 0 0 A A A )
* S = ( A A A A A A A A )
* D = ( A A 0 0 0 A A A )
* D = ( A A 0 0 A A A A )
* D = ( A 0 A A A A A A )
* D = ( A 0 A A A 0 A A )
*
* @see FIPS 186-3 §D.2.3
*/
void secp256r1(uint64_t p[8]) {
int r;
char o;
signed char E;
uint64_t A, B, C, D, a, b, c, d, e;
A = Q(0);
B = Q(2);
C = Q(4);
D = Q(6);
E = 0;
#if !defined(__x86_64__) || defined(__STRICT_ANSI__)
ADC(B, B, H(Q(10)) << 1, 0, o);
ADC(C, C, Q(12) << 1 | Q(10) >> 63, o, o);
ADC(D, D, Q(14) << 1 | Q(12) >> 63, o, o);
E += o + (Q(14) >> 63);
ADC(B, B, Q(12) << 33, 0, o);
ADC(C, C, Q(14) << 33 | Q(12) >> 31, o, o);
ADC(D, D, Q(14) >> 31, o, o);
E += o;
ADC(A, A, Q(8), 0, o);
ADC(B, B, L(Q(10)), o, o);
ADC(C, C, 0, o, o);
ADC(D, D, Q(14), o, o);
E += o;
ADC(A, A, Q(10) << 32 | Q(8) >> 32, 0, o);
ADC(B, B, H(Q(12)) | Q(10) >> 32, o, o);
ADC(C, C, Q(14), o, o);
ADC(D, D, Q(8) << 32 | Q(12) >> 32, o, o);
E += o;
SBB(A, A, Q(12) << 32 | Q(10) >> 32, 0, o);
SBB(B, B, Q(12) >> 32, o, o);
SBB(C, C, 0, o, o);
SBB(D, D, Q(10) << 32 | L(Q(8)), o, o);
E -= o;
SBB(A, A, Q(12), 0, o);
SBB(B, B, Q(14), o, o);
SBB(C, C, 0, o, o);
SBB(D, D, H(Q(10)) | Q(8) >> 32, o, o);
E -= o;
SBB(A, A, Q(14) << 32 | Q(12) >> 32, 0, o);
SBB(B, B, Q(8) << 32 | Q(14) >> 32, o, o);
SBB(C, C, Q(10) << 32 | Q(8) >> 32, o, o);
SBB(D, D, Q(12) << 32, o, o);
E -= o;
SBB(A, A, Q(14), 0, o);
SBB(B, B, H(Q(8)), o, o);
SBB(C, C, Q(10), o, o);
SBB(D, D, H(Q(12)), o, o);
E -= o;
#else
asm volatile(/* x += 2 × ( A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₂ ‖ A₁₁ ‖ 0 ‖ 0 ‖ 0 ) */
"mov\t11*4(%8),%k5\n\t"
"mov\t12*4(%8),%6\n\t"
"mov\t14*4(%8),%7\n\t"
"shl\t$33,%5\n\t"
"rcl\t%6\n\t"
"rcl\t%7\n\t"
"adc\t$0,%b4\n\t"
"add\t%5,%1\n\t"
"adc\t%6,%2\n\t"
"adc\t%7,%3\n\t"
"adc\t$0,%b4\n\t"
/* x += 2 × ( 0 ‖ A₁₅ ‖ A₁₄‖ A₁₃ ‖ A₁₂ ‖ 0 ‖ 0 ‖ 0 ) */
"mov\t12*4(%8),%k5\n\t"
"mov\t13*4(%8),%6\n\t"
"mov\t15*4(%8),%k7\n\t"
"shl\t$33,%5\n\t"
"rcl\t%6\n\t"
"rcl\t%7\n\t"
"add\t%5,%1\n\t"
"adc\t%6,%2\n\t"
"adc\t%7,%3\n\t"
/* x += ( A₁₅ ‖ A₁₄ ‖ 0 ‖ 0 ‖ 0 ‖ A₁₀ ‖ A₉ ‖ A₈ ) */
"mov\t10*4(%8),%k5\n\t"
"add\t8*4(%8),%0\n\t"
"adc\t%5,%1\n\t"
"adc\t$0,%2\n\t"
"adc\t14*4(%8),%3\n\t"
"adc\t$0,%b4\n\t"
/* x += ( A₈ ‖ A₁₃ ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₁ ‖ A₁₀ ‖ A₉ ) */
"mov\t8*4(%8),%k7\n\t" /* A₈ ‖ A₁₃ */
"mov\t13*4(%8),%k5\n\t" /* ... */
"shl\t$32,%7\n\t" /* ... */
"or\t%5,%7\n\t" /* ... */
"shl\t$32,%5\n\t" /* A₁₃ ‖ A₁₁ */
"mov\t11*4(%8),%k6\n\t" /* ... */
"or\t%6,%5\n\t" /* ... */
"add\t9*4(%8),%0\n\t" /* A₁₀ ‖ A₉ */
"adc\t%5,%1\n\t" /* ... */
"adc\t14*4(%8),%2\n\t" /* A₁₅ ‖ A₁₄ */
"adc\t%7,%3\n\t"
"adc\t$0,%b4\n\t"
/* x -= ( A₁₀ ‖ A₈ ‖ 0 ‖ 0 ‖ 0 ‖ A₁₃ ‖ A₁₂ ‖ A₁₁ ) */
"mov\t10*4(%8),%k6\n\t"
"mov\t8*4(%8),%k7\n\t"
"shl\t$32,%6\n\t"
"or\t%6,%7\n\t"
"mov\t13*4(%8),%k5\n\t"
"sub\t11*4(%8),%0\n\t"
"sbb\t%5,%1\n\t"
"sbb\t$0,%2\n\t"
"sbb\t%7,%3\n\t"
"sbb\t$0,%b4\n\t"
/* x -= ( A₁₁ ‖ A₉ ‖ 0 ‖ 0 ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₂ ) */
"mov\t11*4(%8),%k6\n\t"
"mov\t9*4(%8),%k7\n\t"
"shl\t$32,%6\n\t"
"or\t%6,%7\n\t"
"sub\t12*4(%8),%0\n\t"
"sbb\t14*4(%8),%1\n\t"
"sbb\t$0,%2\n\t"
"sbb\t%7,%3\n\t"
"sbb\t$0,%b4\n\t"
/* x -= ( A₁₂ ‖ 0 ‖ A₁₀ ‖ A₉ ‖ A₈ ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ) */
"mov\t12*4(%8),%k7\n\t"
"shl\t$32,%7\n\t"
"mov\t15*4(%8),%k6\n\t"
"mov\t8*4(%8),%k5\n\t"
"shl\t$32,%5\n\t"
"or\t%5,%6\n\t"
"sub\t13*4(%8),%0\n\t"
"sbb\t%6,%1\n\t"
"sbb\t9*4(%8),%2\n\t"
"sbb\t%7,%3\n\t"
"sbb\t$0,%b4\n\t"
/* x -= ( A₁₃ ‖ 0 ‖ A₁₁ ‖ A₁₀ ‖ A₉ ‖ 0 ‖ A₁₅ ‖ A₁₄ ) */
"mov\t9*4(%8),%k6\n\t"
"shl\t$32,%6\n\t"
"mov\t13*4(%8),%k5\n\t"
"shl\t$32,%5\n\t"
"sub\t14*4(%8),%0\n\t"
"sbb\t%6,%1\n\t"
"sbb\t10*4(%8),%2\n\t"
"sbb\t%5,%3\n\t"
"sbb\t$0,%b4\n\t"
: "+r"(A), "+r"(B), "+r"(C), "+r"(D), "+&q"(E), "=&r"(b),
"=&r"(c), "=&r"(d)
: "r"(p)
: "memory");
#endif
p[0] = A;
p[1] = B;
p[2] = C;
p[3] = D;
p[4] = E;
p[5] = 0;
p[6] = 0;
p[7] = 0;
}
int ecp_mod_p256(mbedtls_mpi *N) {
int r;
char o;
if (N->n < 8 && (r = mbedtls_mpi_grow(N, 8))) return r;
secp256r1(N->p);
if ((int64_t)N->p[4] < 0) {
N->s = -1;
SBB(N->p[0], 0, N->p[0], 0, o);
SBB(N->p[1], 0, N->p[1], o, o);
SBB(N->p[2], 0, N->p[2], o, o);
SBB(N->p[3], 0, N->p[3], o, o);
N->p[4] = 0 - (N->p[4] + o);
} else {
N->s = 1;
}
return 0;
}

251
third_party/mbedtls/secp384r1.c vendored Normal file
View file

@ -0,0 +1,251 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/log/check.h"
#include "third_party/mbedtls/bignum.h"
#include "third_party/mbedtls/ecp_internal.h"
#include "third_party/mbedtls/math.h"
#define Q(i) p[i >> 1]
/**
* Fastest quasi-reduction modulo Prime 384.
*
* p = 2³ 2¹² 2 + 2³² 1
* B = T + 2×S + S + S + S + S + S D D D mod p
* T = (AAA A A A A A A A A A )
* S = (0 0 0 0 0 AAA0 0 0 0 )
* S = (AAAAAAAAAAAA)
* S = (AAAAAAAAAAAA)
* S = (AAAAAAAAA0 A0 )
* S = (0 0 0 0 AAAA0 0 0 0 )
* S = (0 0 0 0 0 0 AAA0 0 A)
* D = (AAAAAAAAAAAA)
* D = (0 0 0 0 0 0 0 AAAA0 )
* D = (0 0 0 0 0 0 0 AA0 0 0 )
*
* @see FIPS 186-3 §D.2.4
*/
void secp384r1(uint64_t p[12]) {
int r;
char o;
signed char G;
uint64_t A, B, C, D, E, F, a, b, c;
A = Q(0);
B = Q(2);
C = Q(4);
D = Q(6);
E = Q(8);
F = Q(10);
G = 0;
#if !defined(__x86_64__) || defined(__STRICT_ANSI__)
a = Q(22) << 32 | Q(21) >> 32;
b = Q(23) >> 32;
ADC(C, C, a << 1, 0, o);
ADC(D, D, (b << 1 | a >> 63), o, o);
ADC(E, E, (b >> 63), o, o);
ADC(F, F, o, o, o);
G += o;
ADC(A, A, Q(12), 0, o);
ADC(B, B, Q(14), o, o);
ADC(C, C, Q(16), o, o);
ADC(D, D, Q(18), o, o);
ADC(E, E, Q(20), o, o);
ADC(F, F, Q(22), o, o);
G += o;
ADC(A, A, Q(22) << 32 | Q(21) >> 32, 0, o);
ADC(B, B, Q(12) << 32 | Q(23) >> 32, o, o);
ADC(C, C, Q(14) << 32 | Q(13) >> 32, o, o);
ADC(D, D, Q(16) << 32 | Q(15) >> 32, o, o);
ADC(E, E, Q(18) << 32 | Q(17) >> 32, o, o);
ADC(F, F, Q(20) << 32 | Q(19) >> 32, o, o);
G += o;
ADC(A, A, Q(23) >> 32 << 32, 0, o);
ADC(B, B, Q(20) << 32, o, o);
ADC(C, C, Q(12), o, o);
ADC(D, D, Q(14), o, o);
ADC(E, E, Q(16), o, o);
ADC(F, F, Q(18), o, o);
G += o;
ADC(C, C, Q(20), 0, o);
ADC(D, D, Q(22), o, o);
ADC(E, E, 0, o, o);
ADC(F, F, 0, o, o);
G += o;
ADC(A, A, Q(20) & 0xffffffff, 0, o);
ADC(B, B, Q(21) >> 32 << 32, o, o);
ADC(C, C, Q(22), o, o);
ADC(D, D, 0, o, o);
ADC(E, E, 0, o, o);
ADC(F, F, 0, o, o);
G += o;
SBB(A, A, Q(12) << 32 | Q(23) >> 32, 0, o);
SBB(B, B, Q(14) << 32 | Q(13) >> 32, o, o);
SBB(C, C, Q(16) << 32 | Q(15) >> 32, o, o);
SBB(D, D, Q(18) << 32 | Q(17) >> 32, o, o);
SBB(E, E, Q(20) << 32 | Q(19) >> 32, o, o);
SBB(F, F, Q(22) << 32 | Q(21) >> 32, o, o);
G -= o;
SBB(A, A, Q(20) << 32, 0, o);
SBB(B, B, Q(22) << 32 | Q(21) >> 32, o, o);
SBB(C, C, Q(23) >> 32, o, o);
SBB(D, D, 0, o, o);
SBB(E, E, 0, o, o);
SBB(F, F, 0, o, o);
G -= o;
SBB(B, B, Q(23) >> 32 << 32, 0, o);
SBB(C, C, Q(23) >> 32, o, o);
SBB(D, D, 0, o, o);
SBB(E, E, 0, o, o);
SBB(F, F, 0, o, o);
G -= o;
#else
asm volatile(/* S₁ = (0 ‖0 ‖0 ‖0 ‖0 ‖A₂₃‖A₂₂‖A₂₁‖0 ‖0 ‖0 ‖0 ) */
"mov\t21*4(%9),%7\n\t"
"mov\t23*4(%9),%k8\n\t"
"shl\t%7\n\t"
"rcl\t%8\n\t"
"add\t%7,%2\n\t"
"adc\t%8,%3\n\t"
"adc\t$0,%4\n\t"
"adc\t$0,%5\n\t"
"adc\t$0,%b6\n\t"
/* S₂ = (A₂₃‖A₂₂‖A₂₁‖A₂₀‖A₁₉‖A₁₈‖A₁₇‖A₁₆‖A₁₅‖A₁₄‖A₁₃‖A₁₂) */
"add\t12*4(%9),%0\n\t"
"adc\t14*4(%9),%1\n\t"
"adc\t16*4(%9),%2\n\t"
"adc\t18*4(%9),%3\n\t"
"adc\t20*4(%9),%4\n\t"
"adc\t22*4(%9),%5\n\t"
"adc\t$0,%b6\n\t"
/* S₃ = (A₂₀‖A₁₉‖A₁₈‖A₁₇‖A₁₆‖A₁₅‖A₁₄‖A₁₃‖A₁₂‖A₂₃‖A₂₂‖A₂₁) */
"mov\t12*4(%9),%k7\n\t"
"mov\t23*4(%9),%k8\n\t"
"shl\t$32,%7\n\t"
"or\t%7,%8\n\t"
"add\t21*4(%9),%0\n\t"
"adc\t%8,%1\n\t"
"adc\t13*4(%9),%2\n\t"
"adc\t15*4(%9),%3\n\t"
"adc\t17*4(%9),%4\n\t"
"adc\t19*4(%9),%5\n\t"
"adc\t$0,%b6\n\t"
/* S₄ = (A₁₉‖A₁₈‖A₁₇‖A₁₆‖A₁₅‖A₁₄‖A₁₃‖A₁₂‖A₂₀‖0 ‖A₂₃‖0 ) */
"mov\t23*4(%9),%k7\n\t"
"mov\t20*4(%9),%k8\n\t"
"shl\t$32,%7\n\t"
"shl\t$32,%8\n\t"
"add\t%7,%0\n\t"
"adc\t%8,%1\n\t"
"adc\t12*4(%9),%2\n\t"
"adc\t14*4(%9),%3\n\t"
"adc\t16*4(%9),%4\n\t"
"adc\t18*4(%9),%5\n\t"
"adc\t$0,%b6\n\t"
/* S₅ = (0 ‖0 ‖0 ‖0 ‖A₂₃‖A₂₂‖A₂₁‖A₂₀‖0 ‖0 ‖0 ‖0 ) */
"mov\t23*4(%9),%k7\n\t"
"mov\t20*4(%9),%k8\n\t"
"shl\t$32,%7\n\t"
"shl\t$32,%8\n\t"
"add\t20*4(%9),%2\n\t"
"adc\t22*4(%9),%3\n\t"
"adc\t$0,%4\n\t"
"adc\t$0,%5\n\t"
"adc\t$0,%b6\n\t"
/* S₆ = (0 ‖0 ‖0 ‖0 ‖0 ‖0 ‖A₂₃‖A₂₂‖A₂₁‖0 ‖0 ‖A₂₀) */
"mov\t20*4(%9),%k7\n\t"
"mov\t21*4(%9),%k8\n\t"
"shl\t$32,%8\n\t"
"add\t%7,%0\n\t"
"adc\t%8,%1\n\t"
"adc\t22*4(%9),%2\n\t"
"adc\t$0,%3\n\t"
"adc\t$0,%4\n\t"
"adc\t$0,%5\n\t"
"adc\t$0,%b6\n\t"
/* D₁ = (A₂₂‖A₂₁‖A₂₀‖A₁₉‖A₁₈‖A₁₇‖A₁₆‖A₁₅‖A₁₄‖A₁₃‖A₁₂‖A₂₃) */
"mov\t23*4(%9),%k7\n\t"
"mov\t12*4(%9),%k8\n\t"
"shl\t$32,%8\n\t"
"or\t%8,%7\n\t"
"sub\t%7,%0\n\t"
"sbb\t13*4(%9),%1\n\t"
"sbb\t15*4(%9),%2\n\t"
"sbb\t17*4(%9),%3\n\t"
"sbb\t19*4(%9),%4\n\t"
"sbb\t21*4(%9),%5\n\t"
"sbb\t$0,%b6\n\t"
/* D₂ = (0 ‖0 ‖0 ‖0 ‖0 ‖0 ‖0 ‖A₂₃‖A₂₂‖A₂₁‖A₂₀‖0 ) */
"mov\t20*4(%9),%k7\n\t"
"mov\t23*4(%9),%k8\n\t"
"shl\t$32,%7\n\t"
"sub\t%7,%0\n\t"
"sbb\t21*4(%9),%1\n\t"
"sbb\t%8,%2\n\t"
"sbb\t$0,%3\n\t"
"sbb\t$0,%4\n\t"
"sbb\t$0,%5\n\t"
"sbb\t$0,%b6\n\t"
/* D₃ = (0 ‖0 ‖0 ‖0 ‖0 ‖0 ‖0 ‖A₂₃‖A₂₃‖0 ‖0 ‖0 ) */
"mov\t23*4(%9),%k7\n\t"
"mov\t%k7,%k8\n\t"
"shl\t$32,%7\n\t"
"sub\t%7,%1\n\t"
"sbb\t%8,%2\n\t"
"sbb\t$0,%3\n\t"
"sbb\t$0,%4\n\t"
"sbb\t$0,%5\n\t"
"sbb\t$0,%b6\n\t"
: "+r"(A), "+r"(B), "+r"(C), "+r"(D), "+r"(E), "+r"(F), "+q"(G),
"=&r"(a), "=&r"(b)
: "r"(p)
: "memory");
#endif
p[0] = A;
p[1] = B;
p[2] = C;
p[3] = D;
p[4] = E;
p[5] = F;
p[6] = G;
p[7] = 0;
p[8] = 0;
p[9] = 0;
p[10] = 0;
p[11] = 0;
}
int ecp_mod_p384(mbedtls_mpi *N) {
int r;
char o;
if (N->n < 12 && (r = mbedtls_mpi_grow(N, 12))) return r;
secp384r1(N->p);
if ((int64_t)N->p[6] < 0) {
N->s = -1;
SBB(N->p[0], 0, N->p[0], 0, o);
SBB(N->p[1], 0, N->p[1], o, o);
SBB(N->p[2], 0, N->p[2], o, o);
SBB(N->p[3], 0, N->p[3], o, o);
SBB(N->p[4], 0, N->p[4], o, o);
SBB(N->p[5], 0, N->p[5], o, o);
N->p[6] = 0 - (N->p[6] + o);
} else {
N->s = 1;
}
return 0;
}

12
third_party/mbedtls/select.h vendored Normal file
View file

@ -0,0 +1,12 @@
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SELECT_H_
#define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SELECT_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
static inline uint64_t Select(uint64_t a, uint64_t b, uint64_t mask) {
return (CONCEAL("r", mask) & a) | (CONCEAL("r", ~mask) & b);
}
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SELECT_H_ */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/bits/bits.h"
#include "libc/macros.internal.h"
#include "libc/nexgen32e/x86feature.h"
@ -5,6 +22,7 @@
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/endian.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/md.h"
#include "third_party/mbedtls/platform.h"
#include "third_party/mbedtls/sha1.h"
@ -46,42 +64,6 @@ void sha1_transform_avx2(mbedtls_sha1_context *, const uint8_t *, int);
#define SHA1_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond )
/**
* \brief This function initializes a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize.
* This must not be \c NULL.
*
*/
void mbedtls_sha1_init( mbedtls_sha1_context *ctx )
{
SHA1_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_sha1_context ) );
}
/**
* \brief This function clears a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to clear. This may be \c NULL,
* in which case this function does nothing. If it is
* not \c NULL, it must point to an initialized
* SHA-1 context.
*
*/
void mbedtls_sha1_free( mbedtls_sha1_context *ctx )
{
if( !ctx ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) );
}
/**
* \brief This function clones the state of a SHA-1 context.
*
@ -395,7 +377,7 @@ int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
uint32_t left;
size_t n, fill;
@ -466,7 +448,7 @@ int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
unsigned char output[20] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
uint32_t used;
uint32_t high, low;
@ -483,17 +465,17 @@ int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
if( used <= 56 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 56 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 64 - used );
if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 56 );
mbedtls_platform_zeroize( ctx->buffer, 56 );
}
/*
@ -548,7 +530,7 @@ int mbedtls_sha1_ret( const void *input,
size_t ilen,
unsigned char output[20] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_sha1_context ctx;
SHA1_VALIDATE_RET( ilen == 0 || input != NULL );
@ -571,6 +553,18 @@ exit:
return( ret );
}
const mbedtls_md_info_t mbedtls_sha1_info = {
"SHA1",
MBEDTLS_MD_SHA1,
20,
64,
(void *)mbedtls_sha1_starts_ret,
(void *)mbedtls_sha1_update_ret,
(void *)mbedtls_internal_sha1_process,
(void *)mbedtls_sha1_finish_ret,
(void *)mbedtls_sha1_ret,
};
#if defined(MBEDTLS_SELF_TEST)
/*
* FIPS-180-1 test vectors

View file

@ -1,6 +1,7 @@
#ifndef MBEDTLS_SHA1_H_
#define MBEDTLS_SHA1_H_
#include "third_party/mbedtls/config.h"
#include "third_party/mbedtls/platform.h"
COSMOPOLITAN_C_START_
/* clang-format off */
@ -24,8 +25,6 @@ typedef struct mbedtls_sha1_context
}
mbedtls_sha1_context;
void mbedtls_sha1_init( mbedtls_sha1_context * );
void mbedtls_sha1_free( mbedtls_sha1_context * );
void mbedtls_sha1_clone( mbedtls_sha1_context *, const mbedtls_sha1_context * );
int mbedtls_sha1_starts_ret( mbedtls_sha1_context * );
int mbedtls_sha1_update_ret( mbedtls_sha1_context *, const unsigned char *, size_t );
@ -34,5 +33,39 @@ int mbedtls_internal_sha1_process( mbedtls_sha1_context *, const unsigned char[6
int mbedtls_sha1_ret( const void *, size_t, unsigned char[20] );
int mbedtls_sha1_self_test( int );
/**
* \brief This function initializes a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize.
* This must not be \c NULL.
*
*/
static inline void mbedtls_sha1_init( mbedtls_sha1_context *ctx )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) );
}
/**
* \brief This function clears a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to clear. This may be \c NULL,
* in which case this function does nothing. If it is
* not \c NULL, it must point to an initialized
* SHA-1 context.
*/
static inline void mbedtls_sha1_free( mbedtls_sha1_context *ctx )
{
if( !ctx ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) );
}
COSMOPOLITAN_C_END_
#endif /* MBEDTLS_SHA1_H_ */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/dce.h"
#include "libc/macros.internal.h"
#include "libc/nexgen32e/x86feature.h"
@ -5,6 +22,7 @@
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/endian.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/md.h"
#include "third_party/mbedtls/platform.h"
#include "third_party/mbedtls/sha256.h"
@ -13,30 +31,14 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* FIPS-180-2 compliant SHA-256 implementation
/**
* @fileoverview FIPS-180-2 compliant SHA-256 implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
* The SHA-256 Secure Hash Standard was published by NIST in 2002.
*
* 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.
*/
/*
* The SHA-256 Secure Hash Standard was published by NIST in 2002.
*
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
* @see http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
*/
#define SHA256_VALIDATE_RET(cond) \
@ -47,30 +49,6 @@ void sha256_transform_rorx(mbedtls_sha256_context *, const uint8_t *, int);
#if !defined(MBEDTLS_SHA256_ALT)
/**
* \brief This function initializes a SHA-256 context.
*
* \param ctx The SHA-256 context to initialize. This must not be \c NULL.
*/
void mbedtls_sha256_init( mbedtls_sha256_context *ctx )
{
SHA256_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_sha256_context ) );
}
/**
* \brief This function clears a SHA-256 context.
*
* \param ctx The SHA-256 context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized SHA-256 context.
*/
void mbedtls_sha256_free( mbedtls_sha256_context *ctx )
{
if( ctx == NULL ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) );
}
/**
* \brief This function clones the state of a SHA-256 context.
*
@ -80,11 +58,45 @@ void mbedtls_sha256_free( mbedtls_sha256_context *ctx )
void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src )
{
SHA256_VALIDATE( dst != NULL );
SHA256_VALIDATE( src != NULL );
SHA256_VALIDATE( dst );
SHA256_VALIDATE( src );
*dst = *src;
}
int mbedtls_sha256_starts_224( mbedtls_sha256_context *ctx )
{
SHA256_VALIDATE_RET( ctx );
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0xC1059ED8;
ctx->state[1] = 0x367CD507;
ctx->state[2] = 0x3070DD17;
ctx->state[3] = 0xF70E5939;
ctx->state[4] = 0xFFC00B31;
ctx->state[5] = 0x68581511;
ctx->state[6] = 0x64F98FA7;
ctx->state[7] = 0xBEFA4FA4;
ctx->is224 = true;
return( 0 );
}
int mbedtls_sha256_starts_256( mbedtls_sha256_context *ctx )
{
SHA256_VALIDATE_RET( ctx );
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x6A09E667;
ctx->state[1] = 0xBB67AE85;
ctx->state[2] = 0x3C6EF372;
ctx->state[3] = 0xA54FF53A;
ctx->state[4] = 0x510E527F;
ctx->state[5] = 0x9B05688C;
ctx->state[6] = 0x1F83D9AB;
ctx->state[7] = 0x5BE0CD19;
ctx->is224 = false;
return( 0 );
}
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
@ -98,40 +110,12 @@ void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
*/
int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 )
{
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( ctx );
SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 );
ctx->total[0] = 0;
ctx->total[1] = 0;
if( is224 == 0 )
{
/* SHA-256 */
ctx->state[0] = 0x6A09E667;
ctx->state[1] = 0xBB67AE85;
ctx->state[2] = 0x3C6EF372;
ctx->state[3] = 0xA54FF53A;
ctx->state[4] = 0x510E527F;
ctx->state[5] = 0x9B05688C;
ctx->state[6] = 0x1F83D9AB;
ctx->state[7] = 0x5BE0CD19;
}
if( !is224 )
return mbedtls_sha256_starts_256( ctx );
else
{
/* SHA-224 */
ctx->state[0] = 0xC1059ED8;
ctx->state[1] = 0x367CD507;
ctx->state[2] = 0x3070DD17;
ctx->state[3] = 0xF70E5939;
ctx->state[4] = 0xFFC00B31;
ctx->state[5] = 0x68581511;
ctx->state[6] = 0x64F98FA7;
ctx->state[7] = 0xBEFA4FA4;
}
ctx->is224 = is224;
return( 0 );
return mbedtls_sha256_starts_224( ctx );
}
#if !defined(MBEDTLS_SHA256_PROCESS_ALT)
@ -298,7 +282,7 @@ int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t fill;
uint32_t left;
@ -365,7 +349,7 @@ int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
unsigned char output[32] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
uint32_t used;
uint32_t high, low;
@ -382,17 +366,17 @@ int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
if( used <= 56 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 56 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 64 - used );
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 56 );
mbedtls_platform_zeroize( ctx->buffer, 56 );
}
/*
@ -450,7 +434,7 @@ int mbedtls_sha256_ret( const void *input,
unsigned char output[32],
int is224 )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_sha256_context ctx;
SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 );
@ -474,6 +458,40 @@ exit:
return( ret );
}
noinstrument int mbedtls_sha256_ret_224( const void *input, size_t ilen, void *output )
{
return mbedtls_sha256_ret( input, ilen, output, true );
}
noinstrument int mbedtls_sha256_ret_256( const void *input, size_t ilen, void *output )
{
return mbedtls_sha256_ret( input, ilen, output, false );
}
const mbedtls_md_info_t mbedtls_sha224_info = {
"SHA224",
MBEDTLS_MD_SHA224,
28,
64,
(void *)mbedtls_sha256_starts_224,
(void *)mbedtls_sha256_update_ret,
(void *)mbedtls_internal_sha256_process,
(void *)mbedtls_sha256_finish_ret,
mbedtls_sha256_ret_224,
};
const mbedtls_md_info_t mbedtls_sha256_info = {
"SHA256",
MBEDTLS_MD_SHA256,
32,
64,
(void *)mbedtls_sha256_starts_256,
(void *)mbedtls_sha256_update_ret,
(void *)mbedtls_internal_sha256_process,
(void *)mbedtls_sha256_finish_ret,
mbedtls_sha256_ret_256,
};
#if defined(MBEDTLS_SELF_TEST)
/*
* FIPS-180-2 test vectors
@ -537,40 +555,31 @@ int mbedtls_sha256_self_test( int verbose )
unsigned char *buf;
unsigned char sha256sum[32];
mbedtls_sha256_context ctx;
buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
if( NULL == buf )
{
if( verbose != 0 )
mbedtls_printf( "Buffer allocation failed\n" );
return( 1 );
}
mbedtls_sha256_init( &ctx );
for( i = 0; i < 6; i++ )
{
j = i % 3;
k = i < 3;
if( verbose != 0 )
mbedtls_printf( " SHA-%d test #%d: ", 256 - k * 32, j + 1 );
if( ( ret = mbedtls_sha256_starts_ret( &ctx, k ) ) != 0 )
goto fail;
if( j == 2 )
{
memset( buf, 'a', buflen = 1000 );
for( j = 0; j < 1000; j++ )
{
ret = mbedtls_sha256_update_ret( &ctx, buf, buflen );
if( ret != 0 )
goto fail;
}
}
else
{
@ -579,34 +588,25 @@ int mbedtls_sha256_self_test( int verbose )
if( ret != 0 )
goto fail;
}
if( ( ret = mbedtls_sha256_finish_ret( &ctx, sha256sum ) ) != 0 )
goto fail;
if( memcmp( sha256sum, sha256_test_sum[i], 32 - k * 4 ) != 0 )
{
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
goto exit;
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
exit:
mbedtls_sha256_free( &ctx );
mbedtls_free( buf );
return( ret );
}

View file

@ -1,6 +1,7 @@
#ifndef MBEDTLS_SHA256_H_
#define MBEDTLS_SHA256_H_
#include "third_party/mbedtls/config.h"
#include "third_party/mbedtls/platform.h"
COSMOPOLITAN_C_START_
/* clang-format off */
@ -24,8 +25,6 @@ typedef struct mbedtls_sha256_context
}
mbedtls_sha256_context;
void mbedtls_sha256_init( mbedtls_sha256_context * );
void mbedtls_sha256_free( mbedtls_sha256_context * );
void mbedtls_sha256_clone( mbedtls_sha256_context *, const mbedtls_sha256_context * );
int mbedtls_sha256_starts_ret( mbedtls_sha256_context *, int );
int mbedtls_sha256_update_ret( mbedtls_sha256_context *, const unsigned char *, size_t );
@ -34,5 +33,28 @@ int mbedtls_internal_sha256_process( mbedtls_sha256_context *, const unsigned ch
int mbedtls_sha256_ret( const void *, size_t, unsigned char[32], int );
int mbedtls_sha256_self_test( int );
/**
* \brief This function initializes a SHA-256 context.
*
* \param ctx The SHA-256 context to initialize. This must not be \c NULL.
*/
static inline void mbedtls_sha256_init( mbedtls_sha256_context *ctx )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) );
}
/**
* \brief This function clears a SHA-256 context.
*
* \param ctx The SHA-256 context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized SHA-256 context.
*/
static inline void mbedtls_sha256_free( mbedtls_sha256_context *ctx )
{
if( !ctx ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) );
}
COSMOPOLITAN_C_END_
#endif /* MBEDTLS_SHA256_H_ */

View file

@ -1,10 +1,29 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/literal.h"
#include "libc/macros.internal.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/str/str.h"
#include "third_party/mbedtls/chk.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/endian.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/md.h"
#include "third_party/mbedtls/platform.h"
#include "third_party/mbedtls/sha512.h"
@ -13,30 +32,14 @@ Mbed TLS (Apache 2.0)\\n\
Copyright ARM Limited\\n\
Copyright Mbed TLS Contributors\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/*
* FIPS-180-2 compliant SHA-384/512 implementation
/**
* @fileoverview FIPS-180-2 compliant SHA-384/512 implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
* The SHA-512 Secure Hash Standard was published by NIST in 2002.
*
* 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.
*/
/*
* The SHA-512 Secure Hash Standard was published by NIST in 2002.
*
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
* @see http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
*/
void sha512_transform_rorx(mbedtls_sha512_context *, const uint8_t *, int);
@ -51,32 +54,6 @@ void sha512_transform_rorx(mbedtls_sha512_context *, const uint8_t *, int);
#define sha512_put_uint64_be PUT_UINT64_BE
/**
* \brief This function initializes a SHA-512 context.
*
* \param ctx The SHA-512 context to initialize. This must
* not be \c NULL.
*/
void mbedtls_sha512_init( mbedtls_sha512_context *ctx )
{
SHA512_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_sha512_context ) );
}
/**
* \brief This function clears a SHA-512 context.
*
* \param ctx The SHA-512 context to clear. This may be \c NULL,
* in which case this function does nothing. If it
* is not \c NULL, it must point to an initialized
* SHA-512 context.
*/
void mbedtls_sha512_free( mbedtls_sha512_context *ctx )
{
if( !ctx ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) );
}
/**
* \brief This function clones the state of a SHA-512 context.
*
@ -86,11 +63,45 @@ void mbedtls_sha512_free( mbedtls_sha512_context *ctx )
void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
const mbedtls_sha512_context *src )
{
SHA512_VALIDATE( dst != NULL );
SHA512_VALIDATE( src != NULL );
SHA512_VALIDATE( dst );
SHA512_VALIDATE( src );
*dst = *src;
}
int mbedtls_sha512_starts_384( mbedtls_sha512_context *ctx )
{
SHA512_VALIDATE_RET( ctx );
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = UINT64_C(0xCBBB9D5DC1059ED8);
ctx->state[1] = UINT64_C(0x629A292A367CD507);
ctx->state[2] = UINT64_C(0x9159015A3070DD17);
ctx->state[3] = UINT64_C(0x152FECD8F70E5939);
ctx->state[4] = UINT64_C(0x67332667FFC00B31);
ctx->state[5] = UINT64_C(0x8EB44A8768581511);
ctx->state[6] = UINT64_C(0xDB0C2E0D64F98FA7);
ctx->state[7] = UINT64_C(0x47B5481DBEFA4FA4);
ctx->is384 = true;
return( 0 );
}
int mbedtls_sha512_starts_512( mbedtls_sha512_context *ctx )
{
SHA512_VALIDATE_RET( ctx );
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = UINT64_C(0x6A09E667F3BCC908);
ctx->state[1] = UINT64_C(0xBB67AE8584CAA73B);
ctx->state[2] = UINT64_C(0x3C6EF372FE94F82B);
ctx->state[3] = UINT64_C(0xA54FF53A5F1D36F1);
ctx->state[4] = UINT64_C(0x510E527FADE682D1);
ctx->state[5] = UINT64_C(0x9B05688C2B3E6C1F);
ctx->state[6] = UINT64_C(0x1F83D9ABFB41BD6B);
ctx->state[7] = UINT64_C(0x5BE0CD19137E2179);
ctx->is384 = false;
return( 0 );
}
/**
* \brief This function starts a SHA-384 or SHA-512 checksum
* calculation.
@ -108,50 +119,12 @@ void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
*/
int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 )
{
SHA512_VALIDATE_RET( ctx != NULL );
#if !defined(MBEDTLS_SHA512_NO_SHA384)
SHA512_VALIDATE_RET( ctx );
SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 );
#else
SHA512_VALIDATE_RET( is384 == 0 );
#endif
ctx->total[0] = 0;
ctx->total[1] = 0;
if( is384 == 0 )
{
/* SHA-512 */
ctx->state[0] = UINT64_C(0x6A09E667F3BCC908);
ctx->state[1] = UINT64_C(0xBB67AE8584CAA73B);
ctx->state[2] = UINT64_C(0x3C6EF372FE94F82B);
ctx->state[3] = UINT64_C(0xA54FF53A5F1D36F1);
ctx->state[4] = UINT64_C(0x510E527FADE682D1);
ctx->state[5] = UINT64_C(0x9B05688C2B3E6C1F);
ctx->state[6] = UINT64_C(0x1F83D9ABFB41BD6B);
ctx->state[7] = UINT64_C(0x5BE0CD19137E2179);
}
if( !is384 )
return mbedtls_sha512_starts_512( ctx );
else
{
#if defined(MBEDTLS_SHA512_NO_SHA384)
return( MBEDTLS_ERR_SHA512_BAD_INPUT_DATA );
#else
/* SHA-384 */
ctx->state[0] = UINT64_C(0xCBBB9D5DC1059ED8);
ctx->state[1] = UINT64_C(0x629A292A367CD507);
ctx->state[2] = UINT64_C(0x9159015A3070DD17);
ctx->state[3] = UINT64_C(0x152FECD8F70E5939);
ctx->state[4] = UINT64_C(0x67332667FFC00B31);
ctx->state[5] = UINT64_C(0x8EB44A8768581511);
ctx->state[6] = UINT64_C(0xDB0C2E0D64F98FA7);
ctx->state[7] = UINT64_C(0x47B5481DBEFA4FA4);
#endif /* MBEDTLS_SHA512_NO_SHA384 */
}
#if !defined(MBEDTLS_SHA512_NO_SHA384)
ctx->is384 = is384;
#endif
return( 0 );
return mbedtls_sha512_starts_384( ctx );
}
#if !defined(MBEDTLS_SHA512_PROCESS_ALT)
@ -321,7 +294,6 @@ int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
/* Zeroise buffers and variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
return( 0 );
}
@ -344,54 +316,41 @@ int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t fill;
unsigned int left;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( ilen == 0 || input != NULL );
if( ilen == 0 )
return( 0 );
left = (unsigned int) (ctx->total[0] & 0x7F);
fill = 128 - left;
ctx->total[0] += (uint64_t) ilen;
if( ctx->total[0] < (uint64_t) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left), input, fill );
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
input += fill;
ilen -= fill;
left = 0;
}
if (!IsTiny() && ilen >= 128 && X86_HAVE(AVX2)) {
sha512_transform_rorx(ctx, input, ilen / 128);
input += ROUNDDOWN(ilen, 128);
ilen -= ROUNDDOWN(ilen, 128);
}
while( ilen >= 128 )
{
if( ( ret = mbedtls_internal_sha512_process( ctx, input ) ) != 0 )
return( ret );
input += 128;
ilen -= 128;
}
if( ilen > 0 )
memcpy( (void *) (ctx->buffer + left), input, ilen );
return( 0 );
}
@ -410,49 +369,39 @@ int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
unsigned char output[64] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned used;
uint64_t high, low;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( (unsigned char *)output != NULL );
/*
* Add padding: 0x80 then 0x00 until 16 bytes remain for the length
*/
used = ctx->total[0] & 0x7F;
ctx->buffer[used++] = 0x80;
if( used <= 112 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 112 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 112 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 128 - used );
mbedtls_platform_zeroize( ctx->buffer + used, 128 - used );
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 112 );
mbedtls_platform_zeroize( ctx->buffer, 112 );
}
/*
* Add message length
*/
high = ( ctx->total[0] >> 61 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
sha512_put_uint64_be( high, ctx->buffer, 112 );
sha512_put_uint64_be( low, ctx->buffer, 120 );
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
/*
* Output final state
*/
@ -462,7 +411,6 @@ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
sha512_put_uint64_be( ctx->state[3], output, 24 );
sha512_put_uint64_be( ctx->state[4], output, 32 );
sha512_put_uint64_be( ctx->state[5], output, 40 );
#if !defined(MBEDTLS_SHA512_NO_SHA384)
if( ctx->is384 == 0 )
#endif
@ -470,7 +418,6 @@ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
sha512_put_uint64_be( ctx->state[6], output, 48 );
sha512_put_uint64_be( ctx->state[7], output, 56 );
}
return( 0 );
}
@ -506,34 +453,60 @@ int mbedtls_sha512_ret( const void *input,
unsigned char output[64],
int is384 )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_sha512_context ctx;
#if !defined(MBEDTLS_SHA512_NO_SHA384)
SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 );
#else
SHA512_VALIDATE_RET( is384 == 0 );
#endif
SHA512_VALIDATE_RET( ilen == 0 || input != NULL );
SHA512_VALIDATE_RET( (unsigned char *)output != NULL );
SHA512_VALIDATE_RET( ilen == 0 || input );
SHA512_VALIDATE_RET( (unsigned char *)output );
mbedtls_sha512_init( &ctx );
if( ( ret = mbedtls_sha512_starts_ret( &ctx, is384 ) ) != 0 )
goto exit;
if( ( ret = mbedtls_sha512_update_ret( &ctx, input, ilen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_sha512_finish_ret( &ctx, output ) ) != 0 )
goto exit;
exit:
MBEDTLS_CHK( mbedtls_sha512_starts_ret( &ctx, is384 ) );
MBEDTLS_CHK( mbedtls_sha512_update_ret( &ctx, input, ilen ) );
MBEDTLS_CHK( mbedtls_sha512_finish_ret( &ctx, output ) );
cleanup:
mbedtls_sha512_free( &ctx );
return( ret );
}
noinstrument int mbedtls_sha512_ret_384( const void *input, size_t ilen, void *output )
{
return mbedtls_sha512_ret( input, ilen, output, true );
}
noinstrument int mbedtls_sha512_ret_512( const void *input, size_t ilen, void *output )
{
return mbedtls_sha512_ret( input, ilen, output, false );
}
#if !defined(MBEDTLS_SHA512_NO_SHA384)
const mbedtls_md_info_t mbedtls_sha384_info = {
"SHA384",
MBEDTLS_MD_SHA384,
48,
128,
(void *)mbedtls_sha512_starts_384,
(void *)mbedtls_sha512_update_ret,
(void *)mbedtls_internal_sha512_process,
(void *)mbedtls_sha512_finish_ret,
mbedtls_sha512_ret_384,
};
#endif
const mbedtls_md_info_t mbedtls_sha512_info = {
"SHA512",
MBEDTLS_MD_SHA512,
64,
128,
(void *)mbedtls_sha512_starts_512,
(void *)mbedtls_sha512_update_ret,
(void *)mbedtls_internal_sha512_process,
(void *)mbedtls_sha512_finish_ret,
mbedtls_sha512_ret_512,
};
#if defined(MBEDTLS_SELF_TEST)
/*
@ -620,18 +593,14 @@ int mbedtls_sha512_self_test( int verbose )
unsigned char *buf;
unsigned char sha512sum[64];
mbedtls_sha512_context ctx;
buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
if( NULL == buf )
{
if( verbose != 0 )
mbedtls_printf( "Buffer allocation failed\n" );
return( 1 );
}
mbedtls_sha512_init( &ctx );
for( i = 0; i < (int) ARRAY_LENGTH(sha512_test_sum); i++ )
{
j = i % 3;
@ -640,17 +609,13 @@ int mbedtls_sha512_self_test( int verbose )
#else
k = 0;
#endif
if( verbose != 0 )
mbedtls_printf( " SHA-%d test #%d: ", 512 - k * 128, j + 1 );
if( ( ret = mbedtls_sha512_starts_ret( &ctx, k ) ) != 0 )
goto fail;
if( j == 2 )
{
memset( buf, 'a', buflen = 1000 );
for( j = 0; j < 1000; j++ )
{
ret = mbedtls_sha512_update_ret( &ctx, buf, buflen );
@ -665,33 +630,25 @@ int mbedtls_sha512_self_test( int verbose )
if( ret != 0 )
goto fail;
}
if( ( ret = mbedtls_sha512_finish_ret( &ctx, sha512sum ) ) != 0 )
goto fail;
if( memcmp( sha512sum, sha512_test_sum[i], 64 - k * 16 ) != 0 )
{
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
goto exit;
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
exit:
mbedtls_sha512_free( &ctx );
mbedtls_free( buf );
return( ret );
}

View file

@ -1,6 +1,7 @@
#ifndef MBEDTLS_SHA512_H_
#define MBEDTLS_SHA512_H_
#include "third_party/mbedtls/config.h"
#include "third_party/mbedtls/platform.h"
COSMOPOLITAN_C_START_
/* clang-format off */
@ -26,8 +27,6 @@ typedef struct mbedtls_sha512_context
}
mbedtls_sha512_context;
void mbedtls_sha512_init( mbedtls_sha512_context * );
void mbedtls_sha512_free( mbedtls_sha512_context * );
void mbedtls_sha512_clone( mbedtls_sha512_context *, const mbedtls_sha512_context * );
int mbedtls_sha512_starts_ret( mbedtls_sha512_context *, int );
int mbedtls_sha512_update_ret( mbedtls_sha512_context *, const unsigned char *, size_t );
@ -36,5 +35,30 @@ int mbedtls_internal_sha512_process( mbedtls_sha512_context *, const unsigned ch
int mbedtls_sha512_ret( const void *, size_t, unsigned char[64], int );
int mbedtls_sha512_self_test( int );
/**
* \brief This function initializes a SHA-512 context.
*
* \param ctx The SHA-512 context to initialize. This must
* not be \c NULL.
*/
static inline void mbedtls_sha512_init( mbedtls_sha512_context *ctx )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) );
}
/**
* \brief This function clears a SHA-512 context.
*
* \param ctx The SHA-512 context to clear. This may be \c NULL,
* in which case this function does nothing. If it
* is not \c NULL, it must point to an initialized
* SHA-512 context.
*/
static inline void mbedtls_sha512_free( mbedtls_sha512_context *ctx )
{
if( !ctx ) return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) );
}
COSMOPOLITAN_C_END_
#endif /* MBEDTLS_SHA512_H_ */

51
third_party/mbedtls/shiftright-avx.c vendored Normal file
View file

@ -0,0 +1,51 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/platform.h"
typedef uint64_t xmm_t __attribute__((__vector_size__(16), __aligned__(1)));
void ShiftRightAvx(uint64_t *p, size_t n, unsigned char k) {
uint64_t p1;
xmm_t cv = {0};
xmm_t i0, i1, i2, i3;
xmm_t o0, o1, o2, o3;
MBEDTLS_ASSERT(!(k & ~63));
p1 = n > 1 ? p[1] : 0;
while (n >= 4) {
n -= 4;
i0 = *(xmm_t *)(p + n + 2);
i1 = *(xmm_t *)(p + n + 0);
o0 = i0 >> k | (xmm_t){i0[1], cv[0]} << (64 - k);
o1 = i1 >> k | (xmm_t){i1[1], i0[0]} << (64 - k);
cv = i1;
*(xmm_t *)(p + n + 2) = o0;
*(xmm_t *)(p + n + 0) = o1;
}
if (n >= 2) {
n -= 2;
i0 = *(xmm_t *)(p + n);
o0 = i0 >> k | (xmm_t){i0[1], cv[0]} << (64 - k);
cv = i0;
*(xmm_t *)(p + n) = o0;
}
if (n) {
p[0] = p[0] >> k | p1 << (64 - k);
}
}

39
third_party/mbedtls/shiftright-pure.c vendored Normal file
View file

@ -0,0 +1,39 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "third_party/mbedtls/bignum_internal.h"
#include "third_party/mbedtls/platform.h"
void ShiftRightPure(mbedtls_mpi_uint *p, size_t n, unsigned char k) {
mbedtls_mpi_uint x, y, *e, *f;
MBEDTLS_ASSERT(!(k & ~63));
f = p;
if (n) {
y = 0;
x = p[0];
e = p + n;
for (; ++p < e; x = y) {
y = p[0];
p[-1] = x >> 1 | y << (64 - 1);
}
p[-1] = x >> 1;
}
while (p < f) {
*p++ = 0;
}
}

28
third_party/mbedtls/shiftright.c vendored Normal file
View file

@ -0,0 +1,28 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/nexgen32e/x86feature.h"
#include "third_party/mbedtls/bignum_internal.h"
void (*ShiftRight)(uint64_t *, size_t, unsigned char);
static textstartup void ShiftRightInit(void) {
ShiftRight = X86_HAVE(AVX) ? ShiftRightAvx : ShiftRightPure;
}
const void *const ShiftRightCtor[] initarray = {ShiftRightInit};

80
third_party/mbedtls/speed.sh vendored Executable file
View file

@ -0,0 +1,80 @@
#!/bin/sh
make -j8 o//third_party/mbedtls || exit
run() {
$1
echo $1
}
(
run o//third_party/mbedtls/test/test_suite_aes.cbc.com
run o//third_party/mbedtls/test/test_suite_aes.cfb.com
run o//third_party/mbedtls/test/test_suite_aes.ecb.com
run o//third_party/mbedtls/test/test_suite_aes.ofb.com
run o//third_party/mbedtls/test/test_suite_aes.rest.com
run o//third_party/mbedtls/test/test_suite_aes.xts.com
run o//third_party/mbedtls/test/test_suite_asn1parse.com
run o//third_party/mbedtls/test/test_suite_asn1write.com
run o//third_party/mbedtls/test/test_suite_base64.com
run o//third_party/mbedtls/test/test_suite_blowfish.com
run o//third_party/mbedtls/test/test_suite_chacha20.com
run o//third_party/mbedtls/test/test_suite_chachapoly.com
run o//third_party/mbedtls/test/test_suite_cipher.aes.com
run o//third_party/mbedtls/test/test_suite_cipher.blowfish.com
run o//third_party/mbedtls/test/test_suite_cipher.ccm.com
run o//third_party/mbedtls/test/test_suite_cipher.chacha20.com
run o//third_party/mbedtls/test/test_suite_cipher.chachapoly.com
run o//third_party/mbedtls/test/test_suite_cipher.des.com
run o//third_party/mbedtls/test/test_suite_cipher.gcm.com
run o//third_party/mbedtls/test/test_suite_cipher.misc.com
run o//third_party/mbedtls/test/test_suite_cipher.nist_kw.com
run o//third_party/mbedtls/test/test_suite_cipher.null.com
run o//third_party/mbedtls/test/test_suite_cipher.padding.com
run o//third_party/mbedtls/test/test_suite_ctr_drbg.com
run o//third_party/mbedtls/test/test_suite_des.com
run o//third_party/mbedtls/test/test_suite_dhm.com
run o//third_party/mbedtls/test/test_suite_ecdh.com
run o//third_party/mbedtls/test/test_suite_ecdsa.com
run o//third_party/mbedtls/test/test_suite_ecjpake.com
run o//third_party/mbedtls/test/test_suite_ecp.com
run o//third_party/mbedtls/test/test_suite_entropy.com
run o//third_party/mbedtls/test/test_suite_error.com
run o//third_party/mbedtls/test/test_suite_gcm.aes128_de.com
run o//third_party/mbedtls/test/test_suite_gcm.aes128_en.com
run o//third_party/mbedtls/test/test_suite_gcm.aes192_de.com
run o//third_party/mbedtls/test/test_suite_gcm.aes192_en.com
run o//third_party/mbedtls/test/test_suite_gcm.aes256_de.com
run o//third_party/mbedtls/test/test_suite_gcm.aes256_en.com
run o//third_party/mbedtls/test/test_suite_gcm.misc.com
run o//third_party/mbedtls/test/test_suite_hkdf.com
run o//third_party/mbedtls/test/test_suite_hmac_drbg.misc.com
run o//third_party/mbedtls/test/test_suite_hmac_drbg.no_reseed.com
run o//third_party/mbedtls/test/test_suite_hmac_drbg.nopr.com
run o//third_party/mbedtls/test/test_suite_hmac_drbg.pr.com
run o//third_party/mbedtls/test/test_suite_md.com
run o//third_party/mbedtls/test/test_suite_mdx.com
run o//third_party/mbedtls/test/test_suite_memory_buffer_alloc.com
run o//third_party/mbedtls/test/test_suite_mpi.com
run o//third_party/mbedtls/test/test_suite_net.com
run o//third_party/mbedtls/test/test_suite_nist_kw.com
run o//third_party/mbedtls/test/test_suite_oid.com
run o//third_party/mbedtls/test/test_suite_pem.com
run o//third_party/mbedtls/test/test_suite_pk.com
run o//third_party/mbedtls/test/test_suite_pkcs1_v15.com
run o//third_party/mbedtls/test/test_suite_pkcs1_v21.com
run o//third_party/mbedtls/test/test_suite_pkcs5.com
run o//third_party/mbedtls/test/test_suite_pkparse.com
run o//third_party/mbedtls/test/test_suite_pkwrite.com
run o//third_party/mbedtls/test/test_suite_poly1305.com
run o//third_party/mbedtls/test/test_suite_random.com
run o//third_party/mbedtls/test/test_suite_rsa.com
run o//third_party/mbedtls/test/test_suite_shax.com
run o//third_party/mbedtls/test/test_suite_ssl.com
run o//third_party/mbedtls/test/test_suite_timing.com
run o//third_party/mbedtls/test/test_suite_version.com
run o//third_party/mbedtls/test/test_suite_x509parse.com
run o//third_party/mbedtls/test/test_suite_x509write.com
) | o//tool/build/deltaify.com | sort -n | tee speed.txt
mkdir -p ~/speed/mbedtls
cp speed.txt ~/speed/mbedtls/$(date +%Y-%m-%d-%H-%H).txt

View file

@ -167,8 +167,9 @@ COSMOPOLITAN_C_START_
#define MBEDTLS_SSL_ARC4_ENABLED 0
#define MBEDTLS_SSL_ARC4_DISABLED 1
#define MBEDTLS_SSL_PRESET_DEFAULT 0
#define MBEDTLS_SSL_PRESET_DEFAULT MBEDTLS_SSL_PRESET_SUITEC
#define MBEDTLS_SSL_PRESET_SUITEB 2
#define MBEDTLS_SSL_PRESET_SUITEC 0
#define MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED 1
#define MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED 0
@ -1546,5 +1547,7 @@ forceinline int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
}
}
const char *GetSslStateName(mbedtls_ssl_states );
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SSL_H_ */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "libc/log/log.h"
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/platform.h"
@ -38,7 +55,7 @@ asm(".include \"libc/disclaimer.inc\"");
void mbedtls_ssl_cache_init( mbedtls_ssl_cache_context *cache )
{
memset( cache, 0, sizeof( mbedtls_ssl_cache_context ) );
mbedtls_platform_zeroize( cache, sizeof( mbedtls_ssl_cache_context ) );
cache->timeout = MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT;
cache->max_entries = MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES;
}
@ -228,7 +245,7 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
if( cur->peer_cert.p != NULL )
{
mbedtls_free( cur->peer_cert.p );
memset( &cur->peer_cert, 0, sizeof(mbedtls_x509_buf) );
mbedtls_platform_zeroize( &cur->peer_cert, sizeof(mbedtls_x509_buf) );
}
#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */

File diff suppressed because it is too large Load diff

View file

@ -283,9 +283,9 @@ typedef struct mbedtls_ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t;
/**
* \brief This structure is used for storing ciphersuite information
*/
struct mbedtls_ssl_ciphersuite_t
struct thatispacked mbedtls_ssl_ciphersuite_t
{
int id;
uint16_t id;
const char * name;
unsigned char cipher; /* mbedtls_cipher_type_t */
unsigned char mac; /* mbedtls_md_type_t */
@ -445,5 +445,7 @@ static inline int mbedtls_ssl_ciphersuite_uses_server_signature( const mbedtls_s
}
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
const mbedtls_ssl_ciphersuite_t *GetCipherSuite(const char *);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SSL_CIPHERSUITES_H_ */

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/debug.h"
#include "third_party/mbedtls/error.h"
@ -372,7 +389,7 @@ static int ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
const unsigned char *end,
size_t *olen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *p = buf;
size_t kkpp_len;
@ -767,7 +784,7 @@ static int ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl,
"illegal DTLS-SRTP protection profile %d",
ssl->conf->dtls_srtp_profile_list[protection_profiles_index]
) );
return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED );
return( MBEDTLS_ERR_THIS_CORRUPTION );
}
}
@ -803,7 +820,7 @@ static int ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl,
*/
static int ssl_generate_random( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *p = ssl->handshake->randbytes;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t;
@ -897,7 +914,7 @@ static int ssl_validate_ciphersuite(
static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t i, n, olen, ext_len = 0;
unsigned char *buf;
@ -1629,7 +1646,7 @@ static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
if( ssl->handshake->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE )
@ -2653,7 +2670,7 @@ static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
size_t offset, size_t *olen,
size_t pms_offset )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
unsigned char *p = ssl->handshake->premaster + pms_offset;
mbedtls_pk_context * peer_pk;
@ -2789,7 +2806,7 @@ static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const mbedtls_ecp_keypair *peer_key;
mbedtls_pk_context * peer_pk;
#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
@ -2833,7 +2850,7 @@ static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
@ -3199,7 +3216,7 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char *buf;
size_t n = 0;
size_t cert_type_len = 0, dn_len = 0;
@ -3352,7 +3369,7 @@ exit:
static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
{
@ -3383,7 +3400,7 @@ static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
size_t header_len;
size_t content_len;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
@ -3655,7 +3672,7 @@ static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
@ -3829,7 +3846,7 @@ sign:
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
uint32_t lifetime;
size_t ticket_len;
unsigned char *ticket;

View file

@ -1,3 +1,20 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright The Mbed TLS Contributors
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.
*/
#include "third_party/mbedtls/common.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/platform.h"
@ -87,7 +104,7 @@ int mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
unsigned char key[COOKIE_MD_OUTLEN];
if( ( ret = f_rng( p_rng, key, sizeof( key ) ) ) != 0 )
@ -139,7 +156,7 @@ int mbedtls_ssl_cookie_write( void *p_ctx,
unsigned char **p, unsigned char *end,
const unsigned char *cli_id, size_t cli_id_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_THIS_CORRUPTION;
mbedtls_ssl_cookie_ctx *ctx = (mbedtls_ssl_cookie_ctx *) p_ctx;
unsigned long t;

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