1
0
mirror of https://github.com/Mbed-TLS/mbedtls.git synced 2025-07-30 22:43:08 +03:00

Switch to the new code style

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine
2023-01-11 14:50:10 +01:00
parent fd13a0f851
commit 449bd8303e
442 changed files with 86735 additions and 89438 deletions

File diff suppressed because it is too large Load Diff

View File

@ -28,7 +28,8 @@
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
#warning "MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code."
#warning \
"MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code."
#endif
#endif
@ -47,22 +48,21 @@
/*
* AES-NI support detection routine
*/
int mbedtls_aesni_has_support( unsigned int what )
int mbedtls_aesni_has_support(unsigned int what)
{
static int done = 0;
static unsigned int c = 0;
if( ! done )
{
asm( "movl $1, %%eax \n\t"
if (!done) {
asm ("movl $1, %%eax \n\t"
"cpuid \n\t"
: "=c" (c)
:
: "eax", "ebx", "edx" );
: "eax", "ebx", "edx");
done = 1;
}
return( ( c & what ) != 0 );
return (c & what) != 0;
}
/*
@ -94,12 +94,12 @@ int mbedtls_aesni_has_support( unsigned int what )
/*
* AES-NI AES-ECB block en(de)cryption
*/
int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] )
int mbedtls_aesni_crypt_ecb(mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16])
{
asm( "movdqu (%3), %%xmm0 \n\t" // load input
asm ("movdqu (%3), %%xmm0 \n\t" // load input
"movdqu (%1), %%xmm1 \n\t" // load round key 0
"pxor %%xmm1, %%xmm0 \n\t" // round 0
"add $16, %1 \n\t" // point to next round key
@ -110,51 +110,50 @@ 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
"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
"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
"jmp 3f \n\t"
"jmp 3f \n\t"
"2: \n\t" // decryption loop
"movdqu (%1), %%xmm1 \n\t"
"2: \n\t" // decryption loop
"movdqu (%1), %%xmm1 \n\t"
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
"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
"3: \n\t"
"movdqu %%xmm0, (%4) \n\t" // export output
"3: \n\t"
"movdqu %%xmm0, (%4) \n\t" // export output
:
: "r" (ctx->nr), "r" (ctx->buf + ctx->rk_offset), "r" (mode), "r" (input), "r" (output)
: "memory", "cc", "xmm0", "xmm1" );
: "memory", "cc", "xmm0", "xmm1");
return( 0 );
return 0;
}
/*
* GCM multiplication: c = a times b in GF(2^128)
* Based on [CLMUL-WP] algorithms 1 (with equation 27) and 5.
*/
void mbedtls_aesni_gcm_mult( unsigned char c[16],
const unsigned char a[16],
const unsigned char b[16] )
void mbedtls_aesni_gcm_mult(unsigned char c[16],
const unsigned char a[16],
const unsigned char b[16])
{
unsigned char aa[16], bb[16], cc[16];
size_t i;
/* The inputs are in big-endian order, so byte-reverse them */
for( i = 0; i < 16; i++ )
{
for (i = 0; i < 16; i++) {
aa[i] = a[15 - i];
bb[i] = b[15 - i];
}
asm( "movdqu (%0), %%xmm0 \n\t" // a1:a0
asm ("movdqu (%0), %%xmm0 \n\t" // a1:a0
"movdqu (%1), %%xmm1 \n\t" // b1:b0
/*
@ -168,30 +167,30 @@ void mbedtls_aesni_gcm_mult( unsigned char c[16],
PCLMULQDQ xmm0_xmm2 ",0x11 \n\t" // a1*b1 = d1:d0
PCLMULQDQ xmm0_xmm3 ",0x10 \n\t" // a0*b1 = e1:e0
PCLMULQDQ xmm0_xmm4 ",0x01 \n\t" // a1*b0 = f1:f0
"pxor %%xmm3, %%xmm4 \n\t" // e1+f1:e0+f0
"movdqa %%xmm4, %%xmm3 \n\t" // same
"psrldq $8, %%xmm4 \n\t" // 0:e1+f1
"pslldq $8, %%xmm3 \n\t" // e0+f0:0
"pxor %%xmm4, %%xmm2 \n\t" // d1:d0+e1+f1
"pxor %%xmm3, %%xmm1 \n\t" // c1+e0+f1:c0
"pxor %%xmm3, %%xmm4 \n\t" // e1+f1:e0+f0
"movdqa %%xmm4, %%xmm3 \n\t" // same
"psrldq $8, %%xmm4 \n\t" // 0:e1+f1
"pslldq $8, %%xmm3 \n\t" // e0+f0:0
"pxor %%xmm4, %%xmm2 \n\t" // d1:d0+e1+f1
"pxor %%xmm3, %%xmm1 \n\t" // c1+e0+f1:c0
/*
* Now shift the result one bit to the left,
* taking advantage of [CLMUL-WP] eq 27 (p. 20)
*/
"movdqa %%xmm1, %%xmm3 \n\t" // r1:r0
"movdqa %%xmm2, %%xmm4 \n\t" // r3:r2
"psllq $1, %%xmm1 \n\t" // r1<<1:r0<<1
"psllq $1, %%xmm2 \n\t" // r3<<1:r2<<1
"psrlq $63, %%xmm3 \n\t" // r1>>63:r0>>63
"psrlq $63, %%xmm4 \n\t" // r3>>63:r2>>63
"movdqa %%xmm3, %%xmm5 \n\t" // r1>>63:r0>>63
"pslldq $8, %%xmm3 \n\t" // r0>>63:0
"pslldq $8, %%xmm4 \n\t" // r2>>63:0
"psrldq $8, %%xmm5 \n\t" // 0:r1>>63
"por %%xmm3, %%xmm1 \n\t" // r1<<1|r0>>63:r0<<1
"por %%xmm4, %%xmm2 \n\t" // r3<<1|r2>>62:r2<<1
"por %%xmm5, %%xmm2 \n\t" // r3<<1|r2>>62:r2<<1|r1>>63
"movdqa %%xmm1, %%xmm3 \n\t" // r1:r0
"movdqa %%xmm2, %%xmm4 \n\t" // r3:r2
"psllq $1, %%xmm1 \n\t" // r1<<1:r0<<1
"psllq $1, %%xmm2 \n\t" // r3<<1:r2<<1
"psrlq $63, %%xmm3 \n\t" // r1>>63:r0>>63
"psrlq $63, %%xmm4 \n\t" // r3>>63:r2>>63
"movdqa %%xmm3, %%xmm5 \n\t" // r1>>63:r0>>63
"pslldq $8, %%xmm3 \n\t" // r0>>63:0
"pslldq $8, %%xmm4 \n\t" // r2>>63:0
"psrldq $8, %%xmm5 \n\t" // 0:r1>>63
"por %%xmm3, %%xmm1 \n\t" // r1<<1|r0>>63:r0<<1
"por %%xmm4, %%xmm2 \n\t" // r3<<1|r2>>62:r2<<1
"por %%xmm5, %%xmm2 \n\t" // r3<<1|r2>>62:r2<<1|r1>>63
/*
* Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1
@ -199,51 +198,52 @@ void mbedtls_aesni_gcm_mult( unsigned char c[16],
* Currently xmm2:xmm1 holds x3:x2:x1:x0 (already shifted).
*/
/* Step 2 (1) */
"movdqa %%xmm1, %%xmm3 \n\t" // x1:x0
"movdqa %%xmm1, %%xmm4 \n\t" // same
"movdqa %%xmm1, %%xmm5 \n\t" // same
"psllq $63, %%xmm3 \n\t" // x1<<63:x0<<63 = stuff:a
"psllq $62, %%xmm4 \n\t" // x1<<62:x0<<62 = stuff:b
"psllq $57, %%xmm5 \n\t" // x1<<57:x0<<57 = stuff:c
"movdqa %%xmm1, %%xmm3 \n\t" // x1:x0
"movdqa %%xmm1, %%xmm4 \n\t" // same
"movdqa %%xmm1, %%xmm5 \n\t" // same
"psllq $63, %%xmm3 \n\t" // x1<<63:x0<<63 = stuff:a
"psllq $62, %%xmm4 \n\t" // x1<<62:x0<<62 = stuff:b
"psllq $57, %%xmm5 \n\t" // x1<<57:x0<<57 = stuff:c
/* Step 2 (2) */
"pxor %%xmm4, %%xmm3 \n\t" // stuff:a+b
"pxor %%xmm5, %%xmm3 \n\t" // stuff:a+b+c
"pslldq $8, %%xmm3 \n\t" // a+b+c:0
"pxor %%xmm3, %%xmm1 \n\t" // x1+a+b+c:x0 = d:x0
"pxor %%xmm4, %%xmm3 \n\t" // stuff:a+b
"pxor %%xmm5, %%xmm3 \n\t" // stuff:a+b+c
"pslldq $8, %%xmm3 \n\t" // a+b+c:0
"pxor %%xmm3, %%xmm1 \n\t" // x1+a+b+c:x0 = d:x0
/* Steps 3 and 4 */
"movdqa %%xmm1,%%xmm0 \n\t" // d:x0
"movdqa %%xmm1,%%xmm4 \n\t" // same
"movdqa %%xmm1,%%xmm5 \n\t" // same
"psrlq $1, %%xmm0 \n\t" // e1:x0>>1 = e1:e0'
"psrlq $2, %%xmm4 \n\t" // f1:x0>>2 = f1:f0'
"psrlq $7, %%xmm5 \n\t" // g1:x0>>7 = g1:g0'
"pxor %%xmm4, %%xmm0 \n\t" // e1+f1:e0'+f0'
"pxor %%xmm5, %%xmm0 \n\t" // e1+f1+g1:e0'+f0'+g0'
"movdqa %%xmm1,%%xmm0 \n\t" // d:x0
"movdqa %%xmm1,%%xmm4 \n\t" // same
"movdqa %%xmm1,%%xmm5 \n\t" // same
"psrlq $1, %%xmm0 \n\t" // e1:x0>>1 = e1:e0'
"psrlq $2, %%xmm4 \n\t" // f1:x0>>2 = f1:f0'
"psrlq $7, %%xmm5 \n\t" // g1:x0>>7 = g1:g0'
"pxor %%xmm4, %%xmm0 \n\t" // e1+f1:e0'+f0'
"pxor %%xmm5, %%xmm0 \n\t" // e1+f1+g1:e0'+f0'+g0'
// e0'+f0'+g0' is almost e0+f0+g0, ex\tcept for some missing
// bits carried from d. Now get those\t bits back in.
"movdqa %%xmm1,%%xmm3 \n\t" // d:x0
"movdqa %%xmm1,%%xmm4 \n\t" // same
"movdqa %%xmm1,%%xmm5 \n\t" // same
"psllq $63, %%xmm3 \n\t" // d<<63:stuff
"psllq $62, %%xmm4 \n\t" // d<<62:stuff
"psllq $57, %%xmm5 \n\t" // d<<57:stuff
"pxor %%xmm4, %%xmm3 \n\t" // d<<63+d<<62:stuff
"pxor %%xmm5, %%xmm3 \n\t" // missing bits of d:stuff
"psrldq $8, %%xmm3 \n\t" // 0:missing bits of d
"pxor %%xmm3, %%xmm0 \n\t" // e1+f1+g1:e0+f0+g0
"pxor %%xmm1, %%xmm0 \n\t" // h1:h0
"pxor %%xmm2, %%xmm0 \n\t" // x3+h1:x2+h0
"movdqa %%xmm1,%%xmm3 \n\t" // d:x0
"movdqa %%xmm1,%%xmm4 \n\t" // same
"movdqa %%xmm1,%%xmm5 \n\t" // same
"psllq $63, %%xmm3 \n\t" // d<<63:stuff
"psllq $62, %%xmm4 \n\t" // d<<62:stuff
"psllq $57, %%xmm5 \n\t" // d<<57:stuff
"pxor %%xmm4, %%xmm3 \n\t" // d<<63+d<<62:stuff
"pxor %%xmm5, %%xmm3 \n\t" // missing bits of d:stuff
"psrldq $8, %%xmm3 \n\t" // 0:missing bits of d
"pxor %%xmm3, %%xmm0 \n\t" // e1+f1+g1:e0+f0+g0
"pxor %%xmm1, %%xmm0 \n\t" // h1:h0
"pxor %%xmm2, %%xmm0 \n\t" // x3+h1:x2+h0
"movdqu %%xmm0, (%2) \n\t" // done
"movdqu %%xmm0, (%2) \n\t" // done
:
: "r" (aa), "r" (bb), "r" (cc)
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5" );
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
/* Now byte-reverse the outputs */
for( i = 0; i < 16; i++ )
for (i = 0; i < 16; i++) {
c[i] = cc[15 - i];
}
return;
}
@ -251,32 +251,33 @@ void mbedtls_aesni_gcm_mult( unsigned char c[16],
/*
* Compute decryption round keys from encryption round keys
*/
void mbedtls_aesni_inverse_key( unsigned char *invkey,
const unsigned char *fwdkey, int nr )
void mbedtls_aesni_inverse_key(unsigned char *invkey,
const unsigned char *fwdkey, int nr)
{
unsigned char *ik = invkey;
const unsigned char *fk = fwdkey + 16 * nr;
memcpy( ik, fk, 16 );
memcpy(ik, fk, 16);
for( fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16 )
asm( "movdqu (%0), %%xmm0 \n\t"
for (fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16) {
asm ("movdqu (%0), %%xmm0 \n\t"
AESIMC xmm0_xmm0 "\n\t"
"movdqu %%xmm0, (%1) \n\t"
"movdqu %%xmm0, (%1) \n\t"
:
: "r" (fk), "r" (ik)
: "memory", "xmm0" );
: "memory", "xmm0");
}
memcpy( ik, fk, 16 );
memcpy(ik, fk, 16);
}
/*
* Key expansion, 128-bit case
*/
static void aesni_setkey_enc_128( unsigned char *rk,
const unsigned char *key )
static void aesni_setkey_enc_128(unsigned char *rk,
const unsigned char *key)
{
asm( "movdqu (%1), %%xmm0 \n\t" // copy the original key
asm ("movdqu (%1), %%xmm0 \n\t" // copy the original key
"movdqu %%xmm0, (%0) \n\t" // as round key 0
"jmp 2f \n\t" // skip auxiliary routine
@ -317,16 +318,16 @@ static void aesni_setkey_enc_128( unsigned char *rk,
AESKEYGENA xmm0_xmm1 ",0x36 \n\tcall 1b \n\t"
:
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
: "memory", "cc", "0");
}
/*
* Key expansion, 192-bit case
*/
static void aesni_setkey_enc_192( unsigned char *rk,
const unsigned char *key )
static void aesni_setkey_enc_192(unsigned char *rk,
const unsigned char *key)
{
asm( "movdqu (%1), %%xmm0 \n\t" // copy original round key
asm ("movdqu (%1), %%xmm0 \n\t" // copy original round key
"movdqu %%xmm0, (%0) \n\t"
"add $16, %0 \n\t"
"movq 16(%1), %%xmm1 \n\t"
@ -374,16 +375,16 @@ static void aesni_setkey_enc_192( unsigned char *rk,
:
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
: "memory", "cc", "0");
}
/*
* Key expansion, 256-bit case
*/
static void aesni_setkey_enc_256( unsigned char *rk,
const unsigned char *key )
static void aesni_setkey_enc_256(unsigned char *rk,
const unsigned char *key)
{
asm( "movdqu (%1), %%xmm0 \n\t"
asm ("movdqu (%1), %%xmm0 \n\t"
"movdqu %%xmm0, (%0) \n\t"
"add $16, %0 \n\t"
"movdqu 16(%1), %%xmm1 \n\t"
@ -414,23 +415,23 @@ static void aesni_setkey_enc_256( unsigned char *rk,
/* Set xmm2 to stuff:Y:stuff:stuff with Y = subword( r11 )
* and proceed to generate next round key from there */
AESKEYGENA xmm0_xmm2 ",0x00 \n\t"
"pshufd $0xaa, %%xmm2, %%xmm2 \n\t"
"pxor %%xmm1, %%xmm2 \n\t"
"pslldq $4, %%xmm1 \n\t"
"pxor %%xmm1, %%xmm2 \n\t"
"pslldq $4, %%xmm1 \n\t"
"pxor %%xmm1, %%xmm2 \n\t"
"pslldq $4, %%xmm1 \n\t"
"pxor %%xmm2, %%xmm1 \n\t"
"add $16, %0 \n\t"
"movdqu %%xmm1, (%0) \n\t"
"ret \n\t"
"pshufd $0xaa, %%xmm2, %%xmm2 \n\t"
"pxor %%xmm1, %%xmm2 \n\t"
"pslldq $4, %%xmm1 \n\t"
"pxor %%xmm1, %%xmm2 \n\t"
"pslldq $4, %%xmm1 \n\t"
"pxor %%xmm1, %%xmm2 \n\t"
"pslldq $4, %%xmm1 \n\t"
"pxor %%xmm2, %%xmm1 \n\t"
"add $16, %0 \n\t"
"movdqu %%xmm1, (%0) \n\t"
"ret \n\t"
/*
* Main "loop" - Generating one more key than necessary,
* see definition of mbedtls_aes_context.buf
*/
"2: \n\t"
"2: \n\t"
AESKEYGENA xmm1_xmm2 ",0x01 \n\tcall 1b \n\t"
AESKEYGENA xmm1_xmm2 ",0x02 \n\tcall 1b \n\t"
AESKEYGENA xmm1_xmm2 ",0x04 \n\tcall 1b \n\t"
@ -440,25 +441,24 @@ static void aesni_setkey_enc_256( unsigned char *rk,
AESKEYGENA xmm1_xmm2 ",0x40 \n\tcall 1b \n\t"
:
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
: "memory", "cc", "0");
}
/*
* Key expansion, wrapper
*/
int mbedtls_aesni_setkey_enc( unsigned char *rk,
const unsigned char *key,
size_t bits )
int mbedtls_aesni_setkey_enc(unsigned char *rk,
const unsigned char *key,
size_t bits)
{
switch( bits )
{
case 128: aesni_setkey_enc_128( rk, key ); break;
case 192: aesni_setkey_enc_192( rk, key ); break;
case 256: aesni_setkey_enc_256( rk, key ); break;
default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );
switch (bits) {
case 128: aesni_setkey_enc_128(rk, key); break;
case 192: aesni_setkey_enc_192(rk, key); break;
case 256: aesni_setkey_enc_256(rk, key); break;
default: return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_HAVE_X86_64 */

View File

@ -33,8 +33,8 @@
#define MBEDTLS_AESNI_CLMUL 0x00000002u
#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) && \
( defined(__amd64__) || defined(__x86_64__) ) && \
! defined(MBEDTLS_HAVE_X86_64)
(defined(__amd64__) || defined(__x86_64__)) && \
!defined(MBEDTLS_HAVE_X86_64)
#define MBEDTLS_HAVE_X86_64
#endif
@ -55,7 +55,7 @@ extern "C" {
*
* \return 1 if CPU has support for the feature, 0 otherwise
*/
int mbedtls_aesni_has_support( unsigned int what );
int mbedtls_aesni_has_support(unsigned int what);
/**
* \brief Internal AES-NI AES-ECB block encryption and decryption
@ -70,10 +70,10 @@ int mbedtls_aesni_has_support( unsigned int what );
*
* \return 0 on success (cannot fail)
*/
int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] );
int mbedtls_aesni_crypt_ecb(mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16]);
/**
* \brief Internal GCM multiplication: c = a * b in GF(2^128)
@ -88,9 +88,9 @@ int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,
* \note Both operands and result are bit strings interpreted as
* elements of GF(2^128) as per the GCM spec.
*/
void mbedtls_aesni_gcm_mult( unsigned char c[16],
const unsigned char a[16],
const unsigned char b[16] );
void mbedtls_aesni_gcm_mult(unsigned char c[16],
const unsigned char a[16],
const unsigned char b[16]);
/**
* \brief Internal round key inversion. This function computes
@ -103,9 +103,9 @@ void mbedtls_aesni_gcm_mult( unsigned char c[16],
* \param fwdkey Original round keys (for encryption)
* \param nr Number of rounds (that is, number of round keys minus one)
*/
void mbedtls_aesni_inverse_key( unsigned char *invkey,
const unsigned char *fwdkey,
int nr );
void mbedtls_aesni_inverse_key(unsigned char *invkey,
const unsigned char *fwdkey,
int nr);
/**
* \brief Internal key expansion for encryption
@ -119,9 +119,9 @@ void mbedtls_aesni_inverse_key( unsigned char *invkey,
*
* \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
*/
int mbedtls_aesni_setkey_enc( unsigned char *rk,
const unsigned char *key,
size_t bits );
int mbedtls_aesni_setkey_enc(unsigned char *rk,
const unsigned char *key,
size_t bits);
#ifdef __cplusplus
}

View File

@ -36,10 +36,10 @@
* \param p pointer to 2 bytes of data
* \return Data at the given address
*/
inline uint16_t mbedtls_get_unaligned_uint16( const void *p )
inline uint16_t mbedtls_get_unaligned_uint16(const void *p)
{
uint16_t r;
memcpy( &r, p, sizeof( r ) );
memcpy(&r, p, sizeof(r));
return r;
}
@ -50,9 +50,9 @@ inline uint16_t mbedtls_get_unaligned_uint16( const void *p )
* \param p pointer to 2 bytes of data
* \param x data to write
*/
inline void mbedtls_put_unaligned_uint16( void *p, uint16_t x )
inline void mbedtls_put_unaligned_uint16(void *p, uint16_t x)
{
memcpy( p, &x, sizeof( x ) );
memcpy(p, &x, sizeof(x));
}
/**
@ -62,10 +62,10 @@ inline void mbedtls_put_unaligned_uint16( void *p, uint16_t x )
* \param p pointer to 4 bytes of data
* \return Data at the given address
*/
inline uint32_t mbedtls_get_unaligned_uint32( const void *p )
inline uint32_t mbedtls_get_unaligned_uint32(const void *p)
{
uint32_t r;
memcpy( &r, p, sizeof( r ) );
memcpy(&r, p, sizeof(r));
return r;
}
@ -76,9 +76,9 @@ inline uint32_t mbedtls_get_unaligned_uint32( const void *p )
* \param p pointer to 4 bytes of data
* \param x data to write
*/
inline void mbedtls_put_unaligned_uint32( void *p, uint32_t x )
inline void mbedtls_put_unaligned_uint32(void *p, uint32_t x)
{
memcpy( p, &x, sizeof( x ) );
memcpy(p, &x, sizeof(x));
}
/**
@ -88,10 +88,10 @@ inline void mbedtls_put_unaligned_uint32( void *p, uint32_t x )
* \param p pointer to 8 bytes of data
* \return Data at the given address
*/
inline uint64_t mbedtls_get_unaligned_uint64( const void *p )
inline uint64_t mbedtls_get_unaligned_uint64(const void *p)
{
uint64_t r;
memcpy( &r, p, sizeof( r ) );
memcpy(&r, p, sizeof(r));
return r;
}
@ -102,9 +102,9 @@ inline uint64_t mbedtls_get_unaligned_uint64( const void *p )
* \param p pointer to 8 bytes of data
* \param x data to write
*/
inline void mbedtls_put_unaligned_uint64( void *p, uint64_t x )
inline void mbedtls_put_unaligned_uint64(void *p, uint64_t x)
{
memcpy( p, &x, sizeof( x ) );
memcpy(p, &x, sizeof(x));
}
/** Byte Reading Macros
@ -112,23 +112,23 @@ inline void mbedtls_put_unaligned_uint64( void *p, uint64_t x )
* Given a multi-byte integer \p x, MBEDTLS_BYTE_n retrieves the n-th
* byte from x, where byte 0 is the least significant byte.
*/
#define MBEDTLS_BYTE_0( x ) ( (uint8_t) ( ( x ) & 0xff ) )
#define MBEDTLS_BYTE_1( x ) ( (uint8_t) ( ( ( x ) >> 8 ) & 0xff ) )
#define MBEDTLS_BYTE_2( x ) ( (uint8_t) ( ( ( x ) >> 16 ) & 0xff ) )
#define MBEDTLS_BYTE_3( x ) ( (uint8_t) ( ( ( x ) >> 24 ) & 0xff ) )
#define MBEDTLS_BYTE_4( x ) ( (uint8_t) ( ( ( x ) >> 32 ) & 0xff ) )
#define MBEDTLS_BYTE_5( x ) ( (uint8_t) ( ( ( x ) >> 40 ) & 0xff ) )
#define MBEDTLS_BYTE_6( x ) ( (uint8_t) ( ( ( x ) >> 48 ) & 0xff ) )
#define MBEDTLS_BYTE_7( x ) ( (uint8_t) ( ( ( x ) >> 56 ) & 0xff ) )
#define MBEDTLS_BYTE_0(x) ((uint8_t) ((x) & 0xff))
#define MBEDTLS_BYTE_1(x) ((uint8_t) (((x) >> 8) & 0xff))
#define MBEDTLS_BYTE_2(x) ((uint8_t) (((x) >> 16) & 0xff))
#define MBEDTLS_BYTE_3(x) ((uint8_t) (((x) >> 24) & 0xff))
#define MBEDTLS_BYTE_4(x) ((uint8_t) (((x) >> 32) & 0xff))
#define MBEDTLS_BYTE_5(x) ((uint8_t) (((x) >> 40) & 0xff))
#define MBEDTLS_BYTE_6(x) ((uint8_t) (((x) >> 48) & 0xff))
#define MBEDTLS_BYTE_7(x) ((uint8_t) (((x) >> 56) & 0xff))
/*
* Detect GCC built-in byteswap routines
*/
#if defined(__GNUC__) && defined(__GNUC_PREREQ)
#if __GNUC_PREREQ(4,8)
#if __GNUC_PREREQ(4, 8)
#define MBEDTLS_BSWAP16 __builtin_bswap16
#endif /* __GNUC_PREREQ(4,8) */
#if __GNUC_PREREQ(4,3)
#if __GNUC_PREREQ(4, 3)
#define MBEDTLS_BSWAP32 __builtin_bswap32
#define MBEDTLS_BSWAP64 __builtin_bswap64
#endif /* __GNUC_PREREQ(4,3) */
@ -169,36 +169,39 @@ inline void mbedtls_put_unaligned_uint64( void *p, uint64_t x )
* similar instruction.
*/
#if !defined(MBEDTLS_BSWAP16)
static inline uint16_t mbedtls_bswap16( uint16_t x ) {
static inline uint16_t mbedtls_bswap16(uint16_t x)
{
return
( x & 0x00ff ) << 8 |
( x & 0xff00 ) >> 8;
(x & 0x00ff) << 8 |
(x & 0xff00) >> 8;
}
#define MBEDTLS_BSWAP16 mbedtls_bswap16
#endif /* !defined(MBEDTLS_BSWAP16) */
#if !defined(MBEDTLS_BSWAP32)
static inline uint32_t mbedtls_bswap32( uint32_t x ) {
static inline uint32_t mbedtls_bswap32(uint32_t x)
{
return
( x & 0x000000ff ) << 24 |
( x & 0x0000ff00 ) << 8 |
( x & 0x00ff0000 ) >> 8 |
( x & 0xff000000 ) >> 24;
(x & 0x000000ff) << 24 |
(x & 0x0000ff00) << 8 |
(x & 0x00ff0000) >> 8 |
(x & 0xff000000) >> 24;
}
#define MBEDTLS_BSWAP32 mbedtls_bswap32
#endif /* !defined(MBEDTLS_BSWAP32) */
#if !defined(MBEDTLS_BSWAP64)
static inline uint64_t mbedtls_bswap64( uint64_t x ) {
static inline uint64_t mbedtls_bswap64(uint64_t x)
{
return
( x & 0x00000000000000ff ) << 56 |
( x & 0x000000000000ff00 ) << 40 |
( x & 0x0000000000ff0000 ) << 24 |
( x & 0x00000000ff000000 ) << 8 |
( x & 0x000000ff00000000 ) >> 8 |
( x & 0x0000ff0000000000 ) >> 24 |
( x & 0x00ff000000000000 ) >> 40 |
( x & 0xff00000000000000 ) >> 56;
(x & 0x00000000000000ff) << 56 |
(x & 0x000000000000ff00) << 40 |
(x & 0x0000000000ff0000) << 24 |
(x & 0x00000000ff000000) << 8 |
(x & 0x000000ff00000000) >> 8 |
(x & 0x0000ff0000000000) >> 24 |
(x & 0x00ff000000000000) >> 40 |
(x & 0xff00000000000000) >> 56;
}
#define MBEDTLS_BSWAP64 mbedtls_bswap64
#endif /* !defined(MBEDTLS_BSWAP64) */
@ -219,8 +222,8 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the four bytes to build the 32 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT32_BE( data, offset ) \
( ( MBEDTLS_IS_BIG_ENDIAN ) \
#define MBEDTLS_GET_UINT32_BE(data, offset) \
((MBEDTLS_IS_BIG_ENDIAN) \
? mbedtls_get_unaligned_uint32((data) + (offset)) \
: MBEDTLS_BSWAP32(mbedtls_get_unaligned_uint32((data) + (offset))) \
)
@ -234,17 +237,17 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the most significant
* byte of the 32 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT32_BE( n, data, offset ) \
{ \
if ( MBEDTLS_IS_BIG_ENDIAN ) \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), (uint32_t)(n)); \
} \
else \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), MBEDTLS_BSWAP32((uint32_t)(n))); \
} \
}
#define MBEDTLS_PUT_UINT32_BE(n, data, offset) \
{ \
if (MBEDTLS_IS_BIG_ENDIAN) \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), (uint32_t) (n)); \
} \
else \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), MBEDTLS_BSWAP32((uint32_t) (n))); \
} \
}
/**
* Get the unsigned 32 bits integer corresponding to four bytes in
@ -255,8 +258,8 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the four bytes to build the 32 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT32_LE( data, offset ) \
( ( MBEDTLS_IS_BIG_ENDIAN ) \
#define MBEDTLS_GET_UINT32_LE(data, offset) \
((MBEDTLS_IS_BIG_ENDIAN) \
? MBEDTLS_BSWAP32(mbedtls_get_unaligned_uint32((data) + (offset))) \
: mbedtls_get_unaligned_uint32((data) + (offset)) \
)
@ -271,17 +274,17 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the least significant
* byte of the 32 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT32_LE( n, data, offset ) \
{ \
if ( MBEDTLS_IS_BIG_ENDIAN ) \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), MBEDTLS_BSWAP32((uint32_t)(n))); \
} \
else \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), ((uint32_t)(n))); \
} \
}
#define MBEDTLS_PUT_UINT32_LE(n, data, offset) \
{ \
if (MBEDTLS_IS_BIG_ENDIAN) \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), MBEDTLS_BSWAP32((uint32_t) (n))); \
} \
else \
{ \
mbedtls_put_unaligned_uint32((data) + (offset), ((uint32_t) (n))); \
} \
}
/**
* Get the unsigned 16 bits integer corresponding to two bytes in
@ -292,8 +295,8 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the two bytes to build the 16 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT16_LE( data, offset ) \
( ( MBEDTLS_IS_BIG_ENDIAN ) \
#define MBEDTLS_GET_UINT16_LE(data, offset) \
((MBEDTLS_IS_BIG_ENDIAN) \
? MBEDTLS_BSWAP16(mbedtls_get_unaligned_uint16((data) + (offset))) \
: mbedtls_get_unaligned_uint16((data) + (offset)) \
)
@ -307,17 +310,17 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the least significant
* byte of the 16 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT16_LE( n, data, offset ) \
{ \
if ( MBEDTLS_IS_BIG_ENDIAN ) \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), MBEDTLS_BSWAP16((uint16_t)(n))); \
} \
else \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), (uint16_t)(n)); \
} \
}
#define MBEDTLS_PUT_UINT16_LE(n, data, offset) \
{ \
if (MBEDTLS_IS_BIG_ENDIAN) \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), MBEDTLS_BSWAP16((uint16_t) (n))); \
} \
else \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), (uint16_t) (n)); \
} \
}
/**
* Get the unsigned 16 bits integer corresponding to two bytes in
@ -328,8 +331,8 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the two bytes to build the 16 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT16_BE( data, offset ) \
( ( MBEDTLS_IS_BIG_ENDIAN ) \
#define MBEDTLS_GET_UINT16_BE(data, offset) \
((MBEDTLS_IS_BIG_ENDIAN) \
? mbedtls_get_unaligned_uint16((data) + (offset)) \
: MBEDTLS_BSWAP16(mbedtls_get_unaligned_uint16((data) + (offset))) \
)
@ -343,17 +346,17 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the most significant
* byte of the 16 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT16_BE( n, data, offset ) \
{ \
if ( MBEDTLS_IS_BIG_ENDIAN ) \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), (uint16_t)(n)); \
} \
else \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), MBEDTLS_BSWAP16((uint16_t)(n))); \
} \
}
#define MBEDTLS_PUT_UINT16_BE(n, data, offset) \
{ \
if (MBEDTLS_IS_BIG_ENDIAN) \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), (uint16_t) (n)); \
} \
else \
{ \
mbedtls_put_unaligned_uint16((data) + (offset), MBEDTLS_BSWAP16((uint16_t) (n))); \
} \
}
/**
* Get the unsigned 24 bits integer corresponding to three bytes in
@ -364,11 +367,11 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the three bytes to build the 24 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT24_BE( data , offset ) \
#define MBEDTLS_GET_UINT24_BE(data, offset) \
( \
( (uint32_t) ( data )[( offset ) ] << 16 ) \
| ( (uint32_t) ( data )[( offset ) + 1] << 8 ) \
| ( (uint32_t) ( data )[( offset ) + 2] ) \
((uint32_t) (data)[(offset)] << 16) \
| ((uint32_t) (data)[(offset) + 1] << 8) \
| ((uint32_t) (data)[(offset) + 2]) \
)
/**
@ -380,12 +383,12 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the most significant
* byte of the 24 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT24_BE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_2( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_1( n ); \
( data )[( offset ) + 2] = MBEDTLS_BYTE_0( n ); \
}
#define MBEDTLS_PUT_UINT24_BE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_2(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_1(n); \
(data)[(offset) + 2] = MBEDTLS_BYTE_0(n); \
}
/**
* Get the unsigned 24 bits integer corresponding to three bytes in
@ -396,11 +399,11 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the three bytes to build the 24 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT24_LE( data, offset ) \
#define MBEDTLS_GET_UINT24_LE(data, offset) \
( \
( (uint32_t) ( data )[( offset ) ] ) \
| ( (uint32_t) ( data )[( offset ) + 1] << 8 ) \
| ( (uint32_t) ( data )[( offset ) + 2] << 16 ) \
((uint32_t) (data)[(offset)]) \
| ((uint32_t) (data)[(offset) + 1] << 8) \
| ((uint32_t) (data)[(offset) + 2] << 16) \
)
/**
@ -412,12 +415,12 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the least significant
* byte of the 24 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT24_LE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_0( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_1( n ); \
( data )[( offset ) + 2] = MBEDTLS_BYTE_2( n ); \
}
#define MBEDTLS_PUT_UINT24_LE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_0(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_1(n); \
(data)[(offset) + 2] = MBEDTLS_BYTE_2(n); \
}
/**
* Get the unsigned 64 bits integer corresponding to eight bytes in
@ -428,8 +431,8 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the eight bytes to build the 64 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT64_BE( data, offset ) \
( ( MBEDTLS_IS_BIG_ENDIAN ) \
#define MBEDTLS_GET_UINT64_BE(data, offset) \
((MBEDTLS_IS_BIG_ENDIAN) \
? mbedtls_get_unaligned_uint64((data) + (offset)) \
: MBEDTLS_BSWAP64(mbedtls_get_unaligned_uint64((data) + (offset))) \
)
@ -443,17 +446,17 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the most significant
* byte of the 64 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT64_BE( n, data, offset ) \
{ \
if ( MBEDTLS_IS_BIG_ENDIAN ) \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), (uint64_t)(n)); \
} \
else \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), MBEDTLS_BSWAP64((uint64_t)(n))); \
} \
}
#define MBEDTLS_PUT_UINT64_BE(n, data, offset) \
{ \
if (MBEDTLS_IS_BIG_ENDIAN) \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), (uint64_t) (n)); \
} \
else \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), MBEDTLS_BSWAP64((uint64_t) (n))); \
} \
}
/**
* Get the unsigned 64 bits integer corresponding to eight bytes in
@ -464,8 +467,8 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* byte of the eight bytes to build the 64 bits unsigned
* integer from.
*/
#define MBEDTLS_GET_UINT64_LE( data, offset ) \
( ( MBEDTLS_IS_BIG_ENDIAN ) \
#define MBEDTLS_GET_UINT64_LE(data, offset) \
((MBEDTLS_IS_BIG_ENDIAN) \
? MBEDTLS_BSWAP64(mbedtls_get_unaligned_uint64((data) + (offset))) \
: mbedtls_get_unaligned_uint64((data) + (offset)) \
)
@ -479,16 +482,16 @@ static const uint16_t mbedtls_byte_order_detector = { 0x100 };
* \param offset Offset from \p data where to put the least significant
* byte of the 64 bits unsigned integer \p n.
*/
#define MBEDTLS_PUT_UINT64_LE( n, data, offset ) \
{ \
if ( MBEDTLS_IS_BIG_ENDIAN ) \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), MBEDTLS_BSWAP64((uint64_t)(n))); \
} \
else \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), (uint64_t)(n)); \
} \
}
#define MBEDTLS_PUT_UINT64_LE(n, data, offset) \
{ \
if (MBEDTLS_IS_BIG_ENDIAN) \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), MBEDTLS_BSWAP64((uint64_t) (n))); \
} \
else \
{ \
mbedtls_put_unaligned_uint64((data) + (offset), (uint64_t) (n)); \
} \
}
#endif /* MBEDTLS_LIBRARY_ALIGNMENT_H */

View File

@ -38,10 +38,10 @@
#include "mbedtls/platform_util.h"
/* Parameter validation macros */
#define ARIA_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ARIA_BAD_INPUT_DATA )
#define ARIA_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define ARIA_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_ARIA_BAD_INPUT_DATA)
#define ARIA_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
/*
* modify byte order: ( A B C D ) -> ( B A D C ), i.e. swap pairs of bytes
@ -55,30 +55,30 @@
#if defined(__arm__) /* rev16 available from v6 up */
/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */
#if defined(__GNUC__) && \
( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) && \
(!defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000) && \
__ARM_ARCH >= 6
static inline uint32_t aria_p1( uint32_t x )
static inline uint32_t aria_p1(uint32_t x)
{
uint32_t r;
__asm( "rev16 %0, %1" : "=l" (r) : "l" (x) );
return( r );
__asm("rev16 %0, %1" : "=l" (r) : "l" (x));
return r;
}
#define ARIA_P1 aria_p1
#elif defined(__ARMCC_VERSION) && __ARMCC_VERSION < 6000000 && \
( __TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3 )
static inline uint32_t aria_p1( uint32_t x )
(__TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3)
static inline uint32_t aria_p1(uint32_t x)
{
uint32_t r;
__asm( "rev16 r, x" );
return( r );
__asm("rev16 r, x");
return r;
}
#define ARIA_P1 aria_p1
#endif
#endif /* arm */
#if defined(__GNUC__) && \
defined(__i386__) || defined(__amd64__) || defined( __x86_64__)
defined(__i386__) || defined(__amd64__) || defined(__x86_64__)
/* I couldn't find an Intel equivalent of rev16, so two instructions */
#define ARIA_P1(x) ARIA_P2( ARIA_P3( x ) )
#define ARIA_P1(x) ARIA_P2(ARIA_P3(x))
#endif /* x86 gnuc */
#endif /* MBEDTLS_HAVE_ASM && GNUC */
#if !defined(ARIA_P1)
@ -124,28 +124,28 @@ static inline uint32_t aria_p1( uint32_t x )
* half of App. B.1 in [1] in terms of 4-byte operators P1, P2, P3 and P4.
* The implementation below uses only P1 and P2 as they are sufficient.
*/
static inline void aria_a( uint32_t *a, uint32_t *b,
uint32_t *c, uint32_t *d )
static inline void aria_a(uint32_t *a, uint32_t *b,
uint32_t *c, uint32_t *d)
{
uint32_t ta, tb, tc;
ta = *b; // 4567
*b = *a; // 0123
*a = ARIA_P2( ta ); // 6745
tb = ARIA_P2( *d ); // efcd
*d = ARIA_P1( *c ); // 98ba
*c = ARIA_P1( tb ); // fedc
*a = ARIA_P2(ta); // 6745
tb = ARIA_P2(*d); // efcd
*d = ARIA_P1(*c); // 98ba
*c = ARIA_P1(tb); // fedc
ta ^= *d; // 4567+98ba
tc = ARIA_P2( *b ); // 2301
ta = ARIA_P1( ta ) ^ tc ^ *c; // 2301+5476+89ab+fedc
tb ^= ARIA_P2( *d ); // ba98+efcd
tc ^= ARIA_P1( *a ); // 2301+7654
tc = ARIA_P2(*b); // 2301
ta = ARIA_P1(ta) ^ tc ^ *c; // 2301+5476+89ab+fedc
tb ^= ARIA_P2(*d); // ba98+efcd
tc ^= ARIA_P1(*a); // 2301+7654
*b ^= ta ^ tb; // 0123+2301+5476+89ab+ba98+efcd+fedc OUT
tb = ARIA_P2( tb ) ^ ta; // 2301+5476+89ab+98ba+cdef+fedc
*a ^= ARIA_P1( tb ); // 3210+4567+6745+89ab+98ba+dcfe+efcd OUT
ta = ARIA_P2( ta ); // 0123+7654+ab89+dcfe
*d ^= ARIA_P1( ta ) ^ tc; // 1032+2301+6745+7654+98ba+ba98+cdef OUT
tc = ARIA_P2( tc ); // 0123+5476
*c ^= ARIA_P1( tc ) ^ ta; // 0123+1032+4567+7654+ab89+dcfe+fedc OUT
tb = ARIA_P2(tb) ^ ta; // 2301+5476+89ab+98ba+cdef+fedc
*a ^= ARIA_P1(tb); // 3210+4567+6745+89ab+98ba+dcfe+efcd OUT
ta = ARIA_P2(ta); // 0123+7654+ab89+dcfe
*d ^= ARIA_P1(ta) ^ tc; // 1032+2301+6745+7654+98ba+ba98+cdef OUT
tc = ARIA_P2(tc); // 0123+5476
*c ^= ARIA_P1(tc) ^ ta; // 0123+1032+4567+7654+ab89+dcfe+fedc OUT
}
/*
@ -156,27 +156,27 @@ static inline void aria_a( uint32_t *a, uint32_t *b,
* By passing sb1, sb2, is1, is2 as S-Boxes you get SL1
* By passing is1, is2, sb1, sb2 as S-Boxes you get SL2
*/
static inline void aria_sl( uint32_t *a, uint32_t *b,
uint32_t *c, uint32_t *d,
const uint8_t sa[256], const uint8_t sb[256],
const uint8_t sc[256], const uint8_t sd[256] )
static inline void aria_sl(uint32_t *a, uint32_t *b,
uint32_t *c, uint32_t *d,
const uint8_t sa[256], const uint8_t sb[256],
const uint8_t sc[256], const uint8_t sd[256])
{
*a = ( (uint32_t) sa[ MBEDTLS_BYTE_0( *a ) ] ) ^
(((uint32_t) sb[ MBEDTLS_BYTE_1( *a ) ]) << 8) ^
(((uint32_t) sc[ MBEDTLS_BYTE_2( *a ) ]) << 16) ^
(((uint32_t) sd[ MBEDTLS_BYTE_3( *a ) ]) << 24);
*b = ( (uint32_t) sa[ MBEDTLS_BYTE_0( *b ) ] ) ^
(((uint32_t) sb[ MBEDTLS_BYTE_1( *b ) ]) << 8) ^
(((uint32_t) sc[ MBEDTLS_BYTE_2( *b ) ]) << 16) ^
(((uint32_t) sd[ MBEDTLS_BYTE_3( *b ) ]) << 24);
*c = ( (uint32_t) sa[ MBEDTLS_BYTE_0( *c ) ] ) ^
(((uint32_t) sb[ MBEDTLS_BYTE_1( *c ) ]) << 8) ^
(((uint32_t) sc[ MBEDTLS_BYTE_2( *c ) ]) << 16) ^
(((uint32_t) sd[ MBEDTLS_BYTE_3( *c ) ]) << 24);
*d = ( (uint32_t) sa[ MBEDTLS_BYTE_0( *d ) ] ) ^
(((uint32_t) sb[ MBEDTLS_BYTE_1( *d ) ]) << 8) ^
(((uint32_t) sc[ MBEDTLS_BYTE_2( *d ) ]) << 16) ^
(((uint32_t) sd[ MBEDTLS_BYTE_3( *d ) ]) << 24);
*a = ((uint32_t) sa[MBEDTLS_BYTE_0(*a)]) ^
(((uint32_t) sb[MBEDTLS_BYTE_1(*a)]) << 8) ^
(((uint32_t) sc[MBEDTLS_BYTE_2(*a)]) << 16) ^
(((uint32_t) sd[MBEDTLS_BYTE_3(*a)]) << 24);
*b = ((uint32_t) sa[MBEDTLS_BYTE_0(*b)]) ^
(((uint32_t) sb[MBEDTLS_BYTE_1(*b)]) << 8) ^
(((uint32_t) sc[MBEDTLS_BYTE_2(*b)]) << 16) ^
(((uint32_t) sd[MBEDTLS_BYTE_3(*b)]) << 24);
*c = ((uint32_t) sa[MBEDTLS_BYTE_0(*c)]) ^
(((uint32_t) sb[MBEDTLS_BYTE_1(*c)]) << 8) ^
(((uint32_t) sc[MBEDTLS_BYTE_2(*c)]) << 16) ^
(((uint32_t) sd[MBEDTLS_BYTE_3(*c)]) << 24);
*d = ((uint32_t) sa[MBEDTLS_BYTE_0(*d)]) ^
(((uint32_t) sb[MBEDTLS_BYTE_1(*d)]) << 8) ^
(((uint32_t) sc[MBEDTLS_BYTE_2(*d)]) << 16) ^
(((uint32_t) sd[MBEDTLS_BYTE_3(*d)]) << 24);
}
/*
@ -289,8 +289,8 @@ static const uint8_t aria_is2[256] =
/*
* Helper for key schedule: r = FO( p, k ) ^ x
*/
static void aria_fo_xor( uint32_t r[4], const uint32_t p[4],
const uint32_t k[4], const uint32_t x[4] )
static void aria_fo_xor(uint32_t r[4], const uint32_t p[4],
const uint32_t k[4], const uint32_t x[4])
{
uint32_t a, b, c, d;
@ -299,8 +299,8 @@ static void aria_fo_xor( uint32_t r[4], const uint32_t p[4],
c = p[2] ^ k[2];
d = p[3] ^ k[3];
aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 );
aria_a( &a, &b, &c, &d );
aria_sl(&a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2);
aria_a(&a, &b, &c, &d);
r[0] = a ^ x[0];
r[1] = b ^ x[1];
@ -311,8 +311,8 @@ static void aria_fo_xor( uint32_t r[4], const uint32_t p[4],
/*
* Helper for key schedule: r = FE( p, k ) ^ x
*/
static void aria_fe_xor( uint32_t r[4], const uint32_t p[4],
const uint32_t k[4], const uint32_t x[4] )
static void aria_fe_xor(uint32_t r[4], const uint32_t p[4],
const uint32_t k[4], const uint32_t x[4])
{
uint32_t a, b, c, d;
@ -321,8 +321,8 @@ static void aria_fe_xor( uint32_t r[4], const uint32_t p[4],
c = p[2] ^ k[2];
d = p[3] ^ k[3];
aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 );
aria_a( &a, &b, &c, &d );
aria_sl(&a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2);
aria_a(&a, &b, &c, &d);
r[0] = a ^ x[0];
r[1] = b ^ x[1];
@ -337,8 +337,8 @@ static void aria_fe_xor( uint32_t r[4], const uint32_t p[4],
* MBEDTLS_GET_UINT32_LE / MBEDTLS_PUT_UINT32_LE ) so we need to reverse
* bytes here.
*/
static void aria_rot128( uint32_t r[4], const uint32_t a[4],
const uint32_t b[4], uint8_t n )
static void aria_rot128(uint32_t r[4], const uint32_t a[4],
const uint32_t b[4], uint8_t n)
{
uint8_t i, j;
uint32_t t, u;
@ -346,15 +346,14 @@ static void aria_rot128( uint32_t r[4], const uint32_t a[4],
const uint8_t n1 = n % 32; // bit offset
const uint8_t n2 = n1 ? 32 - n1 : 0; // reverse bit offset
j = ( n / 32 ) % 4; // initial word offset
t = ARIA_P3( b[j] ); // big endian
for( i = 0; i < 4; i++ )
{
j = ( j + 1 ) % 4; // get next word, big endian
u = ARIA_P3( b[j] );
j = (n / 32) % 4; // initial word offset
t = ARIA_P3(b[j]); // big endian
for (i = 0; i < 4; i++) {
j = (j + 1) % 4; // get next word, big endian
u = ARIA_P3(b[j]);
t <<= n1; // rotate
t |= u >> n2;
t = ARIA_P3( t ); // back to little endian
t = ARIA_P3(t); // back to little endian
r[i] = a[i] ^ t; // store
t = u; // move to next word
}
@ -363,8 +362,8 @@ static void aria_rot128( uint32_t r[4], const uint32_t a[4],
/*
* Set encryption key
*/
int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx,
const unsigned char *key, unsigned int keybits )
int mbedtls_aria_setkey_enc(mbedtls_aria_context *ctx,
const unsigned char *key, unsigned int keybits)
{
/* round constant masks */
const uint32_t rc[3][4] =
@ -376,74 +375,71 @@ int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx,
int i;
uint32_t w[4][4], *w2;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( key != NULL );
ARIA_VALIDATE_RET(ctx != NULL);
ARIA_VALIDATE_RET(key != NULL);
if( keybits != 128 && keybits != 192 && keybits != 256 )
return( MBEDTLS_ERR_ARIA_BAD_INPUT_DATA );
if (keybits != 128 && keybits != 192 && keybits != 256) {
return MBEDTLS_ERR_ARIA_BAD_INPUT_DATA;
}
/* Copy key to W0 (and potential remainder to W1) */
w[0][0] = MBEDTLS_GET_UINT32_LE( key, 0 );
w[0][1] = MBEDTLS_GET_UINT32_LE( key, 4 );
w[0][2] = MBEDTLS_GET_UINT32_LE( key, 8 );
w[0][3] = MBEDTLS_GET_UINT32_LE( key, 12 );
w[0][0] = MBEDTLS_GET_UINT32_LE(key, 0);
w[0][1] = MBEDTLS_GET_UINT32_LE(key, 4);
w[0][2] = MBEDTLS_GET_UINT32_LE(key, 8);
w[0][3] = MBEDTLS_GET_UINT32_LE(key, 12);
memset( w[1], 0, 16 );
if( keybits >= 192 )
{
w[1][0] = MBEDTLS_GET_UINT32_LE( key, 16 ); // 192 bit key
w[1][1] = MBEDTLS_GET_UINT32_LE( key, 20 );
memset(w[1], 0, 16);
if (keybits >= 192) {
w[1][0] = MBEDTLS_GET_UINT32_LE(key, 16); // 192 bit key
w[1][1] = MBEDTLS_GET_UINT32_LE(key, 20);
}
if( keybits == 256 )
{
w[1][2] = MBEDTLS_GET_UINT32_LE( key, 24 ); // 256 bit key
w[1][3] = MBEDTLS_GET_UINT32_LE( key, 28 );
if (keybits == 256) {
w[1][2] = MBEDTLS_GET_UINT32_LE(key, 24); // 256 bit key
w[1][3] = MBEDTLS_GET_UINT32_LE(key, 28);
}
i = ( keybits - 128 ) >> 6; // index: 0, 1, 2
i = (keybits - 128) >> 6; // index: 0, 1, 2
ctx->nr = 12 + 2 * i; // no. rounds: 12, 14, 16
aria_fo_xor( w[1], w[0], rc[i], w[1] ); // W1 = FO(W0, CK1) ^ KR
aria_fo_xor(w[1], w[0], rc[i], w[1]); // W1 = FO(W0, CK1) ^ KR
i = i < 2 ? i + 1 : 0;
aria_fe_xor( w[2], w[1], rc[i], w[0] ); // W2 = FE(W1, CK2) ^ W0
aria_fe_xor(w[2], w[1], rc[i], w[0]); // W2 = FE(W1, CK2) ^ W0
i = i < 2 ? i + 1 : 0;
aria_fo_xor( w[3], w[2], rc[i], w[1] ); // W3 = FO(W2, CK3) ^ W1
aria_fo_xor(w[3], w[2], rc[i], w[1]); // W3 = FO(W2, CK3) ^ W1
for( i = 0; i < 4; i++ ) // create round keys
{
for (i = 0; i < 4; i++) { // create round keys
w2 = w[(i + 1) & 3];
aria_rot128( ctx->rk[i ], w[i], w2, 128 - 19 );
aria_rot128( ctx->rk[i + 4], w[i], w2, 128 - 31 );
aria_rot128( ctx->rk[i + 8], w[i], w2, 61 );
aria_rot128( ctx->rk[i + 12], w[i], w2, 31 );
aria_rot128(ctx->rk[i], w[i], w2, 128 - 19);
aria_rot128(ctx->rk[i + 4], w[i], w2, 128 - 31);
aria_rot128(ctx->rk[i + 8], w[i], w2, 61);
aria_rot128(ctx->rk[i + 12], w[i], w2, 31);
}
aria_rot128( ctx->rk[16], w[0], w[1], 19 );
aria_rot128(ctx->rk[16], w[0], w[1], 19);
/* w holds enough info to reconstruct the round keys */
mbedtls_platform_zeroize( w, sizeof( w ) );
mbedtls_platform_zeroize(w, sizeof(w));
return( 0 );
return 0;
}
/*
* Set decryption key
*/
int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx,
const unsigned char *key, unsigned int keybits )
int mbedtls_aria_setkey_dec(mbedtls_aria_context *ctx,
const unsigned char *key, unsigned int keybits)
{
int i, j, k, ret;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( key != NULL );
ARIA_VALIDATE_RET(ctx != NULL);
ARIA_VALIDATE_RET(key != NULL);
ret = mbedtls_aria_setkey_enc( ctx, key, keybits );
if( ret != 0 )
return( ret );
ret = mbedtls_aria_setkey_enc(ctx, key, keybits);
if (ret != 0) {
return ret;
}
/* flip the order of round keys */
for( i = 0, j = ctx->nr; i < j; i++, j-- )
{
for( k = 0; k < 4; k++ )
{
for (i = 0, j = ctx->nr; i < j; i++, j--) {
for (k = 0; k < 4; k++) {
uint32_t t = ctx->rk[i][k];
ctx->rk[i][k] = ctx->rk[j][k];
ctx->rk[j][k] = t;
@ -451,45 +447,43 @@ int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx,
}
/* apply affine transform to middle keys */
for( i = 1; i < ctx->nr; i++ )
{
aria_a( &ctx->rk[i][0], &ctx->rk[i][1],
&ctx->rk[i][2], &ctx->rk[i][3] );
for (i = 1; i < ctx->nr; i++) {
aria_a(&ctx->rk[i][0], &ctx->rk[i][1],
&ctx->rk[i][2], &ctx->rk[i][3]);
}
return( 0 );
return 0;
}
/*
* Encrypt a block
*/
int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,
const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] )
int mbedtls_aria_crypt_ecb(mbedtls_aria_context *ctx,
const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char output[MBEDTLS_ARIA_BLOCKSIZE])
{
int i;
uint32_t a, b, c, d;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( input != NULL );
ARIA_VALIDATE_RET( output != NULL );
ARIA_VALIDATE_RET(ctx != NULL);
ARIA_VALIDATE_RET(input != NULL);
ARIA_VALIDATE_RET(output != NULL);
a = MBEDTLS_GET_UINT32_LE( input, 0 );
b = MBEDTLS_GET_UINT32_LE( input, 4 );
c = MBEDTLS_GET_UINT32_LE( input, 8 );
d = MBEDTLS_GET_UINT32_LE( input, 12 );
a = MBEDTLS_GET_UINT32_LE(input, 0);
b = MBEDTLS_GET_UINT32_LE(input, 4);
c = MBEDTLS_GET_UINT32_LE(input, 8);
d = MBEDTLS_GET_UINT32_LE(input, 12);
i = 0;
while( 1 )
{
while (1) {
a ^= ctx->rk[i][0];
b ^= ctx->rk[i][1];
c ^= ctx->rk[i][2];
d ^= ctx->rk[i][3];
i++;
aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 );
aria_a( &a, &b, &c, &d );
aria_sl(&a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2);
aria_a(&a, &b, &c, &d);
a ^= ctx->rk[i][0];
b ^= ctx->rk[i][1];
@ -497,10 +491,11 @@ int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,
d ^= ctx->rk[i][3];
i++;
aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 );
if( i >= ctx->nr )
aria_sl(&a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2);
if (i >= ctx->nr) {
break;
aria_a( &a, &b, &c, &d );
}
aria_a(&a, &b, &c, &d);
}
/* final key mixing */
@ -509,77 +504,74 @@ int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,
c ^= ctx->rk[i][2];
d ^= ctx->rk[i][3];
MBEDTLS_PUT_UINT32_LE( a, output, 0 );
MBEDTLS_PUT_UINT32_LE( b, output, 4 );
MBEDTLS_PUT_UINT32_LE( c, output, 8 );
MBEDTLS_PUT_UINT32_LE( d, output, 12 );
MBEDTLS_PUT_UINT32_LE(a, output, 0);
MBEDTLS_PUT_UINT32_LE(b, output, 4);
MBEDTLS_PUT_UINT32_LE(c, output, 8);
MBEDTLS_PUT_UINT32_LE(d, output, 12);
return( 0 );
return 0;
}
/* Initialize context */
void mbedtls_aria_init( mbedtls_aria_context *ctx )
void mbedtls_aria_init(mbedtls_aria_context *ctx)
{
ARIA_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_aria_context ) );
ARIA_VALIDATE(ctx != NULL);
memset(ctx, 0, sizeof(mbedtls_aria_context));
}
/* Clear context */
void mbedtls_aria_free( mbedtls_aria_context *ctx )
void mbedtls_aria_free(mbedtls_aria_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aria_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_aria_context));
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* ARIA-CBC buffer encryption/decryption
*/
int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,
int mode,
size_t length,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
int mbedtls_aria_crypt_cbc(mbedtls_aria_context *ctx,
int mode,
size_t length,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output)
{
unsigned char temp[MBEDTLS_ARIA_BLOCKSIZE];
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( mode == MBEDTLS_ARIA_ENCRYPT ||
mode == MBEDTLS_ARIA_DECRYPT );
ARIA_VALIDATE_RET( length == 0 || input != NULL );
ARIA_VALIDATE_RET( length == 0 || output != NULL );
ARIA_VALIDATE_RET( iv != NULL );
ARIA_VALIDATE_RET(ctx != NULL);
ARIA_VALIDATE_RET(mode == MBEDTLS_ARIA_ENCRYPT ||
mode == MBEDTLS_ARIA_DECRYPT);
ARIA_VALIDATE_RET(length == 0 || input != NULL);
ARIA_VALIDATE_RET(length == 0 || output != NULL);
ARIA_VALIDATE_RET(iv != NULL);
if( length % MBEDTLS_ARIA_BLOCKSIZE )
return( MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH );
if (length % MBEDTLS_ARIA_BLOCKSIZE) {
return MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH;
}
if( mode == MBEDTLS_ARIA_DECRYPT )
{
while( length > 0 )
{
memcpy( temp, input, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_aria_crypt_ecb( ctx, input, output );
if (mode == MBEDTLS_ARIA_DECRYPT) {
while (length > 0) {
memcpy(temp, input, MBEDTLS_ARIA_BLOCKSIZE);
mbedtls_aria_crypt_ecb(ctx, input, output);
mbedtls_xor( output, output, iv, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_xor(output, output, iv, MBEDTLS_ARIA_BLOCKSIZE);
memcpy( iv, temp, MBEDTLS_ARIA_BLOCKSIZE );
memcpy(iv, temp, MBEDTLS_ARIA_BLOCKSIZE);
input += MBEDTLS_ARIA_BLOCKSIZE;
output += MBEDTLS_ARIA_BLOCKSIZE;
length -= MBEDTLS_ARIA_BLOCKSIZE;
}
}
else
{
while( length > 0 )
{
mbedtls_xor( output, input, iv, MBEDTLS_ARIA_BLOCKSIZE );
} else {
while (length > 0) {
mbedtls_xor(output, input, iv, MBEDTLS_ARIA_BLOCKSIZE);
mbedtls_aria_crypt_ecb( ctx, output, output );
memcpy( iv, output, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_aria_crypt_ecb(ctx, output, output);
memcpy(iv, output, MBEDTLS_ARIA_BLOCKSIZE);
input += MBEDTLS_ARIA_BLOCKSIZE;
output += MBEDTLS_ARIA_BLOCKSIZE;
@ -587,7 +579,7 @@ int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,
}
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
@ -595,63 +587,61 @@ int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,
/*
* ARIA-CFB128 buffer encryption/decryption
*/
int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx,
int mode,
size_t length,
size_t *iv_off,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
int mbedtls_aria_crypt_cfb128(mbedtls_aria_context *ctx,
int mode,
size_t length,
size_t *iv_off,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output)
{
unsigned char c;
size_t n;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( mode == MBEDTLS_ARIA_ENCRYPT ||
mode == MBEDTLS_ARIA_DECRYPT );
ARIA_VALIDATE_RET( length == 0 || input != NULL );
ARIA_VALIDATE_RET( length == 0 || output != NULL );
ARIA_VALIDATE_RET( iv != NULL );
ARIA_VALIDATE_RET( iv_off != NULL );
ARIA_VALIDATE_RET(ctx != NULL);
ARIA_VALIDATE_RET(mode == MBEDTLS_ARIA_ENCRYPT ||
mode == MBEDTLS_ARIA_DECRYPT);
ARIA_VALIDATE_RET(length == 0 || input != NULL);
ARIA_VALIDATE_RET(length == 0 || output != NULL);
ARIA_VALIDATE_RET(iv != NULL);
ARIA_VALIDATE_RET(iv_off != NULL);
n = *iv_off;
/* An overly large value of n can lead to an unlimited
* buffer overflow. Therefore, guard against this
* outside of parameter validation. */
if( n >= MBEDTLS_ARIA_BLOCKSIZE )
return( MBEDTLS_ERR_ARIA_BAD_INPUT_DATA );
if (n >= MBEDTLS_ARIA_BLOCKSIZE) {
return MBEDTLS_ERR_ARIA_BAD_INPUT_DATA;
}
if( mode == MBEDTLS_ARIA_DECRYPT )
{
while( length-- )
{
if( n == 0 )
mbedtls_aria_crypt_ecb( ctx, iv, iv );
if (mode == MBEDTLS_ARIA_DECRYPT) {
while (length--) {
if (n == 0) {
mbedtls_aria_crypt_ecb(ctx, iv, iv);
}
c = *input++;
*output++ = c ^ iv[n];
iv[n] = c;
n = ( n + 1 ) & 0x0F;
n = (n + 1) & 0x0F;
}
}
else
{
while( length-- )
{
if( n == 0 )
mbedtls_aria_crypt_ecb( ctx, iv, iv );
} else {
while (length--) {
if (n == 0) {
mbedtls_aria_crypt_ecb(ctx, iv, iv);
}
iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );
iv[n] = *output++ = (unsigned char) (iv[n] ^ *input++);
n = ( n + 1 ) & 0x0F;
n = (n + 1) & 0x0F;
}
}
*iv_off = n;
return( 0 );
return 0;
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
@ -659,50 +649,52 @@ int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx,
/*
* ARIA-CTR buffer encryption/decryption
*/
int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
int mbedtls_aria_crypt_ctr(mbedtls_aria_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output)
{
int c, i;
size_t n;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( length == 0 || input != NULL );
ARIA_VALIDATE_RET( length == 0 || output != NULL );
ARIA_VALIDATE_RET( nonce_counter != NULL );
ARIA_VALIDATE_RET( stream_block != NULL );
ARIA_VALIDATE_RET( nc_off != NULL );
ARIA_VALIDATE_RET(ctx != NULL);
ARIA_VALIDATE_RET(length == 0 || input != NULL);
ARIA_VALIDATE_RET(length == 0 || output != NULL);
ARIA_VALIDATE_RET(nonce_counter != NULL);
ARIA_VALIDATE_RET(stream_block != NULL);
ARIA_VALIDATE_RET(nc_off != NULL);
n = *nc_off;
/* An overly large value of n can lead to an unlimited
* buffer overflow. Therefore, guard against this
* outside of parameter validation. */
if( n >= MBEDTLS_ARIA_BLOCKSIZE )
return( MBEDTLS_ERR_ARIA_BAD_INPUT_DATA );
if (n >= MBEDTLS_ARIA_BLOCKSIZE) {
return MBEDTLS_ERR_ARIA_BAD_INPUT_DATA;
}
while( length-- )
{
if( n == 0 ) {
mbedtls_aria_crypt_ecb( ctx, nonce_counter,
stream_block );
while (length--) {
if (n == 0) {
mbedtls_aria_crypt_ecb(ctx, nonce_counter,
stream_block);
for( i = MBEDTLS_ARIA_BLOCKSIZE; i > 0; i-- )
if( ++nonce_counter[i - 1] != 0 )
for (i = MBEDTLS_ARIA_BLOCKSIZE; i > 0; i--) {
if (++nonce_counter[i - 1] != 0) {
break;
}
}
}
c = *input++;
*output++ = (unsigned char)( c ^ stream_block[n] );
*output++ = (unsigned char) (c ^ stream_block[n]);
n = ( n + 1 ) & 0x0F;
n = (n + 1) & 0x0F;
}
*nc_off = n;
return( 0 );
return 0;
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#endif /* !MBEDTLS_ARIA_ALT */
@ -841,22 +833,22 @@ static const uint8_t aria_test2_ctr_ct[3][48] = // CTR ciphertext
};
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#define ARIA_SELF_TEST_ASSERT( cond ) \
do { \
if( cond ) { \
if( verbose ) \
mbedtls_printf( "failed\n" ); \
goto exit; \
} else { \
if( verbose ) \
mbedtls_printf( "passed\n" ); \
} \
} while( 0 )
#define ARIA_SELF_TEST_ASSERT(cond) \
do { \
if (cond) { \
if (verbose) \
mbedtls_printf("failed\n"); \
goto exit; \
} else { \
if (verbose) \
mbedtls_printf("passed\n"); \
} \
} while (0)
/*
* Checkup routine
*/
int mbedtls_aria_self_test( int verbose )
int mbedtls_aria_self_test(int verbose)
{
int i;
uint8_t blk[MBEDTLS_ARIA_BLOCKSIZE];
@ -868,134 +860,142 @@ int mbedtls_aria_self_test( int verbose )
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) || \
defined(MBEDTLS_CIPHER_MODE_CFB) || \
defined(MBEDTLS_CIPHER_MODE_CTR))
defined(MBEDTLS_CIPHER_MODE_CFB) || \
defined(MBEDTLS_CIPHER_MODE_CTR))
uint8_t buf[48], iv[MBEDTLS_ARIA_BLOCKSIZE];
#endif
mbedtls_aria_init( &ctx );
mbedtls_aria_init(&ctx);
/*
* Test set 1
*/
for( i = 0; i < 3; i++ )
{
for (i = 0; i < 3; i++) {
/* test ECB encryption */
if( verbose )
mbedtls_printf( " ARIA-ECB-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test1_ecb_key, 128 + 64 * i );
mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_pt, blk );
if (verbose) {
mbedtls_printf(" ARIA-ECB-%d (enc): ", 128 + 64 * i);
}
mbedtls_aria_setkey_enc(&ctx, aria_test1_ecb_key, 128 + 64 * i);
mbedtls_aria_crypt_ecb(&ctx, aria_test1_ecb_pt, blk);
ARIA_SELF_TEST_ASSERT(
memcmp( blk, aria_test1_ecb_ct[i], MBEDTLS_ARIA_BLOCKSIZE )
!= 0 );
memcmp(blk, aria_test1_ecb_ct[i], MBEDTLS_ARIA_BLOCKSIZE)
!= 0);
/* test ECB decryption */
if( verbose )
mbedtls_printf( " ARIA-ECB-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_dec( &ctx, aria_test1_ecb_key, 128 + 64 * i );
mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_ct[i], blk );
if (verbose) {
mbedtls_printf(" ARIA-ECB-%d (dec): ", 128 + 64 * i);
}
mbedtls_aria_setkey_dec(&ctx, aria_test1_ecb_key, 128 + 64 * i);
mbedtls_aria_crypt_ecb(&ctx, aria_test1_ecb_ct[i], blk);
ARIA_SELF_TEST_ASSERT(
memcmp( blk, aria_test1_ecb_pt, MBEDTLS_ARIA_BLOCKSIZE )
!= 0 );
memcmp(blk, aria_test1_ecb_pt, MBEDTLS_ARIA_BLOCKSIZE)
!= 0);
}
if (verbose) {
mbedtls_printf("\n");
}
if( verbose )
mbedtls_printf( "\n" );
/*
* Test set 2
*/
#if defined(MBEDTLS_CIPHER_MODE_CBC)
for( i = 0; i < 3; i++ )
{
for (i = 0; i < 3; i++) {
/* Test CBC encryption */
if( verbose )
mbedtls_printf( " ARIA-CBC-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0x55, sizeof( buf ) );
mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, iv,
aria_test2_pt, buf );
ARIA_SELF_TEST_ASSERT( memcmp( buf, aria_test2_cbc_ct[i], 48 )
!= 0 );
if (verbose) {
mbedtls_printf(" ARIA-CBC-%d (enc): ", 128 + 64 * i);
}
mbedtls_aria_setkey_enc(&ctx, aria_test2_key, 128 + 64 * i);
memcpy(iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE);
memset(buf, 0x55, sizeof(buf));
mbedtls_aria_crypt_cbc(&ctx, MBEDTLS_ARIA_ENCRYPT, 48, iv,
aria_test2_pt, buf);
ARIA_SELF_TEST_ASSERT(memcmp(buf, aria_test2_cbc_ct[i], 48)
!= 0);
/* Test CBC decryption */
if( verbose )
mbedtls_printf( " ARIA-CBC-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_dec( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0xAA, sizeof( buf ) );
mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_DECRYPT, 48, iv,
aria_test2_cbc_ct[i], buf );
ARIA_SELF_TEST_ASSERT( memcmp( buf, aria_test2_pt, 48 ) != 0 );
if (verbose) {
mbedtls_printf(" ARIA-CBC-%d (dec): ", 128 + 64 * i);
}
mbedtls_aria_setkey_dec(&ctx, aria_test2_key, 128 + 64 * i);
memcpy(iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE);
memset(buf, 0xAA, sizeof(buf));
mbedtls_aria_crypt_cbc(&ctx, MBEDTLS_ARIA_DECRYPT, 48, iv,
aria_test2_cbc_ct[i], buf);
ARIA_SELF_TEST_ASSERT(memcmp(buf, aria_test2_pt, 48) != 0);
}
if (verbose) {
mbedtls_printf("\n");
}
if( verbose )
mbedtls_printf( "\n" );
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
for( i = 0; i < 3; i++ )
{
for (i = 0; i < 3; i++) {
/* Test CFB encryption */
if( verbose )
mbedtls_printf( " ARIA-CFB-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0x55, sizeof( buf ) );
if (verbose) {
mbedtls_printf(" ARIA-CFB-%d (enc): ", 128 + 64 * i);
}
mbedtls_aria_setkey_enc(&ctx, aria_test2_key, 128 + 64 * i);
memcpy(iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE);
memset(buf, 0x55, sizeof(buf));
j = 0;
mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, &j, iv,
aria_test2_pt, buf );
ARIA_SELF_TEST_ASSERT( memcmp( buf, aria_test2_cfb_ct[i], 48 ) != 0 );
mbedtls_aria_crypt_cfb128(&ctx, MBEDTLS_ARIA_ENCRYPT, 48, &j, iv,
aria_test2_pt, buf);
ARIA_SELF_TEST_ASSERT(memcmp(buf, aria_test2_cfb_ct[i], 48) != 0);
/* Test CFB decryption */
if( verbose )
mbedtls_printf( " ARIA-CFB-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0xAA, sizeof( buf ) );
if (verbose) {
mbedtls_printf(" ARIA-CFB-%d (dec): ", 128 + 64 * i);
}
mbedtls_aria_setkey_enc(&ctx, aria_test2_key, 128 + 64 * i);
memcpy(iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE);
memset(buf, 0xAA, sizeof(buf));
j = 0;
mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_DECRYPT, 48, &j,
iv, aria_test2_cfb_ct[i], buf );
ARIA_SELF_TEST_ASSERT( memcmp( buf, aria_test2_pt, 48 ) != 0 );
mbedtls_aria_crypt_cfb128(&ctx, MBEDTLS_ARIA_DECRYPT, 48, &j,
iv, aria_test2_cfb_ct[i], buf);
ARIA_SELF_TEST_ASSERT(memcmp(buf, aria_test2_pt, 48) != 0);
}
if (verbose) {
mbedtls_printf("\n");
}
if( verbose )
mbedtls_printf( "\n" );
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
for( i = 0; i < 3; i++ )
{
for (i = 0; i < 3; i++) {
/* Test CTR encryption */
if( verbose )
mbedtls_printf( " ARIA-CTR-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE ); // IV = 0
memset( buf, 0x55, sizeof( buf ) );
if (verbose) {
mbedtls_printf(" ARIA-CTR-%d (enc): ", 128 + 64 * i);
}
mbedtls_aria_setkey_enc(&ctx, aria_test2_key, 128 + 64 * i);
memset(iv, 0, MBEDTLS_ARIA_BLOCKSIZE); // IV = 0
memset(buf, 0x55, sizeof(buf));
j = 0;
mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk,
aria_test2_pt, buf );
ARIA_SELF_TEST_ASSERT( memcmp( buf, aria_test2_ctr_ct[i], 48 ) != 0 );
mbedtls_aria_crypt_ctr(&ctx, 48, &j, iv, blk,
aria_test2_pt, buf);
ARIA_SELF_TEST_ASSERT(memcmp(buf, aria_test2_ctr_ct[i], 48) != 0);
/* Test CTR decryption */
if( verbose )
mbedtls_printf( " ARIA-CTR-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE ); // IV = 0
memset( buf, 0xAA, sizeof( buf ) );
if (verbose) {
mbedtls_printf(" ARIA-CTR-%d (dec): ", 128 + 64 * i);
}
mbedtls_aria_setkey_enc(&ctx, aria_test2_key, 128 + 64 * i);
memset(iv, 0, MBEDTLS_ARIA_BLOCKSIZE); // IV = 0
memset(buf, 0xAA, sizeof(buf));
j = 0;
mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk,
aria_test2_ctr_ct[i], buf );
ARIA_SELF_TEST_ASSERT( memcmp( buf, aria_test2_pt, 48 ) != 0 );
mbedtls_aria_crypt_ctr(&ctx, 48, &j, iv, blk,
aria_test2_ctr_ct[i], buf);
ARIA_SELF_TEST_ASSERT(memcmp(buf, aria_test2_pt, 48) != 0);
}
if (verbose) {
mbedtls_printf("\n");
}
if( verbose )
mbedtls_printf( "\n" );
#endif /* MBEDTLS_CIPHER_MODE_CTR */
ret = 0;
exit:
mbedtls_aria_free( &ctx );
return( ret );
mbedtls_aria_free(&ctx);
return ret;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@ -36,203 +36,219 @@
/*
* 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(unsigned char **p,
const unsigned char *end,
size_t *len)
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
if ((end - *p) < 1) {
return MBEDTLS_ERR_ASN1_OUT_OF_DATA;
}
if( ( **p & 0x80 ) == 0 )
if ((**p & 0x80) == 0) {
*len = *(*p)++;
else
{
switch( **p & 0x7F )
{
case 1:
if( ( end - *p ) < 2 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
} else {
switch (**p & 0x7F) {
case 1:
if ((end - *p) < 2) {
return MBEDTLS_ERR_ASN1_OUT_OF_DATA;
}
*len = (*p)[1];
(*p) += 2;
break;
*len = (*p)[1];
(*p) += 2;
break;
case 2:
if( ( end - *p ) < 3 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
case 2:
if ((end - *p) < 3) {
return MBEDTLS_ERR_ASN1_OUT_OF_DATA;
}
*len = ( (size_t)(*p)[1] << 8 ) | (*p)[2];
(*p) += 3;
break;
*len = ((size_t) (*p)[1] << 8) | (*p)[2];
(*p) += 3;
break;
case 3:
if( ( end - *p ) < 4 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
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;
*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 );
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;
*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 );
default:
return MBEDTLS_ERR_ASN1_INVALID_LENGTH;
}
}
if( *len > (size_t) ( end - *p ) )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
if (*len > (size_t) (end - *p)) {
return MBEDTLS_ERR_ASN1_OUT_OF_DATA;
}
return( 0 );
return 0;
}
int mbedtls_asn1_get_tag( unsigned char **p,
const unsigned char *end,
size_t *len, int tag )
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 ((end - *p) < 1) {
return MBEDTLS_ERR_ASN1_OUT_OF_DATA;
}
if( **p != tag )
return( MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
if (**p != tag) {
return MBEDTLS_ERR_ASN1_UNEXPECTED_TAG;
}
(*p)++;
return( mbedtls_asn1_get_len( p, end, len ) );
return mbedtls_asn1_get_len(p, end, len);
}
int mbedtls_asn1_get_bool( unsigned char **p,
const unsigned char *end,
int *val )
int mbedtls_asn1_get_bool(unsigned char **p,
const unsigned char *end,
int *val)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_BOOLEAN ) ) != 0 )
return( ret );
if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_BOOLEAN)) != 0) {
return ret;
}
if( len != 1 )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
if (len != 1) {
return MBEDTLS_ERR_ASN1_INVALID_LENGTH;
}
*val = ( **p != 0 ) ? 1 : 0;
*val = (**p != 0) ? 1 : 0;
(*p)++;
return( 0 );
return 0;
}
static int asn1_get_tagged_int( unsigned char **p,
const unsigned char *end,
int tag, int *val )
static int asn1_get_tagged_int(unsigned char **p,
const unsigned char *end,
int tag, int *val)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, tag ) ) != 0 )
return( ret );
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
*/
if( len == 0 )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
if (len == 0) {
return MBEDTLS_ERR_ASN1_INVALID_LENGTH;
}
/* This is a cryptography library. Reject negative integers. */
if( ( **p & 0x80 ) != 0 )
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
if ((**p & 0x80) != 0) {
return MBEDTLS_ERR_ASN1_INVALID_LENGTH;
}
/* Skip leading zeros. */
while( len > 0 && **p == 0 )
{
++( *p );
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 );
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;
while (len-- > 0) {
*val = (*val << 8) | **p;
(*p)++;
}
return( 0 );
return 0;
}
int mbedtls_asn1_get_int( unsigned char **p,
int mbedtls_asn1_get_int(unsigned char **p,
const unsigned char *end,
int *val)
{
return asn1_get_tagged_int(p, end, MBEDTLS_ASN1_INTEGER, val);
}
int mbedtls_asn1_get_enum(unsigned char **p,
const unsigned char *end,
int *val )
int *val)
{
return( asn1_get_tagged_int( p, end, MBEDTLS_ASN1_INTEGER, val) );
}
int mbedtls_asn1_get_enum( unsigned char **p,
const unsigned char *end,
int *val )
{
return( asn1_get_tagged_int( p, end, MBEDTLS_ASN1_ENUMERATED, val) );
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 )
int mbedtls_asn1_get_mpi(unsigned char **p,
const unsigned char *end,
mbedtls_mpi *X)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
return( ret );
if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
return ret;
}
ret = mbedtls_mpi_read_binary( X, *p, len );
ret = mbedtls_mpi_read_binary(X, *p, len);
*p += len;
return( ret );
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;
/* Certificate type is a single byte bitstring */
if( ( ret = mbedtls_asn1_get_tag( p, end, &bs->len, MBEDTLS_ASN1_BIT_STRING ) ) != 0 )
return( ret );
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 );
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 );
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 );
if (*p != end) {
return MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
}
return( 0 );
return 0;
}
/*
@ -244,104 +260,105 @@ int mbedtls_asn1_traverse_sequence_of(
const unsigned char *end,
unsigned char tag_must_mask, unsigned char tag_must_val,
unsigned char tag_may_mask, unsigned char tag_may_val,
int (*cb)( void *ctx, int tag,
unsigned char *start, size_t len ),
void *ctx )
int (*cb)(void *ctx, int tag,
unsigned char *start, size_t len),
void *ctx)
{
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 ((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 );
if (*p + len != end) {
return MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
}
while( *p < end )
{
while (*p < end) {
unsigned char const tag = *(*p)++;
if( ( tag & tag_must_mask ) != tag_must_val )
return( MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
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 ((ret = mbedtls_asn1_get_len(p, end, &len)) != 0) {
return ret;
}
if( ( tag & tag_may_mask ) == tag_may_val )
{
if( cb != NULL )
{
ret = cb( ctx, tag, *p, len );
if( ret != 0 )
return( ret );
if ((tag & tag_may_mask) == tag_may_val) {
if (cb != NULL) {
ret = cb(ctx, tag, *p, len);
if (ret != 0) {
return ret;
}
}
}
*p += len;
}
return( 0 );
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;
if( ( ret = mbedtls_asn1_get_tag( p, end, len, MBEDTLS_ASN1_BIT_STRING ) ) != 0 )
return( ret );
if ((ret = mbedtls_asn1_get_tag(p, end, len, MBEDTLS_ASN1_BIT_STRING)) != 0) {
return ret;
}
if( *len == 0 )
return( MBEDTLS_ERR_ASN1_INVALID_DATA );
--( *len );
if (*len == 0) {
return MBEDTLS_ERR_ASN1_INVALID_DATA;
}
--(*len);
if( **p != 0 )
return( MBEDTLS_ERR_ASN1_INVALID_DATA );
++( *p );
if (**p != 0) {
return MBEDTLS_ERR_ASN1_INVALID_DATA;
}
++(*p);
return( 0 );
return 0;
}
void mbedtls_asn1_sequence_free( mbedtls_asn1_sequence *seq )
void mbedtls_asn1_sequence_free(mbedtls_asn1_sequence *seq)
{
while( seq != NULL )
{
while (seq != NULL) {
mbedtls_asn1_sequence *next = seq->next;
mbedtls_free( seq );
mbedtls_free(seq);
seq = next;
}
}
typedef struct
{
typedef struct {
int tag;
mbedtls_asn1_sequence *cur;
} asn1_get_sequence_of_cb_ctx_t;
static int asn1_get_sequence_of_cb( void *ctx,
int tag,
unsigned char *start,
size_t len )
static int asn1_get_sequence_of_cb(void *ctx,
int tag,
unsigned char *start,
size_t len)
{
asn1_get_sequence_of_cb_ctx_t *cb_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 != NULL) {
cur->next =
mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
mbedtls_calloc(1, sizeof(mbedtls_asn1_sequence));
if( cur->next == NULL )
return( MBEDTLS_ERR_ASN1_ALLOC_FAILED );
if (cur->next == NULL) {
return MBEDTLS_ERR_ASN1_ALLOC_FAILED;
}
cur = cur->next;
}
@ -351,136 +368,139 @@ static int asn1_get_sequence_of_cb( void *ctx,
cur->buf.tag = tag;
cb_ctx->cur = cur;
return( 0 );
return 0;
}
/*
* 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)
int mbedtls_asn1_get_sequence_of(unsigned char **p,
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 ) );
return( mbedtls_asn1_traverse_sequence_of(
p, end, 0xFF, tag, 0, 0,
asn1_get_sequence_of_cb, &cb_ctx ) );
memset(cur, 0, 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 )
int mbedtls_asn1_get_alg(unsigned char **p,
const unsigned char *end,
mbedtls_asn1_buf *alg, mbedtls_asn1_buf *params)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( ret );
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 );
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 );
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 );
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 );
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 );
if (*p != end) {
return MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
}
return( 0 );
return 0;
}
int mbedtls_asn1_get_alg_null( unsigned char **p,
const unsigned char *end,
mbedtls_asn1_buf *alg )
int mbedtls_asn1_get_alg_null(unsigned char **p,
const unsigned char *end,
mbedtls_asn1_buf *alg)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_asn1_buf params;
memset( &params, 0, sizeof(mbedtls_asn1_buf) );
memset(&params, 0, sizeof(mbedtls_asn1_buf));
if( ( ret = mbedtls_asn1_get_alg( p, end, alg, &params ) ) != 0 )
return( ret );
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 );
if ((params.tag != MBEDTLS_ASN1_NULL && params.tag != 0) || params.len != 0) {
return MBEDTLS_ERR_ASN1_INVALID_DATA;
}
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_asn1_free_named_data( mbedtls_asn1_named_data *cur )
void mbedtls_asn1_free_named_data(mbedtls_asn1_named_data *cur)
{
if( cur == NULL )
if (cur == NULL) {
return;
}
mbedtls_free( cur->oid.p );
mbedtls_free( cur->val.p );
mbedtls_free(cur->oid.p);
mbedtls_free(cur->val.p);
mbedtls_platform_zeroize( cur, sizeof( mbedtls_asn1_named_data ) );
mbedtls_platform_zeroize(cur, sizeof(mbedtls_asn1_named_data));
}
#endif /* MBEDTLS_DEPRECATED_REMOVED */
void mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head )
void mbedtls_asn1_free_named_data_list(mbedtls_asn1_named_data **head)
{
mbedtls_asn1_named_data *cur;
while( ( cur = *head ) != NULL )
{
while ((cur = *head) != NULL) {
*head = cur->next;
mbedtls_free( cur->oid.p );
mbedtls_free( cur->val.p );
mbedtls_free( cur );
mbedtls_free(cur->oid.p);
mbedtls_free(cur->val.p);
mbedtls_free(cur);
}
}
void mbedtls_asn1_free_named_data_list_shallow( mbedtls_asn1_named_data *name )
void mbedtls_asn1_free_named_data_list_shallow(mbedtls_asn1_named_data *name)
{
for( mbedtls_asn1_named_data *next; name != NULL; name = next )
{
for (mbedtls_asn1_named_data *next; name != NULL; name = next) {
next = name->next;
mbedtls_free( name );
mbedtls_free(name);
}
}
const mbedtls_asn1_named_data *mbedtls_asn1_find_named_data( const mbedtls_asn1_named_data *list,
const char *oid, size_t len )
const mbedtls_asn1_named_data *mbedtls_asn1_find_named_data(const mbedtls_asn1_named_data *list,
const char *oid, size_t len)
{
while( list != NULL )
{
if( list->oid.len == len &&
memcmp( list->oid.p, oid, len ) == 0 )
{
while (list != NULL) {
if (list->oid.len == len &&
memcmp(list->oid.p, oid, len) == 0) {
break;
}
list = list->next;
}
return( list );
return list;
}
#endif /* MBEDTLS_ASN1_PARSE_C */

View File

@ -28,452 +28,454 @@
#include "mbedtls/platform.h"
int mbedtls_asn1_write_len( unsigned char **p, const unsigned char *start, size_t len )
int mbedtls_asn1_write_len(unsigned char **p, const unsigned char *start, size_t len)
{
if( len < 0x80 )
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (len < 0x80) {
if (*p - start < 1) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*--(*p) = (unsigned char) len;
return( 1 );
return 1;
}
if( len <= 0xFF )
{
if( *p - start < 2 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (len <= 0xFF) {
if (*p - start < 2) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*--(*p) = (unsigned char) len;
*--(*p) = 0x81;
return( 2 );
return 2;
}
if( len <= 0xFFFF )
{
if( *p - start < 3 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (len <= 0xFFFF) {
if (*p - start < 3) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*--(*p) = MBEDTLS_BYTE_0( len );
*--(*p) = MBEDTLS_BYTE_1( len );
*--(*p) = MBEDTLS_BYTE_0(len);
*--(*p) = MBEDTLS_BYTE_1(len);
*--(*p) = 0x82;
return( 3 );
return 3;
}
if( len <= 0xFFFFFF )
{
if( *p - start < 4 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (len <= 0xFFFFFF) {
if (*p - start < 4) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*--(*p) = MBEDTLS_BYTE_0( len );
*--(*p) = MBEDTLS_BYTE_1( len );
*--(*p) = MBEDTLS_BYTE_2( len );
*--(*p) = MBEDTLS_BYTE_0(len);
*--(*p) = MBEDTLS_BYTE_1(len);
*--(*p) = MBEDTLS_BYTE_2(len);
*--(*p) = 0x83;
return( 4 );
return 4;
}
int len_is_valid = 1;
#if SIZE_MAX > 0xFFFFFFFF
len_is_valid = ( len <= 0xFFFFFFFF );
len_is_valid = (len <= 0xFFFFFFFF);
#endif
if( len_is_valid )
{
if( *p - start < 5 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (len_is_valid) {
if (*p - start < 5) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*--(*p) = MBEDTLS_BYTE_0( len );
*--(*p) = MBEDTLS_BYTE_1( len );
*--(*p) = MBEDTLS_BYTE_2( len );
*--(*p) = MBEDTLS_BYTE_3( len );
*--(*p) = MBEDTLS_BYTE_0(len);
*--(*p) = MBEDTLS_BYTE_1(len);
*--(*p) = MBEDTLS_BYTE_2(len);
*--(*p) = MBEDTLS_BYTE_3(len);
*--(*p) = 0x84;
return( 5 );
return 5;
}
return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
return MBEDTLS_ERR_ASN1_INVALID_LENGTH;
}
int mbedtls_asn1_write_tag( unsigned char **p, const unsigned char *start, unsigned char tag )
int mbedtls_asn1_write_tag(unsigned char **p, const unsigned char *start, unsigned char tag)
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (*p - start < 1) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*--(*p) = tag;
return( 1 );
return 1;
}
int mbedtls_asn1_write_raw_buffer( unsigned char **p, const unsigned char *start,
const unsigned char *buf, size_t size )
int mbedtls_asn1_write_raw_buffer(unsigned char **p, const 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 );
if (*p < start || (size_t) (*p - start) < size) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
len = size;
(*p) -= len;
memcpy( *p, buf, len );
memcpy(*p, buf, len);
return( (int) len );
return (int) len;
}
#if defined(MBEDTLS_BIGNUM_C)
int mbedtls_asn1_write_mpi( unsigned char **p, const unsigned char *start, const mbedtls_mpi *X )
int mbedtls_asn1_write_mpi(unsigned char **p, const unsigned char *start, const mbedtls_mpi *X)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
// Write the MPI
//
len = mbedtls_mpi_size( X );
len = mbedtls_mpi_size(X);
/* DER represents 0 with a sign bit (0=nonnegative) and 7 value bits, not
* as 0 digits. We need to end up with 020100, not with 0200. */
if( len == 0 )
if (len == 0) {
len = 1;
}
if( *p < start || (size_t)( *p - start ) < len )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
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 ) );
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.
//
if( X->s ==1 && **p & 0x80 )
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (X->s == 1 && **p & 0x80) {
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 ) );
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 );
return ret;
}
#endif /* MBEDTLS_BIGNUM_C */
int mbedtls_asn1_write_null( unsigned char **p, const unsigned char *start )
int mbedtls_asn1_write_null(unsigned char **p, const unsigned char *start)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
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 ) );
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 );
return (int) len;
}
int mbedtls_asn1_write_oid( unsigned char **p, const unsigned char *start,
const char *oid, size_t oid_len )
int mbedtls_asn1_write_oid(unsigned char **p, const unsigned char *start,
const char *oid, size_t oid_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
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 ) );
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 );
return (int) len;
}
int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, const unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len )
int mbedtls_asn1_write_algorithm_identifier(unsigned char **p, const unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
if( par_len == 0 )
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_null( p, start ) );
else
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_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 ) );
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 );
return (int) len;
}
int mbedtls_asn1_write_bool( unsigned char **p, const unsigned char *start, int boolean )
int mbedtls_asn1_write_bool(unsigned char **p, const unsigned char *start, int boolean)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
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 ) );
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 );
return (int) len;
}
static int asn1_write_tagged_int( unsigned char **p, const unsigned char *start, int val, int tag )
static int asn1_write_tagged_int(unsigned char **p, const unsigned char *start, int val, int tag)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
do
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
do {
if (*p - start < 1) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
len += 1;
*--(*p) = val & 0xff;
val >>= 8;
}
while( val > 0 );
} while (val > 0);
if( **p & 0x80 )
{
if( *p - start < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (**p & 0x80) {
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, tag ) );
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 );
return (int) len;
}
int mbedtls_asn1_write_int( unsigned char **p, const unsigned char *start, int val )
int mbedtls_asn1_write_int(unsigned char **p, const unsigned char *start, int val)
{
return( asn1_write_tagged_int( p, start, val, MBEDTLS_ASN1_INTEGER ) );
return asn1_write_tagged_int(p, start, val, MBEDTLS_ASN1_INTEGER);
}
int mbedtls_asn1_write_enum( unsigned char **p, const unsigned char *start, int val )
int mbedtls_asn1_write_enum(unsigned char **p, const unsigned char *start, int val)
{
return( asn1_write_tagged_int( p, start, val, MBEDTLS_ASN1_ENUMERATED ) );
return asn1_write_tagged_int(p, start, val, MBEDTLS_ASN1_ENUMERATED);
}
int mbedtls_asn1_write_tagged_string( unsigned char **p, const unsigned char *start, int tag,
const char *text, size_t text_len )
int mbedtls_asn1_write_tagged_string(unsigned char **p, const unsigned char *start, int tag,
const char *text, size_t text_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
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_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 ) );
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 );
return (int) len;
}
int mbedtls_asn1_write_utf8_string( unsigned char **p, const unsigned char *start,
const char *text, size_t text_len )
int mbedtls_asn1_write_utf8_string(unsigned char **p, const unsigned char *start,
const char *text, size_t text_len)
{
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_UTF8_STRING, text, text_len) );
return mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_UTF8_STRING, text, text_len);
}
int mbedtls_asn1_write_printable_string( unsigned char **p, const unsigned char *start,
const char *text, size_t text_len )
int mbedtls_asn1_write_printable_string(unsigned char **p, const unsigned char *start,
const char *text, size_t text_len)
{
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_PRINTABLE_STRING, text, text_len) );
return mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_PRINTABLE_STRING, text,
text_len);
}
int mbedtls_asn1_write_ia5_string( unsigned char **p, const unsigned char *start,
const char *text, size_t text_len )
int mbedtls_asn1_write_ia5_string(unsigned char **p, const unsigned char *start,
const char *text, size_t text_len)
{
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_IA5_STRING, text, text_len) );
return mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_IA5_STRING, text, text_len);
}
int mbedtls_asn1_write_named_bitstring( unsigned char **p,
const unsigned char *start,
const unsigned char *buf,
size_t bits )
int mbedtls_asn1_write_named_bitstring(unsigned char **p,
const unsigned char *start,
const unsigned char *buf,
size_t bits)
{
size_t unused_bits, byte_len;
const unsigned char *cur_byte;
unsigned char cur_byte_shifted;
unsigned char bit;
byte_len = ( bits + 7 ) / 8;
unused_bits = ( byte_len * 8 ) - bits;
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 != 0) {
cur_byte = buf + byte_len - 1;
cur_byte_shifted = *cur_byte >> unused_bits;
for( ; ; )
{
for (;;) {
bit = cur_byte_shifted & 0x1;
cur_byte_shifted >>= 1;
if( bit != 0 )
if (bit != 0) {
break;
}
bits--;
if( bits == 0 )
if (bits == 0) {
break;
}
if( bits % 8 == 0 )
if (bits % 8 == 0) {
cur_byte_shifted = *--cur_byte;
}
}
}
return( mbedtls_asn1_write_bitstring( p, start, buf, bits ) );
return mbedtls_asn1_write_bitstring(p, start, buf, bits);
}
int mbedtls_asn1_write_bitstring( unsigned char **p, const unsigned char *start,
const unsigned char *buf, size_t bits )
int mbedtls_asn1_write_bitstring(unsigned char **p, const unsigned char *start,
const unsigned char *buf, size_t bits)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
size_t unused_bits, byte_len;
byte_len = ( bits + 7 ) / 8;
unused_bits = ( byte_len * 8 ) - bits;
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 );
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 )
{
if (byte_len > 0) {
byte_len--;
*--( *p ) = buf[byte_len] & ~( ( 0x1 << unused_bits ) - 1 );
( *p ) -= byte_len;
memcpy( *p, buf, byte_len );
*--(*p) = buf[byte_len] & ~((0x1 << unused_bits) - 1);
(*p) -= byte_len;
memcpy(*p, buf, byte_len);
}
/* Write unused bits */
*--( *p ) = (unsigned char)unused_bits;
*--(*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 ) );
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 );
return (int) len;
}
int mbedtls_asn1_write_octet_string( unsigned char **p, const unsigned char *start,
const unsigned char *buf, size_t size )
int mbedtls_asn1_write_octet_string(unsigned char **p, const unsigned char *start,
const unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
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_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 ) );
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 );
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 )
mbedtls_asn1_named_data *list,
const char *oid, size_t len)
{
while( list != NULL )
{
if( list->oid.len == len &&
memcmp( list->oid.p, oid, len ) == 0 )
{
while (list != NULL) {
if (list->oid.len == len &&
memcmp(list->oid.p, oid, len) == 0) {
break;
}
list = list->next;
}
return( list );
return list;
}
mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(
mbedtls_asn1_named_data **head,
const char *oid, size_t oid_len,
const unsigned char *val,
size_t val_len )
mbedtls_asn1_named_data **head,
const char *oid, size_t oid_len,
const unsigned char *val,
size_t val_len)
{
mbedtls_asn1_named_data *cur;
if( ( cur = asn1_find_named_data( *head, oid, oid_len ) ) == NULL )
{
if ((cur = asn1_find_named_data(*head, oid, oid_len)) == NULL) {
// Add new entry if not present yet based on OID
//
cur = (mbedtls_asn1_named_data*)mbedtls_calloc( 1,
sizeof(mbedtls_asn1_named_data) );
if( cur == NULL )
return( NULL );
cur->oid.len = oid_len;
cur->oid.p = mbedtls_calloc( 1, oid_len );
if( cur->oid.p == NULL )
{
mbedtls_free( cur );
return( NULL );
cur = (mbedtls_asn1_named_data *) mbedtls_calloc(1,
sizeof(mbedtls_asn1_named_data));
if (cur == NULL) {
return NULL;
}
memcpy( cur->oid.p, oid, oid_len );
cur->oid.len = oid_len;
cur->oid.p = mbedtls_calloc(1, oid_len);
if (cur->oid.p == NULL) {
mbedtls_free(cur);
return NULL;
}
memcpy(cur->oid.p, oid, oid_len);
cur->val.len = val_len;
if( val_len != 0 )
{
cur->val.p = mbedtls_calloc( 1, val_len );
if( cur->val.p == NULL )
{
mbedtls_free( cur->oid.p );
mbedtls_free( cur );
return( NULL );
if (val_len != 0) {
cur->val.p = mbedtls_calloc(1, val_len);
if (cur->val.p == NULL) {
mbedtls_free(cur->oid.p);
mbedtls_free(cur);
return NULL;
}
}
cur->next = *head;
*head = cur;
}
else if( val_len == 0 )
{
mbedtls_free( cur->val.p );
} else if (val_len == 0) {
mbedtls_free(cur->val.p);
cur->val.p = NULL;
}
else if( cur->val.len != val_len )
{
} else if (cur->val.len != val_len) {
/*
* Enlarge existing value buffer if needed
* Preserve old data until the allocation succeeded, to leave list in
* a consistent state in case allocation fails.
*/
void *p = mbedtls_calloc( 1, val_len );
if( p == NULL )
return( NULL );
void *p = mbedtls_calloc(1, val_len);
if (p == NULL) {
return NULL;
}
mbedtls_free( cur->val.p );
mbedtls_free(cur->val.p);
cur->val.p = p;
cur->val.len = val_len;
}
if( val != NULL && val_len != 0 )
memcpy( cur->val.p, val, val_len );
if (val != NULL && val_len != 0) {
memcpy(cur->val.p, val, val_len);
}
return( cur );
return cur;
}
#endif /* MBEDTLS_ASN1_WRITE_C */

View File

@ -31,68 +31,65 @@
#include "mbedtls/platform.h"
#endif /* MBEDTLS_SELF_TEST */
#define BASE64_SIZE_T_MAX ( (size_t) -1 ) /* SIZE_T_MAX is not standard */
#define BASE64_SIZE_T_MAX ((size_t) -1) /* SIZE_T_MAX is not standard */
/*
* Encode a buffer into base64 format
*/
int mbedtls_base64_encode( unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen )
int mbedtls_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen)
{
size_t i, n;
int C1, C2, C3;
unsigned char *p;
if( slen == 0 )
{
if (slen == 0) {
*olen = 0;
return( 0 );
return 0;
}
n = slen / 3 + ( slen % 3 != 0 );
n = slen / 3 + (slen % 3 != 0);
if( n > ( BASE64_SIZE_T_MAX - 1 ) / 4 )
{
if (n > (BASE64_SIZE_T_MAX - 1) / 4) {
*olen = BASE64_SIZE_T_MAX;
return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
return MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL;
}
n *= 4;
if( ( dlen < n + 1 ) || ( NULL == dst ) )
{
if ((dlen < n + 1) || (NULL == dst)) {
*olen = n + 1;
return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
return MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL;
}
n = ( slen / 3 ) * 3;
n = (slen / 3) * 3;
for( i = 0, p = dst; i < n; i += 3 )
{
for (i = 0, p = dst; i < n; i += 3) {
C1 = *src++;
C2 = *src++;
C3 = *src++;
*p++ = mbedtls_ct_base64_enc_char( ( C1 >> 2 ) & 0x3F );
*p++ = mbedtls_ct_base64_enc_char( ( ( ( C1 & 3 ) << 4 ) + ( C2 >> 4 ) )
& 0x3F );
*p++ = mbedtls_ct_base64_enc_char( ( ( ( C2 & 15 ) << 2 ) + ( C3 >> 6 ) )
& 0x3F );
*p++ = mbedtls_ct_base64_enc_char( C3 & 0x3F );
*p++ = mbedtls_ct_base64_enc_char((C1 >> 2) & 0x3F);
*p++ = mbedtls_ct_base64_enc_char((((C1 & 3) << 4) + (C2 >> 4))
& 0x3F);
*p++ = mbedtls_ct_base64_enc_char((((C2 & 15) << 2) + (C3 >> 6))
& 0x3F);
*p++ = mbedtls_ct_base64_enc_char(C3 & 0x3F);
}
if( i < slen )
{
if (i < slen) {
C1 = *src++;
C2 = ( ( i + 1 ) < slen ) ? *src++ : 0;
C2 = ((i + 1) < slen) ? *src++ : 0;
*p++ = mbedtls_ct_base64_enc_char( ( C1 >> 2 ) & 0x3F );
*p++ = mbedtls_ct_base64_enc_char( ( ( ( C1 & 3 ) << 4 ) + ( C2 >> 4 ) )
& 0x3F );
*p++ = mbedtls_ct_base64_enc_char((C1 >> 2) & 0x3F);
*p++ = mbedtls_ct_base64_enc_char((((C1 & 3) << 4) + (C2 >> 4))
& 0x3F);
if( ( i + 1 ) < slen )
*p++ = mbedtls_ct_base64_enc_char( ( ( C2 & 15 ) << 2 ) & 0x3F );
else *p++ = '=';
if ((i + 1) < slen) {
*p++ = mbedtls_ct_base64_enc_char(((C2 & 15) << 2) & 0x3F);
} else {
*p++ = '=';
}
*p++ = '=';
}
@ -100,14 +97,14 @@ int mbedtls_base64_encode( unsigned char *dst, size_t dlen, size_t *olen,
*olen = p - dst;
*p = 0;
return( 0 );
return 0;
}
/*
* Decode a base64-formatted buffer
*/
int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen )
int mbedtls_base64_decode(unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen)
{
size_t i; /* index in source */
size_t n; /* number of digits or trailing = in source */
@ -118,92 +115,97 @@ int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
unsigned char *p;
/* First pass: check for validity and get output length */
for( i = n = 0; i < slen; i++ )
{
for (i = n = 0; i < slen; i++) {
/* Skip spaces before checking for EOL */
spaces_present = 0;
while( i < slen && src[i] == ' ' )
{
while (i < slen && src[i] == ' ') {
++i;
spaces_present = 1;
}
/* Spaces at end of buffer are OK */
if( i == slen )
if (i == slen) {
break;
}
if( ( slen - i ) >= 2 &&
src[i] == '\r' && src[i + 1] == '\n' )
if ((slen - i) >= 2 &&
src[i] == '\r' && src[i + 1] == '\n') {
continue;
}
if( src[i] == '\n' )
if (src[i] == '\n') {
continue;
}
/* Space inside a line is an error */
if( spaces_present )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( src[i] > 127 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( src[i] == '=' )
{
if( ++equals > 2 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if (spaces_present) {
return MBEDTLS_ERR_BASE64_INVALID_CHARACTER;
}
else
{
if( equals != 0 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( mbedtls_ct_base64_dec_value( src[i] ) < 0 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if (src[i] > 127) {
return MBEDTLS_ERR_BASE64_INVALID_CHARACTER;
}
if (src[i] == '=') {
if (++equals > 2) {
return MBEDTLS_ERR_BASE64_INVALID_CHARACTER;
}
} else {
if (equals != 0) {
return MBEDTLS_ERR_BASE64_INVALID_CHARACTER;
}
if (mbedtls_ct_base64_dec_value(src[i]) < 0) {
return MBEDTLS_ERR_BASE64_INVALID_CHARACTER;
}
}
n++;
}
if( n == 0 )
{
if (n == 0) {
*olen = 0;
return( 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 = (6 * (n >> 3)) + ((6 * (n & 0x7) + 7) >> 3);
n -= equals;
if( dst == NULL || dlen < n )
{
if (dst == NULL || dlen < n) {
*olen = n;
return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
return MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL;
}
equals = 0;
for( x = 0, p = dst; i > 0; i--, src++ )
{
if( *src == '\r' || *src == '\n' || *src == ' ' )
for (x = 0, p = dst; i > 0; i--, src++) {
if (*src == '\r' || *src == '\n' || *src == ' ') {
continue;
}
x = x << 6;
if( *src == '=' )
if (*src == '=') {
++equals;
else
x |= mbedtls_ct_base64_dec_value( *src );
} else {
x |= mbedtls_ct_base64_dec_value(*src);
}
if( ++accumulated_digits == 4 )
{
if (++accumulated_digits == 4) {
accumulated_digits = 0;
*p++ = MBEDTLS_BYTE_2( x );
if( equals <= 1 ) *p++ = MBEDTLS_BYTE_1( x );
if( equals <= 0 ) *p++ = MBEDTLS_BYTE_0( x );
*p++ = MBEDTLS_BYTE_2(x);
if (equals <= 1) {
*p++ = MBEDTLS_BYTE_1(x);
}
if (equals <= 0) {
*p++ = MBEDTLS_BYTE_0(x);
}
}
}
*olen = p - dst;
return( 0 );
return 0;
}
#if defined(MBEDTLS_SELF_TEST)
@ -227,44 +229,47 @@ static const unsigned char base64_test_enc[] =
/*
* Checkup routine
*/
int mbedtls_base64_self_test( int verbose )
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: " );
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" );
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 );
return 1;
}
if( verbose != 0 )
mbedtls_printf( "passed\n Base64 decoding test: " );
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" );
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 );
return 1;
}
if( verbose != 0 )
mbedtls_printf( "passed\n\n" );
if (verbose != 0) {
mbedtls_printf("passed\n\n");
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_SELF_TEST */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -86,19 +86,19 @@
#include "mbedtls/bignum.h"
#endif
#define ciL ( sizeof(mbedtls_mpi_uint) ) /** chars in limb */
#define biL ( ciL << 3 ) /** bits in limb */
#define biH ( ciL << 2 ) /** half limb size */
#define ciL (sizeof(mbedtls_mpi_uint)) /** chars in limb */
#define biL (ciL << 3) /** bits in limb */
#define biH (ciL << 2) /** half limb size */
/*
* 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 ) )
#define BITS_TO_LIMBS(i) ((i) / biL + ((i) % biL != 0))
#define CHARS_TO_LIMBS(i) ((i) / ciL + ((i) % ciL != 0))
/* Get a specific byte, without range checks. */
#define GET_BYTE( X, i ) \
( ( (X)[(i) / ciL] >> ( ( (i) % ciL ) * 8 ) ) & 0xff )
#define GET_BYTE(X, i) \
(((X)[(i) / ciL] >> (((i) % ciL) * 8)) & 0xff)
/** Count leading zero bits in a given integer.
*
@ -106,7 +106,7 @@
*
* \return The number of leading zero bits in \p a.
*/
size_t mbedtls_mpi_core_clz( mbedtls_mpi_uint a );
size_t mbedtls_mpi_core_clz(mbedtls_mpi_uint a);
/** Return the minimum number of bits required to represent the value held
* in the MPI.
@ -118,7 +118,7 @@ size_t mbedtls_mpi_core_clz( mbedtls_mpi_uint a );
*
* \return The number of bits in \p A.
*/
size_t mbedtls_mpi_core_bitlen( const mbedtls_mpi_uint *A, size_t A_limbs );
size_t mbedtls_mpi_core_bitlen(const mbedtls_mpi_uint *A, size_t A_limbs);
/** Convert a big-endian byte array aligned to the size of mbedtls_mpi_uint
* into the storage form used by mbedtls_mpi.
@ -126,8 +126,8 @@ size_t mbedtls_mpi_core_bitlen( const mbedtls_mpi_uint *A, size_t A_limbs );
* \param[in,out] A The address of the MPI.
* \param A_limbs The number of limbs of \p A.
*/
void mbedtls_mpi_core_bigendian_to_host( mbedtls_mpi_uint *A,
size_t A_limbs );
void mbedtls_mpi_core_bigendian_to_host(mbedtls_mpi_uint *A,
size_t A_limbs);
/** \brief Compare a machine integer with an MPI.
*
@ -141,9 +141,9 @@ void mbedtls_mpi_core_bigendian_to_host( mbedtls_mpi_uint *A,
*
* \return 1 if \p min is less than or equal to \p A, otherwise 0.
*/
unsigned mbedtls_mpi_core_uint_le_mpi( mbedtls_mpi_uint min,
const mbedtls_mpi_uint *A,
size_t A_limbs );
unsigned mbedtls_mpi_core_uint_le_mpi(mbedtls_mpi_uint min,
const mbedtls_mpi_uint *A,
size_t A_limbs);
/**
* \brief Perform a safe conditional copy of an MPI which doesn't reveal
@ -166,10 +166,10 @@ unsigned mbedtls_mpi_core_uint_le_mpi( mbedtls_mpi_uint min,
* is indeterminate, and the resulting value in \p X might be
* neither its original value nor the value in \p A.
*/
void mbedtls_mpi_core_cond_assign( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
size_t limbs,
unsigned char assign );
void mbedtls_mpi_core_cond_assign(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
size_t limbs,
unsigned char assign);
/**
* \brief Perform a safe conditional swap of two MPIs which doesn't reveal
@ -192,10 +192,10 @@ void mbedtls_mpi_core_cond_assign( mbedtls_mpi_uint *X,
* is indeterminate, and both \p X and \p Y might end up with
* values different to either of the original ones.
*/
void mbedtls_mpi_core_cond_swap( mbedtls_mpi_uint *X,
mbedtls_mpi_uint *Y,
size_t limbs,
unsigned char swap );
void mbedtls_mpi_core_cond_swap(mbedtls_mpi_uint *X,
mbedtls_mpi_uint *Y,
size_t limbs,
unsigned char swap);
/** Import X from unsigned binary data, little-endian.
*
@ -211,10 +211,10 @@ void mbedtls_mpi_core_cond_swap( mbedtls_mpi_uint *X,
* \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p X isn't
* large enough to hold the value in \p input.
*/
int mbedtls_mpi_core_read_le( mbedtls_mpi_uint *X,
size_t X_limbs,
const unsigned char *input,
size_t input_length );
int mbedtls_mpi_core_read_le(mbedtls_mpi_uint *X,
size_t X_limbs,
const unsigned char *input,
size_t input_length);
/** Import X from unsigned binary data, big-endian.
*
@ -233,10 +233,10 @@ int mbedtls_mpi_core_read_le( mbedtls_mpi_uint *X,
* \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p X isn't
* large enough to hold the value in \p input.
*/
int mbedtls_mpi_core_read_be( mbedtls_mpi_uint *X,
size_t X_limbs,
const unsigned char *input,
size_t input_length );
int mbedtls_mpi_core_read_be(mbedtls_mpi_uint *X,
size_t X_limbs,
const unsigned char *input,
size_t input_length);
/** Export A into unsigned binary data, little-endian.
*
@ -253,10 +253,10 @@ int mbedtls_mpi_core_read_be( mbedtls_mpi_uint *X,
* \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p output isn't
* large enough to hold the value of \p A.
*/
int mbedtls_mpi_core_write_le( const mbedtls_mpi_uint *A,
size_t A_limbs,
unsigned char *output,
size_t output_length );
int mbedtls_mpi_core_write_le(const mbedtls_mpi_uint *A,
size_t A_limbs,
unsigned char *output,
size_t output_length);
/** Export A into unsigned binary data, big-endian.
*
@ -273,10 +273,10 @@ int mbedtls_mpi_core_write_le( const mbedtls_mpi_uint *A,
* \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p output isn't
* large enough to hold the value of \p A.
*/
int mbedtls_mpi_core_write_be( const mbedtls_mpi_uint *A,
size_t A_limbs,
unsigned char *output,
size_t output_length );
int mbedtls_mpi_core_write_be(const mbedtls_mpi_uint *A,
size_t A_limbs,
unsigned char *output,
size_t output_length);
/** \brief Shift an MPI right in place by a number of bits.
*
@ -290,8 +290,8 @@ int mbedtls_mpi_core_write_be( const mbedtls_mpi_uint *A,
* \param limbs The number of limbs of \p X. This must be at least 1.
* \param count The number of bits to shift by.
*/
void mbedtls_mpi_core_shift_r( mbedtls_mpi_uint *X, size_t limbs,
size_t count );
void mbedtls_mpi_core_shift_r(mbedtls_mpi_uint *X, size_t limbs,
size_t count);
/**
* \brief Add two fixed-size large unsigned integers, returning the carry.
@ -310,10 +310,10 @@ void mbedtls_mpi_core_shift_r( mbedtls_mpi_uint *X, size_t limbs,
*
* \return 1 if `A + B >= 2^(biL*limbs)`, 0 otherwise.
*/
mbedtls_mpi_uint mbedtls_mpi_core_add( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
size_t limbs );
mbedtls_mpi_uint mbedtls_mpi_core_add(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
size_t limbs);
/**
* \brief Conditional addition of two fixed-size large unsigned integers,
@ -345,10 +345,10 @@ mbedtls_mpi_uint mbedtls_mpi_core_add( mbedtls_mpi_uint *X,
*
* \return 1 if `X + cond * A >= 2^(biL*limbs)`, 0 otherwise.
*/
mbedtls_mpi_uint mbedtls_mpi_core_add_if( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
size_t limbs,
unsigned cond );
mbedtls_mpi_uint mbedtls_mpi_core_add_if(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
size_t limbs,
unsigned cond);
/**
* \brief Subtract two fixed-size large unsigned integers, returning the borrow.
@ -368,10 +368,10 @@ mbedtls_mpi_uint mbedtls_mpi_core_add_if( mbedtls_mpi_uint *X,
* \return 1 if `A < B`.
* 0 if `A >= B`.
*/
mbedtls_mpi_uint mbedtls_mpi_core_sub( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
size_t limbs );
mbedtls_mpi_uint mbedtls_mpi_core_sub(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
size_t limbs);
/**
* \brief Perform a fixed-size multiply accumulate operation: X += b * A
@ -394,9 +394,9 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub( mbedtls_mpi_uint *X,
*
* \return The carry at the end of the operation.
*/
mbedtls_mpi_uint mbedtls_mpi_core_mla( mbedtls_mpi_uint *X, size_t X_limbs,
const mbedtls_mpi_uint *A, size_t A_limbs,
mbedtls_mpi_uint b );
mbedtls_mpi_uint mbedtls_mpi_core_mla(mbedtls_mpi_uint *X, size_t X_limbs,
const mbedtls_mpi_uint *A, size_t A_limbs,
mbedtls_mpi_uint b);
/**
* \brief Calculate initialisation value for fast Montgomery modular
@ -407,7 +407,7 @@ mbedtls_mpi_uint mbedtls_mpi_core_mla( mbedtls_mpi_uint *X, size_t X_limbs,
*
* \return The initialisation value for fast Montgomery modular multiplication
*/
mbedtls_mpi_uint mbedtls_mpi_core_montmul_init( const mbedtls_mpi_uint *N );
mbedtls_mpi_uint mbedtls_mpi_core_montmul_init(const mbedtls_mpi_uint *N);
/**
* \brief Montgomery multiplication: X = A * B * R^-1 mod N (HAC 14.36)
@ -444,11 +444,11 @@ mbedtls_mpi_uint mbedtls_mpi_core_montmul_init( const mbedtls_mpi_uint *N );
* It must not alias or otherwise overlap any of the
* other parameters.
*/
void mbedtls_mpi_core_montmul( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B, size_t B_limbs,
const mbedtls_mpi_uint *N, size_t AN_limbs,
mbedtls_mpi_uint mm, mbedtls_mpi_uint *T );
void mbedtls_mpi_core_montmul(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B, size_t B_limbs,
const mbedtls_mpi_uint *N, size_t AN_limbs,
mbedtls_mpi_uint mm, mbedtls_mpi_uint *T);
/**
* \brief Calculate the square of the Montgomery constant. (Needed
@ -465,8 +465,8 @@ void mbedtls_mpi_core_montmul( mbedtls_mpi_uint *X,
* \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p N modulus is zero.
* \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p N modulus is negative.
*/
int mbedtls_mpi_core_get_mont_r2_unsafe( mbedtls_mpi *X,
const mbedtls_mpi *N );
int mbedtls_mpi_core_get_mont_r2_unsafe(mbedtls_mpi *X,
const mbedtls_mpi *N);
#if defined(MBEDTLS_TEST_HOOKS)
/**
@ -481,11 +481,11 @@ int mbedtls_mpi_core_get_mont_r2_unsafe( mbedtls_mpi *X,
* \param index The (secret) table index to look up. This must be in the
* range `0 .. count-1`.
*/
void mbedtls_mpi_core_ct_uint_table_lookup( mbedtls_mpi_uint *dest,
const mbedtls_mpi_uint *table,
size_t limbs,
size_t count,
size_t index );
void mbedtls_mpi_core_ct_uint_table_lookup(mbedtls_mpi_uint *dest,
const mbedtls_mpi_uint *table,
size_t limbs,
size_t count,
size_t index);
#endif /* MBEDTLS_TEST_HOOKS */
/**
@ -507,10 +507,10 @@ void mbedtls_mpi_core_ct_uint_table_lookup( mbedtls_mpi_uint *dest,
* as a big-endian representation of an MPI; this can
* be relevant in applications like deterministic ECDSA.
*/
int mbedtls_mpi_core_fill_random( mbedtls_mpi_uint *X, size_t X_limbs,
size_t bytes,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int mbedtls_mpi_core_fill_random(mbedtls_mpi_uint *X, size_t X_limbs,
size_t bytes,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
/** Generate a random number uniformly in a range.
*
@ -542,12 +542,12 @@ int mbedtls_mpi_core_fill_random( mbedtls_mpi_uint *X, size_t X_limbs,
* is significantly larger than \p min, which is the case
* for all usual cryptographic applications.
*/
int mbedtls_mpi_core_random( mbedtls_mpi_uint *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_uint *N,
size_t limbs,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int mbedtls_mpi_core_random(mbedtls_mpi_uint *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_uint *N,
size_t limbs,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
/* BEGIN MERGE SLOT 1 */
@ -568,7 +568,7 @@ int mbedtls_mpi_core_random( mbedtls_mpi_uint *X,
* \return The number of limbs of working memory required by
* `mbedtls_mpi_core_exp_mod()`.
*/
size_t mbedtls_mpi_core_exp_mod_working_limbs( size_t AN_limbs, size_t E_limbs );
size_t mbedtls_mpi_core_exp_mod_working_limbs(size_t AN_limbs, size_t E_limbs);
/**
* \brief Perform a modular exponentiation with secret exponent:
@ -597,12 +597,12 @@ size_t mbedtls_mpi_core_exp_mod_working_limbs( size_t AN_limbs, size_t E_limbs )
* longer needed, and before freeing it if it was dynamically
* allocated.
*/
void mbedtls_mpi_core_exp_mod( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N, size_t AN_limbs,
const mbedtls_mpi_uint *E, size_t E_limbs,
const mbedtls_mpi_uint *RR,
mbedtls_mpi_uint *T );
void mbedtls_mpi_core_exp_mod(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N, size_t AN_limbs,
const mbedtls_mpi_uint *E, size_t E_limbs,
const mbedtls_mpi_uint *RR,
mbedtls_mpi_uint *T);
/* END MERGE SLOT 1 */
@ -624,10 +624,10 @@ void mbedtls_mpi_core_exp_mod( mbedtls_mpi_uint *X,
* \return 1 if `A < b`.
* 0 if `A >= b`.
*/
mbedtls_mpi_uint mbedtls_mpi_core_sub_int( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
mbedtls_mpi_uint b,
size_t limbs );
mbedtls_mpi_uint mbedtls_mpi_core_sub_int(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
mbedtls_mpi_uint b,
size_t limbs);
/**
* \brief Determine if a given MPI has the value \c 0 in constant time with
@ -639,8 +639,8 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub_int( mbedtls_mpi_uint *X,
* \return 0 if `A == 0`
* non-0 (may be any value) if `A != 0`.
*/
mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct( const mbedtls_mpi_uint *A,
size_t limbs );
mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,
size_t limbs);
/**
* \brief Returns the number of limbs of working memory required for
@ -654,9 +654,9 @@ mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct( const mbedtls_mpi_uint *A,
* \return The number of limbs of working memory required by
* `mbedtls_mpi_core_montmul()` (or other similar function).
*/
static inline size_t mbedtls_mpi_core_montmul_working_limbs( size_t AN_limbs )
static inline size_t mbedtls_mpi_core_montmul_working_limbs(size_t AN_limbs)
{
return( 2 * AN_limbs + 1 );
return 2 * AN_limbs + 1;
}
/** Convert an MPI into Montgomery form.
@ -690,13 +690,13 @@ static inline size_t mbedtls_mpi_core_montmul_working_limbs( size_t AN_limbs )
* It must not alias or otherwise overlap any of the
* other parameters.
*/
void mbedtls_mpi_core_to_mont_rep( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
mbedtls_mpi_uint mm,
const mbedtls_mpi_uint *rr,
mbedtls_mpi_uint *T );
void mbedtls_mpi_core_to_mont_rep(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
mbedtls_mpi_uint mm,
const mbedtls_mpi_uint *rr,
mbedtls_mpi_uint *T);
/** Convert an MPI from Montgomery form.
*
@ -727,12 +727,12 @@ void mbedtls_mpi_core_to_mont_rep( mbedtls_mpi_uint *X,
* It must not alias or otherwise overlap any of the
* other parameters.
*/
void mbedtls_mpi_core_from_mont_rep( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
mbedtls_mpi_uint mm,
mbedtls_mpi_uint *T );
void mbedtls_mpi_core_from_mont_rep(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
mbedtls_mpi_uint mm,
mbedtls_mpi_uint *T);
/* END MERGE SLOT 3 */

View File

@ -34,33 +34,36 @@
#include "bignum_mod_raw.h"
#include "constant_time_internal.h"
int mbedtls_mpi_mod_residue_setup( mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
mbedtls_mpi_uint *p,
size_t p_limbs )
int mbedtls_mpi_mod_residue_setup(mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
mbedtls_mpi_uint *p,
size_t p_limbs)
{
if( p_limbs != m->limbs || !mbedtls_mpi_core_lt_ct( p, m->p, m->limbs ) )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (p_limbs != m->limbs || !mbedtls_mpi_core_lt_ct(p, m->p, m->limbs)) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
r->limbs = m->limbs;
r->p = p;
return( 0 );
return 0;
}
void mbedtls_mpi_mod_residue_release( mbedtls_mpi_mod_residue *r )
void mbedtls_mpi_mod_residue_release(mbedtls_mpi_mod_residue *r)
{
if( r == NULL )
if (r == NULL) {
return;
}
r->limbs = 0;
r->p = NULL;
}
void mbedtls_mpi_mod_modulus_init( mbedtls_mpi_mod_modulus *m )
void mbedtls_mpi_mod_modulus_init(mbedtls_mpi_mod_modulus *m)
{
if( m == NULL )
if (m == NULL) {
return;
}
m->p = NULL;
m->limbs = 0;
@ -68,25 +71,24 @@ void mbedtls_mpi_mod_modulus_init( mbedtls_mpi_mod_modulus *m )
m->int_rep = MBEDTLS_MPI_MOD_REP_INVALID;
}
void mbedtls_mpi_mod_modulus_free( mbedtls_mpi_mod_modulus *m )
void mbedtls_mpi_mod_modulus_free(mbedtls_mpi_mod_modulus *m)
{
if( m == NULL )
if (m == NULL) {
return;
}
switch( m->int_rep )
{
switch (m->int_rep) {
case MBEDTLS_MPI_MOD_REP_MONTGOMERY:
if (m->rep.mont.rr != NULL)
{
mbedtls_platform_zeroize( (mbedtls_mpi_uint *) m->rep.mont.rr,
m->limbs * sizeof(mbedtls_mpi_uint) );
mbedtls_free( (mbedtls_mpi_uint *)m->rep.mont.rr );
if (m->rep.mont.rr != NULL) {
mbedtls_platform_zeroize((mbedtls_mpi_uint *) m->rep.mont.rr,
m->limbs * sizeof(mbedtls_mpi_uint));
mbedtls_free((mbedtls_mpi_uint *) m->rep.mont.rr);
m->rep.mont.rr = NULL;
}
m->rep.mont.mm = 0;
break;
case MBEDTLS_MPI_MOD_REP_OPT_RED:
mbedtls_free( m->rep.ored );
mbedtls_free(m->rep.ored);
break;
case MBEDTLS_MPI_MOD_REP_INVALID:
break;
@ -98,30 +100,31 @@ void mbedtls_mpi_mod_modulus_free( mbedtls_mpi_mod_modulus *m )
m->int_rep = MBEDTLS_MPI_MOD_REP_INVALID;
}
static int set_mont_const_square( const mbedtls_mpi_uint **X,
const mbedtls_mpi_uint *A,
size_t limbs )
static int set_mont_const_square(const mbedtls_mpi_uint **X,
const mbedtls_mpi_uint *A,
size_t limbs)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi N;
mbedtls_mpi RR;
*X = NULL;
mbedtls_mpi_init( &N );
mbedtls_mpi_init( &RR );
mbedtls_mpi_init(&N);
mbedtls_mpi_init(&RR);
if( A == NULL || limbs == 0 || limbs >= ( MBEDTLS_MPI_MAX_LIMBS / 2 ) - 2 )
if (A == NULL || limbs == 0 || limbs >= (MBEDTLS_MPI_MAX_LIMBS / 2) - 2) {
goto cleanup;
}
if( mbedtls_mpi_grow( &N, limbs ) )
if (mbedtls_mpi_grow(&N, limbs)) {
goto cleanup;
}
memcpy( N.p, A, sizeof(mbedtls_mpi_uint) * limbs );
memcpy(N.p, A, sizeof(mbedtls_mpi_uint) * limbs);
ret = mbedtls_mpi_core_get_mont_r2_unsafe(&RR, &N);
if( ret == 0 )
{
if (ret == 0) {
*X = RR.p;
RR.p = NULL;
}
@ -129,27 +132,26 @@ static int set_mont_const_square( const mbedtls_mpi_uint **X,
cleanup:
mbedtls_mpi_free(&N);
mbedtls_mpi_free(&RR);
ret = ( ret != 0 ) ? MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED : 0;
return( ret );
ret = (ret != 0) ? MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED : 0;
return ret;
}
int mbedtls_mpi_mod_modulus_setup( mbedtls_mpi_mod_modulus *m,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_mod_rep_selector int_rep )
int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *m,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_mod_rep_selector int_rep)
{
int ret = 0;
m->p = p;
m->limbs = p_limbs;
m->bits = mbedtls_mpi_core_bitlen( p, p_limbs );
m->bits = mbedtls_mpi_core_bitlen(p, p_limbs);
switch( int_rep )
{
switch (int_rep) {
case MBEDTLS_MPI_MOD_REP_MONTGOMERY:
m->int_rep = int_rep;
m->rep.mont.mm = mbedtls_mpi_core_montmul_init( m->p );
ret = set_mont_const_square( &m->rep.mont.rr, m->p, m->limbs );
m->rep.mont.mm = mbedtls_mpi_core_montmul_init(m->p);
ret = set_mont_const_square(&m->rep.mont.rr, m->p, m->limbs);
break;
case MBEDTLS_MPI_MOD_REP_OPT_RED:
m->int_rep = int_rep;
@ -162,12 +164,11 @@ int mbedtls_mpi_mod_modulus_setup( mbedtls_mpi_mod_modulus *m,
exit:
if( ret != 0 )
{
mbedtls_mpi_mod_modulus_free( m );
if (ret != 0) {
mbedtls_mpi_mod_modulus_free(m);
}
return( ret );
return ret;
}
/* BEGIN MERGE SLOT 1 */
@ -176,129 +177,135 @@ exit:
/* BEGIN MERGE SLOT 2 */
int mbedtls_mpi_mod_mul( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N )
int mbedtls_mpi_mod_mul(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N)
{
if( N->limbs == 0 )
if (N->limbs == 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
if( X->limbs != N->limbs || A->limbs != N->limbs || B->limbs != N->limbs )
if (X->limbs != N->limbs || A->limbs != N->limbs || B->limbs != N->limbs) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
mbedtls_mpi_uint *T = mbedtls_calloc( N->limbs * 2 + 1, ciL );
if( T == NULL )
mbedtls_mpi_uint *T = mbedtls_calloc(N->limbs * 2 + 1, ciL);
if (T == NULL) {
return MBEDTLS_ERR_MPI_ALLOC_FAILED;
}
mbedtls_mpi_mod_raw_mul( X->p, A->p, B->p, N, T );
mbedtls_mpi_mod_raw_mul(X->p, A->p, B->p, N, T);
mbedtls_free( T );
mbedtls_free(T);
return( 0 );
return 0;
}
/* END MERGE SLOT 2 */
/* BEGIN MERGE SLOT 3 */
int mbedtls_mpi_mod_sub( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N )
int mbedtls_mpi_mod_sub(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N)
{
if( X->limbs != N->limbs || A->limbs != N->limbs || B->limbs != N->limbs )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (X->limbs != N->limbs || A->limbs != N->limbs || B->limbs != N->limbs) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
mbedtls_mpi_mod_raw_sub( X->p, A->p, B->p, N );
mbedtls_mpi_mod_raw_sub(X->p, A->p, B->p, N);
return( 0 );
return 0;
}
static int mbedtls_mpi_mod_inv_mont( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *working_memory )
static int mbedtls_mpi_mod_inv_mont(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *working_memory)
{
/* Input already in Montgomery form, so there's little to do */
mbedtls_mpi_mod_raw_inv_prime( X->p, A->p,
N->p, N->limbs,
N->rep.mont.rr,
working_memory );
return( 0 );
mbedtls_mpi_mod_raw_inv_prime(X->p, A->p,
N->p, N->limbs,
N->rep.mont.rr,
working_memory);
return 0;
}
static int mbedtls_mpi_mod_inv_non_mont( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *working_memory )
static int mbedtls_mpi_mod_inv_non_mont(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *working_memory)
{
/* Need to convert input into Montgomery form */
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi_mod_modulus Nmont;
mbedtls_mpi_mod_modulus_init( &Nmont );
mbedtls_mpi_mod_modulus_init(&Nmont);
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_modulus_setup( &Nmont, N->p, N->limbs,
MBEDTLS_MPI_MOD_REP_MONTGOMERY ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_modulus_setup(&Nmont, N->p, N->limbs,
MBEDTLS_MPI_MOD_REP_MONTGOMERY));
/* We'll use X->p to hold the Montgomery form of the input A->p */
mbedtls_mpi_core_to_mont_rep( X->p, A->p, Nmont.p, Nmont.limbs,
Nmont.rep.mont.mm, Nmont.rep.mont.rr,
working_memory );
mbedtls_mpi_core_to_mont_rep(X->p, A->p, Nmont.p, Nmont.limbs,
Nmont.rep.mont.mm, Nmont.rep.mont.rr,
working_memory);
mbedtls_mpi_mod_raw_inv_prime( X->p, X->p,
Nmont.p, Nmont.limbs,
Nmont.rep.mont.rr,
working_memory );
mbedtls_mpi_mod_raw_inv_prime(X->p, X->p,
Nmont.p, Nmont.limbs,
Nmont.rep.mont.rr,
working_memory);
/* And convert back from Montgomery form */
mbedtls_mpi_core_from_mont_rep( X->p, X->p, Nmont.p, Nmont.limbs,
Nmont.rep.mont.mm, working_memory );
mbedtls_mpi_core_from_mont_rep(X->p, X->p, Nmont.p, Nmont.limbs,
Nmont.rep.mont.mm, working_memory);
cleanup:
mbedtls_mpi_mod_modulus_free( &Nmont );
return( ret );
mbedtls_mpi_mod_modulus_free(&Nmont);
return ret;
}
int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N )
int mbedtls_mpi_mod_inv(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N)
{
if( X->limbs != N->limbs || A->limbs != N->limbs )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (X->limbs != N->limbs || A->limbs != N->limbs) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
/* Zero has the same value regardless of Montgomery form or not */
if( mbedtls_mpi_core_check_zero_ct( A->p, A->limbs ) == 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (mbedtls_mpi_core_check_zero_ct(A->p, A->limbs) == 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
size_t working_limbs =
mbedtls_mpi_mod_raw_inv_prime_working_limbs( N->limbs );
mbedtls_mpi_mod_raw_inv_prime_working_limbs(N->limbs);
mbedtls_mpi_uint *working_memory = mbedtls_calloc( working_limbs,
sizeof(mbedtls_mpi_uint) );
if( working_memory == NULL )
return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
mbedtls_mpi_uint *working_memory = mbedtls_calloc(working_limbs,
sizeof(mbedtls_mpi_uint));
if (working_memory == NULL) {
return MBEDTLS_ERR_MPI_ALLOC_FAILED;
}
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
switch( N->int_rep )
{
switch (N->int_rep) {
case MBEDTLS_MPI_MOD_REP_MONTGOMERY:
ret = mbedtls_mpi_mod_inv_mont( X, A, N, working_memory );
ret = mbedtls_mpi_mod_inv_mont(X, A, N, working_memory);
break;
case MBEDTLS_MPI_MOD_REP_OPT_RED:
ret = mbedtls_mpi_mod_inv_non_mont( X, A, N, working_memory );
ret = mbedtls_mpi_mod_inv_non_mont(X, A, N, working_memory);
break;
default:
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
break;
}
mbedtls_platform_zeroize( working_memory,
working_limbs * sizeof(mbedtls_mpi_uint) );
mbedtls_free( working_memory );
mbedtls_platform_zeroize(working_memory,
working_limbs * sizeof(mbedtls_mpi_uint));
mbedtls_free(working_memory);
return ret;
}
@ -309,99 +316,106 @@ int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X,
/* END MERGE SLOT 4 */
/* BEGIN MERGE SLOT 5 */
int mbedtls_mpi_mod_add( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N )
int mbedtls_mpi_mod_add(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N)
{
if( X->limbs != N->limbs || A->limbs != N->limbs || B->limbs != N->limbs )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (X->limbs != N->limbs || A->limbs != N->limbs || B->limbs != N->limbs) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
mbedtls_mpi_mod_raw_add(X->p, A->p, B->p, N);
return( 0 );
return 0;
}
/* END MERGE SLOT 5 */
/* BEGIN MERGE SLOT 6 */
int mbedtls_mpi_mod_random( mbedtls_mpi_mod_residue *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_mpi_mod_random(mbedtls_mpi_mod_residue *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
if( X->limbs != N->limbs )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
return( mbedtls_mpi_mod_raw_random( X->p, min, N, f_rng, p_rng ) );
if (X->limbs != N->limbs) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
return mbedtls_mpi_mod_raw_random(X->p, min, N, f_rng, p_rng);
}
/* END MERGE SLOT 6 */
/* BEGIN MERGE SLOT 7 */
int mbedtls_mpi_mod_read( mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep )
int mbedtls_mpi_mod_read(mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep)
{
int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
/* Do our best to check if r and m have been set up */
if( r->limbs == 0 || m->limbs == 0 )
if (r->limbs == 0 || m->limbs == 0) {
goto cleanup;
if( r->limbs != m->limbs )
}
if (r->limbs != m->limbs) {
goto cleanup;
}
ret = mbedtls_mpi_mod_raw_read( r->p, m, buf, buflen, ext_rep );
if( ret != 0 )
ret = mbedtls_mpi_mod_raw_read(r->p, m, buf, buflen, ext_rep);
if (ret != 0) {
goto cleanup;
}
r->limbs = m->limbs;
ret = mbedtls_mpi_mod_raw_canonical_to_modulus_rep( r->p, m );
ret = mbedtls_mpi_mod_raw_canonical_to_modulus_rep(r->p, m);
cleanup:
return ( ret );
return ret;
}
int mbedtls_mpi_mod_write( const mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep )
int mbedtls_mpi_mod_write(const mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep)
{
int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
/* Do our best to check if r and m have been set up */
if( r->limbs == 0 || m->limbs == 0 )
if (r->limbs == 0 || m->limbs == 0) {
goto cleanup;
if( r->limbs != m->limbs )
}
if (r->limbs != m->limbs) {
goto cleanup;
if( m->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY )
{
ret = mbedtls_mpi_mod_raw_from_mont_rep( r->p, m );
if( ret != 0 )
goto cleanup;
}
ret = mbedtls_mpi_mod_raw_write( r->p, m, buf, buflen, ext_rep );
if (m->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY) {
ret = mbedtls_mpi_mod_raw_from_mont_rep(r->p, m);
if (ret != 0) {
goto cleanup;
}
}
if( m->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY )
{
ret = mbedtls_mpi_mod_raw_write(r->p, m, buf, buflen, ext_rep);
if (m->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY) {
/* If this fails, the value of r is corrupted and we want to return
* this error (as opposed to the error code from the write above) to
* let the caller know. If it succeeds, we want to return the error
* code from write above. */
int conv_ret = mbedtls_mpi_mod_raw_to_mont_rep( r->p, m );
if( ret == 0 )
int conv_ret = mbedtls_mpi_mod_raw_to_mont_rep(r->p, m);
if (ret == 0) {
ret = conv_ret;
}
}
cleanup:
return ( ret );
return ret;
}
/* END MERGE SLOT 7 */

View File

@ -92,8 +92,7 @@
* This also determines which fields of the modulus structure are valid and
* what their contents are (see #mbedtls_mpi_mod_modulus).
*/
typedef enum
{
typedef enum {
/** Representation not chosen (makes the modulus structure invalid). */
MBEDTLS_MPI_MOD_REP_INVALID = 0,
/* Skip 1 as it is slightly easier to accidentally pass to functions. */
@ -108,15 +107,13 @@ typedef enum
/* Make mbedtls_mpi_mod_rep_selector and mbedtls_mpi_mod_ext_rep disjoint to
* make it easier to catch when they are accidentally swapped. */
typedef enum
{
typedef enum {
MBEDTLS_MPI_MOD_EXT_REP_INVALID = 0,
MBEDTLS_MPI_MOD_EXT_REP_LE = 8,
MBEDTLS_MPI_MOD_EXT_REP_BE
} mbedtls_mpi_mod_ext_rep;
typedef struct
{
typedef struct {
mbedtls_mpi_uint *p;
size_t limbs;
} mbedtls_mpi_mod_residue;
@ -133,8 +130,7 @@ typedef struct {
size_t limbs; // number of limbs
size_t bits; // bitlen of p
mbedtls_mpi_mod_rep_selector int_rep; // selector to signal the active member of the union
union rep
{
union rep {
/* if int_rep == #MBEDTLS_MPI_MOD_REP_MONTGOMERY */
mbedtls_mpi_mont_struct mont;
/* if int_rep == #MBEDTLS_MPI_MOD_REP_OPT_RED */
@ -170,10 +166,10 @@ typedef struct {
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p p_limbs is less than the
* limbs in \p m or if \p p is not less than \p m.
*/
int mbedtls_mpi_mod_residue_setup( mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
mbedtls_mpi_uint *p,
size_t p_limbs );
int mbedtls_mpi_mod_residue_setup(mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
mbedtls_mpi_uint *p,
size_t p_limbs);
/** Unbind elements of a residue structure.
*
@ -185,13 +181,13 @@ int mbedtls_mpi_mod_residue_setup( mbedtls_mpi_mod_residue *r,
*
* \param[out] r The address of residue to release.
*/
void mbedtls_mpi_mod_residue_release( mbedtls_mpi_mod_residue *r );
void mbedtls_mpi_mod_residue_release(mbedtls_mpi_mod_residue *r);
/** Initialize a modulus structure.
*
* \param[out] m The address of the modulus structure to initialize.
*/
void mbedtls_mpi_mod_modulus_init( mbedtls_mpi_mod_modulus *m );
void mbedtls_mpi_mod_modulus_init(mbedtls_mpi_mod_modulus *m);
/** Setup a modulus structure.
*
@ -207,10 +203,10 @@ void mbedtls_mpi_mod_modulus_init( mbedtls_mpi_mod_modulus *m );
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p int_rep is invalid.
*/
int mbedtls_mpi_mod_modulus_setup( mbedtls_mpi_mod_modulus *m,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_mod_rep_selector int_rep );
int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *m,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_mod_rep_selector int_rep);
/** Free elements of a modulus structure.
*
@ -222,7 +218,7 @@ int mbedtls_mpi_mod_modulus_setup( mbedtls_mpi_mod_modulus *m,
*
* \param[in,out] m The address of the modulus structure to free.
*/
void mbedtls_mpi_mod_modulus_free( mbedtls_mpi_mod_modulus *m );
void mbedtls_mpi_mod_modulus_free(mbedtls_mpi_mod_modulus *m);
/* BEGIN MERGE SLOT 1 */
@ -259,10 +255,10 @@ void mbedtls_mpi_mod_modulus_free( mbedtls_mpi_mod_modulus *m );
* have the same number of limbs or \p N is invalid.
* \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
*/
int mbedtls_mpi_mod_mul( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N );
int mbedtls_mpi_mod_mul(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N);
/* END MERGE SLOT 2 */
@ -292,10 +288,10 @@ int mbedtls_mpi_mod_mul( mbedtls_mpi_mod_residue *X,
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
* have the correct number of limbs.
*/
int mbedtls_mpi_mod_sub( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N );
int mbedtls_mpi_mod_sub(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N);
/**
* \brief Perform modular inversion of an MPI with respect to a modulus \p N.
@ -322,9 +318,9 @@ int mbedtls_mpi_mod_sub( mbedtls_mpi_mod_residue *X,
* by the inversion calculation itself).
*/
int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N );
int mbedtls_mpi_mod_inv(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_modulus *N);
/* END MERGE SLOT 3 */
/* BEGIN MERGE SLOT 4 */
@ -358,10 +354,10 @@ int mbedtls_mpi_mod_inv( mbedtls_mpi_mod_residue *X,
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
* have the correct number of limbs.
*/
int mbedtls_mpi_mod_add( mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N );
int mbedtls_mpi_mod_add(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
const mbedtls_mpi_mod_modulus *N);
/* END MERGE SLOT 5 */
/* BEGIN MERGE SLOT 6 */
@ -393,11 +389,11 @@ int mbedtls_mpi_mod_add( mbedtls_mpi_mod_residue *X,
* is significantly larger than \p min, which is the case
* for all usual cryptographic applications.
*/
int mbedtls_mpi_mod_random( mbedtls_mpi_mod_residue *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int mbedtls_mpi_mod_random(mbedtls_mpi_mod_residue *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
/* END MERGE SLOT 6 */
@ -425,11 +421,11 @@ int mbedtls_mpi_mod_random( mbedtls_mpi_mod_residue *X,
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p ext_rep
* is invalid or the value in the buffer is not less than \p m.
*/
int mbedtls_mpi_mod_read( mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep );
int mbedtls_mpi_mod_read(mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep);
/** Write a residue into a byte buffer.
*
@ -463,11 +459,11 @@ int mbedtls_mpi_mod_read( mbedtls_mpi_mod_residue *r,
* memory for conversion. Can occur only for moduli with
* MBEDTLS_MPI_MOD_REP_MONTGOMERY.
*/
int mbedtls_mpi_mod_write( const mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep );
int mbedtls_mpi_mod_write(const mbedtls_mpi_mod_residue *r,
const mbedtls_mpi_mod_modulus *m,
unsigned char *buf,
size_t buflen,
mbedtls_mpi_mod_ext_rep ext_rep);
/* END MERGE SLOT 7 */
/* BEGIN MERGE SLOT 8 */

View File

@ -33,74 +33,72 @@
#include "bignum_mod.h"
#include "constant_time_internal.h"
void mbedtls_mpi_mod_raw_cond_assign( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *N,
unsigned char assign )
void mbedtls_mpi_mod_raw_cond_assign(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *N,
unsigned char assign)
{
mbedtls_mpi_core_cond_assign( X, A, N->limbs, assign );
mbedtls_mpi_core_cond_assign(X, A, N->limbs, assign);
}
void mbedtls_mpi_mod_raw_cond_swap( mbedtls_mpi_uint *X,
mbedtls_mpi_uint *Y,
const mbedtls_mpi_mod_modulus *N,
unsigned char swap )
void mbedtls_mpi_mod_raw_cond_swap(mbedtls_mpi_uint *X,
mbedtls_mpi_uint *Y,
const mbedtls_mpi_mod_modulus *N,
unsigned char swap)
{
mbedtls_mpi_core_cond_swap( X, Y, N->limbs, swap );
mbedtls_mpi_core_cond_swap(X, Y, N->limbs, swap);
}
int mbedtls_mpi_mod_raw_read( mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *input,
size_t input_length,
mbedtls_mpi_mod_ext_rep ext_rep )
int mbedtls_mpi_mod_raw_read(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *input,
size_t input_length,
mbedtls_mpi_mod_ext_rep ext_rep)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
switch( ext_rep )
{
switch (ext_rep) {
case MBEDTLS_MPI_MOD_EXT_REP_LE:
ret = mbedtls_mpi_core_read_le( X, m->limbs,
input, input_length );
ret = mbedtls_mpi_core_read_le(X, m->limbs,
input, input_length);
break;
case MBEDTLS_MPI_MOD_EXT_REP_BE:
ret = mbedtls_mpi_core_read_be( X, m->limbs,
input, input_length );
ret = mbedtls_mpi_core_read_be(X, m->limbs,
input, input_length);
break;
default:
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
if( ret != 0 )
if (ret != 0) {
goto cleanup;
}
if( !mbedtls_mpi_core_lt_ct( X, m->p, m->limbs ) )
{
if (!mbedtls_mpi_core_lt_ct(X, m->p, m->limbs)) {
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
goto cleanup;
}
cleanup:
return( ret );
return ret;
}
int mbedtls_mpi_mod_raw_write( const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m,
unsigned char *output,
size_t output_length,
mbedtls_mpi_mod_ext_rep ext_rep )
int mbedtls_mpi_mod_raw_write(const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m,
unsigned char *output,
size_t output_length,
mbedtls_mpi_mod_ext_rep ext_rep)
{
switch( ext_rep )
{
switch (ext_rep) {
case MBEDTLS_MPI_MOD_EXT_REP_LE:
return( mbedtls_mpi_core_write_le( A, m->limbs,
output, output_length ) );
return mbedtls_mpi_core_write_le(A, m->limbs,
output, output_length);
case MBEDTLS_MPI_MOD_EXT_REP_BE:
return( mbedtls_mpi_core_write_be( A, m->limbs,
output, output_length ) );
return mbedtls_mpi_core_write_be(A, m->limbs,
output, output_length);
default:
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
}
@ -110,45 +108,45 @@ int mbedtls_mpi_mod_raw_write( const mbedtls_mpi_uint *A,
/* BEGIN MERGE SLOT 2 */
void mbedtls_mpi_mod_raw_sub( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N )
void mbedtls_mpi_mod_raw_sub(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N)
{
mbedtls_mpi_uint c = mbedtls_mpi_core_sub( X, A, B, N->limbs );
mbedtls_mpi_uint c = mbedtls_mpi_core_sub(X, A, B, N->limbs);
(void) mbedtls_mpi_core_add_if( X, N->p, N->limbs, (unsigned) c );
(void) mbedtls_mpi_core_add_if(X, N->p, N->limbs, (unsigned) c);
}
void mbedtls_mpi_mod_raw_mul( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *T )
void mbedtls_mpi_mod_raw_mul(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *T)
{
mbedtls_mpi_core_montmul( X, A, B, N->limbs, N->p, N->limbs,
N->rep.mont.mm, T );
mbedtls_mpi_core_montmul(X, A, B, N->limbs, N->p, N->limbs,
N->rep.mont.mm, T);
}
/* END MERGE SLOT 2 */
/* BEGIN MERGE SLOT 3 */
size_t mbedtls_mpi_mod_raw_inv_prime_working_limbs( size_t AN_limbs )
size_t mbedtls_mpi_mod_raw_inv_prime_working_limbs(size_t AN_limbs)
{
/* mbedtls_mpi_mod_raw_inv_prime() needs a temporary for the exponent,
* which will be the same size as the modulus and input (AN_limbs),
* and additional space to pass to mbedtls_mpi_core_exp_mod(). */
return( AN_limbs +
mbedtls_mpi_core_exp_mod_working_limbs( AN_limbs, AN_limbs ) );
return AN_limbs +
mbedtls_mpi_core_exp_mod_working_limbs(AN_limbs, AN_limbs);
}
void mbedtls_mpi_mod_raw_inv_prime( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
const mbedtls_mpi_uint *RR,
mbedtls_mpi_uint *T )
void mbedtls_mpi_mod_raw_inv_prime(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
const mbedtls_mpi_uint *RR,
mbedtls_mpi_uint *T)
{
/* Inversion by power: g^|G| = 1 => g^(-1) = g^(|G|-1), and
* |G| = N - 1, so we want
@ -157,12 +155,12 @@ void mbedtls_mpi_mod_raw_inv_prime( mbedtls_mpi_uint *X,
/* Use the first AN_limbs of T to hold N - 2 */
mbedtls_mpi_uint *Nminus2 = T;
(void) mbedtls_mpi_core_sub_int( Nminus2, N, 2, AN_limbs );
(void) mbedtls_mpi_core_sub_int(Nminus2, N, 2, AN_limbs);
/* Rest of T is given to exp_mod for its working space */
mbedtls_mpi_core_exp_mod( X,
A, N, AN_limbs, Nminus2, AN_limbs,
RR, T + AN_limbs );
mbedtls_mpi_core_exp_mod(X,
A, N, AN_limbs, Nminus2, AN_limbs,
RR, T + AN_limbs);
}
/* END MERGE SLOT 3 */
@ -172,15 +170,15 @@ void mbedtls_mpi_mod_raw_inv_prime( mbedtls_mpi_uint *X,
/* END MERGE SLOT 4 */
/* BEGIN MERGE SLOT 5 */
void mbedtls_mpi_mod_raw_add( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N )
void mbedtls_mpi_mod_raw_add(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N)
{
mbedtls_mpi_uint carry, borrow;
carry = mbedtls_mpi_core_add( X, A, B, N->limbs );
borrow = mbedtls_mpi_core_sub( X, X, N->p, N->limbs );
(void) mbedtls_mpi_core_add_if( X, N->p, N->limbs, (unsigned) ( carry ^ borrow ) );
carry = mbedtls_mpi_core_add(X, A, B, N->limbs);
borrow = mbedtls_mpi_core_sub(X, X, N->p, N->limbs);
(void) mbedtls_mpi_core_add_if(X, N->p, N->limbs, (unsigned) (carry ^ borrow));
}
/* END MERGE SLOT 5 */
@ -188,92 +186,93 @@ void mbedtls_mpi_mod_raw_add( mbedtls_mpi_uint *X,
int mbedtls_mpi_mod_raw_canonical_to_modulus_rep(
mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *N )
const mbedtls_mpi_mod_modulus *N)
{
switch( N->int_rep )
{
switch (N->int_rep) {
case MBEDTLS_MPI_MOD_REP_MONTGOMERY:
return( mbedtls_mpi_mod_raw_to_mont_rep( X, N ) );
return mbedtls_mpi_mod_raw_to_mont_rep(X, N);
case MBEDTLS_MPI_MOD_REP_OPT_RED:
return( 0 );
return 0;
default:
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
}
int mbedtls_mpi_mod_raw_modulus_to_canonical_rep(
mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *N )
const mbedtls_mpi_mod_modulus *N)
{
switch( N->int_rep )
{
switch (N->int_rep) {
case MBEDTLS_MPI_MOD_REP_MONTGOMERY:
return( mbedtls_mpi_mod_raw_from_mont_rep( X, N ) );
return mbedtls_mpi_mod_raw_from_mont_rep(X, N);
case MBEDTLS_MPI_MOD_REP_OPT_RED:
return( 0 );
return 0;
default:
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
}
int mbedtls_mpi_mod_raw_random( mbedtls_mpi_uint *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_mpi_mod_raw_random(mbedtls_mpi_uint *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int ret = mbedtls_mpi_core_random( X, min, N->p, N->limbs, f_rng, p_rng );
if( ret != 0 )
return( ret );
return( mbedtls_mpi_mod_raw_canonical_to_modulus_rep( X, N ) );
int ret = mbedtls_mpi_core_random(X, min, N->p, N->limbs, f_rng, p_rng);
if (ret != 0) {
return ret;
}
return mbedtls_mpi_mod_raw_canonical_to_modulus_rep(X, N);
}
/* END MERGE SLOT 6 */
/* BEGIN MERGE SLOT 7 */
int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m )
int mbedtls_mpi_mod_raw_to_mont_rep(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m)
{
mbedtls_mpi_uint *T;
const size_t t_limbs = mbedtls_mpi_core_montmul_working_limbs( m->limbs );
const size_t t_limbs = mbedtls_mpi_core_montmul_working_limbs(m->limbs);
if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL )
return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
if ((T = (mbedtls_mpi_uint *) mbedtls_calloc(t_limbs, ciL)) == NULL) {
return MBEDTLS_ERR_MPI_ALLOC_FAILED;
}
mbedtls_mpi_core_to_mont_rep( X, X, m->p, m->limbs,
m->rep.mont.mm, m->rep.mont.rr, T );
mbedtls_mpi_core_to_mont_rep(X, X, m->p, m->limbs,
m->rep.mont.mm, m->rep.mont.rr, T);
mbedtls_platform_zeroize( T, t_limbs * ciL );
mbedtls_free( T );
return( 0 );
mbedtls_platform_zeroize(T, t_limbs * ciL);
mbedtls_free(T);
return 0;
}
int mbedtls_mpi_mod_raw_from_mont_rep( mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m )
int mbedtls_mpi_mod_raw_from_mont_rep(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m)
{
const size_t t_limbs = mbedtls_mpi_core_montmul_working_limbs( m->limbs );
const size_t t_limbs = mbedtls_mpi_core_montmul_working_limbs(m->limbs);
mbedtls_mpi_uint *T;
if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL )
return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
if ((T = (mbedtls_mpi_uint *) mbedtls_calloc(t_limbs, ciL)) == NULL) {
return MBEDTLS_ERR_MPI_ALLOC_FAILED;
}
mbedtls_mpi_core_from_mont_rep( X, X, m->p, m->limbs, m->rep.mont.mm, T );
mbedtls_mpi_core_from_mont_rep(X, X, m->p, m->limbs, m->rep.mont.mm, T);
mbedtls_platform_zeroize( T, t_limbs * ciL );
mbedtls_free( T );
return( 0 );
mbedtls_platform_zeroize(T, t_limbs * ciL);
mbedtls_free(T);
return 0;
}
void mbedtls_mpi_mod_raw_neg( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m )
void mbedtls_mpi_mod_raw_neg(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m)
{
mbedtls_mpi_core_sub( X, m->p, A, m->limbs );
mbedtls_mpi_core_sub(X, m->p, A, m->limbs);
/* If A=0 initially, then X=N now. Detect this by
* subtracting N and catching the carry. */
mbedtls_mpi_uint borrow = mbedtls_mpi_core_sub( X, X, m->p, m->limbs );
(void) mbedtls_mpi_core_add_if( X, m->p, m->limbs, (unsigned) borrow );
mbedtls_mpi_uint borrow = mbedtls_mpi_core_sub(X, X, m->p, m->limbs);
(void) mbedtls_mpi_core_add_if(X, m->p, m->limbs, (unsigned) borrow);
}
/* END MERGE SLOT 7 */

View File

@ -109,10 +109,10 @@
* is indeterminate, and the resulting value in \p X might be
* neither its original value nor the value in \p A.
*/
void mbedtls_mpi_mod_raw_cond_assign( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *N,
unsigned char assign );
void mbedtls_mpi_mod_raw_cond_assign(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *N,
unsigned char assign);
/**
* \brief Perform a safe conditional swap of two MPIs which doesn't reveal
@ -135,10 +135,10 @@ void mbedtls_mpi_mod_raw_cond_assign( mbedtls_mpi_uint *X,
* is indeterminate, and both \p X and \p Y might end up with
* values different to either of the original ones.
*/
void mbedtls_mpi_mod_raw_cond_swap( mbedtls_mpi_uint *X,
mbedtls_mpi_uint *Y,
const mbedtls_mpi_mod_modulus *N,
unsigned char swap );
void mbedtls_mpi_mod_raw_cond_swap(mbedtls_mpi_uint *X,
mbedtls_mpi_uint *Y,
const mbedtls_mpi_mod_modulus *N,
unsigned char swap);
/** Import X from unsigned binary data.
*
@ -159,11 +159,11 @@ void mbedtls_mpi_mod_raw_cond_swap( mbedtls_mpi_uint *X,
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the external representation
* of \p m is invalid or \p X is not less than \p m.
*/
int mbedtls_mpi_mod_raw_read( mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *input,
size_t input_length,
mbedtls_mpi_mod_ext_rep ext_rep );
int mbedtls_mpi_mod_raw_read(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m,
const unsigned char *input,
size_t input_length,
mbedtls_mpi_mod_ext_rep ext_rep);
/** Export A into unsigned binary data.
*
@ -181,11 +181,11 @@ int mbedtls_mpi_mod_raw_read( mbedtls_mpi_uint *X,
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the external representation
* of \p m is invalid.
*/
int mbedtls_mpi_mod_raw_write( const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m,
unsigned char *output,
size_t output_length,
mbedtls_mpi_mod_ext_rep ext_rep );
int mbedtls_mpi_mod_raw_write(const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m,
unsigned char *output,
size_t output_length,
mbedtls_mpi_mod_ext_rep ext_rep);
/* BEGIN MERGE SLOT 1 */
@ -210,10 +210,10 @@ int mbedtls_mpi_mod_raw_write( const mbedtls_mpi_uint *A,
* \param[in] N The address of the modulus. Used to perform a modulo
* operation on the result of the subtraction.
*/
void mbedtls_mpi_mod_raw_sub( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N );
void mbedtls_mpi_mod_raw_sub(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N);
/** \brief Multiply two MPIs, returning the residue modulo the specified
* modulus.
@ -244,11 +244,11 @@ void mbedtls_mpi_mod_raw_sub( mbedtls_mpi_uint *X,
* It must not alias or otherwise overlap any of the
* other parameters.
*/
void mbedtls_mpi_mod_raw_mul( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *T );
void mbedtls_mpi_mod_raw_mul(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *T);
/* END MERGE SLOT 2 */
@ -269,7 +269,7 @@ void mbedtls_mpi_mod_raw_mul( mbedtls_mpi_uint *X,
* \return The number of limbs of working memory required by
* `mbedtls_mpi_mod_raw_inv_prime()`.
*/
size_t mbedtls_mpi_mod_raw_inv_prime_working_limbs( size_t AN_limbs );
size_t mbedtls_mpi_mod_raw_inv_prime_working_limbs(size_t AN_limbs);
/**
* \brief Perform fixed-width modular inversion of a Montgomery-form MPI with
@ -296,12 +296,12 @@ size_t mbedtls_mpi_mod_raw_inv_prime_working_limbs( size_t AN_limbs );
* longer needed, and before freeing it if it was dynamically
* allocated.
*/
void mbedtls_mpi_mod_raw_inv_prime( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
const mbedtls_mpi_uint *RR,
mbedtls_mpi_uint *T );
void mbedtls_mpi_mod_raw_inv_prime(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *N,
size_t AN_limbs,
const mbedtls_mpi_uint *RR,
mbedtls_mpi_uint *T);
/* END MERGE SLOT 3 */
@ -328,10 +328,10 @@ void mbedtls_mpi_mod_raw_inv_prime( mbedtls_mpi_uint *X,
* must be smaller than \p N.
* \param[in] N The address of the modulus.
*/
void mbedtls_mpi_mod_raw_add( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N );
void mbedtls_mpi_mod_raw_add(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_mod_modulus *N);
/* END MERGE SLOT 5 */
/* BEGIN MERGE SLOT 6 */
@ -351,7 +351,7 @@ void mbedtls_mpi_mod_raw_add( mbedtls_mpi_uint *X,
*/
int mbedtls_mpi_mod_raw_canonical_to_modulus_rep(
mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *N );
const mbedtls_mpi_mod_modulus *N);
/** Convert an MPI from the representation associated with the modulus
* to canonical representation (little-endian limb array).
@ -368,7 +368,7 @@ int mbedtls_mpi_mod_raw_canonical_to_modulus_rep(
*/
int mbedtls_mpi_mod_raw_modulus_to_canonical_rep(
mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *N );
const mbedtls_mpi_mod_modulus *N);
/** Generate a random number uniformly in a range.
*
@ -398,11 +398,11 @@ int mbedtls_mpi_mod_raw_modulus_to_canonical_rep(
* is significantly larger than \p min, which is the case
* for all usual cryptographic applications.
*/
int mbedtls_mpi_mod_raw_random( mbedtls_mpi_uint *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int mbedtls_mpi_mod_raw_random(mbedtls_mpi_uint *X,
mbedtls_mpi_uint min,
const mbedtls_mpi_mod_modulus *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
/* END MERGE SLOT 6 */
@ -416,8 +416,8 @@ int mbedtls_mpi_mod_raw_random( mbedtls_mpi_uint *X,
*
* \return \c 0 if successful.
*/
int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m );
int mbedtls_mpi_mod_raw_to_mont_rep(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m);
/** Convert an MPI back from Montgomery representation.
*
@ -428,8 +428,8 @@ int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X,
*
* \return \c 0 if successful.
*/
int mbedtls_mpi_mod_raw_from_mont_rep( mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m );
int mbedtls_mpi_mod_raw_from_mont_rep(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *m);
/** \brief Perform fixed width modular negation.
*
@ -444,9 +444,9 @@ int mbedtls_mpi_mod_raw_from_mont_rep( mbedtls_mpi_uint *X,
* must be less than or equal to \p m.
* \param[in] m The modulus to use.
*/
void mbedtls_mpi_mod_raw_neg( mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m);
void mbedtls_mpi_mod_raw_neg(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_mod_modulus *m);
/* END MERGE SLOT 7 */
/* BEGIN MERGE SLOT 8 */

View File

@ -47,36 +47,36 @@
*/
#if defined(MBEDTLS_HAVE_INT32)
#define MBEDTLS_BYTES_TO_T_UINT_4( a, b, c, d ) \
( (mbedtls_mpi_uint) (a) << 0 ) | \
( (mbedtls_mpi_uint) (b) << 8 ) | \
( (mbedtls_mpi_uint) (c) << 16 ) | \
( (mbedtls_mpi_uint) (d) << 24 )
#define MBEDTLS_BYTES_TO_T_UINT_4(a, b, c, d) \
((mbedtls_mpi_uint) (a) << 0) | \
((mbedtls_mpi_uint) (b) << 8) | \
((mbedtls_mpi_uint) (c) << 16) | \
((mbedtls_mpi_uint) (d) << 24)
#define MBEDTLS_BYTES_TO_T_UINT_2( a, b ) \
MBEDTLS_BYTES_TO_T_UINT_4( a, b, 0, 0 )
#define MBEDTLS_BYTES_TO_T_UINT_2(a, b) \
MBEDTLS_BYTES_TO_T_UINT_4(a, b, 0, 0)
#define MBEDTLS_BYTES_TO_T_UINT_8( a, b, c, d, e, f, g, h ) \
MBEDTLS_BYTES_TO_T_UINT_4( a, b, c, d ), \
MBEDTLS_BYTES_TO_T_UINT_4( e, f, g, h )
#define MBEDTLS_BYTES_TO_T_UINT_8(a, b, c, d, e, f, g, h) \
MBEDTLS_BYTES_TO_T_UINT_4(a, b, c, d), \
MBEDTLS_BYTES_TO_T_UINT_4(e, f, g, h)
#else /* 64-bits */
#define MBEDTLS_BYTES_TO_T_UINT_8( a, b, c, d, e, f, g, h ) \
( (mbedtls_mpi_uint) (a) << 0 ) | \
( (mbedtls_mpi_uint) (b) << 8 ) | \
( (mbedtls_mpi_uint) (c) << 16 ) | \
( (mbedtls_mpi_uint) (d) << 24 ) | \
( (mbedtls_mpi_uint) (e) << 32 ) | \
( (mbedtls_mpi_uint) (f) << 40 ) | \
( (mbedtls_mpi_uint) (g) << 48 ) | \
( (mbedtls_mpi_uint) (h) << 56 )
#define MBEDTLS_BYTES_TO_T_UINT_8(a, b, c, d, e, f, g, h) \
((mbedtls_mpi_uint) (a) << 0) | \
((mbedtls_mpi_uint) (b) << 8) | \
((mbedtls_mpi_uint) (c) << 16) | \
((mbedtls_mpi_uint) (d) << 24) | \
((mbedtls_mpi_uint) (e) << 32) | \
((mbedtls_mpi_uint) (f) << 40) | \
((mbedtls_mpi_uint) (g) << 48) | \
((mbedtls_mpi_uint) (h) << 56)
#define MBEDTLS_BYTES_TO_T_UINT_4( a, b, c, d ) \
MBEDTLS_BYTES_TO_T_UINT_8( a, b, c, d, 0, 0, 0, 0 )
#define MBEDTLS_BYTES_TO_T_UINT_4(a, b, c, d) \
MBEDTLS_BYTES_TO_T_UINT_8(a, b, c, d, 0, 0, 0, 0)
#define MBEDTLS_BYTES_TO_T_UINT_2( a, b ) \
MBEDTLS_BYTES_TO_T_UINT_8( a, b, 0, 0, 0, 0, 0, 0 )
#define MBEDTLS_BYTES_TO_T_UINT_2(a, b) \
MBEDTLS_BYTES_TO_T_UINT_8(a, b, 0, 0, 0, 0, 0, 0)
#endif /* bits in mbedtls_mpi_uint */

File diff suppressed because it is too large Load Diff

View File

@ -51,50 +51,53 @@
/*
* Initialize context
*/
void mbedtls_ccm_init( mbedtls_ccm_context *ctx )
void mbedtls_ccm_init(mbedtls_ccm_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_ccm_context ) );
memset(ctx, 0, sizeof(mbedtls_ccm_context));
}
int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits )
int mbedtls_ccm_setkey(mbedtls_ccm_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_cipher_info_t *cipher_info;
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 );
cipher_info = mbedtls_cipher_info_from_values(cipher, keybits,
MBEDTLS_MODE_ECB);
if (cipher_info == NULL) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
return( 0 );
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;
}
/*
* Free context
*/
void mbedtls_ccm_free( mbedtls_ccm_context *ctx )
void mbedtls_ccm_free(mbedtls_ccm_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
mbedtls_cipher_free( &ctx->cipher_ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) );
}
mbedtls_cipher_free(&ctx->cipher_ctx);
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_ccm_context));
}
#define CCM_STATE__CLEAR 0
@ -107,33 +110,33 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx )
/*
* Encrypt or decrypt a partial block with CTR
*/
static int mbedtls_ccm_crypt( mbedtls_ccm_context *ctx,
size_t offset, size_t use_len,
const unsigned char *input,
unsigned char *output )
static int mbedtls_ccm_crypt(mbedtls_ccm_context *ctx,
size_t offset, size_t use_len,
const unsigned char *input,
unsigned char *output)
{
size_t olen = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char tmp_buf[16] = {0};
unsigned char tmp_buf[16] = { 0 };
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->ctr, 16, tmp_buf,
&olen ) ) != 0 )
{
if ((ret = mbedtls_cipher_update(&ctx->cipher_ctx, ctx->ctr, 16, tmp_buf,
&olen)) != 0) {
ctx->state |= CCM_STATE__ERROR;
mbedtls_platform_zeroize(tmp_buf, sizeof(tmp_buf));
return ret;
}
mbedtls_xor( output, input, tmp_buf + offset, use_len );
mbedtls_xor(output, input, tmp_buf + offset, use_len);
mbedtls_platform_zeroize(tmp_buf, sizeof(tmp_buf));
return ret;
}
static void mbedtls_ccm_clear_state(mbedtls_ccm_context *ctx) {
static void mbedtls_ccm_clear_state(mbedtls_ccm_context *ctx)
{
ctx->state = CCM_STATE__CLEAR;
memset( ctx->y, 0, 16);
memset( ctx->ctr, 0, 16);
memset(ctx->y, 0, 16);
memset(ctx->ctr, 0, 16);
}
static int ccm_calculate_first_block_if_ready(mbedtls_ccm_context *ctx)
@ -145,21 +148,18 @@ static int ccm_calculate_first_block_if_ready(mbedtls_ccm_context *ctx)
/* length calculation can be done only after both
* mbedtls_ccm_starts() and mbedtls_ccm_set_lengths() have been executed
*/
if( !(ctx->state & CCM_STATE__STARTED) || !(ctx->state & CCM_STATE__LENGTHS_SET) )
if (!(ctx->state & CCM_STATE__STARTED) || !(ctx->state & CCM_STATE__LENGTHS_SET)) {
return 0;
}
/* CCM expects non-empty tag.
* CCM* allows empty tag. For CCM* without tag, ignore plaintext length.
*/
if( ctx->tag_len == 0 )
{
if( ctx->mode == MBEDTLS_CCM_STAR_ENCRYPT || ctx->mode == MBEDTLS_CCM_STAR_DECRYPT )
{
if (ctx->tag_len == 0) {
if (ctx->mode == MBEDTLS_CCM_STAR_ENCRYPT || ctx->mode == MBEDTLS_CCM_STAR_DECRYPT) {
ctx->plaintext_len = 0;
}
else
{
return( MBEDTLS_ERR_CCM_BAD_INPUT );
} else {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
}
@ -175,37 +175,37 @@ static int ccm_calculate_first_block_if_ready(mbedtls_ccm_context *ctx)
* 5 .. 3 (t - 2) / 2
* 2 .. 0 q - 1
*/
ctx->y[0] |= ( ctx->add_len > 0 ) << 6;
ctx->y[0] |= ( ( ctx->tag_len - 2 ) / 2 ) << 3;
ctx->y[0] |= (ctx->add_len > 0) << 6;
ctx->y[0] |= ((ctx->tag_len - 2) / 2) << 3;
ctx->y[0] |= ctx->q - 1;
for( i = 0, len_left = ctx->plaintext_len; i < ctx->q; i++, len_left >>= 8 )
ctx->y[15-i] = MBEDTLS_BYTE_0( len_left );
for (i = 0, len_left = ctx->plaintext_len; i < ctx->q; i++, len_left >>= 8) {
ctx->y[15-i] = MBEDTLS_BYTE_0(len_left);
}
if( len_left > 0 )
{
if (len_left > 0) {
ctx->state |= CCM_STATE__ERROR;
return( MBEDTLS_ERR_CCM_BAD_INPUT );
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
/* Start CBC-MAC with first block*/
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen ) ) != 0 )
{
if ((ret = mbedtls_cipher_update(&ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen)) != 0) {
ctx->state |= CCM_STATE__ERROR;
return( ret );
return ret;
}
return (0);
return 0;
}
int mbedtls_ccm_starts( mbedtls_ccm_context *ctx,
int mode,
const unsigned char *iv,
size_t iv_len )
int mbedtls_ccm_starts(mbedtls_ccm_context *ctx,
int mode,
const unsigned char *iv,
size_t iv_len)
{
/* Also implies q is within bounds */
if( iv_len < 7 || iv_len > 13 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if (iv_len < 7 || iv_len > 13) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
ctx->mode = mode;
ctx->q = 16 - 1 - (unsigned char) iv_len;
@ -220,25 +220,25 @@ int mbedtls_ccm_starts( mbedtls_ccm_context *ctx,
* 7 .. 3 0
* 2 .. 0 q - 1
*/
memset( ctx->ctr, 0, 16);
memset(ctx->ctr, 0, 16);
ctx->ctr[0] = ctx->q - 1;
memcpy( ctx->ctr + 1, iv, iv_len );
memset( ctx->ctr + 1 + iv_len, 0, ctx->q );
memcpy(ctx->ctr + 1, iv, iv_len);
memset(ctx->ctr + 1 + iv_len, 0, ctx->q);
ctx->ctr[15] = 1;
/*
* See ccm_calculate_first_block_if_ready() for block layout description
*/
memcpy( ctx->y + 1, iv, iv_len );
memcpy(ctx->y + 1, iv, iv_len);
ctx->state |= CCM_STATE__STARTED;
return ccm_calculate_first_block_if_ready(ctx);
}
int mbedtls_ccm_set_lengths( mbedtls_ccm_context *ctx,
size_t total_ad_len,
size_t plaintext_len,
size_t tag_len )
int mbedtls_ccm_set_lengths(mbedtls_ccm_context *ctx,
size_t total_ad_len,
size_t plaintext_len,
size_t tag_len)
{
/*
* Check length requirements: SP800-38C A.1
@ -247,11 +247,13 @@ int mbedtls_ccm_set_lengths( mbedtls_ccm_context *ctx,
*
* Also, loosen the requirements to enable support for CCM* (IEEE 802.15.4).
*/
if( tag_len == 2 || tag_len > 16 || tag_len % 2 != 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if (tag_len == 2 || tag_len > 16 || tag_len % 2 != 0) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
if( total_ad_len >= 0xFF00 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if (total_ad_len >= 0xFF00) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
ctx->plaintext_len = plaintext_len;
ctx->add_len = total_ad_len;
@ -262,81 +264,72 @@ int mbedtls_ccm_set_lengths( mbedtls_ccm_context *ctx,
return ccm_calculate_first_block_if_ready(ctx);
}
int mbedtls_ccm_update_ad( mbedtls_ccm_context *ctx,
const unsigned char *add,
size_t add_len )
int mbedtls_ccm_update_ad(mbedtls_ccm_context *ctx,
const unsigned char *add,
size_t add_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t olen, use_len, offset;
if( ctx->state & CCM_STATE__ERROR )
{
if (ctx->state & CCM_STATE__ERROR) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
if( add_len > 0 )
{
if( ctx->state & CCM_STATE__AUTH_DATA_FINISHED )
{
if (add_len > 0) {
if (ctx->state & CCM_STATE__AUTH_DATA_FINISHED) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
if( !(ctx->state & CCM_STATE__AUTH_DATA_STARTED) )
{
if ( add_len > ctx->add_len )
{
if (!(ctx->state & CCM_STATE__AUTH_DATA_STARTED)) {
if (add_len > ctx->add_len) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
ctx->y[0] ^= (unsigned char)( ( ctx->add_len >> 8 ) & 0xFF );
ctx->y[1] ^= (unsigned char)( ( ctx->add_len ) & 0xFF );
ctx->y[0] ^= (unsigned char) ((ctx->add_len >> 8) & 0xFF);
ctx->y[1] ^= (unsigned char) ((ctx->add_len) & 0xFF);
ctx->state |= CCM_STATE__AUTH_DATA_STARTED;
}
else if ( ctx->processed + add_len > ctx->add_len )
{
} else if (ctx->processed + add_len > ctx->add_len) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
while( add_len > 0 )
{
while (add_len > 0) {
offset = (ctx->processed + 2) % 16; /* account for y[0] and y[1]
* holding total auth data length */
use_len = 16 - offset;
if( use_len > add_len )
if (use_len > add_len) {
use_len = add_len;
}
mbedtls_xor( ctx->y + offset, ctx->y + offset, add, use_len );
mbedtls_xor(ctx->y + offset, ctx->y + offset, add, use_len);
ctx->processed += use_len;
add_len -= use_len;
add += use_len;
if( use_len + offset == 16 || ctx->processed == ctx->add_len )
{
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen ) ) != 0 )
{
if (use_len + offset == 16 || ctx->processed == ctx->add_len) {
if ((ret =
mbedtls_cipher_update(&ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen)) != 0) {
ctx->state |= CCM_STATE__ERROR;
return( ret );
return ret;
}
}
}
if( ctx->processed == ctx->add_len )
{
if (ctx->processed == ctx->add_len) {
ctx->state |= CCM_STATE__AUTH_DATA_FINISHED;
ctx->processed = 0; // prepare for mbedtls_ccm_update()
}
}
return (0);
return 0;
}
int mbedtls_ccm_update( mbedtls_ccm_context *ctx,
const unsigned char *input, size_t input_len,
unsigned char *output, size_t output_size,
size_t *output_len )
int mbedtls_ccm_update(mbedtls_ccm_context *ctx,
const unsigned char *input, size_t input_len,
unsigned char *output, size_t output_size,
size_t *output_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char i;
@ -344,88 +337,86 @@ int mbedtls_ccm_update( mbedtls_ccm_context *ctx,
unsigned char local_output[16];
if( ctx->state & CCM_STATE__ERROR )
{
if (ctx->state & CCM_STATE__ERROR) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
/* Check against plaintext length only if performing operation with
* authentication
*/
if( ctx->tag_len != 0 && ctx->processed + input_len > ctx->plaintext_len )
{
if (ctx->tag_len != 0 && ctx->processed + input_len > ctx->plaintext_len) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
if( output_size < input_len )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if (output_size < input_len) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
*output_len = input_len;
ret = 0;
while ( input_len > 0 )
{
while (input_len > 0) {
offset = ctx->processed % 16;
use_len = 16 - offset;
if( use_len > input_len )
if (use_len > input_len) {
use_len = input_len;
}
ctx->processed += use_len;
if( ctx->mode == MBEDTLS_CCM_ENCRYPT || \
ctx->mode == MBEDTLS_CCM_STAR_ENCRYPT )
{
mbedtls_xor( ctx->y + offset, ctx->y + offset, input, use_len );
if (ctx->mode == MBEDTLS_CCM_ENCRYPT || \
ctx->mode == MBEDTLS_CCM_STAR_ENCRYPT) {
mbedtls_xor(ctx->y + offset, ctx->y + offset, input, use_len);
if( use_len + offset == 16 || ctx->processed == ctx->plaintext_len )
{
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen ) ) != 0 )
{
if (use_len + offset == 16 || ctx->processed == ctx->plaintext_len) {
if ((ret =
mbedtls_cipher_update(&ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen)) != 0) {
ctx->state |= CCM_STATE__ERROR;
goto exit;
}
}
ret = mbedtls_ccm_crypt( ctx, offset, use_len, input, output );
if( ret != 0 )
ret = mbedtls_ccm_crypt(ctx, offset, use_len, input, output);
if (ret != 0) {
goto exit;
}
}
if( ctx->mode == MBEDTLS_CCM_DECRYPT || \
ctx->mode == MBEDTLS_CCM_STAR_DECRYPT )
{
if (ctx->mode == MBEDTLS_CCM_DECRYPT || \
ctx->mode == MBEDTLS_CCM_STAR_DECRYPT) {
/* Since output may be in shared memory, we cannot be sure that
* it will contain what we wrote to it. Therefore, we should avoid using
* it as input to any operations.
* Write decrypted data to local_output to avoid using output variable as
* input in the XOR operation for Y.
*/
ret = mbedtls_ccm_crypt( ctx, offset, use_len, input, local_output );
if( ret != 0 )
ret = mbedtls_ccm_crypt(ctx, offset, use_len, input, local_output);
if (ret != 0) {
goto exit;
}
mbedtls_xor( ctx->y + offset, ctx->y + offset, local_output, use_len );
mbedtls_xor(ctx->y + offset, ctx->y + offset, local_output, use_len);
memcpy( output, local_output, use_len );
mbedtls_platform_zeroize( local_output, 16 );
memcpy(output, local_output, use_len);
mbedtls_platform_zeroize(local_output, 16);
if( use_len + offset == 16 || ctx->processed == ctx->plaintext_len )
{
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen ) ) != 0 )
{
if (use_len + offset == 16 || ctx->processed == ctx->plaintext_len) {
if ((ret =
mbedtls_cipher_update(&ctx->cipher_ctx, ctx->y, 16, ctx->y, &olen)) != 0) {
ctx->state |= CCM_STATE__ERROR;
goto exit;
}
}
}
if( use_len + offset == 16 || ctx->processed == ctx->plaintext_len )
{
for( i = 0; i < ctx->q; i++ )
if( ++(ctx->ctr)[15-i] != 0 )
break;
if (use_len + offset == 16 || ctx->processed == ctx->plaintext_len) {
for (i = 0; i < ctx->q; i++) {
if (++(ctx->ctr)[15-i] != 0) {
break;
}
}
}
input_len -= use_len;
@ -434,167 +425,172 @@ int mbedtls_ccm_update( mbedtls_ccm_context *ctx,
}
exit:
mbedtls_platform_zeroize( local_output, 16 );
mbedtls_platform_zeroize(local_output, 16);
return ret;
}
int mbedtls_ccm_finish( mbedtls_ccm_context *ctx,
unsigned char *tag, size_t tag_len )
int mbedtls_ccm_finish(mbedtls_ccm_context *ctx,
unsigned char *tag, size_t tag_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char i;
if( ctx->state & CCM_STATE__ERROR )
{
if (ctx->state & CCM_STATE__ERROR) {
return MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
}
if( ctx->add_len > 0 && !( ctx->state & CCM_STATE__AUTH_DATA_FINISHED ) )
{
if (ctx->add_len > 0 && !(ctx->state & CCM_STATE__AUTH_DATA_FINISHED)) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
if( ctx->plaintext_len > 0 && ctx->processed != ctx->plaintext_len )
{
if (ctx->plaintext_len > 0 && ctx->processed != ctx->plaintext_len) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
/*
* Authentication: reset counter and crypt/mask internal tag
*/
for( i = 0; i < ctx->q; i++ )
for (i = 0; i < ctx->q; i++) {
ctx->ctr[15-i] = 0;
}
ret = mbedtls_ccm_crypt( ctx, 0, 16, ctx->y, ctx->y );
if( ret != 0 )
ret = mbedtls_ccm_crypt(ctx, 0, 16, ctx->y, ctx->y);
if (ret != 0) {
return ret;
if( tag != NULL )
memcpy( tag, ctx->y, tag_len );
}
if (tag != NULL) {
memcpy(tag, ctx->y, tag_len);
}
mbedtls_ccm_clear_state(ctx);
return( 0 );
return 0;
}
/*
* Authenticated encryption or decryption
*/
static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
static int ccm_auth_crypt(mbedtls_ccm_context *ctx, int mode, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t olen;
if( ( ret = mbedtls_ccm_starts( ctx, mode, iv, iv_len ) ) != 0 )
return( ret );
if ((ret = mbedtls_ccm_starts(ctx, mode, iv, iv_len)) != 0) {
return ret;
}
if( ( ret = mbedtls_ccm_set_lengths( ctx, add_len, length, tag_len ) ) != 0 )
return( ret );
if ((ret = mbedtls_ccm_set_lengths(ctx, add_len, length, tag_len)) != 0) {
return ret;
}
if( ( ret = mbedtls_ccm_update_ad( ctx, add, add_len ) ) != 0 )
return( ret );
if ((ret = mbedtls_ccm_update_ad(ctx, add, add_len)) != 0) {
return ret;
}
if( ( ret = mbedtls_ccm_update( ctx, input, length,
output, length, &olen ) ) != 0 )
return( ret );
if ((ret = mbedtls_ccm_update(ctx, input, length,
output, length, &olen)) != 0) {
return ret;
}
if( ( ret = mbedtls_ccm_finish( ctx, tag, tag_len ) ) != 0 )
return( ret );
if ((ret = mbedtls_ccm_finish(ctx, tag, tag_len)) != 0) {
return ret;
}
return( 0 );
return 0;
}
/*
* Authenticated encryption
*/
int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
int mbedtls_ccm_star_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len)
{
return( ccm_auth_crypt( ctx, MBEDTLS_CCM_STAR_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len ) );
return ccm_auth_crypt(ctx, MBEDTLS_CCM_STAR_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len);
}
int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
int mbedtls_ccm_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len)
{
return( ccm_auth_crypt( ctx, MBEDTLS_CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len ) );
return ccm_auth_crypt(ctx, MBEDTLS_CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len);
}
/*
* Authenticated decryption
*/
static int mbedtls_ccm_compare_tags(const unsigned char *tag1, const unsigned char *tag2, size_t tag_len)
static int mbedtls_ccm_compare_tags(const unsigned char *tag1,
const unsigned char *tag2,
size_t tag_len)
{
unsigned char i;
int diff;
/* Check tag in "constant-time" */
for( diff = 0, i = 0; i < tag_len; i++ )
for (diff = 0, i = 0; i < tag_len; i++) {
diff |= tag1[i] ^ tag2[i];
if( diff != 0 )
{
return( MBEDTLS_ERR_CCM_AUTH_FAILED );
}
return( 0 );
if (diff != 0) {
return MBEDTLS_ERR_CCM_AUTH_FAILED;
}
return 0;
}
static int ccm_auth_decrypt( mbedtls_ccm_context *ctx, int mode, 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 )
static int ccm_auth_decrypt(mbedtls_ccm_context *ctx, int mode, 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)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char check_tag[16];
if( ( ret = ccm_auth_crypt( ctx, mode, length,
iv, iv_len, add, add_len,
input, output, check_tag, tag_len ) ) != 0 )
{
return( ret );
if ((ret = ccm_auth_crypt(ctx, mode, length,
iv, iv_len, add, add_len,
input, output, check_tag, tag_len)) != 0) {
return ret;
}
if( ( ret = mbedtls_ccm_compare_tags( tag, check_tag, tag_len ) ) != 0 )
{
mbedtls_platform_zeroize( output, length );
return( ret );
if ((ret = mbedtls_ccm_compare_tags(tag, check_tag, tag_len)) != 0) {
mbedtls_platform_zeroize(output, length);
return ret;
}
return( 0 );
return 0;
}
int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
int mbedtls_ccm_star_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len)
{
return ccm_auth_decrypt( ctx, MBEDTLS_CCM_STAR_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, tag, tag_len );
return ccm_auth_decrypt(ctx, MBEDTLS_CCM_STAR_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, tag, tag_len);
}
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 )
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)
{
return ccm_auth_decrypt( ctx, MBEDTLS_CCM_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, tag, tag_len );
return ccm_auth_decrypt(ctx, MBEDTLS_CCM_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, tag, tag_len);
}
#endif /* !MBEDTLS_CCM_ALT */
@ -631,7 +627,7 @@ static const unsigned char msg_test_data[CCM_SELFTEST_PT_MAX_LEN] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
};
static const size_t iv_len_test_data [NB_TESTS] = { 7, 8, 12 };
static const size_t iv_len_test_data[NB_TESTS] = { 7, 8, 12 };
static const size_t add_len_test_data[NB_TESTS] = { 8, 16, 20 };
static const size_t msg_len_test_data[NB_TESTS] = { 4, 16, 24 };
static const size_t tag_len_test_data[NB_TESTS] = { 4, 6, 8 };
@ -647,7 +643,7 @@ static const unsigned char res_test_data[NB_TESTS][CCM_SELFTEST_CT_MAX_LEN] = {
0x48, 0x43, 0x92, 0xfb, 0xc1, 0xb0, 0x99, 0x51 }
};
int mbedtls_ccm_self_test( int verbose )
int mbedtls_ccm_self_test(int verbose)
{
mbedtls_ccm_context ctx;
/*
@ -660,70 +656,72 @@ int mbedtls_ccm_self_test( int verbose )
size_t i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ccm_init( &ctx );
mbedtls_ccm_init(&ctx);
if( mbedtls_ccm_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, key_test_data,
8 * sizeof key_test_data ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( " CCM: setup failed" );
return( 1 );
}
for( i = 0; i < NB_TESTS; i++ )
{
if( verbose != 0 )
mbedtls_printf( " CCM-AES #%u: ", (unsigned int) i + 1 );
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
memset( ciphertext, 0, CCM_SELFTEST_CT_MAX_LEN );
memcpy( plaintext, msg_test_data, msg_len_test_data[i] );
ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len_test_data[i],
iv_test_data, iv_len_test_data[i],
ad_test_data, add_len_test_data[i],
plaintext, ciphertext,
ciphertext + msg_len_test_data[i],
tag_len_test_data[i] );
if( ret != 0 ||
memcmp( ciphertext, res_test_data[i],
msg_len_test_data[i] + tag_len_test_data[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len_test_data[i],
iv_test_data, iv_len_test_data[i],
ad_test_data, add_len_test_data[i],
ciphertext, plaintext,
ciphertext + msg_len_test_data[i],
tag_len_test_data[i] );
if( ret != 0 ||
memcmp( plaintext, msg_test_data, msg_len_test_data[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
if (mbedtls_ccm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key_test_data,
8 * sizeof key_test_data) != 0) {
if (verbose != 0) {
mbedtls_printf(" CCM: setup failed");
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
return 1;
}
mbedtls_ccm_free( &ctx );
for (i = 0; i < NB_TESTS; i++) {
if (verbose != 0) {
mbedtls_printf(" CCM-AES #%u: ", (unsigned int) i + 1);
}
if( verbose != 0 )
mbedtls_printf( "\n" );
memset(plaintext, 0, CCM_SELFTEST_PT_MAX_LEN);
memset(ciphertext, 0, CCM_SELFTEST_CT_MAX_LEN);
memcpy(plaintext, msg_test_data, msg_len_test_data[i]);
return( 0 );
ret = mbedtls_ccm_encrypt_and_tag(&ctx, msg_len_test_data[i],
iv_test_data, iv_len_test_data[i],
ad_test_data, add_len_test_data[i],
plaintext, ciphertext,
ciphertext + msg_len_test_data[i],
tag_len_test_data[i]);
if (ret != 0 ||
memcmp(ciphertext, res_test_data[i],
msg_len_test_data[i] + tag_len_test_data[i]) != 0) {
if (verbose != 0) {
mbedtls_printf("failed\n");
}
return 1;
}
memset(plaintext, 0, CCM_SELFTEST_PT_MAX_LEN);
ret = mbedtls_ccm_auth_decrypt(&ctx, msg_len_test_data[i],
iv_test_data, iv_len_test_data[i],
ad_test_data, add_len_test_data[i],
ciphertext, plaintext,
ciphertext + msg_len_test_data[i],
tag_len_test_data[i]);
if (ret != 0 ||
memcmp(plaintext, msg_test_data, msg_len_test_data[i]) != 0) {
if (verbose != 0) {
mbedtls_printf("failed\n");
}
return 1;
}
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
mbedtls_ccm_free(&ctx);
if (verbose != 0) {
mbedtls_printf("\n");
}
return 0;
}
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

View File

@ -36,12 +36,12 @@
#if !defined(MBEDTLS_CHACHA20_ALT)
#define ROTL32( value, amount ) \
( (uint32_t) ( (value) << (amount) ) | ( (value) >> ( 32 - (amount) ) ) )
#define ROTL32(value, amount) \
((uint32_t) ((value) << (amount)) | ((value) >> (32 - (amount))))
#define CHACHA20_CTR_INDEX ( 12U )
#define CHACHA20_CTR_INDEX (12U)
#define CHACHA20_BLOCK_SIZE_BYTES ( 4U * 16U )
#define CHACHA20_BLOCK_SIZE_BYTES (4U * 16U)
/**
* \brief ChaCha20 quarter round operation.
@ -58,31 +58,31 @@
* \param c The index of 'c' in the state.
* \param d The index of 'd' in the state.
*/
static inline void chacha20_quarter_round( uint32_t state[16],
size_t a,
size_t b,
size_t c,
size_t d )
static inline void chacha20_quarter_round(uint32_t state[16],
size_t a,
size_t b,
size_t c,
size_t d)
{
/* a += b; d ^= a; d <<<= 16; */
state[a] += state[b];
state[d] ^= state[a];
state[d] = ROTL32( state[d], 16 );
state[d] = ROTL32(state[d], 16);
/* c += d; b ^= c; b <<<= 12 */
state[c] += state[d];
state[b] ^= state[c];
state[b] = ROTL32( state[b], 12 );
state[b] = ROTL32(state[b], 12);
/* a += b; d ^= a; d <<<= 8; */
state[a] += state[b];
state[d] ^= state[a];
state[d] = ROTL32( state[d], 8 );
state[d] = ROTL32(state[d], 8);
/* c += d; b ^= c; b <<<= 7; */
state[c] += state[d];
state[b] ^= state[c];
state[b] = ROTL32( state[b], 7 );
state[b] = ROTL32(state[b], 7);
}
/**
@ -93,17 +93,17 @@ static inline void chacha20_quarter_round( uint32_t state[16],
*
* \param state The ChaCha20 state to update.
*/
static void chacha20_inner_block( uint32_t state[16] )
static void chacha20_inner_block(uint32_t state[16])
{
chacha20_quarter_round( state, 0, 4, 8, 12 );
chacha20_quarter_round( state, 1, 5, 9, 13 );
chacha20_quarter_round( state, 2, 6, 10, 14 );
chacha20_quarter_round( state, 3, 7, 11, 15 );
chacha20_quarter_round(state, 0, 4, 8, 12);
chacha20_quarter_round(state, 1, 5, 9, 13);
chacha20_quarter_round(state, 2, 6, 10, 14);
chacha20_quarter_round(state, 3, 7, 11, 15);
chacha20_quarter_round( state, 0, 5, 10, 15 );
chacha20_quarter_round( state, 1, 6, 11, 12 );
chacha20_quarter_round( state, 2, 7, 8, 13 );
chacha20_quarter_round( state, 3, 4, 9, 14 );
chacha20_quarter_round(state, 0, 5, 10, 15);
chacha20_quarter_round(state, 1, 6, 11, 12);
chacha20_quarter_round(state, 2, 7, 8, 13);
chacha20_quarter_round(state, 3, 4, 9, 14);
}
/**
@ -112,29 +112,30 @@ static void chacha20_inner_block( uint32_t state[16] )
* \param initial_state The initial ChaCha20 state (key, nonce, counter).
* \param keystream Generated keystream bytes are written to this buffer.
*/
static void chacha20_block( const uint32_t initial_state[16],
unsigned char keystream[64] )
static void chacha20_block(const uint32_t initial_state[16],
unsigned char keystream[64])
{
uint32_t working_state[16];
size_t i;
memcpy( working_state,
initial_state,
CHACHA20_BLOCK_SIZE_BYTES );
memcpy(working_state,
initial_state,
CHACHA20_BLOCK_SIZE_BYTES);
for( i = 0U; i < 10U; i++ )
chacha20_inner_block( working_state );
for (i = 0U; i < 10U; i++) {
chacha20_inner_block(working_state);
}
working_state[ 0] += initial_state[ 0];
working_state[ 1] += initial_state[ 1];
working_state[ 2] += initial_state[ 2];
working_state[ 3] += initial_state[ 3];
working_state[ 4] += initial_state[ 4];
working_state[ 5] += initial_state[ 5];
working_state[ 6] += initial_state[ 6];
working_state[ 7] += initial_state[ 7];
working_state[ 8] += initial_state[ 8];
working_state[ 9] += initial_state[ 9];
working_state[0] += initial_state[0];
working_state[1] += initial_state[1];
working_state[2] += initial_state[2];
working_state[3] += initial_state[3];
working_state[4] += initial_state[4];
working_state[5] += initial_state[5];
working_state[6] += initial_state[6];
working_state[7] += initial_state[7];
working_state[8] += initial_state[8];
working_state[9] += initial_state[9];
working_state[10] += initial_state[10];
working_state[11] += initial_state[11];
working_state[12] += initial_state[12];
@ -142,35 +143,33 @@ static void chacha20_block( const uint32_t initial_state[16],
working_state[14] += initial_state[14];
working_state[15] += initial_state[15];
for( i = 0U; i < 16; i++ )
{
for (i = 0U; i < 16; i++) {
size_t offset = i * 4U;
MBEDTLS_PUT_UINT32_LE(working_state[i], keystream, offset);
}
mbedtls_platform_zeroize( working_state, sizeof( working_state ) );
mbedtls_platform_zeroize(working_state, sizeof(working_state));
}
void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx )
void mbedtls_chacha20_init(mbedtls_chacha20_context *ctx)
{
mbedtls_platform_zeroize( ctx->state, sizeof( ctx->state ) );
mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) );
mbedtls_platform_zeroize(ctx->state, sizeof(ctx->state));
mbedtls_platform_zeroize(ctx->keystream8, sizeof(ctx->keystream8));
/* Initially, there's no keystream bytes available */
ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES;
}
void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx )
void mbedtls_chacha20_free(mbedtls_chacha20_context *ctx)
{
if( ctx != NULL )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_chacha20_context ) );
if (ctx != NULL) {
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_chacha20_context));
}
}
int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx,
const unsigned char key[32] )
int mbedtls_chacha20_setkey(mbedtls_chacha20_context *ctx,
const unsigned char key[32])
{
/* ChaCha20 constants - the string "expand 32-byte k" */
ctx->state[0] = 0x61707865;
@ -179,50 +178,49 @@ int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx,
ctx->state[3] = 0x6b206574;
/* Set key */
ctx->state[4] = MBEDTLS_GET_UINT32_LE( key, 0 );
ctx->state[5] = MBEDTLS_GET_UINT32_LE( key, 4 );
ctx->state[6] = MBEDTLS_GET_UINT32_LE( key, 8 );
ctx->state[7] = MBEDTLS_GET_UINT32_LE( key, 12 );
ctx->state[8] = MBEDTLS_GET_UINT32_LE( key, 16 );
ctx->state[9] = MBEDTLS_GET_UINT32_LE( key, 20 );
ctx->state[10] = MBEDTLS_GET_UINT32_LE( key, 24 );
ctx->state[11] = MBEDTLS_GET_UINT32_LE( key, 28 );
ctx->state[4] = MBEDTLS_GET_UINT32_LE(key, 0);
ctx->state[5] = MBEDTLS_GET_UINT32_LE(key, 4);
ctx->state[6] = MBEDTLS_GET_UINT32_LE(key, 8);
ctx->state[7] = MBEDTLS_GET_UINT32_LE(key, 12);
ctx->state[8] = MBEDTLS_GET_UINT32_LE(key, 16);
ctx->state[9] = MBEDTLS_GET_UINT32_LE(key, 20);
ctx->state[10] = MBEDTLS_GET_UINT32_LE(key, 24);
ctx->state[11] = MBEDTLS_GET_UINT32_LE(key, 28);
return( 0 );
return 0;
}
int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx,
const unsigned char nonce[12],
uint32_t counter )
int mbedtls_chacha20_starts(mbedtls_chacha20_context *ctx,
const unsigned char nonce[12],
uint32_t counter)
{
/* Counter */
ctx->state[12] = counter;
/* Nonce */
ctx->state[13] = MBEDTLS_GET_UINT32_LE( nonce, 0 );
ctx->state[14] = MBEDTLS_GET_UINT32_LE( nonce, 4 );
ctx->state[15] = MBEDTLS_GET_UINT32_LE( nonce, 8 );
ctx->state[13] = MBEDTLS_GET_UINT32_LE(nonce, 0);
ctx->state[14] = MBEDTLS_GET_UINT32_LE(nonce, 4);
ctx->state[15] = MBEDTLS_GET_UINT32_LE(nonce, 8);
mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) );
mbedtls_platform_zeroize(ctx->keystream8, sizeof(ctx->keystream8));
/* Initially, there's no keystream bytes available */
ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES;
return( 0 );
return 0;
}
int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,
size_t size,
const unsigned char *input,
unsigned char *output )
int mbedtls_chacha20_update(mbedtls_chacha20_context *ctx,
size_t size,
const unsigned char *input,
unsigned char *output)
{
size_t offset = 0U;
/* Use leftover keystream bytes, if available */
while( size > 0U && ctx->keystream_bytes_used < CHACHA20_BLOCK_SIZE_BYTES )
{
while (size > 0U && ctx->keystream_bytes_used < CHACHA20_BLOCK_SIZE_BYTES) {
output[offset] = input[offset]
^ ctx->keystream8[ctx->keystream_bytes_used];
^ ctx->keystream8[ctx->keystream_bytes_used];
ctx->keystream_bytes_used++;
offset++;
@ -230,59 +228,59 @@ int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,
}
/* Process full blocks */
while( size >= CHACHA20_BLOCK_SIZE_BYTES )
{
while (size >= CHACHA20_BLOCK_SIZE_BYTES) {
/* Generate new keystream block and increment counter */
chacha20_block( ctx->state, ctx->keystream8 );
chacha20_block(ctx->state, ctx->keystream8);
ctx->state[CHACHA20_CTR_INDEX]++;
mbedtls_xor( output + offset, input + offset, ctx->keystream8, 64U );
mbedtls_xor(output + offset, input + offset, ctx->keystream8, 64U);
offset += CHACHA20_BLOCK_SIZE_BYTES;
size -= CHACHA20_BLOCK_SIZE_BYTES;
}
/* Last (partial) block */
if( size > 0U )
{
if (size > 0U) {
/* Generate new keystream block and increment counter */
chacha20_block( ctx->state, ctx->keystream8 );
chacha20_block(ctx->state, ctx->keystream8);
ctx->state[CHACHA20_CTR_INDEX]++;
mbedtls_xor( output + offset, input + offset, ctx->keystream8, size );
mbedtls_xor(output + offset, input + offset, ctx->keystream8, size);
ctx->keystream_bytes_used = size;
}
return( 0 );
return 0;
}
int mbedtls_chacha20_crypt( const unsigned char key[32],
const unsigned char nonce[12],
uint32_t counter,
size_t data_len,
const unsigned char* input,
unsigned char* output )
int mbedtls_chacha20_crypt(const unsigned char key[32],
const unsigned char nonce[12],
uint32_t counter,
size_t data_len,
const unsigned char *input,
unsigned char *output)
{
mbedtls_chacha20_context ctx;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_chacha20_init( &ctx );
mbedtls_chacha20_init(&ctx);
ret = mbedtls_chacha20_setkey( &ctx, key );
if( ret != 0 )
ret = mbedtls_chacha20_setkey(&ctx, key);
if (ret != 0) {
goto cleanup;
}
ret = mbedtls_chacha20_starts( &ctx, nonce, counter );
if( ret != 0 )
ret = mbedtls_chacha20_starts(&ctx, nonce, counter);
if (ret != 0) {
goto cleanup;
}
ret = mbedtls_chacha20_update( &ctx, data_len, input, output );
ret = mbedtls_chacha20_update(&ctx, data_len, input, output);
cleanup:
mbedtls_chacha20_free( &ctx );
return( ret );
mbedtls_chacha20_free(&ctx);
return ret;
}
#endif /* !MBEDTLS_CHACHA20_ALT */
@ -458,50 +456,52 @@ static const size_t test_lengths[2] =
/* Make sure no other definition is already present. */
#undef ASSERT
#define ASSERT( cond, args ) \
#define ASSERT(cond, args) \
do \
{ \
if( ! ( cond ) ) \
if (!(cond)) \
{ \
if( verbose != 0 ) \
mbedtls_printf args; \
if (verbose != 0) \
mbedtls_printf args; \
\
return( -1 ); \
return -1; \
} \
} \
while( 0 )
while (0)
int mbedtls_chacha20_self_test( int verbose )
int mbedtls_chacha20_self_test(int verbose)
{
unsigned char output[381];
unsigned i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
for( i = 0U; i < 2U; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ChaCha20 test %u ", i );
for (i = 0U; i < 2U; i++) {
if (verbose != 0) {
mbedtls_printf(" ChaCha20 test %u ", i);
}
ret = mbedtls_chacha20_crypt( test_keys[i],
test_nonces[i],
test_counters[i],
test_lengths[i],
test_input[i],
output );
ret = mbedtls_chacha20_crypt(test_keys[i],
test_nonces[i],
test_counters[i],
test_lengths[i],
test_input[i],
output);
ASSERT( 0 == ret, ( "error code: %i\n", ret ) );
ASSERT(0 == ret, ("error code: %i\n", ret));
ASSERT( 0 == memcmp( output, test_output[i], test_lengths[i] ),
( "failed (output)\n" ) );
ASSERT(0 == memcmp(output, test_output[i], test_lengths[i]),
("failed (output)\n"));
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@ -32,29 +32,30 @@
#if !defined(MBEDTLS_CHACHAPOLY_ALT)
#define CHACHAPOLY_STATE_INIT ( 0 )
#define CHACHAPOLY_STATE_AAD ( 1 )
#define CHACHAPOLY_STATE_CIPHERTEXT ( 2 ) /* Encrypting or decrypting */
#define CHACHAPOLY_STATE_FINISHED ( 3 )
#define CHACHAPOLY_STATE_INIT (0)
#define CHACHAPOLY_STATE_AAD (1)
#define CHACHAPOLY_STATE_CIPHERTEXT (2) /* Encrypting or decrypting */
#define CHACHAPOLY_STATE_FINISHED (3)
/**
* \brief Adds nul bytes to pad the AAD for Poly1305.
*
* \param ctx The ChaCha20-Poly1305 context.
*/
static int chachapoly_pad_aad( mbedtls_chachapoly_context *ctx )
static int chachapoly_pad_aad(mbedtls_chachapoly_context *ctx)
{
uint32_t partial_block_len = (uint32_t) ( ctx->aad_len % 16U );
uint32_t partial_block_len = (uint32_t) (ctx->aad_len % 16U);
unsigned char zeroes[15];
if( partial_block_len == 0U )
return( 0 );
if (partial_block_len == 0U) {
return 0;
}
memset( zeroes, 0, sizeof( zeroes ) );
memset(zeroes, 0, sizeof(zeroes));
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
return mbedtls_poly1305_update(&ctx->poly1305_ctx,
zeroes,
16U - partial_block_len);
}
/**
@ -62,80 +63,83 @@ static int chachapoly_pad_aad( mbedtls_chachapoly_context *ctx )
*
* \param ctx The ChaCha20-Poly1305 context.
*/
static int chachapoly_pad_ciphertext( mbedtls_chachapoly_context *ctx )
static int chachapoly_pad_ciphertext(mbedtls_chachapoly_context *ctx)
{
uint32_t partial_block_len = (uint32_t) ( ctx->ciphertext_len % 16U );
uint32_t partial_block_len = (uint32_t) (ctx->ciphertext_len % 16U);
unsigned char zeroes[15];
if( partial_block_len == 0U )
return( 0 );
if (partial_block_len == 0U) {
return 0;
}
memset( zeroes, 0, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
memset(zeroes, 0, sizeof(zeroes));
return mbedtls_poly1305_update(&ctx->poly1305_ctx,
zeroes,
16U - partial_block_len);
}
void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx )
void mbedtls_chachapoly_init(mbedtls_chachapoly_context *ctx)
{
mbedtls_chacha20_init( &ctx->chacha20_ctx );
mbedtls_poly1305_init( &ctx->poly1305_ctx );
mbedtls_chacha20_init(&ctx->chacha20_ctx);
mbedtls_poly1305_init(&ctx->poly1305_ctx);
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_INIT;
ctx->mode = MBEDTLS_CHACHAPOLY_ENCRYPT;
}
void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx )
void mbedtls_chachapoly_free(mbedtls_chachapoly_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_chacha20_free( &ctx->chacha20_ctx );
mbedtls_poly1305_free( &ctx->poly1305_ctx );
mbedtls_chacha20_free(&ctx->chacha20_ctx);
mbedtls_poly1305_free(&ctx->poly1305_ctx);
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_INIT;
ctx->mode = MBEDTLS_CHACHAPOLY_ENCRYPT;
}
int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,
const unsigned char key[32] )
int mbedtls_chachapoly_setkey(mbedtls_chachapoly_context *ctx,
const unsigned char key[32])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_chacha20_setkey( &ctx->chacha20_ctx, key );
ret = mbedtls_chacha20_setkey(&ctx->chacha20_ctx, key);
return( ret );
return ret;
}
int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
const unsigned char nonce[12],
mbedtls_chachapoly_mode_t mode )
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;
unsigned char poly1305_key[64];
/* Set counter = 0, will be update to 1 when generating Poly1305 key */
ret = mbedtls_chacha20_starts( &ctx->chacha20_ctx, nonce, 0U );
if( ret != 0 )
ret = mbedtls_chacha20_starts(&ctx->chacha20_ctx, nonce, 0U);
if (ret != 0) {
goto cleanup;
}
/* Generate the Poly1305 key by getting the ChaCha20 keystream output with
* counter = 0. This is the same as encrypting a buffer of zeroes.
* Only the first 256-bits (32 bytes) of the key is used for Poly1305.
* The other 256 bits are discarded.
*/
memset( poly1305_key, 0, sizeof( poly1305_key ) );
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, sizeof( poly1305_key ),
poly1305_key, poly1305_key );
if( ret != 0 )
memset(poly1305_key, 0, sizeof(poly1305_key));
ret = mbedtls_chacha20_update(&ctx->chacha20_ctx, sizeof(poly1305_key),
poly1305_key, poly1305_key);
if (ret != 0) {
goto cleanup;
}
ret = mbedtls_poly1305_starts( &ctx->poly1305_ctx, poly1305_key );
ret = mbedtls_poly1305_starts(&ctx->poly1305_ctx, poly1305_key);
if( ret == 0 )
{
if (ret == 0) {
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_AAD;
@ -143,92 +147,91 @@ int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
}
cleanup:
mbedtls_platform_zeroize( poly1305_key, 64U );
return( ret );
mbedtls_platform_zeroize(poly1305_key, 64U);
return ret;
}
int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,
const unsigned char *aad,
size_t aad_len )
int mbedtls_chachapoly_update_aad(mbedtls_chachapoly_context *ctx,
const unsigned char *aad,
size_t aad_len)
{
if( ctx->state != CHACHAPOLY_STATE_AAD )
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
if (ctx->state != CHACHAPOLY_STATE_AAD) {
return MBEDTLS_ERR_CHACHAPOLY_BAD_STATE;
}
ctx->aad_len += aad_len;
return( mbedtls_poly1305_update( &ctx->poly1305_ctx, aad, aad_len ) );
return mbedtls_poly1305_update(&ctx->poly1305_ctx, aad, aad_len);
}
int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,
size_t len,
const unsigned char *input,
unsigned char *output )
int mbedtls_chachapoly_update(mbedtls_chachapoly_context *ctx,
size_t len,
const unsigned char *input,
unsigned char *output)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ctx->state != CHACHAPOLY_STATE_AAD ) &&
( ctx->state != CHACHAPOLY_STATE_CIPHERTEXT ) )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
if ((ctx->state != CHACHAPOLY_STATE_AAD) &&
(ctx->state != CHACHAPOLY_STATE_CIPHERTEXT)) {
return MBEDTLS_ERR_CHACHAPOLY_BAD_STATE;
}
if( ctx->state == CHACHAPOLY_STATE_AAD )
{
if (ctx->state == CHACHAPOLY_STATE_AAD) {
ctx->state = CHACHAPOLY_STATE_CIPHERTEXT;
ret = chachapoly_pad_aad( ctx );
if( ret != 0 )
return( ret );
ret = chachapoly_pad_aad(ctx);
if (ret != 0) {
return ret;
}
}
ctx->ciphertext_len += len;
if( ctx->mode == MBEDTLS_CHACHAPOLY_ENCRYPT )
{
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );
if( ret != 0 )
return( ret );
if (ctx->mode == MBEDTLS_CHACHAPOLY_ENCRYPT) {
ret = mbedtls_chacha20_update(&ctx->chacha20_ctx, len, input, output);
if (ret != 0) {
return ret;
}
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, output, len );
if( ret != 0 )
return( ret );
}
else /* DECRYPT */
{
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, input, len );
if( ret != 0 )
return( ret );
ret = mbedtls_poly1305_update(&ctx->poly1305_ctx, output, len);
if (ret != 0) {
return ret;
}
} else { /* DECRYPT */
ret = mbedtls_poly1305_update(&ctx->poly1305_ctx, input, len);
if (ret != 0) {
return ret;
}
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );
if( ret != 0 )
return( ret );
ret = mbedtls_chacha20_update(&ctx->chacha20_ctx, len, input, output);
if (ret != 0) {
return ret;
}
}
return( 0 );
return 0;
}
int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
unsigned char mac[16] )
int mbedtls_chachapoly_finish(mbedtls_chachapoly_context *ctx,
unsigned char mac[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char len_block[16];
if( ctx->state == CHACHAPOLY_STATE_INIT )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
if (ctx->state == CHACHAPOLY_STATE_INIT) {
return MBEDTLS_ERR_CHACHAPOLY_BAD_STATE;
}
if( ctx->state == CHACHAPOLY_STATE_AAD )
{
ret = chachapoly_pad_aad( ctx );
if( ret != 0 )
return( ret );
}
else if( ctx->state == CHACHAPOLY_STATE_CIPHERTEXT )
{
ret = chachapoly_pad_ciphertext( ctx );
if( ret != 0 )
return( ret );
if (ctx->state == CHACHAPOLY_STATE_AAD) {
ret = chachapoly_pad_aad(ctx);
if (ret != 0) {
return ret;
}
} else if (ctx->state == CHACHAPOLY_STATE_CIPHERTEXT) {
ret = chachapoly_pad_ciphertext(ctx);
if (ret != 0) {
return ret;
}
}
ctx->state = CHACHAPOLY_STATE_FINISHED;
@ -239,91 +242,94 @@ int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
MBEDTLS_PUT_UINT64_LE(ctx->aad_len, len_block, 0);
MBEDTLS_PUT_UINT64_LE(ctx->ciphertext_len, len_block, 8);
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, len_block, 16U );
if( ret != 0 )
return( ret );
ret = mbedtls_poly1305_update(&ctx->poly1305_ctx, len_block, 16U);
if (ret != 0) {
return ret;
}
ret = mbedtls_poly1305_finish( &ctx->poly1305_ctx, mac );
ret = mbedtls_poly1305_finish(&ctx->poly1305_ctx, mac);
return( ret );
return ret;
}
static int chachapoly_crypt_and_tag( mbedtls_chachapoly_context *ctx,
mbedtls_chachapoly_mode_t mode,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16] )
static int chachapoly_crypt_and_tag(mbedtls_chachapoly_context *ctx,
mbedtls_chachapoly_mode_t mode,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_chachapoly_starts( ctx, nonce, mode );
if( ret != 0 )
ret = mbedtls_chachapoly_starts(ctx, nonce, mode);
if (ret != 0) {
goto cleanup;
}
ret = mbedtls_chachapoly_update_aad( ctx, aad, aad_len );
if( ret != 0 )
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 )
ret = mbedtls_chachapoly_update(ctx, length, input, output);
if (ret != 0) {
goto cleanup;
}
ret = mbedtls_chachapoly_finish( ctx, tag );
ret = mbedtls_chachapoly_finish(ctx, tag);
cleanup:
return( ret );
return ret;
}
int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16] )
int mbedtls_chachapoly_encrypt_and_tag(mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16])
{
return( chachapoly_crypt_and_tag( ctx, MBEDTLS_CHACHAPOLY_ENCRYPT,
length, nonce, aad, aad_len,
input, output, tag ) );
return chachapoly_crypt_and_tag(ctx, MBEDTLS_CHACHAPOLY_ENCRYPT,
length, nonce, aad, aad_len,
input, output, tag);
}
int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char tag[16],
const unsigned char *input,
unsigned char *output )
int mbedtls_chachapoly_auth_decrypt(mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char tag[16],
const unsigned char *input,
unsigned char *output)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char check_tag[16];
size_t i;
int diff;
if( ( ret = chachapoly_crypt_and_tag( ctx,
MBEDTLS_CHACHAPOLY_DECRYPT, length, nonce,
aad, aad_len, input, output, check_tag ) ) != 0 )
{
return( ret );
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++ )
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 );
if (diff != 0) {
mbedtls_platform_zeroize(output, length);
return MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED;
}
return 0;
}
#endif /* MBEDTLS_CHACHAPOLY_ALT */
@ -419,20 +425,20 @@ static const unsigned char test_mac[1][16] =
/* Make sure no other definition is already present. */
#undef ASSERT
#define ASSERT( cond, args ) \
#define ASSERT(cond, args) \
do \
{ \
if( ! ( cond ) ) \
if (!(cond)) \
{ \
if( verbose != 0 ) \
mbedtls_printf args; \
if (verbose != 0) \
mbedtls_printf args; \
\
return( -1 ); \
return -1; \
} \
} \
while( 0 )
while (0)
int mbedtls_chachapoly_self_test( int verbose )
int mbedtls_chachapoly_self_test(int verbose)
{
mbedtls_chachapoly_context ctx;
unsigned i;
@ -440,43 +446,45 @@ int mbedtls_chachapoly_self_test( int verbose )
unsigned char output[200];
unsigned char mac[16];
for( i = 0U; i < 1U; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ChaCha20-Poly1305 test %u ", i );
for (i = 0U; i < 1U; i++) {
if (verbose != 0) {
mbedtls_printf(" ChaCha20-Poly1305 test %u ", i);
}
mbedtls_chachapoly_init( &ctx );
mbedtls_chachapoly_init(&ctx);
ret = mbedtls_chachapoly_setkey( &ctx, test_key[i] );
ASSERT( 0 == ret, ( "setkey() error code: %i\n", ret ) );
ret = mbedtls_chachapoly_setkey(&ctx, test_key[i]);
ASSERT(0 == ret, ("setkey() error code: %i\n", ret));
ret = mbedtls_chachapoly_encrypt_and_tag( &ctx,
test_input_len[i],
test_nonce[i],
test_aad[i],
test_aad_len[i],
test_input[i],
output,
mac );
ret = mbedtls_chachapoly_encrypt_and_tag(&ctx,
test_input_len[i],
test_nonce[i],
test_aad[i],
test_aad_len[i],
test_input[i],
output,
mac);
ASSERT( 0 == ret, ( "crypt_and_tag() error code: %i\n", ret ) );
ASSERT(0 == 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(output, test_output[i], test_input_len[i]),
("failure (wrong output)\n"));
ASSERT( 0 == memcmp( mac, test_mac[i], 16U ),
( "failure (wrong MAC)\n" ) );
ASSERT(0 == memcmp(mac, test_mac[i], 16U),
("failure (wrong MAC)\n"));
mbedtls_chachapoly_free( &ctx );
mbedtls_chachapoly_free(&ctx);
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@ -29,57 +29,57 @@
#define MBEDTLS_CHECK_CRYPTO_CONFIG_H
#if defined(PSA_WANT_ALG_CCM) && \
!( defined(PSA_WANT_KEY_TYPE_AES) || \
defined(PSA_WANT_KEY_TYPE_CAMELLIA) )
!(defined(PSA_WANT_KEY_TYPE_AES) || \
defined(PSA_WANT_KEY_TYPE_CAMELLIA))
#error "PSA_WANT_ALG_CCM defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_CMAC) && \
!( defined(PSA_WANT_KEY_TYPE_AES) || \
defined(PSA_WANT_KEY_TYPE_CAMELLIA) || \
defined(PSA_WANT_KEY_TYPE_DES) )
!(defined(PSA_WANT_KEY_TYPE_AES) || \
defined(PSA_WANT_KEY_TYPE_CAMELLIA) || \
defined(PSA_WANT_KEY_TYPE_DES))
#error "PSA_WANT_ALG_CMAC defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA) && \
!( defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) )
!(defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY))
#error "PSA_WANT_ALG_DETERMINISTIC_ECDSA defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_ECDSA) && \
!( defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) )
!(defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY))
#error "PSA_WANT_ALG_ECDSA defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_GCM) && \
!( defined(PSA_WANT_KEY_TYPE_AES) || \
defined(PSA_WANT_KEY_TYPE_CAMELLIA) )
!(defined(PSA_WANT_KEY_TYPE_AES) || \
defined(PSA_WANT_KEY_TYPE_CAMELLIA))
#error "PSA_WANT_ALG_GCM defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_RSA_PKCS1V15_CRYPT) && \
!( defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY) )
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_PKCS1V15_CRYPT defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) && \
!( defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY) )
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_PKCS1V15_SIGN defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_RSA_OAEP) && \
!( defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY) )
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_OAEP defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_RSA_PSS) && \
!( defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY) )
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_PSS defined, but not all prerequisites"
#endif
@ -89,7 +89,7 @@
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_USE_PSA_CRYPTO) && \
!( defined(PSA_WANT_ALG_SHA_1) || defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_512) )
!(defined(PSA_WANT_ALG_SHA_1) || defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_512))
#error "MBEDTLS_SSL_PROTO_TLS1_2 defined, but not all prerequisites"
#endif

File diff suppressed because it is too large Load Diff

View File

@ -72,100 +72,101 @@
#if defined(MBEDTLS_GCM_C)
/* shared by all GCM ciphers */
static void *gcm_ctx_alloc( void )
static void *gcm_ctx_alloc(void)
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_gcm_context ) );
void *ctx = mbedtls_calloc(1, sizeof(mbedtls_gcm_context));
if( ctx != NULL )
mbedtls_gcm_init( (mbedtls_gcm_context *) ctx );
if (ctx != NULL) {
mbedtls_gcm_init((mbedtls_gcm_context *) ctx);
}
return( ctx );
return ctx;
}
static void gcm_ctx_free( void *ctx )
static void gcm_ctx_free(void *ctx)
{
mbedtls_gcm_free( ctx );
mbedtls_free( ctx );
mbedtls_gcm_free(ctx);
mbedtls_free(ctx);
}
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
/* shared by all CCM ciphers */
static void *ccm_ctx_alloc( void )
static void *ccm_ctx_alloc(void)
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ccm_context ) );
void *ctx = mbedtls_calloc(1, sizeof(mbedtls_ccm_context));
if( ctx != NULL )
mbedtls_ccm_init( (mbedtls_ccm_context *) ctx );
if (ctx != NULL) {
mbedtls_ccm_init((mbedtls_ccm_context *) ctx);
}
return( ctx );
return ctx;
}
static void ccm_ctx_free( void *ctx )
static void ccm_ctx_free(void *ctx)
{
mbedtls_ccm_free( ctx );
mbedtls_free( ctx );
mbedtls_ccm_free(ctx);
mbedtls_free(ctx);
}
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_AES_C)
static int aes_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
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 );
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 )
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 );
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,
const unsigned char *input, unsigned char *output )
static int aes_crypt_cfb128_wrap(void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output)
{
return mbedtls_aes_crypt_cfb128( (mbedtls_aes_context *) ctx, operation, length, iv_off, iv,
input, output );
return mbedtls_aes_crypt_cfb128((mbedtls_aes_context *) ctx, operation, length, iv_off, iv,
input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
static int aes_crypt_ofb_wrap( void *ctx, size_t length, size_t *iv_off,
unsigned char *iv, const unsigned char *input, unsigned char *output )
static int aes_crypt_ofb_wrap(void *ctx, size_t length, size_t *iv_off,
unsigned char *iv, const unsigned char *input, unsigned char *output)
{
return mbedtls_aes_crypt_ofb( (mbedtls_aes_context *) ctx, length, iv_off,
iv, input, output );
return mbedtls_aes_crypt_ofb((mbedtls_aes_context *) ctx, length, iv_off,
iv, input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static int aes_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
static int aes_crypt_ctr_wrap(void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output)
{
return mbedtls_aes_crypt_ctr( (mbedtls_aes_context *) ctx, length, nc_off, nonce_counter,
stream_block, input, output );
return mbedtls_aes_crypt_ctr((mbedtls_aes_context *) ctx, length, nc_off, nonce_counter,
stream_block, input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
static int aes_crypt_xts_wrap( void *ctx, mbedtls_operation_t operation,
size_t length,
const unsigned char data_unit[16],
const unsigned char *input,
unsigned char *output )
static int aes_crypt_xts_wrap(void *ctx, mbedtls_operation_t operation,
size_t length,
const unsigned char data_unit[16],
const unsigned char *input,
unsigned char *output)
{
mbedtls_aes_xts_context *xts_ctx = ctx;
int mode;
switch( operation )
{
switch (operation) {
case MBEDTLS_ENCRYPT:
mode = MBEDTLS_AES_ENCRYPT;
break;
@ -176,39 +177,40 @@ static int aes_crypt_xts_wrap( void *ctx, mbedtls_operation_t operation,
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
return mbedtls_aes_crypt_xts( xts_ctx, mode, length,
data_unit, input, output );
return mbedtls_aes_crypt_xts(xts_ctx, mode, length,
data_unit, input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_XTS */
static int aes_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int aes_setkey_dec_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_aes_setkey_dec( (mbedtls_aes_context *) ctx, key, key_bitlen );
return mbedtls_aes_setkey_dec((mbedtls_aes_context *) ctx, key, key_bitlen);
}
static int aes_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int aes_setkey_enc_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_aes_setkey_enc( (mbedtls_aes_context *) ctx, key, key_bitlen );
return mbedtls_aes_setkey_enc((mbedtls_aes_context *) ctx, key, key_bitlen);
}
static void * aes_ctx_alloc( void )
static void *aes_ctx_alloc(void)
{
mbedtls_aes_context *aes = mbedtls_calloc( 1, sizeof( mbedtls_aes_context ) );
mbedtls_aes_context *aes = mbedtls_calloc(1, sizeof(mbedtls_aes_context));
if( aes == NULL )
return( NULL );
if (aes == NULL) {
return NULL;
}
mbedtls_aes_init( aes );
mbedtls_aes_init(aes);
return( aes );
return aes;
}
static void aes_ctx_free( void *ctx )
static void aes_ctx_free(void *ctx)
{
mbedtls_aes_free( (mbedtls_aes_context *) ctx );
mbedtls_free( ctx );
mbedtls_aes_free((mbedtls_aes_context *) ctx);
mbedtls_free(ctx);
}
static const mbedtls_cipher_base_t aes_info = {
@ -412,39 +414,41 @@ static const mbedtls_cipher_info_t aes_256_ctr_info = {
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
static int xts_aes_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int xts_aes_setkey_enc_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
mbedtls_aes_xts_context *xts_ctx = ctx;
return( mbedtls_aes_xts_setkey_enc( xts_ctx, key, key_bitlen ) );
return mbedtls_aes_xts_setkey_enc(xts_ctx, key, key_bitlen);
}
static int xts_aes_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int xts_aes_setkey_dec_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
mbedtls_aes_xts_context *xts_ctx = ctx;
return( mbedtls_aes_xts_setkey_dec( xts_ctx, key, key_bitlen ) );
return mbedtls_aes_xts_setkey_dec(xts_ctx, key, key_bitlen);
}
static void *xts_aes_ctx_alloc( void )
static void *xts_aes_ctx_alloc(void)
{
mbedtls_aes_xts_context *xts_ctx = mbedtls_calloc( 1, sizeof( *xts_ctx ) );
mbedtls_aes_xts_context *xts_ctx = mbedtls_calloc(1, sizeof(*xts_ctx));
if( xts_ctx != NULL )
mbedtls_aes_xts_init( xts_ctx );
if (xts_ctx != NULL) {
mbedtls_aes_xts_init(xts_ctx);
}
return( xts_ctx );
return xts_ctx;
}
static void xts_aes_ctx_free( void *ctx )
static void xts_aes_ctx_free(void *ctx)
{
mbedtls_aes_xts_context *xts_ctx = ctx;
if( xts_ctx == NULL )
if (xts_ctx == NULL) {
return;
}
mbedtls_aes_xts_free( xts_ctx );
mbedtls_free( xts_ctx );
mbedtls_aes_xts_free(xts_ctx);
mbedtls_free(xts_ctx);
}
static const mbedtls_cipher_base_t xts_aes_info = {
@ -498,11 +502,11 @@ static const mbedtls_cipher_info_t aes_256_xts_info = {
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_GCM_C)
static int gcm_aes_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int gcm_aes_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_AES,
key, key_bitlen );
return mbedtls_gcm_setkey((mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_AES,
key, key_bitlen);
}
static const mbedtls_cipher_base_t gcm_aes_info = {
@ -567,11 +571,11 @@ static const mbedtls_cipher_info_t aes_256_gcm_info = {
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
static int ccm_aes_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int ccm_aes_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_AES,
key, key_bitlen );
return mbedtls_ccm_setkey((mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_AES,
key, key_bitlen);
}
static const mbedtls_cipher_base_t ccm_aes_info = {
@ -672,72 +676,73 @@ static const mbedtls_cipher_info_t aes_256_ccm_star_no_tag_info = {
#if defined(MBEDTLS_CAMELLIA_C)
static int camellia_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
static int camellia_crypt_ecb_wrap(void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output)
{
return mbedtls_camellia_crypt_ecb( (mbedtls_camellia_context *) ctx, operation, input,
output );
return mbedtls_camellia_crypt_ecb((mbedtls_camellia_context *) ctx, operation, input,
output);
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int camellia_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, unsigned char *iv,
const unsigned char *input, unsigned char *output )
static int camellia_crypt_cbc_wrap(void *ctx, mbedtls_operation_t operation,
size_t length, unsigned char *iv,
const unsigned char *input, unsigned char *output)
{
return mbedtls_camellia_crypt_cbc( (mbedtls_camellia_context *) ctx, operation, length, iv,
input, output );
return mbedtls_camellia_crypt_cbc((mbedtls_camellia_context *) ctx, operation, length, iv,
input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static int camellia_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output )
static int camellia_crypt_cfb128_wrap(void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output)
{
return mbedtls_camellia_crypt_cfb128( (mbedtls_camellia_context *) ctx, operation, length,
iv_off, iv, input, output );
return mbedtls_camellia_crypt_cfb128((mbedtls_camellia_context *) ctx, operation, length,
iv_off, iv, input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static int camellia_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
static int camellia_crypt_ctr_wrap(void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output)
{
return mbedtls_camellia_crypt_ctr( (mbedtls_camellia_context *) ctx, length, nc_off,
nonce_counter, stream_block, input, output );
return mbedtls_camellia_crypt_ctr((mbedtls_camellia_context *) ctx, length, nc_off,
nonce_counter, stream_block, input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
static int camellia_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int camellia_setkey_dec_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_camellia_setkey_dec( (mbedtls_camellia_context *) ctx, key, key_bitlen );
return mbedtls_camellia_setkey_dec((mbedtls_camellia_context *) ctx, key, key_bitlen);
}
static int camellia_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int camellia_setkey_enc_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_camellia_setkey_enc( (mbedtls_camellia_context *) ctx, key, key_bitlen );
return mbedtls_camellia_setkey_enc((mbedtls_camellia_context *) ctx, key, key_bitlen);
}
static void * camellia_ctx_alloc( void )
static void *camellia_ctx_alloc(void)
{
mbedtls_camellia_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_camellia_context ) );
ctx = mbedtls_calloc(1, sizeof(mbedtls_camellia_context));
if( ctx == NULL )
return( NULL );
if (ctx == NULL) {
return NULL;
}
mbedtls_camellia_init( ctx );
mbedtls_camellia_init(ctx);
return( ctx );
return ctx;
}
static void camellia_ctx_free( void *ctx )
static void camellia_ctx_free(void *ctx)
{
mbedtls_camellia_free( (mbedtls_camellia_context *) ctx );
mbedtls_free( ctx );
mbedtls_camellia_free((mbedtls_camellia_context *) ctx);
mbedtls_free(ctx);
}
static const mbedtls_cipher_base_t camellia_info = {
@ -906,11 +911,11 @@ static const mbedtls_cipher_info_t camellia_256_ctr_info = {
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_GCM_C)
static int gcm_camellia_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int gcm_camellia_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,
key, key_bitlen );
return mbedtls_gcm_setkey((mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,
key, key_bitlen);
}
static const mbedtls_cipher_base_t gcm_camellia_info = {
@ -975,11 +980,11 @@ static const mbedtls_cipher_info_t camellia_256_gcm_info = {
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
static int ccm_camellia_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int ccm_camellia_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,
key, key_bitlen );
return mbedtls_ccm_setkey((mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,
key, key_bitlen);
}
static const mbedtls_cipher_base_t ccm_camellia_info = {
@ -1080,73 +1085,74 @@ static const mbedtls_cipher_info_t camellia_256_ccm_star_no_tag_info = {
#if defined(MBEDTLS_ARIA_C)
static int aria_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
static int aria_crypt_ecb_wrap(void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output)
{
(void) operation;
return mbedtls_aria_crypt_ecb( (mbedtls_aria_context *) ctx, input,
output );
return mbedtls_aria_crypt_ecb((mbedtls_aria_context *) ctx, input,
output);
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int aria_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, unsigned char *iv,
const unsigned char *input, unsigned char *output )
static int aria_crypt_cbc_wrap(void *ctx, mbedtls_operation_t operation,
size_t length, unsigned char *iv,
const unsigned char *input, unsigned char *output)
{
return mbedtls_aria_crypt_cbc( (mbedtls_aria_context *) ctx, operation, length, iv,
input, output );
return mbedtls_aria_crypt_cbc((mbedtls_aria_context *) ctx, operation, length, iv,
input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static int aria_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output )
static int aria_crypt_cfb128_wrap(void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output)
{
return mbedtls_aria_crypt_cfb128( (mbedtls_aria_context *) ctx, operation, length,
iv_off, iv, input, output );
return mbedtls_aria_crypt_cfb128((mbedtls_aria_context *) ctx, operation, length,
iv_off, iv, input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static int aria_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
static int aria_crypt_ctr_wrap(void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output)
{
return mbedtls_aria_crypt_ctr( (mbedtls_aria_context *) ctx, length, nc_off,
nonce_counter, stream_block, input, output );
return mbedtls_aria_crypt_ctr((mbedtls_aria_context *) ctx, length, nc_off,
nonce_counter, stream_block, input, output);
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
static int aria_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int aria_setkey_dec_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_aria_setkey_dec( (mbedtls_aria_context *) ctx, key, key_bitlen );
return mbedtls_aria_setkey_dec((mbedtls_aria_context *) ctx, key, key_bitlen);
}
static int aria_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int aria_setkey_enc_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_aria_setkey_enc( (mbedtls_aria_context *) ctx, key, key_bitlen );
return mbedtls_aria_setkey_enc((mbedtls_aria_context *) ctx, key, key_bitlen);
}
static void * aria_ctx_alloc( void )
static void *aria_ctx_alloc(void)
{
mbedtls_aria_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_aria_context ) );
ctx = mbedtls_calloc(1, sizeof(mbedtls_aria_context));
if( ctx == NULL )
return( NULL );
if (ctx == NULL) {
return NULL;
}
mbedtls_aria_init( ctx );
mbedtls_aria_init(ctx);
return( ctx );
return ctx;
}
static void aria_ctx_free( void *ctx )
static void aria_ctx_free(void *ctx)
{
mbedtls_aria_free( (mbedtls_aria_context *) ctx );
mbedtls_free( ctx );
mbedtls_aria_free((mbedtls_aria_context *) ctx);
mbedtls_free(ctx);
}
static const mbedtls_cipher_base_t aria_info = {
@ -1315,11 +1321,11 @@ static const mbedtls_cipher_info_t aria_256_ctr_info = {
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_GCM_C)
static int gcm_aria_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int gcm_aria_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,
key, key_bitlen );
return mbedtls_gcm_setkey((mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,
key, key_bitlen);
}
static const mbedtls_cipher_base_t gcm_aria_info = {
@ -1384,11 +1390,11 @@ static const mbedtls_cipher_info_t aria_256_gcm_info = {
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
static int ccm_aria_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int ccm_aria_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,
key, key_bitlen );
return mbedtls_ccm_setkey((mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,
key, key_bitlen);
}
static const mbedtls_cipher_base_t ccm_aria_info = {
@ -1489,121 +1495,123 @@ static const mbedtls_cipher_info_t aria_256_ccm_star_no_tag_info = {
#if defined(MBEDTLS_DES_C)
static int des_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
static int des_crypt_ecb_wrap(void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output)
{
((void) operation);
return mbedtls_des_crypt_ecb( (mbedtls_des_context *) ctx, input, output );
return mbedtls_des_crypt_ecb((mbedtls_des_context *) ctx, input, output);
}
static int des3_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
static int des3_crypt_ecb_wrap(void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output)
{
((void) operation);
return mbedtls_des3_crypt_ecb( (mbedtls_des3_context *) ctx, input, output );
return mbedtls_des3_crypt_ecb((mbedtls_des3_context *) ctx, input, output);
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int des_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
static int des_crypt_cbc_wrap(void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output)
{
return mbedtls_des_crypt_cbc( (mbedtls_des_context *) ctx, operation, length, iv, input,
output );
return mbedtls_des_crypt_cbc((mbedtls_des_context *) ctx, operation, length, iv, input,
output);
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int des3_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
static int des3_crypt_cbc_wrap(void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output)
{
return mbedtls_des3_crypt_cbc( (mbedtls_des3_context *) ctx, operation, length, iv, input,
output );
return mbedtls_des3_crypt_cbc((mbedtls_des3_context *) ctx, operation, length, iv, input,
output);
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
static int des_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int des_setkey_dec_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
((void) key_bitlen);
return mbedtls_des_setkey_dec( (mbedtls_des_context *) ctx, key );
return mbedtls_des_setkey_dec((mbedtls_des_context *) ctx, key);
}
static int des_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int des_setkey_enc_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
((void) key_bitlen);
return mbedtls_des_setkey_enc( (mbedtls_des_context *) ctx, key );
return mbedtls_des_setkey_enc((mbedtls_des_context *) ctx, key);
}
static int des3_set2key_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int des3_set2key_dec_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
((void) key_bitlen);
return mbedtls_des3_set2key_dec( (mbedtls_des3_context *) ctx, key );
return mbedtls_des3_set2key_dec((mbedtls_des3_context *) ctx, key);
}
static int des3_set2key_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int des3_set2key_enc_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
((void) key_bitlen);
return mbedtls_des3_set2key_enc( (mbedtls_des3_context *) ctx, key );
return mbedtls_des3_set2key_enc((mbedtls_des3_context *) ctx, key);
}
static int des3_set3key_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int des3_set3key_dec_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
((void) key_bitlen);
return mbedtls_des3_set3key_dec( (mbedtls_des3_context *) ctx, key );
return mbedtls_des3_set3key_dec((mbedtls_des3_context *) ctx, key);
}
static int des3_set3key_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int des3_set3key_enc_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
((void) key_bitlen);
return mbedtls_des3_set3key_enc( (mbedtls_des3_context *) ctx, key );
return mbedtls_des3_set3key_enc((mbedtls_des3_context *) ctx, key);
}
static void * des_ctx_alloc( void )
static void *des_ctx_alloc(void)
{
mbedtls_des_context *des = mbedtls_calloc( 1, sizeof( mbedtls_des_context ) );
mbedtls_des_context *des = mbedtls_calloc(1, sizeof(mbedtls_des_context));
if( des == NULL )
return( NULL );
if (des == NULL) {
return NULL;
}
mbedtls_des_init( des );
mbedtls_des_init(des);
return( des );
return des;
}
static void des_ctx_free( void *ctx )
static void des_ctx_free(void *ctx)
{
mbedtls_des_free( (mbedtls_des_context *) ctx );
mbedtls_free( ctx );
mbedtls_des_free((mbedtls_des_context *) ctx);
mbedtls_free(ctx);
}
static void * des3_ctx_alloc( void )
static void *des3_ctx_alloc(void)
{
mbedtls_des3_context *des3;
des3 = mbedtls_calloc( 1, sizeof( mbedtls_des3_context ) );
des3 = mbedtls_calloc(1, sizeof(mbedtls_des3_context));
if( des3 == NULL )
return( NULL );
if (des3 == NULL) {
return NULL;
}
mbedtls_des3_init( des3 );
mbedtls_des3_init(des3);
return( des3 );
return des3;
}
static void des3_ctx_free( void *ctx )
static void des3_ctx_free(void *ctx)
{
mbedtls_des3_free( (mbedtls_des3_context *) ctx );
mbedtls_free( ctx );
mbedtls_des3_free((mbedtls_des3_context *) ctx);
mbedtls_free(ctx);
}
static const mbedtls_cipher_base_t des_info = {
@ -1761,48 +1769,52 @@ static const mbedtls_cipher_info_t des_ede3_cbc_info = {
#if defined(MBEDTLS_CHACHA20_C)
static int chacha20_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int chacha20_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
if( key_bitlen != 256U )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (key_bitlen != 256U) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
if ( 0 != mbedtls_chacha20_setkey( (mbedtls_chacha20_context*)ctx, key ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (0 != mbedtls_chacha20_setkey((mbedtls_chacha20_context *) ctx, key)) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
return( 0 );
return 0;
}
static int chacha20_stream_wrap( void *ctx, size_t length,
const unsigned char *input,
unsigned char *output )
static int chacha20_stream_wrap(void *ctx, size_t length,
const unsigned char *input,
unsigned char *output)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_chacha20_update( ctx, length, input, output );
if( ret == MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
ret = mbedtls_chacha20_update(ctx, length, input, output);
if (ret == MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
return( ret );
return ret;
}
static void * chacha20_ctx_alloc( void )
static void *chacha20_ctx_alloc(void)
{
mbedtls_chacha20_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_chacha20_context ) );
ctx = mbedtls_calloc(1, sizeof(mbedtls_chacha20_context));
if( ctx == NULL )
return( NULL );
if (ctx == NULL) {
return NULL;
}
mbedtls_chacha20_init( ctx );
mbedtls_chacha20_init(ctx);
return( ctx );
return ctx;
}
static void chacha20_ctx_free( void *ctx )
static void chacha20_ctx_free(void *ctx)
{
mbedtls_chacha20_free( (mbedtls_chacha20_context *) ctx );
mbedtls_free( ctx );
mbedtls_chacha20_free((mbedtls_chacha20_context *) ctx);
mbedtls_free(ctx);
}
static const mbedtls_cipher_base_t chacha20_base_info = {
@ -1845,36 +1857,39 @@ static const mbedtls_cipher_info_t chacha20_info = {
#if defined(MBEDTLS_CHACHAPOLY_C)
static int chachapoly_setkey_wrap( void *ctx,
const unsigned char *key,
unsigned int key_bitlen )
static int chachapoly_setkey_wrap(void *ctx,
const unsigned char *key,
unsigned int key_bitlen)
{
if( key_bitlen != 256U )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (key_bitlen != 256U) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
if ( 0 != mbedtls_chachapoly_setkey( (mbedtls_chachapoly_context*)ctx, key ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (0 != mbedtls_chachapoly_setkey((mbedtls_chachapoly_context *) ctx, key)) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
return( 0 );
return 0;
}
static void * chachapoly_ctx_alloc( void )
static void *chachapoly_ctx_alloc(void)
{
mbedtls_chachapoly_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_chachapoly_context ) );
ctx = mbedtls_calloc(1, sizeof(mbedtls_chachapoly_context));
if( ctx == NULL )
return( NULL );
if (ctx == NULL) {
return NULL;
}
mbedtls_chachapoly_init( ctx );
mbedtls_chachapoly_init(ctx);
return( ctx );
return ctx;
}
static void chachapoly_ctx_free( void *ctx )
static void chachapoly_ctx_free(void *ctx)
{
mbedtls_chachapoly_free( (mbedtls_chachapoly_context *) ctx );
mbedtls_free( ctx );
mbedtls_chachapoly_free((mbedtls_chachapoly_context *) ctx);
mbedtls_free(ctx);
}
static const mbedtls_cipher_base_t chachapoly_base_info = {
@ -1916,31 +1931,31 @@ static const mbedtls_cipher_info_t chachapoly_info = {
#endif /* MBEDTLS_CHACHAPOLY_C */
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
static int null_crypt_stream( void *ctx, size_t length,
const unsigned char *input,
unsigned char *output )
static int null_crypt_stream(void *ctx, size_t length,
const unsigned char *input,
unsigned char *output)
{
((void) ctx);
memmove( output, input, length );
return( 0 );
memmove(output, input, length);
return 0;
}
static int null_setkey( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int null_setkey(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
((void) ctx);
((void) key);
((void) key_bitlen);
return( 0 );
return 0;
}
static void * null_ctx_alloc( void )
static void *null_ctx_alloc(void)
{
return( (void *) 1 );
return (void *) 1;
}
static void null_ctx_free( void *ctx )
static void null_ctx_free(void *ctx)
{
((void) ctx);
}
@ -1985,34 +2000,35 @@ static const mbedtls_cipher_info_t null_cipher_info = {
#endif /* defined(MBEDTLS_CIPHER_NULL_CIPHER) */
#if defined(MBEDTLS_NIST_KW_C)
static void *kw_ctx_alloc( void )
static void *kw_ctx_alloc(void)
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_nist_kw_context ) );
void *ctx = mbedtls_calloc(1, sizeof(mbedtls_nist_kw_context));
if( ctx != NULL )
mbedtls_nist_kw_init( (mbedtls_nist_kw_context *) ctx );
if (ctx != NULL) {
mbedtls_nist_kw_init((mbedtls_nist_kw_context *) ctx);
}
return( ctx );
return ctx;
}
static void kw_ctx_free( void *ctx )
static void kw_ctx_free(void *ctx)
{
mbedtls_nist_kw_free( ctx );
mbedtls_free( ctx );
mbedtls_nist_kw_free(ctx);
mbedtls_free(ctx);
}
static int kw_aes_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int kw_aes_setkey_wrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_nist_kw_setkey( (mbedtls_nist_kw_context *) ctx,
MBEDTLS_CIPHER_ID_AES, key, key_bitlen, 1 );
return mbedtls_nist_kw_setkey((mbedtls_nist_kw_context *) ctx,
MBEDTLS_CIPHER_ID_AES, key, key_bitlen, 1);
}
static int kw_aes_setkey_unwrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
static int kw_aes_setkey_unwrap(void *ctx, const unsigned char *key,
unsigned int key_bitlen)
{
return mbedtls_nist_kw_setkey( (mbedtls_nist_kw_context *) ctx,
MBEDTLS_CIPHER_ID_AES, key, key_bitlen, 0 );
return mbedtls_nist_kw_setkey((mbedtls_nist_kw_context *) ctx,
MBEDTLS_CIPHER_ID_AES, key, key_bitlen, 0);
}
static const mbedtls_cipher_base_t kw_aes_info = {
@ -2257,8 +2273,8 @@ const mbedtls_cipher_definition_t mbedtls_cipher_definitions[] =
{ MBEDTLS_CIPHER_NONE, NULL }
};
#define NUM_CIPHERS ( sizeof(mbedtls_cipher_definitions) / \
sizeof(mbedtls_cipher_definitions[0]) )
#define NUM_CIPHERS (sizeof(mbedtls_cipher_definitions) / \
sizeof(mbedtls_cipher_definitions[0]))
int mbedtls_cipher_supported[NUM_CIPHERS];
#endif /* MBEDTLS_CIPHER_C */

View File

@ -39,82 +39,79 @@ extern "C" {
/**
* Base cipher information. The non-mode specific functions and values.
*/
struct mbedtls_cipher_base_t
{
struct mbedtls_cipher_base_t {
/** Base Cipher type (e.g. MBEDTLS_CIPHER_ID_AES) */
mbedtls_cipher_id_t cipher;
/** Encrypt using ECB */
int (*ecb_func)( void *ctx, mbedtls_operation_t mode,
const unsigned char *input, unsigned char *output );
int (*ecb_func)(void *ctx, mbedtls_operation_t mode,
const unsigned char *input, unsigned char *output);
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/** Encrypt using CBC */
int (*cbc_func)( void *ctx, mbedtls_operation_t mode, size_t length,
unsigned char *iv, const unsigned char *input,
unsigned char *output );
int (*cbc_func)(void *ctx, mbedtls_operation_t mode, size_t length,
unsigned char *iv, const unsigned char *input,
unsigned char *output);
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
/** Encrypt using CFB (Full length) */
int (*cfb_func)( void *ctx, mbedtls_operation_t mode, size_t length, size_t *iv_off,
unsigned char *iv, const unsigned char *input,
unsigned char *output );
int (*cfb_func)(void *ctx, mbedtls_operation_t mode, size_t length, size_t *iv_off,
unsigned char *iv, const unsigned char *input,
unsigned char *output);
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
/** Encrypt using OFB (Full length) */
int (*ofb_func)( void *ctx, size_t length, size_t *iv_off,
unsigned char *iv,
const unsigned char *input,
unsigned char *output );
int (*ofb_func)(void *ctx, size_t length, size_t *iv_off,
unsigned char *iv,
const unsigned char *input,
unsigned char *output);
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/** Encrypt using CTR */
int (*ctr_func)( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output );
int (*ctr_func)(void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output);
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/** Encrypt or decrypt using XTS. */
int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length,
const unsigned char data_unit[16],
const unsigned char *input, unsigned char *output );
int (*xts_func)(void *ctx, mbedtls_operation_t mode, size_t length,
const unsigned char data_unit[16],
const unsigned char *input, unsigned char *output);
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
/** Encrypt using STREAM */
int (*stream_func)( void *ctx, size_t length,
const unsigned char *input, unsigned char *output );
int (*stream_func)(void *ctx, size_t length,
const unsigned char *input, unsigned char *output);
#endif
/** Set key for encryption purposes */
int (*setkey_enc_func)( void *ctx, const unsigned char *key,
unsigned int key_bitlen );
int (*setkey_enc_func)(void *ctx, const unsigned char *key,
unsigned int key_bitlen);
/** Set key for decryption purposes */
int (*setkey_dec_func)( void *ctx, const unsigned char *key,
unsigned int key_bitlen);
int (*setkey_dec_func)(void *ctx, const unsigned char *key,
unsigned int key_bitlen);
/** Allocate a new context */
void * (*ctx_alloc_func)( void );
void * (*ctx_alloc_func)(void);
/** Free the given context */
void (*ctx_free_func)( void *ctx );
void (*ctx_free_func)(void *ctx);
};
typedef struct
{
typedef struct {
mbedtls_cipher_type_t type;
const mbedtls_cipher_info_t *info;
} mbedtls_cipher_definition_t;
#if defined(MBEDTLS_USE_PSA_CRYPTO)
typedef enum
{
typedef enum {
MBEDTLS_CIPHER_PSA_KEY_UNSET = 0,
MBEDTLS_CIPHER_PSA_KEY_OWNED, /* Used for PSA-based cipher contexts which */
/* use raw key material internally imported */
@ -127,8 +124,7 @@ typedef enum
/* destroyed when the context is freed. */
} mbedtls_cipher_psa_key_ownership;
typedef struct
{
typedef struct {
psa_algorithm_t alg;
mbedtls_svc_key_id_t slot;
mbedtls_cipher_psa_key_ownership slot_state;

File diff suppressed because it is too large Load Diff

View File

@ -52,16 +52,16 @@
#endif
#if defined(MBEDTLS_TEST_HOOKS)
extern void (*mbedtls_test_hook_test_fail)( const char * test, int line, const char * file );
#define MBEDTLS_TEST_HOOK_TEST_ASSERT( TEST ) \
do { \
if( ( ! ( TEST ) ) && ( ( *mbedtls_test_hook_test_fail ) != NULL ) ) \
{ \
( *mbedtls_test_hook_test_fail )( #TEST, __LINE__, __FILE__ ); \
} \
} while( 0 )
extern void (*mbedtls_test_hook_test_fail)(const char *test, int line, const char *file);
#define MBEDTLS_TEST_HOOK_TEST_ASSERT(TEST) \
do { \
if ((!(TEST)) && ((*mbedtls_test_hook_test_fail) != NULL)) \
{ \
(*mbedtls_test_hook_test_fail)( #TEST, __LINE__, __FILE__); \
} \
} while (0)
#else
#define MBEDTLS_TEST_HOOK_TEST_ASSERT( TEST )
#define MBEDTLS_TEST_HOOK_TEST_ASSERT(TEST)
#endif /* defined(MBEDTLS_TEST_HOOKS) */
/** Allow library to access its structs' private members.
@ -87,9 +87,9 @@ extern void (*mbedtls_test_hook_test_fail)( const char * test, int line, const c
* buffer is at least \p n + 1.
*/
static inline unsigned char *mbedtls_buffer_offset(
unsigned char *p, size_t n )
unsigned char *p, size_t n)
{
return( p == NULL ? NULL : p + n );
return p == NULL ? NULL : p + n;
}
/** Return an offset into a read-only buffer.
@ -104,9 +104,9 @@ static inline unsigned char *mbedtls_buffer_offset(
* buffer is at least \p n + 1.
*/
static inline const unsigned char *mbedtls_buffer_offset_const(
const unsigned char *p, size_t n )
const unsigned char *p, size_t n)
{
return( p == NULL ? NULL : p + n );
return p == NULL ? NULL : p + n;
}
/**
@ -120,16 +120,14 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* \param b Pointer to input (buffer of at least \p n bytes)
* \param n Number of bytes to process.
*/
inline void mbedtls_xor( unsigned char *r, const unsigned char *a, const unsigned char *b, size_t n )
inline void mbedtls_xor(unsigned char *r, const unsigned char *a, const unsigned char *b, size_t n)
{
size_t i;
for ( i = 0; ( i + 4 ) <= n; i += 4 )
{
uint32_t x = mbedtls_get_unaligned_uint32( a + i ) ^ mbedtls_get_unaligned_uint32( b + i );
mbedtls_put_unaligned_uint32( r + i, x );
for (i = 0; (i + 4) <= n; i += 4) {
uint32_t x = mbedtls_get_unaligned_uint32(a + i) ^ mbedtls_get_unaligned_uint32(b + i);
mbedtls_put_unaligned_uint32(r + i, x);
}
for ( ; i < n; i++ )
{
for (; i < n; i++) {
r[i] = a[i] ^ b[i];
}
}
@ -138,7 +136,7 @@ inline void mbedtls_xor( unsigned char *r, const unsigned char *a, const unsigne
* MSVC support __func__ from visual studio 2015( 1900 )
* Use MSVC predefine macro to avoid name check fail.
*/
#if (defined(_MSC_VER) && ( _MSC_VER <= 1900 ))
#if (defined(_MSC_VER) && (_MSC_VER <= 1900))
#define /*no-check-names*/ __func__ __FUNCTION__
#endif

File diff suppressed because it is too large Load Diff

View File

@ -44,7 +44,7 @@
*
* \return Zero if \p value is zero, otherwise all-bits-one.
*/
unsigned mbedtls_ct_uint_mask( unsigned value );
unsigned mbedtls_ct_uint_mask(unsigned value);
#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
@ -59,7 +59,7 @@ unsigned mbedtls_ct_uint_mask( unsigned value );
*
* \return Zero if \p value is zero, otherwise all-bits-one.
*/
size_t mbedtls_ct_size_mask( size_t value );
size_t mbedtls_ct_size_mask(size_t value);
#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
@ -76,7 +76,7 @@ size_t mbedtls_ct_size_mask( size_t value );
*
* \return Zero if \p value is zero, otherwise all-bits-one.
*/
mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask( mbedtls_mpi_uint value );
mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask(mbedtls_mpi_uint value);
#endif /* MBEDTLS_BIGNUM_C */
@ -95,8 +95,8 @@ mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask( mbedtls_mpi_uint value );
* \return All-bits-one if \p x is greater or equal than \p y,
* otherwise zero.
*/
size_t mbedtls_ct_size_mask_ge( size_t x,
size_t y );
size_t mbedtls_ct_size_mask_ge(size_t x,
size_t y);
#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
@ -111,8 +111,8 @@ size_t mbedtls_ct_size_mask_ge( size_t x,
*
* \return 1 if \p x equals to \p y, otherwise 0.
*/
unsigned mbedtls_ct_size_bool_eq( size_t x,
size_t y );
unsigned mbedtls_ct_size_bool_eq(size_t x,
size_t y);
#if defined(MBEDTLS_BIGNUM_C)
@ -126,8 +126,8 @@ unsigned mbedtls_ct_size_bool_eq( size_t x,
*
* \return 1 if \p x is less than \p y, otherwise 0.
*/
unsigned mbedtls_ct_mpi_uint_lt( const mbedtls_mpi_uint x,
const mbedtls_mpi_uint y );
unsigned mbedtls_ct_mpi_uint_lt(const mbedtls_mpi_uint x,
const mbedtls_mpi_uint y);
/**
* \brief Check if one unsigned MPI is less than another in constant
@ -144,9 +144,9 @@ unsigned mbedtls_ct_mpi_uint_lt( const mbedtls_mpi_uint x,
* \c 1 if \p A is less than \p B.
* \c 0 if \p A is greater than or equal to \p B.
*/
unsigned mbedtls_mpi_core_lt_ct( const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
size_t limbs);
unsigned mbedtls_mpi_core_lt_ct(const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
size_t limbs);
#endif /* MBEDTLS_BIGNUM_C */
/** Choose between two integer values without branches.
@ -160,9 +160,9 @@ unsigned mbedtls_mpi_core_lt_ct( const mbedtls_mpi_uint *A,
*
* \return \c if1 if \p condition is nonzero, otherwise \c if0.
*/
unsigned mbedtls_ct_uint_if( unsigned condition,
unsigned if1,
unsigned if0 );
unsigned mbedtls_ct_uint_if(unsigned condition,
unsigned if1,
unsigned if0);
#if defined(MBEDTLS_BIGNUM_C)
@ -178,10 +178,10 @@ unsigned mbedtls_ct_uint_if( unsigned condition,
* initialized MPI.
* \param condition Condition to test, must be 0 or 1.
*/
void mbedtls_ct_mpi_uint_cond_assign( size_t n,
mbedtls_mpi_uint *dest,
const mbedtls_mpi_uint *src,
unsigned char condition );
void mbedtls_ct_mpi_uint_cond_assign(size_t n,
mbedtls_mpi_uint *dest,
const mbedtls_mpi_uint *src,
unsigned char condition);
#endif /* MBEDTLS_BIGNUM_C */
@ -196,7 +196,7 @@ void mbedtls_ct_mpi_uint_cond_assign( size_t n,
*
* \return A base64 digit converted from \p value.
*/
unsigned char mbedtls_ct_base64_enc_char( unsigned char value );
unsigned char mbedtls_ct_base64_enc_char(unsigned char value);
/** Given a Base64 digit, return its value.
*
@ -210,7 +210,7 @@ unsigned char mbedtls_ct_base64_enc_char( unsigned char value );
*
* \return The value of the base64 digit \p c.
*/
signed char mbedtls_ct_base64_dec_value( unsigned char c );
signed char mbedtls_ct_base64_dec_value(unsigned char c);
#endif /* MBEDTLS_BASE64_C */
@ -227,10 +227,10 @@ signed char mbedtls_ct_base64_dec_value( unsigned char c );
* \param c1 The first value to analyze in the condition.
* \param c2 The second value to analyze in the condition.
*/
void mbedtls_ct_memcpy_if_eq( unsigned char *dest,
const unsigned char *src,
size_t len,
size_t c1, size_t c2 );
void mbedtls_ct_memcpy_if_eq(unsigned char *dest,
const unsigned char *src,
size_t len,
size_t c1, size_t c2);
/** Copy data from a secret position with constant flow.
*
@ -258,12 +258,12 @@ void mbedtls_ct_memcpy_if_eq( unsigned char *dest,
* \param offset_max The maximal value of \p offset.
* \param len The number of bytes to copy.
*/
void mbedtls_ct_memcpy_offset( unsigned char *dest,
const unsigned char *src,
size_t offset,
size_t offset_min,
size_t offset_max,
size_t len );
void mbedtls_ct_memcpy_offset(unsigned char *dest,
const unsigned char *src,
size_t offset,
size_t offset_min,
size_t offset_max,
size_t len);
/** Compute the HMAC of variable-length data with constant flow.
*
@ -302,24 +302,24 @@ void mbedtls_ct_memcpy_offset( unsigned char *dest,
* The hardware accelerator failed.
*/
#if defined(MBEDTLS_USE_PSA_CRYPTO)
int mbedtls_ct_hmac( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const unsigned char *add_data,
size_t add_data_len,
const unsigned char *data,
size_t data_len_secret,
size_t min_data_len,
size_t max_data_len,
unsigned char *output );
int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const unsigned char *add_data,
size_t add_data_len,
const unsigned char *data,
size_t data_len_secret,
size_t min_data_len,
size_t max_data_len,
unsigned char *output);
#else
int mbedtls_ct_hmac( mbedtls_md_context_t *ctx,
const unsigned char *add_data,
size_t add_data_len,
const unsigned char *data,
size_t data_len_secret,
size_t min_data_len,
size_t max_data_len,
unsigned char *output );
int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
const unsigned char *add_data,
size_t add_data_len,
const unsigned char *data,
size_t data_len_secret,
size_t min_data_len,
size_t max_data_len,
unsigned char *output);
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
@ -352,11 +352,11 @@ int mbedtls_ct_hmac( mbedtls_md_context_t *ctx,
* \return #MBEDTLS_ERR_RSA_INVALID_PADDING
* The input doesn't contain properly formatted padding.
*/
int mbedtls_ct_rsaes_pkcs1_v15_unpadding( unsigned char *input,
size_t ilen,
unsigned char *output,
size_t output_max_len,
size_t *olen );
int mbedtls_ct_rsaes_pkcs1_v15_unpadding(unsigned char *input,
size_t ilen,
unsigned char *output,
size_t output_max_len,
size_t *olen);
#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */

View File

@ -42,9 +42,9 @@
*
* \return All-bits-one if \p low <= \p c <= \p high, otherwise zero.
*/
unsigned char mbedtls_ct_uchar_mask_of_range( unsigned char low,
unsigned char high,
unsigned char c );
unsigned char mbedtls_ct_uchar_mask_of_range(unsigned char low,
unsigned char high,
unsigned char c);
#endif /* MBEDTLS_TEST_HOOKS */

File diff suppressed because it is too large Load Diff

View File

@ -34,7 +34,7 @@
static int debug_threshold = 0;
void mbedtls_debug_set_threshold( int threshold )
void mbedtls_debug_set_threshold(int threshold)
{
debug_threshold = threshold;
}
@ -42,9 +42,9 @@ void mbedtls_debug_set_threshold( int threshold )
/*
* All calls to f_dbg must be made via this function
*/
static inline void debug_send_line( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *str )
static inline void debug_send_line(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *str)
{
/*
* If in a threaded environment, we need a thread identifier.
@ -53,54 +53,51 @@ static inline void debug_send_line( const mbedtls_ssl_context *ssl, int level,
*/
#if defined(MBEDTLS_THREADING_C)
char idstr[20 + DEBUG_BUF_SIZE]; /* 0x + 16 nibbles + ': ' */
mbedtls_snprintf( idstr, sizeof( idstr ), "%p: %s", (void*)ssl, str );
ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, idstr );
mbedtls_snprintf(idstr, sizeof(idstr), "%p: %s", (void *) ssl, str);
ssl->conf->f_dbg(ssl->conf->p_dbg, level, file, line, idstr);
#else
ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
ssl->conf->f_dbg(ssl->conf->p_dbg, level, file, line, str);
#endif
}
MBEDTLS_PRINTF_ATTRIBUTE(5, 6)
void mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *format, ... )
void mbedtls_debug_print_msg(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *format, ...)
{
va_list argp;
char str[DEBUG_BUF_SIZE];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( NULL == ssl ||
if (NULL == ssl ||
NULL == ssl->conf ||
NULL == ssl->conf->f_dbg ||
level > debug_threshold )
{
level > debug_threshold) {
return;
}
va_start( argp, format );
ret = mbedtls_vsnprintf( str, DEBUG_BUF_SIZE, format, argp );
va_end( argp );
va_start(argp, format);
ret = mbedtls_vsnprintf(str, DEBUG_BUF_SIZE, format, argp);
va_end(argp);
if( ret >= 0 && ret < DEBUG_BUF_SIZE - 1 )
{
if (ret >= 0 && ret < DEBUG_BUF_SIZE - 1) {
str[ret] = '\n';
str[ret + 1] = '\0';
}
debug_send_line( ssl, level, file, line, str );
debug_send_line(ssl, level, file, line, str);
}
void mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, int ret )
void mbedtls_debug_print_ret(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, int ret)
{
char str[DEBUG_BUF_SIZE];
if( NULL == ssl ||
if (NULL == ssl ||
NULL == ssl->conf ||
NULL == ssl->conf->f_dbg ||
level > debug_threshold )
{
level > debug_threshold) {
return;
}
@ -109,246 +106,232 @@ void mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level,
* the logs would be quickly flooded with WANT_READ, so ignore that.
* Don't ignore WANT_WRITE however, since it is usually rare.
*/
if( ret == MBEDTLS_ERR_SSL_WANT_READ )
if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
return;
}
mbedtls_snprintf( str, sizeof( str ), "%s() returned %d (-0x%04x)\n",
text, ret, (unsigned int) -ret );
mbedtls_snprintf(str, sizeof(str), "%s() returned %d (-0x%04x)\n",
text, ret, (unsigned int) -ret);
debug_send_line( ssl, level, file, line, str );
debug_send_line(ssl, level, file, line, str);
}
void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,
const char *file, int line, const char *text,
const unsigned char *buf, size_t len )
void mbedtls_debug_print_buf(const mbedtls_ssl_context *ssl, int level,
const char *file, int line, const char *text,
const unsigned char *buf, size_t len)
{
char str[DEBUG_BUF_SIZE];
char txt[17];
size_t i, idx = 0;
if( NULL == ssl ||
if (NULL == ssl ||
NULL == ssl->conf ||
NULL == ssl->conf->f_dbg ||
level > debug_threshold )
{
level > debug_threshold) {
return;
}
mbedtls_snprintf( str + idx, sizeof( str ) - idx, "dumping '%s' (%u bytes)\n",
text, (unsigned int) len );
mbedtls_snprintf(str + idx, sizeof(str) - idx, "dumping '%s' (%u bytes)\n",
text, (unsigned int) len);
debug_send_line( ssl, level, file, line, str );
debug_send_line(ssl, level, file, line, str);
idx = 0;
memset( txt, 0, sizeof( txt ) );
for( i = 0; i < len; i++ )
{
if( i >= 4096 )
memset(txt, 0, sizeof(txt));
for (i = 0; i < len; i++) {
if (i >= 4096) {
break;
}
if( i % 16 == 0 )
{
if( i > 0 )
{
mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %s\n", txt );
debug_send_line( ssl, level, file, line, str );
if (i % 16 == 0) {
if (i > 0) {
mbedtls_snprintf(str + idx, sizeof(str) - idx, " %s\n", txt);
debug_send_line(ssl, level, file, line, str);
idx = 0;
memset( txt, 0, sizeof( txt ) );
memset(txt, 0, sizeof(txt));
}
idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, "%04x: ",
(unsigned int) i );
idx += mbedtls_snprintf(str + idx, sizeof(str) - idx, "%04x: ",
(unsigned int) i);
}
idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %02x",
(unsigned int) buf[i] );
txt[i % 16] = ( buf[i] > 31 && buf[i] < 127 ) ? buf[i] : '.' ;
idx += mbedtls_snprintf(str + idx, sizeof(str) - idx, " %02x",
(unsigned int) buf[i]);
txt[i % 16] = (buf[i] > 31 && buf[i] < 127) ? buf[i] : '.';
}
if( len > 0 )
{
for( /* i = i */; i % 16 != 0; i++ )
idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, " " );
if (len > 0) {
for (/* i = i */; i % 16 != 0; i++) {
idx += mbedtls_snprintf(str + idx, sizeof(str) - idx, " ");
}
mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %s\n", txt );
debug_send_line( ssl, level, file, line, str );
mbedtls_snprintf(str + idx, sizeof(str) - idx, " %s\n", txt);
debug_send_line(ssl, level, file, line, str);
}
}
#if defined(MBEDTLS_ECP_C)
void mbedtls_debug_print_ecp( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_ecp_point *X )
void mbedtls_debug_print_ecp(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_ecp_point *X)
{
char str[DEBUG_BUF_SIZE];
if( NULL == ssl ||
if (NULL == ssl ||
NULL == ssl->conf ||
NULL == ssl->conf->f_dbg ||
level > debug_threshold )
{
level > debug_threshold) {
return;
}
mbedtls_snprintf( str, sizeof( str ), "%s(X)", text );
mbedtls_debug_print_mpi( ssl, level, file, line, str, &X->X );
mbedtls_snprintf(str, sizeof(str), "%s(X)", text);
mbedtls_debug_print_mpi(ssl, level, file, line, str, &X->X);
mbedtls_snprintf( str, sizeof( str ), "%s(Y)", text );
mbedtls_debug_print_mpi( ssl, level, file, line, str, &X->Y );
mbedtls_snprintf(str, sizeof(str), "%s(Y)", text);
mbedtls_debug_print_mpi(ssl, level, file, line, str, &X->Y);
}
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_BIGNUM_C)
void mbedtls_debug_print_mpi( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_mpi *X )
void mbedtls_debug_print_mpi(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_mpi *X)
{
char str[DEBUG_BUF_SIZE];
size_t bitlen;
size_t idx = 0;
if( NULL == ssl ||
if (NULL == ssl ||
NULL == ssl->conf ||
NULL == ssl->conf->f_dbg ||
NULL == X ||
level > debug_threshold )
{
level > debug_threshold) {
return;
}
bitlen = mbedtls_mpi_bitlen( X );
bitlen = mbedtls_mpi_bitlen(X);
mbedtls_snprintf( str, sizeof( str ), "value of '%s' (%u bits) is:\n",
text, (unsigned) bitlen );
debug_send_line( ssl, level, file, line, str );
mbedtls_snprintf(str, sizeof(str), "value of '%s' (%u bits) is:\n",
text, (unsigned) bitlen);
debug_send_line(ssl, level, file, line, str);
if( bitlen == 0 )
{
if (bitlen == 0) {
str[0] = ' '; str[1] = '0'; str[2] = '0';
idx = 3;
}
else
{
} else {
int n;
for( n = (int) ( ( bitlen - 1 ) / 8 ); n >= 0; n-- )
{
size_t limb_offset = n / sizeof( mbedtls_mpi_uint );
size_t offset_in_limb = n % sizeof( mbedtls_mpi_uint );
for (n = (int) ((bitlen - 1) / 8); n >= 0; n--) {
size_t limb_offset = n / sizeof(mbedtls_mpi_uint);
size_t offset_in_limb = n % sizeof(mbedtls_mpi_uint);
unsigned char octet =
( X->p[limb_offset] >> ( offset_in_limb * 8 ) ) & 0xff;
mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %02x", octet );
(X->p[limb_offset] >> (offset_in_limb * 8)) & 0xff;
mbedtls_snprintf(str + idx, sizeof(str) - idx, " %02x", octet);
idx += 3;
/* Wrap lines after 16 octets that each take 3 columns */
if( idx >= 3 * 16 )
{
mbedtls_snprintf( str + idx, sizeof( str ) - idx, "\n" );
debug_send_line( ssl, level, file, line, str );
if (idx >= 3 * 16) {
mbedtls_snprintf(str + idx, sizeof(str) - idx, "\n");
debug_send_line(ssl, level, file, line, str);
idx = 0;
}
}
}
if( idx != 0 )
{
mbedtls_snprintf( str + idx, sizeof( str ) - idx, "\n" );
debug_send_line( ssl, level, file, line, str );
if (idx != 0) {
mbedtls_snprintf(str + idx, sizeof(str) - idx, "\n");
debug_send_line(ssl, level, file, line, str);
}
}
#endif /* MBEDTLS_BIGNUM_C */
#if defined(MBEDTLS_X509_CRT_PARSE_C) && !defined(MBEDTLS_X509_REMOVE_INFO)
static void debug_print_pk( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_pk_context *pk )
static void debug_print_pk(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_pk_context *pk)
{
size_t i;
mbedtls_pk_debug_item items[MBEDTLS_PK_DEBUG_MAX_ITEMS];
char name[16];
memset( items, 0, sizeof( items ) );
memset(items, 0, sizeof(items));
if( mbedtls_pk_debug( pk, items ) != 0 )
{
debug_send_line( ssl, level, file, line,
"invalid PK context\n" );
if (mbedtls_pk_debug(pk, items) != 0) {
debug_send_line(ssl, level, file, line,
"invalid PK context\n");
return;
}
for( i = 0; i < MBEDTLS_PK_DEBUG_MAX_ITEMS; i++ )
{
if( items[i].type == MBEDTLS_PK_DEBUG_NONE )
for (i = 0; i < MBEDTLS_PK_DEBUG_MAX_ITEMS; i++) {
if (items[i].type == MBEDTLS_PK_DEBUG_NONE) {
return;
}
mbedtls_snprintf( name, sizeof( name ), "%s%s", text, items[i].name );
name[sizeof( name ) - 1] = '\0';
mbedtls_snprintf(name, sizeof(name), "%s%s", text, items[i].name);
name[sizeof(name) - 1] = '\0';
if( items[i].type == MBEDTLS_PK_DEBUG_MPI )
mbedtls_debug_print_mpi( ssl, level, file, line, name, items[i].value );
else
if (items[i].type == MBEDTLS_PK_DEBUG_MPI) {
mbedtls_debug_print_mpi(ssl, level, file, line, name, items[i].value);
} else
#if defined(MBEDTLS_ECP_C)
if( items[i].type == MBEDTLS_PK_DEBUG_ECP )
mbedtls_debug_print_ecp( ssl, level, file, line, name, items[i].value );
else
if (items[i].type == MBEDTLS_PK_DEBUG_ECP) {
mbedtls_debug_print_ecp(ssl, level, file, line, name, items[i].value);
} else
#endif
debug_send_line( ssl, level, file, line,
"should not happen\n" );
{ debug_send_line(ssl, level, file, line,
"should not happen\n"); }
}
}
static void debug_print_line_by_line( const mbedtls_ssl_context *ssl, int level,
const char *file, int line, const char *text )
static void debug_print_line_by_line(const mbedtls_ssl_context *ssl, int level,
const char *file, int line, const char *text)
{
char str[DEBUG_BUF_SIZE];
const char *start, *cur;
start = text;
for( cur = text; *cur != '\0'; cur++ )
{
if( *cur == '\n' )
{
for (cur = text; *cur != '\0'; cur++) {
if (*cur == '\n') {
size_t len = cur - start + 1;
if( len > DEBUG_BUF_SIZE - 1 )
if (len > DEBUG_BUF_SIZE - 1) {
len = DEBUG_BUF_SIZE - 1;
}
memcpy( str, start, len );
memcpy(str, start, len);
str[len] = '\0';
debug_send_line( ssl, level, file, line, str );
debug_send_line(ssl, level, file, line, str);
start = cur + 1;
}
}
}
void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_x509_crt *crt )
void mbedtls_debug_print_crt(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_x509_crt *crt)
{
char str[DEBUG_BUF_SIZE];
int i = 0;
if( NULL == ssl ||
if (NULL == ssl ||
NULL == ssl->conf ||
NULL == ssl->conf->f_dbg ||
NULL == crt ||
level > debug_threshold )
{
level > debug_threshold) {
return;
}
while( crt != NULL )
{
while (crt != NULL) {
char buf[1024];
mbedtls_snprintf( str, sizeof( str ), "%s #%d:\n", text, ++i );
debug_send_line( ssl, level, file, line, str );
mbedtls_snprintf(str, sizeof(str), "%s #%d:\n", text, ++i);
debug_send_line(ssl, level, file, line, str);
mbedtls_x509_crt_info( buf, sizeof( buf ) - 1, "", crt );
debug_print_line_by_line( ssl, level, file, line, buf );
mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt);
debug_print_line_by_line(ssl, level, file, line, buf);
debug_print_pk( ssl, level, file, line, "crt->", &crt->pk );
debug_print_pk(ssl, level, file, line, "crt->", &crt->pk);
crt = crt->next;
}
@ -356,50 +339,48 @@ void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,
#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_X509_REMOVE_INFO */
#if defined(MBEDTLS_ECDH_C)
static void mbedtls_debug_printf_ecdh_internal( const mbedtls_ssl_context *ssl,
int level, const char *file,
int line,
const mbedtls_ecdh_context *ecdh,
mbedtls_debug_ecdh_attr attr )
static void mbedtls_debug_printf_ecdh_internal(const mbedtls_ssl_context *ssl,
int level, const char *file,
int line,
const mbedtls_ecdh_context *ecdh,
mbedtls_debug_ecdh_attr attr)
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
const mbedtls_ecdh_context* ctx = ecdh;
const mbedtls_ecdh_context *ctx = ecdh;
#else
const mbedtls_ecdh_context_mbed* ctx = &ecdh->ctx.mbed_ecdh;
const mbedtls_ecdh_context_mbed *ctx = &ecdh->ctx.mbed_ecdh;
#endif
switch( attr )
{
switch (attr) {
case MBEDTLS_DEBUG_ECDH_Q:
mbedtls_debug_print_ecp( ssl, level, file, line, "ECDH: Q",
&ctx->Q );
mbedtls_debug_print_ecp(ssl, level, file, line, "ECDH: Q",
&ctx->Q);
break;
case MBEDTLS_DEBUG_ECDH_QP:
mbedtls_debug_print_ecp( ssl, level, file, line, "ECDH: Qp",
&ctx->Qp );
mbedtls_debug_print_ecp(ssl, level, file, line, "ECDH: Qp",
&ctx->Qp);
break;
case MBEDTLS_DEBUG_ECDH_Z:
mbedtls_debug_print_mpi( ssl, level, file, line, "ECDH: z",
&ctx->z );
mbedtls_debug_print_mpi(ssl, level, file, line, "ECDH: z",
&ctx->z);
break;
default:
break;
}
}
void mbedtls_debug_printf_ecdh( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const mbedtls_ecdh_context *ecdh,
mbedtls_debug_ecdh_attr attr )
void mbedtls_debug_printf_ecdh(const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const mbedtls_ecdh_context *ecdh,
mbedtls_debug_ecdh_attr attr)
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
mbedtls_debug_printf_ecdh_internal( ssl, level, file, line, ecdh, attr );
mbedtls_debug_printf_ecdh_internal(ssl, level, file, line, ecdh, attr);
#else
switch( ecdh->var )
{
switch (ecdh->var) {
default:
mbedtls_debug_printf_ecdh_internal( ssl, level, file, line, ecdh,
attr );
mbedtls_debug_printf_ecdh_internal(ssl, level, file, line, ecdh,
attr);
}
#endif
}

File diff suppressed because it is too large Load Diff

View File

@ -50,27 +50,30 @@
/*
* helper to validate the mbedtls_mpi size and import it
*/
static int dhm_read_bignum( mbedtls_mpi *X,
unsigned char **p,
const unsigned char *end )
static int dhm_read_bignum(mbedtls_mpi *X,
unsigned char **p,
const unsigned char *end)
{
int ret, n;
if( end - *p < 2 )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (end - *p < 2) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
n = ( (*p)[0] << 8 ) | (*p)[1];
n = ((*p)[0] << 8) | (*p)[1];
(*p) += 2;
if( (int)( end - *p ) < n )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if ((int) (end - *p) < n) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
if( ( ret = mbedtls_mpi_read_binary( X, *p, n ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_READ_PARAMS_FAILED, ret ) );
if ((ret = mbedtls_mpi_read_binary(X, *p, n)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED, ret);
}
(*p) += n;
return( 0 );
return 0;
}
/*
@ -85,48 +88,46 @@ static int dhm_read_bignum( mbedtls_mpi *X,
* http://www.cl.cam.ac.uk/~rja14/Papers/psandqs.pdf
* http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-2643
*/
static int dhm_check_range( const mbedtls_mpi *param, const mbedtls_mpi *P )
static int dhm_check_range(const mbedtls_mpi *param, const mbedtls_mpi *P)
{
mbedtls_mpi U;
int ret = 0;
mbedtls_mpi_init( &U );
mbedtls_mpi_init(&U);
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &U, P, 2 ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&U, P, 2));
if( mbedtls_mpi_cmp_int( param, 2 ) < 0 ||
mbedtls_mpi_cmp_mpi( param, &U ) > 0 )
{
if (mbedtls_mpi_cmp_int(param, 2) < 0 ||
mbedtls_mpi_cmp_mpi(param, &U) > 0) {
ret = MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
cleanup:
mbedtls_mpi_free( &U );
return( ret );
mbedtls_mpi_free(&U);
return ret;
}
void mbedtls_dhm_init( mbedtls_dhm_context *ctx )
void mbedtls_dhm_init(mbedtls_dhm_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_dhm_context ) );
memset(ctx, 0, sizeof(mbedtls_dhm_context));
}
size_t mbedtls_dhm_get_bitlen( const mbedtls_dhm_context *ctx )
size_t mbedtls_dhm_get_bitlen(const mbedtls_dhm_context *ctx)
{
return( mbedtls_mpi_bitlen( &ctx->P ) );
return mbedtls_mpi_bitlen(&ctx->P);
}
size_t mbedtls_dhm_get_len( const mbedtls_dhm_context *ctx )
size_t mbedtls_dhm_get_len(const mbedtls_dhm_context *ctx)
{
return( mbedtls_mpi_size( &ctx->P ) );
return mbedtls_mpi_size(&ctx->P);
}
int mbedtls_dhm_get_value( const mbedtls_dhm_context *ctx,
mbedtls_dhm_parameter param,
mbedtls_mpi *dest )
int mbedtls_dhm_get_value(const mbedtls_dhm_context *ctx,
mbedtls_dhm_parameter param,
mbedtls_mpi *dest)
{
const mbedtls_mpi *src = NULL;
switch( param )
{
switch (param) {
case MBEDTLS_DHM_PARAM_P:
src = &ctx->P;
break;
@ -146,191 +147,202 @@ int mbedtls_dhm_get_value( const mbedtls_dhm_context *ctx,
src = &ctx->K;
break;
default:
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
return( mbedtls_mpi_copy( dest, src ) );
return mbedtls_mpi_copy(dest, src);
}
/*
* Parse the ServerKeyExchange parameters
*/
int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,
unsigned char **p,
const unsigned char *end )
int mbedtls_dhm_read_params(mbedtls_dhm_context *ctx,
unsigned char **p,
const unsigned char *end)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = dhm_read_bignum( &ctx->P, p, end ) ) != 0 ||
( ret = dhm_read_bignum( &ctx->G, p, end ) ) != 0 ||
( ret = dhm_read_bignum( &ctx->GY, p, end ) ) != 0 )
return( ret );
if ((ret = dhm_read_bignum(&ctx->P, p, end)) != 0 ||
(ret = dhm_read_bignum(&ctx->G, p, end)) != 0 ||
(ret = dhm_read_bignum(&ctx->GY, p, end)) != 0) {
return ret;
}
if( ( ret = dhm_check_range( &ctx->GY, &ctx->P ) ) != 0 )
return( ret );
if ((ret = dhm_check_range(&ctx->GY, &ctx->P)) != 0) {
return ret;
}
return( 0 );
return 0;
}
/*
* Pick a random R in the range [2, M-2] for blinding or key generation.
*/
static int dhm_random_below( mbedtls_mpi *R, const mbedtls_mpi *M,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
static int dhm_random_below(mbedtls_mpi *R, const mbedtls_mpi *M,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
{
int ret;
MBEDTLS_MPI_CHK( mbedtls_mpi_random( R, 3, M, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( R, R, 1 ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_random(R, 3, M, f_rng, p_rng));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(R, R, 1));
cleanup:
return( ret );
return ret;
}
static int dhm_make_common( mbedtls_dhm_context *ctx, int x_size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
static int dhm_make_common(mbedtls_dhm_context *ctx, int x_size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int ret = 0;
if( mbedtls_mpi_cmp_int( &ctx->P, 0 ) == 0 )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if( x_size < 0 )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if( (unsigned) x_size < mbedtls_mpi_size( &ctx->P ) )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) );
if (mbedtls_mpi_cmp_int(&ctx->P, 0) == 0) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
else
{
if (x_size < 0) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
if ((unsigned) x_size < mbedtls_mpi_size(&ctx->P)) {
MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->X, x_size, f_rng, p_rng));
} else {
/* Generate X as large as possible ( <= P - 2 ) */
ret = dhm_random_below( &ctx->X, &ctx->P, f_rng, p_rng );
if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED );
if( ret != 0 )
return( ret );
ret = dhm_random_below(&ctx->X, &ctx->P, f_rng, p_rng);
if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
return MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED;
}
if (ret != 0) {
return ret;
}
}
/*
* Calculate GX = G^X mod P
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->GX, &ctx->G, &ctx->X,
&ctx->P , &ctx->RP ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->GX, &ctx->G, &ctx->X,
&ctx->P, &ctx->RP));
if( ( ret = dhm_check_range( &ctx->GX, &ctx->P ) ) != 0 )
return( ret );
if ((ret = dhm_check_range(&ctx->GX, &ctx->P)) != 0) {
return ret;
}
cleanup:
return( ret );
return ret;
}
/*
* Setup and write the ServerKeyExchange parameters
*/
int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
unsigned char *output, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_dhm_make_params(mbedtls_dhm_context *ctx, int x_size,
unsigned char *output, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int ret;
size_t n1, n2, n3;
unsigned char *p;
ret = dhm_make_common( ctx, x_size, f_rng, p_rng );
if( ret != 0 )
ret = dhm_make_common(ctx, x_size, f_rng, p_rng);
if (ret != 0) {
goto cleanup;
}
/*
* Export P, G, GX. RFC 5246 §4.4 states that "leading zero octets are
* not required". We omit leading zeros for compactness.
*/
#define DHM_MPI_EXPORT( X, n ) \
#define DHM_MPI_EXPORT(X, n) \
do { \
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( ( X ), \
p + 2, \
( n ) ) ); \
*p++ = MBEDTLS_BYTE_1( n ); \
*p++ = MBEDTLS_BYTE_0( n ); \
p += ( n ); \
} while( 0 )
MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary((X), \
p + 2, \
(n))); \
*p++ = MBEDTLS_BYTE_1(n); \
*p++ = MBEDTLS_BYTE_0(n); \
p += (n); \
} while (0)
n1 = mbedtls_mpi_size( &ctx->P );
n2 = mbedtls_mpi_size( &ctx->G );
n3 = mbedtls_mpi_size( &ctx->GX );
n1 = mbedtls_mpi_size(&ctx->P);
n2 = mbedtls_mpi_size(&ctx->G);
n3 = mbedtls_mpi_size(&ctx->GX);
p = output;
DHM_MPI_EXPORT( &ctx->P , n1 );
DHM_MPI_EXPORT( &ctx->G , n2 );
DHM_MPI_EXPORT( &ctx->GX, n3 );
DHM_MPI_EXPORT(&ctx->P, n1);
DHM_MPI_EXPORT(&ctx->G, n2);
DHM_MPI_EXPORT(&ctx->GX, n3);
*olen = p - output;
cleanup:
if( ret != 0 && ret > -128 )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED, ret );
return( ret );
if (ret != 0 && ret > -128) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED, ret);
}
return ret;
}
/*
* Set prime modulus and generator
*/
int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,
const mbedtls_mpi *P,
const mbedtls_mpi *G )
int mbedtls_dhm_set_group(mbedtls_dhm_context *ctx,
const mbedtls_mpi *P,
const mbedtls_mpi *G)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ||
( ret = mbedtls_mpi_copy( &ctx->G, G ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_SET_GROUP_FAILED, ret ) );
if ((ret = mbedtls_mpi_copy(&ctx->P, P)) != 0 ||
(ret = mbedtls_mpi_copy(&ctx->G, G)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_SET_GROUP_FAILED, ret);
}
return( 0 );
return 0;
}
/*
* Import the peer's public value G^Y
*/
int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx,
const unsigned char *input, size_t ilen )
int mbedtls_dhm_read_public(mbedtls_dhm_context *ctx,
const unsigned char *input, size_t ilen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ilen < 1 || ilen > mbedtls_dhm_get_len( ctx ) )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (ilen < 1 || ilen > mbedtls_dhm_get_len(ctx)) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
if( ( ret = mbedtls_mpi_read_binary( &ctx->GY, input, ilen ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED, ret ) );
if ((ret = mbedtls_mpi_read_binary(&ctx->GY, input, ilen)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED, ret);
}
return( 0 );
return 0;
}
/*
* Create own private value X and export G^X
*/
int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
unsigned char *output, size_t olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_dhm_make_public(mbedtls_dhm_context *ctx, int x_size,
unsigned char *output, size_t olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int ret;
if( olen < 1 || olen > mbedtls_dhm_get_len( ctx ) )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (olen < 1 || olen > mbedtls_dhm_get_len(ctx)) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
ret = dhm_make_common( ctx, x_size, f_rng, p_rng );
if( ret == MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED )
return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED );
if( ret != 0 )
ret = dhm_make_common(ctx, x_size, f_rng, p_rng);
if (ret == MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) {
return MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED;
}
if (ret != 0) {
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->GX, output, olen ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->GX, output, olen));
cleanup:
if( ret != 0 && ret > -128 )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED, ret );
return( ret );
if (ret != 0 && ret > -128) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED, ret);
}
return ret;
}
@ -340,40 +352,38 @@ cleanup:
* DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
* Berlin Heidelberg, 1996. p. 104-113.
*/
static int dhm_update_blinding( mbedtls_dhm_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
static int dhm_update_blinding(mbedtls_dhm_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
{
int ret;
mbedtls_mpi R;
mbedtls_mpi_init( &R );
mbedtls_mpi_init(&R);
/*
* Don't use any blinding the first time a particular X is used,
* but remember it to use blinding next time.
*/
if( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->pX ) != 0 )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &ctx->pX, &ctx->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->Vi, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->Vf, 1 ) );
if (mbedtls_mpi_cmp_mpi(&ctx->X, &ctx->pX) != 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&ctx->pX, &ctx->X));
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->Vi, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->Vf, 1));
return( 0 );
return 0;
}
/*
* 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 )
{
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 ) );
if (mbedtls_mpi_cmp_int(&ctx->Vi, 1) != 0) {
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));
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->P ) );
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->P));
return( 0 );
return 0;
}
/*
@ -381,103 +391,108 @@ static int dhm_update_blinding( mbedtls_dhm_context *ctx,
*/
/* Vi = random( 2, P-2 ) */
MBEDTLS_MPI_CHK( dhm_random_below( &ctx->Vi, &ctx->P, f_rng, p_rng ) );
MBEDTLS_MPI_CHK(dhm_random_below(&ctx->Vi, &ctx->P, f_rng, p_rng));
/* Vf = Vi^-X mod P
* First compute Vi^-1 = R * (R Vi)^-1, (avoiding leaks from inv_mod),
* then elevate to the Xth power. */
MBEDTLS_MPI_CHK( dhm_random_below( &R, &ctx->P, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vi, &R ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vf, &ctx->Vf, &ctx->P ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &R ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) );
MBEDTLS_MPI_CHK(dhm_random_below(&R, &ctx->P, f_rng, p_rng));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vi, &R));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->P));
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->Vf, &ctx->Vf, &ctx->P));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &R));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->P));
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vf, &ctx->Vf, &ctx->X, &ctx->P, &ctx->RP ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vf, &ctx->Vf, &ctx->X, &ctx->P, &ctx->RP));
cleanup:
mbedtls_mpi_free( &R );
mbedtls_mpi_free(&R);
return( ret );
return ret;
}
/*
* Derive and export the shared secret (G^Y)^X mod P
*/
int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
unsigned char *output, size_t output_size, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_dhm_calc_secret(mbedtls_dhm_context *ctx,
unsigned char *output, size_t output_size, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi GYb;
if( f_rng == NULL )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (f_rng == NULL) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
if( output_size < mbedtls_dhm_get_len( ctx ) )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (output_size < mbedtls_dhm_get_len(ctx)) {
return MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
if( ( ret = dhm_check_range( &ctx->GY, &ctx->P ) ) != 0 )
return( ret );
if ((ret = dhm_check_range(&ctx->GY, &ctx->P)) != 0) {
return ret;
}
mbedtls_mpi_init( &GYb );
mbedtls_mpi_init(&GYb);
/* Blind peer's value */
MBEDTLS_MPI_CHK( dhm_update_blinding( ctx, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &GYb, &ctx->GY, &ctx->Vi ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &GYb, &GYb, &ctx->P ) );
MBEDTLS_MPI_CHK(dhm_update_blinding(ctx, f_rng, p_rng));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&GYb, &ctx->GY, &ctx->Vi));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&GYb, &GYb, &ctx->P));
/* Do modular exponentiation */
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->K, &GYb, &ctx->X,
&ctx->P, &ctx->RP ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->K, &GYb, &ctx->X,
&ctx->P, &ctx->RP));
/* Unblind secret value */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->K, &ctx->K, &ctx->Vf ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->K, &ctx->K, &ctx->P ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->K, &ctx->K, &ctx->Vf));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->K, &ctx->K, &ctx->P));
/* Output the secret without any leading zero byte. This is mandatory
* for TLS per RFC 5246 §8.1.2. */
*olen = mbedtls_mpi_size( &ctx->K );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->K, output, *olen ) );
*olen = mbedtls_mpi_size(&ctx->K);
MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->K, output, *olen));
cleanup:
mbedtls_mpi_free( &GYb );
mbedtls_mpi_free(&GYb);
if( ret != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_CALC_SECRET_FAILED, ret ) );
if (ret != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED, ret);
}
return( 0 );
return 0;
}
/*
* Free the components of a DHM key
*/
void mbedtls_dhm_free( mbedtls_dhm_context *ctx )
void mbedtls_dhm_free(mbedtls_dhm_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_mpi_free( &ctx->pX );
mbedtls_mpi_free( &ctx->Vf );
mbedtls_mpi_free( &ctx->Vi );
mbedtls_mpi_free( &ctx->RP );
mbedtls_mpi_free( &ctx->K );
mbedtls_mpi_free( &ctx->GY );
mbedtls_mpi_free( &ctx->GX );
mbedtls_mpi_free( &ctx->X );
mbedtls_mpi_free( &ctx->G );
mbedtls_mpi_free( &ctx->P );
mbedtls_mpi_free(&ctx->pX);
mbedtls_mpi_free(&ctx->Vf);
mbedtls_mpi_free(&ctx->Vi);
mbedtls_mpi_free(&ctx->RP);
mbedtls_mpi_free(&ctx->K);
mbedtls_mpi_free(&ctx->GY);
mbedtls_mpi_free(&ctx->GX);
mbedtls_mpi_free(&ctx->X);
mbedtls_mpi_free(&ctx->G);
mbedtls_mpi_free(&ctx->P);
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_dhm_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_dhm_context));
}
#if defined(MBEDTLS_ASN1_PARSE_C)
/*
* Parse DHM parameters
*/
int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
size_t dhminlen )
int mbedtls_dhm_parse_dhm(mbedtls_dhm_context *dhm, const unsigned char *dhmin,
size_t dhminlen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
@ -487,28 +502,28 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
#endif /* MBEDTLS_PEM_PARSE_C */
#if defined(MBEDTLS_PEM_PARSE_C)
mbedtls_pem_init( &pem );
mbedtls_pem_init(&pem);
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( dhminlen == 0 || dhmin[dhminlen - 1] != '\0' )
if (dhminlen == 0 || dhmin[dhminlen - 1] != '\0') {
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN DH PARAMETERS-----",
"-----END DH PARAMETERS-----",
dhmin, NULL, 0, &dhminlen );
} else {
ret = mbedtls_pem_read_buffer(&pem,
"-----BEGIN DH PARAMETERS-----",
"-----END DH PARAMETERS-----",
dhmin, NULL, 0, &dhminlen);
}
if( ret == 0 )
{
if (ret == 0) {
/*
* Was PEM encoded
*/
dhminlen = pem.buflen;
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
} else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
goto exit;
}
p = ( ret == 0 ) ? pem.buf : (unsigned char *) dhmin;
p = (ret == 0) ? pem.buf : (unsigned char *) dhmin;
#else
p = (unsigned char *) dhmin;
#endif /* MBEDTLS_PEM_PARSE_C */
@ -521,39 +536,34 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
* privateValueLength INTEGER OPTIONAL
* }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_INVALID_FORMAT, ret );
if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_INVALID_FORMAT, ret);
goto exit;
}
end = p + len;
if( ( ret = mbedtls_asn1_get_mpi( &p, end, &dhm->P ) ) != 0 ||
( ret = mbedtls_asn1_get_mpi( &p, end, &dhm->G ) ) != 0 )
{
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_INVALID_FORMAT, ret );
if ((ret = mbedtls_asn1_get_mpi(&p, end, &dhm->P)) != 0 ||
(ret = mbedtls_asn1_get_mpi(&p, end, &dhm->G)) != 0) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_INVALID_FORMAT, ret);
goto exit;
}
if( p != end )
{
if (p != end) {
/* This might be the optional privateValueLength.
* If so, we can cleanly discard it */
mbedtls_mpi rec;
mbedtls_mpi_init( &rec );
ret = mbedtls_asn1_get_mpi( &p, end, &rec );
mbedtls_mpi_free( &rec );
if ( ret != 0 )
{
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_INVALID_FORMAT, ret );
mbedtls_mpi_init(&rec);
ret = mbedtls_asn1_get_mpi(&p, end, &rec);
mbedtls_mpi_free(&rec);
if (ret != 0) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_INVALID_FORMAT, ret);
goto exit;
}
if ( p != end )
{
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
if (p != end) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_DHM_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
goto exit;
}
}
@ -562,12 +572,13 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
exit:
#if defined(MBEDTLS_PEM_PARSE_C)
mbedtls_pem_free( &pem );
mbedtls_pem_free(&pem);
#endif
if( ret != 0 )
mbedtls_dhm_free( dhm );
if (ret != 0) {
mbedtls_dhm_free(dhm);
}
return( ret );
return ret;
}
#if defined(MBEDTLS_FS_IO)
@ -578,70 +589,70 @@ exit:
* A terminating null byte is always appended. It is included in the announced
* length only if the data looks like it is PEM encoded.
*/
static int load_file( const char *path, unsigned char **buf, size_t *n )
static int load_file(const char *path, unsigned char **buf, size_t *n)
{
FILE *f;
long size;
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );
if ((f = fopen(path, "rb")) == NULL) {
return MBEDTLS_ERR_DHM_FILE_IO_ERROR;
}
/* The data loaded here is public, so don't bother disabling buffering. */
fseek( f, 0, SEEK_END );
if( ( size = ftell( f ) ) == -1 )
{
fclose( f );
return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );
fseek(f, 0, SEEK_END);
if ((size = ftell(f)) == -1) {
fclose(f);
return MBEDTLS_ERR_DHM_FILE_IO_ERROR;
}
fseek( f, 0, SEEK_SET );
fseek(f, 0, SEEK_SET);
*n = (size_t) size;
if( *n + 1 == 0 ||
( *buf = mbedtls_calloc( 1, *n + 1 ) ) == NULL )
{
fclose( f );
return( MBEDTLS_ERR_DHM_ALLOC_FAILED );
if (*n + 1 == 0 ||
(*buf = mbedtls_calloc(1, *n + 1)) == NULL) {
fclose(f);
return MBEDTLS_ERR_DHM_ALLOC_FAILED;
}
if( fread( *buf, 1, *n, f ) != *n )
{
fclose( f );
if (fread(*buf, 1, *n, f) != *n) {
fclose(f);
mbedtls_platform_zeroize( *buf, *n + 1 );
mbedtls_free( *buf );
mbedtls_platform_zeroize(*buf, *n + 1);
mbedtls_free(*buf);
return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );
return MBEDTLS_ERR_DHM_FILE_IO_ERROR;
}
fclose( f );
fclose(f);
(*buf)[*n] = '\0';
if( strstr( (const char *) *buf, "-----BEGIN " ) != NULL )
if (strstr((const char *) *buf, "-----BEGIN ") != NULL) {
++*n;
}
return( 0 );
return 0;
}
/*
* Load and parse DHM parameters
*/
int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path )
int mbedtls_dhm_parse_dhmfile(mbedtls_dhm_context *dhm, const char *path)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t n;
unsigned char *buf;
if( ( ret = load_file( path, &buf, &n ) ) != 0 )
return( ret );
if ((ret = load_file(path, &buf, &n)) != 0) {
return ret;
}
ret = mbedtls_dhm_parse_dhm( dhm, buf, n );
ret = mbedtls_dhm_parse_dhm(dhm, buf, n);
mbedtls_platform_zeroize( buf, n );
mbedtls_free( buf );
mbedtls_platform_zeroize(buf, n);
mbedtls_free(buf);
return( ret );
return ret;
}
#endif /* MBEDTLS_FS_IO */
#endif /* MBEDTLS_ASN1_PARSE_C */
@ -651,60 +662,63 @@ int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path )
#if defined(MBEDTLS_PEM_PARSE_C)
static const char mbedtls_test_dhm_params[] =
"-----BEGIN DH PARAMETERS-----\r\n"
"MIGHAoGBAJ419DBEOgmQTzo5qXl5fQcN9TN455wkOL7052HzxxRVMyhYmwQcgJvh\r\n"
"1sa18fyfR9OiVEMYglOpkqVoGLN7qd5aQNNi5W7/C+VBdHTBJcGZJyyP5B3qcz32\r\n"
"9mLJKudlVudV0Qxk5qUJaPZ/xupz0NyoVpviuiBOI1gNi8ovSXWzAgEC\r\n"
"-----END DH PARAMETERS-----\r\n";
"-----BEGIN DH PARAMETERS-----\r\n"
"MIGHAoGBAJ419DBEOgmQTzo5qXl5fQcN9TN455wkOL7052HzxxRVMyhYmwQcgJvh\r\n"
"1sa18fyfR9OiVEMYglOpkqVoGLN7qd5aQNNi5W7/C+VBdHTBJcGZJyyP5B3qcz32\r\n"
"9mLJKudlVudV0Qxk5qUJaPZ/xupz0NyoVpviuiBOI1gNi8ovSXWzAgEC\r\n"
"-----END DH PARAMETERS-----\r\n";
#else /* MBEDTLS_PEM_PARSE_C */
static const char mbedtls_test_dhm_params[] = {
0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0x9e, 0x35, 0xf4, 0x30, 0x44,
0x3a, 0x09, 0x90, 0x4f, 0x3a, 0x39, 0xa9, 0x79, 0x79, 0x7d, 0x07, 0x0d,
0xf5, 0x33, 0x78, 0xe7, 0x9c, 0x24, 0x38, 0xbe, 0xf4, 0xe7, 0x61, 0xf3,
0xc7, 0x14, 0x55, 0x33, 0x28, 0x58, 0x9b, 0x04, 0x1c, 0x80, 0x9b, 0xe1,
0xd6, 0xc6, 0xb5, 0xf1, 0xfc, 0x9f, 0x47, 0xd3, 0xa2, 0x54, 0x43, 0x18,
0x82, 0x53, 0xa9, 0x92, 0xa5, 0x68, 0x18, 0xb3, 0x7b, 0xa9, 0xde, 0x5a,
0x40, 0xd3, 0x62, 0xe5, 0x6e, 0xff, 0x0b, 0xe5, 0x41, 0x74, 0x74, 0xc1,
0x25, 0xc1, 0x99, 0x27, 0x2c, 0x8f, 0xe4, 0x1d, 0xea, 0x73, 0x3d, 0xf6,
0xf6, 0x62, 0xc9, 0x2a, 0xe7, 0x65, 0x56, 0xe7, 0x55, 0xd1, 0x0c, 0x64,
0xe6, 0xa5, 0x09, 0x68, 0xf6, 0x7f, 0xc6, 0xea, 0x73, 0xd0, 0xdc, 0xa8,
0x56, 0x9b, 0xe2, 0xba, 0x20, 0x4e, 0x23, 0x58, 0x0d, 0x8b, 0xca, 0x2f,
0x49, 0x75, 0xb3, 0x02, 0x01, 0x02 };
0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0x9e, 0x35, 0xf4, 0x30, 0x44,
0x3a, 0x09, 0x90, 0x4f, 0x3a, 0x39, 0xa9, 0x79, 0x79, 0x7d, 0x07, 0x0d,
0xf5, 0x33, 0x78, 0xe7, 0x9c, 0x24, 0x38, 0xbe, 0xf4, 0xe7, 0x61, 0xf3,
0xc7, 0x14, 0x55, 0x33, 0x28, 0x58, 0x9b, 0x04, 0x1c, 0x80, 0x9b, 0xe1,
0xd6, 0xc6, 0xb5, 0xf1, 0xfc, 0x9f, 0x47, 0xd3, 0xa2, 0x54, 0x43, 0x18,
0x82, 0x53, 0xa9, 0x92, 0xa5, 0x68, 0x18, 0xb3, 0x7b, 0xa9, 0xde, 0x5a,
0x40, 0xd3, 0x62, 0xe5, 0x6e, 0xff, 0x0b, 0xe5, 0x41, 0x74, 0x74, 0xc1,
0x25, 0xc1, 0x99, 0x27, 0x2c, 0x8f, 0xe4, 0x1d, 0xea, 0x73, 0x3d, 0xf6,
0xf6, 0x62, 0xc9, 0x2a, 0xe7, 0x65, 0x56, 0xe7, 0x55, 0xd1, 0x0c, 0x64,
0xe6, 0xa5, 0x09, 0x68, 0xf6, 0x7f, 0xc6, 0xea, 0x73, 0xd0, 0xdc, 0xa8,
0x56, 0x9b, 0xe2, 0xba, 0x20, 0x4e, 0x23, 0x58, 0x0d, 0x8b, 0xca, 0x2f,
0x49, 0x75, 0xb3, 0x02, 0x01, 0x02
};
#endif /* MBEDTLS_PEM_PARSE_C */
static const size_t mbedtls_test_dhm_params_len = sizeof( mbedtls_test_dhm_params );
static const size_t mbedtls_test_dhm_params_len = sizeof(mbedtls_test_dhm_params);
/*
* Checkup routine
*/
int mbedtls_dhm_self_test( int verbose )
int mbedtls_dhm_self_test(int verbose)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_dhm_context dhm;
mbedtls_dhm_init( &dhm );
mbedtls_dhm_init(&dhm);
if( verbose != 0 )
mbedtls_printf( " DHM parameter load: " );
if (verbose != 0) {
mbedtls_printf(" DHM parameter load: ");
}
if( ( ret = mbedtls_dhm_parse_dhm( &dhm,
(const unsigned char *) mbedtls_test_dhm_params,
mbedtls_test_dhm_params_len ) ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
if ((ret = mbedtls_dhm_parse_dhm(&dhm,
(const unsigned char *) mbedtls_test_dhm_params,
mbedtls_test_dhm_params_len)) != 0) {
if (verbose != 0) {
mbedtls_printf("failed\n");
}
ret = 1;
goto exit;
}
if( verbose != 0 )
mbedtls_printf( "passed\n\n" );
if (verbose != 0) {
mbedtls_printf("passed\n\n");
}
exit:
mbedtls_dhm_free( &dhm );
mbedtls_dhm_free(&dhm);
return( ret );
return ret;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@ -39,20 +39,20 @@ typedef mbedtls_ecdh_context mbedtls_ecdh_context_mbed;
#endif
static mbedtls_ecp_group_id mbedtls_ecdh_grp_id(
const mbedtls_ecdh_context *ctx )
const mbedtls_ecdh_context *ctx)
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ctx->grp.id );
return ctx->grp.id;
#else
return( ctx->grp_id );
return ctx->grp_id;
#endif
}
int mbedtls_ecdh_can_do( mbedtls_ecp_group_id gid )
int mbedtls_ecdh_can_do(mbedtls_ecp_group_id gid)
{
/* At this time, all groups support ECDH. */
(void) gid;
return( 1 );
return 1;
}
#if !defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)
@ -63,37 +63,38 @@ int mbedtls_ecdh_can_do( mbedtls_ecp_group_id gid )
* the output parameter 'd' across continuation calls. This would not be
* 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 )
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)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int restarting = 0;
#if defined(MBEDTLS_ECP_RESTARTABLE)
restarting = ( rs_ctx != NULL && rs_ctx->rsm != NULL );
restarting = (rs_ctx != NULL && rs_ctx->rsm != NULL);
#endif
/* If multiplication is in progress, we already generated a privkey */
if( !restarting )
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
if (!restarting) {
MBEDTLS_MPI_CHK(mbedtls_ecp_gen_privkey(grp, d, f_rng, p_rng));
}
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, Q, d, &grp->G,
f_rng, p_rng, rs_ctx ) );
MBEDTLS_MPI_CHK(mbedtls_ecp_mul_restartable(grp, Q, d, &grp->G,
f_rng, p_rng, rs_ctx));
cleanup:
return( ret );
return ret;
}
/*
* 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 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)
{
return( ecdh_gen_public_restartable( grp, d, Q, f_rng, p_rng, NULL ) );
return ecdh_gen_public_restartable(grp, d, Q, f_rng, p_rng, NULL);
}
#endif /* !MBEDTLS_ECDH_GEN_PUBLIC_ALT */
@ -101,73 +102,72 @@ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp
/*
* Compute shared secret (SEC1 3.3.1)
*/
static int ecdh_compute_shared_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *z,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
static int ecdh_compute_shared_restartable(mbedtls_ecp_group *grp,
mbedtls_mpi *z,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_point P;
mbedtls_ecp_point_init( &P );
mbedtls_ecp_point_init(&P);
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &P, d, Q,
f_rng, p_rng, rs_ctx ) );
MBEDTLS_MPI_CHK(mbedtls_ecp_mul_restartable(grp, &P, d, Q,
f_rng, p_rng, rs_ctx));
if( mbedtls_ecp_is_zero( &P ) )
{
if (mbedtls_ecp_is_zero(&P)) {
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( z, &P.X ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(z, &P.X));
cleanup:
mbedtls_ecp_point_free( &P );
mbedtls_ecp_point_free(&P);
return( ret );
return ret;
}
/*
* Compute shared secret (SEC1 3.3.1)
*/
int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_ecdh_compute_shared(mbedtls_ecp_group *grp, mbedtls_mpi *z,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
return( ecdh_compute_shared_restartable( grp, z, Q, d,
f_rng, p_rng, NULL ) );
return ecdh_compute_shared_restartable(grp, z, Q, d,
f_rng, p_rng, NULL);
}
#endif /* !MBEDTLS_ECDH_COMPUTE_SHARED_ALT */
static void ecdh_init_internal( mbedtls_ecdh_context_mbed *ctx )
static void ecdh_init_internal(mbedtls_ecdh_context_mbed *ctx)
{
mbedtls_ecp_group_init( &ctx->grp );
mbedtls_mpi_init( &ctx->d );
mbedtls_ecp_point_init( &ctx->Q );
mbedtls_ecp_point_init( &ctx->Qp );
mbedtls_mpi_init( &ctx->z );
mbedtls_ecp_group_init(&ctx->grp);
mbedtls_mpi_init(&ctx->d);
mbedtls_ecp_point_init(&ctx->Q);
mbedtls_ecp_point_init(&ctx->Qp);
mbedtls_mpi_init(&ctx->z);
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_init( &ctx->rs );
mbedtls_ecp_restart_init(&ctx->rs);
#endif
}
/*
* Initialize context
*/
void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx )
void mbedtls_ecdh_init(mbedtls_ecdh_context *ctx)
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
ecdh_init_internal( ctx );
mbedtls_ecp_point_init( &ctx->Vi );
mbedtls_ecp_point_init( &ctx->Vf );
mbedtls_mpi_init( &ctx->_d );
ecdh_init_internal(ctx);
mbedtls_ecp_point_init(&ctx->Vi);
mbedtls_ecp_point_init(&ctx->Vf);
mbedtls_mpi_init(&ctx->_d);
#else
memset( ctx, 0, sizeof( mbedtls_ecdh_context ) );
memset(ctx, 0, sizeof(mbedtls_ecdh_context));
ctx->var = MBEDTLS_ECDH_VARIANT_NONE;
#endif
@ -177,57 +177,55 @@ void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx )
#endif
}
static int ecdh_setup_internal( mbedtls_ecdh_context_mbed *ctx,
mbedtls_ecp_group_id grp_id )
static int ecdh_setup_internal(mbedtls_ecdh_context_mbed *ctx,
mbedtls_ecp_group_id grp_id)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_ecp_group_load( &ctx->grp, grp_id );
if( ret != 0 )
{
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
ret = mbedtls_ecp_group_load(&ctx->grp, grp_id);
if (ret != 0) {
return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
}
return( 0 );
return 0;
}
/*
* Setup context
*/
int mbedtls_ecdh_setup( mbedtls_ecdh_context *ctx, mbedtls_ecp_group_id grp_id )
int mbedtls_ecdh_setup(mbedtls_ecdh_context *ctx, mbedtls_ecp_group_id grp_id)
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_setup_internal( ctx, grp_id ) );
return ecdh_setup_internal(ctx, grp_id);
#else
switch( grp_id )
{
switch (grp_id) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECP_DP_CURVE25519:
ctx->point_format = MBEDTLS_ECP_PF_COMPRESSED;
ctx->var = MBEDTLS_ECDH_VARIANT_EVEREST;
ctx->grp_id = grp_id;
return( mbedtls_everest_setup( &ctx->ctx.everest_ecdh, grp_id ) );
return mbedtls_everest_setup(&ctx->ctx.everest_ecdh, grp_id);
#endif
default:
ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED;
ctx->var = MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0;
ctx->grp_id = grp_id;
ecdh_init_internal( &ctx->ctx.mbed_ecdh );
return( ecdh_setup_internal( &ctx->ctx.mbed_ecdh, grp_id ) );
ecdh_init_internal(&ctx->ctx.mbed_ecdh);
return ecdh_setup_internal(&ctx->ctx.mbed_ecdh, grp_id);
}
#endif
}
static void ecdh_free_internal( mbedtls_ecdh_context_mbed *ctx )
static void ecdh_free_internal(mbedtls_ecdh_context_mbed *ctx)
{
mbedtls_ecp_group_free( &ctx->grp );
mbedtls_mpi_free( &ctx->d );
mbedtls_ecp_point_free( &ctx->Q );
mbedtls_ecp_point_free( &ctx->Qp );
mbedtls_mpi_free( &ctx->z );
mbedtls_ecp_group_free(&ctx->grp);
mbedtls_mpi_free(&ctx->d);
mbedtls_ecp_point_free(&ctx->Q);
mbedtls_ecp_point_free(&ctx->Qp);
mbedtls_mpi_free(&ctx->z);
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_free( &ctx->rs );
mbedtls_ecp_restart_free(&ctx->rs);
#endif
}
@ -235,7 +233,7 @@ static void ecdh_free_internal( mbedtls_ecdh_context_mbed *ctx )
/*
* Enable restartable operations for context
*/
void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx )
void mbedtls_ecdh_enable_restart(mbedtls_ecdh_context *ctx)
{
ctx->restart_enabled = 1;
}
@ -244,26 +242,26 @@ void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx )
/*
* Free context
*/
void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx )
void mbedtls_ecdh_free(mbedtls_ecdh_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
mbedtls_ecp_point_free( &ctx->Vi );
mbedtls_ecp_point_free( &ctx->Vf );
mbedtls_mpi_free( &ctx->_d );
ecdh_free_internal( ctx );
mbedtls_ecp_point_free(&ctx->Vi);
mbedtls_ecp_point_free(&ctx->Vf);
mbedtls_mpi_free(&ctx->_d);
ecdh_free_internal(ctx);
#else
switch( ctx->var )
{
switch (ctx->var) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
mbedtls_everest_free( &ctx->ctx.everest_ecdh );
mbedtls_everest_free(&ctx->ctx.everest_ecdh);
break;
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
ecdh_free_internal( &ctx->ctx.mbed_ecdh );
ecdh_free_internal(&ctx->ctx.mbed_ecdh);
break;
default:
break;
@ -275,14 +273,14 @@ void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx )
#endif
}
static int ecdh_make_params_internal( mbedtls_ecdh_context_mbed *ctx,
size_t *olen, int point_format,
unsigned char *buf, size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled )
static int ecdh_make_params_internal(mbedtls_ecdh_context_mbed *ctx,
size_t *olen, int point_format,
unsigned char *buf, size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t grp_len, pt_len;
@ -290,40 +288,46 @@ static int ecdh_make_params_internal( mbedtls_ecdh_context_mbed *ctx,
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif
if( ctx->grp.pbits == 0 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if (ctx->grp.pbits == 0) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( restart_enabled )
if (restart_enabled) {
rs_ctx = &ctx->rs;
}
#else
(void) restart_enabled;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( ( ret = ecdh_gen_public_restartable( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng, rs_ctx ) ) != 0 )
return( ret );
if ((ret = ecdh_gen_public_restartable(&ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng, rs_ctx)) != 0) {
return ret;
}
#else
if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng ) ) != 0 )
return( ret );
if ((ret = mbedtls_ecdh_gen_public(&ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng)) != 0) {
return ret;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
if( ( ret = mbedtls_ecp_tls_write_group( &ctx->grp, &grp_len, buf,
blen ) ) != 0 )
return( ret );
if ((ret = mbedtls_ecp_tls_write_group(&ctx->grp, &grp_len, buf,
blen)) != 0) {
return ret;
}
buf += grp_len;
blen -= grp_len;
if( ( ret = mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, point_format,
&pt_len, buf, blen ) ) != 0 )
return( ret );
if ((ret = mbedtls_ecp_tls_write_point(&ctx->grp, &ctx->Q, point_format,
&pt_len, buf, blen)) != 0) {
return ret;
}
*olen = grp_len + pt_len;
return( 0 );
return 0;
}
/*
@ -333,10 +337,10 @@ static int ecdh_make_params_internal( mbedtls_ecdh_context_mbed *ctx,
* ECPoint public;
* } ServerECDHParams;
*/
int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_ecdh_make_params(mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int restart_enabled = 0;
#if defined(MBEDTLS_ECP_RESTARTABLE)
@ -346,33 +350,32 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
#endif
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_make_params_internal( ctx, olen, ctx->point_format, buf, blen,
f_rng, p_rng, restart_enabled ) );
return ecdh_make_params_internal(ctx, olen, ctx->point_format, buf, blen,
f_rng, p_rng, restart_enabled);
#else
switch( ctx->var )
{
switch (ctx->var) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_make_params( &ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng ) );
return mbedtls_everest_make_params(&ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng);
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_make_params_internal( &ctx->ctx.mbed_ecdh, olen,
ctx->point_format, buf, blen,
f_rng, p_rng,
restart_enabled ) );
return ecdh_make_params_internal(&ctx->ctx.mbed_ecdh, olen,
ctx->point_format, buf, blen,
f_rng, p_rng,
restart_enabled);
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_read_params_internal( mbedtls_ecdh_context_mbed *ctx,
const unsigned char **buf,
const unsigned char *end )
static int ecdh_read_params_internal(mbedtls_ecdh_context_mbed *ctx,
const unsigned char **buf,
const unsigned char *end)
{
return( mbedtls_ecp_tls_read_point( &ctx->grp, &ctx->Qp, buf,
end - *buf ) );
return mbedtls_ecp_tls_read_point(&ctx->grp, &ctx->Qp, buf,
end - *buf);
}
/*
@ -382,155 +385,162 @@ static int ecdh_read_params_internal( mbedtls_ecdh_context_mbed *ctx,
* ECPoint public;
* } ServerECDHParams;
*/
int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
const unsigned char **buf,
const unsigned char *end )
int mbedtls_ecdh_read_params(mbedtls_ecdh_context *ctx,
const unsigned char **buf,
const unsigned char *end)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_group_id grp_id;
if( ( ret = mbedtls_ecp_tls_read_group_id( &grp_id, buf, end - *buf ) )
!= 0 )
return( ret );
if ((ret = mbedtls_ecp_tls_read_group_id(&grp_id, buf, end - *buf))
!= 0) {
return ret;
}
if( ( ret = mbedtls_ecdh_setup( ctx, grp_id ) ) != 0 )
return( ret );
if ((ret = mbedtls_ecdh_setup(ctx, grp_id)) != 0) {
return ret;
}
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_read_params_internal( ctx, buf, end ) );
return ecdh_read_params_internal(ctx, buf, end);
#else
switch( ctx->var )
{
switch (ctx->var) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_read_params( &ctx->ctx.everest_ecdh,
buf, end) );
return mbedtls_everest_read_params(&ctx->ctx.everest_ecdh,
buf, end);
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_read_params_internal( &ctx->ctx.mbed_ecdh,
buf, end ) );
return ecdh_read_params_internal(&ctx->ctx.mbed_ecdh,
buf, end);
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_get_params_internal( mbedtls_ecdh_context_mbed *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side )
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;
/* If it's not our key, just import the public part as Qp */
if( side == MBEDTLS_ECDH_THEIRS )
return( mbedtls_ecp_copy( &ctx->Qp, &key->Q ) );
if (side == MBEDTLS_ECDH_THEIRS) {
return mbedtls_ecp_copy(&ctx->Qp, &key->Q);
}
/* Our key: import public (as Q) and private parts */
if( side != MBEDTLS_ECDH_OURS )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if (side != MBEDTLS_ECDH_OURS) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
if( ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 ||
( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 )
return( ret );
if ((ret = mbedtls_ecp_copy(&ctx->Q, &key->Q)) != 0 ||
(ret = mbedtls_mpi_copy(&ctx->d, &key->d)) != 0) {
return ret;
}
return( 0 );
return 0;
}
/*
* Get parameters from a keypair
*/
int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side )
int mbedtls_ecdh_get_params(mbedtls_ecdh_context *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( side != MBEDTLS_ECDH_OURS && side != MBEDTLS_ECDH_THEIRS )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if (side != MBEDTLS_ECDH_OURS && side != MBEDTLS_ECDH_THEIRS) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
if( mbedtls_ecdh_grp_id( ctx ) == MBEDTLS_ECP_DP_NONE )
{
if (mbedtls_ecdh_grp_id(ctx) == MBEDTLS_ECP_DP_NONE) {
/* This is the first call to get_params(). Set up the context
* for use with the group. */
if( ( ret = mbedtls_ecdh_setup( ctx, key->grp.id ) ) != 0 )
return( ret );
}
else
{
if ((ret = mbedtls_ecdh_setup(ctx, key->grp.id)) != 0) {
return ret;
}
} else {
/* This is not the first call to get_params(). Check that the
* current key's group is the same as the context's, which was set
* from the first key's group. */
if( mbedtls_ecdh_grp_id( ctx ) != key->grp.id )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if (mbedtls_ecdh_grp_id(ctx) != key->grp.id) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
}
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_get_params_internal( ctx, key, side ) );
return ecdh_get_params_internal(ctx, key, side);
#else
switch( ctx->var )
{
switch (ctx->var) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
{
mbedtls_everest_ecdh_side s = side == MBEDTLS_ECDH_OURS ?
MBEDTLS_EVEREST_ECDH_OURS :
MBEDTLS_EVEREST_ECDH_THEIRS;
return( mbedtls_everest_get_params( &ctx->ctx.everest_ecdh,
key, s) );
MBEDTLS_EVEREST_ECDH_OURS :
MBEDTLS_EVEREST_ECDH_THEIRS;
return mbedtls_everest_get_params(&ctx->ctx.everest_ecdh,
key, s);
}
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_get_params_internal( &ctx->ctx.mbed_ecdh,
key, side ) );
return ecdh_get_params_internal(&ctx->ctx.mbed_ecdh,
key, side);
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_make_public_internal( mbedtls_ecdh_context_mbed *ctx,
size_t *olen, int point_format,
unsigned char *buf, size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled )
static int ecdh_make_public_internal(mbedtls_ecdh_context_mbed *ctx,
size_t *olen, int point_format,
unsigned char *buf, size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif
if( ctx->grp.pbits == 0 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if (ctx->grp.pbits == 0) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( restart_enabled )
if (restart_enabled) {
rs_ctx = &ctx->rs;
}
#else
(void) restart_enabled;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( ( ret = ecdh_gen_public_restartable( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng, rs_ctx ) ) != 0 )
return( ret );
if ((ret = ecdh_gen_public_restartable(&ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng, rs_ctx)) != 0) {
return ret;
}
#else
if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng ) ) != 0 )
return( ret );
if ((ret = mbedtls_ecdh_gen_public(&ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng)) != 0) {
return ret;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
return mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, point_format, olen,
buf, blen );
return mbedtls_ecp_tls_write_point(&ctx->grp, &ctx->Q, point_format, olen,
buf, blen);
}
/*
* Setup and export the client public value
*/
int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_ecdh_make_public(mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int restart_enabled = 0;
#if defined(MBEDTLS_ECP_RESTARTABLE)
@ -538,125 +548,127 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
#endif
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_make_public_internal( ctx, olen, ctx->point_format, buf, blen,
f_rng, p_rng, restart_enabled ) );
return ecdh_make_public_internal(ctx, olen, ctx->point_format, buf, blen,
f_rng, p_rng, restart_enabled);
#else
switch( ctx->var )
{
switch (ctx->var) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_make_public( &ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng ) );
return mbedtls_everest_make_public(&ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng);
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_make_public_internal( &ctx->ctx.mbed_ecdh, olen,
ctx->point_format, buf, blen,
f_rng, p_rng,
restart_enabled ) );
return ecdh_make_public_internal(&ctx->ctx.mbed_ecdh, olen,
ctx->point_format, buf, blen,
f_rng, p_rng,
restart_enabled);
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_read_public_internal( mbedtls_ecdh_context_mbed *ctx,
const unsigned char *buf, size_t blen )
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;
const unsigned char *p = buf;
if( ( ret = mbedtls_ecp_tls_read_point( &ctx->grp, &ctx->Qp, &p,
blen ) ) != 0 )
return( ret );
if ((ret = mbedtls_ecp_tls_read_point(&ctx->grp, &ctx->Qp, &p,
blen)) != 0) {
return ret;
}
if( (size_t)( p - buf ) != blen )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if ((size_t) (p - buf) != blen) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
return( 0 );
return 0;
}
/*
* Parse and import the client's public value
*/
int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,
const unsigned char *buf, size_t blen )
int mbedtls_ecdh_read_public(mbedtls_ecdh_context *ctx,
const unsigned char *buf, size_t blen)
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_read_public_internal( ctx, buf, blen ) );
return ecdh_read_public_internal(ctx, buf, blen);
#else
switch( ctx->var )
{
switch (ctx->var) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_read_public( &ctx->ctx.everest_ecdh,
buf, blen ) );
return mbedtls_everest_read_public(&ctx->ctx.everest_ecdh,
buf, blen);
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_read_public_internal( &ctx->ctx.mbed_ecdh,
buf, blen ) );
return ecdh_read_public_internal(&ctx->ctx.mbed_ecdh,
buf, blen);
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_calc_secret_internal( mbedtls_ecdh_context_mbed *ctx,
size_t *olen, unsigned char *buf,
size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled )
static int ecdh_calc_secret_internal(mbedtls_ecdh_context_mbed *ctx,
size_t *olen, unsigned char *buf,
size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif
if( ctx == NULL || ctx->grp.pbits == 0 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if (ctx == NULL || ctx->grp.pbits == 0) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( restart_enabled )
if (restart_enabled) {
rs_ctx = &ctx->rs;
}
#else
(void) restart_enabled;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( ( ret = ecdh_compute_shared_restartable( &ctx->grp, &ctx->z, &ctx->Qp,
&ctx->d, f_rng, p_rng,
rs_ctx ) ) != 0 )
{
return( ret );
if ((ret = ecdh_compute_shared_restartable(&ctx->grp, &ctx->z, &ctx->Qp,
&ctx->d, f_rng, p_rng,
rs_ctx)) != 0) {
return ret;
}
#else
if( ( ret = mbedtls_ecdh_compute_shared( &ctx->grp, &ctx->z, &ctx->Qp,
&ctx->d, f_rng, p_rng ) ) != 0 )
{
return( ret );
if ((ret = mbedtls_ecdh_compute_shared(&ctx->grp, &ctx->z, &ctx->Qp,
&ctx->d, f_rng, p_rng)) != 0) {
return ret;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
if( mbedtls_mpi_size( &ctx->z ) > blen )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if (mbedtls_mpi_size(&ctx->z) > blen) {
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
*olen = ctx->grp.pbits / 8 + ( ( ctx->grp.pbits % 8 ) != 0 );
*olen = ctx->grp.pbits / 8 + ((ctx->grp.pbits % 8) != 0);
if( mbedtls_ecp_get_type( &ctx->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
return mbedtls_mpi_write_binary_le( &ctx->z, buf, *olen );
if (mbedtls_ecp_get_type(&ctx->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
return mbedtls_mpi_write_binary_le(&ctx->z, buf, *olen);
}
return mbedtls_mpi_write_binary( &ctx->z, buf, *olen );
return mbedtls_mpi_write_binary(&ctx->z, buf, *olen);
}
/*
* Derive and export the shared secret
*/
int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_ecdh_calc_secret(mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int restart_enabled = 0;
#if defined(MBEDTLS_ECP_RESTARTABLE)
@ -664,22 +676,21 @@ int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
#endif
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_calc_secret_internal( ctx, olen, buf, blen, f_rng, p_rng,
restart_enabled ) );
return ecdh_calc_secret_internal(ctx, olen, buf, blen, f_rng, p_rng,
restart_enabled);
#else
switch( ctx->var )
{
switch (ctx->var) {
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_calc_secret( &ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng ) );
return mbedtls_everest_calc_secret(&ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng);
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_calc_secret_internal( &ctx->ctx.mbed_ecdh, olen, buf,
blen, f_rng, p_rng,
restart_enabled ) );
return ecdh_calc_secret_internal(&ctx->ctx.mbed_ecdh, olen, buf,
blen, f_rng, p_rng,
restart_enabled);
default:
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -72,7 +72,7 @@
*
* \return Non-zero if successful.
*/
unsigned char mbedtls_internal_ecp_grp_capable( const mbedtls_ecp_group *grp );
unsigned char mbedtls_internal_ecp_grp_capable(const mbedtls_ecp_group *grp);
/**
* \brief Initialise the Elliptic Curve Point module extension.
@ -89,7 +89,7 @@ unsigned char mbedtls_internal_ecp_grp_capable( const mbedtls_ecp_group *grp );
*
* \return 0 if successful.
*/
int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp );
int mbedtls_internal_ecp_init(const mbedtls_ecp_group *grp);
/**
* \brief Frees and deallocates the Elliptic Curve Point module
@ -97,7 +97,7 @@ int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp );
*
* \param grp The pointer to the group the module was initialised for.
*/
void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp );
void mbedtls_internal_ecp_free(const mbedtls_ecp_group *grp);
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
@ -117,9 +117,11 @@ void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp );
*
* \return 0 if successful.
*/
int mbedtls_internal_ecp_randomize_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt, int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int mbedtls_internal_ecp_randomize_jac(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt, int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng);
#endif
#if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
@ -162,9 +164,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 );
int mbedtls_internal_ecp_add_mixed(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q);
#endif
/**
@ -187,8 +189,8 @@ int mbedtls_internal_ecp_add_mixed( const mbedtls_ecp_group *grp,
* \return 0 if successful.
*/
#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
int mbedtls_internal_ecp_double_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, const mbedtls_ecp_point *P );
int mbedtls_internal_ecp_double_jac(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, const mbedtls_ecp_point *P);
#endif
/**
@ -217,8 +219,8 @@ int mbedtls_internal_ecp_double_jac( const mbedtls_ecp_group *grp,
* an error if one of the points is zero.
*/
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
int mbedtls_internal_ecp_normalize_jac_many( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *T[], size_t t_len );
int mbedtls_internal_ecp_normalize_jac_many(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *T[], size_t t_len);
#endif
/**
@ -235,8 +237,8 @@ int mbedtls_internal_ecp_normalize_jac_many( const mbedtls_ecp_group *grp,
* \return 0 if successful.
*/
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
int mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt );
int mbedtls_internal_ecp_normalize_jac(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt);
#endif
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
@ -244,9 +246,12 @@ int mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp,
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
int mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, mbedtls_ecp_point *S, const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d );
int mbedtls_internal_ecp_double_add_mxz(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R,
mbedtls_ecp_point *S,
const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q,
const mbedtls_mpi *d);
#endif
/**
@ -265,9 +270,11 @@ int mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp,
* \return 0 if successful
*/
#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
int mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int mbedtls_internal_ecp_randomize_mxz(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P, int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng);
#endif
/**
@ -281,8 +288,8 @@ int mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp,
* \return 0 if successful
*/
#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
int mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P );
int mbedtls_internal_ecp_normalize_mxz(const mbedtls_ecp_group *grp,
mbedtls_ecp_point *P);
#endif
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
@ -290,4 +297,3 @@ int mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp,
#endif /* MBEDTLS_ECP_INTERNAL_ALT */
#endif /* ecp_internal_alt.h */

View File

@ -44,7 +44,7 @@
* Behavior:
* Set N to c * 2^bits + old_value_of_N.
*/
void mbedtls_ecp_fix_negative( mbedtls_mpi *N, signed char c, size_t bits );
void mbedtls_ecp_fix_negative(mbedtls_mpi *N, signed char c, size_t bits);
#endif
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
@ -69,10 +69,10 @@ void mbedtls_ecp_fix_negative( mbedtls_mpi *N, signed char c, size_t bits );
* \return \c 0 on success.
* \return \c MBEDTLS_ERR_ECP_xxx or MBEDTLS_ERR_MPI_xxx on failure.
*/
int mbedtls_ecp_gen_privkey_mx( size_t n_bits,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int mbedtls_ecp_gen_privkey_mx(size_t n_bits,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */

View File

@ -39,20 +39,20 @@
#define ENTROPY_MAX_LOOP 256 /**< Maximum amount to loop before error */
void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
void mbedtls_entropy_init(mbedtls_entropy_context *ctx)
{
ctx->source_count = 0;
memset( ctx->source, 0, sizeof( ctx->source ) );
memset(ctx->source, 0, sizeof(ctx->source));
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &ctx->mutex );
mbedtls_mutex_init(&ctx->mutex);
#endif
ctx->accumulator_started = 0;
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
mbedtls_sha512_init( &ctx->accumulator );
mbedtls_sha512_init(&ctx->accumulator);
#else
mbedtls_sha256_init( &ctx->accumulator );
mbedtls_sha256_init(&ctx->accumulator);
#endif
/* Reminder: Update ENTROPY_HAVE_STRONG in the test files
@ -60,61 +60,62 @@ void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
#if !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
mbedtls_entropy_add_source( ctx, mbedtls_platform_entropy_poll, NULL,
MBEDTLS_ENTROPY_MIN_PLATFORM,
MBEDTLS_ENTROPY_SOURCE_STRONG );
mbedtls_entropy_add_source(ctx, mbedtls_platform_entropy_poll, NULL,
MBEDTLS_ENTROPY_MIN_PLATFORM,
MBEDTLS_ENTROPY_SOURCE_STRONG);
#endif
#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
mbedtls_entropy_add_source( ctx, mbedtls_hardware_poll, NULL,
MBEDTLS_ENTROPY_MIN_HARDWARE,
MBEDTLS_ENTROPY_SOURCE_STRONG );
mbedtls_entropy_add_source(ctx, mbedtls_hardware_poll, NULL,
MBEDTLS_ENTROPY_MIN_HARDWARE,
MBEDTLS_ENTROPY_SOURCE_STRONG);
#endif
#if defined(MBEDTLS_ENTROPY_NV_SEED)
mbedtls_entropy_add_source( ctx, mbedtls_nv_seed_poll, NULL,
MBEDTLS_ENTROPY_BLOCK_SIZE,
MBEDTLS_ENTROPY_SOURCE_STRONG );
mbedtls_entropy_add_source(ctx, mbedtls_nv_seed_poll, NULL,
MBEDTLS_ENTROPY_BLOCK_SIZE,
MBEDTLS_ENTROPY_SOURCE_STRONG);
ctx->initial_entropy_run = 0;
#endif
#endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */
}
void mbedtls_entropy_free( mbedtls_entropy_context *ctx )
void mbedtls_entropy_free(mbedtls_entropy_context *ctx)
{
/* If the context was already free, don't call free() again.
* This is important for mutexes which don't allow double-free. */
if( ctx->accumulator_started == -1 )
if (ctx->accumulator_started == -1) {
return;
}
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_free( &ctx->mutex );
mbedtls_mutex_free(&ctx->mutex);
#endif
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
mbedtls_sha512_free( &ctx->accumulator );
mbedtls_sha512_free(&ctx->accumulator);
#else
mbedtls_sha256_free( &ctx->accumulator );
mbedtls_sha256_free(&ctx->accumulator);
#endif
#if defined(MBEDTLS_ENTROPY_NV_SEED)
ctx->initial_entropy_run = 0;
#endif
ctx->source_count = 0;
mbedtls_platform_zeroize( ctx->source, sizeof( ctx->source ) );
mbedtls_platform_zeroize(ctx->source, sizeof(ctx->source));
ctx->accumulator_started = -1;
}
int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
mbedtls_entropy_f_source_ptr f_source, void *p_source,
size_t threshold, int strong )
int mbedtls_entropy_add_source(mbedtls_entropy_context *ctx,
mbedtls_entropy_f_source_ptr f_source, void *p_source,
size_t threshold, int strong)
{
int idx, ret = 0;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
return ret;
}
#endif
idx = ctx->source_count;
if( idx >= MBEDTLS_ENTROPY_MAX_SOURCES )
{
if (idx >= MBEDTLS_ENTROPY_MAX_SOURCES) {
ret = MBEDTLS_ERR_ENTROPY_MAX_SOURCES;
goto exit;
}
@ -128,18 +129,19 @@ int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
exit:
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
}
#endif
return( ret );
return ret;
}
/*
* Entropy accumulator update
*/
static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id,
const unsigned char *data, size_t len )
static int entropy_update(mbedtls_entropy_context *ctx, unsigned char source_id,
const unsigned char *data, size_t len)
{
unsigned char header[2];
unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE];
@ -147,14 +149,15 @@ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id
const unsigned char *p = data;
int ret = 0;
if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE )
{
if (use_len > MBEDTLS_ENTROPY_BLOCK_SIZE) {
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
if( ( ret = mbedtls_sha512( data, len, tmp, 0 ) ) != 0 )
if ((ret = mbedtls_sha512(data, len, tmp, 0)) != 0) {
goto cleanup;
}
#else
if( ( ret = mbedtls_sha256( data, len, tmp, 0 ) ) != 0 )
if ((ret = mbedtls_sha256(data, len, tmp, 0)) != 0) {
goto cleanup;
}
#endif
p = tmp;
use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
@ -169,55 +172,61 @@ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id
* gather entropy eventually execute this code.
*/
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
if( ctx->accumulator_started == 0 &&
( ret = mbedtls_sha512_starts( &ctx->accumulator, 0 ) ) != 0 )
if (ctx->accumulator_started == 0 &&
(ret = mbedtls_sha512_starts(&ctx->accumulator, 0)) != 0) {
goto cleanup;
else
} else {
ctx->accumulator_started = 1;
if( ( ret = mbedtls_sha512_update( &ctx->accumulator, header, 2 ) ) != 0 )
}
if ((ret = mbedtls_sha512_update(&ctx->accumulator, header, 2)) != 0) {
goto cleanup;
ret = mbedtls_sha512_update( &ctx->accumulator, p, use_len );
}
ret = mbedtls_sha512_update(&ctx->accumulator, p, use_len);
#else
if( ctx->accumulator_started == 0 &&
( ret = mbedtls_sha256_starts( &ctx->accumulator, 0 ) ) != 0 )
if (ctx->accumulator_started == 0 &&
(ret = mbedtls_sha256_starts(&ctx->accumulator, 0)) != 0) {
goto cleanup;
else
} else {
ctx->accumulator_started = 1;
if( ( ret = mbedtls_sha256_update( &ctx->accumulator, header, 2 ) ) != 0 )
}
if ((ret = mbedtls_sha256_update(&ctx->accumulator, header, 2)) != 0) {
goto cleanup;
ret = mbedtls_sha256_update( &ctx->accumulator, p, use_len );
}
ret = mbedtls_sha256_update(&ctx->accumulator, p, use_len);
#endif
cleanup:
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
mbedtls_platform_zeroize(tmp, sizeof(tmp));
return( ret );
return ret;
}
int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
const unsigned char *data, size_t len )
int mbedtls_entropy_update_manual(mbedtls_entropy_context *ctx,
const unsigned char *data, size_t len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
return ret;
}
#endif
ret = entropy_update( ctx, MBEDTLS_ENTROPY_SOURCE_MANUAL, data, len );
ret = entropy_update(ctx, MBEDTLS_ENTROPY_SOURCE_MANUAL, data, len);
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
}
#endif
return( ret );
return ret;
}
/*
* Run through the different sources to add entropy to our accumulator
*/
static int entropy_gather_internal( mbedtls_entropy_context *ctx )
static int entropy_gather_internal(mbedtls_entropy_context *ctx)
{
int ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
int i;
@ -225,121 +234,125 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx )
unsigned char buf[MBEDTLS_ENTROPY_MAX_GATHER];
size_t olen;
if( ctx->source_count == 0 )
return( MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED );
if (ctx->source_count == 0) {
return MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED;
}
/*
* Run through our entropy sources
*/
for( i = 0; i < ctx->source_count; i++ )
{
if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG )
for (i = 0; i < ctx->source_count; i++) {
if (ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG) {
have_one_strong = 1;
}
olen = 0;
if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source,
buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen ) ) != 0 )
{
if ((ret = ctx->source[i].f_source(ctx->source[i].p_source,
buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen)) != 0) {
goto cleanup;
}
/*
* Add if we actually gathered something
*/
if( olen > 0 )
{
if( ( ret = entropy_update( ctx, (unsigned char) i,
buf, olen ) ) != 0 )
return( ret );
if (olen > 0) {
if ((ret = entropy_update(ctx, (unsigned char) i,
buf, olen)) != 0) {
return ret;
}
ctx->source[i].size += olen;
}
}
if( have_one_strong == 0 )
if (have_one_strong == 0) {
ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;
}
cleanup:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
mbedtls_platform_zeroize(buf, sizeof(buf));
return( ret );
return ret;
}
/*
* Thread-safe wrapper for entropy_gather_internal()
*/
int mbedtls_entropy_gather( mbedtls_entropy_context *ctx )
int mbedtls_entropy_gather(mbedtls_entropy_context *ctx)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
return ret;
}
#endif
ret = entropy_gather_internal( ctx );
ret = entropy_gather_internal(ctx);
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
}
#endif
return( ret );
return ret;
}
int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
int mbedtls_entropy_func(void *data, unsigned char *output, size_t len)
{
int ret, count = 0, i, thresholds_reached;
size_t strong_size;
mbedtls_entropy_context *ctx = (mbedtls_entropy_context *) data;
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
if( len > MBEDTLS_ENTROPY_BLOCK_SIZE )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
if (len > MBEDTLS_ENTROPY_BLOCK_SIZE) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
#if defined(MBEDTLS_ENTROPY_NV_SEED)
/* Update the NV entropy seed before generating any entropy for outside
* use.
*/
if( ctx->initial_entropy_run == 0 )
{
if (ctx->initial_entropy_run == 0) {
ctx->initial_entropy_run = 1;
if( ( ret = mbedtls_entropy_update_nv_seed( ctx ) ) != 0 )
return( ret );
if ((ret = mbedtls_entropy_update_nv_seed(ctx)) != 0) {
return ret;
}
}
#endif
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
return ret;
}
#endif
/*
* Always gather extra entropy before a call
*/
do
{
if( count++ > ENTROPY_MAX_LOOP )
{
do {
if (count++ > ENTROPY_MAX_LOOP) {
ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
goto exit;
}
if( ( ret = entropy_gather_internal( ctx ) ) != 0 )
if ((ret = entropy_gather_internal(ctx)) != 0) {
goto exit;
}
thresholds_reached = 1;
strong_size = 0;
for( i = 0; i < ctx->source_count; i++ )
{
if( ctx->source[i].size < ctx->source[i].threshold )
for (i = 0; i < ctx->source_count; i++) {
if (ctx->source[i].size < ctx->source[i].threshold) {
thresholds_reached = 0;
if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG )
}
if (ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG) {
strong_size += ctx->source[i].size;
}
}
}
while( ! thresholds_reached || strong_size < MBEDTLS_ENTROPY_BLOCK_SIZE );
} while (!thresholds_reached || strong_size < MBEDTLS_ENTROPY_BLOCK_SIZE);
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset(buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
/*
@ -347,112 +360,121 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
* in a previous call to entropy_update(). If this is not guaranteed, the
* code below will fail.
*/
if( ( ret = mbedtls_sha512_finish( &ctx->accumulator, buf ) ) != 0 )
if ((ret = mbedtls_sha512_finish(&ctx->accumulator, buf)) != 0) {
goto exit;
}
/*
* Reset accumulator and counters and recycle existing entropy
*/
mbedtls_sha512_free( &ctx->accumulator );
mbedtls_sha512_init( &ctx->accumulator );
if( ( ret = mbedtls_sha512_starts( &ctx->accumulator, 0 ) ) != 0 )
mbedtls_sha512_free(&ctx->accumulator);
mbedtls_sha512_init(&ctx->accumulator);
if ((ret = mbedtls_sha512_starts(&ctx->accumulator, 0)) != 0) {
goto exit;
if( ( ret = mbedtls_sha512_update( &ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
}
if ((ret = mbedtls_sha512_update(&ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
goto exit;
}
/*
* Perform second SHA-512 on entropy
*/
if( ( ret = mbedtls_sha512( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
buf, 0 ) ) != 0 )
if ((ret = mbedtls_sha512(buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
buf, 0)) != 0) {
goto exit;
}
#else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
if( ( ret = mbedtls_sha256_finish( &ctx->accumulator, buf ) ) != 0 )
if ((ret = mbedtls_sha256_finish(&ctx->accumulator, buf)) != 0) {
goto exit;
}
/*
* Reset accumulator and counters and recycle existing entropy
*/
mbedtls_sha256_free( &ctx->accumulator );
mbedtls_sha256_init( &ctx->accumulator );
if( ( ret = mbedtls_sha256_starts( &ctx->accumulator, 0 ) ) != 0 )
mbedtls_sha256_free(&ctx->accumulator);
mbedtls_sha256_init(&ctx->accumulator);
if ((ret = mbedtls_sha256_starts(&ctx->accumulator, 0)) != 0) {
goto exit;
if( ( ret = mbedtls_sha256_update( &ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
}
if ((ret = mbedtls_sha256_update(&ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
goto exit;
}
/*
* Perform second SHA-256 on entropy
*/
if( ( ret = mbedtls_sha256( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
buf, 0 ) ) != 0 )
if ((ret = mbedtls_sha256(buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
buf, 0)) != 0) {
goto exit;
}
#endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
for( i = 0; i < ctx->source_count; i++ )
for (i = 0; i < ctx->source_count; i++) {
ctx->source[i].size = 0;
}
memcpy( output, buf, len );
memcpy(output, buf, len);
ret = 0;
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
mbedtls_platform_zeroize(buf, sizeof(buf));
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
}
#endif
return( ret );
return ret;
}
#if defined(MBEDTLS_ENTROPY_NV_SEED)
int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )
int mbedtls_entropy_update_nv_seed(mbedtls_entropy_context *ctx)
{
int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
/* Read new seed and write it to NV */
if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
return( ret );
if ((ret = mbedtls_entropy_func(ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
return ret;
}
if( mbedtls_nv_seed_write( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )
return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
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 );
ret = mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset(buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
ret = mbedtls_entropy_update_manual(ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE);
return( ret );
return ret;
}
#endif /* MBEDTLS_ENTROPY_NV_SEED */
#if defined(MBEDTLS_FS_IO)
int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path )
int mbedtls_entropy_write_seed_file(mbedtls_entropy_context *ctx, const char *path)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
FILE *f = NULL;
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
{
if ((ret = mbedtls_entropy_func(ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
goto exit;
}
if( ( f = fopen( path, "wb" ) ) == NULL )
{
if ((f = fopen(path, "wb")) == NULL) {
ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
goto exit;
}
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( f, NULL );
mbedtls_setbuf(f, NULL);
if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE )
{
if (fwrite(buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f) != MBEDTLS_ENTROPY_BLOCK_SIZE) {
ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
goto exit;
}
@ -460,47 +482,52 @@ int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *p
ret = 0;
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
mbedtls_platform_zeroize(buf, sizeof(buf));
if( f != NULL )
fclose( f );
if (f != NULL) {
fclose(f);
}
return( ret );
return ret;
}
int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path )
int mbedtls_entropy_update_seed_file(mbedtls_entropy_context *ctx, const char *path)
{
int ret = 0;
FILE *f;
size_t n;
unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ];
unsigned char buf[MBEDTLS_ENTROPY_MAX_SEED_SIZE];
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
if ((f = fopen(path, "rb")) == NULL) {
return MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
}
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( f, NULL );
mbedtls_setbuf(f, NULL);
fseek( f, 0, SEEK_END );
n = (size_t) ftell( f );
fseek( f, 0, SEEK_SET );
fseek(f, 0, SEEK_END);
n = (size_t) ftell(f);
fseek(f, 0, SEEK_SET);
if( n > MBEDTLS_ENTROPY_MAX_SEED_SIZE )
if (n > MBEDTLS_ENTROPY_MAX_SEED_SIZE) {
n = MBEDTLS_ENTROPY_MAX_SEED_SIZE;
}
if( fread( buf, 1, n, f ) != n )
if (fread(buf, 1, n, f) != n) {
ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
else
ret = mbedtls_entropy_update_manual( ctx, buf, n );
} else {
ret = mbedtls_entropy_update_manual(ctx, buf, n);
}
fclose( f );
fclose(f);
mbedtls_platform_zeroize( buf, sizeof( buf ) );
mbedtls_platform_zeroize(buf, sizeof(buf));
if( ret != 0 )
return( ret );
if (ret != 0) {
return ret;
}
return( mbedtls_entropy_write_seed_file( ctx, path ) );
return mbedtls_entropy_write_seed_file(ctx, path);
}
#endif /* MBEDTLS_FS_IO */
@ -508,59 +535,57 @@ int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *
/*
* Dummy source function
*/
static int entropy_dummy_source( void *data, unsigned char *output,
size_t len, size_t *olen )
static int entropy_dummy_source(void *data, unsigned char *output,
size_t len, size_t *olen)
{
((void) data);
memset( output, 0x2a, len );
memset(output, 0x2a, len);
*olen = len;
return( 0 );
return 0;
}
#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
static int mbedtls_entropy_source_self_test_gather( unsigned char *buf, size_t buf_len )
static int mbedtls_entropy_source_self_test_gather(unsigned char *buf, size_t buf_len)
{
int ret = 0;
size_t entropy_len = 0;
size_t olen = 0;
size_t attempts = buf_len;
while( attempts > 0 && entropy_len < buf_len )
{
if( ( ret = mbedtls_hardware_poll( NULL, buf + entropy_len,
buf_len - entropy_len, &olen ) ) != 0 )
return( ret );
while (attempts > 0 && entropy_len < buf_len) {
if ((ret = mbedtls_hardware_poll(NULL, buf + entropy_len,
buf_len - entropy_len, &olen)) != 0) {
return ret;
}
entropy_len += olen;
attempts--;
}
if( entropy_len < buf_len )
{
if (entropy_len < buf_len) {
ret = 1;
}
return( ret );
return ret;
}
static int mbedtls_entropy_source_self_test_check_bits( const unsigned char *buf,
size_t buf_len )
static int mbedtls_entropy_source_self_test_check_bits(const unsigned char *buf,
size_t buf_len)
{
unsigned char set= 0xFF;
unsigned char set = 0xFF;
unsigned char unset = 0x00;
size_t i;
for( i = 0; i < buf_len; i++ )
{
for (i = 0; i < buf_len; i++) {
set &= buf[i];
unset |= buf[i];
}
return( set == 0xFF || unset == 0x00 );
return set == 0xFF || unset == 0x00;
}
/*
@ -574,45 +599,50 @@ static int mbedtls_entropy_source_self_test_check_bits( const unsigned char *buf
* are not equal.
* - The error code returned by the entropy source is not an error.
*/
int mbedtls_entropy_source_self_test( int verbose )
int mbedtls_entropy_source_self_test(int verbose)
{
int ret = 0;
unsigned char buf0[2 * sizeof( unsigned long long int )];
unsigned char buf1[2 * sizeof( unsigned long long int )];
unsigned char buf0[2 * sizeof(unsigned long long int)];
unsigned char buf1[2 * sizeof(unsigned long long int)];
if( verbose != 0 )
mbedtls_printf( " ENTROPY_BIAS test: " );
if (verbose != 0) {
mbedtls_printf(" ENTROPY_BIAS test: ");
}
memset( buf0, 0x00, sizeof( buf0 ) );
memset( buf1, 0x00, sizeof( buf1 ) );
memset(buf0, 0x00, sizeof(buf0));
memset(buf1, 0x00, sizeof(buf1));
if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 )
if ((ret = mbedtls_entropy_source_self_test_gather(buf0, sizeof(buf0))) != 0) {
goto cleanup;
if( ( ret = mbedtls_entropy_source_self_test_gather( buf1, sizeof( buf1 ) ) ) != 0 )
}
if ((ret = mbedtls_entropy_source_self_test_gather(buf1, sizeof(buf1))) != 0) {
goto cleanup;
}
/* Make sure that the returned values are not all 0 or 1 */
if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf0, sizeof( buf0 ) ) ) != 0 )
if ((ret = mbedtls_entropy_source_self_test_check_bits(buf0, sizeof(buf0))) != 0) {
goto cleanup;
if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf1, sizeof( buf1 ) ) ) != 0 )
}
if ((ret = mbedtls_entropy_source_self_test_check_bits(buf1, sizeof(buf1))) != 0) {
goto cleanup;
}
/* Make sure that the entropy source is not returning values in a
* pattern */
ret = memcmp( buf0, buf1, sizeof( buf0 ) ) == 0;
ret = memcmp(buf0, buf1, sizeof(buf0)) == 0;
cleanup:
if( verbose != 0 )
{
if( ret != 0 )
mbedtls_printf( "failed\n" );
else
mbedtls_printf( "passed\n" );
if (verbose != 0) {
if (ret != 0) {
mbedtls_printf("failed\n");
} else {
mbedtls_printf("passed\n");
}
mbedtls_printf( "\n" );
mbedtls_printf("\n");
}
return( ret != 0 );
return ret != 0;
}
#endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */
@ -622,7 +652,7 @@ cleanup:
* test that the functions don't cause errors and write the correct
* amount of data to buffers.
*/
int mbedtls_entropy_self_test( int verbose )
int mbedtls_entropy_self_test(int verbose)
{
int ret = 1;
mbedtls_entropy_context ctx;
@ -630,22 +660,26 @@ int mbedtls_entropy_self_test( int verbose )
unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
size_t i, j;
if( verbose != 0 )
mbedtls_printf( " ENTROPY test: " );
if (verbose != 0) {
mbedtls_printf(" ENTROPY test: ");
}
mbedtls_entropy_init( &ctx );
mbedtls_entropy_init(&ctx);
/* First do a gather to make sure we have default sources */
if( ( ret = mbedtls_entropy_gather( &ctx ) ) != 0 )
if ((ret = mbedtls_entropy_gather(&ctx)) != 0) {
goto cleanup;
}
ret = mbedtls_entropy_add_source( &ctx, entropy_dummy_source, NULL, 16,
MBEDTLS_ENTROPY_SOURCE_WEAK );
if( ret != 0 )
ret = mbedtls_entropy_add_source(&ctx, entropy_dummy_source, NULL, 16,
MBEDTLS_ENTROPY_SOURCE_WEAK);
if (ret != 0) {
goto cleanup;
}
if( ( ret = mbedtls_entropy_update_manual( &ctx, buf, sizeof buf ) ) != 0 )
if ((ret = mbedtls_entropy_update_manual(&ctx, buf, sizeof buf)) != 0) {
goto cleanup;
}
/*
* To test that mbedtls_entropy_func writes correct number of bytes:
@ -655,43 +689,43 @@ int mbedtls_entropy_self_test( int verbose )
* each of the 32 or 64 bytes to be non-zero has a false failure rate
* of at most 2^(-58) which is acceptable.
*/
for( i = 0; i < 8; i++ )
{
if( ( ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) ) ) != 0 )
for (i = 0; i < 8; i++) {
if ((ret = mbedtls_entropy_func(&ctx, buf, sizeof(buf))) != 0) {
goto cleanup;
}
for( j = 0; j < sizeof( buf ); j++ )
for (j = 0; j < sizeof(buf); j++) {
acc[j] |= buf[j];
}
}
for( j = 0; j < sizeof( buf ); j++ )
{
if( acc[j] == 0 )
{
for (j = 0; j < sizeof(buf); j++) {
if (acc[j] == 0) {
ret = 1;
goto cleanup;
}
}
#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
if( ( ret = mbedtls_entropy_source_self_test( 0 ) ) != 0 )
if ((ret = mbedtls_entropy_source_self_test(0)) != 0) {
goto cleanup;
}
#endif
cleanup:
mbedtls_entropy_free( &ctx );
mbedtls_entropy_free(&ctx);
if( verbose != 0 )
{
if( ret != 0 )
mbedtls_printf( "failed\n" );
else
mbedtls_printf( "passed\n" );
if (verbose != 0) {
if (ret != 0) {
mbedtls_printf("failed\n");
} else {
mbedtls_printf("passed\n");
}
mbedtls_printf( "\n" );
mbedtls_printf("\n");
}
return( ret != 0 );
return ret != 0;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@ -42,7 +42,8 @@
#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
!defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \
!defined(__HAIKU__) && !defined(__midipix__)
#error "Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in mbedtls_config.h"
#error \
"Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in mbedtls_config.h"
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
@ -53,29 +54,27 @@
#include <windows.h>
#include <wincrypt.h>
int mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len,
size_t *olen )
int mbedtls_platform_entropy_poll(void *data, unsigned char *output, size_t len,
size_t *olen)
{
HCRYPTPROV provider;
((void) data);
*olen = 0;
if( CryptAcquireContext( &provider, NULL, NULL,
PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) == FALSE )
{
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
if (CryptAcquireContext(&provider, NULL, NULL,
PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
if( CryptGenRandom( provider, (DWORD) len, output ) == FALSE )
{
CryptReleaseContext( provider, 0 );
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
if (CryptGenRandom(provider, (DWORD) len, output) == FALSE) {
CryptReleaseContext(provider, 0);
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
CryptReleaseContext( provider, 0 );
CryptReleaseContext(provider, 0);
*olen = len;
return( 0 );
return 0;
}
#else /* _WIN32 && !EFIX64 && !EFI32 */
@ -91,15 +90,15 @@ int mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len
#define HAVE_GETRANDOM
#include <errno.h>
static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
static int getrandom_wrapper(void *buf, size_t buflen, unsigned int flags)
{
/* MemSan cannot understand that the syscall writes to the buffer */
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
memset( buf, 0, buflen );
memset(buf, 0, buflen);
#endif
#endif
return( syscall( SYS_getrandom, buf, buflen, flags ) );
return syscall(SYS_getrandom, buf, buflen, flags);
}
#endif /* SYS_getrandom */
#endif /* __linux__ || __midipix__ */
@ -111,9 +110,9 @@ static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
#include <errno.h>
#include <sys/random.h>
#define HAVE_GETRANDOM
static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
static int getrandom_wrapper(void *buf, size_t buflen, unsigned int flags)
{
return getrandom( buf, buflen, flags );
return getrandom(buf, buflen, flags);
}
#endif /* (__FreeBSD__ && __FreeBSD_version >= 1200000) ||
(__DragonFly__ && __DragonFly_version >= 500700) */
@ -133,7 +132,7 @@ static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
#if defined(KERN_ARND)
#define HAVE_SYSCTL_ARND
static int sysctl_arnd_wrapper( unsigned char *buf, size_t buflen )
static int sysctl_arnd_wrapper(unsigned char *buf, size_t buflen)
{
int name[2];
size_t len;
@ -141,23 +140,23 @@ static int sysctl_arnd_wrapper( unsigned char *buf, size_t buflen )
name[0] = CTL_KERN;
name[1] = KERN_ARND;
while( buflen > 0 )
{
while (buflen > 0) {
len = buflen > 256 ? 256 : buflen;
if( sysctl(name, 2, buf, &len, NULL, 0) == -1 )
return( -1 );
if (sysctl(name, 2, buf, &len, NULL, 0) == -1) {
return -1;
}
buflen -= len;
buf += len;
}
return( 0 );
return 0;
}
#endif /* KERN_ARND */
#endif /* __FreeBSD__ || __NetBSD__ */
#include <stdio.h>
int mbedtls_platform_entropy_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
int mbedtls_platform_entropy_poll(void *data,
unsigned char *output, size_t len, size_t *olen)
{
FILE *file;
size_t read_len;
@ -165,14 +164,13 @@ int mbedtls_platform_entropy_poll( void *data,
((void) data);
#if defined(HAVE_GETRANDOM)
ret = getrandom_wrapper( output, len, 0 );
if( ret >= 0 )
{
ret = getrandom_wrapper(output, len, 0);
if (ret >= 0) {
*olen = ret;
return( 0 );
return 0;
} else if (errno != ENOSYS) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
else if( errno != ENOSYS )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
/* Fall through if the system call isn't known. */
#else
((void) ret);
@ -181,57 +179,60 @@ int mbedtls_platform_entropy_poll( void *data,
#if defined(HAVE_SYSCTL_ARND)
((void) file);
((void) read_len);
if( sysctl_arnd_wrapper( output, len ) == -1 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
if (sysctl_arnd_wrapper(output, len) == -1) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
*olen = len;
return( 0 );
return 0;
#else
*olen = 0;
file = fopen( "/dev/urandom", "rb" );
if( file == NULL )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( file, NULL );
read_len = fread( output, 1, len, file );
if( read_len != len )
{
fclose( file );
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
file = fopen("/dev/urandom", "rb");
if (file == NULL) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
fclose( file );
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf(file, NULL);
read_len = fread(output, 1, len, file);
if (read_len != len) {
fclose(file);
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
fclose(file);
*olen = len;
return( 0 );
return 0;
#endif /* HAVE_SYSCTL_ARND */
}
#endif /* _WIN32 && !EFIX64 && !EFI32 */
#endif /* !MBEDTLS_NO_PLATFORM_ENTROPY */
#if defined(MBEDTLS_ENTROPY_NV_SEED)
int mbedtls_nv_seed_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
int mbedtls_nv_seed_poll(void *data,
unsigned char *output, size_t len, size_t *olen)
{
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
size_t use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
((void) data);
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset(buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
if( mbedtls_nv_seed_read( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
if (mbedtls_nv_seed_read(buf, MBEDTLS_ENTROPY_BLOCK_SIZE) < 0) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
if( len < use_len )
use_len = len;
if (len < use_len) {
use_len = len;
}
memcpy( output, buf, use_len );
memcpy(output, buf, use_len);
*olen = use_len;
return( 0 );
return 0;
}
#endif /* MBEDTLS_ENTROPY_NV_SEED */

View File

@ -42,8 +42,8 @@ extern "C" {
/**
* \brief Platform-specific entropy poll callback
*/
int mbedtls_platform_entropy_poll( void *data,
unsigned char *output, size_t len, size_t *olen );
int mbedtls_platform_entropy_poll(void *data,
unsigned char *output, size_t len, size_t *olen);
#endif
#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
@ -55,8 +55,8 @@ int mbedtls_platform_entropy_poll( void *data,
*
* \note This must accept NULL as its first argument.
*/
int mbedtls_hardware_poll( void *data,
unsigned char *output, size_t len, size_t *olen );
int mbedtls_hardware_poll(void *data,
unsigned char *output, size_t len, size_t *olen);
#endif
#if defined(MBEDTLS_ENTROPY_NV_SEED)
@ -65,8 +65,8 @@ int mbedtls_hardware_poll( void *data,
*
* \note This must accept NULL as its first argument.
*/
int mbedtls_nv_seed_poll( void *data,
unsigned char *output, size_t len, size_t *olen );
int mbedtls_nv_seed_poll(void *data,
unsigned char *output, size_t len, size_t *olen);
#endif
#ifdef __cplusplus

File diff suppressed because it is too large Load Diff

View File

@ -24,8 +24,7 @@
#include "mbedtls/legacy_or_psa.h"
#include "mbedtls/error.h"
typedef struct
{
typedef struct {
psa_algorithm_t psa_alg;
mbedtls_md_type_t md_type;
unsigned char size;
@ -58,12 +57,11 @@ static const hash_entry hash_table[] = {
};
/* Get size from MD type */
unsigned char mbedtls_hash_info_get_size( mbedtls_md_type_t md_type )
unsigned char mbedtls_hash_info_get_size(mbedtls_md_type_t md_type)
{
const hash_entry *entry = hash_table;
while( entry->md_type != MBEDTLS_MD_NONE &&
entry->md_type != md_type )
{
while (entry->md_type != MBEDTLS_MD_NONE &&
entry->md_type != md_type) {
entry++;
}
@ -71,12 +69,11 @@ unsigned char mbedtls_hash_info_get_size( mbedtls_md_type_t md_type )
}
/* Get block size from MD type */
unsigned char mbedtls_hash_info_get_block_size( mbedtls_md_type_t md_type )
unsigned char mbedtls_hash_info_get_block_size(mbedtls_md_type_t md_type)
{
const hash_entry *entry = hash_table;
while( entry->md_type != MBEDTLS_MD_NONE &&
entry->md_type != md_type )
{
while (entry->md_type != MBEDTLS_MD_NONE &&
entry->md_type != md_type) {
entry++;
}
@ -84,12 +81,11 @@ unsigned char mbedtls_hash_info_get_block_size( mbedtls_md_type_t md_type )
}
/* Get PSA from MD */
psa_algorithm_t mbedtls_hash_info_psa_from_md( mbedtls_md_type_t md_type )
psa_algorithm_t mbedtls_hash_info_psa_from_md(mbedtls_md_type_t md_type)
{
const hash_entry *entry = hash_table;
while( entry->md_type != MBEDTLS_MD_NONE &&
entry->md_type != md_type )
{
while (entry->md_type != MBEDTLS_MD_NONE &&
entry->md_type != md_type) {
entry++;
}
@ -97,31 +93,29 @@ psa_algorithm_t mbedtls_hash_info_psa_from_md( mbedtls_md_type_t md_type )
}
/* Get MD from PSA */
mbedtls_md_type_t mbedtls_hash_info_md_from_psa( psa_algorithm_t psa_alg )
mbedtls_md_type_t mbedtls_hash_info_md_from_psa(psa_algorithm_t psa_alg)
{
const hash_entry *entry = hash_table;
while( entry->md_type != MBEDTLS_MD_NONE &&
entry->psa_alg != psa_alg )
{
while (entry->md_type != MBEDTLS_MD_NONE &&
entry->psa_alg != psa_alg) {
entry++;
}
return entry->md_type;
}
int mbedtls_md_error_from_psa( psa_status_t status )
int mbedtls_md_error_from_psa(psa_status_t status)
{
switch( status )
{
switch (status) {
case PSA_SUCCESS:
return( 0 );
return 0;
case PSA_ERROR_NOT_SUPPORTED:
return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE );
return MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE;
case PSA_ERROR_INVALID_ARGUMENT:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
case PSA_ERROR_INSUFFICIENT_MEMORY:
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
return MBEDTLS_ERR_MD_ALLOC_FAILED;
default:
return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
}
}

View File

@ -41,11 +41,11 @@
*/
#if defined(MBEDTLS_MD_C) && ( \
!defined(MBEDTLS_PSA_CRYPTO_C) || \
MBEDTLS_MD_MAX_SIZE >= PSA_HASH_MAX_SIZE )
MBEDTLS_MD_MAX_SIZE >= PSA_HASH_MAX_SIZE)
#define MBEDTLS_HASH_MAX_SIZE MBEDTLS_MD_MAX_SIZE
#elif defined(MBEDTLS_PSA_CRYPTO_C) && ( \
!defined(MBEDTLS_MD_C) || \
PSA_HASH_MAX_SIZE >= MBEDTLS_MD_MAX_SIZE )
PSA_HASH_MAX_SIZE >= MBEDTLS_MD_MAX_SIZE)
#define MBEDTLS_HASH_MAX_SIZE PSA_HASH_MAX_SIZE
#endif
@ -57,7 +57,7 @@
*
* \return The output length in bytes, or 0 if not known.
*/
unsigned char mbedtls_hash_info_get_size( mbedtls_md_type_t md_type );
unsigned char mbedtls_hash_info_get_size(mbedtls_md_type_t md_type);
/** Get the block size of the given hash type from its MD type.
*
@ -68,7 +68,7 @@ unsigned char mbedtls_hash_info_get_size( mbedtls_md_type_t md_type );
*
* \return The block size in bytes, or 0 if not known.
*/
unsigned char mbedtls_hash_info_get_block_size( mbedtls_md_type_t md_type );
unsigned char mbedtls_hash_info_get_block_size(mbedtls_md_type_t md_type);
/** Get the PSA alg from the MD type.
*
@ -77,7 +77,7 @@ unsigned char mbedtls_hash_info_get_block_size( mbedtls_md_type_t md_type );
* \return The corresponding PSA algorithm identifier,
* or PSA_ALG_NONE if not known.
*/
psa_algorithm_t mbedtls_hash_info_psa_from_md( mbedtls_md_type_t md_type );
psa_algorithm_t mbedtls_hash_info_psa_from_md(mbedtls_md_type_t md_type);
/** Get the MD type alg from the PSA algorithm identifier.
*
@ -86,7 +86,7 @@ psa_algorithm_t mbedtls_hash_info_psa_from_md( mbedtls_md_type_t md_type );
* \return The corresponding MD type,
* or MBEDTLS_MD_NONE if not known.
*/
mbedtls_md_type_t mbedtls_hash_info_md_from_psa( psa_algorithm_t psa_alg );
mbedtls_md_type_t mbedtls_hash_info_md_from_psa(psa_algorithm_t psa_alg);
/** Convert PSA status to MD error code.
*
@ -94,6 +94,6 @@ mbedtls_md_type_t mbedtls_hash_info_md_from_psa( psa_algorithm_t psa_alg );
*
* \return The corresponding MD error code,
*/
int mbedtls_md_error_from_psa( psa_status_t status );
int mbedtls_md_error_from_psa(psa_status_t status);
#endif /* MBEDTLS_HASH_INFO_H */

View File

@ -25,47 +25,43 @@
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,
size_t salt_len, const unsigned char *ikm, size_t ikm_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len )
int mbedtls_hkdf(const mbedtls_md_info_t *md, const unsigned char *salt,
size_t salt_len, const unsigned char *ikm, size_t ikm_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char prk[MBEDTLS_MD_MAX_SIZE];
ret = mbedtls_hkdf_extract( md, salt, salt_len, ikm, ikm_len, prk );
ret = mbedtls_hkdf_extract(md, salt, salt_len, ikm, ikm_len, prk);
if( ret == 0 )
{
ret = mbedtls_hkdf_expand( md, prk, mbedtls_md_get_size( md ),
info, info_len, okm, okm_len );
if (ret == 0) {
ret = mbedtls_hkdf_expand(md, prk, mbedtls_md_get_size(md),
info, info_len, okm, okm_len);
}
mbedtls_platform_zeroize( prk, sizeof( prk ) );
mbedtls_platform_zeroize(prk, sizeof(prk));
return( ret );
return ret;
}
int mbedtls_hkdf_extract( const mbedtls_md_info_t *md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk )
int mbedtls_hkdf_extract(const mbedtls_md_info_t *md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk)
{
unsigned char null_salt[MBEDTLS_MD_MAX_SIZE] = { '\0' };
if( salt == NULL )
{
if (salt == NULL) {
size_t hash_len;
if( salt_len != 0 )
{
if (salt_len != 0) {
return MBEDTLS_ERR_HKDF_BAD_INPUT_DATA;
}
hash_len = mbedtls_md_get_size( md );
hash_len = mbedtls_md_get_size(md);
if( hash_len == 0 )
{
if (hash_len == 0) {
return MBEDTLS_ERR_HKDF_BAD_INPUT_DATA;
}
@ -73,12 +69,12 @@ int mbedtls_hkdf_extract( const mbedtls_md_info_t *md,
salt_len = hash_len;
}
return( mbedtls_md_hmac( md, salt, salt_len, ikm, ikm_len, prk ) );
return mbedtls_md_hmac(md, salt, salt_len, ikm, ikm_len, prk);
}
int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
size_t prk_len, const unsigned char *info,
size_t info_len, unsigned char *okm, size_t okm_len )
int mbedtls_hkdf_expand(const mbedtls_md_info_t *md, const unsigned char *prk,
size_t prk_len, const unsigned char *info,
size_t info_len, unsigned char *okm, size_t okm_len)
{
size_t hash_len;
size_t where = 0;
@ -89,28 +85,24 @@ int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
mbedtls_md_context_t ctx;
unsigned char t[MBEDTLS_MD_MAX_SIZE];
if( okm == NULL )
{
return( MBEDTLS_ERR_HKDF_BAD_INPUT_DATA );
if (okm == NULL) {
return MBEDTLS_ERR_HKDF_BAD_INPUT_DATA;
}
hash_len = mbedtls_md_get_size( md );
hash_len = mbedtls_md_get_size(md);
if( prk_len < hash_len || hash_len == 0 )
{
return( MBEDTLS_ERR_HKDF_BAD_INPUT_DATA );
if (prk_len < hash_len || hash_len == 0) {
return MBEDTLS_ERR_HKDF_BAD_INPUT_DATA;
}
if( info == NULL )
{
if (info == NULL) {
info = (const unsigned char *) "";
info_len = 0;
}
n = okm_len / hash_len;
if( okm_len % hash_len != 0 )
{
if (okm_len % hash_len != 0) {
n++;
}
@ -118,72 +110,64 @@ int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
* Per RFC 5869 Section 2.3, okm_len must not exceed
* 255 times the hash length
*/
if( n > 255 )
{
return( MBEDTLS_ERR_HKDF_BAD_INPUT_DATA );
if (n > 255) {
return MBEDTLS_ERR_HKDF_BAD_INPUT_DATA;
}
mbedtls_md_init( &ctx );
mbedtls_md_init(&ctx);
if( ( ret = mbedtls_md_setup( &ctx, md, 1 ) ) != 0 )
{
if ((ret = mbedtls_md_setup(&ctx, md, 1)) != 0) {
goto exit;
}
memset( t, 0, hash_len );
memset(t, 0, hash_len);
/*
* Compute T = T(1) | T(2) | T(3) | ... | T(N)
* Where T(N) is defined in RFC 5869 Section 2.3
*/
for( i = 1; i <= n; i++ )
{
for (i = 1; i <= n; i++) {
size_t num_to_copy;
unsigned char c = i & 0xff;
ret = mbedtls_md_hmac_starts( &ctx, prk, prk_len );
if( ret != 0 )
{
ret = mbedtls_md_hmac_starts(&ctx, prk, prk_len);
if (ret != 0) {
goto exit;
}
ret = mbedtls_md_hmac_update( &ctx, t, t_len );
if( ret != 0 )
{
ret = mbedtls_md_hmac_update(&ctx, t, t_len);
if (ret != 0) {
goto exit;
}
ret = mbedtls_md_hmac_update( &ctx, info, info_len );
if( ret != 0 )
{
ret = mbedtls_md_hmac_update(&ctx, info, info_len);
if (ret != 0) {
goto exit;
}
/* The constant concatenated to the end of each T(n) is a single octet.
* */
ret = mbedtls_md_hmac_update( &ctx, &c, 1 );
if( ret != 0 )
{
ret = mbedtls_md_hmac_update(&ctx, &c, 1);
if (ret != 0) {
goto exit;
}
ret = mbedtls_md_hmac_finish( &ctx, t );
if( ret != 0 )
{
ret = mbedtls_md_hmac_finish(&ctx, t);
if (ret != 0) {
goto exit;
}
num_to_copy = i != n ? hash_len : okm_len - where;
memcpy( okm + where, t, num_to_copy );
memcpy(okm + where, t, num_to_copy);
where += hash_len;
t_len = hash_len;
}
exit:
mbedtls_md_free( &ctx );
mbedtls_platform_zeroize( t, sizeof( t ) );
mbedtls_md_free(&ctx);
mbedtls_platform_zeroize(t, sizeof(t));
return( ret );
return ret;
}
#endif /* MBEDTLS_HKDF_C */

View File

@ -42,9 +42,9 @@
/*
* HMAC_DRBG context initialization
*/
void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx )
void mbedtls_hmac_drbg_init(mbedtls_hmac_drbg_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_hmac_drbg_context ) );
memset(ctx, 0, sizeof(mbedtls_hmac_drbg_context));
ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;
}
@ -52,65 +52,72 @@ void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx )
/*
* HMAC_DRBG update, using optional additional data (10.1.2.2)
*/
int mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional,
size_t add_len )
int mbedtls_hmac_drbg_update(mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional,
size_t add_len)
{
size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info );
unsigned char rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1;
size_t md_len = mbedtls_md_get_size(ctx->md_ctx.md_info);
unsigned char rounds = (additional != NULL && add_len != 0) ? 2 : 1;
unsigned char sep[1];
unsigned char K[MBEDTLS_MD_MAX_SIZE];
int ret = MBEDTLS_ERR_MD_BAD_INPUT_DATA;
for( sep[0] = 0; sep[0] < rounds; sep[0]++ )
{
for (sep[0] = 0; sep[0] < rounds; sep[0]++) {
/* Step 1 or 4 */
if( ( ret = mbedtls_md_hmac_reset( &ctx->md_ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
ctx->V, md_len ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
sep, 1 ) ) != 0 )
goto exit;
if( rounds == 2 )
{
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
additional, add_len ) ) != 0 )
if ((ret = mbedtls_md_hmac_reset(&ctx->md_ctx)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, K ) ) != 0 )
if ((ret = mbedtls_md_hmac_update(&ctx->md_ctx,
ctx->V, md_len)) != 0) {
goto exit;
}
if ((ret = mbedtls_md_hmac_update(&ctx->md_ctx,
sep, 1)) != 0) {
goto exit;
}
if (rounds == 2) {
if ((ret = mbedtls_md_hmac_update(&ctx->md_ctx,
additional, add_len)) != 0) {
goto exit;
}
}
if ((ret = mbedtls_md_hmac_finish(&ctx->md_ctx, K)) != 0) {
goto exit;
}
/* Step 2 or 5 */
if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, K, md_len ) ) != 0 )
if ((ret = mbedtls_md_hmac_starts(&ctx->md_ctx, K, md_len)) != 0) {
goto exit;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
ctx->V, md_len ) ) != 0 )
}
if ((ret = mbedtls_md_hmac_update(&ctx->md_ctx,
ctx->V, md_len)) != 0) {
goto exit;
if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 )
}
if ((ret = mbedtls_md_hmac_finish(&ctx->md_ctx, ctx->V)) != 0) {
goto exit;
}
}
exit:
mbedtls_platform_zeroize( K, sizeof( K ) );
return( ret );
mbedtls_platform_zeroize(K, sizeof(K));
return ret;
}
/*
* Simplified HMAC_DRBG initialisation (for use with deterministic ECDSA)
*/
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 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;
if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )
return( ret );
if ((ret = mbedtls_md_setup(&ctx->md_ctx, md_info, 1)) != 0) {
return ret;
}
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &ctx->mutex );
mbedtls_mutex_init(&ctx->mutex);
#endif
/*
@ -118,15 +125,17 @@ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,
* Use the V memory location, which is currently all 0, to initialize the
* MD context with an all-zero key. Then set V to its initial value.
*/
if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V,
mbedtls_md_get_size( md_info ) ) ) != 0 )
return( ret );
memset( ctx->V, 0x01, mbedtls_md_get_size( md_info ) );
if ((ret = mbedtls_md_hmac_starts(&ctx->md_ctx, ctx->V,
mbedtls_md_get_size(md_info))) != 0) {
return ret;
}
memset(ctx->V, 0x01, mbedtls_md_get_size(md_info));
if( ( ret = mbedtls_hmac_drbg_update( ctx, data, data_len ) ) != 0 )
return( ret );
if ((ret = mbedtls_hmac_drbg_update(ctx, data, data_len)) != 0) {
return ret;
}
return( 0 );
return 0;
}
/*
@ -134,9 +143,9 @@ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,
* Comments starting with arabic numbers refer to section 10.1.2.4
* of SP800-90A, while roman numbers refer to section 9.2.
*/
static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t len,
int use_nonce )
static int hmac_drbg_reseed_core(mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t len,
int use_nonce)
{
unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT];
size_t seedlen = 0;
@ -145,33 +154,31 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
{
size_t total_entropy_len;
if( use_nonce == 0 )
if (use_nonce == 0) {
total_entropy_len = ctx->entropy_len;
else
} else {
total_entropy_len = ctx->entropy_len * 3 / 2;
}
/* III. Check input length */
if( len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||
total_entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT )
{
return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );
if (len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||
total_entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) {
return MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG;
}
}
memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT );
memset(seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT);
/* IV. Gather entropy_len bytes of entropy for the seed */
if( ( ret = ctx->f_entropy( ctx->p_entropy,
seed, ctx->entropy_len ) ) != 0 )
{
return( MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED );
if ((ret = ctx->f_entropy(ctx->p_entropy,
seed, ctx->entropy_len)) != 0) {
return MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED;
}
seedlen += ctx->entropy_len;
/* For initial seeding, allow adding of nonce generated
* from the entropy source. See Sect 8.6.7 in SP800-90A. */
if( use_nonce )
{
if (use_nonce) {
/* Note: We don't merge the two calls to f_entropy() in order
* to avoid requesting too much entropy from f_entropy()
* at once. Specifically, if the underlying digest is not
@ -179,11 +186,10 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
* is larger than the maximum of 32 Bytes that our own
* entropy source implementation can emit in a single
* call in configurations disabling SHA-512. */
if( ( ret = ctx->f_entropy( ctx->p_entropy,
seed + seedlen,
ctx->entropy_len / 2 ) ) != 0 )
{
return( MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED );
if ((ret = ctx->f_entropy(ctx->p_entropy,
seed + seedlen,
ctx->entropy_len / 2)) != 0) {
return MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED;
}
seedlen += ctx->entropy_len / 2;
@ -191,32 +197,32 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
/* 1. Concatenate entropy and additional data if any */
if( additional != NULL && len != 0 )
{
memcpy( seed + seedlen, additional, len );
if (additional != NULL && len != 0) {
memcpy(seed + seedlen, additional, len);
seedlen += len;
}
/* 2. Update state */
if( ( ret = mbedtls_hmac_drbg_update( ctx, seed, seedlen ) ) != 0 )
if ((ret = mbedtls_hmac_drbg_update(ctx, seed, seedlen)) != 0) {
goto exit;
}
/* 3. Reset reseed_counter */
ctx->reseed_counter = 1;
exit:
/* 4. Done */
mbedtls_platform_zeroize( seed, seedlen );
return( ret );
mbedtls_platform_zeroize(seed, seedlen);
return ret;
}
/*
* HMAC_DRBG reseeding: 10.1.2.4 + 9.2
*/
int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t len )
int mbedtls_hmac_drbg_reseed(mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t len)
{
return( hmac_drbg_reseed_core( ctx, additional, len, 0 ) );
return hmac_drbg_reseed_core(ctx, additional, len, 0);
}
/*
@ -225,40 +231,41 @@ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
* The nonce is not passed as a separate parameter but extracted
* from the entropy source as suggested in 8.6.7.
*/
int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
const mbedtls_md_info_t * md_info,
int (*f_entropy)(void *, unsigned char *, size_t),
void *p_entropy,
const unsigned char *custom,
size_t len )
int mbedtls_hmac_drbg_seed(mbedtls_hmac_drbg_context *ctx,
const mbedtls_md_info_t *md_info,
int (*f_entropy)(void *, unsigned char *, size_t),
void *p_entropy,
const unsigned char *custom,
size_t len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t md_size;
if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )
return( ret );
if ((ret = mbedtls_md_setup(&ctx->md_ctx, md_info, 1)) != 0) {
return ret;
}
/* The mutex is initialized iff the md context is set up. */
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &ctx->mutex );
mbedtls_mutex_init(&ctx->mutex);
#endif
md_size = mbedtls_md_get_size( md_info );
md_size = mbedtls_md_get_size(md_info);
/*
* Set initial working state.
* Use the V memory location, which is currently all 0, to initialize the
* MD context with an all-zero key. Then set V to its initial value.
*/
if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size ) ) != 0 )
return( ret );
memset( ctx->V, 0x01, md_size );
if ((ret = mbedtls_md_hmac_starts(&ctx->md_ctx, ctx->V, md_size)) != 0) {
return ret;
}
memset(ctx->V, 0x01, md_size);
ctx->f_entropy = f_entropy;
ctx->p_entropy = p_entropy;
if( ctx->entropy_len == 0 )
{
if (ctx->entropy_len == 0) {
/*
* See SP800-57 5.6.1 (p. 65-66) for the security strength provided by
* each hash function, then according to SP800-90A rev1 10.1 table 2,
@ -271,20 +278,19 @@ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
32; /* better (256+) -> 256 bits */
}
if( ( ret = hmac_drbg_reseed_core( ctx, custom, len,
1 /* add nonce */ ) ) != 0 )
{
return( ret );
if ((ret = hmac_drbg_reseed_core(ctx, custom, len,
1 /* add nonce */)) != 0) {
return ret;
}
return( 0 );
return 0;
}
/*
* Set prediction resistance
*/
void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx,
int resistance )
void mbedtls_hmac_drbg_set_prediction_resistance(mbedtls_hmac_drbg_context *ctx,
int resistance)
{
ctx->prediction_resistance = resistance;
}
@ -292,7 +298,7 @@ void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx
/*
* Set entropy length grabbed for seeding
*/
void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, size_t len )
void mbedtls_hmac_drbg_set_entropy_len(mbedtls_hmac_drbg_context *ctx, size_t len)
{
ctx->entropy_len = len;
}
@ -300,7 +306,7 @@ void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, size_t l
/*
* Set reseed interval
*/
void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx, int interval )
void mbedtls_hmac_drbg_set_reseed_interval(mbedtls_hmac_drbg_context *ctx, int interval)
{
ctx->reseed_interval = interval;
}
@ -309,134 +315,144 @@ void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx, int
* HMAC_DRBG random function with optional additional data:
* 10.1.2.5 (arabic) + 9.3 (Roman)
*/
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 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;
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 md_len = mbedtls_md_get_size(ctx->md_ctx.md_info);
size_t left = out_len;
unsigned char *out = output;
/* II. Check request length */
if( out_len > MBEDTLS_HMAC_DRBG_MAX_REQUEST )
return( MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG );
if (out_len > MBEDTLS_HMAC_DRBG_MAX_REQUEST) {
return MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG;
}
/* III. Check input length */
if( add_len > MBEDTLS_HMAC_DRBG_MAX_INPUT )
return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );
if (add_len > MBEDTLS_HMAC_DRBG_MAX_INPUT) {
return MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG;
}
/* 1. (aka VII and IX) Check reseed counter and PR */
if( ctx->f_entropy != NULL && /* For no-reseeding instances */
( ctx->prediction_resistance == MBEDTLS_HMAC_DRBG_PR_ON ||
ctx->reseed_counter > ctx->reseed_interval ) )
{
if( ( ret = mbedtls_hmac_drbg_reseed( ctx, additional, add_len ) ) != 0 )
return( ret );
if (ctx->f_entropy != NULL && /* For no-reseeding instances */
(ctx->prediction_resistance == MBEDTLS_HMAC_DRBG_PR_ON ||
ctx->reseed_counter > ctx->reseed_interval)) {
if ((ret = mbedtls_hmac_drbg_reseed(ctx, additional, add_len)) != 0) {
return ret;
}
add_len = 0; /* VII.4 */
}
/* 2. Use additional data if any */
if( additional != NULL && add_len != 0 )
{
if( ( ret = mbedtls_hmac_drbg_update( ctx,
additional, add_len ) ) != 0 )
if (additional != NULL && add_len != 0) {
if ((ret = mbedtls_hmac_drbg_update(ctx,
additional, add_len)) != 0) {
goto exit;
}
}
/* 3, 4, 5. Generate bytes */
while( left != 0 )
{
while (left != 0) {
size_t use_len = left > md_len ? md_len : left;
if( ( ret = mbedtls_md_hmac_reset( &ctx->md_ctx ) ) != 0 )
if ((ret = mbedtls_md_hmac_reset(&ctx->md_ctx)) != 0) {
goto exit;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
ctx->V, md_len ) ) != 0 )
}
if ((ret = mbedtls_md_hmac_update(&ctx->md_ctx,
ctx->V, md_len)) != 0) {
goto exit;
if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 )
}
if ((ret = mbedtls_md_hmac_finish(&ctx->md_ctx, ctx->V)) != 0) {
goto exit;
}
memcpy( out, ctx->V, use_len );
memcpy(out, ctx->V, use_len);
out += use_len;
left -= use_len;
}
/* 6. Update */
if( ( ret = mbedtls_hmac_drbg_update( ctx,
additional, add_len ) ) != 0 )
if ((ret = mbedtls_hmac_drbg_update(ctx,
additional, add_len)) != 0) {
goto exit;
}
/* 7. Update reseed counter */
ctx->reseed_counter++;
exit:
/* 8. Done */
return( ret );
return ret;
}
/*
* HMAC_DRBG random function
*/
int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len )
int mbedtls_hmac_drbg_random(void *p_rng, unsigned char *output, size_t out_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
return ret;
}
#endif
ret = mbedtls_hmac_drbg_random_with_add( ctx, output, out_len, NULL, 0 );
ret = mbedtls_hmac_drbg_random_with_add(ctx, output, out_len, NULL, 0);
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
}
#endif
return( ret );
return ret;
}
/*
* This function resets HMAC_DRBG context to the state immediately
* after initial call of mbedtls_hmac_drbg_init().
*/
void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx )
void mbedtls_hmac_drbg_free(mbedtls_hmac_drbg_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
#if defined(MBEDTLS_THREADING_C)
/* The mutex is initialized iff the md context is set up. */
if( ctx->md_ctx.md_info != NULL )
mbedtls_mutex_free( &ctx->mutex );
if (ctx->md_ctx.md_info != NULL) {
mbedtls_mutex_free(&ctx->mutex);
}
#endif
mbedtls_md_free( &ctx->md_ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_hmac_drbg_context ) );
mbedtls_md_free(&ctx->md_ctx);
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_hmac_drbg_context));
ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;
}
#if defined(MBEDTLS_FS_IO)
int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )
int mbedtls_hmac_drbg_write_seed_file(mbedtls_hmac_drbg_context *ctx, const char *path)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
FILE *f;
unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];
unsigned char buf[MBEDTLS_HMAC_DRBG_MAX_INPUT];
if( ( f = fopen( path, "wb" ) ) == NULL )
return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR );
if ((f = fopen(path, "wb")) == NULL) {
return MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;
}
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( f, NULL );
mbedtls_setbuf(f, NULL);
if( ( ret = mbedtls_hmac_drbg_random( ctx, buf, sizeof( buf ) ) ) != 0 )
if ((ret = mbedtls_hmac_drbg_random(ctx, buf, sizeof(buf))) != 0) {
goto exit;
}
if( fwrite( buf, 1, sizeof( buf ), f ) != sizeof( buf ) )
{
if (fwrite(buf, 1, sizeof(buf), f) != sizeof(buf)) {
ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;
goto exit;
}
@ -444,49 +460,50 @@ int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const cha
ret = 0;
exit:
fclose( f );
mbedtls_platform_zeroize( buf, sizeof( buf ) );
fclose(f);
mbedtls_platform_zeroize(buf, sizeof(buf));
return( ret );
return ret;
}
int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )
int mbedtls_hmac_drbg_update_seed_file(mbedtls_hmac_drbg_context *ctx, const char *path)
{
int ret = 0;
FILE *f = NULL;
size_t n;
unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];
unsigned char buf[MBEDTLS_HMAC_DRBG_MAX_INPUT];
unsigned char c;
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR );
if ((f = fopen(path, "rb")) == NULL) {
return MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;
}
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( f, NULL );
mbedtls_setbuf(f, NULL);
n = fread( buf, 1, sizeof( buf ), f );
if( fread( &c, 1, 1, f ) != 0 )
{
n = fread(buf, 1, sizeof(buf), f);
if (fread(&c, 1, 1, f) != 0) {
ret = MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG;
goto exit;
}
if( n == 0 || ferror( f ) )
{
if (n == 0 || ferror(f)) {
ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;
goto exit;
}
fclose( f );
fclose(f);
f = NULL;
ret = mbedtls_hmac_drbg_update( ctx, buf, n );
ret = mbedtls_hmac_drbg_update(ctx, buf, n);
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
if( f != NULL )
fclose( f );
if( ret != 0 )
return( ret );
return( mbedtls_hmac_drbg_write_seed_file( ctx, path ) );
mbedtls_platform_zeroize(buf, sizeof(buf));
if (f != NULL) {
fclose(f);
}
if (ret != 0) {
return ret;
}
return mbedtls_hmac_drbg_write_seed_file(ctx, path);
}
#endif /* MBEDTLS_FS_IO */
@ -495,10 +512,10 @@ exit:
#if !defined(MBEDTLS_SHA1_C)
/* Dummy checkup routine */
int mbedtls_hmac_drbg_self_test( int verbose )
int mbedtls_hmac_drbg_self_test(int verbose)
{
(void) verbose;
return( 0 );
return 0;
}
#else
@ -510,7 +527,8 @@ static const unsigned char entropy_pr[] = {
0xf7, 0x3e, 0x9c, 0x5b, 0x64, 0xef, 0xd8, 0xca, 0x02, 0x8c, 0xf8, 0x11,
0x48, 0xa5, 0x84, 0xfe, 0x69, 0xab, 0x5a, 0xee, 0x42, 0xaa, 0x4d, 0x42,
0x17, 0x60, 0x99, 0xd4, 0x5e, 0x13, 0x97, 0xdc, 0x40, 0x4d, 0x86, 0xa3,
0x7b, 0xf5, 0x59, 0x54, 0x75, 0x69, 0x51, 0xe4 };
0x7b, 0xf5, 0x59, 0x54, 0x75, 0x69, 0x51, 0xe4
};
static const unsigned char result_pr[OUTPUT_LEN] = {
0x9a, 0x00, 0xa2, 0xd0, 0x0e, 0xd5, 0x9b, 0xfe, 0x31, 0xec, 0xb1, 0x39,
0x9b, 0x60, 0x81, 0x48, 0xd1, 0x96, 0x9d, 0x25, 0x0d, 0x3c, 0x1e, 0x94,
@ -518,14 +536,16 @@ static const unsigned char result_pr[OUTPUT_LEN] = {
0x73, 0x19, 0x70, 0xc0, 0x10, 0x7a, 0xa4, 0x89, 0x25, 0x19, 0x95, 0x5e,
0x4b, 0xc6, 0x00, 0x1d, 0x7f, 0x4e, 0x6a, 0x2b, 0xf8, 0xa3, 0x01, 0xab,
0x46, 0x05, 0x5c, 0x09, 0xa6, 0x71, 0x88, 0xf1, 0xa7, 0x40, 0xee, 0xf3,
0xe1, 0x5c, 0x02, 0x9b, 0x44, 0xaf, 0x03, 0x44 };
0xe1, 0x5c, 0x02, 0x9b, 0x44, 0xaf, 0x03, 0x44
};
/* From a NIST PR=false test vector */
static const unsigned char entropy_nopr[] = {
0x79, 0x34, 0x9b, 0xbf, 0x7c, 0xdd, 0xa5, 0x79, 0x95, 0x57, 0x86, 0x66,
0x21, 0xc9, 0x13, 0x83, 0x11, 0x46, 0x73, 0x3a, 0xbf, 0x8c, 0x35, 0xc8,
0xc7, 0x21, 0x5b, 0x5b, 0x96, 0xc4, 0x8e, 0x9b, 0x33, 0x8c, 0x74, 0xe3,
0xe9, 0x9d, 0xfe, 0xdf };
0xe9, 0x9d, 0xfe, 0xdf
};
static const unsigned char result_nopr[OUTPUT_LEN] = {
0xc6, 0xa1, 0x6a, 0xb8, 0xd4, 0x20, 0x70, 0x6f, 0x0f, 0x34, 0xab, 0x7f,
0xec, 0x5a, 0xdc, 0xa9, 0xd8, 0xca, 0x3a, 0x13, 0x3e, 0x15, 0x9c, 0xa6,
@ -533,85 +553,91 @@ static const unsigned char result_nopr[OUTPUT_LEN] = {
0xff, 0xb1, 0x0d, 0x71, 0x94, 0xf1, 0xc1, 0xa5, 0xcf, 0x73, 0x22, 0xec,
0x1a, 0xe0, 0x96, 0x4e, 0xd4, 0xbf, 0x12, 0x27, 0x46, 0xe0, 0x87, 0xfd,
0xb5, 0xb3, 0xe9, 0x1b, 0x34, 0x93, 0xd5, 0xbb, 0x98, 0xfa, 0xed, 0x49,
0xe8, 0x5f, 0x13, 0x0f, 0xc8, 0xa4, 0x59, 0xb7 };
0xe8, 0x5f, 0x13, 0x0f, 0xc8, 0xa4, 0x59, 0xb7
};
/* "Entropy" from buffer */
static size_t test_offset;
static int hmac_drbg_self_test_entropy( void *data,
unsigned char *buf, size_t len )
static int hmac_drbg_self_test_entropy(void *data,
unsigned char *buf, size_t len)
{
const unsigned char *p = data;
memcpy( buf, p + test_offset, len );
memcpy(buf, p + test_offset, len);
test_offset += len;
return( 0 );
return 0;
}
#define CHK( c ) if( (c) != 0 ) \
{ \
if( verbose != 0 ) \
mbedtls_printf( "failed\n" ); \
return( 1 ); \
}
#define CHK(c) if ((c) != 0) \
{ \
if (verbose != 0) \
mbedtls_printf("failed\n"); \
return 1; \
}
/*
* Checkup routine for HMAC_DRBG with SHA-1
*/
int mbedtls_hmac_drbg_self_test( int verbose )
int mbedtls_hmac_drbg_self_test(int verbose)
{
mbedtls_hmac_drbg_context ctx;
unsigned char buf[OUTPUT_LEN];
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
mbedtls_hmac_drbg_init( &ctx );
mbedtls_hmac_drbg_init(&ctx);
/*
* PR = True
*/
if( verbose != 0 )
mbedtls_printf( " HMAC_DRBG (PR = True) : " );
if (verbose != 0) {
mbedtls_printf(" HMAC_DRBG (PR = True) : ");
}
test_offset = 0;
CHK( mbedtls_hmac_drbg_seed( &ctx, md_info,
hmac_drbg_self_test_entropy, (void *) entropy_pr,
NULL, 0 ) );
mbedtls_hmac_drbg_set_prediction_resistance( &ctx, MBEDTLS_HMAC_DRBG_PR_ON );
CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );
CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );
CHK( memcmp( buf, result_pr, OUTPUT_LEN ) );
mbedtls_hmac_drbg_free( &ctx );
CHK(mbedtls_hmac_drbg_seed(&ctx, md_info,
hmac_drbg_self_test_entropy, (void *) entropy_pr,
NULL, 0));
mbedtls_hmac_drbg_set_prediction_resistance(&ctx, MBEDTLS_HMAC_DRBG_PR_ON);
CHK(mbedtls_hmac_drbg_random(&ctx, buf, OUTPUT_LEN));
CHK(mbedtls_hmac_drbg_random(&ctx, buf, OUTPUT_LEN));
CHK(memcmp(buf, result_pr, OUTPUT_LEN));
mbedtls_hmac_drbg_free(&ctx);
mbedtls_hmac_drbg_free( &ctx );
mbedtls_hmac_drbg_free(&ctx);
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
/*
* PR = False
*/
if( verbose != 0 )
mbedtls_printf( " HMAC_DRBG (PR = False) : " );
if (verbose != 0) {
mbedtls_printf(" HMAC_DRBG (PR = False) : ");
}
mbedtls_hmac_drbg_init( &ctx );
mbedtls_hmac_drbg_init(&ctx);
test_offset = 0;
CHK( mbedtls_hmac_drbg_seed( &ctx, md_info,
hmac_drbg_self_test_entropy, (void *) entropy_nopr,
NULL, 0 ) );
CHK( mbedtls_hmac_drbg_reseed( &ctx, NULL, 0 ) );
CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );
CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );
CHK( memcmp( buf, result_nopr, OUTPUT_LEN ) );
mbedtls_hmac_drbg_free( &ctx );
CHK(mbedtls_hmac_drbg_seed(&ctx, md_info,
hmac_drbg_self_test_entropy, (void *) entropy_nopr,
NULL, 0));
CHK(mbedtls_hmac_drbg_reseed(&ctx, NULL, 0));
CHK(mbedtls_hmac_drbg_random(&ctx, buf, OUTPUT_LEN));
CHK(mbedtls_hmac_drbg_random(&ctx, buf, OUTPUT_LEN));
CHK(memcmp(buf, result_nopr, OUTPUT_LEN));
mbedtls_hmac_drbg_free(&ctx);
mbedtls_hmac_drbg_free( &ctx );
mbedtls_hmac_drbg_free(&ctx);
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_SELF_TEST */

File diff suppressed because it is too large Load Diff

View File

@ -53,7 +53,7 @@ extern "C" {
#if defined(MBEDTLS_TEST_HOOKS)
extern int( *mbedtls_lmots_sign_private_key_invalidated_hook )( unsigned char * );
extern int (*mbedtls_lmots_sign_private_key_invalidated_hook)(unsigned char *);
#endif /* defined(MBEDTLS_TEST_HOOKS) */
/**
@ -64,8 +64,8 @@ extern int( *mbedtls_lmots_sign_private_key_invalidated_hook )( unsigned char *
* \param len The length of the string.
* \param bytes The string to output into.
*/
void mbedtls_lms_unsigned_int_to_network_bytes( unsigned int val, size_t len,
unsigned char *bytes );
void mbedtls_lms_unsigned_int_to_network_bytes(unsigned int val, size_t len,
unsigned char *bytes);
/**
* \brief This function converts a network-byte-order
@ -76,8 +76,8 @@ void mbedtls_lms_unsigned_int_to_network_bytes( unsigned int val, size_t len,
*
* \return The corresponding LMS error code.
*/
unsigned int mbedtls_lms_network_bytes_to_unsigned_int( size_t len,
const unsigned char *bytes );
unsigned int mbedtls_lms_network_bytes_to_unsigned_int(size_t len,
const unsigned char *bytes);
/**
* \brief This function converts a \ref psa_status_t to a
@ -87,7 +87,7 @@ unsigned int mbedtls_lms_network_bytes_to_unsigned_int( size_t len,
*
* \return The corresponding LMS error code.
*/
int mbedtls_lms_error_from_psa( psa_status_t status );
int mbedtls_lms_error_from_psa(psa_status_t status);
/**
@ -96,7 +96,7 @@ int mbedtls_lms_error_from_psa( psa_status_t status );
* \param ctx The uninitialized LMOTS context that will then be
* initialized.
*/
void mbedtls_lmots_public_init( mbedtls_lmots_public_t *ctx );
void mbedtls_lmots_public_init(mbedtls_lmots_public_t *ctx);
/**
* \brief This function uninitializes a public LMOTS context
@ -104,7 +104,7 @@ void mbedtls_lmots_public_init( mbedtls_lmots_public_t *ctx );
* \param ctx The initialized LMOTS context that will then be
* uninitialized.
*/
void mbedtls_lmots_public_free( mbedtls_lmots_public_t *ctx );
void mbedtls_lmots_public_free(mbedtls_lmots_public_t *ctx);
/**
* \brief This function imports an LMOTS public key into a
@ -124,8 +124,8 @@ void mbedtls_lmots_public_free( mbedtls_lmots_public_t *ctx );
* \return \c 0 on success.
* \return A non-zero error code on failure.
*/
int mbedtls_lmots_import_public_key( mbedtls_lmots_public_t *ctx,
const unsigned char *key, size_t key_size );
int mbedtls_lmots_import_public_key(mbedtls_lmots_public_t *ctx,
const unsigned char *key, size_t key_size);
/**
* \brief This function exports an LMOTS public key from a
@ -146,9 +146,9 @@ int mbedtls_lmots_import_public_key( mbedtls_lmots_public_t *ctx,
* \return \c 0 on success.
* \return A non-zero error code on failure.
*/
int mbedtls_lmots_export_public_key( const mbedtls_lmots_public_t *ctx,
unsigned char *key, size_t key_size,
size_t *key_len );
int mbedtls_lmots_export_public_key(const mbedtls_lmots_public_t *ctx,
unsigned char *key, size_t key_size,
size_t *key_len);
/**
* \brief This function creates a candidate public key from
@ -175,14 +175,14 @@ int mbedtls_lmots_export_public_key( const mbedtls_lmots_public_t *ctx,
* \return \c 0 on success.
* \return A non-zero error code on failure.
*/
int mbedtls_lmots_calculate_public_key_candidate( const mbedtls_lmots_parameters_t *params,
const unsigned char *msg,
size_t msg_size,
const unsigned char *sig,
size_t sig_size,
unsigned char *out,
size_t out_size,
size_t *out_len );
int mbedtls_lmots_calculate_public_key_candidate(const mbedtls_lmots_parameters_t *params,
const unsigned char *msg,
size_t msg_size,
const unsigned char *sig,
size_t sig_size,
unsigned char *out,
size_t out_size,
size_t *out_len);
/**
* \brief This function verifies a LMOTS signature, using a
@ -209,10 +209,10 @@ int mbedtls_lmots_calculate_public_key_candidate( const mbedtls_lmots_parameters
* \return \c 0 on successful verification.
* \return A non-zero error code on failure.
*/
int mbedtls_lmots_verify( const mbedtls_lmots_public_t *ctx,
const unsigned char *msg,
size_t msg_size, const unsigned char *sig,
size_t sig_size );
int mbedtls_lmots_verify(const mbedtls_lmots_public_t *ctx,
const unsigned char *msg,
size_t msg_size, const unsigned char *sig,
size_t sig_size);
#if defined(MBEDTLS_LMS_PRIVATE)
@ -222,7 +222,7 @@ int mbedtls_lmots_verify( const mbedtls_lmots_public_t *ctx,
* \param ctx The uninitialized LMOTS context that will then be
* initialized.
*/
void mbedtls_lmots_private_init( mbedtls_lmots_private_t *ctx );
void mbedtls_lmots_private_init(mbedtls_lmots_private_t *ctx);
/**
* \brief This function uninitializes a private LMOTS context
@ -230,7 +230,7 @@ void mbedtls_lmots_private_init( mbedtls_lmots_private_t *ctx );
* \param ctx The initialized LMOTS context that will then be
* uninitialized.
*/
void mbedtls_lmots_private_free( mbedtls_lmots_private_t *ctx );
void mbedtls_lmots_private_free(mbedtls_lmots_private_t *ctx);
/**
* \brief This function calculates an LMOTS private key, and
@ -256,12 +256,12 @@ void mbedtls_lmots_private_free( mbedtls_lmots_private_t *ctx );
* \return \c 0 on success.
* \return A non-zero error code on failure.
*/
int mbedtls_lmots_generate_private_key( mbedtls_lmots_private_t *ctx,
mbedtls_lmots_algorithm_type_t type,
const unsigned char I_key_identifier[MBEDTLS_LMOTS_I_KEY_ID_LEN],
uint32_t q_leaf_identifier,
const unsigned char *seed,
size_t seed_size );
int mbedtls_lmots_generate_private_key(mbedtls_lmots_private_t *ctx,
mbedtls_lmots_algorithm_type_t type,
const unsigned char I_key_identifier[MBEDTLS_LMOTS_I_KEY_ID_LEN],
uint32_t q_leaf_identifier,
const unsigned char *seed,
size_t seed_size);
/**
* \brief This function generates an LMOTS public key from a
@ -277,8 +277,8 @@ int mbedtls_lmots_generate_private_key( mbedtls_lmots_private_t *ctx,
* \return \c 0 on success.
* \return A non-zero error code on failure.
*/
int mbedtls_lmots_calculate_public_key( mbedtls_lmots_public_t *ctx,
const mbedtls_lmots_private_t *priv_ctx );
int mbedtls_lmots_calculate_public_key(mbedtls_lmots_public_t *ctx,
const mbedtls_lmots_private_t *priv_ctx);
/**
* \brief This function creates a LMOTS signature, using a
@ -308,10 +308,10 @@ int mbedtls_lmots_calculate_public_key( mbedtls_lmots_public_t *ctx,
* \return \c 0 on success.
* \return A non-zero error code on failure.
*/
int mbedtls_lmots_sign( mbedtls_lmots_private_t *ctx,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, const unsigned char *msg, size_t msg_size,
unsigned char *sig, size_t sig_size, size_t* sig_len );
int mbedtls_lmots_sign(mbedtls_lmots_private_t *ctx,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, const unsigned char *msg, size_t msg_size,
unsigned char *sig, size_t sig_size, size_t *sig_len);
#endif /* defined(MBEDTLS_LMS_PRIVATE) */

File diff suppressed because it is too large Load Diff

View File

@ -113,479 +113,481 @@ const mbedtls_md_info_t mbedtls_sha512_info = {
static const int supported_digests[] = {
#if defined(MBEDTLS_SHA512_C)
MBEDTLS_MD_SHA512,
MBEDTLS_MD_SHA512,
#endif
#if defined(MBEDTLS_SHA384_C)
MBEDTLS_MD_SHA384,
MBEDTLS_MD_SHA384,
#endif
#if defined(MBEDTLS_SHA256_C)
MBEDTLS_MD_SHA256,
MBEDTLS_MD_SHA256,
#endif
#if defined(MBEDTLS_SHA224_C)
MBEDTLS_MD_SHA224,
MBEDTLS_MD_SHA224,
#endif
#if defined(MBEDTLS_SHA1_C)
MBEDTLS_MD_SHA1,
MBEDTLS_MD_SHA1,
#endif
#if defined(MBEDTLS_RIPEMD160_C)
MBEDTLS_MD_RIPEMD160,
MBEDTLS_MD_RIPEMD160,
#endif
#if defined(MBEDTLS_MD5_C)
MBEDTLS_MD_MD5,
MBEDTLS_MD_MD5,
#endif
MBEDTLS_MD_NONE
MBEDTLS_MD_NONE
};
const int *mbedtls_md_list( void )
const int *mbedtls_md_list(void)
{
return( supported_digests );
return supported_digests;
}
const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name )
const mbedtls_md_info_t *mbedtls_md_info_from_string(const char *md_name)
{
if( NULL == md_name )
return( NULL );
if (NULL == md_name) {
return NULL;
}
/* Get the appropriate digest information */
#if defined(MBEDTLS_MD5_C)
if( !strcmp( "MD5", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_MD5 );
if (!strcmp("MD5", md_name)) {
return mbedtls_md_info_from_type(MBEDTLS_MD_MD5);
}
#endif
#if defined(MBEDTLS_RIPEMD160_C)
if( !strcmp( "RIPEMD160", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_RIPEMD160 );
if (!strcmp("RIPEMD160", md_name)) {
return mbedtls_md_info_from_type(MBEDTLS_MD_RIPEMD160);
}
#endif
#if defined(MBEDTLS_SHA1_C)
if( !strcmp( "SHA1", md_name ) || !strcmp( "SHA", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );
if (!strcmp("SHA1", md_name) || !strcmp("SHA", md_name)) {
return mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
}
#endif
#if defined(MBEDTLS_SHA224_C)
if( !strcmp( "SHA224", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA224 );
if (!strcmp("SHA224", md_name)) {
return mbedtls_md_info_from_type(MBEDTLS_MD_SHA224);
}
#endif
#if defined(MBEDTLS_SHA256_C)
if( !strcmp( "SHA256", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 );
if (!strcmp("SHA256", md_name)) {
return mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
}
#endif
#if defined(MBEDTLS_SHA384_C)
if( !strcmp( "SHA384", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA384 );
if (!strcmp("SHA384", md_name)) {
return mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
}
#endif
#if defined(MBEDTLS_SHA512_C)
if( !strcmp( "SHA512", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA512 );
if (!strcmp("SHA512", md_name)) {
return mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
}
#endif
return( NULL );
return NULL;
}
const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type )
const mbedtls_md_info_t *mbedtls_md_info_from_type(mbedtls_md_type_t md_type)
{
switch( md_type )
{
switch (md_type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( &mbedtls_md5_info );
return &mbedtls_md5_info;
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
return( &mbedtls_ripemd160_info );
return &mbedtls_ripemd160_info;
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( &mbedtls_sha1_info );
return &mbedtls_sha1_info;
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
return( &mbedtls_sha224_info );
return &mbedtls_sha224_info;
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
return( &mbedtls_sha256_info );
return &mbedtls_sha256_info;
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
return( &mbedtls_sha384_info );
return &mbedtls_sha384_info;
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
return( &mbedtls_sha512_info );
return &mbedtls_sha512_info;
#endif
default:
return( NULL );
return NULL;
}
}
const mbedtls_md_info_t *mbedtls_md_info_from_ctx(
const mbedtls_md_context_t *ctx )
const mbedtls_md_context_t *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return NULL;
}
return( ctx->MBEDTLS_PRIVATE(md_info) );
return ctx->MBEDTLS_PRIVATE(md_info);
}
void mbedtls_md_init( mbedtls_md_context_t *ctx )
void mbedtls_md_init(mbedtls_md_context_t *ctx)
{
memset( ctx, 0, sizeof( mbedtls_md_context_t ) );
memset(ctx, 0, sizeof(mbedtls_md_context_t));
}
void mbedtls_md_free( mbedtls_md_context_t *ctx )
void mbedtls_md_free(mbedtls_md_context_t *ctx)
{
if( ctx == NULL || ctx->md_info == NULL )
if (ctx == NULL || ctx->md_info == NULL) {
return;
}
if( ctx->md_ctx != NULL )
{
switch( ctx->md_info->type )
{
if (ctx->md_ctx != NULL) {
switch (ctx->md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
mbedtls_md5_free( ctx->md_ctx );
mbedtls_md5_free(ctx->md_ctx);
break;
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
mbedtls_ripemd160_free( ctx->md_ctx );
mbedtls_ripemd160_free(ctx->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
mbedtls_sha1_free( ctx->md_ctx );
mbedtls_sha1_free(ctx->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
mbedtls_sha256_free( ctx->md_ctx );
mbedtls_sha256_free(ctx->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
mbedtls_sha256_free( ctx->md_ctx );
mbedtls_sha256_free(ctx->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
mbedtls_sha512_free( ctx->md_ctx );
mbedtls_sha512_free(ctx->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
mbedtls_sha512_free( ctx->md_ctx );
mbedtls_sha512_free(ctx->md_ctx);
break;
#endif
default:
/* Shouldn't happen */
break;
}
mbedtls_free( ctx->md_ctx );
mbedtls_free(ctx->md_ctx);
}
if( ctx->hmac_ctx != NULL )
{
mbedtls_platform_zeroize( ctx->hmac_ctx,
2 * ctx->md_info->block_size );
mbedtls_free( ctx->hmac_ctx );
if (ctx->hmac_ctx != NULL) {
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 ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_md_context_t));
}
int mbedtls_md_clone( mbedtls_md_context_t *dst,
const mbedtls_md_context_t *src )
int mbedtls_md_clone(mbedtls_md_context_t *dst,
const mbedtls_md_context_t *src)
{
if( dst == NULL || dst->md_info == NULL ||
if (dst == NULL || dst->md_info == NULL ||
src == NULL || src->md_info == NULL ||
dst->md_info != src->md_info )
{
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
dst->md_info != src->md_info) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
switch( src->md_info->type )
{
switch (src->md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
mbedtls_md5_clone( dst->md_ctx, src->md_ctx );
mbedtls_md5_clone(dst->md_ctx, src->md_ctx);
break;
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
mbedtls_ripemd160_clone( dst->md_ctx, src->md_ctx );
mbedtls_ripemd160_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 );
mbedtls_sha1_clone(dst->md_ctx, src->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
mbedtls_sha256_clone( dst->md_ctx, src->md_ctx );
mbedtls_sha256_clone(dst->md_ctx, src->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
mbedtls_sha256_clone( dst->md_ctx, src->md_ctx );
mbedtls_sha256_clone(dst->md_ctx, src->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
mbedtls_sha512_clone( dst->md_ctx, src->md_ctx );
mbedtls_sha512_clone(dst->md_ctx, src->md_ctx);
break;
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
mbedtls_sha512_clone( dst->md_ctx, src->md_ctx );
mbedtls_sha512_clone(dst->md_ctx, src->md_ctx);
break;
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
return( 0 );
return 0;
}
#define ALLOC( type ) \
#define ALLOC(type) \
do { \
ctx->md_ctx = mbedtls_calloc( 1, sizeof( mbedtls_##type##_context ) ); \
if( ctx->md_ctx == NULL ) \
return( MBEDTLS_ERR_MD_ALLOC_FAILED ); \
mbedtls_##type##_init( ctx->md_ctx ); \
ctx->md_ctx = mbedtls_calloc(1, sizeof(mbedtls_##type##_context)); \
if (ctx->md_ctx == NULL) \
return MBEDTLS_ERR_MD_ALLOC_FAILED; \
mbedtls_##type##_init(ctx->md_ctx); \
} \
while( 0 )
while (0)
int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac )
int mbedtls_md_setup(mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac)
{
if( md_info == NULL || ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if (md_info == NULL || ctx == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
ctx->md_info = md_info;
ctx->md_ctx = NULL;
ctx->hmac_ctx = NULL;
switch( md_info->type )
{
switch (md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
ALLOC( md5 );
ALLOC(md5);
break;
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
ALLOC( ripemd160 );
ALLOC(ripemd160);
break;
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
ALLOC( sha1 );
ALLOC(sha1);
break;
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
ALLOC( sha256 );
ALLOC(sha256);
break;
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
ALLOC( sha256 );
ALLOC(sha256);
break;
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
ALLOC( sha512 );
ALLOC(sha512);
break;
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
ALLOC( sha512 );
ALLOC(sha512);
break;
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
if( hmac != 0 )
{
ctx->hmac_ctx = mbedtls_calloc( 2, md_info->block_size );
if( ctx->hmac_ctx == NULL )
{
mbedtls_md_free( ctx );
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
if (hmac != 0) {
ctx->hmac_ctx = mbedtls_calloc(2, md_info->block_size);
if (ctx->hmac_ctx == NULL) {
mbedtls_md_free(ctx);
return MBEDTLS_ERR_MD_ALLOC_FAILED;
}
}
return( 0 );
return 0;
}
#undef ALLOC
int mbedtls_md_starts( mbedtls_md_context_t *ctx )
int mbedtls_md_starts(mbedtls_md_context_t *ctx)
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if (ctx == NULL || ctx->md_info == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
switch( ctx->md_info->type )
{
switch (ctx->md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5_starts( ctx->md_ctx ) );
return mbedtls_md5_starts(ctx->md_ctx);
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
return( mbedtls_ripemd160_starts( ctx->md_ctx ) );
return mbedtls_ripemd160_starts(ctx->md_ctx);
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1_starts( ctx->md_ctx ) );
return mbedtls_sha1_starts(ctx->md_ctx);
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
return( mbedtls_sha256_starts( ctx->md_ctx, 1 ) );
return mbedtls_sha256_starts(ctx->md_ctx, 1);
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256_starts( ctx->md_ctx, 0 ) );
return mbedtls_sha256_starts(ctx->md_ctx, 0);
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
return( mbedtls_sha512_starts( ctx->md_ctx, 1 ) );
return mbedtls_sha512_starts(ctx->md_ctx, 1);
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512_starts( ctx->md_ctx, 0 ) );
return mbedtls_sha512_starts(ctx->md_ctx, 0);
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
}
int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )
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 );
if (ctx == NULL || ctx->md_info == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
switch( ctx->md_info->type )
{
switch (ctx->md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5_update( ctx->md_ctx, input, ilen ) );
return mbedtls_md5_update(ctx->md_ctx, input, ilen);
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
return( mbedtls_ripemd160_update( ctx->md_ctx, input, ilen ) );
return mbedtls_ripemd160_update(ctx->md_ctx, input, ilen);
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1_update( ctx->md_ctx, input, ilen ) );
return mbedtls_sha1_update(ctx->md_ctx, input, ilen);
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
return( mbedtls_sha256_update( ctx->md_ctx, input, ilen ) );
return mbedtls_sha256_update(ctx->md_ctx, input, ilen);
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256_update( ctx->md_ctx, input, ilen ) );
return mbedtls_sha256_update(ctx->md_ctx, input, ilen);
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
return( mbedtls_sha512_update( ctx->md_ctx, input, ilen ) );
return mbedtls_sha512_update(ctx->md_ctx, input, ilen);
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512_update( ctx->md_ctx, input, ilen ) );
return mbedtls_sha512_update(ctx->md_ctx, input, ilen);
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
}
int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output )
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 );
if (ctx == NULL || ctx->md_info == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
switch( ctx->md_info->type )
{
switch (ctx->md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5_finish( ctx->md_ctx, output ) );
return mbedtls_md5_finish(ctx->md_ctx, output);
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
return( mbedtls_ripemd160_finish( ctx->md_ctx, output ) );
return mbedtls_ripemd160_finish(ctx->md_ctx, output);
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1_finish( ctx->md_ctx, output ) );
return mbedtls_sha1_finish(ctx->md_ctx, output);
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
return( mbedtls_sha256_finish( ctx->md_ctx, output ) );
return mbedtls_sha256_finish(ctx->md_ctx, output);
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256_finish( ctx->md_ctx, output ) );
return mbedtls_sha256_finish(ctx->md_ctx, output);
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
return( mbedtls_sha512_finish( ctx->md_ctx, output ) );
return mbedtls_sha512_finish(ctx->md_ctx, output);
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512_finish( ctx->md_ctx, output ) );
return mbedtls_sha512_finish(ctx->md_ctx, output);
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
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 )
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 );
if (md_info == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
switch( md_info->type )
{
switch (md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_md5( input, ilen, output ) );
return mbedtls_md5(input, ilen, output);
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
return( mbedtls_ripemd160( input, ilen, output ) );
return mbedtls_ripemd160(input, ilen, output);
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_sha1( input, ilen, output ) );
return mbedtls_sha1(input, ilen, output);
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
return( mbedtls_sha256( input, ilen, output, 1 ) );
return mbedtls_sha256(input, ilen, output, 1);
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
return( mbedtls_sha256( input, ilen, output, 0 ) );
return mbedtls_sha256(input, ilen, output, 0);
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
return( mbedtls_sha512( input, ilen, output, 1 ) );
return mbedtls_sha512(input, ilen, output, 1);
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
return( mbedtls_sha512( input, ilen, output, 0 ) );
return mbedtls_sha512(input, ilen, output, 0);
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
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 mbedtls_md_file(const mbedtls_md_info_t *md_info, const char *path, unsigned char *output)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
FILE *f;
@ -593,58 +595,68 @@ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigne
mbedtls_md_context_t ctx;
unsigned char buf[1024];
if( md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if (md_info == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_MD_FILE_IO_ERROR );
if ((f = fopen(path, "rb")) == NULL) {
return MBEDTLS_ERR_MD_FILE_IO_ERROR;
}
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( f, NULL );
mbedtls_setbuf(f, NULL);
mbedtls_md_init( &ctx );
mbedtls_md_init(&ctx);
if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
if ((ret = mbedtls_md_setup(&ctx, md_info, 0)) != 0) {
goto cleanup;
}
if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
if ((ret = mbedtls_md_starts(&ctx)) != 0) {
goto cleanup;
}
while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
if( ( ret = mbedtls_md_update( &ctx, buf, n ) ) != 0 )
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
if ((ret = mbedtls_md_update(&ctx, buf, n)) != 0) {
goto cleanup;
}
}
if( ferror( f ) != 0 )
if (ferror(f) != 0) {
ret = MBEDTLS_ERR_MD_FILE_IO_ERROR;
else
ret = mbedtls_md_finish( &ctx, output );
} else {
ret = mbedtls_md_finish(&ctx, output);
}
cleanup:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
fclose( f );
mbedtls_md_free( &ctx );
mbedtls_platform_zeroize(buf, sizeof(buf));
fclose(f);
mbedtls_md_free(&ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_FS_IO */
int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen )
int mbedtls_md_hmac_starts(mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char sum[MBEDTLS_MD_MAX_SIZE];
unsigned char *ipad, *opad;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if (ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
if( keylen > (size_t) ctx->md_info->block_size )
{
if( ( ret = mbedtls_md_starts( ctx ) ) != 0 )
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 )
}
if ((ret = mbedtls_md_update(ctx, key, keylen)) != 0) {
goto cleanup;
if( ( ret = mbedtls_md_finish( ctx, sum ) ) != 0 )
}
if ((ret = mbedtls_md_finish(ctx, sum)) != 0) {
goto cleanup;
}
keylen = ctx->md_info->size;
key = sum;
@ -653,160 +665,178 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
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 );
memset(ipad, 0x36, ctx->md_info->block_size);
memset(opad, 0x5C, ctx->md_info->block_size);
mbedtls_xor( ipad, ipad, key, keylen );
mbedtls_xor( opad, opad, key, keylen );
mbedtls_xor(ipad, ipad, key, keylen);
mbedtls_xor(opad, opad, key, keylen);
if( ( ret = mbedtls_md_starts( ctx ) ) != 0 )
if ((ret = mbedtls_md_starts(ctx)) != 0) {
goto cleanup;
if( ( ret = mbedtls_md_update( ctx, ipad,
ctx->md_info->block_size ) ) != 0 )
}
if ((ret = mbedtls_md_update(ctx, ipad,
ctx->md_info->block_size)) != 0) {
goto cleanup;
}
cleanup:
mbedtls_platform_zeroize( sum, sizeof( sum ) );
mbedtls_platform_zeroize(sum, sizeof(sum));
return( ret );
return ret;
}
int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )
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 );
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 ) );
return mbedtls_md_update(ctx, input, ilen);
}
int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )
int mbedtls_md_hmac_finish(mbedtls_md_context_t *ctx, unsigned char *output)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char tmp[MBEDTLS_MD_MAX_SIZE];
unsigned char *opad;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if (ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL) {
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 );
return( mbedtls_md_finish( ctx, output ) );
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;
}
return mbedtls_md_finish(ctx, output);
}
int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )
int mbedtls_md_hmac_reset(mbedtls_md_context_t *ctx)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *ipad;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if (ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
ipad = (unsigned char *) ctx->hmac_ctx;
if( ( ret = mbedtls_md_starts( ctx ) ) != 0 )
return( ret );
return( mbedtls_md_update( ctx, ipad, ctx->md_info->block_size ) );
if ((ret = mbedtls_md_starts(ctx)) != 0) {
return ret;
}
return mbedtls_md_update(ctx, ipad, ctx->md_info->block_size);
}
int mbedtls_md_hmac( const mbedtls_md_info_t *md_info,
const unsigned char *key, size_t keylen,
const unsigned char *input, size_t ilen,
unsigned char *output )
int mbedtls_md_hmac(const mbedtls_md_info_t *md_info,
const unsigned char *key, size_t keylen,
const unsigned char *input, size_t ilen,
unsigned char *output)
{
mbedtls_md_context_t ctx;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if (md_info == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
mbedtls_md_init( &ctx );
mbedtls_md_init(&ctx);
if( ( ret = mbedtls_md_setup( &ctx, md_info, 1 ) ) != 0 )
if ((ret = mbedtls_md_setup(&ctx, md_info, 1)) != 0) {
goto cleanup;
}
if( ( ret = mbedtls_md_hmac_starts( &ctx, key, keylen ) ) != 0 )
if ((ret = mbedtls_md_hmac_starts(&ctx, key, keylen)) != 0) {
goto cleanup;
if( ( ret = mbedtls_md_hmac_update( &ctx, input, ilen ) ) != 0 )
}
if ((ret = mbedtls_md_hmac_update(&ctx, input, ilen)) != 0) {
goto cleanup;
if( ( ret = mbedtls_md_hmac_finish( &ctx, output ) ) != 0 )
}
if ((ret = mbedtls_md_hmac_finish(&ctx, output)) != 0) {
goto cleanup;
}
cleanup:
mbedtls_md_free( &ctx );
mbedtls_md_free(&ctx);
return( ret );
return ret;
}
int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )
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 );
if (ctx == NULL || ctx->md_info == NULL) {
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
switch( ctx->md_info->type )
{
switch (ctx->md_info->type) {
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( mbedtls_internal_md5_process( ctx->md_ctx, data ) );
return mbedtls_internal_md5_process(ctx->md_ctx, data);
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
return( mbedtls_internal_ripemd160_process( ctx->md_ctx, data ) );
return mbedtls_internal_ripemd160_process(ctx->md_ctx, data);
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( mbedtls_internal_sha1_process( ctx->md_ctx, data ) );
return mbedtls_internal_sha1_process(ctx->md_ctx, data);
#endif
#if defined(MBEDTLS_SHA224_C)
case MBEDTLS_MD_SHA224:
return( mbedtls_internal_sha256_process( ctx->md_ctx, data ) );
return mbedtls_internal_sha256_process(ctx->md_ctx, data);
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA256:
return( mbedtls_internal_sha256_process( ctx->md_ctx, data ) );
return mbedtls_internal_sha256_process(ctx->md_ctx, data);
#endif
#if defined(MBEDTLS_SHA384_C)
case MBEDTLS_MD_SHA384:
return( mbedtls_internal_sha512_process( ctx->md_ctx, data ) );
return mbedtls_internal_sha512_process(ctx->md_ctx, data);
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA512:
return( mbedtls_internal_sha512_process( ctx->md_ctx, data ) );
return mbedtls_internal_sha512_process(ctx->md_ctx, data);
#endif
default:
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
}
}
unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info )
unsigned char mbedtls_md_get_size(const mbedtls_md_info_t *md_info)
{
if( md_info == NULL )
return( 0 );
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 )
mbedtls_md_type_t mbedtls_md_get_type(const mbedtls_md_info_t *md_info)
{
if( md_info == NULL )
return( MBEDTLS_MD_NONE );
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 )
const char *mbedtls_md_get_name(const mbedtls_md_info_t *md_info)
{
if( md_info == NULL )
return( NULL );
if (md_info == NULL) {
return NULL;
}
return md_info->name;
}

View File

@ -36,21 +36,22 @@
#if !defined(MBEDTLS_MD5_ALT)
void mbedtls_md5_init( mbedtls_md5_context *ctx )
void mbedtls_md5_init(mbedtls_md5_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_md5_context ) );
memset(ctx, 0, sizeof(mbedtls_md5_context));
}
void mbedtls_md5_free( mbedtls_md5_context *ctx )
void mbedtls_md5_free(mbedtls_md5_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_md5_context));
}
void mbedtls_md5_clone( mbedtls_md5_context *dst,
const mbedtls_md5_context *src )
void mbedtls_md5_clone(mbedtls_md5_context *dst,
const mbedtls_md5_context *src)
{
*dst = *src;
}
@ -58,7 +59,7 @@ void mbedtls_md5_clone( mbedtls_md5_context *dst,
/*
* MD5 context setup
*/
int mbedtls_md5_starts( mbedtls_md5_context *ctx )
int mbedtls_md5_starts(mbedtls_md5_context *ctx)
{
ctx->total[0] = 0;
ctx->total[1] = 0;
@ -68,131 +69,130 @@ int mbedtls_md5_starts( mbedtls_md5_context *ctx )
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
return( 0 );
return 0;
}
#if !defined(MBEDTLS_MD5_PROCESS_ALT)
int mbedtls_internal_md5_process( mbedtls_md5_context *ctx,
const unsigned char data[64] )
int mbedtls_internal_md5_process(mbedtls_md5_context *ctx,
const unsigned char data[64])
{
struct
{
struct {
uint32_t X[16], A, B, C, D;
} local;
local.X[ 0] = MBEDTLS_GET_UINT32_LE( data, 0 );
local.X[ 1] = MBEDTLS_GET_UINT32_LE( data, 4 );
local.X[ 2] = MBEDTLS_GET_UINT32_LE( data, 8 );
local.X[ 3] = MBEDTLS_GET_UINT32_LE( data, 12 );
local.X[ 4] = MBEDTLS_GET_UINT32_LE( data, 16 );
local.X[ 5] = MBEDTLS_GET_UINT32_LE( data, 20 );
local.X[ 6] = MBEDTLS_GET_UINT32_LE( data, 24 );
local.X[ 7] = MBEDTLS_GET_UINT32_LE( data, 28 );
local.X[ 8] = MBEDTLS_GET_UINT32_LE( data, 32 );
local.X[ 9] = MBEDTLS_GET_UINT32_LE( data, 36 );
local.X[10] = MBEDTLS_GET_UINT32_LE( data, 40 );
local.X[11] = MBEDTLS_GET_UINT32_LE( data, 44 );
local.X[12] = MBEDTLS_GET_UINT32_LE( data, 48 );
local.X[13] = MBEDTLS_GET_UINT32_LE( data, 52 );
local.X[14] = MBEDTLS_GET_UINT32_LE( data, 56 );
local.X[15] = MBEDTLS_GET_UINT32_LE( data, 60 );
local.X[0] = MBEDTLS_GET_UINT32_LE(data, 0);
local.X[1] = MBEDTLS_GET_UINT32_LE(data, 4);
local.X[2] = MBEDTLS_GET_UINT32_LE(data, 8);
local.X[3] = MBEDTLS_GET_UINT32_LE(data, 12);
local.X[4] = MBEDTLS_GET_UINT32_LE(data, 16);
local.X[5] = MBEDTLS_GET_UINT32_LE(data, 20);
local.X[6] = MBEDTLS_GET_UINT32_LE(data, 24);
local.X[7] = MBEDTLS_GET_UINT32_LE(data, 28);
local.X[8] = MBEDTLS_GET_UINT32_LE(data, 32);
local.X[9] = MBEDTLS_GET_UINT32_LE(data, 36);
local.X[10] = MBEDTLS_GET_UINT32_LE(data, 40);
local.X[11] = MBEDTLS_GET_UINT32_LE(data, 44);
local.X[12] = MBEDTLS_GET_UINT32_LE(data, 48);
local.X[13] = MBEDTLS_GET_UINT32_LE(data, 52);
local.X[14] = MBEDTLS_GET_UINT32_LE(data, 56);
local.X[15] = MBEDTLS_GET_UINT32_LE(data, 60);
#define S(x,n) \
( ( (x) << (n) ) | ( ( (x) & 0xFFFFFFFF) >> ( 32 - (n) ) ) )
#define S(x, n) \
(((x) << (n)) | (((x) & 0xFFFFFFFF) >> (32 - (n))))
#define P(a,b,c,d,k,s,t) \
#define P(a, b, c, d, k, s, t) \
do \
{ \
(a) += F((b),(c),(d)) + local.X[(k)] + (t); \
(a) = S((a),(s)) + (b); \
} while( 0 )
(a) += F((b), (c), (d)) + local.X[(k)] + (t); \
(a) = S((a), (s)) + (b); \
} while (0)
local.A = ctx->state[0];
local.B = ctx->state[1];
local.C = ctx->state[2];
local.D = ctx->state[3];
#define F(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
P( local.A, local.B, local.C, local.D, 0, 7, 0xD76AA478 );
P( local.D, local.A, local.B, local.C, 1, 12, 0xE8C7B756 );
P( local.C, local.D, local.A, local.B, 2, 17, 0x242070DB );
P( local.B, local.C, local.D, local.A, 3, 22, 0xC1BDCEEE );
P( local.A, local.B, local.C, local.D, 4, 7, 0xF57C0FAF );
P( local.D, local.A, local.B, local.C, 5, 12, 0x4787C62A );
P( local.C, local.D, local.A, local.B, 6, 17, 0xA8304613 );
P( local.B, local.C, local.D, local.A, 7, 22, 0xFD469501 );
P( local.A, local.B, local.C, local.D, 8, 7, 0x698098D8 );
P( local.D, local.A, local.B, local.C, 9, 12, 0x8B44F7AF );
P( local.C, local.D, local.A, local.B, 10, 17, 0xFFFF5BB1 );
P( local.B, local.C, local.D, local.A, 11, 22, 0x895CD7BE );
P( local.A, local.B, local.C, local.D, 12, 7, 0x6B901122 );
P( local.D, local.A, local.B, local.C, 13, 12, 0xFD987193 );
P( local.C, local.D, local.A, local.B, 14, 17, 0xA679438E );
P( local.B, local.C, local.D, local.A, 15, 22, 0x49B40821 );
P(local.A, local.B, local.C, local.D, 0, 7, 0xD76AA478);
P(local.D, local.A, local.B, local.C, 1, 12, 0xE8C7B756);
P(local.C, local.D, local.A, local.B, 2, 17, 0x242070DB);
P(local.B, local.C, local.D, local.A, 3, 22, 0xC1BDCEEE);
P(local.A, local.B, local.C, local.D, 4, 7, 0xF57C0FAF);
P(local.D, local.A, local.B, local.C, 5, 12, 0x4787C62A);
P(local.C, local.D, local.A, local.B, 6, 17, 0xA8304613);
P(local.B, local.C, local.D, local.A, 7, 22, 0xFD469501);
P(local.A, local.B, local.C, local.D, 8, 7, 0x698098D8);
P(local.D, local.A, local.B, local.C, 9, 12, 0x8B44F7AF);
P(local.C, local.D, local.A, local.B, 10, 17, 0xFFFF5BB1);
P(local.B, local.C, local.D, local.A, 11, 22, 0x895CD7BE);
P(local.A, local.B, local.C, local.D, 12, 7, 0x6B901122);
P(local.D, local.A, local.B, local.C, 13, 12, 0xFD987193);
P(local.C, local.D, local.A, local.B, 14, 17, 0xA679438E);
P(local.B, local.C, local.D, local.A, 15, 22, 0x49B40821);
#undef F
#define F(x,y,z) ((y) ^ ((z) & ((x) ^ (y))))
#define F(x, y, z) ((y) ^ ((z) & ((x) ^ (y))))
P( local.A, local.B, local.C, local.D, 1, 5, 0xF61E2562 );
P( local.D, local.A, local.B, local.C, 6, 9, 0xC040B340 );
P( local.C, local.D, local.A, local.B, 11, 14, 0x265E5A51 );
P( local.B, local.C, local.D, local.A, 0, 20, 0xE9B6C7AA );
P( local.A, local.B, local.C, local.D, 5, 5, 0xD62F105D );
P( local.D, local.A, local.B, local.C, 10, 9, 0x02441453 );
P( local.C, local.D, local.A, local.B, 15, 14, 0xD8A1E681 );
P( local.B, local.C, local.D, local.A, 4, 20, 0xE7D3FBC8 );
P( local.A, local.B, local.C, local.D, 9, 5, 0x21E1CDE6 );
P( local.D, local.A, local.B, local.C, 14, 9, 0xC33707D6 );
P( local.C, local.D, local.A, local.B, 3, 14, 0xF4D50D87 );
P( local.B, local.C, local.D, local.A, 8, 20, 0x455A14ED );
P( local.A, local.B, local.C, local.D, 13, 5, 0xA9E3E905 );
P( local.D, local.A, local.B, local.C, 2, 9, 0xFCEFA3F8 );
P( local.C, local.D, local.A, local.B, 7, 14, 0x676F02D9 );
P( local.B, local.C, local.D, local.A, 12, 20, 0x8D2A4C8A );
P(local.A, local.B, local.C, local.D, 1, 5, 0xF61E2562);
P(local.D, local.A, local.B, local.C, 6, 9, 0xC040B340);
P(local.C, local.D, local.A, local.B, 11, 14, 0x265E5A51);
P(local.B, local.C, local.D, local.A, 0, 20, 0xE9B6C7AA);
P(local.A, local.B, local.C, local.D, 5, 5, 0xD62F105D);
P(local.D, local.A, local.B, local.C, 10, 9, 0x02441453);
P(local.C, local.D, local.A, local.B, 15, 14, 0xD8A1E681);
P(local.B, local.C, local.D, local.A, 4, 20, 0xE7D3FBC8);
P(local.A, local.B, local.C, local.D, 9, 5, 0x21E1CDE6);
P(local.D, local.A, local.B, local.C, 14, 9, 0xC33707D6);
P(local.C, local.D, local.A, local.B, 3, 14, 0xF4D50D87);
P(local.B, local.C, local.D, local.A, 8, 20, 0x455A14ED);
P(local.A, local.B, local.C, local.D, 13, 5, 0xA9E3E905);
P(local.D, local.A, local.B, local.C, 2, 9, 0xFCEFA3F8);
P(local.C, local.D, local.A, local.B, 7, 14, 0x676F02D9);
P(local.B, local.C, local.D, local.A, 12, 20, 0x8D2A4C8A);
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
#define F(x, y, z) ((x) ^ (y) ^ (z))
P( local.A, local.B, local.C, local.D, 5, 4, 0xFFFA3942 );
P( local.D, local.A, local.B, local.C, 8, 11, 0x8771F681 );
P( local.C, local.D, local.A, local.B, 11, 16, 0x6D9D6122 );
P( local.B, local.C, local.D, local.A, 14, 23, 0xFDE5380C );
P( local.A, local.B, local.C, local.D, 1, 4, 0xA4BEEA44 );
P( local.D, local.A, local.B, local.C, 4, 11, 0x4BDECFA9 );
P( local.C, local.D, local.A, local.B, 7, 16, 0xF6BB4B60 );
P( local.B, local.C, local.D, local.A, 10, 23, 0xBEBFBC70 );
P( local.A, local.B, local.C, local.D, 13, 4, 0x289B7EC6 );
P( local.D, local.A, local.B, local.C, 0, 11, 0xEAA127FA );
P( local.C, local.D, local.A, local.B, 3, 16, 0xD4EF3085 );
P( local.B, local.C, local.D, local.A, 6, 23, 0x04881D05 );
P( local.A, local.B, local.C, local.D, 9, 4, 0xD9D4D039 );
P( local.D, local.A, local.B, local.C, 12, 11, 0xE6DB99E5 );
P( local.C, local.D, local.A, local.B, 15, 16, 0x1FA27CF8 );
P( local.B, local.C, local.D, local.A, 2, 23, 0xC4AC5665 );
P(local.A, local.B, local.C, local.D, 5, 4, 0xFFFA3942);
P(local.D, local.A, local.B, local.C, 8, 11, 0x8771F681);
P(local.C, local.D, local.A, local.B, 11, 16, 0x6D9D6122);
P(local.B, local.C, local.D, local.A, 14, 23, 0xFDE5380C);
P(local.A, local.B, local.C, local.D, 1, 4, 0xA4BEEA44);
P(local.D, local.A, local.B, local.C, 4, 11, 0x4BDECFA9);
P(local.C, local.D, local.A, local.B, 7, 16, 0xF6BB4B60);
P(local.B, local.C, local.D, local.A, 10, 23, 0xBEBFBC70);
P(local.A, local.B, local.C, local.D, 13, 4, 0x289B7EC6);
P(local.D, local.A, local.B, local.C, 0, 11, 0xEAA127FA);
P(local.C, local.D, local.A, local.B, 3, 16, 0xD4EF3085);
P(local.B, local.C, local.D, local.A, 6, 23, 0x04881D05);
P(local.A, local.B, local.C, local.D, 9, 4, 0xD9D4D039);
P(local.D, local.A, local.B, local.C, 12, 11, 0xE6DB99E5);
P(local.C, local.D, local.A, local.B, 15, 16, 0x1FA27CF8);
P(local.B, local.C, local.D, local.A, 2, 23, 0xC4AC5665);
#undef F
#define F(x,y,z) ((y) ^ ((x) | ~(z)))
#define F(x, y, z) ((y) ^ ((x) | ~(z)))
P( local.A, local.B, local.C, local.D, 0, 6, 0xF4292244 );
P( local.D, local.A, local.B, local.C, 7, 10, 0x432AFF97 );
P( local.C, local.D, local.A, local.B, 14, 15, 0xAB9423A7 );
P( local.B, local.C, local.D, local.A, 5, 21, 0xFC93A039 );
P( local.A, local.B, local.C, local.D, 12, 6, 0x655B59C3 );
P( local.D, local.A, local.B, local.C, 3, 10, 0x8F0CCC92 );
P( local.C, local.D, local.A, local.B, 10, 15, 0xFFEFF47D );
P( local.B, local.C, local.D, local.A, 1, 21, 0x85845DD1 );
P( local.A, local.B, local.C, local.D, 8, 6, 0x6FA87E4F );
P( local.D, local.A, local.B, local.C, 15, 10, 0xFE2CE6E0 );
P( local.C, local.D, local.A, local.B, 6, 15, 0xA3014314 );
P( local.B, local.C, local.D, local.A, 13, 21, 0x4E0811A1 );
P( local.A, local.B, local.C, local.D, 4, 6, 0xF7537E82 );
P( local.D, local.A, local.B, local.C, 11, 10, 0xBD3AF235 );
P( local.C, local.D, local.A, local.B, 2, 15, 0x2AD7D2BB );
P( local.B, local.C, local.D, local.A, 9, 21, 0xEB86D391 );
P(local.A, local.B, local.C, local.D, 0, 6, 0xF4292244);
P(local.D, local.A, local.B, local.C, 7, 10, 0x432AFF97);
P(local.C, local.D, local.A, local.B, 14, 15, 0xAB9423A7);
P(local.B, local.C, local.D, local.A, 5, 21, 0xFC93A039);
P(local.A, local.B, local.C, local.D, 12, 6, 0x655B59C3);
P(local.D, local.A, local.B, local.C, 3, 10, 0x8F0CCC92);
P(local.C, local.D, local.A, local.B, 10, 15, 0xFFEFF47D);
P(local.B, local.C, local.D, local.A, 1, 21, 0x85845DD1);
P(local.A, local.B, local.C, local.D, 8, 6, 0x6FA87E4F);
P(local.D, local.A, local.B, local.C, 15, 10, 0xFE2CE6E0);
P(local.C, local.D, local.A, local.B, 6, 15, 0xA3014314);
P(local.B, local.C, local.D, local.A, 13, 21, 0x4E0811A1);
P(local.A, local.B, local.C, local.D, 4, 6, 0xF7537E82);
P(local.D, local.A, local.B, local.C, 11, 10, 0xBD3AF235);
P(local.C, local.D, local.A, local.B, 2, 15, 0x2AD7D2BB);
P(local.B, local.C, local.D, local.A, 9, 21, 0xEB86D391);
#undef F
@ -202,9 +202,9 @@ int mbedtls_internal_md5_process( mbedtls_md5_context *ctx,
ctx->state[3] += local.D;
/* Zeroise variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
mbedtls_platform_zeroize(&local, sizeof(local));
return( 0 );
return 0;
}
#endif /* !MBEDTLS_MD5_PROCESS_ALT */
@ -212,16 +212,17 @@ int mbedtls_internal_md5_process( mbedtls_md5_context *ctx,
/*
* MD5 process buffer
*/
int mbedtls_md5_update( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_md5_update(mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
uint32_t left;
if( ilen == 0 )
return( 0 );
if (ilen == 0) {
return 0;
}
left = ctx->total[0] & 0x3F;
fill = 64 - left;
@ -229,42 +230,42 @@ int mbedtls_md5_update( mbedtls_md5_context *ctx,
ctx->total[0] += (uint32_t) ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (uint32_t) ilen )
if (ctx->total[0] < (uint32_t) ilen) {
ctx->total[1]++;
}
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left), input, fill );
if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if (left && ilen >= fill) {
memcpy((void *) (ctx->buffer + left), input, fill);
if ((ret = mbedtls_internal_md5_process(ctx, ctx->buffer)) != 0) {
return ret;
}
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
if( ( ret = mbedtls_internal_md5_process( ctx, input ) ) != 0 )
return( ret );
while (ilen >= 64) {
if ((ret = mbedtls_internal_md5_process(ctx, input)) != 0) {
return ret;
}
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
memcpy( (void *) (ctx->buffer + left), input, ilen );
if (ilen > 0) {
memcpy((void *) (ctx->buffer + left), input, ilen);
}
return( 0 );
return 0;
}
/*
* MD5 final digest
*/
int mbedtls_md5_finish( mbedtls_md5_context *ctx,
unsigned char output[16] )
int mbedtls_md5_finish(mbedtls_md5_context *ctx,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint32_t used;
@ -277,44 +278,43 @@ int mbedtls_md5_finish( mbedtls_md5_context *ctx,
ctx->buffer[used++] = 0x80;
if( used <= 56 )
{
if (used <= 56) {
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
}
else
{
memset(ctx->buffer + used, 0, 56 - used);
} else {
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
memset(ctx->buffer + used, 0, 64 - used);
if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_md5_process(ctx, ctx->buffer)) != 0) {
return ret;
}
memset( ctx->buffer, 0, 56 );
memset(ctx->buffer, 0, 56);
}
/*
* Add message length
*/
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
high = (ctx->total[0] >> 29)
| (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
MBEDTLS_PUT_UINT32_LE( low, ctx->buffer, 56 );
MBEDTLS_PUT_UINT32_LE( high, ctx->buffer, 60 );
MBEDTLS_PUT_UINT32_LE(low, ctx->buffer, 56);
MBEDTLS_PUT_UINT32_LE(high, ctx->buffer, 60);
if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_md5_process(ctx, ctx->buffer)) != 0) {
return ret;
}
/*
* Output final state
*/
MBEDTLS_PUT_UINT32_LE( ctx->state[0], output, 0 );
MBEDTLS_PUT_UINT32_LE( ctx->state[1], output, 4 );
MBEDTLS_PUT_UINT32_LE( ctx->state[2], output, 8 );
MBEDTLS_PUT_UINT32_LE( ctx->state[3], output, 12 );
MBEDTLS_PUT_UINT32_LE(ctx->state[0], output, 0);
MBEDTLS_PUT_UINT32_LE(ctx->state[1], output, 4);
MBEDTLS_PUT_UINT32_LE(ctx->state[2], output, 8);
MBEDTLS_PUT_UINT32_LE(ctx->state[3], output, 12);
return( 0 );
return 0;
}
#endif /* !MBEDTLS_MD5_ALT */
@ -322,28 +322,31 @@ int mbedtls_md5_finish( mbedtls_md5_context *ctx,
/*
* output = MD5( input buffer )
*/
int mbedtls_md5( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
int mbedtls_md5(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md5_context ctx;
mbedtls_md5_init( &ctx );
mbedtls_md5_init(&ctx);
if( ( ret = mbedtls_md5_starts( &ctx ) ) != 0 )
if ((ret = mbedtls_md5_starts(&ctx)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md5_update( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_md5_update(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md5_finish( &ctx, output ) ) != 0 )
if ((ret = mbedtls_md5_finish(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_md5_free( &ctx );
mbedtls_md5_free(&ctx);
return( ret );
return ret;
}
#if defined(MBEDTLS_SELF_TEST)
@ -387,40 +390,43 @@ static const unsigned char md5_test_sum[7][16] =
/*
* Checkup routine
*/
int mbedtls_md5_self_test( int verbose )
int mbedtls_md5_self_test(int verbose)
{
int i, ret = 0;
unsigned char md5sum[16];
for( i = 0; i < 7; i++ )
{
if( verbose != 0 )
mbedtls_printf( " MD5 test #%d: ", i + 1 );
for (i = 0; i < 7; i++) {
if (verbose != 0) {
mbedtls_printf(" MD5 test #%d: ", i + 1);
}
ret = mbedtls_md5( md5_test_buf[i], md5_test_buflen[i], md5sum );
if( ret != 0 )
ret = mbedtls_md5(md5_test_buf[i], md5_test_buflen[i], md5sum);
if (ret != 0) {
goto fail;
}
if( memcmp( md5sum, md5_test_sum[i], 16 ) != 0 )
{
if (memcmp(md5sum, md5_test_sum[i], 16) != 0) {
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
return( 0 );
return 0;
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
if (verbose != 0) {
mbedtls_printf("failed\n");
}
return( ret );
return ret;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@ -38,10 +38,9 @@ extern "C" {
* Message digest information.
* Allows message digest functions to be called in a generic way.
*/
struct mbedtls_md_info_t
{
struct mbedtls_md_info_t {
/** Name of the message digest */
const char * name;
const char *name;
/** Digest identifier */
mbedtls_md_type_t type;

View File

@ -42,8 +42,7 @@
#define MAX_BT 20
typedef struct _memory_header memory_header;
struct _memory_header
{
struct _memory_header {
size_t magic1;
size_t size;
size_t alloc;
@ -58,8 +57,7 @@ struct _memory_header
size_t magic2;
};
typedef struct
{
typedef struct {
unsigned char *buf;
size_t len;
memory_header *first;
@ -82,146 +80,135 @@ buffer_alloc_ctx;
static buffer_alloc_ctx heap;
#if defined(MBEDTLS_MEMORY_DEBUG)
static void debug_header( memory_header *hdr )
static void debug_header(memory_header *hdr)
{
#if defined(MBEDTLS_MEMORY_BACKTRACE)
size_t i;
#endif
mbedtls_fprintf( stderr, "HDR: PTR(%10zu), PREV(%10zu), NEXT(%10zu), "
"ALLOC(%zu), SIZE(%10zu)\n",
(size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next,
hdr->alloc, hdr->size );
mbedtls_fprintf( stderr, " FPREV(%10zu), FNEXT(%10zu)\n",
(size_t) hdr->prev_free, (size_t) hdr->next_free );
mbedtls_fprintf(stderr, "HDR: PTR(%10zu), PREV(%10zu), NEXT(%10zu), "
"ALLOC(%zu), SIZE(%10zu)\n",
(size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next,
hdr->alloc, hdr->size);
mbedtls_fprintf(stderr, " FPREV(%10zu), FNEXT(%10zu)\n",
(size_t) hdr->prev_free, (size_t) hdr->next_free);
#if defined(MBEDTLS_MEMORY_BACKTRACE)
mbedtls_fprintf( stderr, "TRACE: \n" );
for( i = 0; i < hdr->trace_count; i++ )
mbedtls_fprintf( stderr, "%s\n", hdr->trace[i] );
mbedtls_fprintf( stderr, "\n" );
mbedtls_fprintf(stderr, "TRACE: \n");
for (i = 0; i < hdr->trace_count; i++) {
mbedtls_fprintf(stderr, "%s\n", hdr->trace[i]);
}
mbedtls_fprintf(stderr, "\n");
#endif
}
static void debug_chain( void )
static void debug_chain(void)
{
memory_header *cur = heap.first;
mbedtls_fprintf( stderr, "\nBlock list\n" );
while( cur != NULL )
{
debug_header( cur );
mbedtls_fprintf(stderr, "\nBlock list\n");
while (cur != NULL) {
debug_header(cur);
cur = cur->next;
}
mbedtls_fprintf( stderr, "Free list\n" );
mbedtls_fprintf(stderr, "Free list\n");
cur = heap.first_free;
while( cur != NULL )
{
debug_header( cur );
while (cur != NULL) {
debug_header(cur);
cur = cur->next_free;
}
}
#endif /* MBEDTLS_MEMORY_DEBUG */
static int verify_header( memory_header *hdr )
static int verify_header(memory_header *hdr)
{
if( hdr->magic1 != MAGIC1 )
{
if (hdr->magic1 != MAGIC1) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: MAGIC1 mismatch\n" );
mbedtls_fprintf(stderr, "FATAL: MAGIC1 mismatch\n");
#endif
return( 1 );
return 1;
}
if( hdr->magic2 != MAGIC2 )
{
if (hdr->magic2 != MAGIC2) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: MAGIC2 mismatch\n" );
mbedtls_fprintf(stderr, "FATAL: MAGIC2 mismatch\n");
#endif
return( 1 );
return 1;
}
if( hdr->alloc > 1 )
{
if (hdr->alloc > 1) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: alloc has illegal value\n" );
mbedtls_fprintf(stderr, "FATAL: alloc has illegal value\n");
#endif
return( 1 );
return 1;
}
if( hdr->prev != NULL && hdr->prev == hdr->next )
{
if (hdr->prev != NULL && hdr->prev == hdr->next) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: prev == next\n" );
mbedtls_fprintf(stderr, "FATAL: prev == next\n");
#endif
return( 1 );
return 1;
}
if( hdr->prev_free != NULL && hdr->prev_free == hdr->next_free )
{
if (hdr->prev_free != NULL && hdr->prev_free == hdr->next_free) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: prev_free == next_free\n" );
mbedtls_fprintf(stderr, "FATAL: prev_free == next_free\n");
#endif
return( 1 );
return 1;
}
return( 0 );
return 0;
}
static int verify_chain( void )
static int verify_chain(void)
{
memory_header *prv = heap.first, *cur;
if( prv == NULL || verify_header( prv ) != 0 )
{
if (prv == NULL || verify_header(prv) != 0) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification of first header "
"failed\n" );
mbedtls_fprintf(stderr, "FATAL: verification of first header "
"failed\n");
#endif
return( 1 );
return 1;
}
if( heap.first->prev != NULL )
{
if (heap.first->prev != NULL) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification failed: "
"first->prev != NULL\n" );
mbedtls_fprintf(stderr, "FATAL: verification failed: "
"first->prev != NULL\n");
#endif
return( 1 );
return 1;
}
cur = heap.first->next;
while( cur != NULL )
{
if( verify_header( cur ) != 0 )
{
while (cur != NULL) {
if (verify_header(cur) != 0) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification of header "
"failed\n" );
mbedtls_fprintf(stderr, "FATAL: verification of header "
"failed\n");
#endif
return( 1 );
return 1;
}
if( cur->prev != prv )
{
if (cur->prev != prv) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification failed: "
"cur->prev != prv\n" );
mbedtls_fprintf(stderr, "FATAL: verification failed: "
"cur->prev != prv\n");
#endif
return( 1 );
return 1;
}
prv = cur;
cur = cur->next;
}
return( 0 );
return 0;
}
static void *buffer_alloc_calloc( size_t n, size_t size )
static void *buffer_alloc_calloc(size_t n, size_t size)
{
memory_header *new, *cur = heap.first_free;
unsigned char *p;
@ -232,42 +219,43 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
size_t trace_cnt;
#endif
if( heap.buf == NULL || heap.first == NULL )
return( NULL );
if (heap.buf == NULL || heap.first == NULL) {
return NULL;
}
original_len = len = n * size;
if( n == 0 || size == 0 || len / n != size )
return( NULL );
else if( len > (size_t)-MBEDTLS_MEMORY_ALIGN_MULTIPLE )
return( NULL );
if (n == 0 || size == 0 || len / n != size) {
return NULL;
} else if (len > (size_t) -MBEDTLS_MEMORY_ALIGN_MULTIPLE) {
return NULL;
}
if( len % MBEDTLS_MEMORY_ALIGN_MULTIPLE )
{
if (len % MBEDTLS_MEMORY_ALIGN_MULTIPLE) {
len -= len % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
len += MBEDTLS_MEMORY_ALIGN_MULTIPLE;
}
// Find block that fits
//
while( cur != NULL )
{
if( cur->size >= len )
while (cur != NULL) {
if (cur->size >= len) {
break;
}
cur = cur->next_free;
}
if( cur == NULL )
return( NULL );
if (cur == NULL) {
return NULL;
}
if( cur->alloc != 0 )
{
if (cur->alloc != 0) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: block in free_list but allocated "
"data\n" );
mbedtls_fprintf(stderr, "FATAL: block in free_list but allocated "
"data\n");
#endif
mbedtls_exit( 1 );
mbedtls_exit(1);
}
#if defined(MBEDTLS_MEMORY_DEBUG)
@ -276,45 +264,48 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
// Found location, split block if > memory_header + 4 room left
//
if( cur->size - len < sizeof(memory_header) +
MBEDTLS_MEMORY_ALIGN_MULTIPLE )
{
if (cur->size - len < sizeof(memory_header) +
MBEDTLS_MEMORY_ALIGN_MULTIPLE) {
cur->alloc = 1;
// Remove from free_list
//
if( cur->prev_free != NULL )
if (cur->prev_free != NULL) {
cur->prev_free->next_free = cur->next_free;
else
} else {
heap.first_free = cur->next_free;
}
if( cur->next_free != NULL )
if (cur->next_free != NULL) {
cur->next_free->prev_free = cur->prev_free;
}
cur->prev_free = NULL;
cur->next_free = NULL;
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.total_used += cur->size;
if( heap.total_used > heap.maximum_used )
if (heap.total_used > heap.maximum_used) {
heap.maximum_used = heap.total_used;
}
#endif
#if defined(MBEDTLS_MEMORY_BACKTRACE)
trace_cnt = backtrace( trace_buffer, MAX_BT );
cur->trace = backtrace_symbols( trace_buffer, trace_cnt );
trace_cnt = backtrace(trace_buffer, MAX_BT);
cur->trace = backtrace_symbols(trace_buffer, trace_cnt);
cur->trace_count = trace_cnt;
#endif
if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )
mbedtls_exit( 1 );
if ((heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC) && verify_chain() != 0) {
mbedtls_exit(1);
}
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
ret = (unsigned char *) cur + sizeof(memory_header);
memset(ret, 0, original_len);
return( ret );
return ret;
}
p = ( (unsigned char *) cur ) + sizeof(memory_header) + len;
p = ((unsigned char *) cur) + sizeof(memory_header) + len;
new = (memory_header *) p;
new->size = cur->size - len - sizeof(memory_header);
@ -328,20 +319,23 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
new->magic1 = MAGIC1;
new->magic2 = MAGIC2;
if( new->next != NULL )
if (new->next != NULL) {
new->next->prev = new;
}
// Replace cur with new in free_list
//
new->prev_free = cur->prev_free;
new->next_free = cur->next_free;
if( new->prev_free != NULL )
if (new->prev_free != NULL) {
new->prev_free->next_free = new;
else
} else {
heap.first_free = new;
}
if( new->next_free != NULL )
if (new->next_free != NULL) {
new->next_free->prev_free = new;
}
cur->alloc = 1;
cur->size = len;
@ -351,57 +345,60 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.header_count++;
if( heap.header_count > heap.maximum_header_count )
if (heap.header_count > heap.maximum_header_count) {
heap.maximum_header_count = heap.header_count;
}
heap.total_used += cur->size;
if( heap.total_used > heap.maximum_used )
if (heap.total_used > heap.maximum_used) {
heap.maximum_used = heap.total_used;
}
#endif
#if defined(MBEDTLS_MEMORY_BACKTRACE)
trace_cnt = backtrace( trace_buffer, MAX_BT );
cur->trace = backtrace_symbols( trace_buffer, trace_cnt );
trace_cnt = backtrace(trace_buffer, MAX_BT);
cur->trace = backtrace_symbols(trace_buffer, trace_cnt);
cur->trace_count = trace_cnt;
#endif
if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )
mbedtls_exit( 1 );
if ((heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC) && verify_chain() != 0) {
mbedtls_exit(1);
}
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
ret = (unsigned char *) cur + sizeof(memory_header);
memset(ret, 0, original_len);
return( ret );
return ret;
}
static void buffer_alloc_free( void *ptr )
static void buffer_alloc_free(void *ptr)
{
memory_header *hdr, *old = NULL;
unsigned char *p = (unsigned char *) ptr;
if( ptr == NULL || heap.buf == NULL || heap.first == NULL )
if (ptr == NULL || heap.buf == NULL || heap.first == NULL) {
return;
}
if( p < heap.buf || p >= heap.buf + heap.len )
{
if (p < heap.buf || p >= heap.buf + heap.len) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: mbedtls_free() outside of managed "
"space\n" );
mbedtls_fprintf(stderr, "FATAL: mbedtls_free() outside of managed "
"space\n");
#endif
mbedtls_exit( 1 );
mbedtls_exit(1);
}
p -= sizeof(memory_header);
hdr = (memory_header *) p;
if( verify_header( hdr ) != 0 )
mbedtls_exit( 1 );
if (verify_header(hdr) != 0) {
mbedtls_exit(1);
}
if( hdr->alloc != 1 )
{
if (hdr->alloc != 1) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: mbedtls_free() on unallocated "
"data\n" );
mbedtls_fprintf(stderr, "FATAL: mbedtls_free() on unallocated "
"data\n");
#endif
mbedtls_exit( 1 );
mbedtls_exit(1);
}
hdr->alloc = 0;
@ -412,15 +409,14 @@ static void buffer_alloc_free( void *ptr )
#endif
#if defined(MBEDTLS_MEMORY_BACKTRACE)
free( hdr->trace );
free(hdr->trace);
hdr->trace = NULL;
hdr->trace_count = 0;
#endif
// Regroup with block before
//
if( hdr->prev != NULL && hdr->prev->alloc == 0 )
{
if (hdr->prev != NULL && hdr->prev->alloc == 0) {
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.header_count--;
#endif
@ -429,16 +425,16 @@ static void buffer_alloc_free( void *ptr )
old = hdr;
hdr = hdr->prev;
if( hdr->next != NULL )
if (hdr->next != NULL) {
hdr->next->prev = hdr;
}
memset( old, 0, sizeof(memory_header) );
memset(old, 0, sizeof(memory_header));
}
// Regroup with block after
//
if( hdr->next != NULL && hdr->next->alloc == 0 )
{
if (hdr->next != NULL && hdr->next->alloc == 0) {
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.header_count--;
#endif
@ -446,101 +442,103 @@ static void buffer_alloc_free( void *ptr )
old = hdr->next;
hdr->next = hdr->next->next;
if( hdr->prev_free != NULL || hdr->next_free != NULL )
{
if( hdr->prev_free != NULL )
if (hdr->prev_free != NULL || hdr->next_free != NULL) {
if (hdr->prev_free != NULL) {
hdr->prev_free->next_free = hdr->next_free;
else
} else {
heap.first_free = hdr->next_free;
}
if( hdr->next_free != NULL )
if (hdr->next_free != NULL) {
hdr->next_free->prev_free = hdr->prev_free;
}
}
hdr->prev_free = old->prev_free;
hdr->next_free = old->next_free;
if( hdr->prev_free != NULL )
if (hdr->prev_free != NULL) {
hdr->prev_free->next_free = hdr;
else
} else {
heap.first_free = hdr;
}
if( hdr->next_free != NULL )
if (hdr->next_free != NULL) {
hdr->next_free->prev_free = hdr;
}
if( hdr->next != NULL )
if (hdr->next != NULL) {
hdr->next->prev = hdr;
}
memset( old, 0, sizeof(memory_header) );
memset(old, 0, sizeof(memory_header));
}
// Prepend to free_list if we have not merged
// (Does not have to stay in same order as prev / next list)
//
if( old == NULL )
{
if (old == NULL) {
hdr->next_free = heap.first_free;
if( heap.first_free != NULL )
if (heap.first_free != NULL) {
heap.first_free->prev_free = hdr;
}
heap.first_free = hdr;
}
if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_FREE ) && verify_chain() != 0 )
mbedtls_exit( 1 );
if ((heap.verify & MBEDTLS_MEMORY_VERIFY_FREE) && verify_chain() != 0) {
mbedtls_exit(1);
}
}
void mbedtls_memory_buffer_set_verify( int verify )
void mbedtls_memory_buffer_set_verify(int verify)
{
heap.verify = verify;
}
int mbedtls_memory_buffer_alloc_verify( void )
int mbedtls_memory_buffer_alloc_verify(void)
{
return verify_chain();
}
#if defined(MBEDTLS_MEMORY_DEBUG)
void mbedtls_memory_buffer_alloc_status( void )
void mbedtls_memory_buffer_alloc_status(void)
{
mbedtls_fprintf( stderr,
"Current use: %zu blocks / %zu bytes, max: %zu blocks / "
"%zu bytes (total %zu bytes), alloc / free: %zu / %zu\n",
heap.header_count, heap.total_used,
heap.maximum_header_count, heap.maximum_used,
heap.maximum_header_count * sizeof( memory_header )
+ heap.maximum_used,
heap.alloc_count, heap.free_count );
mbedtls_fprintf(stderr,
"Current use: %zu blocks / %zu bytes, max: %zu blocks / "
"%zu bytes (total %zu bytes), alloc / free: %zu / %zu\n",
heap.header_count, heap.total_used,
heap.maximum_header_count, heap.maximum_used,
heap.maximum_header_count * sizeof(memory_header)
+ heap.maximum_used,
heap.alloc_count, heap.free_count);
if( heap.first->next == NULL )
{
mbedtls_fprintf( stderr, "All memory de-allocated in stack buffer\n" );
}
else
{
mbedtls_fprintf( stderr, "Memory currently allocated:\n" );
if (heap.first->next == NULL) {
mbedtls_fprintf(stderr, "All memory de-allocated in stack buffer\n");
} else {
mbedtls_fprintf(stderr, "Memory currently allocated:\n");
debug_chain();
}
}
void mbedtls_memory_buffer_alloc_count_get( size_t *alloc_count, size_t *free_count )
void mbedtls_memory_buffer_alloc_count_get(size_t *alloc_count, size_t *free_count)
{
*alloc_count = heap.alloc_count;
*free_count = heap.free_count;
}
void mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks )
void mbedtls_memory_buffer_alloc_max_get(size_t *max_used, size_t *max_blocks)
{
*max_used = heap.maximum_used;
*max_blocks = heap.maximum_header_count;
}
void mbedtls_memory_buffer_alloc_max_reset( void )
void mbedtls_memory_buffer_alloc_max_reset(void)
{
heap.maximum_used = 0;
heap.maximum_header_count = 0;
}
void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks )
void mbedtls_memory_buffer_alloc_cur_get(size_t *cur_used, size_t *cur_blocks)
{
*cur_used = heap.total_used;
*cur_blocks = heap.header_count;
@ -548,202 +546,211 @@ void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks )
#endif /* MBEDTLS_MEMORY_DEBUG */
#if defined(MBEDTLS_THREADING_C)
static void *buffer_alloc_calloc_mutexed( size_t n, size_t size )
static void *buffer_alloc_calloc_mutexed(size_t n, size_t size)
{
void *buf;
if( mbedtls_mutex_lock( &heap.mutex ) != 0 )
return( NULL );
buf = buffer_alloc_calloc( n, size );
if( mbedtls_mutex_unlock( &heap.mutex ) )
return( NULL );
return( buf );
if (mbedtls_mutex_lock(&heap.mutex) != 0) {
return NULL;
}
buf = buffer_alloc_calloc(n, size);
if (mbedtls_mutex_unlock(&heap.mutex)) {
return NULL;
}
return buf;
}
static void buffer_alloc_free_mutexed( void *ptr )
static void buffer_alloc_free_mutexed(void *ptr)
{
/* We have no good option here, but corrupting the heap seems
* worse than losing memory. */
if( mbedtls_mutex_lock( &heap.mutex ) )
if (mbedtls_mutex_lock(&heap.mutex)) {
return;
buffer_alloc_free( ptr );
(void) mbedtls_mutex_unlock( &heap.mutex );
}
buffer_alloc_free(ptr);
(void) mbedtls_mutex_unlock(&heap.mutex);
}
#endif /* MBEDTLS_THREADING_C */
void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len )
void mbedtls_memory_buffer_alloc_init(unsigned char *buf, size_t len)
{
memset( &heap, 0, sizeof( buffer_alloc_ctx ) );
memset(&heap, 0, sizeof(buffer_alloc_ctx));
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &heap.mutex );
mbedtls_platform_set_calloc_free( buffer_alloc_calloc_mutexed,
buffer_alloc_free_mutexed );
mbedtls_mutex_init(&heap.mutex);
mbedtls_platform_set_calloc_free(buffer_alloc_calloc_mutexed,
buffer_alloc_free_mutexed);
#else
mbedtls_platform_set_calloc_free( buffer_alloc_calloc, buffer_alloc_free );
mbedtls_platform_set_calloc_free(buffer_alloc_calloc, buffer_alloc_free);
#endif
if( len < sizeof( memory_header ) + MBEDTLS_MEMORY_ALIGN_MULTIPLE )
if (len < sizeof(memory_header) + MBEDTLS_MEMORY_ALIGN_MULTIPLE) {
return;
else if( (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE )
{
} else if ((size_t) buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE) {
/* Adjust len first since buf is used in the computation */
len -= MBEDTLS_MEMORY_ALIGN_MULTIPLE
- (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
- (size_t) buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
buf += MBEDTLS_MEMORY_ALIGN_MULTIPLE
- (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
- (size_t) buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
}
memset( buf, 0, len );
memset(buf, 0, len);
heap.buf = buf;
heap.len = len;
heap.first = (memory_header *)buf;
heap.first->size = len - sizeof( memory_header );
heap.first = (memory_header *) buf;
heap.first->size = len - sizeof(memory_header);
heap.first->magic1 = MAGIC1;
heap.first->magic2 = MAGIC2;
heap.first_free = heap.first;
}
void mbedtls_memory_buffer_alloc_free( void )
void mbedtls_memory_buffer_alloc_free(void)
{
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_free( &heap.mutex );
mbedtls_mutex_free(&heap.mutex);
#endif
mbedtls_platform_zeroize( &heap, sizeof(buffer_alloc_ctx) );
mbedtls_platform_zeroize(&heap, sizeof(buffer_alloc_ctx));
}
#if defined(MBEDTLS_SELF_TEST)
static int check_pointer( void *p )
static int check_pointer(void *p)
{
if( p == NULL )
return( -1 );
if (p == NULL) {
return -1;
}
if( (size_t) p % MBEDTLS_MEMORY_ALIGN_MULTIPLE != 0 )
return( -1 );
if ((size_t) p % MBEDTLS_MEMORY_ALIGN_MULTIPLE != 0) {
return -1;
}
return( 0 );
return 0;
}
static int check_all_free( void )
static int check_all_free(void)
{
if(
if (
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.total_used != 0 ||
#endif
heap.first != heap.first_free ||
(void *) heap.first != (void *) heap.buf )
{
return( -1 );
(void *) heap.first != (void *) heap.buf) {
return -1;
}
return( 0 );
return 0;
}
#define TEST_ASSERT( condition ) \
if( ! (condition) ) \
#define TEST_ASSERT(condition) \
if (!(condition)) \
{ \
if( verbose != 0 ) \
mbedtls_printf( "failed\n" ); \
if (verbose != 0) \
mbedtls_printf("failed\n"); \
\
ret = 1; \
goto cleanup; \
}
int mbedtls_memory_buffer_alloc_self_test( int verbose )
int mbedtls_memory_buffer_alloc_self_test(int verbose)
{
unsigned char buf[1024];
unsigned char *p, *q, *r, *end;
int ret = 0;
if( verbose != 0 )
mbedtls_printf( " MBA test #1 (basic alloc-free cycle): " );
if (verbose != 0) {
mbedtls_printf(" MBA test #1 (basic alloc-free cycle): ");
}
mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) );
mbedtls_memory_buffer_alloc_init(buf, sizeof(buf));
p = mbedtls_calloc( 1, 1 );
q = mbedtls_calloc( 1, 128 );
r = mbedtls_calloc( 1, 16 );
p = mbedtls_calloc(1, 1);
q = mbedtls_calloc(1, 128);
r = mbedtls_calloc(1, 16);
TEST_ASSERT( check_pointer( p ) == 0 &&
check_pointer( q ) == 0 &&
check_pointer( r ) == 0 );
TEST_ASSERT(check_pointer(p) == 0 &&
check_pointer(q) == 0 &&
check_pointer(r) == 0);
mbedtls_free( r );
mbedtls_free( q );
mbedtls_free( p );
mbedtls_free(r);
mbedtls_free(q);
mbedtls_free(p);
TEST_ASSERT( check_all_free( ) == 0 );
TEST_ASSERT(check_all_free() == 0);
/* Memorize end to compare with the next test */
end = heap.buf + heap.len;
mbedtls_memory_buffer_alloc_free( );
mbedtls_memory_buffer_alloc_free();
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
if( verbose != 0 )
mbedtls_printf( " MBA test #2 (buf not aligned): " );
if (verbose != 0) {
mbedtls_printf(" MBA test #2 (buf not aligned): ");
}
mbedtls_memory_buffer_alloc_init( buf + 1, sizeof( buf ) - 1 );
mbedtls_memory_buffer_alloc_init(buf + 1, sizeof(buf) - 1);
TEST_ASSERT( heap.buf + heap.len == end );
TEST_ASSERT(heap.buf + heap.len == end);
p = mbedtls_calloc( 1, 1 );
q = mbedtls_calloc( 1, 128 );
r = mbedtls_calloc( 1, 16 );
p = mbedtls_calloc(1, 1);
q = mbedtls_calloc(1, 128);
r = mbedtls_calloc(1, 16);
TEST_ASSERT( check_pointer( p ) == 0 &&
check_pointer( q ) == 0 &&
check_pointer( r ) == 0 );
TEST_ASSERT(check_pointer(p) == 0 &&
check_pointer(q) == 0 &&
check_pointer(r) == 0);
mbedtls_free( r );
mbedtls_free( q );
mbedtls_free( p );
mbedtls_free(r);
mbedtls_free(q);
mbedtls_free(p);
TEST_ASSERT( check_all_free( ) == 0 );
TEST_ASSERT(check_all_free() == 0);
mbedtls_memory_buffer_alloc_free( );
mbedtls_memory_buffer_alloc_free();
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
if( verbose != 0 )
mbedtls_printf( " MBA test #3 (full): " );
if (verbose != 0) {
mbedtls_printf(" MBA test #3 (full): ");
}
mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) );
mbedtls_memory_buffer_alloc_init(buf, sizeof(buf));
p = mbedtls_calloc( 1, sizeof( buf ) - sizeof( memory_header ) );
p = mbedtls_calloc(1, sizeof(buf) - sizeof(memory_header));
TEST_ASSERT( check_pointer( p ) == 0 );
TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL );
TEST_ASSERT(check_pointer(p) == 0);
TEST_ASSERT(mbedtls_calloc(1, 1) == NULL);
mbedtls_free( p );
mbedtls_free(p);
p = mbedtls_calloc( 1, sizeof( buf ) - 2 * sizeof( memory_header ) - 16 );
q = mbedtls_calloc( 1, 16 );
p = mbedtls_calloc(1, sizeof(buf) - 2 * sizeof(memory_header) - 16);
q = mbedtls_calloc(1, 16);
TEST_ASSERT( check_pointer( p ) == 0 && check_pointer( q ) == 0 );
TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL );
TEST_ASSERT(check_pointer(p) == 0 && check_pointer(q) == 0);
TEST_ASSERT(mbedtls_calloc(1, 1) == NULL);
mbedtls_free( q );
mbedtls_free(q);
TEST_ASSERT( mbedtls_calloc( 1, 17 ) == NULL );
TEST_ASSERT(mbedtls_calloc(1, 17) == NULL);
mbedtls_free( p );
mbedtls_free(p);
TEST_ASSERT( check_all_free( ) == 0 );
TEST_ASSERT(check_all_free() == 0);
mbedtls_memory_buffer_alloc_free( );
mbedtls_memory_buffer_alloc_free();
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
cleanup:
mbedtls_memory_buffer_alloc_free( );
mbedtls_memory_buffer_alloc_free();
return( ret );
return ret;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@ -99,41 +99,41 @@
#if defined(MBEDTLS_MPS_STATE_VALIDATION)
#define MBEDTLS_MPS_STATE_VALIDATE_RAW( cond, string ) \
#define MBEDTLS_MPS_STATE_VALIDATE_RAW(cond, string) \
do \
{ \
if( !(cond) ) \
if (!(cond)) \
{ \
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_ERROR, string ); \
MBEDTLS_MPS_TRACE_RETURN( MBEDTLS_ERR_MPS_OPERATION_UNEXPECTED ); \
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_ERROR, string); \
MBEDTLS_MPS_TRACE_RETURN(MBEDTLS_ERR_MPS_OPERATION_UNEXPECTED); \
} \
} while( 0 )
} while (0)
#else /* MBEDTLS_MPS_STATE_VALIDATION */
#define MBEDTLS_MPS_STATE_VALIDATE_RAW( cond, string ) \
#define MBEDTLS_MPS_STATE_VALIDATE_RAW(cond, string) \
do \
{ \
( cond ); \
} while( 0 )
(cond); \
} while (0)
#endif /* MBEDTLS_MPS_STATE_VALIDATION */
#if defined(MBEDTLS_MPS_ENABLE_ASSERTIONS)
#define MBEDTLS_MPS_ASSERT_RAW( cond, string ) \
#define MBEDTLS_MPS_ASSERT_RAW(cond, string) \
do \
{ \
if( !(cond) ) \
if (!(cond)) \
{ \
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_ERROR, string ); \
MBEDTLS_MPS_TRACE_RETURN( MBEDTLS_ERR_MPS_INTERNAL_ERROR ); \
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_ERROR, string); \
MBEDTLS_MPS_TRACE_RETURN(MBEDTLS_ERR_MPS_INTERNAL_ERROR); \
} \
} while( 0 )
} while (0)
#else /* MBEDTLS_MPS_ENABLE_ASSERTIONS */
#define MBEDTLS_MPS_ASSERT_RAW( cond, string ) do {} while( 0 )
#define MBEDTLS_MPS_ASSERT_RAW(cond, string) do {} while (0)
#endif /* MBEDTLS_MPS_ENABLE_ASSERTIONS */
@ -169,7 +169,7 @@
*
*/
typedef size_t mbedtls_mps_stored_size_t;
#define MBEDTLS_MPS_STORED_SIZE_MAX ( (mbedtls_mps_stored_size_t) -1 )
#define MBEDTLS_MPS_STORED_SIZE_MAX ((mbedtls_mps_stored_size_t) -1)
/** \brief The type of buffer sizes and offsets used in the MPS API
* and implementation.
@ -183,7 +183,7 @@ typedef size_t mbedtls_mps_stored_size_t;
* so almost 10%.
*/
typedef size_t mbedtls_mps_size_t;
#define MBEDTLS_MPS_SIZE_MAX ( (mbedtls_mps_size_t) -1 )
#define MBEDTLS_MPS_SIZE_MAX ((mbedtls_mps_size_t) -1)
#if MBEDTLS_MPS_STORED_SIZE_MAX > MBEDTLS_MPS_SIZE_MAX
#error "Misconfiguration of mbedtls_mps_size_t and mbedtls_mps_stored_size_t."

View File

@ -45,14 +45,14 @@
*/
#ifndef MBEDTLS_MPS_ERR_BASE
#define MBEDTLS_MPS_ERR_BASE ( 0 )
#define MBEDTLS_MPS_ERR_BASE (0)
#endif
#define MBEDTLS_MPS_MAKE_ERROR(code) \
( -( MBEDTLS_MPS_ERR_BASE | (code) ) )
(-(MBEDTLS_MPS_ERR_BASE | (code)))
#define MBEDTLS_ERR_MPS_OPERATION_UNEXPECTED MBEDTLS_MPS_MAKE_ERROR( 0x1 )
#define MBEDTLS_ERR_MPS_INTERNAL_ERROR MBEDTLS_MPS_MAKE_ERROR( 0x2 )
#define MBEDTLS_ERR_MPS_OPERATION_UNEXPECTED MBEDTLS_MPS_MAKE_ERROR(0x1)
#define MBEDTLS_ERR_MPS_INTERNAL_ERROR MBEDTLS_MPS_MAKE_ERROR(0x2)
/* \} name SECTION: MPS general error codes */
@ -63,40 +63,40 @@
*/
#ifndef MBEDTLS_MPS_READER_ERR_BASE
#define MBEDTLS_MPS_READER_ERR_BASE ( 1 << 8 )
#define MBEDTLS_MPS_READER_ERR_BASE (1 << 8)
#endif
#define MBEDTLS_MPS_READER_MAKE_ERROR(code) \
( -( MBEDTLS_MPS_READER_ERR_BASE | (code) ) )
(-(MBEDTLS_MPS_READER_ERR_BASE | (code)))
/*! An attempt to reclaim the data buffer from a reader failed because
* the user hasn't yet read and committed all of it. */
#define MBEDTLS_ERR_MPS_READER_DATA_LEFT MBEDTLS_MPS_READER_MAKE_ERROR( 0x1 )
#define MBEDTLS_ERR_MPS_READER_DATA_LEFT MBEDTLS_MPS_READER_MAKE_ERROR(0x1)
/*! An invalid argument was passed to the reader. */
#define MBEDTLS_ERR_MPS_READER_INVALID_ARG MBEDTLS_MPS_READER_MAKE_ERROR( 0x2 )
#define MBEDTLS_ERR_MPS_READER_INVALID_ARG MBEDTLS_MPS_READER_MAKE_ERROR(0x2)
/*! An attempt to move a reader to consuming mode through mbedtls_mps_reader_feed()
* after pausing failed because the provided data is not sufficient to serve the
* read requests that led to the pausing. */
#define MBEDTLS_ERR_MPS_READER_NEED_MORE MBEDTLS_MPS_READER_MAKE_ERROR( 0x3 )
#define MBEDTLS_ERR_MPS_READER_NEED_MORE MBEDTLS_MPS_READER_MAKE_ERROR(0x3)
/*! A get request failed because not enough data is available in the reader. */
#define MBEDTLS_ERR_MPS_READER_OUT_OF_DATA MBEDTLS_MPS_READER_MAKE_ERROR( 0x4 )
#define MBEDTLS_ERR_MPS_READER_OUT_OF_DATA MBEDTLS_MPS_READER_MAKE_ERROR(0x4)
/*!< A get request after pausing and reactivating the reader failed because
* the request is not in line with the request made prior to pausing. The user
* must not change it's 'strategy' after pausing and reactivating a reader. */
#define MBEDTLS_ERR_MPS_READER_INCONSISTENT_REQUESTS MBEDTLS_MPS_READER_MAKE_ERROR( 0x5 )
#define MBEDTLS_ERR_MPS_READER_INCONSISTENT_REQUESTS MBEDTLS_MPS_READER_MAKE_ERROR(0x5)
/*! An attempt to reclaim the data buffer from a reader failed because the reader
* has no accumulator it can use to backup the data that hasn't been processed. */
#define MBEDTLS_ERR_MPS_READER_NEED_ACCUMULATOR MBEDTLS_MPS_READER_MAKE_ERROR( 0x6 )
#define MBEDTLS_ERR_MPS_READER_NEED_ACCUMULATOR MBEDTLS_MPS_READER_MAKE_ERROR(0x6)
/*! An attempt to reclaim the data buffer from a reader failed because the
* accumulator passed to the reader is not large enough to hold both the
* data that hasn't been processed and the excess of the last read-request. */
#define MBEDTLS_ERR_MPS_READER_ACCUMULATOR_TOO_SMALL MBEDTLS_MPS_READER_MAKE_ERROR( 0x7 )
#define MBEDTLS_ERR_MPS_READER_ACCUMULATOR_TOO_SMALL MBEDTLS_MPS_READER_MAKE_ERROR(0x7)
/* \} name SECTION: MPS Reader error codes */

View File

@ -67,54 +67,56 @@ static int mbedtls_mps_trace_id = MBEDTLS_MPS_TRACE_BIT_READER;
*/
static inline int mps_reader_is_accumulating(
mbedtls_mps_reader const *rd )
mbedtls_mps_reader const *rd)
{
mbedtls_mps_size_t acc_remaining;
if( rd->acc == NULL )
return( 0 );
if (rd->acc == NULL) {
return 0;
}
acc_remaining = rd->acc_share.acc_remaining;
return( acc_remaining > 0 );
return acc_remaining > 0;
}
static inline int mps_reader_is_producing(
mbedtls_mps_reader const *rd )
mbedtls_mps_reader const *rd)
{
unsigned char *frag = rd->frag;
return( frag == NULL );
return frag == NULL;
}
static inline int mps_reader_is_consuming(
mbedtls_mps_reader const *rd )
mbedtls_mps_reader const *rd)
{
return( !mps_reader_is_producing( rd ) );
return !mps_reader_is_producing(rd);
}
static inline mbedtls_mps_size_t mps_reader_get_fragment_offset(
mbedtls_mps_reader const *rd )
mbedtls_mps_reader const *rd)
{
unsigned char *acc = rd->acc;
mbedtls_mps_size_t frag_offset;
if( acc == NULL )
return( 0 );
if (acc == NULL) {
return 0;
}
frag_offset = rd->acc_share.frag_offset;
return( frag_offset );
return frag_offset;
}
static inline mbedtls_mps_size_t mps_reader_serving_from_accumulator(
mbedtls_mps_reader const *rd )
mbedtls_mps_reader const *rd)
{
mbedtls_mps_size_t frag_offset, end;
frag_offset = mps_reader_get_fragment_offset( rd );
frag_offset = mps_reader_get_fragment_offset(rd);
end = rd->end;
return( end < frag_offset );
return end < frag_offset;
}
static inline void mps_reader_zero( mbedtls_mps_reader *rd )
static inline void mps_reader_zero(mbedtls_mps_reader *rd)
{
/* A plain memset() would likely be more efficient,
* but the current way of zeroing makes it harder
@ -123,56 +125,56 @@ static inline void mps_reader_zero( mbedtls_mps_reader *rd )
* doesn't require reasoning about structs being
* interpreted as unstructured binary blobs. */
static mbedtls_mps_reader const zero =
{ .frag = NULL,
.frag_len = 0,
.commit = 0,
.end = 0,
.pending = 0,
.acc = NULL,
.acc_len = 0,
.acc_available = 0,
.acc_share = { .acc_remaining = 0 }
};
{ .frag = NULL,
.frag_len = 0,
.commit = 0,
.end = 0,
.pending = 0,
.acc = NULL,
.acc_len = 0,
.acc_available = 0,
.acc_share = { .acc_remaining = 0 } };
*rd = zero;
}
int mbedtls_mps_reader_init( mbedtls_mps_reader *rd,
unsigned char *acc,
mbedtls_mps_size_t acc_len )
int mbedtls_mps_reader_init(mbedtls_mps_reader *rd,
unsigned char *acc,
mbedtls_mps_size_t acc_len)
{
MBEDTLS_MPS_TRACE_INIT( "mbedtls_mps_reader_init" );
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"* Accumulator size: %u bytes", (unsigned) acc_len );
mps_reader_zero( rd );
MBEDTLS_MPS_TRACE_INIT("mbedtls_mps_reader_init");
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"* Accumulator size: %u bytes", (unsigned) acc_len);
mps_reader_zero(rd);
rd->acc = acc;
rd->acc_len = acc_len;
MBEDTLS_MPS_TRACE_RETURN( 0 );
MBEDTLS_MPS_TRACE_RETURN(0);
}
int mbedtls_mps_reader_free( mbedtls_mps_reader *rd )
int mbedtls_mps_reader_free(mbedtls_mps_reader *rd)
{
MBEDTLS_MPS_TRACE_INIT( "mbedtls_mps_reader_free" );
mps_reader_zero( rd );
MBEDTLS_MPS_TRACE_RETURN( 0 );
MBEDTLS_MPS_TRACE_INIT("mbedtls_mps_reader_free");
mps_reader_zero(rd);
MBEDTLS_MPS_TRACE_RETURN(0);
}
int mbedtls_mps_reader_feed( mbedtls_mps_reader *rd,
unsigned char *new_frag,
mbedtls_mps_size_t new_frag_len )
int mbedtls_mps_reader_feed(mbedtls_mps_reader *rd,
unsigned char *new_frag,
mbedtls_mps_size_t new_frag_len)
{
mbedtls_mps_size_t copy_to_acc;
MBEDTLS_MPS_TRACE_INIT( "mbedtls_mps_reader_feed" );
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"* Fragment length: %u bytes", (unsigned) new_frag_len );
MBEDTLS_MPS_TRACE_INIT("mbedtls_mps_reader_feed");
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"* Fragment length: %u bytes", (unsigned) new_frag_len);
if( new_frag == NULL )
MBEDTLS_MPS_TRACE_RETURN( MBEDTLS_ERR_MPS_READER_INVALID_ARG );
if (new_frag == NULL) {
MBEDTLS_MPS_TRACE_RETURN(MBEDTLS_ERR_MPS_READER_INVALID_ARG);
}
MBEDTLS_MPS_STATE_VALIDATE_RAW( mps_reader_is_producing( rd ),
"mbedtls_mps_reader_feed() requires reader to be in producing mode" );
MBEDTLS_MPS_STATE_VALIDATE_RAW(mps_reader_is_producing(
rd),
"mbedtls_mps_reader_feed() requires reader to be in producing mode");
if( mps_reader_is_accumulating( rd ) )
{
if (mps_reader_is_accumulating(rd)) {
unsigned char *acc = rd->acc;
mbedtls_mps_size_t acc_remaining = rd->acc_share.acc_remaining;
mbedtls_mps_size_t acc_available = rd->acc_available;
@ -181,39 +183,38 @@ int mbedtls_mps_reader_feed( mbedtls_mps_reader *rd,
acc += acc_available;
copy_to_acc = acc_remaining;
if( copy_to_acc > new_frag_len )
if (copy_to_acc > new_frag_len) {
copy_to_acc = new_frag_len;
}
/* Copy new contents to accumulator. */
memcpy( acc, new_frag, copy_to_acc );
memcpy(acc, new_frag, copy_to_acc);
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Copy new data of size %u of %u into accumulator at offset %u",
(unsigned) copy_to_acc, (unsigned) new_frag_len, (unsigned) acc_available );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Copy new data of size %u of %u into accumulator at offset %u",
(unsigned) copy_to_acc, (unsigned) new_frag_len,
(unsigned) acc_available);
/* Check if, with the new fragment, we have enough data. */
acc_remaining -= copy_to_acc;
if( acc_remaining > 0 )
{
if (acc_remaining > 0) {
/* We need to accumulate more data. Stay in producing mode. */
acc_available += copy_to_acc;
rd->acc_share.acc_remaining = acc_remaining;
rd->acc_available = acc_available;
MBEDTLS_MPS_TRACE_RETURN( MBEDTLS_ERR_MPS_READER_NEED_MORE );
MBEDTLS_MPS_TRACE_RETURN(MBEDTLS_ERR_MPS_READER_NEED_MORE);
}
/* We have filled the accumulator: Move to consuming mode. */
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Enough data available to serve user request" );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Enough data available to serve user request");
/* Remember overlap of accumulator and fragment. */
rd->acc_share.frag_offset = acc_available;
acc_available += copy_to_acc;
rd->acc_available = acc_available;
}
else /* Not accumulating */
{
} else { /* Not accumulating */
rd->acc_share.frag_offset = 0;
}
@ -221,30 +222,30 @@ int mbedtls_mps_reader_feed( mbedtls_mps_reader *rd,
rd->frag_len = new_frag_len;
rd->commit = 0;
rd->end = 0;
MBEDTLS_MPS_TRACE_RETURN( 0 );
MBEDTLS_MPS_TRACE_RETURN(0);
}
int mbedtls_mps_reader_get( mbedtls_mps_reader *rd,
mbedtls_mps_size_t desired,
unsigned char **buffer,
mbedtls_mps_size_t *buflen )
int mbedtls_mps_reader_get(mbedtls_mps_reader *rd,
mbedtls_mps_size_t desired,
unsigned char **buffer,
mbedtls_mps_size_t *buflen)
{
unsigned char *frag;
mbedtls_mps_size_t frag_len, frag_offset, end, frag_fetched, frag_remaining;
MBEDTLS_MPS_TRACE_INIT( "mbedtls_mps_reader_get" );
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"* Bytes requested: %u", (unsigned) desired );
MBEDTLS_MPS_TRACE_INIT("mbedtls_mps_reader_get");
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"* Bytes requested: %u", (unsigned) desired);
MBEDTLS_MPS_STATE_VALIDATE_RAW( mps_reader_is_consuming( rd ),
"mbedtls_mps_reader_get() requires reader to be in consuming mode" );
MBEDTLS_MPS_STATE_VALIDATE_RAW(mps_reader_is_consuming(
rd),
"mbedtls_mps_reader_get() requires reader to be in consuming mode");
end = rd->end;
frag_offset = mps_reader_get_fragment_offset( rd );
frag_offset = mps_reader_get_fragment_offset(rd);
/* Check if we're still serving from the accumulator. */
if( mps_reader_serving_from_accumulator( rd ) )
{
if (mps_reader_serving_from_accumulator(rd)) {
/* Illustration of supported and unsupported cases:
*
* - Allowed #1
@ -310,14 +311,12 @@ int mbedtls_mps_reader_get( mbedtls_mps_reader *rd,
unsigned char *acc;
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Serve the request from the accumulator" );
if( frag_offset - end < desired )
{
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Serve the request from the accumulator");
if (frag_offset - end < desired) {
mbedtls_mps_size_t acc_available;
acc_available = rd->acc_available;
if( acc_available - end != desired )
{
if (acc_available - end != desired) {
/* It might be possible to serve some of these situations by
* making additional space in the accumulator, removing those
* parts that have already been committed.
@ -329,7 +328,7 @@ int mbedtls_mps_reader_get( mbedtls_mps_reader *rd,
* the library, this check is a good opportunity to
* validate this. */
MBEDTLS_MPS_TRACE_RETURN(
MBEDTLS_ERR_MPS_READER_INCONSISTENT_REQUESTS );
MBEDTLS_ERR_MPS_READER_INCONSISTENT_REQUESTS);
}
}
@ -337,19 +336,20 @@ int mbedtls_mps_reader_get( mbedtls_mps_reader *rd,
acc += end;
*buffer = acc;
if( buflen != NULL )
if (buflen != NULL) {
*buflen = desired;
}
end += desired;
rd->end = end;
rd->pending = 0;
MBEDTLS_MPS_TRACE_RETURN( 0 );
MBEDTLS_MPS_TRACE_RETURN(0);
}
/* Attempt to serve the request from the current fragment */
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Serve the request from the current fragment." );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Serve the request from the current fragment.");
frag_len = rd->frag_len;
frag_fetched = end - frag_offset; /* The amount of data from the current
@ -358,23 +358,20 @@ int mbedtls_mps_reader_get( mbedtls_mps_reader *rd,
frag_remaining = frag_len - frag_fetched; /* Remaining data in fragment */
/* Check if we can serve the read request from the fragment. */
if( frag_remaining < desired )
{
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"There's not enough data in the current fragment "
"to serve the request." );
if (frag_remaining < desired) {
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"There's not enough data in the current fragment "
"to serve the request.");
/* There's not enough data in the current fragment,
* so either just RETURN what we have or fail. */
if( buflen == NULL )
{
if( frag_remaining > 0 )
{
if (buflen == NULL) {
if (frag_remaining > 0) {
rd->pending = desired - frag_remaining;
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Remember to collect %u bytes before re-opening",
(unsigned) rd->pending );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Remember to collect %u bytes before re-opening",
(unsigned) rd->pending);
}
MBEDTLS_MPS_TRACE_RETURN( MBEDTLS_ERR_MPS_READER_OUT_OF_DATA );
MBEDTLS_MPS_TRACE_RETURN(MBEDTLS_ERR_MPS_READER_OUT_OF_DATA);
}
desired = frag_remaining;
@ -387,41 +384,45 @@ int mbedtls_mps_reader_get( mbedtls_mps_reader *rd,
frag += frag_fetched;
*buffer = frag;
if( buflen != NULL )
if (buflen != NULL) {
*buflen = desired;
}
end += desired;
rd->end = end;
rd->pending = 0;
MBEDTLS_MPS_TRACE_RETURN( 0 );
MBEDTLS_MPS_TRACE_RETURN(0);
}
int mbedtls_mps_reader_commit( mbedtls_mps_reader *rd )
int mbedtls_mps_reader_commit(mbedtls_mps_reader *rd)
{
mbedtls_mps_size_t end;
MBEDTLS_MPS_TRACE_INIT( "mbedtls_mps_reader_commit" );
MBEDTLS_MPS_STATE_VALIDATE_RAW( mps_reader_is_consuming( rd ),
"mbedtls_mps_reader_commit() requires reader to be in consuming mode" );
MBEDTLS_MPS_TRACE_INIT("mbedtls_mps_reader_commit");
MBEDTLS_MPS_STATE_VALIDATE_RAW(mps_reader_is_consuming(
rd),
"mbedtls_mps_reader_commit() requires reader to be in consuming mode");
end = rd->end;
rd->commit = end;
MBEDTLS_MPS_TRACE_RETURN( 0 );
MBEDTLS_MPS_TRACE_RETURN(0);
}
int mbedtls_mps_reader_reclaim( mbedtls_mps_reader *rd,
int *paused )
int mbedtls_mps_reader_reclaim(mbedtls_mps_reader *rd,
int *paused)
{
unsigned char *frag, *acc;
mbedtls_mps_size_t pending, commit;
mbedtls_mps_size_t acc_len, frag_offset, frag_len;
MBEDTLS_MPS_TRACE_INIT( "mbedtls_mps_reader_reclaim" );
MBEDTLS_MPS_TRACE_INIT("mbedtls_mps_reader_reclaim");
if( paused != NULL )
if (paused != NULL) {
*paused = 0;
}
MBEDTLS_MPS_STATE_VALIDATE_RAW( mps_reader_is_consuming( rd ),
"mbedtls_mps_reader_reclaim() requires reader to be in consuming mode" );
MBEDTLS_MPS_STATE_VALIDATE_RAW(mps_reader_is_consuming(
rd),
"mbedtls_mps_reader_reclaim() requires reader to be in consuming mode");
frag = rd->frag;
acc = rd->acc;
@ -429,30 +430,26 @@ int mbedtls_mps_reader_reclaim( mbedtls_mps_reader *rd,
commit = rd->commit;
frag_len = rd->frag_len;
frag_offset = mps_reader_get_fragment_offset( rd );
frag_offset = mps_reader_get_fragment_offset(rd);
if( pending == 0 )
{
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"No unsatisfied read-request has been logged." );
if (pending == 0) {
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"No unsatisfied read-request has been logged.");
/* Check if there's data left to be consumed. */
if( commit < frag_offset || commit - frag_offset < frag_len )
{
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"There is data left to be consumed." );
if (commit < frag_offset || commit - frag_offset < frag_len) {
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"There is data left to be consumed.");
rd->end = commit;
MBEDTLS_MPS_TRACE_RETURN( MBEDTLS_ERR_MPS_READER_DATA_LEFT );
MBEDTLS_MPS_TRACE_RETURN(MBEDTLS_ERR_MPS_READER_DATA_LEFT);
}
rd->acc_available = 0;
rd->acc_share.acc_remaining = 0;
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Fragment has been fully processed and committed." );
}
else
{
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Fragment has been fully processed and committed.");
} else {
int overflow;
mbedtls_mps_size_t acc_backup_offset;
@ -463,31 +460,27 @@ int mbedtls_mps_reader_reclaim( mbedtls_mps_reader *rd,
mbedtls_mps_size_t backup_len;
mbedtls_mps_size_t acc_len_needed;
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"There has been an unsatisfied read with %u bytes overhead.",
(unsigned) pending );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"There has been an unsatisfied read with %u bytes overhead.",
(unsigned) pending);
if( acc == NULL )
{
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"No accumulator present" );
if (acc == NULL) {
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"No accumulator present");
MBEDTLS_MPS_TRACE_RETURN(
MBEDTLS_ERR_MPS_READER_NEED_ACCUMULATOR );
MBEDTLS_ERR_MPS_READER_NEED_ACCUMULATOR);
}
acc_len = rd->acc_len;
/* Check if the upper layer has already fetched
* and committed the contents of the accumulator. */
if( commit < frag_offset )
{
if (commit < frag_offset) {
/* No, accumulator is still being processed. */
frag_backup_offset = 0;
frag_backup_len = frag_len;
acc_backup_offset = commit;
acc_backup_len = frag_offset - commit;
}
else
{
} else {
/* Yes, the accumulator is already processed. */
frag_backup_offset = commit - frag_offset;
frag_backup_len = frag_len - frag_backup_offset;
@ -499,47 +492,47 @@ int mbedtls_mps_reader_reclaim( mbedtls_mps_reader *rd,
acc_len_needed = backup_len + pending;
overflow = 0;
overflow |= ( backup_len < acc_backup_len );
overflow |= ( acc_len_needed < backup_len );
overflow |= (backup_len < acc_backup_len);
overflow |= (acc_len_needed < backup_len);
if( overflow || acc_len < acc_len_needed )
{
if (overflow || acc_len < acc_len_needed) {
/* Except for the different return code, we behave as if
* there hadn't been a call to mbedtls_mps_reader_get()
* since the last commit. */
rd->end = commit;
rd->pending = 0;
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_ERROR,
"The accumulator is too small to handle the backup." );
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_ERROR,
"* Size: %u", (unsigned) acc_len );
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_ERROR,
"* Needed: %u (%u + %u)",
(unsigned) acc_len_needed,
(unsigned) backup_len, (unsigned) pending );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_ERROR,
"The accumulator is too small to handle the backup.");
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_ERROR,
"* Size: %u", (unsigned) acc_len);
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_ERROR,
"* Needed: %u (%u + %u)",
(unsigned) acc_len_needed,
(unsigned) backup_len, (unsigned) pending);
MBEDTLS_MPS_TRACE_RETURN(
MBEDTLS_ERR_MPS_READER_ACCUMULATOR_TOO_SMALL );
MBEDTLS_ERR_MPS_READER_ACCUMULATOR_TOO_SMALL);
}
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Fragment backup: %u", (unsigned) frag_backup_len );
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Accumulator backup: %u", (unsigned) acc_backup_len );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Fragment backup: %u", (unsigned) frag_backup_len);
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Accumulator backup: %u", (unsigned) acc_backup_len);
/* Move uncommitted parts from the accumulator to the front
* of the accumulator. */
memmove( acc, acc + acc_backup_offset, acc_backup_len );
memmove(acc, acc + acc_backup_offset, acc_backup_len);
/* Copy uncommitted parts of the current fragment to the
* accumulator. */
memcpy( acc + acc_backup_len,
frag + frag_backup_offset, frag_backup_len );
memcpy(acc + acc_backup_len,
frag + frag_backup_offset, frag_backup_len);
rd->acc_available = backup_len;
rd->acc_share.acc_remaining = pending;
if( paused != NULL )
if (paused != NULL) {
*paused = 1;
}
}
rd->frag = NULL;
@ -549,11 +542,11 @@ int mbedtls_mps_reader_reclaim( mbedtls_mps_reader *rd,
rd->end = 0;
rd->pending = 0;
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Final state: aa %u, al %u, ar %u",
(unsigned) rd->acc_available, (unsigned) rd->acc_len,
(unsigned) rd->acc_share.acc_remaining );
MBEDTLS_MPS_TRACE_RETURN( 0 );
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_COMMENT,
"Final state: aa %u, al %u, ar %u",
(unsigned) rd->acc_available, (unsigned) rd->acc_len,
(unsigned) rd->acc_share.acc_remaining);
MBEDTLS_MPS_TRACE_RETURN(0);
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */

View File

@ -134,8 +134,7 @@ typedef struct mbedtls_mps_reader mbedtls_mps_reader;
* Structure definitions
*/
struct mbedtls_mps_reader
{
struct mbedtls_mps_reader {
unsigned char *frag; /*!< The fragment of incoming data managed by
* the reader; it is provided to the reader
* through mbedtls_mps_reader_feed(). The reader
@ -146,46 +145,46 @@ struct mbedtls_mps_reader
* The reader is in consuming mode if
* and only if \c frag is not \c NULL. */
mbedtls_mps_stored_size_t frag_len;
/*!< The length of the current fragment.
* Must be 0 if \c frag == \c NULL. */
/*!< The length of the current fragment.
* Must be 0 if \c frag == \c NULL. */
mbedtls_mps_stored_size_t commit;
/*!< The offset of the last commit, relative
* to the first byte in the fragment, if
* no accumulator is present. If an accumulator
* is present, it is viewed as a prefix to the
* current fragment, and this variable contains
* an offset from the beginning of the accumulator.
*
* This is only used when the reader is in
* consuming mode, i.e. \c frag != \c NULL;
* otherwise, its value is \c 0. */
/*!< The offset of the last commit, relative
* to the first byte in the fragment, if
* no accumulator is present. If an accumulator
* is present, it is viewed as a prefix to the
* current fragment, and this variable contains
* an offset from the beginning of the accumulator.
*
* This is only used when the reader is in
* consuming mode, i.e. \c frag != \c NULL;
* otherwise, its value is \c 0. */
mbedtls_mps_stored_size_t end;
/*!< The offset of the end of the last chunk
* passed to the user through a call to
* mbedtls_mps_reader_get(), relative to the first
* byte in the fragment, if no accumulator is
* present. If an accumulator is present, it is
* viewed as a prefix to the current fragment, and
* this variable contains an offset from the
* beginning of the accumulator.
*
* This is only used when the reader is in
* consuming mode, i.e. \c frag != \c NULL;
* otherwise, its value is \c 0. */
/*!< The offset of the end of the last chunk
* passed to the user through a call to
* mbedtls_mps_reader_get(), relative to the first
* byte in the fragment, if no accumulator is
* present. If an accumulator is present, it is
* viewed as a prefix to the current fragment, and
* this variable contains an offset from the
* beginning of the accumulator.
*
* This is only used when the reader is in
* consuming mode, i.e. \c frag != \c NULL;
* otherwise, its value is \c 0. */
mbedtls_mps_stored_size_t pending;
/*!< The amount of incoming data missing on the
* last call to mbedtls_mps_reader_get().
* In particular, it is \c 0 if the last call
* was successful.
* If a reader is reclaimed after an
* unsuccessful call to mbedtls_mps_reader_get(),
* this variable is used to have the reader
* remember how much data should be accumulated
* so that the call to mbedtls_mps_reader_get()
* succeeds next time.
* This is only used when the reader is in
* consuming mode, i.e. \c frag != \c NULL;
* otherwise, its value is \c 0. */
/*!< The amount of incoming data missing on the
* last call to mbedtls_mps_reader_get().
* In particular, it is \c 0 if the last call
* was successful.
* If a reader is reclaimed after an
* unsuccessful call to mbedtls_mps_reader_get(),
* this variable is used to have the reader
* remember how much data should be accumulated
* so that the call to mbedtls_mps_reader_get()
* succeeds next time.
* This is only used when the reader is in
* consuming mode, i.e. \c frag != \c NULL;
* otherwise, its value is \c 0. */
/* The accumulator is only needed if we need to be able to pause
* the reader. A few bytes could be saved by moving this to a
@ -195,32 +194,31 @@ struct mbedtls_mps_reader
* data if a read-request via mbedtls_mps_reader_get()
* cannot be served from the current fragment. */
mbedtls_mps_stored_size_t acc_len;
/*!< The total size of the accumulator. */
/*!< The total size of the accumulator. */
mbedtls_mps_stored_size_t acc_available;
/*!< The number of bytes currently gathered in
* the accumulator. This is both used in
* producing and in consuming mode:
* While producing, it is increased until
* it reaches the value of \c acc_remaining below.
* While consuming, it is used to judge if a
* get request can be served from the
* accumulator or not.
* Must not be larger than \c acc_len. */
union
{
/*!< The number of bytes currently gathered in
* the accumulator. This is both used in
* producing and in consuming mode:
* While producing, it is increased until
* it reaches the value of \c acc_remaining below.
* While consuming, it is used to judge if a
* get request can be served from the
* accumulator or not.
* Must not be larger than \c acc_len. */
union {
mbedtls_mps_stored_size_t acc_remaining;
/*!< This indicates the amount of data still
* to be gathered in the accumulator. It is
* only used in producing mode.
* Must be at most acc_len - acc_available. */
/*!< This indicates the amount of data still
* to be gathered in the accumulator. It is
* only used in producing mode.
* Must be at most acc_len - acc_available. */
mbedtls_mps_stored_size_t frag_offset;
/*!< If an accumulator is present and in use, this
* field indicates the offset of the current
* fragment from the beginning of the
* accumulator. If no accumulator is present
* or the accumulator is not in use, this is \c 0.
* It is only used in consuming mode.
* Must not be larger than \c acc_available. */
/*!< If an accumulator is present and in use, this
* field indicates the offset of the current
* fragment from the beginning of the
* accumulator. If no accumulator is present
* or the accumulator is not in use, this is \c 0.
* It is only used in consuming mode.
* Must not be larger than \c acc_available. */
} acc_share;
};
@ -254,9 +252,9 @@ struct mbedtls_mps_reader
* \return \c 0 on success.
* \return A negative \c MBEDTLS_ERR_READER_XXX error code on failure.
*/
int mbedtls_mps_reader_init( mbedtls_mps_reader *reader,
unsigned char *acc,
mbedtls_mps_size_t acc_len );
int mbedtls_mps_reader_init(mbedtls_mps_reader *reader,
unsigned char *acc,
mbedtls_mps_size_t acc_len);
/**
* \brief Free a reader object
@ -266,7 +264,7 @@ int mbedtls_mps_reader_init( mbedtls_mps_reader *reader,
* \return \c 0 on success.
* \return A negative \c MBEDTLS_ERR_READER_XXX error code on failure.
*/
int mbedtls_mps_reader_free( mbedtls_mps_reader *reader );
int mbedtls_mps_reader_free(mbedtls_mps_reader *reader);
/**
* \brief Pass chunk of data for the reader to manage.
@ -291,9 +289,9 @@ int mbedtls_mps_reader_free( mbedtls_mps_reader *reader );
* \return Another negative \c MBEDTLS_ERR_READER_XXX error code on
* different kinds of failures.
*/
int mbedtls_mps_reader_feed( mbedtls_mps_reader *reader,
unsigned char *buf,
mbedtls_mps_size_t buflen );
int mbedtls_mps_reader_feed(mbedtls_mps_reader *reader,
unsigned char *buf,
mbedtls_mps_size_t buflen);
/**
* \brief Reclaim reader's access to the current input buffer.
@ -310,8 +308,8 @@ int mbedtls_mps_reader_feed( mbedtls_mps_reader *reader,
* \return \c 0 on success.
* \return A negative \c MBEDTLS_ERR_READER_XXX error code on failure.
*/
int mbedtls_mps_reader_reclaim( mbedtls_mps_reader *reader,
int *paused );
int mbedtls_mps_reader_reclaim(mbedtls_mps_reader *reader,
int *paused);
/*
* Usage API (Upper layer)
@ -353,10 +351,10 @@ int mbedtls_mps_reader_reclaim( mbedtls_mps_reader *reader,
* address as buflen and checking \c *buflen == \c desired
* afterwards.
*/
int mbedtls_mps_reader_get( mbedtls_mps_reader *reader,
mbedtls_mps_size_t desired,
unsigned char **buffer,
mbedtls_mps_size_t *buflen );
int mbedtls_mps_reader_get(mbedtls_mps_reader *reader,
mbedtls_mps_size_t desired,
unsigned char **buffer,
mbedtls_mps_size_t *buflen);
/**
* \brief Mark data obtained from mbedtls_mps_reader_get() as processed.
@ -377,6 +375,6 @@ int mbedtls_mps_reader_get( mbedtls_mps_reader *reader,
* \return A negative \c MBEDTLS_ERR_READER_XXX error code on failure.
*
*/
int mbedtls_mps_reader_commit( mbedtls_mps_reader *reader );
int mbedtls_mps_reader_commit(mbedtls_mps_reader *reader);
#endif /* MBEDTLS_READER_H */

View File

@ -41,7 +41,7 @@ static int trace_depth = 0;
#define color_cyan "\x1B[1;36m"
#define color_white "\x1B[1;37m"
static char const * colors[] =
static char const *colors[] =
{
color_default,
color_green,
@ -54,19 +54,18 @@ static char const * colors[] =
#define MPS_TRACE_BUF_SIZE 100
void mbedtls_mps_trace_print_msg( int id, int line, const char *format, ... )
void mbedtls_mps_trace_print_msg(int id, int line, const char *format, ...)
{
int ret;
char str[MPS_TRACE_BUF_SIZE];
va_list argp;
va_start( argp, format );
ret = mbedtls_vsnprintf( str, MPS_TRACE_BUF_SIZE, format, argp );
va_end( argp );
va_start(argp, format);
ret = mbedtls_vsnprintf(str, MPS_TRACE_BUF_SIZE, format, argp);
va_end(argp);
if( ret >= 0 && ret < MPS_TRACE_BUF_SIZE )
{
if (ret >= 0 && ret < MPS_TRACE_BUF_SIZE) {
str[ret] = '\0';
mbedtls_printf( "[%d|L%d]: %s\n", id, line, str );
mbedtls_printf("[%d|L%d]: %s\n", id, line, str);
}
}
@ -83,39 +82,39 @@ void mbedtls_mps_trace_inc_depth()
trace_depth++;
}
void mbedtls_mps_trace_color( int id )
void mbedtls_mps_trace_color(int id)
{
if( id > (int) ( sizeof( colors ) / sizeof( *colors ) ) )
if (id > (int) (sizeof(colors) / sizeof(*colors))) {
return;
printf( "%s", colors[ id ] );
}
printf("%s", colors[id]);
}
void mbedtls_mps_trace_indent( int level, mbedtls_mps_trace_type ty )
void mbedtls_mps_trace_indent(int level, mbedtls_mps_trace_type ty)
{
if( level > 0 )
{
while( --level )
printf( "| " );
if (level > 0) {
while (--level) {
printf("| ");
}
printf( "| " );
printf("| ");
}
switch( ty )
{
switch (ty) {
case MBEDTLS_MPS_TRACE_TYPE_COMMENT:
mbedtls_printf( "@ " );
mbedtls_printf("@ ");
break;
case MBEDTLS_MPS_TRACE_TYPE_CALL:
mbedtls_printf( "+--> " );
mbedtls_printf("+--> ");
break;
case MBEDTLS_MPS_TRACE_TYPE_ERROR:
mbedtls_printf( "E " );
mbedtls_printf("E ");
break;
case MBEDTLS_MPS_TRACE_TYPE_RETURN:
mbedtls_printf( "< " );
mbedtls_printf("< ");
break;
default:

View File

@ -52,8 +52,7 @@
* rest of this file.
*/
typedef enum
{
typedef enum {
MBEDTLS_MPS_TRACE_TYPE_COMMENT,
MBEDTLS_MPS_TRACE_TYPE_CALL,
MBEDTLS_MPS_TRACE_TYPE_ERROR,
@ -68,101 +67,101 @@ typedef enum
#define MBEDTLS_MPS_TRACE_BIT_READER 6
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_1)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_1 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_1 )
#define MBEDTLS_MPS_TRACE_MASK_LAYER_1 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_1)
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_1 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_2)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_2 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_2 )
#define MBEDTLS_MPS_TRACE_MASK_LAYER_2 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_2)
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_2 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_3)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_3 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_3 )
#define MBEDTLS_MPS_TRACE_MASK_LAYER_3 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_3)
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_3 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_4)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_4 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_4 )
#define MBEDTLS_MPS_TRACE_MASK_LAYER_4 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_4)
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_4 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_READER)
#define MBEDTLS_MPS_TRACE_MASK_READER (1u << MBEDTLS_MPS_TRACE_BIT_READER )
#define MBEDTLS_MPS_TRACE_MASK_READER (1u << MBEDTLS_MPS_TRACE_BIT_READER)
#else
#define MBEDTLS_MPS_TRACE_MASK_READER 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_WRITER)
#define MBEDTLS_MPS_TRACE_MASK_WRITER (1u << MBEDTLS_MPS_TRACE_BIT_WRITER )
#define MBEDTLS_MPS_TRACE_MASK_WRITER (1u << MBEDTLS_MPS_TRACE_BIT_WRITER)
#else
#define MBEDTLS_MPS_TRACE_MASK_WRITER 0
#endif
#define MBEDTLS_MPS_TRACE_MASK ( MBEDTLS_MPS_TRACE_MASK_LAYER_1 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_2 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_3 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_4 | \
MBEDTLS_MPS_TRACE_MASK_READER | \
MBEDTLS_MPS_TRACE_MASK_WRITER )
#define MBEDTLS_MPS_TRACE_MASK (MBEDTLS_MPS_TRACE_MASK_LAYER_1 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_2 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_3 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_4 | \
MBEDTLS_MPS_TRACE_MASK_READER | \
MBEDTLS_MPS_TRACE_MASK_WRITER)
/* We have to avoid globals because E-ACSL chokes on them...
* Wrap everything in stub functions. */
int mbedtls_mps_trace_get_depth( void );
void mbedtls_mps_trace_inc_depth( void );
void mbedtls_mps_trace_dec_depth( void );
int mbedtls_mps_trace_get_depth(void);
void mbedtls_mps_trace_inc_depth(void);
void mbedtls_mps_trace_dec_depth(void);
void mbedtls_mps_trace_color( int id );
void mbedtls_mps_trace_indent( int level, mbedtls_mps_trace_type ty );
void mbedtls_mps_trace_color(int id);
void mbedtls_mps_trace_indent(int level, mbedtls_mps_trace_type ty);
void mbedtls_mps_trace_print_msg( int id, int line, const char *format, ... );
void mbedtls_mps_trace_print_msg(int id, int line, const char *format, ...);
#define MBEDTLS_MPS_TRACE( type, ... ) \
#define MBEDTLS_MPS_TRACE(type, ...) \
do { \
if( ! ( MBEDTLS_MPS_TRACE_MASK & ( 1u << mbedtls_mps_trace_id ) ) ) \
break; \
mbedtls_mps_trace_indent( mbedtls_mps_trace_get_depth(), type ); \
mbedtls_mps_trace_color( mbedtls_mps_trace_id ); \
mbedtls_mps_trace_print_msg( mbedtls_mps_trace_id, __LINE__, __VA_ARGS__ ); \
mbedtls_mps_trace_color( 0 ); \
} while( 0 )
if (!(MBEDTLS_MPS_TRACE_MASK & (1u << mbedtls_mps_trace_id))) \
break; \
mbedtls_mps_trace_indent(mbedtls_mps_trace_get_depth(), type); \
mbedtls_mps_trace_color(mbedtls_mps_trace_id); \
mbedtls_mps_trace_print_msg(mbedtls_mps_trace_id, __LINE__, __VA_ARGS__); \
mbedtls_mps_trace_color(0); \
} while (0)
#define MBEDTLS_MPS_TRACE_INIT( ... ) \
#define MBEDTLS_MPS_TRACE_INIT(...) \
do { \
if( ! ( MBEDTLS_MPS_TRACE_MASK & ( 1u << mbedtls_mps_trace_id ) ) ) \
break; \
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_CALL, __VA_ARGS__ ); \
if (!(MBEDTLS_MPS_TRACE_MASK & (1u << mbedtls_mps_trace_id))) \
break; \
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_CALL, __VA_ARGS__); \
mbedtls_mps_trace_inc_depth(); \
} while( 0 )
} while (0)
#define MBEDTLS_MPS_TRACE_END( val ) \
#define MBEDTLS_MPS_TRACE_END(val) \
do { \
if( ! ( MBEDTLS_MPS_TRACE_MASK & ( 1u << mbedtls_mps_trace_id ) ) ) \
break; \
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_RETURN, "%d (-%#04x)", \
(int) (val), -((unsigned)(val)) ); \
if (!(MBEDTLS_MPS_TRACE_MASK & (1u << mbedtls_mps_trace_id))) \
break; \
MBEDTLS_MPS_TRACE(MBEDTLS_MPS_TRACE_TYPE_RETURN, "%d (-%#04x)", \
(int) (val), -((unsigned) (val))); \
mbedtls_mps_trace_dec_depth(); \
} while( 0 )
} while (0)
#define MBEDTLS_MPS_TRACE_RETURN( val ) \
#define MBEDTLS_MPS_TRACE_RETURN(val) \
do { \
/* Breaks tail recursion. */ \
int ret__ = val; \
MBEDTLS_MPS_TRACE_END( ret__ ); \
return( ret__ ); \
} while( 0 )
MBEDTLS_MPS_TRACE_END(ret__); \
return ret__; \
} while (0)
#else /* MBEDTLS_MPS_TRACE */
#define MBEDTLS_MPS_TRACE( type, ... ) do { } while( 0 )
#define MBEDTLS_MPS_TRACE_INIT( ... ) do { } while( 0 )
#define MBEDTLS_MPS_TRACE_END do { } while( 0 )
#define MBEDTLS_MPS_TRACE(type, ...) do { } while (0)
#define MBEDTLS_MPS_TRACE_INIT(...) do { } while (0)
#define MBEDTLS_MPS_TRACE_END do { } while (0)
#define MBEDTLS_MPS_TRACE_RETURN( val ) return( val );
#define MBEDTLS_MPS_TRACE_RETURN(val) return val;
#endif /* MBEDTLS_MPS_TRACE */

View File

@ -47,7 +47,7 @@
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
#define IS_EINTR( ret ) ( ( ret ) == WSAEINTR )
#define IS_EINTR(ret) ((ret) == WSAEINTR)
#if !defined(_WIN32_WINNT)
/* Enables getaddrinfo() & Co */
@ -70,8 +70,8 @@
#endif
#endif /* _MSC_VER */
#define read(fd,buf,len) recv( fd, (char*)( buf ), (int)( len ), 0 )
#define write(fd,buf,len) send( fd, (char*)( buf ), (int)( len ), 0 )
#define read(fd, buf, len) recv(fd, (char *) (buf), (int) (len), 0)
#define write(fd, buf, len) send(fd, (char *) (buf), (int) (len), 0)
#define close(fd) closesocket(fd)
static int wsa_init_done = 0;
@ -89,7 +89,7 @@ static int wsa_init_done = 0;
#include <netdb.h>
#include <errno.h>
#define IS_EINTR( ret ) ( ( ret ) == EINTR )
#define IS_EINTR(ret) ((ret) == EINTR)
#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
@ -112,25 +112,25 @@ static int wsa_init_done = 0;
/*
* Prepare for using the sockets interface
*/
static int net_prepare( void )
static int net_prepare(void)
{
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
WSADATA wsaData;
if( wsa_init_done == 0 )
{
if( WSAStartup( MAKEWORD(2,0), &wsaData ) != 0 )
return( MBEDTLS_ERR_NET_SOCKET_FAILED );
if (wsa_init_done == 0) {
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
return MBEDTLS_ERR_NET_SOCKET_FAILED;
}
wsa_init_done = 1;
}
#else
#if !defined(EFIX64) && !defined(EFI32)
signal( SIGPIPE, SIG_IGN );
signal(SIGPIPE, SIG_IGN);
#endif
#endif
return( 0 );
return 0;
}
/*
@ -138,10 +138,11 @@ static int net_prepare( void )
* If for_select != 0, check whether the file descriptor is within the range
* allowed for fd_set used for the FD_xxx macros and the select() function.
*/
static int check_fd( int fd, int for_select )
static int check_fd(int fd, int for_select)
{
if( fd < 0 )
return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
if (fd < 0) {
return MBEDTLS_ERR_NET_INVALID_CONTEXT;
}
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
@ -151,17 +152,18 @@ static int check_fd( int fd, int for_select )
* 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( for_select && fd >= FD_SETSIZE )
return( MBEDTLS_ERR_NET_POLL_FAILED );
if (for_select && fd >= FD_SETSIZE) {
return MBEDTLS_ERR_NET_POLL_FAILED;
}
#endif
return( 0 );
return 0;
}
/*
* Initialize a context
*/
void mbedtls_net_init( mbedtls_net_context *ctx )
void mbedtls_net_init(mbedtls_net_context *ctx)
{
ctx->fd = -1;
}
@ -169,107 +171,103 @@ void mbedtls_net_init( mbedtls_net_context *ctx )
/*
* Initiate a TCP connection with host:port and the given protocol
*/
int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host,
const char *port, int proto )
int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host,
const char *port, int proto)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
struct addrinfo hints, *addr_list, *cur;
if( ( ret = net_prepare() ) != 0 )
return( ret );
if ((ret = net_prepare()) != 0) {
return ret;
}
/* Do name resolution with both IPv6 and IPv4 */
memset( &hints, 0, sizeof( hints ) );
memset(&hints, 0, 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 );
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 )
{
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, MSVC_INT_CAST cur->ai_addrlen ) == 0 )
{
if (connect(ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen) == 0) {
ret = 0;
break;
}
close( ctx->fd );
close(ctx->fd);
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}
freeaddrinfo( addr_list );
freeaddrinfo(addr_list);
return( ret );
return ret;
}
/*
* Create a listening socket on bind_ip:port
*/
int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )
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 );
if ((ret = net_prepare()) != 0) {
return ret;
}
/* Bind to IPv6 and/or IPv4, but only in the desired protocol */
memset( &hints, 0, sizeof( hints ) );
memset(&hints, 0, 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 )
if (bind_ip == NULL) {
hints.ai_flags = AI_PASSIVE;
}
if( getaddrinfo( bind_ip, port, &hints, &addr_list ) != 0 )
return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
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 )
{
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 );
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, MSVC_INT_CAST cur->ai_addrlen ) != 0 )
{
close( ctx->fd );
if (bind(ctx->fd, cur->ai_addr, MSVC_INT_CAST 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 );
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;
}
@ -280,22 +278,22 @@ int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char
break;
}
freeaddrinfo( addr_list );
freeaddrinfo(addr_list);
return( ret );
return ret;
}
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
/*
* Check if the requested operation would be blocking on a non-blocking socket
* and thus 'failed' with a negative return value.
*/
static int net_would_block( const mbedtls_net_context *ctx )
static int net_would_block(const mbedtls_net_context *ctx)
{
((void) ctx);
return( WSAGetLastError() == WSAEWOULDBLOCK );
return WSAGetLastError() == WSAEWOULDBLOCK;
}
#else
/*
@ -304,39 +302,37 @@ static int net_would_block( const mbedtls_net_context *ctx )
*
* Note: on a blocking socket this function always returns 0!
*/
static int net_would_block( const mbedtls_net_context *ctx )
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 )
{
if ((fcntl(ctx->fd, F_GETFL) & O_NONBLOCK) != O_NONBLOCK) {
errno = err;
return( 0 );
return 0;
}
switch( errno = err )
{
switch (errno = err) {
#if defined EAGAIN
case EAGAIN:
#endif
#if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
return( 1 );
return 1;
}
return( 0 );
return 0;
}
#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
/*
* Accept a connection from a remote client
*/
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 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_ERROR_CORRUPTION_DETECTED;
int type;
@ -346,132 +342,123 @@ int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
#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 );
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 );
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 (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 )
{
if (type == SOCK_STREAM) {
/* TCP: actual accept() */
ret = client_ctx->fd = (int) accept( bind_ctx->fd,
(struct sockaddr *) &client_addr, &n );
}
else
{
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 );
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 )
{
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 );
if (ret < 0) {
if (net_would_block(bind_ctx) != 0) {
return MBEDTLS_ERR_SSL_WANT_READ;
}
return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
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 )
{
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 );
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 );
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 (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 )
{
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 );
*ip_len = sizeof(addr4->sin_addr.s_addr);
if( buf_size < *ip_len )
return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
if (buf_size < *ip_len) {
return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL;
}
memcpy( client_ip, &addr4->sin_addr.s_addr, *ip_len );
}
else
{
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 );
*ip_len = sizeof(addr6->sin6_addr.s6_addr);
if( buf_size < *ip_len )
return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
if (buf_size < *ip_len) {
return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL;
}
memcpy( client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
memcpy(client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
}
}
return( 0 );
return 0;
}
/*
* Set the socket blocking or non-blocking
*/
int mbedtls_net_set_block( mbedtls_net_context *ctx )
int mbedtls_net_set_block(mbedtls_net_context *ctx)
{
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
u_long n = 0;
return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
return ioctlsocket(ctx->fd, FIONBIO, &n);
#else
return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) & ~O_NONBLOCK ) );
return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) & ~O_NONBLOCK);
#endif
}
int mbedtls_net_set_nonblock( mbedtls_net_context *ctx )
int mbedtls_net_set_nonblock(mbedtls_net_context *ctx)
{
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
u_long n = 1;
return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
return ioctlsocket(ctx->fd, FIONBIO, &n);
#else
return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ) );
return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) | O_NONBLOCK);
#endif
}
@ -479,7 +466,7 @@ int mbedtls_net_set_nonblock( mbedtls_net_context *ctx )
* Check if data is available on the socket
*/
int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout )
int mbedtls_net_poll(mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
struct timeval tv;
@ -489,207 +476,220 @@ int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout )
int fd = ctx->fd;
ret = check_fd( fd, 1 );
if( ret != 0 )
return( ret );
ret = check_fd(fd, 1);
if (ret != 0) {
return ret;
}
#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. */
memset( &read_fds, 0, sizeof( read_fds ) );
memset( &write_fds, 0, sizeof( write_fds ) );
memset(&read_fds, 0, sizeof(read_fds));
memset(&write_fds, 0, sizeof(write_fds));
#endif
#endif
FD_ZERO( &read_fds );
if( rw & MBEDTLS_NET_POLL_READ )
{
FD_ZERO(&read_fds);
if (rw & MBEDTLS_NET_POLL_READ) {
rw &= ~MBEDTLS_NET_POLL_READ;
FD_SET( fd, &read_fds );
FD_SET(fd, &read_fds);
}
FD_ZERO( &write_fds );
if( rw & MBEDTLS_NET_POLL_WRITE )
{
FD_ZERO(&write_fds);
if (rw & MBEDTLS_NET_POLL_WRITE) {
rw &= ~MBEDTLS_NET_POLL_WRITE;
FD_SET( fd, &write_fds );
FD_SET(fd, &write_fds);
}
if( rw != 0 )
return( MBEDTLS_ERR_NET_BAD_INPUT_DATA );
if (rw != 0) {
return MBEDTLS_ERR_NET_BAD_INPUT_DATA;
}
tv.tv_sec = timeout / 1000;
tv.tv_usec = ( timeout % 1000 ) * 1000;
tv.tv_usec = (timeout % 1000) * 1000;
do
{
ret = select( fd + 1, &read_fds, &write_fds, NULL,
timeout == (uint32_t) -1 ? NULL : &tv );
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;
}
while( IS_EINTR( ret ) );
if( ret < 0 )
return( MBEDTLS_ERR_NET_POLL_FAILED );
ret = 0;
if( FD_ISSET( fd, &read_fds ) )
if (FD_ISSET(fd, &read_fds)) {
ret |= MBEDTLS_NET_POLL_READ;
if( FD_ISSET( fd, &write_fds ) )
}
if (FD_ISSET(fd, &write_fds)) {
ret |= MBEDTLS_NET_POLL_WRITE;
}
return( ret );
return ret;
}
/*
* Portable usleep helper
*/
void mbedtls_net_usleep( unsigned long usec )
void mbedtls_net_usleep(unsigned long usec)
{
#if defined(_WIN32)
Sleep( ( usec + 999 ) / 1000 );
Sleep((usec + 999) / 1000);
#else
struct timeval tv;
tv.tv_sec = usec / 1000000;
#if defined(__unix__) || defined(__unix) || \
( defined(__APPLE__) && defined(__MACH__) )
(defined(__APPLE__) && defined(__MACH__))
tv.tv_usec = (suseconds_t) usec % 1000000;
#else
tv.tv_usec = usec % 1000000;
#endif
select( 0, NULL, NULL, NULL, &tv );
select(0, NULL, NULL, NULL, &tv);
#endif
}
/*
* Read at most 'len' characters
*/
int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )
int mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int fd = ((mbedtls_net_context *) ctx)->fd;
ret = check_fd( fd, 0 );
if( ret != 0 )
return( ret );
ret = (int) read( fd, buf, len );
if( ret < 0 )
{
if( net_would_block( ctx ) != 0 )
return( MBEDTLS_ERR_SSL_WANT_READ );
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
!defined(EFI32)
if( WSAGetLastError() == WSAECONNRESET )
return( MBEDTLS_ERR_NET_CONN_RESET );
#else
if( errno == EPIPE || errno == ECONNRESET )
return( MBEDTLS_ERR_NET_CONN_RESET );
if( errno == EINTR )
return( MBEDTLS_ERR_SSL_WANT_READ );
#endif
return( MBEDTLS_ERR_NET_RECV_FAILED );
ret = check_fd(fd, 0);
if (ret != 0) {
return ret;
}
return( ret );
ret = (int) read(fd, buf, len);
if (ret < 0) {
if (net_would_block(ctx) != 0) {
return MBEDTLS_ERR_SSL_WANT_READ;
}
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
if (WSAGetLastError() == WSAECONNRESET) {
return MBEDTLS_ERR_NET_CONN_RESET;
}
#else
if (errno == EPIPE || errno == ECONNRESET) {
return MBEDTLS_ERR_NET_CONN_RESET;
}
if (errno == EINTR) {
return MBEDTLS_ERR_SSL_WANT_READ;
}
#endif
return MBEDTLS_ERR_NET_RECV_FAILED;
}
return ret;
}
/*
* Read at most 'len' characters, blocking for at most 'timeout' ms
*/
int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf,
size_t len, uint32_t timeout )
int mbedtls_net_recv_timeout(void *ctx, unsigned char *buf,
size_t len, uint32_t timeout)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
struct timeval tv;
fd_set read_fds;
int fd = ((mbedtls_net_context *) ctx)->fd;
ret = check_fd( fd, 1 );
if( ret != 0 )
return( ret );
ret = check_fd(fd, 1);
if (ret != 0) {
return ret;
}
FD_ZERO( &read_fds );
FD_SET( fd, &read_fds );
FD_ZERO(&read_fds);
FD_SET(fd, &read_fds);
tv.tv_sec = timeout / 1000;
tv.tv_usec = ( timeout % 1000 ) * 1000;
tv.tv_usec = (timeout % 1000) * 1000;
ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );
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) {
return MBEDTLS_ERR_SSL_TIMEOUT;
}
if( ret < 0 )
{
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
!defined(EFI32)
if( WSAGetLastError() == WSAEINTR )
return( MBEDTLS_ERR_SSL_WANT_READ );
if (ret < 0) {
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
if (WSAGetLastError() == WSAEINTR) {
return MBEDTLS_ERR_SSL_WANT_READ;
}
#else
if( errno == EINTR )
return( MBEDTLS_ERR_SSL_WANT_READ );
if (errno == EINTR) {
return MBEDTLS_ERR_SSL_WANT_READ;
}
#endif
return( MBEDTLS_ERR_NET_RECV_FAILED );
return MBEDTLS_ERR_NET_RECV_FAILED;
}
/* This call will not block */
return( mbedtls_net_recv( ctx, buf, len ) );
return mbedtls_net_recv(ctx, buf, len);
}
/*
* Write at most 'len' characters
*/
int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )
int mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int fd = ((mbedtls_net_context *) ctx)->fd;
ret = check_fd( fd, 0 );
if( ret != 0 )
return( ret );
ret = (int) write( fd, buf, len );
if( ret < 0 )
{
if( net_would_block( ctx ) != 0 )
return( MBEDTLS_ERR_SSL_WANT_WRITE );
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
!defined(EFI32)
if( WSAGetLastError() == WSAECONNRESET )
return( MBEDTLS_ERR_NET_CONN_RESET );
#else
if( errno == EPIPE || errno == ECONNRESET )
return( MBEDTLS_ERR_NET_CONN_RESET );
if( errno == EINTR )
return( MBEDTLS_ERR_SSL_WANT_WRITE );
#endif
return( MBEDTLS_ERR_NET_SEND_FAILED );
ret = check_fd(fd, 0);
if (ret != 0) {
return ret;
}
return( ret );
ret = (int) write(fd, buf, len);
if (ret < 0) {
if (net_would_block(ctx) != 0) {
return MBEDTLS_ERR_SSL_WANT_WRITE;
}
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
if (WSAGetLastError() == WSAECONNRESET) {
return MBEDTLS_ERR_NET_CONN_RESET;
}
#else
if (errno == EPIPE || errno == ECONNRESET) {
return MBEDTLS_ERR_NET_CONN_RESET;
}
if (errno == EINTR) {
return MBEDTLS_ERR_SSL_WANT_WRITE;
}
#endif
return MBEDTLS_ERR_NET_SEND_FAILED;
}
return ret;
}
/*
* Close the connection
*/
void mbedtls_net_close( mbedtls_net_context *ctx )
void mbedtls_net_close(mbedtls_net_context *ctx)
{
if( ctx->fd == -1 )
if (ctx->fd == -1) {
return;
}
close( ctx->fd );
close(ctx->fd);
ctx->fd = -1;
}
@ -697,13 +697,14 @@ void mbedtls_net_close( mbedtls_net_context *ctx )
/*
* Gracefully close the connection
*/
void mbedtls_net_free( mbedtls_net_context *ctx )
void mbedtls_net_free(mbedtls_net_context *ctx)
{
if( ctx->fd == -1 )
if (ctx->fd == -1) {
return;
}
shutdown( ctx->fd, 2 );
close( ctx->fd );
shutdown(ctx->fd, 2);
close(ctx->fd);
ctx->fd = -1;
}

View File

@ -47,35 +47,37 @@
#define MIN_SEMIBLOCKS_COUNT 3
/*! The 64-bit default integrity check value (ICV) for KW mode. */
static const unsigned char NIST_KW_ICV1[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6};
static const unsigned char NIST_KW_ICV1[] = { 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6 };
/*! The 32-bit default integrity check value (ICV) for KWP mode. */
static const unsigned char NIST_KW_ICV2[] = {0xA6, 0x59, 0x59, 0xA6};
static const unsigned char NIST_KW_ICV2[] = { 0xA6, 0x59, 0x59, 0xA6 };
/*
* Initialize context
*/
void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx )
void mbedtls_nist_kw_init(mbedtls_nist_kw_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_nist_kw_context ) );
memset(ctx, 0, sizeof(mbedtls_nist_kw_context));
}
int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits,
const int is_wrap )
int mbedtls_nist_kw_setkey(mbedtls_nist_kw_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits,
const int is_wrap)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_cipher_info_t *cipher_info;
cipher_info = mbedtls_cipher_info_from_values( cipher,
keybits,
MBEDTLS_MODE_ECB );
if( cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
cipher_info = mbedtls_cipher_info_from_values(cipher,
keybits,
MBEDTLS_MODE_ECB);
if (cipher_info == NULL) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
if( cipher_info->block_size != 16 )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (cipher_info->block_size != 16) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
/*
* SP 800-38F currently defines AES cipher as the only block cipher allowed:
@ -86,44 +88,44 @@ int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,
* Currently we don't support other 128 bit block ciphers for key wrapping,
* such as Camellia and Aria.
*/
if( cipher != MBEDTLS_CIPHER_ID_AES )
return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
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,
is_wrap ? MBEDTLS_ENCRYPT :
MBEDTLS_DECRYPT )
) != 0 )
{
return( ret );
if (cipher != MBEDTLS_CIPHER_ID_AES) {
return MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
return( 0 );
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,
is_wrap ? MBEDTLS_ENCRYPT :
MBEDTLS_DECRYPT)
) != 0) {
return ret;
}
return 0;
}
/*
* Free context
*/
void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx )
void mbedtls_nist_kw_free(mbedtls_nist_kw_context *ctx)
{
mbedtls_cipher_free( &ctx->cipher_ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_nist_kw_context ) );
mbedtls_cipher_free(&ctx->cipher_ctx);
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_nist_kw_context));
}
/*
* Helper function for Xoring the uint64_t "t" with the encrypted A.
* Defined in NIST SP 800-38F section 6.1
*/
static void calc_a_xor_t( unsigned char A[KW_SEMIBLOCK_LENGTH], uint64_t t )
static void calc_a_xor_t(unsigned char A[KW_SEMIBLOCK_LENGTH], uint64_t t)
{
size_t i = 0;
for( i = 0; i < sizeof( t ); i++ )
{
A[i] ^= ( t >> ( ( sizeof( t ) - 1 - i ) * 8 ) ) & 0xff;
for (i = 0; i < sizeof(t); i++) {
A[i] ^= (t >> ((sizeof(t) - 1 - i) * 8)) & 0xff;
}
}
@ -131,10 +133,10 @@ static void calc_a_xor_t( unsigned char A[KW_SEMIBLOCK_LENGTH], uint64_t t )
* KW-AE as defined in SP 800-38F section 6.2
* KWP-AE as defined in SP 800-38F section 6.3
*/
int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx,
mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t *out_len, size_t out_size )
int mbedtls_nist_kw_wrap(mbedtls_nist_kw_context *ctx,
mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t *out_len, size_t out_size)
{
int ret = 0;
size_t semiblocks = 0;
@ -148,106 +150,96 @@ int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx,
/*
* Generate the String to work on
*/
if( mode == MBEDTLS_KW_MODE_KW )
{
if( out_size < in_len + KW_SEMIBLOCK_LENGTH )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (mode == MBEDTLS_KW_MODE_KW) {
if (out_size < in_len + KW_SEMIBLOCK_LENGTH) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
/*
* According to SP 800-38F Table 1, the plaintext length for KW
* must be between 2 to 2^54-1 semiblocks inclusive.
*/
if( in_len < 16 ||
if (in_len < 16 ||
#if SIZE_MAX > 0x1FFFFFFFFFFFFF8
in_len > 0x1FFFFFFFFFFFFF8 ||
#endif
in_len % KW_SEMIBLOCK_LENGTH != 0 )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
in_len % KW_SEMIBLOCK_LENGTH != 0) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
memcpy( output, NIST_KW_ICV1, KW_SEMIBLOCK_LENGTH );
memmove( output + KW_SEMIBLOCK_LENGTH, input, in_len );
}
else
{
if( in_len % 8 != 0 )
{
padlen = ( 8 - ( in_len % 8 ) );
memcpy(output, NIST_KW_ICV1, KW_SEMIBLOCK_LENGTH);
memmove(output + KW_SEMIBLOCK_LENGTH, input, in_len);
} else {
if (in_len % 8 != 0) {
padlen = (8 - (in_len % 8));
}
if( out_size < in_len + KW_SEMIBLOCK_LENGTH + padlen )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (out_size < in_len + KW_SEMIBLOCK_LENGTH + padlen) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
/*
* According to SP 800-38F Table 1, the plaintext length for KWP
* must be between 1 and 2^32-1 octets inclusive.
*/
if( in_len < 1
if (in_len < 1
#if SIZE_MAX > 0xFFFFFFFF
|| in_len > 0xFFFFFFFF
#endif
)
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
memcpy( output, NIST_KW_ICV2, KW_SEMIBLOCK_LENGTH / 2 );
MBEDTLS_PUT_UINT32_BE( ( in_len & 0xffffffff ), output,
KW_SEMIBLOCK_LENGTH / 2 );
memcpy(output, NIST_KW_ICV2, KW_SEMIBLOCK_LENGTH / 2);
MBEDTLS_PUT_UINT32_BE((in_len & 0xffffffff), output,
KW_SEMIBLOCK_LENGTH / 2);
memcpy( output + KW_SEMIBLOCK_LENGTH, input, in_len );
memset( output + KW_SEMIBLOCK_LENGTH + in_len, 0, padlen );
memcpy(output + KW_SEMIBLOCK_LENGTH, input, in_len);
memset(output + KW_SEMIBLOCK_LENGTH + in_len, 0, padlen);
}
semiblocks = ( ( in_len + padlen ) / KW_SEMIBLOCK_LENGTH ) + 1;
semiblocks = ((in_len + padlen) / KW_SEMIBLOCK_LENGTH) + 1;
s = 6 * ( semiblocks - 1 );
s = 6 * (semiblocks - 1);
if( mode == MBEDTLS_KW_MODE_KWP
&& in_len <= KW_SEMIBLOCK_LENGTH )
{
memcpy( inbuff, output, 16 );
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
inbuff, 16, output, &olen );
if( ret != 0 )
if (mode == MBEDTLS_KW_MODE_KWP
&& in_len <= KW_SEMIBLOCK_LENGTH) {
memcpy(inbuff, output, 16);
ret = mbedtls_cipher_update(&ctx->cipher_ctx,
inbuff, 16, output, &olen);
if (ret != 0) {
goto cleanup;
}
else
{
}
} else {
unsigned char *R2 = output + KW_SEMIBLOCK_LENGTH;
unsigned char *A = output;
/*
* Do the wrapping function W, as defined in RFC 3394 section 2.2.1
*/
if( semiblocks < MIN_SEMIBLOCKS_COUNT )
{
if (semiblocks < MIN_SEMIBLOCKS_COUNT) {
ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
goto cleanup;
}
/* Calculate intermediate values */
for( t = 1; t <= s; t++ )
{
memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH );
memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R2, KW_SEMIBLOCK_LENGTH );
for (t = 1; t <= s; t++) {
memcpy(inbuff, A, KW_SEMIBLOCK_LENGTH);
memcpy(inbuff + KW_SEMIBLOCK_LENGTH, R2, KW_SEMIBLOCK_LENGTH);
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
inbuff, 16, outbuff, &olen );
if( ret != 0 )
ret = mbedtls_cipher_update(&ctx->cipher_ctx,
inbuff, 16, outbuff, &olen);
if (ret != 0) {
goto cleanup;
}
memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );
calc_a_xor_t( A, t );
memcpy(A, outbuff, KW_SEMIBLOCK_LENGTH);
calc_a_xor_t(A, t);
memcpy( R2, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );
memcpy(R2, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH);
R2 += KW_SEMIBLOCK_LENGTH;
if( R2 >= output + ( semiblocks * KW_SEMIBLOCK_LENGTH ) )
if (R2 >= output + (semiblocks * KW_SEMIBLOCK_LENGTH)) {
R2 = output + KW_SEMIBLOCK_LENGTH;
}
}
}
@ -255,14 +247,13 @@ int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx,
cleanup:
if( ret != 0)
{
memset( output, 0, semiblocks * KW_SEMIBLOCK_LENGTH );
if (ret != 0) {
memset(output, 0, semiblocks * KW_SEMIBLOCK_LENGTH);
}
mbedtls_platform_zeroize( inbuff, KW_SEMIBLOCK_LENGTH * 2 );
mbedtls_platform_zeroize( outbuff, KW_SEMIBLOCK_LENGTH * 2 );
mbedtls_platform_zeroize(inbuff, KW_SEMIBLOCK_LENGTH * 2);
mbedtls_platform_zeroize(outbuff, KW_SEMIBLOCK_LENGTH * 2);
return( ret );
return ret;
}
/*
@ -273,13 +264,13 @@ cleanup:
* 3. Minimal number of semiblocks is 3.
* 4. A is a buffer to hold the first semiblock of the input buffer.
*/
static int unwrap( mbedtls_nist_kw_context *ctx,
const unsigned char *input, size_t semiblocks,
unsigned char A[KW_SEMIBLOCK_LENGTH],
unsigned char *output, size_t* out_len )
static int unwrap(mbedtls_nist_kw_context *ctx,
const unsigned char *input, size_t semiblocks,
unsigned char A[KW_SEMIBLOCK_LENGTH],
unsigned char *output, size_t *out_len)
{
int ret = 0;
const size_t s = 6 * ( semiblocks - 1 );
const size_t s = 6 * (semiblocks - 1);
size_t olen;
uint64_t t = 0;
unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];
@ -287,58 +278,59 @@ static int unwrap( mbedtls_nist_kw_context *ctx,
unsigned char *R = NULL;
*out_len = 0;
if( semiblocks < MIN_SEMIBLOCKS_COUNT )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (semiblocks < MIN_SEMIBLOCKS_COUNT) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
memcpy( A, input, KW_SEMIBLOCK_LENGTH );
memmove( output, input + KW_SEMIBLOCK_LENGTH, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;
memcpy(A, input, KW_SEMIBLOCK_LENGTH);
memmove(output, input + KW_SEMIBLOCK_LENGTH, (semiblocks - 1) * KW_SEMIBLOCK_LENGTH);
R = output + (semiblocks - 2) * KW_SEMIBLOCK_LENGTH;
/* Calculate intermediate values */
for( t = s; t >= 1; t-- )
{
calc_a_xor_t( A, t );
for (t = s; t >= 1; t--) {
calc_a_xor_t(A, t);
memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH );
memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R, KW_SEMIBLOCK_LENGTH );
memcpy(inbuff, A, KW_SEMIBLOCK_LENGTH);
memcpy(inbuff + KW_SEMIBLOCK_LENGTH, R, KW_SEMIBLOCK_LENGTH);
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
inbuff, 16, outbuff, &olen );
if( ret != 0 )
ret = mbedtls_cipher_update(&ctx->cipher_ctx,
inbuff, 16, outbuff, &olen);
if (ret != 0) {
goto cleanup;
}
memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );
memcpy(A, outbuff, KW_SEMIBLOCK_LENGTH);
/* Set R as LSB64 of outbuff */
memcpy( R, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );
memcpy(R, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH);
if( R == output )
R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;
else
if (R == output) {
R = output + (semiblocks - 2) * KW_SEMIBLOCK_LENGTH;
} else {
R -= KW_SEMIBLOCK_LENGTH;
}
}
*out_len = ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH;
*out_len = (semiblocks - 1) * KW_SEMIBLOCK_LENGTH;
cleanup:
if( ret != 0)
memset( output, 0, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
mbedtls_platform_zeroize( inbuff, sizeof( inbuff ) );
mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) );
if (ret != 0) {
memset(output, 0, (semiblocks - 1) * KW_SEMIBLOCK_LENGTH);
}
mbedtls_platform_zeroize(inbuff, sizeof(inbuff));
mbedtls_platform_zeroize(outbuff, sizeof(outbuff));
return( ret );
return ret;
}
/*
* KW-AD as defined in SP 800-38F section 6.2
* KWP-AD as defined in SP 800-38F section 6.3
*/
int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx,
mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t *out_len, size_t out_size )
int mbedtls_nist_kw_unwrap(mbedtls_nist_kw_context *ctx,
mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t *out_len, size_t out_size)
{
int ret = 0;
size_t i, olen;
@ -346,89 +338,81 @@ int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx,
unsigned char diff, bad_padding = 0;
*out_len = 0;
if( out_size < in_len - KW_SEMIBLOCK_LENGTH )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if (out_size < in_len - KW_SEMIBLOCK_LENGTH) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
if( mode == MBEDTLS_KW_MODE_KW )
{
if (mode == MBEDTLS_KW_MODE_KW) {
/*
* According to SP 800-38F Table 1, the ciphertext length for KW
* must be between 3 to 2^54 semiblocks inclusive.
*/
if( in_len < 24 ||
if (in_len < 24 ||
#if SIZE_MAX > 0x200000000000000
in_len > 0x200000000000000 ||
#endif
in_len % KW_SEMIBLOCK_LENGTH != 0 )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
in_len % KW_SEMIBLOCK_LENGTH != 0) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH,
A, output, out_len );
if( ret != 0 )
ret = unwrap(ctx, input, in_len / KW_SEMIBLOCK_LENGTH,
A, output, out_len);
if (ret != 0) {
goto cleanup;
}
/* Check ICV in "constant-time" */
diff = mbedtls_ct_memcmp( NIST_KW_ICV1, A, KW_SEMIBLOCK_LENGTH );
diff = mbedtls_ct_memcmp(NIST_KW_ICV1, A, KW_SEMIBLOCK_LENGTH);
if( diff != 0 )
{
if (diff != 0) {
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
goto cleanup;
}
}
else if( mode == MBEDTLS_KW_MODE_KWP )
{
} else if (mode == MBEDTLS_KW_MODE_KWP) {
size_t padlen = 0;
uint32_t Plen;
/*
* According to SP 800-38F Table 1, the ciphertext length for KWP
* must be between 2 to 2^29 semiblocks inclusive.
*/
if( in_len < KW_SEMIBLOCK_LENGTH * 2 ||
if (in_len < KW_SEMIBLOCK_LENGTH * 2 ||
#if SIZE_MAX > 0x100000000
in_len > 0x100000000 ||
#endif
in_len % KW_SEMIBLOCK_LENGTH != 0 )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
in_len % KW_SEMIBLOCK_LENGTH != 0) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
if( in_len == KW_SEMIBLOCK_LENGTH * 2 )
{
if (in_len == KW_SEMIBLOCK_LENGTH * 2) {
unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
input, 16, outbuff, &olen );
if( ret != 0 )
ret = mbedtls_cipher_update(&ctx->cipher_ctx,
input, 16, outbuff, &olen);
if (ret != 0) {
goto cleanup;
}
memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );
memcpy( output, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );
mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) );
memcpy(A, outbuff, KW_SEMIBLOCK_LENGTH);
memcpy(output, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH);
mbedtls_platform_zeroize(outbuff, sizeof(outbuff));
*out_len = KW_SEMIBLOCK_LENGTH;
}
else
{
} else {
/* in_len >= KW_SEMIBLOCK_LENGTH * 3 */
ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH,
A, output, out_len );
if( ret != 0 )
ret = unwrap(ctx, input, in_len / KW_SEMIBLOCK_LENGTH,
A, output, out_len);
if (ret != 0) {
goto cleanup;
}
}
/* Check ICV in "constant-time" */
diff = mbedtls_ct_memcmp( NIST_KW_ICV2, A, KW_SEMIBLOCK_LENGTH / 2 );
diff = mbedtls_ct_memcmp(NIST_KW_ICV2, A, KW_SEMIBLOCK_LENGTH / 2);
if( diff != 0 )
{
if (diff != 0) {
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
}
Plen = MBEDTLS_GET_UINT32_BE( A, KW_SEMIBLOCK_LENGTH / 2 );
Plen = MBEDTLS_GET_UINT32_BE(A, KW_SEMIBLOCK_LENGTH / 2);
/*
* Plen is the length of the plaintext, when the input is valid.
@ -436,51 +420,45 @@ int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx,
* larger than 8, because of the type wrap around.
*/
padlen = in_len - KW_SEMIBLOCK_LENGTH - Plen;
if ( padlen > 7 )
{
if (padlen > 7) {
padlen &= 7;
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
}
/* Check padding in "constant-time" */
for( diff = 0, i = 0; i < KW_SEMIBLOCK_LENGTH; i++ )
{
if( i >= KW_SEMIBLOCK_LENGTH - padlen )
diff |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];
else
bad_padding |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];
for (diff = 0, i = 0; i < KW_SEMIBLOCK_LENGTH; i++) {
if (i >= KW_SEMIBLOCK_LENGTH - padlen) {
diff |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];
} else {
bad_padding |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];
}
}
if( diff != 0 )
{
if (diff != 0) {
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
}
if( ret != 0 )
{
if (ret != 0) {
goto cleanup;
}
memset( output + Plen, 0, padlen );
memset(output + Plen, 0, padlen);
*out_len = Plen;
}
else
{
} else {
ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
goto cleanup;
}
cleanup:
if( ret != 0 )
{
memset( output, 0, *out_len );
if (ret != 0) {
memset(output, 0, *out_len);
*out_len = 0;
}
mbedtls_platform_zeroize( &bad_padding, sizeof( bad_padding) );
mbedtls_platform_zeroize( &diff, sizeof( diff ) );
mbedtls_platform_zeroize( A, sizeof( A ) );
mbedtls_platform_zeroize(&bad_padding, sizeof(bad_padding));
mbedtls_platform_zeroize(&diff, sizeof(diff));
mbedtls_platform_zeroize(A, sizeof(A));
return( ret );
return ret;
}
#endif /* !MBEDTLS_NIST_KW_ALT */
@ -575,130 +553,133 @@ static const unsigned char kwp_res[KW_TESTS][48] = {
};
static const size_t kwp_out_len[KW_TESTS] = { 24, 40, 16 };
int mbedtls_nist_kw_self_test( int verbose )
int mbedtls_nist_kw_self_test(int verbose)
{
mbedtls_nist_kw_context ctx;
unsigned char out[48];
size_t olen;
int i;
int ret = 0;
mbedtls_nist_kw_init( &ctx );
mbedtls_nist_kw_init(&ctx);
for( i = 0; i < KW_TESTS; i++ )
{
if( verbose != 0 )
mbedtls_printf( " KW-AES-%u ", (unsigned int) key_len[i] * 8 );
for (i = 0; i < KW_TESTS; i++) {
if (verbose != 0) {
mbedtls_printf(" KW-AES-%u ", (unsigned int) key_len[i] * 8);
}
ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,
kw_key[i], key_len[i] * 8, 1 );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( " KW: setup failed " );
ret = mbedtls_nist_kw_setkey(&ctx, MBEDTLS_CIPHER_ID_AES,
kw_key[i], key_len[i] * 8, 1);
if (ret != 0) {
if (verbose != 0) {
mbedtls_printf(" KW: setup failed ");
}
goto end;
}
ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KW, kw_msg[i],
kw_msg_len[i], out, &olen, sizeof( out ) );
if( ret != 0 || kw_out_len[i] != olen ||
memcmp( out, kw_res[i], kw_out_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed. ");
ret = mbedtls_nist_kw_wrap(&ctx, MBEDTLS_KW_MODE_KW, kw_msg[i],
kw_msg_len[i], out, &olen, sizeof(out));
if (ret != 0 || kw_out_len[i] != olen ||
memcmp(out, kw_res[i], kw_out_len[i]) != 0) {
if (verbose != 0) {
mbedtls_printf("failed. ");
}
ret = 1;
goto end;
}
if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,
kw_key[i], key_len[i] * 8, 0 ) )
!= 0 )
{
if( verbose != 0 )
mbedtls_printf( " KW: setup failed ");
if ((ret = mbedtls_nist_kw_setkey(&ctx, MBEDTLS_CIPHER_ID_AES,
kw_key[i], key_len[i] * 8, 0))
!= 0) {
if (verbose != 0) {
mbedtls_printf(" KW: setup failed ");
}
goto end;
}
ret = mbedtls_nist_kw_unwrap( &ctx, MBEDTLS_KW_MODE_KW,
out, olen, out, &olen, sizeof( out ) );
ret = mbedtls_nist_kw_unwrap(&ctx, MBEDTLS_KW_MODE_KW,
out, olen, out, &olen, sizeof(out));
if( ret != 0 || olen != kw_msg_len[i] ||
memcmp( out, kw_msg[i], kw_msg_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
if (ret != 0 || olen != kw_msg_len[i] ||
memcmp(out, kw_msg[i], kw_msg_len[i]) != 0) {
if (verbose != 0) {
mbedtls_printf("failed\n");
}
ret = 1;
goto end;
}
if( verbose != 0 )
mbedtls_printf( " passed\n" );
if (verbose != 0) {
mbedtls_printf(" passed\n");
}
}
for( i = 0; i < KW_TESTS; i++ )
{
olen = sizeof( out );
if( verbose != 0 )
mbedtls_printf( " KWP-AES-%u ", (unsigned int) key_len[i] * 8 );
for (i = 0; i < KW_TESTS; i++) {
olen = sizeof(out);
if (verbose != 0) {
mbedtls_printf(" KWP-AES-%u ", (unsigned int) key_len[i] * 8);
}
ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, kwp_key[i],
key_len[i] * 8, 1 );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( " KWP: setup failed " );
ret = mbedtls_nist_kw_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, kwp_key[i],
key_len[i] * 8, 1);
if (ret != 0) {
if (verbose != 0) {
mbedtls_printf(" KWP: setup failed ");
}
goto end;
}
ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KWP, kwp_msg[i],
kwp_msg_len[i], out, &olen, sizeof( out ) );
ret = mbedtls_nist_kw_wrap(&ctx, MBEDTLS_KW_MODE_KWP, kwp_msg[i],
kwp_msg_len[i], out, &olen, sizeof(out));
if( ret != 0 || kwp_out_len[i] != olen ||
memcmp( out, kwp_res[i], kwp_out_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed. ");
if (ret != 0 || kwp_out_len[i] != olen ||
memcmp(out, kwp_res[i], kwp_out_len[i]) != 0) {
if (verbose != 0) {
mbedtls_printf("failed. ");
}
ret = 1;
goto end;
}
if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,
kwp_key[i], key_len[i] * 8, 0 ) )
!= 0 )
{
if( verbose != 0 )
mbedtls_printf( " KWP: setup failed ");
if ((ret = mbedtls_nist_kw_setkey(&ctx, MBEDTLS_CIPHER_ID_AES,
kwp_key[i], key_len[i] * 8, 0))
!= 0) {
if (verbose != 0) {
mbedtls_printf(" KWP: setup failed ");
}
goto end;
}
ret = mbedtls_nist_kw_unwrap( &ctx, MBEDTLS_KW_MODE_KWP, out,
olen, out, &olen, sizeof( out ) );
ret = mbedtls_nist_kw_unwrap(&ctx, MBEDTLS_KW_MODE_KWP, out,
olen, out, &olen, sizeof(out));
if( ret != 0 || olen != kwp_msg_len[i] ||
memcmp( out, kwp_msg[i], kwp_msg_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed. ");
if (ret != 0 || olen != kwp_msg_len[i] ||
memcmp(out, kwp_msg[i], kwp_msg_len[i]) != 0) {
if (verbose != 0) {
mbedtls_printf("failed. ");
}
ret = 1;
goto end;
}
if( verbose != 0 )
mbedtls_printf( " passed\n" );
if (verbose != 0) {
mbedtls_printf(" passed\n");
}
}
end:
mbedtls_nist_kw_free( &ctx );
mbedtls_nist_kw_free(&ctx);
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
return( ret );
return ret;
}
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

View File

@ -54,23 +54,23 @@
* Macro to generate an internal function for oid_XXX_from_asn1() (used by
* the other functions)
*/
#define FN_OID_TYPED_FROM_ASN1( TYPE_T, NAME, LIST ) \
static const TYPE_T * oid_ ## NAME ## _from_asn1( \
const mbedtls_asn1_buf *oid ) \
#define FN_OID_TYPED_FROM_ASN1(TYPE_T, NAME, LIST) \
static const TYPE_T *oid_ ## NAME ## _from_asn1( \
const mbedtls_asn1_buf *oid) \
{ \
const TYPE_T *p = (LIST); \
const mbedtls_oid_descriptor_t *cur = \
(const mbedtls_oid_descriptor_t *) p; \
if( p == NULL || oid == NULL ) return( NULL ); \
while( cur->asn1 != NULL ) { \
if( cur->asn1_len == oid->len && \
memcmp( cur->asn1, oid->p, oid->len ) == 0 ) { \
return( p ); \
if (p == NULL || oid == NULL) return NULL; \
while (cur->asn1 != NULL) { \
if (cur->asn1_len == oid->len && \
memcmp(cur->asn1, oid->p, oid->len) == 0) { \
return p; \
} \
p++; \
cur = (const mbedtls_oid_descriptor_t *) p; \
} \
return( NULL ); \
return NULL; \
}
#if !defined(MBEDTLS_X509_REMOVE_INFO)
@ -79,13 +79,13 @@
* descriptor of an mbedtls_oid_descriptor_t wrapper.
*/
#define FN_OID_GET_DESCRIPTOR_ATTR1(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1) \
int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 ) \
{ \
const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid ); \
if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND ); \
*ATTR1 = data->descriptor.ATTR1; \
return( 0 ); \
}
int FN_NAME(const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1) \
{ \
const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1(oid); \
if (data == NULL) return MBEDTLS_ERR_OID_NOT_FOUND; \
*ATTR1 = data->descriptor.ATTR1; \
return 0; \
}
#endif /* MBEDTLS_X509_REMOVE_INFO */
/*
@ -93,13 +93,13 @@ int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 )
* mbedtls_oid_descriptor_t wrapper.
*/
#define FN_OID_GET_ATTR1(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1) \
int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 ) \
{ \
const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid ); \
if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND ); \
*ATTR1 = data->ATTR1; \
return( 0 ); \
}
int FN_NAME(const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1) \
{ \
const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1(oid); \
if (data == NULL) return MBEDTLS_ERR_OID_NOT_FOUND; \
*ATTR1 = data->ATTR1; \
return 0; \
}
/*
* Macro to generate a function for retrieving two attributes from an
@ -107,34 +107,34 @@ int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 )
*/
#define FN_OID_GET_ATTR2(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1, \
ATTR2_TYPE, ATTR2) \
int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1, \
ATTR2_TYPE * ATTR2 ) \
{ \
const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid ); \
if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND ); \
*(ATTR1) = data->ATTR1; \
*(ATTR2) = data->ATTR2; \
return( 0 ); \
}
int FN_NAME(const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1, \
ATTR2_TYPE * ATTR2) \
{ \
const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1(oid); \
if (data == NULL) return MBEDTLS_ERR_OID_NOT_FOUND; \
*(ATTR1) = data->ATTR1; \
*(ATTR2) = data->ATTR2; \
return 0; \
}
/*
* Macro to generate a function for retrieving the OID based on a single
* attribute from a mbedtls_oid_descriptor_t wrapper.
*/
#define FN_OID_GET_OID_BY_ATTR1(FN_NAME, TYPE_T, LIST, ATTR1_TYPE, ATTR1) \
int FN_NAME( ATTR1_TYPE ATTR1, const char **oid, size_t *olen ) \
{ \
const TYPE_T *cur = (LIST); \
while( cur->descriptor.asn1 != NULL ) { \
if( cur->ATTR1 == (ATTR1) ) { \
*oid = cur->descriptor.asn1; \
*olen = cur->descriptor.asn1_len; \
return( 0 ); \
} \
cur++; \
} \
return( MBEDTLS_ERR_OID_NOT_FOUND ); \
}
int FN_NAME(ATTR1_TYPE ATTR1, const char **oid, size_t *olen) \
{ \
const TYPE_T *cur = (LIST); \
while (cur->descriptor.asn1 != NULL) { \
if (cur->ATTR1 == (ATTR1)) { \
*oid = cur->descriptor.asn1; \
*olen = cur->descriptor.asn1_len; \
return 0; \
} \
cur++; \
} \
return MBEDTLS_ERR_OID_NOT_FOUND; \
}
/*
* Macro to generate a function for retrieving the OID based on two
@ -142,20 +142,20 @@ int FN_NAME( ATTR1_TYPE ATTR1, const char **oid, size_t *olen ) \
*/
#define FN_OID_GET_OID_BY_ATTR2(FN_NAME, TYPE_T, LIST, ATTR1_TYPE, ATTR1, \
ATTR2_TYPE, ATTR2) \
int FN_NAME( ATTR1_TYPE ATTR1, ATTR2_TYPE ATTR2, const char **oid , \
size_t *olen ) \
{ \
const TYPE_T *cur = (LIST); \
while( cur->descriptor.asn1 != NULL ) { \
if( cur->ATTR1 == (ATTR1) && cur->ATTR2 == (ATTR2) ) { \
*oid = cur->descriptor.asn1; \
*olen = cur->descriptor.asn1_len; \
return( 0 ); \
} \
cur++; \
} \
return( MBEDTLS_ERR_OID_NOT_FOUND ); \
}
int FN_NAME(ATTR1_TYPE ATTR1, ATTR2_TYPE ATTR2, const char **oid, \
size_t *olen) \
{ \
const TYPE_T *cur = (LIST); \
while (cur->descriptor.asn1 != NULL) { \
if (cur->ATTR1 == (ATTR1) && cur->ATTR2 == (ATTR2)) { \
*oid = cur->descriptor.asn1; \
*olen = cur->descriptor.asn1_len; \
return 0; \
} \
cur++; \
} \
return MBEDTLS_ERR_OID_NOT_FOUND; \
}
/*
* For X520 attribute types
@ -168,83 +168,98 @@ typedef struct {
static const oid_x520_attr_t oid_x520_attr_type[] =
{
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_CN, "id-at-commonName", "Common Name" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_CN, "id-at-commonName", "Common Name"),
"CN",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_COUNTRY, "id-at-countryName", "Country" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_COUNTRY, "id-at-countryName", "Country"),
"C",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_LOCALITY, "id-at-locality", "Locality" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_LOCALITY, "id-at-locality", "Locality"),
"L",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_STATE, "id-at-state", "State" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_STATE, "id-at-state", "State"),
"ST",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_ORGANIZATION,"id-at-organizationName", "Organization" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_ORGANIZATION, "id-at-organizationName",
"Organization"),
"O",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_ORG_UNIT, "id-at-organizationalUnitName", "Org Unit" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_ORG_UNIT, "id-at-organizationalUnitName", "Org Unit"),
"OU",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS9_EMAIL, "emailAddress", "E-mail address" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS9_EMAIL,
"emailAddress",
"E-mail address"),
"emailAddress",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_SERIAL_NUMBER,"id-at-serialNumber", "Serial number" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_SERIAL_NUMBER,
"id-at-serialNumber",
"Serial number"),
"serialNumber",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_POSTAL_ADDRESS,"id-at-postalAddress", "Postal address" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_POSTAL_ADDRESS,
"id-at-postalAddress",
"Postal address"),
"postalAddress",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_POSTAL_CODE, "id-at-postalCode", "Postal code" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_POSTAL_CODE, "id-at-postalCode", "Postal code"),
"postalCode",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_SUR_NAME, "id-at-surName", "Surname" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_SUR_NAME, "id-at-surName", "Surname"),
"SN",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_GIVEN_NAME, "id-at-givenName", "Given name" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_GIVEN_NAME, "id-at-givenName", "Given name"),
"GN",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_INITIALS, "id-at-initials", "Initials" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_INITIALS, "id-at-initials", "Initials"),
"initials",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_GENERATION_QUALIFIER, "id-at-generationQualifier", "Generation qualifier" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_GENERATION_QUALIFIER,
"id-at-generationQualifier",
"Generation qualifier"),
"generationQualifier",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_TITLE, "id-at-title", "Title" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_TITLE, "id-at-title", "Title"),
"title",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_DN_QUALIFIER,"id-at-dnQualifier", "Distinguished Name qualifier" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_DN_QUALIFIER,
"id-at-dnQualifier",
"Distinguished Name qualifier"),
"dnQualifier",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_PSEUDONYM, "id-at-pseudonym", "Pseudonym" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_PSEUDONYM, "id-at-pseudonym", "Pseudonym"),
"pseudonym",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_UID, "id-uid", "User Id" ),
OID_DESCRIPTOR(MBEDTLS_OID_UID, "id-uid", "User Id"),
"uid",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_DOMAIN_COMPONENT, "id-domainComponent", "Domain component" ),
OID_DESCRIPTOR(MBEDTLS_OID_DOMAIN_COMPONENT,
"id-domainComponent",
"Domain component"),
"DC",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_AT_UNIQUE_IDENTIFIER, "id-at-uniqueIdentifier", "Unique Identifier" ),
OID_DESCRIPTOR(MBEDTLS_OID_AT_UNIQUE_IDENTIFIER,
"id-at-uniqueIdentifier",
"Unique Identifier"),
"uniqueIdentifier",
},
{
@ -254,7 +269,11 @@ static const oid_x520_attr_t oid_x520_attr_type[] =
};
FN_OID_TYPED_FROM_ASN1(oid_x520_attr_t, x520_attr, oid_x520_attr_type)
FN_OID_GET_ATTR1(mbedtls_oid_get_attr_short_name, oid_x520_attr_t, x520_attr, const char *, short_name)
FN_OID_GET_ATTR1(mbedtls_oid_get_attr_short_name,
oid_x520_attr_t,
x520_attr,
const char *,
short_name)
/*
* For X509 extensions
@ -267,27 +286,37 @@ typedef struct {
static const oid_x509_ext_t oid_x509_ext[] =
{
{
OID_DESCRIPTOR( MBEDTLS_OID_BASIC_CONSTRAINTS, "id-ce-basicConstraints", "Basic Constraints" ),
OID_DESCRIPTOR(MBEDTLS_OID_BASIC_CONSTRAINTS,
"id-ce-basicConstraints",
"Basic Constraints"),
MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_KEY_USAGE, "id-ce-keyUsage", "Key Usage" ),
OID_DESCRIPTOR(MBEDTLS_OID_KEY_USAGE, "id-ce-keyUsage", "Key Usage"),
MBEDTLS_OID_X509_EXT_KEY_USAGE,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_EXTENDED_KEY_USAGE, "id-ce-extKeyUsage", "Extended Key Usage" ),
OID_DESCRIPTOR(MBEDTLS_OID_EXTENDED_KEY_USAGE,
"id-ce-extKeyUsage",
"Extended Key Usage"),
MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_SUBJECT_ALT_NAME, "id-ce-subjectAltName", "Subject Alt Name" ),
OID_DESCRIPTOR(MBEDTLS_OID_SUBJECT_ALT_NAME,
"id-ce-subjectAltName",
"Subject Alt Name"),
MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_NS_CERT_TYPE, "id-netscape-certtype", "Netscape Certificate Type" ),
OID_DESCRIPTOR(MBEDTLS_OID_NS_CERT_TYPE,
"id-netscape-certtype",
"Netscape Certificate Type"),
MBEDTLS_OID_X509_EXT_NS_CERT_TYPE,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_CERTIFICATE_POLICIES, "id-ce-certificatePolicies", "Certificate Policies" ),
OID_DESCRIPTOR(MBEDTLS_OID_CERTIFICATE_POLICIES,
"id-ce-certificatePolicies",
"Certificate Policies"),
MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES,
},
{
@ -302,27 +331,41 @@ FN_OID_GET_ATTR1(mbedtls_oid_get_x509_ext_type, oid_x509_ext_t, x509_ext, int, e
#if !defined(MBEDTLS_X509_REMOVE_INFO)
static const mbedtls_oid_descriptor_t oid_ext_key_usage[] =
{
OID_DESCRIPTOR( MBEDTLS_OID_SERVER_AUTH, "id-kp-serverAuth", "TLS Web Server Authentication" ),
OID_DESCRIPTOR( MBEDTLS_OID_CLIENT_AUTH, "id-kp-clientAuth", "TLS Web Client Authentication" ),
OID_DESCRIPTOR( MBEDTLS_OID_CODE_SIGNING, "id-kp-codeSigning", "Code Signing" ),
OID_DESCRIPTOR( MBEDTLS_OID_EMAIL_PROTECTION, "id-kp-emailProtection", "E-mail Protection" ),
OID_DESCRIPTOR( MBEDTLS_OID_TIME_STAMPING, "id-kp-timeStamping", "Time Stamping" ),
OID_DESCRIPTOR( MBEDTLS_OID_OCSP_SIGNING, "id-kp-OCSPSigning", "OCSP Signing" ),
OID_DESCRIPTOR( MBEDTLS_OID_WISUN_FAN, "id-kp-wisun-fan-device", "Wi-SUN Alliance Field Area Network (FAN)" ),
OID_DESCRIPTOR(MBEDTLS_OID_SERVER_AUTH,
"id-kp-serverAuth",
"TLS Web Server Authentication"),
OID_DESCRIPTOR(MBEDTLS_OID_CLIENT_AUTH,
"id-kp-clientAuth",
"TLS Web Client Authentication"),
OID_DESCRIPTOR(MBEDTLS_OID_CODE_SIGNING, "id-kp-codeSigning", "Code Signing"),
OID_DESCRIPTOR(MBEDTLS_OID_EMAIL_PROTECTION, "id-kp-emailProtection", "E-mail Protection"),
OID_DESCRIPTOR(MBEDTLS_OID_TIME_STAMPING, "id-kp-timeStamping", "Time Stamping"),
OID_DESCRIPTOR(MBEDTLS_OID_OCSP_SIGNING, "id-kp-OCSPSigning", "OCSP Signing"),
OID_DESCRIPTOR(MBEDTLS_OID_WISUN_FAN,
"id-kp-wisun-fan-device",
"Wi-SUN Alliance Field Area Network (FAN)"),
NULL_OID_DESCRIPTOR,
};
FN_OID_TYPED_FROM_ASN1(mbedtls_oid_descriptor_t, ext_key_usage, oid_ext_key_usage)
FN_OID_GET_ATTR1(mbedtls_oid_get_extended_key_usage, mbedtls_oid_descriptor_t, ext_key_usage, const char *, description)
FN_OID_GET_ATTR1(mbedtls_oid_get_extended_key_usage,
mbedtls_oid_descriptor_t,
ext_key_usage,
const char *,
description)
static const mbedtls_oid_descriptor_t oid_certificate_policies[] =
{
OID_DESCRIPTOR( MBEDTLS_OID_ANY_POLICY, "anyPolicy", "Any Policy" ),
OID_DESCRIPTOR(MBEDTLS_OID_ANY_POLICY, "anyPolicy", "Any Policy"),
NULL_OID_DESCRIPTOR,
};
FN_OID_TYPED_FROM_ASN1(mbedtls_oid_descriptor_t, certificate_policies, oid_certificate_policies)
FN_OID_GET_ATTR1(mbedtls_oid_get_certificate_policies, mbedtls_oid_descriptor_t, certificate_policies, const char *, description)
FN_OID_GET_ATTR1(mbedtls_oid_get_certificate_policies,
mbedtls_oid_descriptor_t,
certificate_policies,
const char *,
description)
#endif /* MBEDTLS_X509_REMOVE_INFO */
/*
@ -339,43 +382,47 @@ static const oid_sig_alg_t oid_sig_alg[] =
#if defined(MBEDTLS_RSA_C)
#if defined(MBEDTLS_HAS_ALG_MD5_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS1_MD5, "md5WithRSAEncryption", "RSA with MD5" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS1_MD5, "md5WithRSAEncryption", "RSA with MD5"),
MBEDTLS_MD_MD5, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_HAS_ALG_MD5_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS1_SHA1, "sha-1WithRSAEncryption", "RSA with SHA1" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS1_SHA1, "sha-1WithRSAEncryption", "RSA with SHA1"),
MBEDTLS_MD_SHA1, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS1_SHA224, "sha224WithRSAEncryption", "RSA with SHA-224" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS1_SHA224, "sha224WithRSAEncryption",
"RSA with SHA-224"),
MBEDTLS_MD_SHA224, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_224_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS1_SHA256, "sha256WithRSAEncryption", "RSA with SHA-256" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS1_SHA256, "sha256WithRSAEncryption",
"RSA with SHA-256"),
MBEDTLS_MD_SHA256, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS1_SHA384, "sha384WithRSAEncryption", "RSA with SHA-384" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS1_SHA384, "sha384WithRSAEncryption",
"RSA with SHA-384"),
MBEDTLS_MD_SHA384, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS1_SHA512, "sha512WithRSAEncryption", "RSA with SHA-512" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS1_SHA512, "sha512WithRSAEncryption",
"RSA with SHA-512"),
MBEDTLS_MD_SHA512, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_512_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_RSA_SHA_OBS, "sha-1WithRSAEncryption", "RSA with SHA1" ),
OID_DESCRIPTOR(MBEDTLS_OID_RSA_SHA_OBS, "sha-1WithRSAEncryption", "RSA with SHA1"),
MBEDTLS_MD_SHA1, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA */
@ -383,38 +430,38 @@ static const oid_sig_alg_t oid_sig_alg[] =
#if defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_ECDSA_SHA1, "ecdsa-with-SHA1", "ECDSA with SHA1" ),
OID_DESCRIPTOR(MBEDTLS_OID_ECDSA_SHA1, "ecdsa-with-SHA1", "ECDSA with SHA1"),
MBEDTLS_MD_SHA1, MBEDTLS_PK_ECDSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_ECDSA_SHA224, "ecdsa-with-SHA224", "ECDSA with SHA224" ),
OID_DESCRIPTOR(MBEDTLS_OID_ECDSA_SHA224, "ecdsa-with-SHA224", "ECDSA with SHA224"),
MBEDTLS_MD_SHA224, MBEDTLS_PK_ECDSA,
},
#endif
#if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_ECDSA_SHA256, "ecdsa-with-SHA256", "ECDSA with SHA256" ),
OID_DESCRIPTOR(MBEDTLS_OID_ECDSA_SHA256, "ecdsa-with-SHA256", "ECDSA with SHA256"),
MBEDTLS_MD_SHA256, MBEDTLS_PK_ECDSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_ECDSA_SHA384, "ecdsa-with-SHA384", "ECDSA with SHA384" ),
OID_DESCRIPTOR(MBEDTLS_OID_ECDSA_SHA384, "ecdsa-with-SHA384", "ECDSA with SHA384"),
MBEDTLS_MD_SHA384, MBEDTLS_PK_ECDSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_ECDSA_SHA512, "ecdsa-with-SHA512", "ECDSA with SHA512" ),
OID_DESCRIPTOR(MBEDTLS_OID_ECDSA_SHA512, "ecdsa-with-SHA512", "ECDSA with SHA512"),
MBEDTLS_MD_SHA512, MBEDTLS_PK_ECDSA,
},
#endif /* MBEDTLS_HAS_ALG_SHA_512_VIA_LOWLEVEL_OR_PSA */
#endif /* MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_RSA_C)
{
OID_DESCRIPTOR( MBEDTLS_OID_RSASSA_PSS, "RSASSA-PSS", "RSASSA-PSS" ),
OID_DESCRIPTOR(MBEDTLS_OID_RSASSA_PSS, "RSASSA-PSS", "RSASSA-PSS"),
MBEDTLS_MD_NONE, MBEDTLS_PK_RSASSA_PSS,
},
#endif /* MBEDTLS_RSA_C */
@ -427,11 +474,27 @@ static const oid_sig_alg_t oid_sig_alg[] =
FN_OID_TYPED_FROM_ASN1(oid_sig_alg_t, sig_alg, oid_sig_alg)
#if !defined(MBEDTLS_X509_REMOVE_INFO)
FN_OID_GET_DESCRIPTOR_ATTR1(mbedtls_oid_get_sig_alg_desc, oid_sig_alg_t, sig_alg, const char *, description)
FN_OID_GET_DESCRIPTOR_ATTR1(mbedtls_oid_get_sig_alg_desc,
oid_sig_alg_t,
sig_alg,
const char *,
description)
#endif
FN_OID_GET_ATTR2(mbedtls_oid_get_sig_alg, oid_sig_alg_t, sig_alg, mbedtls_md_type_t, md_alg, mbedtls_pk_type_t, pk_alg)
FN_OID_GET_OID_BY_ATTR2(mbedtls_oid_get_oid_by_sig_alg, oid_sig_alg_t, oid_sig_alg, mbedtls_pk_type_t, pk_alg, mbedtls_md_type_t, md_alg)
FN_OID_GET_ATTR2(mbedtls_oid_get_sig_alg,
oid_sig_alg_t,
sig_alg,
mbedtls_md_type_t,
md_alg,
mbedtls_pk_type_t,
pk_alg)
FN_OID_GET_OID_BY_ATTR2(mbedtls_oid_get_oid_by_sig_alg,
oid_sig_alg_t,
oid_sig_alg,
mbedtls_pk_type_t,
pk_alg,
mbedtls_md_type_t,
md_alg)
/*
* For PublicKeyInfo (PKCS1, RFC 5480)
@ -444,15 +507,15 @@ typedef struct {
static const oid_pk_alg_t oid_pk_alg[] =
{
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS1_RSA, "rsaEncryption", "RSA" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS1_RSA, "rsaEncryption", "RSA"),
MBEDTLS_PK_RSA,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_ALG_UNRESTRICTED, "id-ecPublicKey", "Generic EC key" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_ALG_UNRESTRICTED, "id-ecPublicKey", "Generic EC key"),
MBEDTLS_PK_ECKEY,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_ALG_ECDH, "id-ecDH", "EC key for ECDH" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_ALG_ECDH, "id-ecDH", "EC key for ECDH"),
MBEDTLS_PK_ECKEY_DH,
},
{
@ -463,7 +526,11 @@ static const oid_pk_alg_t oid_pk_alg[] =
FN_OID_TYPED_FROM_ASN1(oid_pk_alg_t, pk_alg, oid_pk_alg)
FN_OID_GET_ATTR1(mbedtls_oid_get_pk_alg, oid_pk_alg_t, pk_alg, mbedtls_pk_type_t, pk_alg)
FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_pk_alg, oid_pk_alg_t, oid_pk_alg, mbedtls_pk_type_t, pk_alg)
FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_pk_alg,
oid_pk_alg_t,
oid_pk_alg,
mbedtls_pk_type_t,
pk_alg)
#if defined(MBEDTLS_ECP_C)
/*
@ -478,67 +545,67 @@ static const oid_ecp_grp_t oid_ecp_grp[] =
{
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP192R1, "secp192r1", "secp192r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP192R1, "secp192r1", "secp192r1"),
MBEDTLS_ECP_DP_SECP192R1,
},
#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP224R1, "secp224r1", "secp224r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP224R1, "secp224r1", "secp224r1"),
MBEDTLS_ECP_DP_SECP224R1,
},
#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP256R1, "secp256r1", "secp256r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP256R1, "secp256r1", "secp256r1"),
MBEDTLS_ECP_DP_SECP256R1,
},
#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP384R1, "secp384r1", "secp384r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP384R1, "secp384r1", "secp384r1"),
MBEDTLS_ECP_DP_SECP384R1,
},
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP521R1, "secp521r1", "secp521r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP521R1, "secp521r1", "secp521r1"),
MBEDTLS_ECP_DP_SECP521R1,
},
#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP192K1, "secp192k1", "secp192k1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP192K1, "secp192k1", "secp192k1"),
MBEDTLS_ECP_DP_SECP192K1,
},
#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP224K1, "secp224k1", "secp224k1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP224K1, "secp224k1", "secp224k1"),
MBEDTLS_ECP_DP_SECP224K1,
},
#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_SECP256K1, "secp256k1", "secp256k1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_SECP256K1, "secp256k1", "secp256k1"),
MBEDTLS_ECP_DP_SECP256K1,
},
#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_BP256R1, "brainpoolP256r1","brainpool256r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_BP256R1, "brainpoolP256r1", "brainpool256r1"),
MBEDTLS_ECP_DP_BP256R1,
},
#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_BP384R1, "brainpoolP384r1","brainpool384r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_BP384R1, "brainpoolP384r1", "brainpool384r1"),
MBEDTLS_ECP_DP_BP384R1,
},
#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
{
OID_DESCRIPTOR( MBEDTLS_OID_EC_GRP_BP512R1, "brainpoolP512r1","brainpool512r1" ),
OID_DESCRIPTOR(MBEDTLS_OID_EC_GRP_BP512R1, "brainpoolP512r1", "brainpool512r1"),
MBEDTLS_ECP_DP_BP512R1,
},
#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */
@ -550,7 +617,11 @@ static const oid_ecp_grp_t oid_ecp_grp[] =
FN_OID_TYPED_FROM_ASN1(oid_ecp_grp_t, grp_id, oid_ecp_grp)
FN_OID_GET_ATTR1(mbedtls_oid_get_ec_grp, oid_ecp_grp_t, grp_id, mbedtls_ecp_group_id, grp_id)
FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_ec_grp, oid_ecp_grp_t, oid_ecp_grp, mbedtls_ecp_group_id, grp_id)
FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_ec_grp,
oid_ecp_grp_t,
oid_ecp_grp,
mbedtls_ecp_group_id,
grp_id)
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_CIPHER_C)
@ -565,11 +636,11 @@ typedef struct {
static const oid_cipher_alg_t oid_cipher_alg[] =
{
{
OID_DESCRIPTOR( MBEDTLS_OID_DES_CBC, "desCBC", "DES-CBC" ),
OID_DESCRIPTOR(MBEDTLS_OID_DES_CBC, "desCBC", "DES-CBC"),
MBEDTLS_CIPHER_DES_CBC,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_DES_EDE3_CBC, "des-ede3-cbc", "DES-EDE3-CBC" ),
OID_DESCRIPTOR(MBEDTLS_OID_DES_EDE3_CBC, "des-ede3-cbc", "DES-EDE3-CBC"),
MBEDTLS_CIPHER_DES_EDE3_CBC,
},
{
@ -579,7 +650,11 @@ static const oid_cipher_alg_t oid_cipher_alg[] =
};
FN_OID_TYPED_FROM_ASN1(oid_cipher_alg_t, cipher_alg, oid_cipher_alg)
FN_OID_GET_ATTR1(mbedtls_oid_get_cipher_alg, oid_cipher_alg_t, cipher_alg, mbedtls_cipher_type_t, cipher_alg)
FN_OID_GET_ATTR1(mbedtls_oid_get_cipher_alg,
oid_cipher_alg_t,
cipher_alg,
mbedtls_cipher_type_t,
cipher_alg)
#endif /* MBEDTLS_CIPHER_C */
/*
@ -594,43 +669,43 @@ static const oid_md_alg_t oid_md_alg[] =
{
#if defined(MBEDTLS_HAS_ALG_MD5_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_DIGEST_ALG_MD5, "id-md5", "MD5" ),
OID_DESCRIPTOR(MBEDTLS_OID_DIGEST_ALG_MD5, "id-md5", "MD5"),
MBEDTLS_MD_MD5,
},
#endif
#if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_DIGEST_ALG_SHA1, "id-sha1", "SHA-1" ),
OID_DESCRIPTOR(MBEDTLS_OID_DIGEST_ALG_SHA1, "id-sha1", "SHA-1"),
MBEDTLS_MD_SHA1,
},
#endif
#if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_DIGEST_ALG_SHA224, "id-sha224", "SHA-224" ),
OID_DESCRIPTOR(MBEDTLS_OID_DIGEST_ALG_SHA224, "id-sha224", "SHA-224"),
MBEDTLS_MD_SHA224,
},
#endif
#if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_DIGEST_ALG_SHA256, "id-sha256", "SHA-256" ),
OID_DESCRIPTOR(MBEDTLS_OID_DIGEST_ALG_SHA256, "id-sha256", "SHA-256"),
MBEDTLS_MD_SHA256,
},
#endif
#if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_DIGEST_ALG_SHA384, "id-sha384", "SHA-384" ),
OID_DESCRIPTOR(MBEDTLS_OID_DIGEST_ALG_SHA384, "id-sha384", "SHA-384"),
MBEDTLS_MD_SHA384,
},
#endif
#if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_DIGEST_ALG_SHA512, "id-sha512", "SHA-512" ),
OID_DESCRIPTOR(MBEDTLS_OID_DIGEST_ALG_SHA512, "id-sha512", "SHA-512"),
MBEDTLS_MD_SHA512,
},
#endif
#if defined(MBEDTLS_HAS_ALG_RIPEMD160_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_DIGEST_ALG_RIPEMD160, "id-ripemd160", "RIPEMD-160" ),
OID_DESCRIPTOR(MBEDTLS_OID_DIGEST_ALG_RIPEMD160, "id-ripemd160", "RIPEMD-160"),
MBEDTLS_MD_RIPEMD160,
},
#endif
@ -642,7 +717,11 @@ static const oid_md_alg_t oid_md_alg[] =
FN_OID_TYPED_FROM_ASN1(oid_md_alg_t, md_alg, oid_md_alg)
FN_OID_GET_ATTR1(mbedtls_oid_get_md_alg, oid_md_alg_t, md_alg, mbedtls_md_type_t, md_alg)
FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_md, oid_md_alg_t, oid_md_alg, mbedtls_md_type_t, md_alg)
FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_md,
oid_md_alg_t,
oid_md_alg,
mbedtls_md_type_t,
md_alg)
/*
* For HMAC digestAlgorithm
@ -656,31 +735,31 @@ static const oid_md_hmac_t oid_md_hmac[] =
{
#if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_HMAC_SHA1, "hmacSHA1", "HMAC-SHA-1" ),
OID_DESCRIPTOR(MBEDTLS_OID_HMAC_SHA1, "hmacSHA1", "HMAC-SHA-1"),
MBEDTLS_MD_SHA1,
},
#endif /* MBEDTLS_HAS_ALG_SHA_1_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_HMAC_SHA224, "hmacSHA224", "HMAC-SHA-224" ),
OID_DESCRIPTOR(MBEDTLS_OID_HMAC_SHA224, "hmacSHA224", "HMAC-SHA-224"),
MBEDTLS_MD_SHA224,
},
#endif
#if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_HMAC_SHA256, "hmacSHA256", "HMAC-SHA-256" ),
OID_DESCRIPTOR(MBEDTLS_OID_HMAC_SHA256, "hmacSHA256", "HMAC-SHA-256"),
MBEDTLS_MD_SHA256,
},
#endif /* MBEDTLS_HAS_ALG_SHA_256_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_HMAC_SHA384, "hmacSHA384", "HMAC-SHA-384" ),
OID_DESCRIPTOR(MBEDTLS_OID_HMAC_SHA384, "hmacSHA384", "HMAC-SHA-384"),
MBEDTLS_MD_SHA384,
},
#endif /* MBEDTLS_HAS_ALG_SHA_384_VIA_LOWLEVEL_OR_PSA */
#if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_LOWLEVEL_OR_PSA)
{
OID_DESCRIPTOR( MBEDTLS_OID_HMAC_SHA512, "hmacSHA512", "HMAC-SHA-512" ),
OID_DESCRIPTOR(MBEDTLS_OID_HMAC_SHA512, "hmacSHA512", "HMAC-SHA-512"),
MBEDTLS_MD_SHA512,
},
#endif /* MBEDTLS_HAS_ALG_SHA_512_VIA_LOWLEVEL_OR_PSA */
@ -706,11 +785,15 @@ typedef struct {
static const oid_pkcs12_pbe_alg_t oid_pkcs12_pbe_alg[] =
{
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC, "pbeWithSHAAnd3-KeyTripleDES-CBC", "PBE with SHA1 and 3-Key 3DES" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC,
"pbeWithSHAAnd3-KeyTripleDES-CBC",
"PBE with SHA1 and 3-Key 3DES"),
MBEDTLS_MD_SHA1, MBEDTLS_CIPHER_DES_EDE3_CBC,
},
{
OID_DESCRIPTOR( MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC, "pbeWithSHAAnd2-KeyTripleDES-CBC", "PBE with SHA1 and 2-Key 3DES" ),
OID_DESCRIPTOR(MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC,
"pbeWithSHAAnd2-KeyTripleDES-CBC",
"PBE with SHA1 and 2-Key 3DES"),
MBEDTLS_MD_SHA1, MBEDTLS_CIPHER_DES_EDE_CBC,
},
{
@ -720,21 +803,27 @@ static const oid_pkcs12_pbe_alg_t oid_pkcs12_pbe_alg[] =
};
FN_OID_TYPED_FROM_ASN1(oid_pkcs12_pbe_alg_t, pkcs12_pbe_alg, oid_pkcs12_pbe_alg)
FN_OID_GET_ATTR2(mbedtls_oid_get_pkcs12_pbe_alg, oid_pkcs12_pbe_alg_t, pkcs12_pbe_alg, mbedtls_md_type_t, md_alg, mbedtls_cipher_type_t, cipher_alg)
FN_OID_GET_ATTR2(mbedtls_oid_get_pkcs12_pbe_alg,
oid_pkcs12_pbe_alg_t,
pkcs12_pbe_alg,
mbedtls_md_type_t,
md_alg,
mbedtls_cipher_type_t,
cipher_alg)
#endif /* MBEDTLS_PKCS12_C */
#define OID_SAFE_SNPRINTF \
do { \
if( ret < 0 || (size_t) ret >= n ) \
return( MBEDTLS_ERR_OID_BUF_TOO_SMALL ); \
\
if (ret < 0 || (size_t) ret >= n) \
return MBEDTLS_ERR_OID_BUF_TOO_SMALL; \
\
n -= (size_t) ret; \
p += (size_t) ret; \
} while( 0 )
} while (0)
/* 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 )
int mbedtls_oid_get_numeric_string(char *buf, size_t size,
const mbedtls_asn1_buf *oid)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i, n;
@ -745,32 +834,30 @@ int mbedtls_oid_get_numeric_string( char *buf, size_t size,
n = size;
/* First byte contains first two dots */
if( oid->len > 0 )
{
ret = mbedtls_snprintf( p, n, "%d.%d", oid->p[0] / 40, oid->p[0] % 40 );
if (oid->len > 0) {
ret = mbedtls_snprintf(p, n, "%d.%d", oid->p[0] / 40, oid->p[0] % 40);
OID_SAFE_SNPRINTF;
}
value = 0;
for( i = 1; i < oid->len; i++ )
{
for (i = 1; i < oid->len; i++) {
/* Prevent overflow in value. */
if( ( ( value << 7 ) >> 7 ) != value )
return( MBEDTLS_ERR_OID_BUF_TOO_SMALL );
if (((value << 7) >> 7) != value) {
return MBEDTLS_ERR_OID_BUF_TOO_SMALL;
}
value <<= 7;
value += oid->p[i] & 0x7F;
if( !( oid->p[i] & 0x80 ) )
{
if (!(oid->p[i] & 0x80)) {
/* Last byte */
ret = mbedtls_snprintf( p, n, ".%u", value );
ret = mbedtls_snprintf(p, n, ".%u", value);
OID_SAFE_SNPRINTF;
value = 0;
}
}
return( (int) ( size - n ) );
return (int) (size - n);
}
#endif /* MBEDTLS_OID_C */

View File

@ -42,14 +42,13 @@
/*
* PadLock detection routine
*/
int mbedtls_padlock_has_support( int feature )
int mbedtls_padlock_has_support(int feature)
{
static int flags = -1;
int ebx = 0, edx = 0;
if( flags == -1 )
{
asm( "movl %%ebx, %0 \n\t"
if (flags == -1) {
asm ("movl %%ebx, %0 \n\t"
"movl $0xC0000000, %%eax \n\t"
"cpuid \n\t"
"cmpl $0xC0000001, %%eax \n\t"
@ -62,21 +61,21 @@ int mbedtls_padlock_has_support( int feature )
"movl %2, %%ebx \n\t"
: "=m" (ebx), "=m" (edx)
: "m" (ebx)
: "eax", "ecx", "edx" );
: "eax", "ecx", "edx");
flags = edx;
}
return( flags & feature );
return flags & feature;
}
/*
* PadLock AES-ECB block en(de)cryption
*/
int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] )
int mbedtls_padlock_xcryptecb(mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16])
{
int ebx = 0;
uint32_t *rk;
@ -86,16 +85,17 @@ int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
rk = ctx->buf + ctx->rk_offset;
if( ( (long) rk & 15 ) != 0 )
return( MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED );
if (((long) rk & 15) != 0) {
return MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED;
}
blk = MBEDTLS_PADLOCK_ALIGN16( buf );
memcpy( blk, input, 16 );
blk = MBEDTLS_PADLOCK_ALIGN16(buf);
memcpy(blk, input, 16);
ctrl = blk + 4;
*ctrl = 0x80 | ctx->nr | ( ( ctx->nr + ( mode^1 ) - 10 ) << 9 );
ctrl = blk + 4;
*ctrl = 0x80 | ctx->nr | ((ctx->nr + (mode^1) - 10) << 9);
asm( "pushfl \n\t"
asm ("pushfl \n\t"
"popfl \n\t"
"movl %%ebx, %0 \n\t"
"movl $1, %%ecx \n\t"
@ -107,22 +107,22 @@ int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
"movl %1, %%ebx \n\t"
: "=m" (ebx)
: "m" (ebx), "m" (ctrl), "m" (rk), "m" (blk)
: "memory", "ecx", "edx", "esi", "edi" );
: "memory", "ecx", "edx", "esi", "edi");
memcpy( output, blk, 16 );
memcpy(output, blk, 16);
return( 0 );
return 0;
}
/*
* PadLock AES-CBC buffer en(de)cryption
*/
int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output )
int mbedtls_padlock_xcryptcbc(mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output)
{
int ebx = 0;
size_t count;
@ -133,20 +133,21 @@ int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,
rk = ctx->buf + ctx->rk_offset;
if( ( (long) input & 15 ) != 0 ||
( (long) output & 15 ) != 0 ||
( (long) rk & 15 ) != 0 )
return( MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED );
if (((long) input & 15) != 0 ||
((long) output & 15) != 0 ||
((long) rk & 15) != 0) {
return MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED;
}
iw = MBEDTLS_PADLOCK_ALIGN16( buf );
memcpy( iw, iv, 16 );
iw = MBEDTLS_PADLOCK_ALIGN16(buf);
memcpy(iw, iv, 16);
ctrl = iw + 4;
*ctrl = 0x80 | ctx->nr | ( ( ctx->nr + ( mode ^ 1 ) - 10 ) << 9 );
ctrl = iw + 4;
*ctrl = 0x80 | ctx->nr | ((ctx->nr + (mode ^ 1) - 10) << 9);
count = ( length + 15 ) >> 4;
count = (length + 15) >> 4;
asm( "pushfl \n\t"
asm ("pushfl \n\t"
"popfl \n\t"
"movl %%ebx, %0 \n\t"
"movl %2, %%ecx \n\t"
@ -159,12 +160,12 @@ int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,
"movl %1, %%ebx \n\t"
: "=m" (ebx)
: "m" (ebx), "m" (count), "m" (ctrl),
"m" (rk), "m" (input), "m" (output), "m" (iw)
: "memory", "eax", "ecx", "edx", "esi", "edi" );
"m" (rk), "m" (input), "m" (output), "m" (iw)
: "memory", "eax", "ecx", "edx", "esi", "edi");
memcpy( iv, iw, 16 );
memcpy(iv, iw, 16);
return( 0 );
return 0;
}
#endif /* MBEDTLS_HAVE_X86 */

View File

@ -69,7 +69,7 @@ extern "C" {
*
* \return non-zero if CPU has support for the feature, 0 otherwise
*/
int mbedtls_padlock_has_support( int feature );
int mbedtls_padlock_has_support(int feature);
/**
* \brief Internal PadLock AES-ECB block en(de)cryption
@ -84,10 +84,10 @@ int mbedtls_padlock_has_support( int feature );
*
* \return 0 if success, 1 if operation failed
*/
int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] );
int mbedtls_padlock_xcryptecb(mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16]);
/**
* \brief Internal PadLock AES-CBC buffer en(de)cryption
@ -104,12 +104,12 @@ int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
*
* \return 0 if success, 1 if operation failed
*/
int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output );
int mbedtls_padlock_xcryptcbc(mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output);
#ifdef __cplusplus
}

View File

@ -43,106 +43,121 @@
#if defined(MBEDTLS_HAS_ALG_MD5_VIA_MD_OR_PSA_BASED_ON_USE_PSA) && \
defined(MBEDTLS_CIPHER_MODE_CBC) && \
( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
(defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C))
#define PEM_RFC1421
#endif /* MBEDTLS_HAS_ALG_MD5_VIA_MD_OR_PSA_BASED_ON_USE_PSA &&
MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
#if defined(MBEDTLS_PEM_PARSE_C)
void mbedtls_pem_init( mbedtls_pem_context *ctx )
void mbedtls_pem_init(mbedtls_pem_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_pem_context ) );
memset(ctx, 0, sizeof(mbedtls_pem_context));
}
#if defined(PEM_RFC1421)
/*
* Read a 16-byte hex string and convert it to binary
*/
static int pem_get_iv( const unsigned char *s, unsigned char *iv,
size_t iv_len )
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 );
memset(iv, 0, 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 );
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;
k = ((i & 1) != 0) ? j : j << 4;
iv[i >> 1] = (unsigned char)( iv[i >> 1] | k );
iv[i >> 1] = (unsigned char) (iv[i >> 1] | k);
}
return( 0 );
return 0;
}
#if defined(MBEDTLS_MD5_C)
static int pem_pbkdf1( unsigned char *key, size_t keylen,
unsigned char *iv,
const unsigned char *pwd, size_t pwdlen )
static int pem_pbkdf1(unsigned char *key, size_t keylen,
unsigned char *iv,
const unsigned char *pwd, size_t pwdlen)
{
mbedtls_md5_context md5_ctx;
unsigned char md5sum[16];
size_t use_len;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md5_init( &md5_ctx );
mbedtls_md5_init(&md5_ctx);
/*
* key[ 0..15] = MD5(pwd || IV)
*/
if( ( ret = mbedtls_md5_starts( &md5_ctx ) ) != 0 )
if ((ret = mbedtls_md5_starts(&md5_ctx)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update( &md5_ctx, pwd, pwdlen ) ) != 0 )
}
if ((ret = mbedtls_md5_update(&md5_ctx, pwd, pwdlen)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update( &md5_ctx, iv, 8 ) ) != 0 )
}
if ((ret = mbedtls_md5_update(&md5_ctx, iv, 8)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_finish( &md5_ctx, md5sum ) ) != 0 )
goto exit;
if( keylen <= 16 )
{
memcpy( key, md5sum, keylen );
}
if ((ret = mbedtls_md5_finish(&md5_ctx, md5sum)) != 0) {
goto exit;
}
memcpy( key, md5sum, 16 );
if (keylen <= 16) {
memcpy(key, md5sum, keylen);
goto exit;
}
memcpy(key, md5sum, 16);
/*
* key[16..23] = MD5(key[ 0..15] || pwd || IV])
*/
if( ( ret = mbedtls_md5_starts( &md5_ctx ) ) != 0 )
if ((ret = mbedtls_md5_starts(&md5_ctx)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update( &md5_ctx, md5sum, 16 ) ) != 0 )
}
if ((ret = mbedtls_md5_update(&md5_ctx, md5sum, 16)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update( &md5_ctx, pwd, pwdlen ) ) != 0 )
}
if ((ret = mbedtls_md5_update(&md5_ctx, pwd, pwdlen)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update( &md5_ctx, iv, 8 ) ) != 0 )
}
if ((ret = mbedtls_md5_update(&md5_ctx, iv, 8)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_finish( &md5_ctx, md5sum ) ) != 0 )
}
if ((ret = mbedtls_md5_finish(&md5_ctx, md5sum)) != 0) {
goto exit;
}
use_len = 16;
if( keylen < 32 )
if (keylen < 32) {
use_len = keylen - 16;
}
memcpy( key + 16, md5sum, use_len );
memcpy(key + 16, md5sum, use_len);
exit:
mbedtls_md5_free( &md5_ctx );
mbedtls_platform_zeroize( md5sum, 16 );
mbedtls_md5_free(&md5_ctx);
mbedtls_platform_zeroize(md5sum, 16);
return( ret );
return ret;
}
#else
static int pem_pbkdf1( unsigned char *key, size_t keylen,
unsigned char *iv,
const unsigned char *pwd, size_t pwdlen )
static int pem_pbkdf1(unsigned char *key, size_t keylen,
unsigned char *iv,
const unsigned char *pwd, size_t pwdlen)
{
unsigned char md5sum[16];
psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
@ -150,71 +165,78 @@ static int pem_pbkdf1( unsigned char *key, size_t keylen,
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( ( status = psa_hash_setup( &operation, PSA_ALG_MD5 ) ) != PSA_SUCCESS )
goto exit;
if( ( status = psa_hash_update( &operation, pwd, pwdlen ) ) != PSA_SUCCESS )
goto exit;
if( ( status = psa_hash_update( &operation, iv, 8 ) ) != PSA_SUCCESS )
goto exit;
if( ( status = psa_hash_finish( &operation, md5sum,
PSA_HASH_LENGTH( PSA_ALG_MD5 ),
&output_length ) ) != PSA_SUCCESS )
{
if ((status = psa_hash_setup(&operation, PSA_ALG_MD5)) != PSA_SUCCESS) {
goto exit;
}
if( ( status = psa_hash_abort( &operation ) ) != PSA_SUCCESS )
if ((status = psa_hash_update(&operation, pwd, pwdlen)) != PSA_SUCCESS) {
goto exit;
}
if ((status = psa_hash_update(&operation, iv, 8)) != PSA_SUCCESS) {
goto exit;
}
if ((status = psa_hash_finish(&operation, md5sum,
PSA_HASH_LENGTH(PSA_ALG_MD5),
&output_length)) != PSA_SUCCESS) {
goto exit;
}
if ((status = psa_hash_abort(&operation)) != PSA_SUCCESS) {
goto exit;
}
/*
* key[ 0..15] = MD5(pwd || IV)
*/
if( keylen <= 16 )
{
memcpy( key, md5sum, keylen );
if (keylen <= 16) {
memcpy(key, md5sum, keylen);
goto exit;
}
memcpy( key, md5sum, 16 );
memcpy(key, md5sum, 16);
/*
* key[16..23] = MD5(key[ 0..15] || pwd || IV])
*/
if( ( status = psa_hash_setup( &operation, PSA_ALG_MD5 ) ) != PSA_SUCCESS )
goto exit;
if( ( status = psa_hash_update( &operation, md5sum, 16 ) ) != PSA_SUCCESS )
goto exit;
if( ( status = psa_hash_update( &operation, pwd, pwdlen ) ) != PSA_SUCCESS )
goto exit;
if( ( status = psa_hash_update( &operation, iv, 8 ) ) != PSA_SUCCESS )
goto exit;
if( ( status = psa_hash_finish( &operation, md5sum,
PSA_HASH_LENGTH( PSA_ALG_MD5 ),
&output_length ) ) != PSA_SUCCESS )
{
if ((status = psa_hash_setup(&operation, PSA_ALG_MD5)) != PSA_SUCCESS) {
goto exit;
}
if( ( status = psa_hash_abort( &operation ) ) != PSA_SUCCESS )
if ((status = psa_hash_update(&operation, md5sum, 16)) != PSA_SUCCESS) {
goto exit;
}
if ((status = psa_hash_update(&operation, pwd, pwdlen)) != PSA_SUCCESS) {
goto exit;
}
if ((status = psa_hash_update(&operation, iv, 8)) != PSA_SUCCESS) {
goto exit;
}
if ((status = psa_hash_finish(&operation, md5sum,
PSA_HASH_LENGTH(PSA_ALG_MD5),
&output_length)) != PSA_SUCCESS) {
goto exit;
}
if ((status = psa_hash_abort(&operation)) != PSA_SUCCESS) {
goto exit;
}
size_t use_len = 16;
if( keylen < 32 )
if (keylen < 32) {
use_len = keylen - 16;
}
memcpy( key + 16, md5sum, use_len );
memcpy(key + 16, md5sum, use_len);
exit:
mbedtls_platform_zeroize( md5sum, 16 );
mbedtls_platform_zeroize(md5sum, 16);
return( mbedtls_md_error_from_psa ( status ) );
return mbedtls_md_error_from_psa(status);
}
#endif /* MBEDTLS_MD5_C */
@ -222,57 +244,61 @@ exit:
/*
* Decrypt with DES-CBC, using PBKDF1 for key derivation
*/
static int pem_des_decrypt( unsigned char des_iv[8],
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen )
static int pem_des_decrypt(unsigned char des_iv[8],
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen)
{
mbedtls_des_context des_ctx;
unsigned char des_key[8];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_des_init( &des_ctx );
mbedtls_des_init(&des_ctx);
if( ( ret = pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen ) ) != 0 )
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 )
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 );
}
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 );
mbedtls_des_free(&des_ctx);
mbedtls_platform_zeroize(des_key, 8);
return( ret );
return ret;
}
/*
* Decrypt with 3DES-CBC, using PBKDF1 for key derivation
*/
static int pem_des3_decrypt( unsigned char des3_iv[8],
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen )
static int pem_des3_decrypt(unsigned char des3_iv[8],
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen)
{
mbedtls_des3_context des3_ctx;
unsigned char des3_key[24];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_des3_init( &des3_ctx );
mbedtls_des3_init(&des3_ctx);
if( ( ret = pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen ) ) != 0 )
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 )
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 );
}
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 );
mbedtls_des3_free(&des3_ctx);
mbedtls_platform_zeroize(des3_key, 24);
return( ret );
return ret;
}
#endif /* MBEDTLS_DES_C */
@ -280,37 +306,39 @@ exit:
/*
* Decrypt with AES-XXX-CBC, using PBKDF1 for key derivation
*/
static int pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen,
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen )
static int pem_aes_decrypt(unsigned char aes_iv[16], unsigned int keylen,
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen)
{
mbedtls_aes_context aes_ctx;
unsigned char aes_key[32];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_aes_init( &aes_ctx );
mbedtls_aes_init(&aes_ctx);
if( ( ret = pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen ) ) != 0 )
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 )
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 );
}
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 );
mbedtls_aes_free(&aes_ctx);
mbedtls_platform_zeroize(aes_key, keylen);
return( ret );
return ret;
}
#endif /* MBEDTLS_AES_C */
#endif /* PEM_RFC1421 */
int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const char *footer,
const unsigned char *data, const unsigned char *pwd,
size_t pwdlen, size_t *use_len )
int mbedtls_pem_read_buffer(mbedtls_pem_context *ctx, const char *header, const char *footer,
const unsigned char *data, const unsigned char *pwd,
size_t pwdlen, size_t *use_len)
{
int ret, enc;
size_t len;
@ -324,151 +352,178 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
((void) pwdlen);
#endif /* PEM_RFC1421 */
if( ctx == NULL )
return( MBEDTLS_ERR_PEM_BAD_INPUT_DATA );
if (ctx == NULL) {
return MBEDTLS_ERR_PEM_BAD_INPUT_DATA;
}
s1 = (unsigned char *) strstr( (const char *) data, header );
s1 = (unsigned char *) strstr((const char *) data, header);
if( s1 == NULL )
return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
if (s1 == NULL) {
return MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
}
s2 = (unsigned char *) strstr( (const char *) data, footer );
s2 = (unsigned char *) strstr((const char *) data, footer);
if( s2 == NULL || s2 <= s1 )
return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
if (s2 == NULL || 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 );
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++;
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 (s2 - s1 >= 22 && memcmp(s1, "Proc-Type: 4,ENCRYPTED", 22) == 0) {
#if defined(PEM_RFC1421)
enc++;
s1 += 22;
if( *s1 == '\r' ) s1++;
if( *s1 == '\n' ) s1++;
else return( MBEDTLS_ERR_PEM_INVALID_DATA );
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 )
{
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 );
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 )
{
} 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 );
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 )
{
if( s2 - s1 < 22 )
return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
else if( memcmp( s1, "DEK-Info: AES-128-CBC,", 22 ) == 0 )
if (s2 - s1 >= 14 && memcmp(s1, "DEK-Info: AES-", 14) == 0) {
if (s2 - s1 < 22) {
return MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG;
} else if (memcmp(s1, "DEK-Info: AES-128-CBC,", 22) == 0) {
enc_alg = MBEDTLS_CIPHER_AES_128_CBC;
else if( memcmp( s1, "DEK-Info: AES-192-CBC,", 22 ) == 0 )
} else if (memcmp(s1, "DEK-Info: AES-192-CBC,", 22) == 0) {
enc_alg = MBEDTLS_CIPHER_AES_192_CBC;
else if( memcmp( s1, "DEK-Info: AES-256-CBC,", 22 ) == 0 )
} else if (memcmp(s1, "DEK-Info: AES-256-CBC,", 22) == 0) {
enc_alg = MBEDTLS_CIPHER_AES_256_CBC;
else
return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
} 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 );
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 (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 );
if (*s1 == '\r') {
s1++;
}
if (*s1 == '\n') {
s1++;
} else {
return MBEDTLS_ERR_PEM_INVALID_DATA;
}
#else
return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE );
return MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE;
#endif /* PEM_RFC1421 */
}
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_ERROR_ADD( 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_ERROR_ADD( MBEDTLS_ERR_PEM_INVALID_DATA, ret ) );
if (s1 >= s2) {
return MBEDTLS_ERR_PEM_INVALID_DATA;
}
if( enc != 0 )
{
ret = mbedtls_base64_decode(NULL, 0, &len, s1, s2 - s1);
if (ret == MBEDTLS_ERR_BASE64_INVALID_CHARACTER) {
return MBEDTLS_ERROR_ADD(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_ERROR_ADD(MBEDTLS_ERR_PEM_INVALID_DATA, ret);
}
if (enc != 0) {
#if defined(PEM_RFC1421)
if( pwd == NULL )
{
mbedtls_platform_zeroize( buf, len );
mbedtls_free( buf );
return( MBEDTLS_ERR_PEM_PASSWORD_REQUIRED );
if (pwd == NULL) {
mbedtls_platform_zeroize(buf, len);
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 );
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 );
else if( enc_alg == MBEDTLS_CIPHER_AES_192_CBC )
ret = pem_aes_decrypt( pem_iv, 24, buf, len, pwd, pwdlen );
else if( enc_alg == MBEDTLS_CIPHER_AES_256_CBC )
ret = pem_aes_decrypt( pem_iv, 32, buf, len, pwd, pwdlen );
if (enc_alg == MBEDTLS_CIPHER_AES_128_CBC) {
ret = pem_aes_decrypt(pem_iv, 16, buf, len, pwd, pwdlen);
} else if (enc_alg == MBEDTLS_CIPHER_AES_192_CBC) {
ret = pem_aes_decrypt(pem_iv, 24, buf, len, pwd, pwdlen);
} 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 );
if (ret != 0) {
mbedtls_free(buf);
return ret;
}
/*
@ -477,93 +532,88 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
*
* Use that as a heuristic to try to detect password mismatches.
*/
if( len <= 2 || buf[0] != 0x30 || buf[1] > 0x83 )
{
mbedtls_platform_zeroize( buf, len );
mbedtls_free( buf );
return( MBEDTLS_ERR_PEM_PASSWORD_MISMATCH );
if (len <= 2 || buf[0] != 0x30 || buf[1] > 0x83) {
mbedtls_platform_zeroize(buf, len);
mbedtls_free(buf);
return MBEDTLS_ERR_PEM_PASSWORD_MISMATCH;
}
#else
mbedtls_platform_zeroize( buf, len );
mbedtls_free( buf );
return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE );
mbedtls_platform_zeroize(buf, len);
mbedtls_free(buf);
return MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE;
#endif /* PEM_RFC1421 */
}
ctx->buf = buf;
ctx->buflen = len;
return( 0 );
return 0;
}
void mbedtls_pem_free( mbedtls_pem_context *ctx )
void mbedtls_pem_free(mbedtls_pem_context *ctx)
{
if ( ctx->buf != NULL )
{
mbedtls_platform_zeroize( ctx->buf, ctx->buflen );
mbedtls_free( ctx->buf );
if (ctx->buf != NULL) {
mbedtls_platform_zeroize(ctx->buf, ctx->buflen);
mbedtls_free(ctx->buf);
}
mbedtls_free( ctx->info );
mbedtls_free(ctx->info);
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_pem_context));
}
#endif /* MBEDTLS_PEM_PARSE_C */
#if defined(MBEDTLS_PEM_WRITE_C)
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 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;
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;
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 )
{
if (use_len + add_len > buf_len) {
*olen = use_len + add_len;
return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
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 );
if (use_len != 0 &&
((encode_buf = mbedtls_calloc(1, use_len)) == NULL)) {
return MBEDTLS_ERR_PEM_ALLOC_FAILED;
}
memcpy( p, header, strlen( header ) );
p += strlen( header );
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;
memcpy( p, c, len );
while (use_len) {
len = (use_len > 64) ? 64 : use_len;
memcpy(p, c, len);
use_len -= len;
p += len;
c += len;
*p++ = '\n';
}
memcpy( p, footer, strlen( footer ) );
p += strlen( footer );
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 );
/* Clean any remaining data previously written to the buffer */
memset(buf + *olen, 0, buf_len - *olen);
mbedtls_free( encode_buf );
return( 0 );
mbedtls_free(encode_buf);
return 0;
}
#endif /* MBEDTLS_PEM_WRITE_C */
#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -31,8 +31,7 @@
#include "psa/crypto.h"
#endif /* MBEDTLS_PSA_CRYPTO_C */
struct mbedtls_pk_info_t
{
struct mbedtls_pk_info_t {
/** Public key type */
mbedtls_pk_type_t type;
@ -40,77 +39,76 @@ struct mbedtls_pk_info_t
const char *name;
/** Get key size in bits */
size_t (*get_bitlen)( const void * );
size_t (*get_bitlen)(const void *);
/** Tell if the context implements this type (e.g. ECKEY can do ECDSA) */
int (*can_do)( mbedtls_pk_type_t type );
int (*can_do)(mbedtls_pk_type_t type);
/** Verify signature */
int (*verify_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len );
int (*verify_func)(void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len);
/** Make signature */
int (*sign_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t sig_size, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int (*sign_func)(void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t sig_size, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/** Verify signature (restartable) */
int (*verify_rs_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx );
int (*verify_rs_func)(void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx);
/** Make signature (restartable) */
int (*sign_rs_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t sig_size, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, void *rs_ctx );
int (*sign_rs_func)(void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t sig_size, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, void *rs_ctx);
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/** Decrypt message */
int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int (*decrypt_func)(void *ctx, const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
/** Encrypt message */
int (*encrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int (*encrypt_func)(void *ctx, const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
/** Check public-private key pair */
int (*check_pair_func)( const void *pub, const void *prv,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
int (*check_pair_func)(const void *pub, const void *prv,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng);
/** Allocate a new context */
void * (*ctx_alloc_func)( void );
void * (*ctx_alloc_func)(void);
/** Free the given context */
void (*ctx_free_func)( void *ctx );
void (*ctx_free_func)(void *ctx);
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/** Allocate the restart context */
void * (*rs_alloc_func)( void );
void *(*rs_alloc_func)(void);
/** Free the restart context */
void (*rs_free_func)( void *rs_ctx );
void (*rs_free_func)(void *rs_ctx);
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/** Interface with the debug module */
void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items );
void (*debug_func)(const void *ctx, mbedtls_pk_debug_item *items);
};
#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
/* Container for RSA-alt */
typedef struct
{
typedef struct {
void *key;
mbedtls_pk_rsa_alt_decrypt_func decrypt_func;
mbedtls_pk_rsa_alt_sign_func sign_func;
@ -140,25 +138,25 @@ extern const mbedtls_pk_info_t mbedtls_pk_ecdsa_opaque_info;
extern const mbedtls_pk_info_t mbedtls_pk_rsa_opaque_info;
#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
int mbedtls_pk_error_from_psa_ecdsa( psa_status_t status );
int mbedtls_pk_error_from_psa_ecdsa(psa_status_t status);
#endif
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#if defined(MBEDTLS_PSA_CRYPTO_C)
int mbedtls_pk_error_from_psa( psa_status_t status );
int mbedtls_pk_error_from_psa(psa_status_t status);
#if defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
int mbedtls_pk_error_from_psa_rsa( psa_status_t status );
int mbedtls_pk_error_from_psa_rsa(psa_status_t status);
#endif /* PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY || PSA_WANT_KEY_TYPE_RSA_KEY_PAIR */
#if defined(MBEDTLS_RSA_C)
int mbedtls_pk_psa_rsa_sign_ext( psa_algorithm_t psa_alg_md,
mbedtls_rsa_context *rsa_ctx,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t sig_size,
size_t *sig_len );
int mbedtls_pk_psa_rsa_sign_ext(psa_algorithm_t psa_alg_md,
mbedtls_rsa_context *rsa_ctx,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t sig_size,
size_t *sig_len);
#endif /* MBEDTLS_RSA_C */
#endif /* MBEDTLS_PSA_CRYPTO_C */

View File

@ -44,8 +44,8 @@
#if defined(MBEDTLS_ASN1_PARSE_C)
static int pkcs12_parse_pbe_params( mbedtls_asn1_buf *params,
mbedtls_asn1_buf *salt, int *iterations )
static int pkcs12_parse_pbe_params(mbedtls_asn1_buf *params,
mbedtls_asn1_buf *salt, int *iterations)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char **p = &params->p;
@ -58,77 +58,83 @@ static int pkcs12_parse_pbe_params( mbedtls_asn1_buf *params,
* }
*
*/
if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
if (params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
}
if( ( ret = mbedtls_asn1_get_tag( p, end, &salt->len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT, ret ) );
if ((ret = mbedtls_asn1_get_tag(p, end, &salt->len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT, ret);
}
salt->p = *p;
*p += salt->len;
if( ( ret = mbedtls_asn1_get_int( p, end, iterations ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT, ret ) );
if ((ret = mbedtls_asn1_get_int(p, end, iterations)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT, ret);
}
if( *p != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
if (*p != end) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
}
return( 0 );
return 0;
}
#define PKCS12_MAX_PWDLEN 128
static int pkcs12_pbe_derive_key_iv( mbedtls_asn1_buf *pbe_params, mbedtls_md_type_t md_type,
const unsigned char *pwd, size_t pwdlen,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen )
static int pkcs12_pbe_derive_key_iv(mbedtls_asn1_buf *pbe_params, mbedtls_md_type_t md_type,
const unsigned char *pwd, size_t pwdlen,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen)
{
int ret, iterations = 0;
mbedtls_asn1_buf salt;
size_t i;
unsigned char unipwd[PKCS12_MAX_PWDLEN * 2 + 2];
if( pwdlen > PKCS12_MAX_PWDLEN )
return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );
if (pwdlen > PKCS12_MAX_PWDLEN) {
return MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA;
}
memset( &salt, 0, sizeof(mbedtls_asn1_buf) );
memset( &unipwd, 0, sizeof(unipwd) );
memset(&salt, 0, sizeof(mbedtls_asn1_buf));
memset(&unipwd, 0, sizeof(unipwd));
if( ( ret = pkcs12_parse_pbe_params( pbe_params, &salt,
&iterations ) ) != 0 )
return( ret );
if ((ret = pkcs12_parse_pbe_params(pbe_params, &salt,
&iterations)) != 0) {
return ret;
}
for( i = 0; i < pwdlen; i++ )
for (i = 0; i < pwdlen; i++) {
unipwd[i * 2 + 1] = pwd[i];
if( ( ret = mbedtls_pkcs12_derivation( key, keylen, unipwd, pwdlen * 2 + 2,
salt.p, salt.len, md_type,
MBEDTLS_PKCS12_DERIVE_KEY, iterations ) ) != 0 )
{
return( ret );
}
if( iv == NULL || ivlen == 0 )
return( 0 );
if( ( ret = mbedtls_pkcs12_derivation( iv, ivlen, unipwd, pwdlen * 2 + 2,
salt.p, salt.len, md_type,
MBEDTLS_PKCS12_DERIVE_IV, iterations ) ) != 0 )
{
return( ret );
if ((ret = mbedtls_pkcs12_derivation(key, keylen, unipwd, pwdlen * 2 + 2,
salt.p, salt.len, md_type,
MBEDTLS_PKCS12_DERIVE_KEY, iterations)) != 0) {
return ret;
}
return( 0 );
if (iv == NULL || ivlen == 0) {
return 0;
}
if ((ret = mbedtls_pkcs12_derivation(iv, ivlen, unipwd, pwdlen * 2 + 2,
salt.p, salt.len, md_type,
MBEDTLS_PKCS12_DERIVE_IV, iterations)) != 0) {
return ret;
}
return 0;
}
#undef PKCS12_MAX_PWDLEN
int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode,
mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t len,
unsigned char *output )
int mbedtls_pkcs12_pbe(mbedtls_asn1_buf *pbe_params, int mode,
mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t len,
unsigned char *output)
{
int ret, keylen = 0;
unsigned char key[32];
@ -137,73 +143,76 @@ int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode,
mbedtls_cipher_context_t cipher_ctx;
size_t olen = 0;
if( pwd == NULL && pwdlen != 0 )
return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );
if (pwd == NULL && pwdlen != 0) {
return MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA;
}
cipher_info = mbedtls_cipher_info_from_type( cipher_type );
if( cipher_info == NULL )
return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
cipher_info = mbedtls_cipher_info_from_type(cipher_type);
if (cipher_info == NULL) {
return MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE;
}
keylen = cipher_info->key_bitlen / 8;
if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, md_type, pwd, pwdlen,
key, keylen,
iv, cipher_info->iv_size ) ) != 0 )
{
return( ret );
if ((ret = pkcs12_pbe_derive_key_iv(pbe_params, md_type, pwd, pwdlen,
key, keylen,
iv, cipher_info->iv_size)) != 0) {
return ret;
}
mbedtls_cipher_init( &cipher_ctx );
mbedtls_cipher_init(&cipher_ctx);
if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen, (mbedtls_operation_t) mode ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_set_iv( &cipher_ctx, iv, cipher_info->iv_size ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_reset( &cipher_ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_update( &cipher_ctx, data, len,
output, &olen ) ) != 0 )
{
if ((ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0) {
goto exit;
}
if( ( ret = mbedtls_cipher_finish( &cipher_ctx, output + olen, &olen ) ) != 0 )
if ((ret =
mbedtls_cipher_setkey(&cipher_ctx, key, 8 * keylen,
(mbedtls_operation_t) mode)) != 0) {
goto exit;
}
if ((ret = mbedtls_cipher_set_iv(&cipher_ctx, iv, cipher_info->iv_size)) != 0) {
goto exit;
}
if ((ret = mbedtls_cipher_reset(&cipher_ctx)) != 0) {
goto exit;
}
if ((ret = mbedtls_cipher_update(&cipher_ctx, data, len,
output, &olen)) != 0) {
goto exit;
}
if ((ret = mbedtls_cipher_finish(&cipher_ctx, output + olen, &olen)) != 0) {
ret = MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH;
}
exit:
mbedtls_platform_zeroize( key, sizeof( key ) );
mbedtls_platform_zeroize( iv, sizeof( iv ) );
mbedtls_cipher_free( &cipher_ctx );
mbedtls_platform_zeroize(key, sizeof(key));
mbedtls_platform_zeroize(iv, sizeof(iv));
mbedtls_cipher_free(&cipher_ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_ASN1_PARSE_C */
static void pkcs12_fill_buffer( unsigned char *data, size_t data_len,
const unsigned char *filler, size_t fill_len )
static void pkcs12_fill_buffer(unsigned char *data, size_t data_len,
const unsigned char *filler, size_t fill_len)
{
unsigned char *p = data;
size_t use_len;
if( filler != NULL && fill_len != 0 )
{
while( data_len > 0 )
{
use_len = ( data_len > fill_len ) ? fill_len : data_len;
memcpy( p, filler, use_len );
if (filler != NULL && fill_len != 0) {
while (data_len > 0) {
use_len = (data_len > fill_len) ? fill_len : data_len;
memcpy(p, filler, use_len);
p += use_len;
data_len -= use_len;
}
}
else
{
} else {
/* If either of the above are not true then clearly there is nothing
* that this function can do. The function should *not* be called
* under either of those circumstances, as you could end up with an
@ -213,117 +222,127 @@ static void pkcs12_fill_buffer( unsigned char *data, size_t data_len,
}
static int calculate_hashes( mbedtls_md_type_t md_type, int iterations,
unsigned char *diversifier, unsigned char *salt_block,
unsigned char *pwd_block, unsigned char *hash_output, int use_salt,
int use_password, size_t hlen, size_t v )
static int calculate_hashes(mbedtls_md_type_t md_type, int iterations,
unsigned char *diversifier, unsigned char *salt_block,
unsigned char *pwd_block, unsigned char *hash_output, int use_salt,
int use_password, size_t hlen, size_t v)
{
#if defined(MBEDTLS_MD_C)
int ret = -1;
size_t i;
const mbedtls_md_info_t *md_info;
mbedtls_md_context_t md_ctx;
md_info = mbedtls_md_info_from_type( md_type );
if( md_info == NULL )
return ( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
md_info = mbedtls_md_info_from_type(md_type);
if (md_info == NULL) {
return MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE;
}
mbedtls_md_init( &md_ctx );
mbedtls_md_init(&md_ctx);
if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
return ( ret );
if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
return ret;
}
// Calculate hash( diversifier || salt_block || pwd_block )
if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 )
if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
goto exit;
if( ( ret = mbedtls_md_update( &md_ctx, diversifier, v ) ) != 0 )
goto exit;
if( use_salt != 0 )
{
if( ( ret = mbedtls_md_update( &md_ctx, salt_block, v ) ) != 0 )
goto exit;
}
if( use_password != 0 )
{
if( ( ret = mbedtls_md_update( &md_ctx, pwd_block, v ) ) != 0 )
goto exit;
if ((ret = mbedtls_md_update(&md_ctx, diversifier, v)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md_finish( &md_ctx, hash_output ) ) != 0 )
if (use_salt != 0) {
if ((ret = mbedtls_md_update(&md_ctx, salt_block, v)) != 0) {
goto exit;
}
}
if (use_password != 0) {
if ((ret = mbedtls_md_update(&md_ctx, pwd_block, v)) != 0) {
goto exit;
}
}
if ((ret = mbedtls_md_finish(&md_ctx, hash_output)) != 0) {
goto exit;
}
// Perform remaining ( iterations - 1 ) recursive hash calculations
for( i = 1; i < (size_t) iterations; i++ )
{
if( ( ret = mbedtls_md( md_info, hash_output, hlen, hash_output ) )
!= 0 )
for (i = 1; i < (size_t) iterations; i++) {
if ((ret = mbedtls_md(md_info, hash_output, hlen, hash_output))
!= 0) {
goto exit;
}
}
exit:
mbedtls_md_free( &md_ctx );
mbedtls_md_free(&md_ctx);
return ret;
#else
psa_hash_operation_t op = PSA_HASH_OPERATION_INIT;
psa_algorithm_t alg = mbedtls_psa_translate_md( md_type );
psa_algorithm_t alg = mbedtls_psa_translate_md(md_type);
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t status_abort = PSA_ERROR_CORRUPTION_DETECTED;
size_t i, out_len, out_size = PSA_HASH_LENGTH( alg );
size_t i, out_len, out_size = PSA_HASH_LENGTH(alg);
if( alg == PSA_ALG_NONE )
return ( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
if (alg == PSA_ALG_NONE) {
return MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE;
}
if( ( status = psa_hash_setup( &op, alg ) ) != PSA_SUCCESS )
if ((status = psa_hash_setup(&op, alg)) != PSA_SUCCESS) {
goto exit;
}
// Calculate hash( diversifier || salt_block || pwd_block )
if( ( status = psa_hash_update( &op, diversifier, v ) ) != PSA_SUCCESS )
if ((status = psa_hash_update(&op, diversifier, v)) != PSA_SUCCESS) {
goto exit;
if( use_salt != 0 )
{
if( ( status = psa_hash_update( &op, salt_block, v ) ) != PSA_SUCCESS )
goto exit;
}
if( use_password != 0 )
{
if( ( status = psa_hash_update( &op, pwd_block, v ) ) != PSA_SUCCESS )
if (use_salt != 0) {
if ((status = psa_hash_update(&op, salt_block, v)) != PSA_SUCCESS) {
goto exit;
}
}
if( ( status = psa_hash_finish( &op, hash_output, out_size, &out_len ) )
!= PSA_SUCCESS )
if (use_password != 0) {
if ((status = psa_hash_update(&op, pwd_block, v)) != PSA_SUCCESS) {
goto exit;
}
}
if ((status = psa_hash_finish(&op, hash_output, out_size, &out_len))
!= PSA_SUCCESS) {
goto exit;
}
// Perform remaining ( iterations - 1 ) recursive hash calculations
for( i = 1; i < (size_t) iterations; i++ )
{
if( ( status = psa_hash_compute( alg, hash_output, hlen, hash_output,
out_size, &out_len ) ) != PSA_SUCCESS )
for (i = 1; i < (size_t) iterations; i++) {
if ((status = psa_hash_compute(alg, hash_output, hlen, hash_output,
out_size, &out_len)) != PSA_SUCCESS) {
goto exit;
}
}
exit:
status_abort = psa_hash_abort( &op );
if( status == PSA_SUCCESS )
status_abort = psa_hash_abort(&op);
if (status == PSA_SUCCESS) {
status = status_abort;
return ( mbedtls_md_error_from_psa( status ) );
}
return mbedtls_md_error_from_psa(status);
#endif /* !MBEDTLS_MD_C */
}
int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *salt, size_t saltlen,
mbedtls_md_type_t md_type, int id, int iterations )
int mbedtls_pkcs12_derivation(unsigned char *data, size_t datalen,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *salt, size_t saltlen,
mbedtls_md_type_t md_type, int id, int iterations)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned int j;
unsigned char diversifier[128];
unsigned char salt_block[128], pwd_block[128], hash_block[128] = {0};
unsigned char salt_block[128], pwd_block[128], hash_block[128] = { 0 };
unsigned char hash_output[MBEDTLS_HASH_MAX_SIZE];
unsigned char *p;
unsigned char c;
@ -333,84 +352,83 @@ int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen,
size_t hlen, use_len, v, i;
// This version only allows max of 64 bytes of password or salt
if( datalen > 128 || pwdlen > 64 || saltlen > 64 )
return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );
if( pwd == NULL && pwdlen != 0 )
return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );
if( salt == NULL && saltlen != 0 )
return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );
use_password = ( pwd && pwdlen != 0 );
use_salt = ( salt && saltlen != 0 );
hlen = mbedtls_hash_info_get_size( md_type );
if( hlen <= 32 )
v = 64;
else
v = 128;
memset( diversifier, (unsigned char) id, v );
if( use_salt != 0 )
{
pkcs12_fill_buffer( salt_block, v, salt, saltlen );
if (datalen > 128 || pwdlen > 64 || saltlen > 64) {
return MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA;
}
if( use_password != 0 )
{
pkcs12_fill_buffer( pwd_block, v, pwd, pwdlen );
if (pwd == NULL && pwdlen != 0) {
return MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA;
}
if (salt == NULL && saltlen != 0) {
return MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA;
}
use_password = (pwd && pwdlen != 0);
use_salt = (salt && saltlen != 0);
hlen = mbedtls_hash_info_get_size(md_type);
if (hlen <= 32) {
v = 64;
} else {
v = 128;
}
memset(diversifier, (unsigned char) id, v);
if (use_salt != 0) {
pkcs12_fill_buffer(salt_block, v, salt, saltlen);
}
if (use_password != 0) {
pkcs12_fill_buffer(pwd_block, v, pwd, pwdlen);
}
p = data;
while( datalen > 0 )
{
if( calculate_hashes( md_type, iterations, diversifier, salt_block,
pwd_block, hash_output, use_salt, use_password, hlen,
v ) != 0 )
{
while (datalen > 0) {
if (calculate_hashes(md_type, iterations, diversifier, salt_block,
pwd_block, hash_output, use_salt, use_password, hlen,
v) != 0) {
goto exit;
}
use_len = ( datalen > hlen ) ? hlen : datalen;
memcpy( p, hash_output, use_len );
use_len = (datalen > hlen) ? hlen : datalen;
memcpy(p, hash_output, use_len);
datalen -= use_len;
p += use_len;
if( datalen == 0 )
if (datalen == 0) {
break;
}
// Concatenating copies of hash_output into hash_block (B)
pkcs12_fill_buffer( hash_block, v, hash_output, hlen );
pkcs12_fill_buffer(hash_block, v, hash_output, hlen);
// B += 1
for( i = v; i > 0; i-- )
if( ++hash_block[i - 1] != 0 )
for (i = v; i > 0; i--) {
if (++hash_block[i - 1] != 0) {
break;
if( use_salt != 0 )
{
// salt_block += B
c = 0;
for( i = v; i > 0; i-- )
{
j = salt_block[i - 1] + hash_block[i - 1] + c;
c = MBEDTLS_BYTE_1( j );
salt_block[i - 1] = MBEDTLS_BYTE_0( j );
}
}
if( use_password != 0 )
{
if (use_salt != 0) {
// salt_block += B
c = 0;
for (i = v; i > 0; i--) {
j = salt_block[i - 1] + hash_block[i - 1] + c;
c = MBEDTLS_BYTE_1(j);
salt_block[i - 1] = MBEDTLS_BYTE_0(j);
}
}
if (use_password != 0) {
// pwd_block += B
c = 0;
for( i = v; i > 0; i-- )
{
for (i = v; i > 0; i--) {
j = pwd_block[i - 1] + hash_block[i - 1] + c;
c = MBEDTLS_BYTE_1( j );
pwd_block[i - 1] = MBEDTLS_BYTE_0( j );
c = MBEDTLS_BYTE_1(j);
pwd_block[i - 1] = MBEDTLS_BYTE_0(j);
}
}
}
@ -418,12 +436,12 @@ int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen,
ret = 0;
exit:
mbedtls_platform_zeroize( salt_block, sizeof( salt_block ) );
mbedtls_platform_zeroize( pwd_block, sizeof( pwd_block ) );
mbedtls_platform_zeroize( hash_block, sizeof( hash_block ) );
mbedtls_platform_zeroize( hash_output, sizeof( hash_output ) );
mbedtls_platform_zeroize(salt_block, sizeof(salt_block));
mbedtls_platform_zeroize(pwd_block, sizeof(pwd_block));
mbedtls_platform_zeroize(hash_block, sizeof(hash_block));
mbedtls_platform_zeroize(hash_output, sizeof(hash_output));
return( ret );
return ret;
}
#endif /* MBEDTLS_PKCS12_C */

View File

@ -48,18 +48,19 @@
#include "mbedtls/psa_util.h"
#if defined(MBEDTLS_ASN1_PARSE_C)
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 )
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;
mbedtls_asn1_buf prf_alg_oid;
unsigned char *p = params->p;
const unsigned char *end = params->p + params->len;
if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
if (params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
}
/*
* PBKDF2-params ::= SEQUENCE {
* salt OCTET STRING,
@ -69,45 +70,52 @@ static int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params,
* }
*
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &salt->len,
MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret ) );
if ((ret = mbedtls_asn1_get_tag(&p, end, &salt->len,
MBEDTLS_ASN1_OCTET_STRING)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
}
salt->p = p;
p += salt->len;
if( ( ret = mbedtls_asn1_get_int( &p, end, iterations ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret ) );
if( p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_int( &p, end, keylen ) ) != 0 )
{
if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret ) );
if ((ret = mbedtls_asn1_get_int(&p, end, iterations)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
}
if( p == end )
return( 0 );
if (p == end) {
return 0;
}
if( ( ret = mbedtls_asn1_get_alg_null( &p, end, &prf_alg_oid ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret ) );
if ((ret = mbedtls_asn1_get_int(&p, end, keylen)) != 0) {
if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
}
}
if( mbedtls_oid_get_md_hmac( &prf_alg_oid, md_type ) != 0 )
return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
if (p == end) {
return 0;
}
if( p != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
if ((ret = mbedtls_asn1_get_alg_null(&p, end, &prf_alg_oid)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
}
return( 0 );
if (mbedtls_oid_get_md_hmac(&prf_alg_oid, md_type) != 0) {
return MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE;
}
if (p != end) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
}
return 0;
}
int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t datalen,
unsigned char *output )
int mbedtls_pkcs5_pbes2(const mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t datalen,
unsigned char *output)
{
int ret, iterations = 0, keylen = 0;
unsigned char *p, *end;
@ -129,38 +137,41 @@ int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,
* encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
* }
*/
if( pbe_params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
if (pbe_params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
}
if( ( ret = mbedtls_asn1_get_alg( &p, end, &kdf_alg_oid,
&kdf_alg_params ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret ) );
if ((ret = mbedtls_asn1_get_alg(&p, end, &kdf_alg_oid,
&kdf_alg_params)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
}
// Only PBKDF2 supported at the moment
//
if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBKDF2, &kdf_alg_oid ) != 0 )
return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
if( ( ret = pkcs5_parse_pbkdf2_params( &kdf_alg_params,
&salt, &iterations, &keylen,
&md_type ) ) != 0 )
{
return( ret );
if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS5_PBKDF2, &kdf_alg_oid) != 0) {
return MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE;
}
if( ( ret = mbedtls_asn1_get_alg( &p, end, &enc_scheme_oid,
&enc_scheme_params ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret ) );
if ((ret = pkcs5_parse_pbkdf2_params(&kdf_alg_params,
&salt, &iterations, &keylen,
&md_type)) != 0) {
return ret;
}
if( mbedtls_oid_get_cipher_alg( &enc_scheme_oid, &cipher_alg ) != 0 )
return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
if ((ret = mbedtls_asn1_get_alg(&p, end, &enc_scheme_oid,
&enc_scheme_params)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
}
cipher_info = mbedtls_cipher_info_from_type( cipher_alg );
if( cipher_info == NULL )
return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
if (mbedtls_oid_get_cipher_alg(&enc_scheme_oid, &cipher_alg) != 0) {
return MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE;
}
cipher_info = mbedtls_cipher_info_from_type(cipher_alg);
if (cipher_info == NULL) {
return MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE;
}
/*
* The value of keylen from pkcs5_parse_pbkdf2_params() is ignored
@ -168,164 +179,176 @@ int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,
*/
keylen = cipher_info->key_bitlen / 8;
if( enc_scheme_params.tag != MBEDTLS_ASN1_OCTET_STRING ||
enc_scheme_params.len != cipher_info->iv_size )
{
return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT );
if (enc_scheme_params.tag != MBEDTLS_ASN1_OCTET_STRING ||
enc_scheme_params.len != cipher_info->iv_size) {
return MBEDTLS_ERR_PKCS5_INVALID_FORMAT;
}
mbedtls_cipher_init( &cipher_ctx );
mbedtls_cipher_init(&cipher_ctx);
memcpy( iv, enc_scheme_params.p, enc_scheme_params.len );
memcpy(iv, enc_scheme_params.p, enc_scheme_params.len);
if( ( ret = mbedtls_pkcs5_pbkdf2_hmac_ext( md_type, pwd, pwdlen, salt.p,
salt.len, iterations, keylen,
key ) ) != 0 )
{
if ((ret = mbedtls_pkcs5_pbkdf2_hmac_ext(md_type, pwd, pwdlen, salt.p,
salt.len, iterations, keylen,
key)) != 0) {
goto exit;
}
if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 )
if ((ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0) {
goto exit;
}
if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen,
(mbedtls_operation_t) mode ) ) != 0 )
if ((ret = mbedtls_cipher_setkey(&cipher_ctx, key, 8 * keylen,
(mbedtls_operation_t) mode)) != 0) {
goto exit;
}
if( ( ret = mbedtls_cipher_crypt( &cipher_ctx, iv, enc_scheme_params.len,
data, datalen, output, &olen ) ) != 0 )
if ((ret = mbedtls_cipher_crypt(&cipher_ctx, iv, enc_scheme_params.len,
data, datalen, output, &olen)) != 0) {
ret = MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH;
}
exit:
mbedtls_cipher_free( &cipher_ctx );
mbedtls_cipher_free(&cipher_ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_ASN1_PARSE_C */
#if defined(MBEDTLS_MD_C)
static int pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx,
const unsigned char *password,
size_t plen, const unsigned char *salt, size_t slen,
unsigned int iteration_count,
uint32_t key_length, unsigned char *output )
static int pkcs5_pbkdf2_hmac(mbedtls_md_context_t *ctx,
const unsigned char *password,
size_t plen, const unsigned char *salt, size_t slen,
unsigned int iteration_count,
uint32_t key_length, unsigned char *output)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned int i;
unsigned char md1[MBEDTLS_MD_MAX_SIZE];
unsigned char work[MBEDTLS_MD_MAX_SIZE];
unsigned char md_size = mbedtls_md_get_size( ctx->md_info );
unsigned char md_size = mbedtls_md_get_size(ctx->md_info);
size_t use_len;
unsigned char *out_p = output;
unsigned char counter[4];
memset( counter, 0, 4 );
memset(counter, 0, 4);
counter[3] = 1;
#if UINT_MAX > 0xFFFFFFFF
if( iteration_count > 0xFFFFFFFF )
return( MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA );
if (iteration_count > 0xFFFFFFFF) {
return MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA;
}
#endif
if( ( ret = mbedtls_md_hmac_starts( ctx, password, plen ) ) != 0 )
return( ret );
while( key_length )
{
if ((ret = mbedtls_md_hmac_starts(ctx, password, plen)) != 0) {
return ret;
}
while (key_length) {
// U1 ends up in work
//
if( ( ret = mbedtls_md_hmac_update( ctx, salt, slen ) ) != 0 )
if ((ret = mbedtls_md_hmac_update(ctx, salt, slen)) != 0) {
goto cleanup;
}
if( ( ret = mbedtls_md_hmac_update( ctx, counter, 4 ) ) != 0 )
if ((ret = mbedtls_md_hmac_update(ctx, counter, 4)) != 0) {
goto cleanup;
}
if( ( ret = mbedtls_md_hmac_finish( ctx, work ) ) != 0 )
if ((ret = mbedtls_md_hmac_finish(ctx, work)) != 0) {
goto cleanup;
}
if( ( ret = mbedtls_md_hmac_reset( ctx ) ) != 0 )
if ((ret = mbedtls_md_hmac_reset(ctx)) != 0) {
goto cleanup;
}
memcpy( md1, work, md_size );
memcpy(md1, work, md_size);
for( i = 1; i < iteration_count; i++ )
{
for (i = 1; i < iteration_count; i++) {
// U2 ends up in md1
//
if( ( ret = mbedtls_md_hmac_update( ctx, md1, md_size ) ) != 0 )
if ((ret = mbedtls_md_hmac_update(ctx, md1, md_size)) != 0) {
goto cleanup;
}
if( ( ret = mbedtls_md_hmac_finish( ctx, md1 ) ) != 0 )
if ((ret = mbedtls_md_hmac_finish(ctx, md1)) != 0) {
goto cleanup;
}
if( ( ret = mbedtls_md_hmac_reset( ctx ) ) != 0 )
if ((ret = mbedtls_md_hmac_reset(ctx)) != 0) {
goto cleanup;
}
// U1 xor U2
//
mbedtls_xor( work, work, md1, md_size );
mbedtls_xor(work, work, md1, md_size);
}
use_len = ( key_length < md_size ) ? key_length : md_size;
memcpy( out_p, work, use_len );
use_len = (key_length < md_size) ? key_length : md_size;
memcpy(out_p, work, use_len);
key_length -= (uint32_t) use_len;
out_p += use_len;
for( i = 4; i > 0; i-- )
if( ++counter[i - 1] != 0 )
for (i = 4; i > 0; i--) {
if (++counter[i - 1] != 0) {
break;
}
}
}
cleanup:
/* Zeroise buffers to clear sensitive data from memory. */
mbedtls_platform_zeroize( work, MBEDTLS_MD_MAX_SIZE );
mbedtls_platform_zeroize( md1, MBEDTLS_MD_MAX_SIZE );
mbedtls_platform_zeroize(work, MBEDTLS_MD_MAX_SIZE);
mbedtls_platform_zeroize(md1, MBEDTLS_MD_MAX_SIZE);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx,
const unsigned char *password,
size_t plen, const unsigned char *salt, size_t slen,
unsigned int iteration_count,
uint32_t key_length, unsigned char *output )
int mbedtls_pkcs5_pbkdf2_hmac(mbedtls_md_context_t *ctx,
const unsigned char *password,
size_t plen, const unsigned char *salt, size_t slen,
unsigned int iteration_count,
uint32_t key_length, unsigned char *output)
{
return( pkcs5_pbkdf2_hmac( ctx, password, plen, salt, slen, iteration_count,
key_length, output ) );
return pkcs5_pbkdf2_hmac(ctx, password, plen, salt, slen, iteration_count,
key_length, output);
}
#endif
#endif /* MBEDTLS_MD_C */
int mbedtls_pkcs5_pbkdf2_hmac_ext( mbedtls_md_type_t md_alg,
const unsigned char *password,
size_t plen, const unsigned char *salt, size_t slen,
unsigned int iteration_count,
uint32_t key_length, unsigned char *output )
int mbedtls_pkcs5_pbkdf2_hmac_ext(mbedtls_md_type_t md_alg,
const unsigned char *password,
size_t plen, const unsigned char *salt, size_t slen,
unsigned int iteration_count,
uint32_t key_length, unsigned char *output)
{
#if defined(MBEDTLS_MD_C)
mbedtls_md_context_t md_ctx;
const mbedtls_md_info_t *md_info = NULL;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
md_info = mbedtls_md_info_from_type( md_alg );
if( md_info == NULL )
return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
md_info = mbedtls_md_info_from_type(md_alg);
if (md_info == NULL) {
return MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE;
}
mbedtls_md_init( &md_ctx );
mbedtls_md_init(&md_ctx);
if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
goto exit;
ret = pkcs5_pbkdf2_hmac( &md_ctx, password, plen, salt, slen,
iteration_count, key_length, output );
}
ret = pkcs5_pbkdf2_hmac(&md_ctx, password, plen, salt, slen,
iteration_count, key_length, output);
exit:
mbedtls_md_free( &md_ctx );
return( ret );
mbedtls_md_free(&md_ctx);
return ret;
#else
unsigned int i;
unsigned char md1[PSA_HASH_MAX_SIZE];
unsigned char work[PSA_HASH_MAX_SIZE];
const unsigned char md_size = mbedtls_hash_info_get_size( md_alg );
const unsigned char md_size = mbedtls_hash_info_get_size(md_alg);
psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
@ -335,109 +358,121 @@ exit:
unsigned char counter[4];
mbedtls_svc_key_id_t psa_hmac_key = MBEDTLS_SVC_KEY_ID_INIT;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
const psa_algorithm_t alg = PSA_ALG_HMAC( mbedtls_hash_info_psa_from_md( md_alg ) );
const size_t out_size = PSA_MAC_LENGTH( PSA_KEY_TYPE_HMAC, 0, alg );
const psa_algorithm_t alg = PSA_ALG_HMAC(mbedtls_hash_info_psa_from_md(md_alg));
const size_t out_size = PSA_MAC_LENGTH(PSA_KEY_TYPE_HMAC, 0, alg);
memset( counter, 0, sizeof( counter ) );
memset(counter, 0, sizeof(counter));
counter[3] = 1;
psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_MESSAGE );
psa_set_key_algorithm( &attributes, alg );
psa_set_key_type( &attributes, PSA_KEY_TYPE_HMAC );
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
if( key_length == 0 )
if (key_length == 0) {
return 0;
if( ( status = psa_import_key( &attributes,
password, plen,
&psa_hmac_key ) ) != PSA_SUCCESS )
{
}
if ((status = psa_import_key(&attributes,
password, plen,
&psa_hmac_key)) != PSA_SUCCESS) {
return MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA;
}
#if UINT_MAX > 0xFFFFFFFF
if( iteration_count > 0xFFFFFFFF )
return( MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA );
if (iteration_count > 0xFFFFFFFF) {
return MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA;
}
#endif
while( key_length )
{
status = psa_mac_sign_setup( &operation, psa_hmac_key,
PSA_ALG_HMAC( alg ) );
if( status != PSA_SUCCESS )
while (key_length) {
status = psa_mac_sign_setup(&operation, psa_hmac_key,
PSA_ALG_HMAC(alg));
if (status != PSA_SUCCESS) {
goto cleanup;
}
// U1 ends up in work
if( ( status = psa_mac_update( &operation, salt, slen ) ) != PSA_SUCCESS )
if ((status = psa_mac_update(&operation, salt, slen)) != PSA_SUCCESS) {
goto cleanup;
}
if( ( status = psa_mac_update( &operation, counter, sizeof( counter ) ) ) != PSA_SUCCESS )
if ((status = psa_mac_update(&operation, counter, sizeof(counter))) != PSA_SUCCESS) {
goto cleanup;
}
if( ( status = psa_mac_sign_finish( &operation, work, out_size, &out_len ) )
!= PSA_SUCCESS )
if ((status = psa_mac_sign_finish(&operation, work, out_size, &out_len))
!= PSA_SUCCESS) {
goto cleanup;
}
memcpy( md1, work, out_len );
memcpy(md1, work, out_len);
for( i = 1; i < iteration_count; i++ )
{
for (i = 1; i < iteration_count; i++) {
// U2 ends up in md1
//
status = psa_mac_sign_setup( &operation, psa_hmac_key,
PSA_ALG_HMAC( alg ) );
if( status != PSA_SUCCESS )
status = psa_mac_sign_setup(&operation, psa_hmac_key,
PSA_ALG_HMAC(alg));
if (status != PSA_SUCCESS) {
goto cleanup;
if( ( status = psa_mac_update( &operation, md1, md_size ) ) != PSA_SUCCESS )
}
if ((status = psa_mac_update(&operation, md1, md_size)) != PSA_SUCCESS) {
goto cleanup;
if( ( status = psa_mac_sign_finish( &operation, md1, out_size, &out_len ) ) != PSA_SUCCESS )
}
if ((status =
psa_mac_sign_finish(&operation, md1, out_size, &out_len)) != PSA_SUCCESS) {
goto cleanup;
}
// U1 xor U2
//
mbedtls_xor( work, work, md1, md_size );
mbedtls_xor(work, work, md1, md_size);
}
use_len = ( key_length < md_size ) ? key_length : md_size;
memcpy( out_p, work, use_len );
use_len = (key_length < md_size) ? key_length : md_size;
memcpy(out_p, work, use_len);
key_length -= (uint32_t) use_len;
out_p += use_len;
for( i = 4; i > 0; i-- )
if( ++counter[i - 1] != 0 )
for (i = 4; i > 0; i--) {
if (++counter[i - 1] != 0) {
break;
}
}
}
cleanup:
/* Zeroise buffers to clear sensitive data from memory. */
mbedtls_platform_zeroize( work, PSA_HASH_MAX_SIZE );
mbedtls_platform_zeroize( md1, PSA_HASH_MAX_SIZE );
status_destruction = psa_destroy_key( psa_hmac_key );
if( status == PSA_SUCCESS && status_destruction != PSA_SUCCESS )
mbedtls_platform_zeroize(work, PSA_HASH_MAX_SIZE);
mbedtls_platform_zeroize(md1, PSA_HASH_MAX_SIZE);
status_destruction = psa_destroy_key(psa_hmac_key);
if (status == PSA_SUCCESS && status_destruction != PSA_SUCCESS) {
status = status_destruction;
status_destruction = psa_mac_abort( &operation );
if( status == PSA_SUCCESS && status_destruction != PSA_SUCCESS )
}
status_destruction = psa_mac_abort(&operation);
if (status == PSA_SUCCESS && status_destruction != PSA_SUCCESS) {
status = status_destruction;
}
return( mbedtls_md_error_from_psa( status ) );
return mbedtls_md_error_from_psa(status);
#endif /* !MBEDTLS_MD_C */
}
#if defined(MBEDTLS_SELF_TEST)
#if !defined(MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA)
int mbedtls_pkcs5_self_test( int verbose )
int mbedtls_pkcs5_self_test(int verbose)
{
if( verbose != 0 )
mbedtls_printf( " PBKDF2 (SHA1): skipped\n\n" );
if (verbose != 0) {
mbedtls_printf(" PBKDF2 (SHA1): skipped\n\n");
}
return( 0 );
return 0;
}
#else
#define MAX_TESTS 6
static const size_t plen_test_data[MAX_TESTS] =
{ 8, 8, 8, 24, 9 };
{ 8, 8, 8, 24, 9 };
static const unsigned char password_test_data[MAX_TESTS][32] =
{
@ -449,7 +484,7 @@ static const unsigned char password_test_data[MAX_TESTS][32] =
};
static const size_t slen_test_data[MAX_TESTS] =
{ 4, 4, 4, 36, 5 };
{ 4, 4, 4, 36, 5 };
static const unsigned char salt_test_data[MAX_TESTS][40] =
{
@ -461,10 +496,10 @@ static const unsigned char salt_test_data[MAX_TESTS][40] =
};
static const uint32_t it_cnt_test_data[MAX_TESTS] =
{ 1, 2, 4096, 4096, 4096 };
{ 1, 2, 4096, 4096, 4096 };
static const uint32_t key_len_test_data[MAX_TESTS] =
{ 20, 20, 20, 25, 16 };
{ 20, 20, 20, 25, 16 };
static const unsigned char result_key_test_data[MAX_TESTS][32] =
{
@ -485,39 +520,41 @@ static const unsigned char result_key_test_data[MAX_TESTS][32] =
0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3 },
};
int mbedtls_pkcs5_self_test( int verbose )
int mbedtls_pkcs5_self_test(int verbose)
{
int ret, i;
unsigned char key[64];
for( i = 0; i < MAX_TESTS; i++ )
{
if( verbose != 0 )
mbedtls_printf( " PBKDF2 (SHA1) #%d: ", i );
for (i = 0; i < MAX_TESTS; i++) {
if (verbose != 0) {
mbedtls_printf(" PBKDF2 (SHA1) #%d: ", i);
}
ret = mbedtls_pkcs5_pbkdf2_hmac_ext( MBEDTLS_MD_SHA1, password_test_data[i],
plen_test_data[i], salt_test_data[i],
slen_test_data[i], it_cnt_test_data[i],
key_len_test_data[i], key );
if( ret != 0 ||
memcmp( result_key_test_data[i], key, key_len_test_data[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = mbedtls_pkcs5_pbkdf2_hmac_ext(MBEDTLS_MD_SHA1, password_test_data[i],
plen_test_data[i], salt_test_data[i],
slen_test_data[i], it_cnt_test_data[i],
key_len_test_data[i], key);
if (ret != 0 ||
memcmp(result_key_test_data[i], key, key_len_test_data[i]) != 0) {
if (verbose != 0) {
mbedtls_printf("failed\n");
}
ret = 1;
goto exit;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
exit:
return( ret );
return ret;
}
#endif /* MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA */

View File

@ -47,43 +47,44 @@
/**
* Initializes the pkcs7 structure.
*/
void mbedtls_pkcs7_init( mbedtls_pkcs7 *pkcs7 )
void mbedtls_pkcs7_init(mbedtls_pkcs7 *pkcs7)
{
memset( pkcs7, 0, sizeof( *pkcs7 ) );
memset(pkcs7, 0, sizeof(*pkcs7));
}
static int pkcs7_get_next_content_len( unsigned char **p, unsigned char *end,
size_t *len )
static int pkcs7_get_next_content_len(unsigned char **p, unsigned char *end,
size_t *len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_asn1_get_tag( p, end, len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_CONTEXT_SPECIFIC );
if( ret != 0 )
{
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_FORMAT, ret );
ret = mbedtls_asn1_get_tag(p, end, len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_CONTEXT_SPECIFIC);
if (ret != 0) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_FORMAT, ret);
}
return( ret );
return ret;
}
/**
* version Version
* Version ::= INTEGER
**/
static int pkcs7_get_version( unsigned char **p, unsigned char *end, int *ver )
static int pkcs7_get_version(unsigned char **p, unsigned char *end, int *ver)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_asn1_get_int( p, end, ver );
if( ret != 0 )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_VERSION, ret );
ret = mbedtls_asn1_get_int(p, end, ver);
if (ret != 0) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_VERSION, ret);
}
/* If version != 1, return invalid version */
if( *ver != MBEDTLS_PKCS7_SUPPORTED_VERSION )
if (*ver != MBEDTLS_PKCS7_SUPPORTED_VERSION) {
ret = MBEDTLS_ERR_PKCS7_INVALID_VERSION;
}
return( ret );
return ret;
}
/**
@ -92,24 +93,24 @@ static int pkcs7_get_version( unsigned char **p, unsigned char *end, int *ver )
* content
* [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
**/
static int pkcs7_get_content_info_type( unsigned char **p, unsigned char *end,
mbedtls_pkcs7_buf *pkcs7 )
static int pkcs7_get_content_info_type(unsigned char **p, unsigned char *end,
mbedtls_pkcs7_buf *pkcs7)
{
size_t len = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *start = *p;
ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE );
if( ret != 0 ) {
ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE);
if (ret != 0) {
*p = start;
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, ret ) );
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, ret);
}
ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_OID );
if( ret != 0 ) {
ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_OID);
if (ret != 0) {
*p = start;
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, ret ) );
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO, ret);
}
pkcs7->tag = MBEDTLS_ASN1_OID;
@ -117,7 +118,7 @@ static int pkcs7_get_content_info_type( unsigned char **p, unsigned char *end,
pkcs7->p = *p;
*p += len;
return( ret );
return ret;
}
/**
@ -125,47 +126,47 @@ static int pkcs7_get_content_info_type( unsigned char **p, unsigned char *end,
*
* This is from x509.h
**/
static int pkcs7_get_digest_algorithm( unsigned char **p, unsigned char *end,
mbedtls_x509_buf *alg )
static int pkcs7_get_digest_algorithm(unsigned char **p, unsigned char *end,
mbedtls_x509_buf *alg)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = mbedtls_asn1_get_alg_null( p, end, alg ) ) != 0 )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_ALG, ret );
if ((ret = mbedtls_asn1_get_alg_null(p, end, alg)) != 0) {
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_ALG, ret);
}
return( ret );
return ret;
}
/**
* DigestAlgorithmIdentifiers :: SET of DigestAlgorithmIdentifier
**/
static int pkcs7_get_digest_algorithm_set( unsigned char **p,
unsigned char *end,
mbedtls_x509_buf *alg )
static int pkcs7_get_digest_algorithm_set(unsigned char **p,
unsigned char *end,
mbedtls_x509_buf *alg)
{
size_t len = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SET );
if( ret != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_ALG, ret ) );
ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SET);
if (ret != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_ALG, ret);
}
end = *p + len;
ret = mbedtls_asn1_get_alg_null( p, end, alg );
if( ret != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_ALG, ret ) );
ret = mbedtls_asn1_get_alg_null(p, end, alg);
if (ret != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_ALG, ret);
}
/** For now, it assumes there is only one digest algorithm specified **/
if ( *p != end )
return( MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE );
if (*p != end) {
return MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE;
}
return( 0 );
return 0;
}
/**
@ -177,30 +178,29 @@ static int pkcs7_get_digest_algorithm_set( unsigned char **p,
* 0 or higher is valid.
* Return negative error code for failure.
**/
static int pkcs7_get_certificates( unsigned char **p, unsigned char *end,
mbedtls_x509_crt *certs )
static int pkcs7_get_certificates(unsigned char **p, unsigned char *end,
mbedtls_x509_crt *certs)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len1 = 0;
size_t len2 = 0;
unsigned char *end_set, *end_cert, *start;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len1, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
else
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_FORMAT, ret ) );
if ((ret = mbedtls_asn1_get_tag(p, end, &len1, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_CONTEXT_SPECIFIC)) != 0) {
if (ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
return 0;
} else {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_FORMAT, ret);
}
}
start = *p;
end_set = *p + len1;
ret = mbedtls_asn1_get_tag( p, end_set, &len2, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE );
if( ret != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_CERT, ret ) );
ret = mbedtls_asn1_get_tag(p, end_set, &len2, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE);
if (ret != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_CERT, ret);
}
end_cert = *p + len2;
@ -211,15 +211,13 @@ static int pkcs7_get_certificates( unsigned char **p, unsigned char *end,
* So, we support only the root certificate and the single signer.
* The behaviour would be improved with addition of multiple signer support.
*/
if ( end_cert != end_set )
{
return( MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE );
if (end_cert != end_set) {
return MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE;
}
*p = start;
if( ( ret = mbedtls_x509_crt_parse_der( certs, *p, len1 ) ) < 0 )
{
return( MBEDTLS_ERR_PKCS7_INVALID_CERT );
if ((ret = mbedtls_x509_crt_parse_der(certs, *p, len1)) < 0) {
return MBEDTLS_ERR_PKCS7_INVALID_CERT;
}
*p = *p + len1;
@ -228,21 +226,22 @@ static int pkcs7_get_certificates( unsigned char **p, unsigned char *end,
* Since in this version we strictly support single certificate, and reaching
* here implies we have parsed successfully, we return 1.
*/
return( 1 );
return 1;
}
/**
* EncryptedDigest ::= OCTET STRING
**/
static int pkcs7_get_signature( unsigned char **p, unsigned char *end,
mbedtls_pkcs7_buf *signature )
static int pkcs7_get_signature(unsigned char **p, unsigned char *end,
mbedtls_pkcs7_buf *signature)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_OCTET_STRING );
if( ret != 0 )
return( ret );
ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_OCTET_STRING);
if (ret != 0) {
return ret;
}
signature->tag = MBEDTLS_ASN1_OCTET_STRING;
signature->len = len;
@ -250,23 +249,23 @@ static int pkcs7_get_signature( unsigned char **p, unsigned char *end,
*p = *p + len;
return( 0 );
return 0;
}
static void pkcs7_free_signer_info( mbedtls_pkcs7_signer_info *signer )
static void pkcs7_free_signer_info(mbedtls_pkcs7_signer_info *signer)
{
mbedtls_x509_name *name_cur;
mbedtls_x509_name *name_prv;
if( signer == NULL )
if (signer == NULL) {
return;
}
name_cur = signer->issuer.next;
while( name_cur != NULL )
{
while (name_cur != NULL) {
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_free( name_prv );
mbedtls_free(name_prv);
}
signer->issuer.next = NULL;
}
@ -287,74 +286,83 @@ static void pkcs7_free_signer_info( mbedtls_pkcs7_signer_info *signer )
* Structure must not contain vales for authenticatedAttributes
* and unauthenticatedAttributes.
**/
static int pkcs7_get_signer_info( unsigned char **p, unsigned char *end,
mbedtls_pkcs7_signer_info *signer )
static int pkcs7_get_signer_info(unsigned char **p, unsigned char *end,
mbedtls_pkcs7_signer_info *signer)
{
unsigned char *end_signer;
int asn1_ret = 0, ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
asn1_ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE );
if( asn1_ret != 0 )
asn1_ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE);
if (asn1_ret != 0) {
goto out;
}
end_signer = *p + len;
ret = pkcs7_get_version( p, end_signer, &signer->version );
if( ret != 0 )
ret = pkcs7_get_version(p, end_signer, &signer->version);
if (ret != 0) {
goto out;
}
asn1_ret = mbedtls_asn1_get_tag( p, end_signer, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE );
if( asn1_ret != 0 )
asn1_ret = mbedtls_asn1_get_tag(p, end_signer, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
if (asn1_ret != 0) {
goto out;
}
/* Parsing IssuerAndSerialNumber */
signer->issuer_raw.p = *p;
asn1_ret = mbedtls_asn1_get_tag( p, end_signer, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE );
if( asn1_ret != 0 )
asn1_ret = mbedtls_asn1_get_tag(p, end_signer, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
if (asn1_ret != 0) {
goto out;
}
ret = mbedtls_x509_get_name( p, *p + len, &signer->issuer );
if( ret != 0 )
ret = mbedtls_x509_get_name(p, *p + len, &signer->issuer);
if (ret != 0) {
goto out;
}
signer->issuer_raw.len = *p - signer->issuer_raw.p;
ret = mbedtls_x509_get_serial( p, end_signer, &signer->serial );
if( ret != 0 )
ret = mbedtls_x509_get_serial(p, end_signer, &signer->serial);
if (ret != 0) {
goto out;
}
ret = pkcs7_get_digest_algorithm( p, end_signer, &signer->alg_identifier );
if( ret != 0 )
ret = pkcs7_get_digest_algorithm(p, end_signer, &signer->alg_identifier);
if (ret != 0) {
goto out;
}
/* Assume authenticatedAttributes is nonexistent */
ret = pkcs7_get_digest_algorithm( p, end_signer, &signer->sig_alg_identifier );
if( ret != 0 )
ret = pkcs7_get_digest_algorithm(p, end_signer, &signer->sig_alg_identifier);
if (ret != 0) {
goto out;
ret = pkcs7_get_signature( p, end_signer, &signer->sig );
if( ret != 0 )
goto out;
/* Do not permit any unauthenticated attributes */
if( *p != end_signer )
ret = MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO;
out:
if( asn1_ret != 0 || ret != 0 )
{
pkcs7_free_signer_info( signer );
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO,
asn1_ret );
}
return( ret );
ret = pkcs7_get_signature(p, end_signer, &signer->sig);
if (ret != 0) {
goto out;
}
/* Do not permit any unauthenticated attributes */
if (*p != end_signer) {
ret = MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO;
}
out:
if (asn1_ret != 0 || ret != 0) {
pkcs7_free_signer_info(signer);
ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO,
asn1_ret);
}
return ret;
}
/**
@ -363,48 +371,45 @@ out:
* 0 or higher is valid.
* Return negative error code for failure.
**/
static int pkcs7_get_signers_info_set( unsigned char **p, unsigned char *end,
mbedtls_pkcs7_signer_info *signers_set )
static int pkcs7_get_signers_info_set(unsigned char **p, unsigned char *end,
mbedtls_pkcs7_signer_info *signers_set)
{
unsigned char *end_set;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int count = 0;
size_t len = 0;
ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SET );
if( ret != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO, ret ) );
ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SET);
if (ret != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO, ret);
}
/* Detect zero signers */
if( len == 0 )
{
return( 0 );
if (len == 0) {
return 0;
}
end_set = *p + len;
ret = pkcs7_get_signer_info( p, end_set, signers_set );
if( ret != 0 )
return( ret );
ret = pkcs7_get_signer_info(p, end_set, signers_set);
if (ret != 0) {
return ret;
}
count++;
mbedtls_pkcs7_signer_info *prev = signers_set;
while( *p != end_set )
{
while (*p != end_set) {
mbedtls_pkcs7_signer_info *signer =
mbedtls_calloc( 1, sizeof( mbedtls_pkcs7_signer_info ) );
if( !signer )
{
mbedtls_calloc(1, sizeof(mbedtls_pkcs7_signer_info));
if (!signer) {
ret = MBEDTLS_ERR_PKCS7_ALLOC_FAILED;
goto cleanup;
}
ret = pkcs7_get_signer_info( p, end_set, signer );
if( ret != 0 ) {
mbedtls_free( signer );
ret = pkcs7_get_signer_info(p, end_set, signer);
if (ret != 0) {
mbedtls_free(signer);
goto cleanup;
}
prev->next = signer;
@ -412,20 +417,19 @@ static int pkcs7_get_signers_info_set( unsigned char **p, unsigned char *end,
count++;
}
return( count );
return count;
cleanup:
pkcs7_free_signer_info( signers_set );
pkcs7_free_signer_info(signers_set);
mbedtls_pkcs7_signer_info *signer = signers_set->next;
while( signer != NULL )
{
while (signer != NULL) {
prev = signer;
signer = signer->next;
pkcs7_free_signer_info( prev );
mbedtls_free( prev );
pkcs7_free_signer_info(prev);
mbedtls_free(prev);
}
signers_set->next = NULL;
return( ret );
return ret;
}
/**
@ -440,8 +444,8 @@ cleanup:
* [0] IMPLICIT CertificateRevocationLists OPTIONAL,
* signerInfos SignerInfos }
*/
static int pkcs7_get_signed_data( unsigned char *buf, size_t buflen,
mbedtls_pkcs7_signed_data *signed_data )
static int pkcs7_get_signed_data(unsigned char *buf, size_t buflen,
mbedtls_pkcs7_signed_data *signed_data)
{
unsigned char *p = buf;
unsigned char *end = buf + buflen;
@ -450,47 +454,48 @@ static int pkcs7_get_signed_data( unsigned char *buf, size_t buflen,
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md_type_t md_alg;
ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE );
if( ret != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS7_INVALID_FORMAT, ret ) );
ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED
| MBEDTLS_ASN1_SEQUENCE);
if (ret != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS7_INVALID_FORMAT, ret);
}
end_set = p + len;
/* Get version of signed data */
ret = pkcs7_get_version( &p, end_set, &signed_data->version );
if( ret != 0 )
return( ret );
ret = pkcs7_get_version(&p, end_set, &signed_data->version);
if (ret != 0) {
return ret;
}
/* Get digest algorithm */
ret = pkcs7_get_digest_algorithm_set( &p, end_set,
&signed_data->digest_alg_identifiers );
if( ret != 0 )
return( ret );
ret = pkcs7_get_digest_algorithm_set(&p, end_set,
&signed_data->digest_alg_identifiers);
if (ret != 0) {
return ret;
}
ret = mbedtls_oid_get_md_alg( &signed_data->digest_alg_identifiers, &md_alg );
if( ret != 0 )
{
return( MBEDTLS_ERR_PKCS7_INVALID_ALG );
ret = mbedtls_oid_get_md_alg(&signed_data->digest_alg_identifiers, &md_alg);
if (ret != 0) {
return MBEDTLS_ERR_PKCS7_INVALID_ALG;
}
/* Do not expect any content */
ret = pkcs7_get_content_info_type( &p, end_set, &signed_data->content.oid );
if( ret != 0 )
return( ret );
ret = pkcs7_get_content_info_type(&p, end_set, &signed_data->content.oid);
if (ret != 0) {
return ret;
}
if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_DATA, &signed_data->content.oid ) )
{
return( MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO );
if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_DATA, &signed_data->content.oid)) {
return MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO;
}
/* Look for certificates, there may or may not be any */
mbedtls_x509_crt_init( &signed_data->certs );
ret = pkcs7_get_certificates( &p, end_set, &signed_data->certs );
if( ret < 0 )
return( ret );
mbedtls_x509_crt_init(&signed_data->certs);
ret = pkcs7_get_certificates(&p, end_set, &signed_data->certs);
if (ret < 0) {
return ret;
}
signed_data->no_of_certs = ret;
@ -503,21 +508,23 @@ static int pkcs7_get_signed_data( unsigned char *buf, size_t buflen,
signed_data->no_of_crls = 0;
/* Get signers info */
ret = pkcs7_get_signers_info_set( &p, end_set, &signed_data->signers );
if( ret < 0 )
return( ret );
ret = pkcs7_get_signers_info_set(&p, end_set, &signed_data->signers);
if (ret < 0) {
return ret;
}
signed_data->no_of_signers = ret;
/* Don't permit trailing data */
if ( p != end )
return( MBEDTLS_ERR_PKCS7_INVALID_FORMAT );
if (p != end) {
return MBEDTLS_ERR_PKCS7_INVALID_FORMAT;
}
return( 0 );
return 0;
}
int mbedtls_pkcs7_parse_der( mbedtls_pkcs7 *pkcs7, const unsigned char *buf,
const size_t buflen )
int mbedtls_pkcs7_parse_der(mbedtls_pkcs7 *pkcs7, const unsigned char *buf,
const size_t buflen)
{
unsigned char *p;
unsigned char *end;
@ -525,78 +532,75 @@ int mbedtls_pkcs7_parse_der( mbedtls_pkcs7 *pkcs7, const unsigned char *buf,
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int isoidset = 0;
if( pkcs7 == NULL )
{
return( MBEDTLS_ERR_PKCS7_BAD_INPUT_DATA );
if (pkcs7 == NULL) {
return MBEDTLS_ERR_PKCS7_BAD_INPUT_DATA;
}
/* make an internal copy of the buffer for parsing */
pkcs7->raw.p = p = mbedtls_calloc( 1, buflen );
if( pkcs7->raw.p == NULL )
{
pkcs7->raw.p = p = mbedtls_calloc(1, buflen);
if (pkcs7->raw.p == NULL) {
ret = MBEDTLS_ERR_PKCS7_ALLOC_FAILED;
goto out;
}
memcpy( p, buf, buflen );
memcpy(p, buf, buflen);
pkcs7->raw.len = buflen;
end = p + buflen;
ret = pkcs7_get_content_info_type( &p, end, &pkcs7->content_type_oid );
if( ret != 0 )
{
ret = pkcs7_get_content_info_type(&p, end, &pkcs7->content_type_oid);
if (ret != 0) {
len = buflen;
goto try_data;
}
if( ! MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_DATA, &pkcs7->content_type_oid )
|| ! MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_ENCRYPTED_DATA, &pkcs7->content_type_oid )
|| ! MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_ENVELOPED_DATA, &pkcs7->content_type_oid )
|| ! MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_SIGNED_AND_ENVELOPED_DATA, &pkcs7->content_type_oid )
|| ! MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_DIGESTED_DATA, &pkcs7->content_type_oid )
|| ! MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_ENCRYPTED_DATA, &pkcs7->content_type_oid ) )
{
if (!MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_DATA, &pkcs7->content_type_oid)
|| !MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_ENCRYPTED_DATA, &pkcs7->content_type_oid)
|| !MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_ENVELOPED_DATA, &pkcs7->content_type_oid)
|| !MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_SIGNED_AND_ENVELOPED_DATA, &pkcs7->content_type_oid)
|| !MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_DIGESTED_DATA, &pkcs7->content_type_oid)
|| !MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_ENCRYPTED_DATA, &pkcs7->content_type_oid)) {
ret = MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE;
goto out;
}
if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS7_SIGNED_DATA, &pkcs7->content_type_oid ) )
{
if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS7_SIGNED_DATA, &pkcs7->content_type_oid)) {
ret = MBEDTLS_ERR_PKCS7_BAD_INPUT_DATA;
goto out;
}
isoidset = 1;
ret = pkcs7_get_next_content_len( &p, end, &len );
if( ret != 0 )
ret = pkcs7_get_next_content_len(&p, end, &len);
if (ret != 0) {
goto out;
}
try_data:
ret = pkcs7_get_signed_data( p, len, &pkcs7->signed_data );
if ( ret != 0 )
ret = pkcs7_get_signed_data(p, len, &pkcs7->signed_data);
if (ret != 0) {
goto out;
}
if ( !isoidset )
{
if (!isoidset) {
pkcs7->content_type_oid.tag = MBEDTLS_ASN1_OID;
pkcs7->content_type_oid.len = MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS7_SIGNED_DATA );
pkcs7->content_type_oid.p = (unsigned char *)MBEDTLS_OID_PKCS7_SIGNED_DATA;
pkcs7->content_type_oid.len = MBEDTLS_OID_SIZE(MBEDTLS_OID_PKCS7_SIGNED_DATA);
pkcs7->content_type_oid.p = (unsigned char *) MBEDTLS_OID_PKCS7_SIGNED_DATA;
}
ret = MBEDTLS_PKCS7_SIGNED_DATA;
out:
if ( ret < 0 )
mbedtls_pkcs7_free( pkcs7 );
if (ret < 0) {
mbedtls_pkcs7_free(pkcs7);
}
return( ret );
return ret;
}
static int mbedtls_pkcs7_data_or_hash_verify( mbedtls_pkcs7 *pkcs7,
static int mbedtls_pkcs7_data_or_hash_verify(mbedtls_pkcs7 *pkcs7,
const mbedtls_x509_crt *cert,
const unsigned char *data,
size_t datalen,
const int is_data_hash )
const int is_data_hash)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *hash;
@ -605,15 +609,13 @@ static int mbedtls_pkcs7_data_or_hash_verify( mbedtls_pkcs7 *pkcs7,
mbedtls_md_type_t md_alg;
mbedtls_pkcs7_signer_info *signer;
if( pkcs7->signed_data.no_of_signers == 0 )
{
return( MBEDTLS_ERR_PKCS7_INVALID_CERT );
if (pkcs7->signed_data.no_of_signers == 0) {
return MBEDTLS_ERR_PKCS7_INVALID_CERT;
}
if( mbedtls_x509_time_is_past( &cert->valid_to ) ||
mbedtls_x509_time_is_future( &cert->valid_from ))
{
return( MBEDTLS_ERR_PKCS7_CERT_DATE_INVALID );
if (mbedtls_x509_time_is_past(&cert->valid_to) ||
mbedtls_x509_time_is_future(&cert->valid_from)) {
return MBEDTLS_ERR_PKCS7_CERT_DATE_INVALID;
}
/*
@ -629,97 +631,92 @@ static int mbedtls_pkcs7_data_or_hash_verify( mbedtls_pkcs7 *pkcs7,
* We could also cache hashes by md, so if there are several sigs all using
* the same algo we don't recalculate the hash each time.
*/
for( signer = &pkcs7->signed_data.signers; signer; signer = signer->next )
{
ret = mbedtls_oid_get_md_alg( &signer->alg_identifier, &md_alg );
if( ret != 0 )
{
for (signer = &pkcs7->signed_data.signers; signer; signer = signer->next) {
ret = mbedtls_oid_get_md_alg(&signer->alg_identifier, &md_alg);
if (ret != 0) {
ret = MBEDTLS_ERR_PKCS7_VERIFY_FAIL;
continue;
}
md_info = mbedtls_md_info_from_type( md_alg );
if( md_info == NULL )
{
md_info = mbedtls_md_info_from_type(md_alg);
if (md_info == NULL) {
ret = MBEDTLS_ERR_PKCS7_VERIFY_FAIL;
continue;
}
hash = mbedtls_calloc( mbedtls_md_get_size( md_info ), 1 );
if( hash == NULL ) {
return( MBEDTLS_ERR_PKCS7_ALLOC_FAILED );
hash = mbedtls_calloc(mbedtls_md_get_size(md_info), 1);
if (hash == NULL) {
return MBEDTLS_ERR_PKCS7_ALLOC_FAILED;
}
/* BEGIN must free hash before jumping out */
if( is_data_hash )
{
if( datalen != mbedtls_md_get_size( md_info ))
if (is_data_hash) {
if (datalen != mbedtls_md_get_size(md_info)) {
ret = MBEDTLS_ERR_PKCS7_VERIFY_FAIL;
else
} else {
memcpy(hash, data, datalen);
}
} else {
ret = mbedtls_md(md_info, data, datalen, hash);
}
else
{
ret = mbedtls_md( md_info, data, datalen, hash );
}
if( ret != 0 )
{
if (ret != 0) {
ret = MBEDTLS_ERR_PKCS7_VERIFY_FAIL;
mbedtls_free( hash );
mbedtls_free(hash);
continue;
}
ret = mbedtls_pk_verify( &pk_cxt, md_alg, hash,
mbedtls_md_get_size( md_info ),
signer->sig.p, signer->sig.len );
mbedtls_free( hash );
ret = mbedtls_pk_verify(&pk_cxt, md_alg, hash,
mbedtls_md_get_size(md_info),
signer->sig.p, signer->sig.len);
mbedtls_free(hash);
/* END must free hash before jumping out */
if( ret == 0 )
if (ret == 0) {
break;
}
}
return( ret );
return ret;
}
int mbedtls_pkcs7_signed_data_verify( mbedtls_pkcs7 *pkcs7,
const mbedtls_x509_crt *cert,
const unsigned char *data,
size_t datalen )
int mbedtls_pkcs7_signed_data_verify(mbedtls_pkcs7 *pkcs7,
const mbedtls_x509_crt *cert,
const unsigned char *data,
size_t datalen)
{
return( mbedtls_pkcs7_data_or_hash_verify( pkcs7, cert, data, datalen, 0 ) );
return mbedtls_pkcs7_data_or_hash_verify(pkcs7, cert, data, datalen, 0);
}
int mbedtls_pkcs7_signed_hash_verify( mbedtls_pkcs7 *pkcs7,
const mbedtls_x509_crt *cert,
const unsigned char *hash,
size_t hashlen )
int mbedtls_pkcs7_signed_hash_verify(mbedtls_pkcs7 *pkcs7,
const mbedtls_x509_crt *cert,
const unsigned char *hash,
size_t hashlen)
{
return( mbedtls_pkcs7_data_or_hash_verify( pkcs7, cert, hash, hashlen, 1 ) );
return mbedtls_pkcs7_data_or_hash_verify(pkcs7, cert, hash, hashlen, 1);
}
/*
* Unallocate all pkcs7 data
*/
void mbedtls_pkcs7_free( mbedtls_pkcs7 *pkcs7 )
void mbedtls_pkcs7_free(mbedtls_pkcs7 *pkcs7)
{
mbedtls_pkcs7_signer_info *signer_cur;
mbedtls_pkcs7_signer_info *signer_prev;
if( pkcs7 == NULL || pkcs7->raw.p == NULL )
if (pkcs7 == NULL || pkcs7->raw.p == NULL) {
return;
}
mbedtls_free( pkcs7->raw.p );
mbedtls_free(pkcs7->raw.p);
mbedtls_x509_crt_free( &pkcs7->signed_data.certs );
mbedtls_x509_crl_free( &pkcs7->signed_data.crl );
mbedtls_x509_crt_free(&pkcs7->signed_data.certs);
mbedtls_x509_crl_free(&pkcs7->signed_data.crl);
signer_cur = pkcs7->signed_data.signers.next;
pkcs7_free_signer_info( &pkcs7->signed_data.signers );
while( signer_cur != NULL )
{
pkcs7_free_signer_info(&pkcs7->signed_data.signers);
while (signer_cur != NULL) {
signer_prev = signer_cur;
signer_cur = signer_prev->next;
pkcs7_free_signer_info( signer_prev );
mbedtls_free( signer_prev );
pkcs7_free_signer_info(signer_prev);
mbedtls_free(signer_prev);
}
pkcs7->raw.p = NULL;

File diff suppressed because it is too large Load Diff

View File

@ -60,38 +60,41 @@
* publicExponent INTEGER -- e
* }
*/
static int pk_write_rsa_pubkey( unsigned char **p, unsigned char *start,
mbedtls_rsa_context *rsa )
static int pk_write_rsa_pubkey(unsigned char **p, unsigned char *start,
mbedtls_rsa_context *rsa)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
mbedtls_mpi T;
mbedtls_mpi_init( &T );
mbedtls_mpi_init(&T);
/* Export E */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &T ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &T)) != 0 ||
(ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export N */
if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL, NULL, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export(rsa, &T, NULL, NULL, NULL, NULL)) != 0 ||
(ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
goto end_of_export;
}
len += ret;
end_of_export:
mbedtls_mpi_free( &T );
if( ret < 0 )
return( ret );
mbedtls_mpi_free(&T);
if (ret < 0) {
return ret;
}
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 ) );
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 );
return (int) len;
}
#endif /* MBEDTLS_RSA_C */
@ -99,27 +102,27 @@ end_of_export:
/*
* EC public key is an EC point
*/
static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec )
static int pk_write_ec_pubkey(unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
unsigned char buf[MBEDTLS_ECP_MAX_PT_LEN];
if( ( ret = mbedtls_ecp_point_write_binary( &ec->grp, &ec->Q,
MBEDTLS_ECP_PF_UNCOMPRESSED,
&len, buf, sizeof( buf ) ) ) != 0 )
{
return( ret );
if ((ret = mbedtls_ecp_point_write_binary(&ec->grp, &ec->Q,
MBEDTLS_ECP_PF_UNCOMPRESSED,
&len, buf, sizeof(buf))) != 0) {
return ret;
}
if( *p < start || (size_t)( *p - start ) < len )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (*p < start || (size_t) (*p - start) < len) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*p -= len;
memcpy( *p, buf, len );
memcpy(*p, buf, len);
return( (int) len );
return (int) len;
}
/*
@ -127,88 +130,86 @@ static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,
* namedCurve OBJECT IDENTIFIER
* }
*/
static int pk_write_ec_param( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec )
static int pk_write_ec_param(unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
const char *oid;
size_t oid_len;
if( ( ret = mbedtls_oid_get_oid_by_ec_grp( ec->grp.id, &oid, &oid_len ) ) != 0 )
return( ret );
if ((ret = mbedtls_oid_get_oid_by_ec_grp(ec->grp.id, &oid, &oid_len)) != 0) {
return ret;
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) );
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_oid(p, start, oid, oid_len));
return( (int) len );
return (int) len;
}
/*
* privateKey OCTET STRING -- always of length ceil(log2(n)/8)
*/
static int pk_write_ec_private( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec )
static int pk_write_ec_private(unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t byte_length = ( ec->grp.pbits + 7 ) / 8;
size_t byte_length = (ec->grp.pbits + 7) / 8;
unsigned char tmp[MBEDTLS_ECP_MAX_BYTES];
ret = mbedtls_ecp_write_key( ec, tmp, byte_length );
if( ret != 0 )
ret = mbedtls_ecp_write_key(ec, tmp, byte_length);
if (ret != 0) {
goto exit;
ret = mbedtls_asn1_write_octet_string( p, start, tmp, byte_length );
}
ret = mbedtls_asn1_write_octet_string(p, start, tmp, byte_length);
exit:
mbedtls_platform_zeroize( tmp, byte_length );
return( ret );
mbedtls_platform_zeroize(tmp, byte_length);
return ret;
}
#endif /* MBEDTLS_ECP_C */
int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,
const mbedtls_pk_context *key )
int mbedtls_pk_write_pubkey(unsigned char **p, unsigned char *start,
const mbedtls_pk_context *key)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
#if defined(MBEDTLS_RSA_C)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )
MBEDTLS_ASN1_CHK_ADD( len, pk_write_rsa_pubkey( p, start, mbedtls_pk_rsa( *key ) ) );
else
if (mbedtls_pk_get_type(key) == MBEDTLS_PK_RSA) {
MBEDTLS_ASN1_CHK_ADD(len, pk_write_rsa_pubkey(p, start, mbedtls_pk_rsa(*key)));
} else
#endif
#if defined(MBEDTLS_ECP_C)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )
MBEDTLS_ASN1_CHK_ADD( len, pk_write_ec_pubkey( p, start, mbedtls_pk_ec( *key ) ) );
else
if (mbedtls_pk_get_type(key) == MBEDTLS_PK_ECKEY) {
MBEDTLS_ASN1_CHK_ADD(len, pk_write_ec_pubkey(p, start, mbedtls_pk_ec(*key)));
} else
#endif
#if defined(MBEDTLS_USE_PSA_CRYPTO)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_OPAQUE )
{
if (mbedtls_pk_get_type(key) == MBEDTLS_PK_OPAQUE) {
size_t buffer_size;
mbedtls_svc_key_id_t* key_id = (mbedtls_svc_key_id_t*) key->pk_ctx;
mbedtls_svc_key_id_t *key_id = (mbedtls_svc_key_id_t *) key->pk_ctx;
if ( *p < start )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
buffer_size = (size_t)( *p - start );
if ( psa_export_public_key( *key_id, start, buffer_size, &len )
!= PSA_SUCCESS )
{
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (*p < start) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
else
{
buffer_size = (size_t) (*p - start);
if (psa_export_public_key(*key_id, start, buffer_size, &len)
!= PSA_SUCCESS) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
} else {
*p -= len;
memmove( *p, start, len );
memmove(*p, start, len);
}
}
else
} else
#endif /* MBEDTLS_USE_PSA_CRYPTO */
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
return( (int) len );
return (int) len;
}
int mbedtls_pk_write_pubkey_der( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_pubkey_der(const mbedtls_pk_context *key, unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *c;
@ -216,15 +217,17 @@ int mbedtls_pk_write_pubkey_der( const mbedtls_pk_context *key, unsigned char *b
mbedtls_pk_type_t pk_type;
const char *oid;
if( size == 0 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (size == 0) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
c = buf + size;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, key ) );
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_pk_write_pubkey(&c, buf, key));
if( c - buf < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (c - buf < 1) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
/*
* SubjectPublicKeyInfo ::= SEQUENCE {
@ -234,174 +237,176 @@ int mbedtls_pk_write_pubkey_der( const mbedtls_pk_context *key, unsigned char *b
*--c = 0;
len += 1;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_BIT_STRING ) );
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_BIT_STRING));
pk_type = mbedtls_pk_get_type( key );
pk_type = mbedtls_pk_get_type(key);
#if defined(MBEDTLS_ECP_C)
if( pk_type == MBEDTLS_PK_ECKEY )
{
MBEDTLS_ASN1_CHK_ADD( par_len, pk_write_ec_param( &c, buf, mbedtls_pk_ec( *key ) ) );
if (pk_type == MBEDTLS_PK_ECKEY) {
MBEDTLS_ASN1_CHK_ADD(par_len, pk_write_ec_param(&c, buf, mbedtls_pk_ec(*key)));
}
#endif
#if defined(MBEDTLS_USE_PSA_CRYPTO)
if( pk_type == MBEDTLS_PK_OPAQUE )
{
if (pk_type == MBEDTLS_PK_OPAQUE) {
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_type_t key_type;
mbedtls_svc_key_id_t key_id;
psa_ecc_family_t curve;
size_t bits;
key_id = *((mbedtls_svc_key_id_t*) key->pk_ctx );
if( PSA_SUCCESS != psa_get_key_attributes( key_id, &attributes ) )
return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
key_type = psa_get_key_type( &attributes );
bits = psa_get_key_bits( &attributes );
psa_reset_key_attributes( &attributes );
key_id = *((mbedtls_svc_key_id_t *) key->pk_ctx);
if (PSA_SUCCESS != psa_get_key_attributes(key_id, &attributes)) {
return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
}
key_type = psa_get_key_type(&attributes);
bits = psa_get_key_bits(&attributes);
psa_reset_key_attributes(&attributes);
if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( key_type ) )
{
curve = PSA_KEY_TYPE_ECC_GET_FAMILY( key_type );
if( curve == 0 )
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
if (PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type)) {
curve = PSA_KEY_TYPE_ECC_GET_FAMILY(key_type);
if (curve == 0) {
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
}
ret = mbedtls_psa_get_ecc_oid_from_id( curve, bits,
&oid, &oid_len );
if( ret != 0 )
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
ret = mbedtls_psa_get_ecc_oid_from_id(curve, bits,
&oid, &oid_len);
if (ret != 0) {
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
}
/* Write EC algorithm parameters; that's akin
* to pk_write_ec_param() above. */
MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_oid( &c, buf,
oid,
oid_len ) );
MBEDTLS_ASN1_CHK_ADD(par_len, mbedtls_asn1_write_oid(&c, buf,
oid,
oid_len));
/* The rest of the function works as for legacy EC contexts. */
pk_type = MBEDTLS_PK_ECKEY;
}
else if( PSA_KEY_TYPE_IS_RSA( key_type ) )
{
} else if (PSA_KEY_TYPE_IS_RSA(key_type)) {
/* The rest of the function works as for legacy RSA contexts. */
pk_type = MBEDTLS_PK_RSA;
}
else
{
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
} else {
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
}
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */
if( ( ret = mbedtls_oid_get_oid_by_pk_alg( pk_type, &oid,
&oid_len ) ) != 0 )
{
return( ret );
if ((ret = mbedtls_oid_get_oid_by_pk_alg(pk_type, &oid,
&oid_len)) != 0) {
return ret;
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( &c, buf, oid, oid_len,
par_len ) );
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_algorithm_identifier(&c, buf, oid, oid_len,
par_len));
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE));
return( (int) len );
return (int) len;
}
int mbedtls_pk_write_key_der( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_key_der(const mbedtls_pk_context *key, unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *c;
size_t len = 0;
if( size == 0 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (size == 0) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
c = buf + size;
#if defined(MBEDTLS_RSA_C)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )
{
if (mbedtls_pk_get_type(key) == MBEDTLS_PK_RSA) {
mbedtls_mpi T; /* Temporary holding the exported parameters */
mbedtls_rsa_context *rsa = mbedtls_pk_rsa( *key );
mbedtls_rsa_context *rsa = mbedtls_pk_rsa(*key);
/*
* Export the parameters one after another to avoid simultaneous copies.
*/
mbedtls_mpi_init( &T );
mbedtls_mpi_init(&T);
/* Export QP */
if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, NULL, &T ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export_crt(rsa, NULL, NULL, &T)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export DQ */
if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, &T, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export_crt(rsa, NULL, &T, NULL)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export DP */
if( ( ret = mbedtls_rsa_export_crt( rsa, &T, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export_crt(rsa, &T, NULL, NULL)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export Q */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
&T, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export(rsa, NULL, NULL,
&T, NULL, NULL)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export P */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, &T,
NULL, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export(rsa, NULL, &T,
NULL, NULL, NULL)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export D */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
NULL, &T, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export(rsa, NULL, NULL,
NULL, &T, NULL)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export E */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
NULL, NULL, &T ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export(rsa, NULL, NULL,
NULL, NULL, &T)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
/* Export N */
if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL,
NULL, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
if ((ret = mbedtls_rsa_export(rsa, &T, NULL,
NULL, NULL, NULL)) != 0 ||
(ret = mbedtls_asn1_write_mpi(&c, buf, &T)) < 0) {
goto end_of_export;
}
len += ret;
end_of_export:
end_of_export:
mbedtls_mpi_free( &T );
if( ret < 0 )
return( ret );
mbedtls_mpi_free(&T);
if (ret < 0) {
return ret;
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c,
buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
}
else
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_int(&c, buf, 0));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c,
buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE));
} else
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )
{
mbedtls_ecp_keypair *ec = mbedtls_pk_ec( *key );
if (mbedtls_pk_get_type(key) == MBEDTLS_PK_ECKEY) {
mbedtls_ecp_keypair *ec = mbedtls_pk_ec(*key);
size_t pub_len = 0, par_len = 0;
/*
@ -416,44 +421,46 @@ int mbedtls_pk_write_key_der( const mbedtls_pk_context *key, unsigned char *buf,
*/
/* publicKey */
MBEDTLS_ASN1_CHK_ADD( pub_len, pk_write_ec_pubkey( &c, buf, ec ) );
MBEDTLS_ASN1_CHK_ADD(pub_len, pk_write_ec_pubkey(&c, buf, ec));
if( c - buf < 1 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
if (c - buf < 1) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
*--c = 0;
pub_len += 1;
MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_len( &c, buf, pub_len ) );
MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_BIT_STRING ) );
MBEDTLS_ASN1_CHK_ADD(pub_len, mbedtls_asn1_write_len(&c, buf, pub_len));
MBEDTLS_ASN1_CHK_ADD(pub_len, mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_BIT_STRING));
MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_len( &c, buf, pub_len ) );
MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) );
MBEDTLS_ASN1_CHK_ADD(pub_len, mbedtls_asn1_write_len(&c, buf, pub_len));
MBEDTLS_ASN1_CHK_ADD(pub_len, mbedtls_asn1_write_tag(&c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 1));
len += pub_len;
/* parameters */
MBEDTLS_ASN1_CHK_ADD( par_len, pk_write_ec_param( &c, buf, ec ) );
MBEDTLS_ASN1_CHK_ADD(par_len, pk_write_ec_param(&c, buf, ec));
MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_len( &c, buf, par_len ) );
MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) );
MBEDTLS_ASN1_CHK_ADD(par_len, mbedtls_asn1_write_len(&c, buf, par_len));
MBEDTLS_ASN1_CHK_ADD(par_len, mbedtls_asn1_write_tag(&c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 0));
len += par_len;
/* privateKey */
MBEDTLS_ASN1_CHK_ADD( len, pk_write_ec_private( &c, buf, ec ) );
MBEDTLS_ASN1_CHK_ADD(len, pk_write_ec_private(&c, buf, ec));
/* version */
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 1 ) );
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_int(&c, buf, 1));
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
}
else
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE));
} else
#endif /* MBEDTLS_ECP_C */
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
return( (int) len );
return (int) len;
}
#if defined(MBEDTLS_PEM_WRITE_C)
@ -467,70 +474,64 @@ int mbedtls_pk_write_key_der( const mbedtls_pk_context *key, unsigned char *buf,
#define PEM_END_PRIVATE_KEY_EC "-----END EC PRIVATE KEY-----\n"
#define PUB_DER_MAX_BYTES \
( MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES > MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES ? \
MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES : MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES )
(MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES > MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES ? \
MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES : MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES)
#define PRV_DER_MAX_BYTES \
( MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES > MBEDTLS_PK_ECP_PRV_DER_MAX_BYTES ? \
MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES : MBEDTLS_PK_ECP_PRV_DER_MAX_BYTES )
(MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES > MBEDTLS_PK_ECP_PRV_DER_MAX_BYTES ? \
MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES : MBEDTLS_PK_ECP_PRV_DER_MAX_BYTES)
int mbedtls_pk_write_pubkey_pem( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_pubkey_pem(const mbedtls_pk_context *key, unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char output_buf[PUB_DER_MAX_BYTES];
size_t olen = 0;
if( ( ret = mbedtls_pk_write_pubkey_der( key, output_buf,
sizeof(output_buf) ) ) < 0 )
{
return( ret );
if ((ret = mbedtls_pk_write_pubkey_der(key, output_buf,
sizeof(output_buf))) < 0) {
return ret;
}
if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_PUBLIC_KEY, PEM_END_PUBLIC_KEY,
output_buf + sizeof(output_buf) - ret,
ret, buf, size, &olen ) ) != 0 )
{
return( ret );
if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_PUBLIC_KEY, PEM_END_PUBLIC_KEY,
output_buf + sizeof(output_buf) - ret,
ret, buf, size, &olen)) != 0) {
return ret;
}
return( 0 );
return 0;
}
int mbedtls_pk_write_key_pem( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_key_pem(const mbedtls_pk_context *key, unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char output_buf[PRV_DER_MAX_BYTES];
const char *begin, *end;
size_t olen = 0;
if( ( ret = mbedtls_pk_write_key_der( key, output_buf, sizeof(output_buf) ) ) < 0 )
return( ret );
if ((ret = mbedtls_pk_write_key_der(key, output_buf, sizeof(output_buf))) < 0) {
return ret;
}
#if defined(MBEDTLS_RSA_C)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )
{
if (mbedtls_pk_get_type(key) == MBEDTLS_PK_RSA) {
begin = PEM_BEGIN_PRIVATE_KEY_RSA;
end = PEM_END_PRIVATE_KEY_RSA;
}
else
} else
#endif
#if defined(MBEDTLS_ECP_C)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )
{
if (mbedtls_pk_get_type(key) == MBEDTLS_PK_ECKEY) {
begin = PEM_BEGIN_PRIVATE_KEY_EC;
end = PEM_END_PRIVATE_KEY_EC;
}
else
} else
#endif
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
if( ( ret = mbedtls_pem_write_buffer( begin, end,
output_buf + sizeof(output_buf) - ret,
ret, buf, size, &olen ) ) != 0 )
{
return( ret );
if ((ret = mbedtls_pem_write_buffer(begin, end,
output_buf + sizeof(output_buf) - ret,
ret, buf, size, &olen)) != 0) {
return ret;
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_PEM_WRITE_C */

View File

@ -44,7 +44,7 @@
* publicExponent INTEGER -- e 1 + 3 + MPI_MAX + 1
* }
*/
#define MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES ( 38 + 2 * MBEDTLS_MPI_MAX_SIZE )
#define MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE)
/*
* RSA private keys:
@ -61,10 +61,10 @@
* otherPrimeInfos OtherPrimeInfos OPTIONAL 0 (not supported)
* }
*/
#define MBEDTLS_MPI_MAX_SIZE_2 ( MBEDTLS_MPI_MAX_SIZE / 2 + \
MBEDTLS_MPI_MAX_SIZE % 2 )
#define MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES ( 47 + 3 * MBEDTLS_MPI_MAX_SIZE \
+ 5 * MBEDTLS_MPI_MAX_SIZE_2 )
#define MBEDTLS_MPI_MAX_SIZE_2 (MBEDTLS_MPI_MAX_SIZE / 2 + \
MBEDTLS_MPI_MAX_SIZE % 2)
#define MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES (47 + 3 * MBEDTLS_MPI_MAX_SIZE \
+ 5 * MBEDTLS_MPI_MAX_SIZE_2)
#else /* MBEDTLS_RSA_C */
@ -85,7 +85,7 @@
* + 2 * ECP_MAX (coords) [1]
* }
*/
#define MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES ( 30 + 2 * MBEDTLS_ECP_MAX_BYTES )
#define MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES)
/*
* EC private keys:
@ -96,7 +96,7 @@
* publicKey [1] BIT STRING OPTIONAL 1 + 2 + [1] above
* }
*/
#define MBEDTLS_PK_ECP_PRV_DER_MAX_BYTES ( 29 + 3 * MBEDTLS_ECP_MAX_BYTES )
#define MBEDTLS_PK_ECP_PRV_DER_MAX_BYTES (29 + 3 * MBEDTLS_ECP_MAX_BYTES)
#else /* MBEDTLS_ECP_C */

View File

@ -30,22 +30,22 @@
* configuration via mbedtls_platform_set_calloc_free(). So, omit everything
* related to the latter if MBEDTLS_PLATFORM_{FREE/CALLOC}_MACRO are defined. */
#if defined(MBEDTLS_PLATFORM_MEMORY) && \
!( defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && \
defined(MBEDTLS_PLATFORM_FREE_MACRO) )
!(defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && \
defined(MBEDTLS_PLATFORM_FREE_MACRO))
#if !defined(MBEDTLS_PLATFORM_STD_CALLOC)
static void *platform_calloc_uninit( size_t n, size_t size )
static void *platform_calloc_uninit(size_t n, size_t size)
{
((void) n);
((void) size);
return( NULL );
return NULL;
}
#define MBEDTLS_PLATFORM_STD_CALLOC platform_calloc_uninit
#endif /* !MBEDTLS_PLATFORM_STD_CALLOC */
#if !defined(MBEDTLS_PLATFORM_STD_FREE)
static void platform_free_uninit( void *ptr )
static void platform_free_uninit(void *ptr)
{
((void) ptr);
}
@ -53,25 +53,25 @@ static void platform_free_uninit( void *ptr )
#define MBEDTLS_PLATFORM_STD_FREE platform_free_uninit
#endif /* !MBEDTLS_PLATFORM_STD_FREE */
static void * (*mbedtls_calloc_func)( size_t, size_t ) = MBEDTLS_PLATFORM_STD_CALLOC;
static void (*mbedtls_free_func)( void * ) = MBEDTLS_PLATFORM_STD_FREE;
static void * (*mbedtls_calloc_func)(size_t, size_t) = MBEDTLS_PLATFORM_STD_CALLOC;
static void (*mbedtls_free_func)(void *) = MBEDTLS_PLATFORM_STD_FREE;
void * mbedtls_calloc( size_t nmemb, size_t size )
void *mbedtls_calloc(size_t nmemb, size_t size)
{
return (*mbedtls_calloc_func)( nmemb, size );
return (*mbedtls_calloc_func)(nmemb, size);
}
void mbedtls_free( void * ptr )
void mbedtls_free(void *ptr)
{
(*mbedtls_free_func)( ptr );
(*mbedtls_free_func)(ptr);
}
int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
void (*free_func)( void * ) )
int mbedtls_platform_set_calloc_free(void *(*calloc_func)(size_t, size_t),
void (*free_func)(void *))
{
mbedtls_calloc_func = calloc_func;
mbedtls_free_func = free_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_MEMORY &&
!( defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&
@ -79,16 +79,16 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF)
#include <stdarg.h>
int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... )
int mbedtls_platform_win32_snprintf(char *s, size_t n, const char *fmt, ...)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
va_list argp;
va_start( argp, fmt );
ret = mbedtls_vsnprintf( s, n, fmt, argp );
va_end( argp );
va_start(argp, fmt);
ret = mbedtls_vsnprintf(s, n, fmt, argp);
va_end(argp);
return( ret );
return ret;
}
#endif
@ -97,53 +97,53 @@ int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... )
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_snprintf_uninit( char * s, size_t n,
const char * format, ... )
static int platform_snprintf_uninit(char *s, size_t n,
const char *format, ...)
{
((void) s);
((void) n);
((void) format);
return( 0 );
return 0;
}
#define MBEDTLS_PLATFORM_STD_SNPRINTF platform_snprintf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_SNPRINTF */
int (*mbedtls_snprintf)( char * s, size_t n,
const char * format,
... ) = MBEDTLS_PLATFORM_STD_SNPRINTF;
int (*mbedtls_snprintf)(char *s, size_t n,
const char *format,
...) = MBEDTLS_PLATFORM_STD_SNPRINTF;
int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
const char * format,
... ) )
int mbedtls_platform_set_snprintf(int (*snprintf_func)(char *s, size_t n,
const char *format,
...))
{
mbedtls_snprintf = snprintf_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF)
#include <stdarg.h>
int mbedtls_platform_win32_vsnprintf( char *s, size_t n, const char *fmt, va_list arg )
int mbedtls_platform_win32_vsnprintf(char *s, size_t n, const char *fmt, va_list arg)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* Avoid calling the invalid parameter handler by checking ourselves */
if( s == NULL || n == 0 || fmt == NULL )
return( -1 );
if (s == NULL || n == 0 || fmt == NULL) {
return -1;
}
#if defined(_TRUNCATE)
ret = vsnprintf_s( s, n, _TRUNCATE, fmt, arg );
ret = vsnprintf_s(s, n, _TRUNCATE, fmt, arg);
#else
ret = vsnprintf( s, n, fmt, arg );
if( ret < 0 || (size_t) ret == n )
{
ret = vsnprintf(s, n, fmt, arg);
if (ret < 0 || (size_t) ret == n) {
s[n-1] = '\0';
ret = -1;
}
#endif
return( ret );
return ret;
}
#endif
@ -152,29 +152,29 @@ int mbedtls_platform_win32_vsnprintf( char *s, size_t n, const char *fmt, va_lis
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_vsnprintf_uninit( char * s, size_t n,
const char * format, va_list arg )
static int platform_vsnprintf_uninit(char *s, size_t n,
const char *format, va_list arg)
{
((void) s);
((void) n);
((void) format);
((void) arg);
return( -1 );
return -1;
}
#define MBEDTLS_PLATFORM_STD_VSNPRINTF platform_vsnprintf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_VSNPRINTF */
int (*mbedtls_vsnprintf)( char * s, size_t n,
const char * format,
va_list arg ) = MBEDTLS_PLATFORM_STD_VSNPRINTF;
int (*mbedtls_vsnprintf)(char *s, size_t n,
const char *format,
va_list arg) = MBEDTLS_PLATFORM_STD_VSNPRINTF;
int mbedtls_platform_set_vsnprintf( int (*vsnprintf_func)( char * s, size_t n,
const char * format,
va_list arg ) )
int mbedtls_platform_set_vsnprintf(int (*vsnprintf_func)(char *s, size_t n,
const char *format,
va_list arg))
{
mbedtls_vsnprintf = vsnprintf_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */
@ -183,21 +183,21 @@ int mbedtls_platform_set_vsnprintf( int (*vsnprintf_func)( char * s, size_t n,
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_printf_uninit( const char *format, ... )
static int platform_printf_uninit(const char *format, ...)
{
((void) format);
return( 0 );
return 0;
}
#define MBEDTLS_PLATFORM_STD_PRINTF platform_printf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_PRINTF */
int (*mbedtls_printf)( const char *, ... ) = MBEDTLS_PLATFORM_STD_PRINTF;
int (*mbedtls_printf)(const char *, ...) = MBEDTLS_PLATFORM_STD_PRINTF;
int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) )
int mbedtls_platform_set_printf(int (*printf_func)(const char *, ...))
{
mbedtls_printf = printf_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_PRINTF_ALT */
@ -206,23 +206,23 @@ int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) )
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_fprintf_uninit( FILE *stream, const char *format, ... )
static int platform_fprintf_uninit(FILE *stream, const char *format, ...)
{
((void) stream);
((void) format);
return( 0 );
return 0;
}
#define MBEDTLS_PLATFORM_STD_FPRINTF platform_fprintf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_FPRINTF */
int (*mbedtls_fprintf)( FILE *, const char *, ... ) =
MBEDTLS_PLATFORM_STD_FPRINTF;
int (*mbedtls_fprintf)(FILE *, const char *, ...) =
MBEDTLS_PLATFORM_STD_FPRINTF;
int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *, const char *, ... ) )
int mbedtls_platform_set_fprintf(int (*fprintf_func)(FILE *, const char *, ...))
{
mbedtls_fprintf = fprintf_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */
@ -231,20 +231,20 @@ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *, const char *, ...
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static void platform_setbuf_uninit( FILE *stream, char *buf )
static void platform_setbuf_uninit(FILE *stream, char *buf)
{
((void) stream);
((void) buf);
((void) stream);
((void) buf);
}
#define MBEDTLS_PLATFORM_STD_SETBUF platform_setbuf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_SETBUF */
void (*mbedtls_setbuf)( FILE *stream, char *buf ) = MBEDTLS_PLATFORM_STD_SETBUF;
void (*mbedtls_setbuf)(FILE *stream, char *buf) = MBEDTLS_PLATFORM_STD_SETBUF;
int mbedtls_platform_set_setbuf( void (*setbuf_func)( FILE *stream, char *buf ) )
int mbedtls_platform_set_setbuf(void (*setbuf_func)(FILE *stream, char *buf))
{
mbedtls_setbuf = setbuf_func;
return( 0 );
mbedtls_setbuf = setbuf_func;
return 0;
}
#endif /* MBEDTLS_PLATFORM_SETBUF_ALT */
@ -253,7 +253,7 @@ int mbedtls_platform_set_setbuf( void (*setbuf_func)( FILE *stream, char *buf )
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static void platform_exit_uninit( int status )
static void platform_exit_uninit(int status)
{
((void) status);
}
@ -261,12 +261,12 @@ static void platform_exit_uninit( int status )
#define MBEDTLS_PLATFORM_STD_EXIT platform_exit_uninit
#endif /* !MBEDTLS_PLATFORM_STD_EXIT */
void (*mbedtls_exit)( int status ) = MBEDTLS_PLATFORM_STD_EXIT;
void (*mbedtls_exit)(int status) = MBEDTLS_PLATFORM_STD_EXIT;
int mbedtls_platform_set_exit( void (*exit_func)( int status ) )
int mbedtls_platform_set_exit(void (*exit_func)(int status))
{
mbedtls_exit = exit_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_EXIT_ALT */
@ -277,21 +277,21 @@ int mbedtls_platform_set_exit( void (*exit_func)( int status ) )
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static mbedtls_time_t platform_time_uninit( mbedtls_time_t* timer )
static mbedtls_time_t platform_time_uninit(mbedtls_time_t *timer)
{
((void) timer);
return( 0 );
return 0;
}
#define MBEDTLS_PLATFORM_STD_TIME platform_time_uninit
#endif /* !MBEDTLS_PLATFORM_STD_TIME */
mbedtls_time_t (*mbedtls_time)( mbedtls_time_t* timer ) = MBEDTLS_PLATFORM_STD_TIME;
mbedtls_time_t (*mbedtls_time)(mbedtls_time_t *timer) = MBEDTLS_PLATFORM_STD_TIME;
int mbedtls_platform_set_time( mbedtls_time_t (*time_func)( mbedtls_time_t* timer ) )
int mbedtls_platform_set_time(mbedtls_time_t (*time_func)(mbedtls_time_t *timer))
{
mbedtls_time = time_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_TIME_ALT */
@ -302,47 +302,47 @@ int mbedtls_platform_set_time( mbedtls_time_t (*time_func)( mbedtls_time_t* time
/* Default implementations for the platform independent seed functions use
* standard libc file functions to read from and write to a pre-defined filename
*/
int mbedtls_platform_std_nv_seed_read( unsigned char *buf, size_t buf_len )
int mbedtls_platform_std_nv_seed_read(unsigned char *buf, size_t buf_len)
{
FILE *file;
size_t n;
if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "rb" ) ) == NULL )
return( -1 );
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( file, NULL );
if( ( n = fread( buf, 1, buf_len, file ) ) != buf_len )
{
fclose( file );
mbedtls_platform_zeroize( buf, buf_len );
return( -1 );
if ((file = fopen(MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "rb")) == NULL) {
return -1;
}
fclose( file );
return( (int)n );
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf(file, NULL);
if ((n = fread(buf, 1, buf_len, file)) != buf_len) {
fclose(file);
mbedtls_platform_zeroize(buf, buf_len);
return -1;
}
fclose(file);
return (int) n;
}
int mbedtls_platform_std_nv_seed_write( unsigned char *buf, size_t buf_len )
int mbedtls_platform_std_nv_seed_write(unsigned char *buf, size_t buf_len)
{
FILE *file;
size_t n;
if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "w" ) ) == NULL )
return -1;
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf( file, NULL );
if( ( n = fwrite( buf, 1, buf_len, file ) ) != buf_len )
{
fclose( file );
if ((file = fopen(MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "w")) == NULL) {
return -1;
}
fclose( file );
return( (int)n );
/* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
mbedtls_setbuf(file, NULL);
if ((n = fwrite(buf, 1, buf_len, file)) != buf_len) {
fclose(file);
return -1;
}
fclose(file);
return (int) n;
}
#endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */
@ -351,11 +351,11 @@ int mbedtls_platform_std_nv_seed_write( unsigned char *buf, size_t buf_len )
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_nv_seed_read_uninit( unsigned char *buf, size_t buf_len )
static int platform_nv_seed_read_uninit(unsigned char *buf, size_t buf_len)
{
((void) buf);
((void) buf_len);
return( -1 );
return -1;
}
#define MBEDTLS_PLATFORM_STD_NV_SEED_READ platform_nv_seed_read_uninit
@ -365,28 +365,28 @@ static int platform_nv_seed_read_uninit( unsigned char *buf, size_t buf_len )
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_nv_seed_write_uninit( unsigned char *buf, size_t buf_len )
static int platform_nv_seed_write_uninit(unsigned char *buf, size_t buf_len)
{
((void) buf);
((void) buf_len);
return( -1 );
return -1;
}
#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE platform_nv_seed_write_uninit
#endif /* !MBEDTLS_PLATFORM_STD_NV_SEED_WRITE */
int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len ) =
MBEDTLS_PLATFORM_STD_NV_SEED_READ;
int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len ) =
MBEDTLS_PLATFORM_STD_NV_SEED_WRITE;
int (*mbedtls_nv_seed_read)(unsigned char *buf, size_t buf_len) =
MBEDTLS_PLATFORM_STD_NV_SEED_READ;
int (*mbedtls_nv_seed_write)(unsigned char *buf, size_t buf_len) =
MBEDTLS_PLATFORM_STD_NV_SEED_WRITE;
int mbedtls_platform_set_nv_seed(
int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),
int (*nv_seed_write_func)( unsigned char *buf, size_t buf_len ) )
int (*nv_seed_read_func)(unsigned char *buf, size_t buf_len),
int (*nv_seed_write_func)(unsigned char *buf, size_t buf_len))
{
mbedtls_nv_seed_read = nv_seed_read_func;
mbedtls_nv_seed_write = nv_seed_write_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
#endif /* MBEDTLS_ENTROPY_NV_SEED */
@ -395,19 +395,19 @@ int mbedtls_platform_set_nv_seed(
/*
* Placeholder platform setup that does nothing by default
*/
int mbedtls_platform_setup( mbedtls_platform_context *ctx )
int mbedtls_platform_setup(mbedtls_platform_context *ctx)
{
(void)ctx;
(void) ctx;
return( 0 );
return 0;
}
/*
* Placeholder platform teardown that does nothing by default
*/
void mbedtls_platform_teardown( mbedtls_platform_context *ctx )
void mbedtls_platform_teardown(mbedtls_platform_context *ctx)
{
(void)ctx;
(void) ctx;
}
#endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */

View File

@ -62,14 +62,15 @@
* mbedtls_platform_zeroize() to use a suitable implementation for their
* platform and needs.
*/
static void * (* const volatile memset_func)( void *, int, size_t ) = memset;
static void *(*const volatile memset_func)(void *, int, size_t) = memset;
void mbedtls_platform_zeroize( void *buf, size_t len )
void mbedtls_platform_zeroize(void *buf, size_t len)
{
MBEDTLS_INTERNAL_VALIDATE( len == 0 || buf != NULL );
MBEDTLS_INTERNAL_VALIDATE(len == 0 || buf != NULL);
if( len > 0 )
memset_func( buf, 0, len );
if (len > 0) {
memset_func(buf, 0, len);
}
}
#endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */
@ -83,9 +84,9 @@ void mbedtls_platform_zeroize( void *buf, size_t len )
#endif /* !_WIN32 && (unix || __unix || __unix__ ||
* (__APPLE__ && __MACH__)) */
#if !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \
( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \
_POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) )
#if !((defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L) || \
(defined(_POSIX_THREAD_SAFE_FUNCTIONS) && \
_POSIX_THREAD_SAFE_FUNCTIONS >= 200112L))
/*
* This is a convenience shorthand macro to avoid checking the long
* preprocessor conditions above. Ideally, we could expose this macro in
@ -93,70 +94,74 @@ void mbedtls_platform_zeroize( void *buf, size_t len )
* threading.h. However, this macro is not part of the Mbed TLS public API, so
* we keep it private by only defining it in this file
*/
#if ! ( defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) ) || \
( defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) )
#if !(defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)) || \
(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR))
#define PLATFORM_UTIL_USE_GMTIME
#endif
#endif /* !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \
( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \
#endif /* !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \
( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \
_POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) ) */
struct tm *mbedtls_platform_gmtime_r( const mbedtls_time_t *tt,
struct tm *tm_buf )
struct tm *mbedtls_platform_gmtime_r(const mbedtls_time_t *tt,
struct tm *tm_buf)
{
#if defined(_WIN32) && !defined(PLATFORM_UTIL_USE_GMTIME)
#if defined(__STDC_LIB_EXT1__)
return( ( gmtime_s( tt, tm_buf ) == 0 ) ? NULL : tm_buf );
return (gmtime_s(tt, tm_buf) == 0) ? NULL : tm_buf;
#else
/* MSVC and mingw64 argument order and return value are inconsistent with the C11 standard */
return( ( gmtime_s( tm_buf, tt ) == 0 ) ? tm_buf : NULL );
return (gmtime_s(tm_buf, tt) == 0) ? tm_buf : NULL;
#endif
#elif !defined(PLATFORM_UTIL_USE_GMTIME)
return( gmtime_r( tt, tm_buf ) );
return gmtime_r(tt, tm_buf);
#else
struct tm *lt;
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_lock( &mbedtls_threading_gmtime_mutex ) != 0 )
return( NULL );
if (mbedtls_mutex_lock(&mbedtls_threading_gmtime_mutex) != 0) {
return NULL;
}
#endif /* MBEDTLS_THREADING_C */
lt = gmtime( tt );
lt = gmtime(tt);
if( lt != NULL )
{
memcpy( tm_buf, lt, sizeof( struct tm ) );
if (lt != NULL) {
memcpy(tm_buf, lt, sizeof(struct tm));
}
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &mbedtls_threading_gmtime_mutex ) != 0 )
return( NULL );
if (mbedtls_mutex_unlock(&mbedtls_threading_gmtime_mutex) != 0) {
return NULL;
}
#endif /* MBEDTLS_THREADING_C */
return( ( lt == NULL ) ? NULL : tm_buf );
return (lt == NULL) ? NULL : tm_buf;
#endif /* _WIN32 && !EFIX64 && !EFI32 */
}
#endif /* MBEDTLS_HAVE_TIME_DATE && MBEDTLS_PLATFORM_GMTIME_R_ALT */
#if defined(MBEDTLS_TEST_HOOKS)
void (*mbedtls_test_hook_test_fail)( const char *, int, const char *);
void (*mbedtls_test_hook_test_fail)(const char *, int, const char *);
#endif /* MBEDTLS_TEST_HOOKS */
/*
* Provide external definitions of some inline functions so that the compiler
* has the option to not inline them
*/
extern inline void mbedtls_xor( unsigned char *r, const unsigned char *a, const unsigned char *b, size_t n );
extern inline void mbedtls_xor(unsigned char *r,
const unsigned char *a,
const unsigned char *b,
size_t n);
extern inline uint16_t mbedtls_get_unaligned_uint16( const void *p );
extern inline uint16_t mbedtls_get_unaligned_uint16(const void *p);
extern inline void mbedtls_put_unaligned_uint16( void *p, uint16_t x );
extern inline void mbedtls_put_unaligned_uint16(void *p, uint16_t x);
extern inline uint32_t mbedtls_get_unaligned_uint32( const void *p );
extern inline uint32_t mbedtls_get_unaligned_uint32(const void *p);
extern inline void mbedtls_put_unaligned_uint32( void *p, uint32_t x );
extern inline void mbedtls_put_unaligned_uint32(void *p, uint32_t x);
extern inline uint64_t mbedtls_get_unaligned_uint64( const void *p );
extern inline uint64_t mbedtls_get_unaligned_uint64(const void *p);
extern inline void mbedtls_put_unaligned_uint64( void *p, uint64_t x );
extern inline void mbedtls_put_unaligned_uint64(void *p, uint64_t x);

View File

@ -32,14 +32,14 @@
#if !defined(MBEDTLS_POLY1305_ALT)
#define POLY1305_BLOCK_SIZE_BYTES ( 16U )
#define POLY1305_BLOCK_SIZE_BYTES (16U)
/*
* Our implementation is tuned for 32-bit platforms with a 64-bit multiplier.
* However we provided an alternative for platforms without such a multiplier.
*/
#if defined(MBEDTLS_NO_64BIT_MULTIPLICATION)
static uint64_t mul64( uint32_t a, uint32_t b )
static uint64_t mul64(uint32_t a, uint32_t b)
{
/* a = al + 2**16 ah, b = bl + 2**16 bh */
const uint16_t al = (uint16_t) a;
@ -49,15 +49,15 @@ static uint64_t mul64( uint32_t a, uint32_t b )
/* ab = al*bl + 2**16 (ah*bl + bl*bh) + 2**32 ah*bh */
const uint32_t lo = (uint32_t) al * bl;
const uint64_t me = (uint64_t)( (uint32_t) ah * bl ) + (uint32_t) al * bh;
const uint64_t me = (uint64_t) ((uint32_t) ah * bl) + (uint32_t) al * bh;
const uint32_t hi = (uint32_t) ah * bh;
return( lo + ( me << 16 ) + ( (uint64_t) hi << 32 ) );
return lo + (me << 16) + ((uint64_t) hi << 32);
}
#else
static inline uint64_t mul64( uint32_t a, uint32_t b )
static inline uint64_t mul64(uint32_t a, uint32_t b)
{
return( (uint64_t) a * b );
return (uint64_t) a * b;
}
#endif
@ -73,10 +73,10 @@ static inline uint64_t mul64( uint32_t a, uint32_t b )
* applied to the input data before calling this
* function. Otherwise, set this parameter to 1.
*/
static void poly1305_process( mbedtls_poly1305_context *ctx,
size_t nblocks,
const unsigned char *input,
uint32_t needs_padding )
static void poly1305_process(mbedtls_poly1305_context *ctx,
size_t nblocks,
const unsigned char *input,
uint32_t needs_padding)
{
uint64_t d0, d1, d2, d3;
uint32_t acc0, acc1, acc2, acc3, acc4;
@ -90,9 +90,9 @@ static void poly1305_process( mbedtls_poly1305_context *ctx,
r2 = ctx->r[2];
r3 = ctx->r[3];
rs1 = r1 + ( r1 >> 2U );
rs2 = r2 + ( r2 >> 2U );
rs3 = r3 + ( r3 >> 2U );
rs1 = r1 + (r1 >> 2U);
rs2 = r2 + (r2 >> 2U);
rs3 = r3 + (r3 >> 2U);
acc0 = ctx->acc[0];
acc1 = ctx->acc[1];
@ -101,67 +101,66 @@ static void poly1305_process( mbedtls_poly1305_context *ctx,
acc4 = ctx->acc[4];
/* Process full blocks */
for( i = 0U; i < nblocks; i++ )
{
for (i = 0U; i < nblocks; i++) {
/* The input block is treated as a 128-bit little-endian integer */
d0 = MBEDTLS_GET_UINT32_LE( input, offset + 0 );
d1 = MBEDTLS_GET_UINT32_LE( input, offset + 4 );
d2 = MBEDTLS_GET_UINT32_LE( input, offset + 8 );
d3 = MBEDTLS_GET_UINT32_LE( input, offset + 12 );
d0 = MBEDTLS_GET_UINT32_LE(input, offset + 0);
d1 = MBEDTLS_GET_UINT32_LE(input, offset + 4);
d2 = MBEDTLS_GET_UINT32_LE(input, offset + 8);
d3 = MBEDTLS_GET_UINT32_LE(input, offset + 12);
/* Compute: acc += (padded) block as a 130-bit integer */
d0 += (uint64_t) acc0;
d1 += (uint64_t) acc1 + ( d0 >> 32U );
d2 += (uint64_t) acc2 + ( d1 >> 32U );
d3 += (uint64_t) acc3 + ( d2 >> 32U );
d1 += (uint64_t) acc1 + (d0 >> 32U);
d2 += (uint64_t) acc2 + (d1 >> 32U);
d3 += (uint64_t) acc3 + (d2 >> 32U);
acc0 = (uint32_t) d0;
acc1 = (uint32_t) d1;
acc2 = (uint32_t) d2;
acc3 = (uint32_t) d3;
acc4 += (uint32_t) ( d3 >> 32U ) + needs_padding;
acc4 += (uint32_t) (d3 >> 32U) + needs_padding;
/* Compute: acc *= r */
d0 = mul64( acc0, r0 ) +
mul64( acc1, rs3 ) +
mul64( acc2, rs2 ) +
mul64( acc3, rs1 );
d1 = mul64( acc0, r1 ) +
mul64( acc1, r0 ) +
mul64( acc2, rs3 ) +
mul64( acc3, rs2 ) +
mul64( acc4, rs1 );
d2 = mul64( acc0, r2 ) +
mul64( acc1, r1 ) +
mul64( acc2, r0 ) +
mul64( acc3, rs3 ) +
mul64( acc4, rs2 );
d3 = mul64( acc0, r3 ) +
mul64( acc1, r2 ) +
mul64( acc2, r1 ) +
mul64( acc3, r0 ) +
mul64( acc4, rs3 );
d0 = mul64(acc0, r0) +
mul64(acc1, rs3) +
mul64(acc2, rs2) +
mul64(acc3, rs1);
d1 = mul64(acc0, r1) +
mul64(acc1, r0) +
mul64(acc2, rs3) +
mul64(acc3, rs2) +
mul64(acc4, rs1);
d2 = mul64(acc0, r2) +
mul64(acc1, r1) +
mul64(acc2, r0) +
mul64(acc3, rs3) +
mul64(acc4, rs2);
d3 = mul64(acc0, r3) +
mul64(acc1, r2) +
mul64(acc2, r1) +
mul64(acc3, r0) +
mul64(acc4, rs3);
acc4 *= r0;
/* Compute: acc %= (2^130 - 5) (partial remainder) */
d1 += ( d0 >> 32 );
d2 += ( d1 >> 32 );
d3 += ( d2 >> 32 );
d1 += (d0 >> 32);
d2 += (d1 >> 32);
d3 += (d2 >> 32);
acc0 = (uint32_t) d0;
acc1 = (uint32_t) d1;
acc2 = (uint32_t) d2;
acc3 = (uint32_t) d3;
acc4 = (uint32_t) ( d3 >> 32 ) + acc4;
acc4 = (uint32_t) (d3 >> 32) + acc4;
d0 = (uint64_t) acc0 + ( acc4 >> 2 ) + ( acc4 & 0xFFFFFFFCU );
d0 = (uint64_t) acc0 + (acc4 >> 2) + (acc4 & 0xFFFFFFFCU);
acc4 &= 3U;
acc0 = (uint32_t) d0;
d0 = (uint64_t) acc1 + ( d0 >> 32U );
d0 = (uint64_t) acc1 + (d0 >> 32U);
acc1 = (uint32_t) d0;
d0 = (uint64_t) acc2 + ( d0 >> 32U );
d0 = (uint64_t) acc2 + (d0 >> 32U);
acc2 = (uint32_t) d0;
d0 = (uint64_t) acc3 + ( d0 >> 32U );
d0 = (uint64_t) acc3 + (d0 >> 32U);
acc3 = (uint32_t) d0;
d0 = (uint64_t) acc4 + ( d0 >> 32U );
d0 = (uint64_t) acc4 + (d0 >> 32U);
acc4 = (uint32_t) d0;
offset += POLY1305_BLOCK_SIZE_BYTES;
@ -181,8 +180,8 @@ static void poly1305_process( mbedtls_poly1305_context *ctx,
* \param mac The buffer to where the MAC is written. Must be
* big enough to contain the 16-byte MAC.
*/
static void poly1305_compute_mac( const mbedtls_poly1305_context *ctx,
unsigned char mac[16] )
static void poly1305_compute_mac(const mbedtls_poly1305_context *ctx,
unsigned char mac[16])
{
uint64_t d;
uint32_t g0, g1, g2, g3, g4;
@ -202,68 +201,69 @@ static void poly1305_compute_mac( const mbedtls_poly1305_context *ctx,
*/
/* Calculate acc + -(2^130 - 5) */
d = ( (uint64_t) acc0 + 5U );
d = ((uint64_t) acc0 + 5U);
g0 = (uint32_t) d;
d = ( (uint64_t) acc1 + ( d >> 32 ) );
d = ((uint64_t) acc1 + (d >> 32));
g1 = (uint32_t) d;
d = ( (uint64_t) acc2 + ( d >> 32 ) );
d = ((uint64_t) acc2 + (d >> 32));
g2 = (uint32_t) d;
d = ( (uint64_t) acc3 + ( d >> 32 ) );
d = ((uint64_t) acc3 + (d >> 32));
g3 = (uint32_t) d;
g4 = acc4 + (uint32_t) ( d >> 32U );
g4 = acc4 + (uint32_t) (d >> 32U);
/* mask == 0xFFFFFFFF if 131st bit is set, otherwise mask == 0 */
mask = (uint32_t) 0U - ( g4 >> 2U );
mask = (uint32_t) 0U - (g4 >> 2U);
mask_inv = ~mask;
/* If 131st bit is set then acc=g, otherwise, acc is unmodified */
acc0 = ( acc0 & mask_inv ) | ( g0 & mask );
acc1 = ( acc1 & mask_inv ) | ( g1 & mask );
acc2 = ( acc2 & mask_inv ) | ( g2 & mask );
acc3 = ( acc3 & mask_inv ) | ( g3 & mask );
acc0 = (acc0 & mask_inv) | (g0 & mask);
acc1 = (acc1 & mask_inv) | (g1 & mask);
acc2 = (acc2 & mask_inv) | (g2 & mask);
acc3 = (acc3 & mask_inv) | (g3 & mask);
/* Add 's' */
d = (uint64_t) acc0 + ctx->s[0];
acc0 = (uint32_t) d;
d = (uint64_t) acc1 + ctx->s[1] + ( d >> 32U );
d = (uint64_t) acc1 + ctx->s[1] + (d >> 32U);
acc1 = (uint32_t) d;
d = (uint64_t) acc2 + ctx->s[2] + ( d >> 32U );
d = (uint64_t) acc2 + ctx->s[2] + (d >> 32U);
acc2 = (uint32_t) d;
acc3 += ctx->s[3] + (uint32_t) ( d >> 32U );
acc3 += ctx->s[3] + (uint32_t) (d >> 32U);
/* Compute MAC (128 least significant bits of the accumulator) */
MBEDTLS_PUT_UINT32_LE( acc0, mac, 0 );
MBEDTLS_PUT_UINT32_LE( acc1, mac, 4 );
MBEDTLS_PUT_UINT32_LE( acc2, mac, 8 );
MBEDTLS_PUT_UINT32_LE( acc3, mac, 12 );
MBEDTLS_PUT_UINT32_LE(acc0, mac, 0);
MBEDTLS_PUT_UINT32_LE(acc1, mac, 4);
MBEDTLS_PUT_UINT32_LE(acc2, mac, 8);
MBEDTLS_PUT_UINT32_LE(acc3, mac, 12);
}
void mbedtls_poly1305_init( mbedtls_poly1305_context *ctx )
void mbedtls_poly1305_init(mbedtls_poly1305_context *ctx)
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_poly1305_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_poly1305_context));
}
void mbedtls_poly1305_free( mbedtls_poly1305_context *ctx )
void mbedtls_poly1305_free(mbedtls_poly1305_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_poly1305_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_poly1305_context));
}
int mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx,
const unsigned char key[32] )
int mbedtls_poly1305_starts(mbedtls_poly1305_context *ctx,
const unsigned char key[32])
{
/* r &= 0x0ffffffc0ffffffc0ffffffc0fffffff */
ctx->r[0] = MBEDTLS_GET_UINT32_LE( key, 0 ) & 0x0FFFFFFFU;
ctx->r[1] = MBEDTLS_GET_UINT32_LE( key, 4 ) & 0x0FFFFFFCU;
ctx->r[2] = MBEDTLS_GET_UINT32_LE( key, 8 ) & 0x0FFFFFFCU;
ctx->r[3] = MBEDTLS_GET_UINT32_LE( key, 12 ) & 0x0FFFFFFCU;
ctx->r[0] = MBEDTLS_GET_UINT32_LE(key, 0) & 0x0FFFFFFFU;
ctx->r[1] = MBEDTLS_GET_UINT32_LE(key, 4) & 0x0FFFFFFCU;
ctx->r[2] = MBEDTLS_GET_UINT32_LE(key, 8) & 0x0FFFFFFCU;
ctx->r[3] = MBEDTLS_GET_UINT32_LE(key, 12) & 0x0FFFFFFCU;
ctx->s[0] = MBEDTLS_GET_UINT32_LE( key, 16 );
ctx->s[1] = MBEDTLS_GET_UINT32_LE( key, 20 );
ctx->s[2] = MBEDTLS_GET_UINT32_LE( key, 24 );
ctx->s[3] = MBEDTLS_GET_UINT32_LE( key, 28 );
ctx->s[0] = MBEDTLS_GET_UINT32_LE(key, 16);
ctx->s[1] = MBEDTLS_GET_UINT32_LE(key, 20);
ctx->s[2] = MBEDTLS_GET_UINT32_LE(key, 24);
ctx->s[3] = MBEDTLS_GET_UINT32_LE(key, 28);
/* Initial accumulator state */
ctx->acc[0] = 0U;
@ -273,121 +273,116 @@ int mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx,
ctx->acc[4] = 0U;
/* Queue initially empty */
mbedtls_platform_zeroize( ctx->queue, sizeof( ctx->queue ) );
mbedtls_platform_zeroize(ctx->queue, sizeof(ctx->queue));
ctx->queue_len = 0U;
return( 0 );
return 0;
}
int mbedtls_poly1305_update( mbedtls_poly1305_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_poly1305_update(mbedtls_poly1305_context *ctx,
const unsigned char *input,
size_t ilen)
{
size_t offset = 0U;
size_t remaining = ilen;
size_t queue_free_len;
size_t nblocks;
if( ( remaining > 0U ) && ( ctx->queue_len > 0U ) )
{
queue_free_len = ( POLY1305_BLOCK_SIZE_BYTES - ctx->queue_len );
if ((remaining > 0U) && (ctx->queue_len > 0U)) {
queue_free_len = (POLY1305_BLOCK_SIZE_BYTES - ctx->queue_len);
if( ilen < queue_free_len )
{
if (ilen < queue_free_len) {
/* Not enough data to complete the block.
* Store this data with the other leftovers.
*/
memcpy( &ctx->queue[ctx->queue_len],
input,
ilen );
memcpy(&ctx->queue[ctx->queue_len],
input,
ilen);
ctx->queue_len += ilen;
remaining = 0U;
}
else
{
} else {
/* Enough data to produce a complete block */
memcpy( &ctx->queue[ctx->queue_len],
input,
queue_free_len );
memcpy(&ctx->queue[ctx->queue_len],
input,
queue_free_len);
ctx->queue_len = 0U;
poly1305_process( ctx, 1U, ctx->queue, 1U ); /* add padding bit */
poly1305_process(ctx, 1U, ctx->queue, 1U); /* add padding bit */
offset += queue_free_len;
remaining -= queue_free_len;
}
}
if( remaining >= POLY1305_BLOCK_SIZE_BYTES )
{
if (remaining >= POLY1305_BLOCK_SIZE_BYTES) {
nblocks = remaining / POLY1305_BLOCK_SIZE_BYTES;
poly1305_process( ctx, nblocks, &input[offset], 1U );
poly1305_process(ctx, nblocks, &input[offset], 1U);
offset += nblocks * POLY1305_BLOCK_SIZE_BYTES;
remaining %= POLY1305_BLOCK_SIZE_BYTES;
}
if( remaining > 0U )
{
if (remaining > 0U) {
/* Store partial block */
ctx->queue_len = remaining;
memcpy( ctx->queue, &input[offset], remaining );
memcpy(ctx->queue, &input[offset], remaining);
}
return( 0 );
return 0;
}
int mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx,
unsigned char mac[16] )
int mbedtls_poly1305_finish(mbedtls_poly1305_context *ctx,
unsigned char mac[16])
{
/* Process any leftover data */
if( ctx->queue_len > 0U )
{
if (ctx->queue_len > 0U) {
/* Add padding bit */
ctx->queue[ctx->queue_len] = 1U;
ctx->queue_len++;
/* Pad with zeroes */
memset( &ctx->queue[ctx->queue_len],
0,
POLY1305_BLOCK_SIZE_BYTES - ctx->queue_len );
memset(&ctx->queue[ctx->queue_len],
0,
POLY1305_BLOCK_SIZE_BYTES - ctx->queue_len);
poly1305_process( ctx, 1U, /* Process 1 block */
ctx->queue, 0U ); /* Already padded above */
poly1305_process(ctx, 1U, /* Process 1 block */
ctx->queue, 0U); /* Already padded above */
}
poly1305_compute_mac( ctx, mac );
poly1305_compute_mac(ctx, mac);
return( 0 );
return 0;
}
int mbedtls_poly1305_mac( const unsigned char key[32],
const unsigned char *input,
size_t ilen,
unsigned char mac[16] )
int mbedtls_poly1305_mac(const unsigned char key[32],
const unsigned char *input,
size_t ilen,
unsigned char mac[16])
{
mbedtls_poly1305_context ctx;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_poly1305_init( &ctx );
mbedtls_poly1305_init(&ctx);
ret = mbedtls_poly1305_starts( &ctx, key );
if( ret != 0 )
ret = mbedtls_poly1305_starts(&ctx, key);
if (ret != 0) {
goto cleanup;
}
ret = mbedtls_poly1305_update( &ctx, input, ilen );
if( ret != 0 )
ret = mbedtls_poly1305_update(&ctx, input, ilen);
if (ret != 0) {
goto cleanup;
}
ret = mbedtls_poly1305_finish( &ctx, mac );
ret = mbedtls_poly1305_finish(&ctx, mac);
cleanup:
mbedtls_poly1305_free( &ctx );
return( ret );
mbedtls_poly1305_free(&ctx);
return ret;
}
#endif /* MBEDTLS_POLY1305_ALT */
@ -460,46 +455,48 @@ static const unsigned char test_mac[2][16] =
/* Make sure no other definition is already present. */
#undef ASSERT
#define ASSERT( cond, args ) \
#define ASSERT(cond, args) \
do \
{ \
if( ! ( cond ) ) \
if (!(cond)) \
{ \
if( verbose != 0 ) \
mbedtls_printf args; \
if (verbose != 0) \
mbedtls_printf args; \
\
return( -1 ); \
return -1; \
} \
} \
while( 0 )
while (0)
int mbedtls_poly1305_self_test( int verbose )
int mbedtls_poly1305_self_test(int verbose)
{
unsigned char mac[16];
unsigned i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
for( i = 0U; i < 2U; i++ )
{
if( verbose != 0 )
mbedtls_printf( " Poly1305 test %u ", i );
for (i = 0U; i < 2U; i++) {
if (verbose != 0) {
mbedtls_printf(" Poly1305 test %u ", i);
}
ret = mbedtls_poly1305_mac( test_keys[i],
test_data[i],
test_data_len[i],
mac );
ASSERT( 0 == ret, ( "error code: %i\n", ret ) );
ret = mbedtls_poly1305_mac(test_keys[i],
test_data[i],
test_data_len[i],
mac);
ASSERT(0 == ret, ("error code: %i\n", ret));
ASSERT( 0 == memcmp( mac, test_mac[i], 16U ), ( "failed (mac)\n" ) );
ASSERT(0 == memcmp(mac, test_mac[i], 16U), ("failed (mac)\n"));
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_SELF_TEST */

File diff suppressed because it is too large Load Diff

View File

@ -40,88 +40,94 @@ static psa_status_t psa_aead_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t key_bits;
const mbedtls_cipher_info_t *cipher_info;
mbedtls_cipher_id_t cipher_id;
( void ) key_buffer_size;
(void) key_buffer_size;
key_bits = attributes->core.bits;
cipher_info = mbedtls_cipher_info_from_psa( alg,
attributes->core.type, key_bits,
&cipher_id );
if( cipher_info == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
cipher_info = mbedtls_cipher_info_from_psa(alg,
attributes->core.type, key_bits,
&cipher_id);
if (cipher_info == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
switch( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 ) )
{
switch (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg, 0)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, 0 ):
case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 0):
operation->alg = PSA_ALG_CCM;
/* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.
* The call to mbedtls_ccm_encrypt_and_tag or
* mbedtls_ccm_auth_decrypt will validate the tag length. */
if( PSA_BLOCK_CIPHER_BLOCK_LENGTH( attributes->core.type ) != 16 )
return( PSA_ERROR_INVALID_ARGUMENT );
if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(attributes->core.type) != 16) {
return PSA_ERROR_INVALID_ARGUMENT;
}
mbedtls_ccm_init( &operation->ctx.ccm );
mbedtls_ccm_init(&operation->ctx.ccm);
status = mbedtls_to_psa_error(
mbedtls_ccm_setkey( &operation->ctx.ccm, cipher_id,
key_buffer, (unsigned int) key_bits ) );
if( status != PSA_SUCCESS )
return( status );
mbedtls_ccm_setkey(&operation->ctx.ccm, cipher_id,
key_buffer, (unsigned int) key_bits));
if (status != PSA_SUCCESS) {
return status;
}
break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, 0 ):
case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0):
operation->alg = PSA_ALG_GCM;
/* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16.
* The call to mbedtls_gcm_crypt_and_tag or
* mbedtls_gcm_auth_decrypt will validate the tag length. */
if( PSA_BLOCK_CIPHER_BLOCK_LENGTH( attributes->core.type ) != 16 )
return( PSA_ERROR_INVALID_ARGUMENT );
if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(attributes->core.type) != 16) {
return PSA_ERROR_INVALID_ARGUMENT;
}
mbedtls_gcm_init( &operation->ctx.gcm );
mbedtls_gcm_init(&operation->ctx.gcm);
status = mbedtls_to_psa_error(
mbedtls_gcm_setkey( &operation->ctx.gcm, cipher_id,
key_buffer, (unsigned int) key_bits ) );
if( status != PSA_SUCCESS )
return( status );
mbedtls_gcm_setkey(&operation->ctx.gcm, cipher_id,
key_buffer, (unsigned int) key_bits));
if (status != PSA_SUCCESS) {
return status;
}
break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CHACHA20_POLY1305, 0 ):
case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CHACHA20_POLY1305, 0):
operation->alg = PSA_ALG_CHACHA20_POLY1305;
/* We only support the default tag length. */
if( alg != PSA_ALG_CHACHA20_POLY1305 )
return( PSA_ERROR_NOT_SUPPORTED );
if (alg != PSA_ALG_CHACHA20_POLY1305) {
return PSA_ERROR_NOT_SUPPORTED;
}
mbedtls_chachapoly_init( &operation->ctx.chachapoly );
mbedtls_chachapoly_init(&operation->ctx.chachapoly);
status = mbedtls_to_psa_error(
mbedtls_chachapoly_setkey( &operation->ctx.chachapoly,
key_buffer ) );
if( status != PSA_SUCCESS )
return( status );
mbedtls_chachapoly_setkey(&operation->ctx.chachapoly,
key_buffer));
if (status != PSA_SUCCESS) {
return status;
}
break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
default:
(void) status;
(void) key_buffer;
return( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
operation->key_type = psa_get_key_type( attributes );
operation->key_type = psa_get_key_type(attributes);
operation->tag_length = PSA_ALG_AEAD_GET_TAG_LENGTH( alg );
operation->tag_length = PSA_ALG_AEAD_GET_TAG_LENGTH(alg);
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_aead_encrypt(
@ -131,74 +137,67 @@ psa_status_t mbedtls_psa_aead_encrypt(
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *plaintext, size_t plaintext_length,
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length )
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_aead_operation_t operation = MBEDTLS_PSA_AEAD_OPERATION_INIT;
uint8_t *tag;
status = psa_aead_setup( &operation, attributes, key_buffer,
key_buffer_size, alg );
status = psa_aead_setup(&operation, attributes, key_buffer,
key_buffer_size, alg);
if( status != PSA_SUCCESS )
if (status != PSA_SUCCESS) {
goto exit;
}
/* For all currently supported modes, the tag is at the end of the
* ciphertext. */
if( ciphertext_size < ( plaintext_length + operation.tag_length ) )
{
if (ciphertext_size < (plaintext_length + operation.tag_length)) {
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto exit;
}
tag = ciphertext + plaintext_length;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if( operation.alg == PSA_ALG_CCM )
{
if (operation.alg == PSA_ALG_CCM) {
status = mbedtls_to_psa_error(
mbedtls_ccm_encrypt_and_tag( &operation.ctx.ccm,
plaintext_length,
nonce, nonce_length,
additional_data,
additional_data_length,
plaintext, ciphertext,
tag, operation.tag_length ) );
}
else
mbedtls_ccm_encrypt_and_tag(&operation.ctx.ccm,
plaintext_length,
nonce, nonce_length,
additional_data,
additional_data_length,
plaintext, ciphertext,
tag, operation.tag_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
if( operation.alg == PSA_ALG_GCM )
{
if (operation.alg == PSA_ALG_GCM) {
status = mbedtls_to_psa_error(
mbedtls_gcm_crypt_and_tag( &operation.ctx.gcm,
MBEDTLS_GCM_ENCRYPT,
plaintext_length,
nonce, nonce_length,
additional_data, additional_data_length,
plaintext, ciphertext,
operation.tag_length, tag ) );
}
else
mbedtls_gcm_crypt_and_tag(&operation.ctx.gcm,
MBEDTLS_GCM_ENCRYPT,
plaintext_length,
nonce, nonce_length,
additional_data, additional_data_length,
plaintext, ciphertext,
operation.tag_length, tag));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
if( operation.alg == PSA_ALG_CHACHA20_POLY1305 )
{
if( operation.tag_length != 16 )
{
if (operation.alg == PSA_ALG_CHACHA20_POLY1305) {
if (operation.tag_length != 16) {
status = PSA_ERROR_NOT_SUPPORTED;
goto exit;
}
status = mbedtls_to_psa_error(
mbedtls_chachapoly_encrypt_and_tag( &operation.ctx.chachapoly,
plaintext_length,
nonce,
additional_data,
additional_data_length,
plaintext,
ciphertext,
tag ) );
}
else
mbedtls_chachapoly_encrypt_and_tag(&operation.ctx.chachapoly,
plaintext_length,
nonce,
additional_data,
additional_data_length,
plaintext,
ciphertext,
tag));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
{
(void) tag;
@ -207,16 +206,17 @@ psa_status_t mbedtls_psa_aead_encrypt(
(void) additional_data;
(void) additional_data_length;
(void) plaintext;
return( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
*ciphertext_length = plaintext_length + operation.tag_length;
}
exit:
mbedtls_psa_aead_abort( &operation );
mbedtls_psa_aead_abort(&operation);
return( status );
return status;
}
/* Locate the tag in a ciphertext buffer containing the encrypted data
@ -224,20 +224,22 @@ exit:
* *plaintext_length. This is the size of the plaintext in modes where
* the encrypted data has the same size as the plaintext, such as
* CCM and GCM. */
static psa_status_t psa_aead_unpadded_locate_tag( size_t tag_length,
const uint8_t *ciphertext,
size_t ciphertext_length,
size_t plaintext_size,
const uint8_t **p_tag )
static psa_status_t psa_aead_unpadded_locate_tag(size_t tag_length,
const uint8_t *ciphertext,
size_t ciphertext_length,
size_t plaintext_size,
const uint8_t **p_tag)
{
size_t payload_length;
if( tag_length > ciphertext_length )
return( PSA_ERROR_INVALID_ARGUMENT );
if (tag_length > ciphertext_length) {
return PSA_ERROR_INVALID_ARGUMENT;
}
payload_length = ciphertext_length - tag_length;
if( payload_length > plaintext_size )
return( PSA_ERROR_BUFFER_TOO_SMALL );
if (payload_length > plaintext_size) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
*p_tag = ciphertext + payload_length;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_aead_decrypt(
@ -247,71 +249,66 @@ psa_status_t mbedtls_psa_aead_decrypt(
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *ciphertext, size_t ciphertext_length,
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length )
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_aead_operation_t operation = MBEDTLS_PSA_AEAD_OPERATION_INIT;
const uint8_t *tag = NULL;
status = psa_aead_setup( &operation, attributes, key_buffer,
key_buffer_size, alg );
status = psa_aead_setup(&operation, attributes, key_buffer,
key_buffer_size, alg);
if( status != PSA_SUCCESS )
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_aead_unpadded_locate_tag( operation.tag_length,
ciphertext, ciphertext_length,
plaintext_size, &tag );
if( status != PSA_SUCCESS )
status = psa_aead_unpadded_locate_tag(operation.tag_length,
ciphertext, ciphertext_length,
plaintext_size, &tag);
if (status != PSA_SUCCESS) {
goto exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if( operation.alg == PSA_ALG_CCM )
{
if (operation.alg == PSA_ALG_CCM) {
status = mbedtls_to_psa_error(
mbedtls_ccm_auth_decrypt( &operation.ctx.ccm,
ciphertext_length - operation.tag_length,
nonce, nonce_length,
additional_data,
additional_data_length,
ciphertext, plaintext,
tag, operation.tag_length ) );
}
else
mbedtls_ccm_auth_decrypt(&operation.ctx.ccm,
ciphertext_length - operation.tag_length,
nonce, nonce_length,
additional_data,
additional_data_length,
ciphertext, plaintext,
tag, operation.tag_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
if( operation.alg == PSA_ALG_GCM )
{
if (operation.alg == PSA_ALG_GCM) {
status = mbedtls_to_psa_error(
mbedtls_gcm_auth_decrypt( &operation.ctx.gcm,
ciphertext_length - operation.tag_length,
nonce, nonce_length,
additional_data,
additional_data_length,
tag, operation.tag_length,
ciphertext, plaintext ) );
}
else
mbedtls_gcm_auth_decrypt(&operation.ctx.gcm,
ciphertext_length - operation.tag_length,
nonce, nonce_length,
additional_data,
additional_data_length,
tag, operation.tag_length,
ciphertext, plaintext));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
if( operation.alg == PSA_ALG_CHACHA20_POLY1305 )
{
if( operation.tag_length != 16 )
{
if (operation.alg == PSA_ALG_CHACHA20_POLY1305) {
if (operation.tag_length != 16) {
status = PSA_ERROR_NOT_SUPPORTED;
goto exit;
}
status = mbedtls_to_psa_error(
mbedtls_chachapoly_auth_decrypt( &operation.ctx.chachapoly,
ciphertext_length - operation.tag_length,
nonce,
additional_data,
additional_data_length,
tag,
ciphertext,
plaintext ) );
}
else
mbedtls_chachapoly_auth_decrypt(&operation.ctx.chachapoly,
ciphertext_length - operation.tag_length,
nonce,
additional_data,
additional_data_length,
tag,
ciphertext,
plaintext));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
{
(void) nonce;
@ -319,18 +316,20 @@ psa_status_t mbedtls_psa_aead_decrypt(
(void) additional_data;
(void) additional_data_length;
(void) plaintext;
return( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
*plaintext_length = ciphertext_length - operation.tag_length;
}
exit:
mbedtls_psa_aead_abort( &operation );
mbedtls_psa_aead_abort(&operation);
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
*plaintext_length = ciphertext_length - operation.tag_length;
return( status );
}
return status;
}
/* Set the key and algorithm for a multipart authenticated encryption
@ -340,17 +339,18 @@ psa_status_t mbedtls_psa_aead_encrypt_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
status = psa_aead_setup( operation, attributes, key_buffer,
key_buffer_size, alg );
status = psa_aead_setup(operation, attributes, key_buffer,
key_buffer_size, alg);
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
operation->is_encrypt = 1;
}
return ( status );
return status;
}
/* Set the key and algorithm for a multipart authenticated decryption
@ -360,152 +360,139 @@ psa_status_t mbedtls_psa_aead_decrypt_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
status = psa_aead_setup( operation, attributes, key_buffer,
key_buffer_size, alg );
status = psa_aead_setup(operation, attributes, key_buffer,
key_buffer_size, alg);
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
operation->is_encrypt = 0;
}
return ( status );
return status;
}
/* Set a nonce for the multipart AEAD operation*/
psa_status_t mbedtls_psa_aead_set_nonce(
mbedtls_psa_aead_operation_t *operation,
const uint8_t *nonce,
size_t nonce_length )
size_t nonce_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
if( operation->alg == PSA_ALG_GCM )
{
if (operation->alg == PSA_ALG_GCM) {
status = mbedtls_to_psa_error(
mbedtls_gcm_starts( &operation->ctx.gcm,
operation->is_encrypt ?
MBEDTLS_GCM_ENCRYPT : MBEDTLS_GCM_DECRYPT,
nonce,
nonce_length ) );
}
else
mbedtls_gcm_starts(&operation->ctx.gcm,
operation->is_encrypt ?
MBEDTLS_GCM_ENCRYPT : MBEDTLS_GCM_DECRYPT,
nonce,
nonce_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if( operation->alg == PSA_ALG_CCM )
{
if (operation->alg == PSA_ALG_CCM) {
status = mbedtls_to_psa_error(
mbedtls_ccm_starts( &operation->ctx.ccm,
operation->is_encrypt ?
MBEDTLS_CCM_ENCRYPT : MBEDTLS_CCM_DECRYPT,
nonce,
nonce_length ) );
}
else
mbedtls_ccm_starts(&operation->ctx.ccm,
operation->is_encrypt ?
MBEDTLS_CCM_ENCRYPT : MBEDTLS_CCM_DECRYPT,
nonce,
nonce_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
{
if (operation->alg == PSA_ALG_CHACHA20_POLY1305) {
/* Note - ChaChaPoly allows an 8 byte nonce, but we would have to
* allocate a buffer in the operation, copy the nonce to it and pad
* it, so for now check the nonce is 12 bytes, as
* mbedtls_chachapoly_starts() assumes it can read 12 bytes from the
* passed in buffer. */
if( nonce_length != 12 )
{
return( PSA_ERROR_INVALID_ARGUMENT );
if (nonce_length != 12) {
return PSA_ERROR_INVALID_ARGUMENT;
}
status = mbedtls_to_psa_error(
mbedtls_chachapoly_starts( &operation->ctx.chachapoly,
mbedtls_chachapoly_starts(&operation->ctx.chachapoly,
nonce,
operation->is_encrypt ?
MBEDTLS_CHACHAPOLY_ENCRYPT :
MBEDTLS_CHACHAPOLY_DECRYPT ) );
}
else
MBEDTLS_CHACHAPOLY_DECRYPT));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
{
( void ) operation;
( void ) nonce;
( void ) nonce_length;
(void) operation;
(void) nonce;
(void) nonce_length;
return ( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
return( status );
return status;
}
/* Declare the lengths of the message and additional data for AEAD. */
/* Declare the lengths of the message and additional data for AEAD. */
psa_status_t mbedtls_psa_aead_set_lengths(
mbedtls_psa_aead_operation_t *operation,
size_t ad_length,
size_t plaintext_length )
size_t plaintext_length)
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if( operation->alg == PSA_ALG_CCM )
{
return( mbedtls_to_psa_error(
mbedtls_ccm_set_lengths( &operation->ctx.ccm,
ad_length,
plaintext_length,
operation->tag_length ) ) );
if (operation->alg == PSA_ALG_CCM) {
return mbedtls_to_psa_error(
mbedtls_ccm_set_lengths(&operation->ctx.ccm,
ad_length,
plaintext_length,
operation->tag_length));
}
#else /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
( void ) operation;
( void ) ad_length;
( void ) plaintext_length;
(void) operation;
(void) ad_length;
(void) plaintext_length;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
return ( PSA_SUCCESS );
return PSA_SUCCESS;
}
/* Pass additional data to an active multipart AEAD operation. */
psa_status_t mbedtls_psa_aead_update_ad(
mbedtls_psa_aead_operation_t *operation,
const uint8_t *input,
size_t input_length )
size_t input_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
if( operation->alg == PSA_ALG_GCM )
{
if (operation->alg == PSA_ALG_GCM) {
status = mbedtls_to_psa_error(
mbedtls_gcm_update_ad( &operation->ctx.gcm, input, input_length ) );
}
else
mbedtls_gcm_update_ad(&operation->ctx.gcm, input, input_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if( operation->alg == PSA_ALG_CCM )
{
if (operation->alg == PSA_ALG_CCM) {
status = mbedtls_to_psa_error(
mbedtls_ccm_update_ad( &operation->ctx.ccm, input, input_length ) );
}
else
mbedtls_ccm_update_ad(&operation->ctx.ccm, input, input_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
{
if (operation->alg == PSA_ALG_CHACHA20_POLY1305) {
status = mbedtls_to_psa_error(
mbedtls_chachapoly_update_aad( &operation->ctx.chachapoly,
mbedtls_chachapoly_update_aad(&operation->ctx.chachapoly,
input,
input_length ) );
}
else
input_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
{
( void ) operation;
( void ) input;
( void ) input_length;
(void) operation;
(void) input;
(void) input_length;
return ( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
return ( status );
return status;
}
/* Encrypt or decrypt a message fragment in an active multipart AEAD
@ -516,7 +503,7 @@ psa_status_t mbedtls_psa_aead_update(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
size_t *output_length)
{
size_t update_output_length;
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
@ -524,57 +511,54 @@ psa_status_t mbedtls_psa_aead_update(
update_output_length = input_length;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
if( operation->alg == PSA_ALG_GCM )
{
if (operation->alg == PSA_ALG_GCM) {
status = mbedtls_to_psa_error(
mbedtls_gcm_update( &operation->ctx.gcm,
input, input_length,
output, output_size,
&update_output_length ) );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if( operation->alg == PSA_ALG_CCM )
{
if( output_size < input_length )
return( PSA_ERROR_BUFFER_TOO_SMALL );
status = mbedtls_to_psa_error(
mbedtls_ccm_update( &operation->ctx.ccm,
mbedtls_gcm_update(&operation->ctx.gcm,
input, input_length,
output, output_size,
&update_output_length ) );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
{
if( output_size < input_length )
return( PSA_ERROR_BUFFER_TOO_SMALL );
&update_output_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if (operation->alg == PSA_ALG_CCM) {
if (output_size < input_length) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
status = mbedtls_to_psa_error(
mbedtls_chachapoly_update( &operation->ctx.chachapoly,
mbedtls_ccm_update(&operation->ctx.ccm,
input, input_length,
output, output_size,
&update_output_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
if (operation->alg == PSA_ALG_CHACHA20_POLY1305) {
if (output_size < input_length) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
status = mbedtls_to_psa_error(
mbedtls_chachapoly_update(&operation->ctx.chachapoly,
input_length,
input,
output ) );
}
else
output));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
{
( void ) operation;
( void ) input;
( void ) output;
( void ) output_size;
(void) operation;
(void) input;
(void) output;
(void) output_size;
return ( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
*output_length = update_output_length;
}
return( status );
return status;
}
/* Finish encrypting a message in a multipart AEAD operation. */
@ -585,103 +569,97 @@ psa_status_t mbedtls_psa_aead_finish(
size_t *ciphertext_length,
uint8_t *tag,
size_t tag_size,
size_t *tag_length )
size_t *tag_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t finish_output_size = 0;
if( tag_size < operation->tag_length )
return( PSA_ERROR_BUFFER_TOO_SMALL );
if (tag_size < operation->tag_length) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
if( operation->alg == PSA_ALG_GCM )
{
if (operation->alg == PSA_ALG_GCM) {
status = mbedtls_to_psa_error(
mbedtls_gcm_finish( &operation->ctx.gcm,
ciphertext, ciphertext_size, ciphertext_length,
tag, operation->tag_length ) );
}
else
mbedtls_gcm_finish(&operation->ctx.gcm,
ciphertext, ciphertext_size, ciphertext_length,
tag, operation->tag_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
if( operation->alg == PSA_ALG_CCM )
{
if (operation->alg == PSA_ALG_CCM) {
/* tag must be big enough to store a tag of size passed into set
* lengths. */
if( tag_size < operation->tag_length )
return( PSA_ERROR_BUFFER_TOO_SMALL );
if (tag_size < operation->tag_length) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
status = mbedtls_to_psa_error(
mbedtls_ccm_finish( &operation->ctx.ccm,
tag, operation->tag_length ) );
}
else
mbedtls_ccm_finish(&operation->ctx.ccm,
tag, operation->tag_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
{
if (operation->alg == PSA_ALG_CHACHA20_POLY1305) {
/* Belt and braces. Although the above tag_size check should have
* already done this, if we later start supporting smaller tag sizes
* for chachapoly, then passing a tag buffer smaller than 16 into here
* could cause a buffer overflow, so better safe than sorry. */
if( tag_size < 16 )
return( PSA_ERROR_BUFFER_TOO_SMALL );
if (tag_size < 16) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
status = mbedtls_to_psa_error(
mbedtls_chachapoly_finish( &operation->ctx.chachapoly,
tag ) );
}
else
mbedtls_chachapoly_finish(&operation->ctx.chachapoly,
tag));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
{
( void ) ciphertext;
( void ) ciphertext_size;
( void ) ciphertext_length;
( void ) tag;
( void ) tag_size;
( void ) tag_length;
(void) ciphertext;
(void) ciphertext_size;
(void) ciphertext_length;
(void) tag;
(void) tag_size;
(void) tag_length;
return ( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
if( status == PSA_SUCCESS )
{
if (status == PSA_SUCCESS) {
/* This will be zero for all supported algorithms currently, but left
* here for future support. */
*ciphertext_length = finish_output_size;
*tag_length = operation->tag_length;
}
return ( status );
return status;
}
/* Abort an AEAD operation */
psa_status_t mbedtls_psa_aead_abort(
mbedtls_psa_aead_operation_t *operation )
mbedtls_psa_aead_operation_t *operation)
{
switch( operation->alg )
{
switch (operation->alg) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
case PSA_ALG_CCM:
mbedtls_ccm_free( &operation->ctx.ccm );
mbedtls_ccm_free(&operation->ctx.ccm);
break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
case PSA_ALG_GCM:
mbedtls_gcm_free( &operation->ctx.gcm );
mbedtls_gcm_free(&operation->ctx.gcm);
break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
case PSA_ALG_CHACHA20_POLY1305:
mbedtls_chachapoly_free( &operation->ctx.chachapoly );
mbedtls_chachapoly_free(&operation->ctx.chachapoly);
break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
}
operation->is_encrypt = 0;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
#endif /* MBEDTLS_PSA_CRYPTO_C */

View File

@ -83,7 +83,7 @@ psa_status_t mbedtls_psa_aead_encrypt(
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *plaintext, size_t plaintext_length,
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length );
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length);
/**
* \brief Process an authenticated decryption operation.
@ -146,7 +146,7 @@ psa_status_t mbedtls_psa_aead_decrypt(
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *ciphertext, size_t ciphertext_length,
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length );
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length);
/** Set the key for a multipart authenticated encryption operation.
*
@ -189,7 +189,7 @@ psa_status_t mbedtls_psa_aead_encrypt_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
/** Set the key for a multipart authenticated decryption operation.
*
@ -232,7 +232,7 @@ psa_status_t mbedtls_psa_aead_decrypt_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
/** Set the nonce for an authenticated encryption or decryption operation.
*
@ -265,7 +265,7 @@ psa_status_t mbedtls_psa_aead_decrypt_setup(
psa_status_t mbedtls_psa_aead_set_nonce(
mbedtls_psa_aead_operation_t *operation,
const uint8_t *nonce,
size_t nonce_length );
size_t nonce_length);
/** Declare the lengths of the message and additional data for AEAD.
*
@ -306,7 +306,7 @@ psa_status_t mbedtls_psa_aead_set_nonce(
psa_status_t mbedtls_psa_aead_set_lengths(
mbedtls_psa_aead_operation_t *operation,
size_t ad_length,
size_t plaintext_length );
size_t plaintext_length);
/** Pass additional data to an active AEAD operation.
*
@ -343,7 +343,7 @@ psa_status_t mbedtls_psa_aead_set_lengths(
psa_status_t mbedtls_psa_aead_update_ad(
mbedtls_psa_aead_operation_t *operation,
const uint8_t *input,
size_t input_length );
size_t input_length);
/** Encrypt or decrypt a message fragment in an active AEAD operation.
*
@ -406,7 +406,7 @@ psa_status_t mbedtls_psa_aead_update(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
/** Finish encrypting a message in an AEAD operation.
*
@ -479,7 +479,7 @@ psa_status_t mbedtls_psa_aead_finish(
size_t *ciphertext_length,
uint8_t *tag,
size_t tag_size,
size_t *tag_length );
size_t *tag_length);
/** Abort an AEAD operation.
*
@ -506,6 +506,6 @@ psa_status_t mbedtls_psa_aead_finish(
* Success.
*/
psa_status_t mbedtls_psa_aead_abort(
mbedtls_psa_aead_operation_t *operation );
mbedtls_psa_aead_operation_t *operation);
#endif /* PSA_CRYPTO_AEAD_H */

View File

@ -35,18 +35,17 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
psa_algorithm_t alg,
psa_key_type_t key_type,
size_t key_bits,
mbedtls_cipher_id_t* cipher_id )
mbedtls_cipher_id_t *cipher_id)
{
mbedtls_cipher_mode_t mode;
mbedtls_cipher_id_t cipher_id_tmp;
if( PSA_ALG_IS_AEAD( alg ) )
alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 );
if (PSA_ALG_IS_AEAD(alg)) {
alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg, 0);
}
if( PSA_ALG_IS_CIPHER( alg ) || PSA_ALG_IS_AEAD( alg ) )
{
switch( alg )
{
if (PSA_ALG_IS_CIPHER(alg) || PSA_ALG_IS_AEAD(alg)) {
switch (alg) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER)
case PSA_ALG_STREAM_CIPHER:
mode = MBEDTLS_MODE_STREAM;
@ -88,31 +87,30 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, 0 ):
case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 0):
mode = MBEDTLS_MODE_CCM;
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, 0 ):
case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0):
mode = MBEDTLS_MODE_GCM;
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CHACHA20_POLY1305, 0 ):
case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CHACHA20_POLY1305, 0):
mode = MBEDTLS_MODE_CHACHAPOLY;
break;
#endif
default:
return( NULL );
return NULL;
}
}
else if( alg == PSA_ALG_CMAC )
} else if (alg == PSA_ALG_CMAC) {
mode = MBEDTLS_MODE_ECB;
else
return( NULL );
} else {
return NULL;
}
switch( key_type )
{
switch (key_type) {
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_AES)
case PSA_KEY_TYPE_AES:
cipher_id_tmp = MBEDTLS_CIPHER_ID_AES;
@ -127,15 +125,17 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
case PSA_KEY_TYPE_DES:
/* key_bits is 64 for Single-DES, 128 for two-key Triple-DES,
* and 192 for three-key Triple-DES. */
if( key_bits == 64 )
if (key_bits == 64) {
cipher_id_tmp = MBEDTLS_CIPHER_ID_DES;
else
} else {
cipher_id_tmp = MBEDTLS_CIPHER_ID_3DES;
}
/* mbedtls doesn't recognize two-key Triple-DES as an algorithm,
* but two-key Triple-DES is functionally three-key Triple-DES
* with K1=K3, so that's how we present it to mbedtls. */
if( key_bits == 128 )
if (key_bits == 128) {
key_bits = 192;
}
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_CAMELLIA)
@ -149,13 +149,14 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
break;
#endif
default:
return( NULL );
return NULL;
}
if( cipher_id != NULL )
if (cipher_id != NULL) {
*cipher_id = cipher_id_tmp;
}
return( mbedtls_cipher_info_from_values( cipher_id_tmp,
(int) key_bits, mode ) );
return mbedtls_cipher_info_from_values(cipher_id_tmp,
(int) key_bits, mode);
}
#if defined(MBEDTLS_PSA_BUILTIN_CIPHER)
@ -165,110 +166,112 @@ static psa_status_t psa_cipher_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg,
mbedtls_operation_t cipher_operation )
mbedtls_operation_t cipher_operation)
{
int ret = 0;
size_t key_bits;
const mbedtls_cipher_info_t *cipher_info = NULL;
psa_key_type_t key_type = attributes->core.type;
(void)key_buffer_size;
(void) key_buffer_size;
mbedtls_cipher_init( &operation->ctx.cipher );
mbedtls_cipher_init(&operation->ctx.cipher);
operation->alg = alg;
key_bits = attributes->core.bits;
cipher_info = mbedtls_cipher_info_from_psa( alg, key_type,
key_bits, NULL );
if( cipher_info == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
cipher_info = mbedtls_cipher_info_from_psa(alg, key_type,
key_bits, NULL);
if (cipher_info == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
ret = mbedtls_cipher_setup( &operation->ctx.cipher, cipher_info );
if( ret != 0 )
ret = mbedtls_cipher_setup(&operation->ctx.cipher, cipher_info);
if (ret != 0) {
goto exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
if( key_type == PSA_KEY_TYPE_DES && key_bits == 128 )
{
if (key_type == PSA_KEY_TYPE_DES && key_bits == 128) {
/* Two-key Triple-DES is 3-key Triple-DES with K1=K3 */
uint8_t keys[24];
memcpy( keys, key_buffer, 16 );
memcpy( keys + 16, key_buffer, 8 );
ret = mbedtls_cipher_setkey( &operation->ctx.cipher,
keys,
192, cipher_operation );
}
else
memcpy(keys, key_buffer, 16);
memcpy(keys + 16, key_buffer, 8);
ret = mbedtls_cipher_setkey(&operation->ctx.cipher,
keys,
192, cipher_operation);
} else
#endif
{
ret = mbedtls_cipher_setkey( &operation->ctx.cipher, key_buffer,
(int) key_bits, cipher_operation );
ret = mbedtls_cipher_setkey(&operation->ctx.cipher, key_buffer,
(int) key_bits, cipher_operation);
}
if( ret != 0 )
if (ret != 0) {
goto exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7)
switch( alg )
{
switch (alg) {
case PSA_ALG_CBC_NO_PADDING:
ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
MBEDTLS_PADDING_NONE );
ret = mbedtls_cipher_set_padding_mode(&operation->ctx.cipher,
MBEDTLS_PADDING_NONE);
break;
case PSA_ALG_CBC_PKCS7:
ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
MBEDTLS_PADDING_PKCS7 );
ret = mbedtls_cipher_set_padding_mode(&operation->ctx.cipher,
MBEDTLS_PADDING_PKCS7);
break;
default:
/* The algorithm doesn't involve padding. */
ret = 0;
break;
}
if( ret != 0 )
if (ret != 0) {
goto exit;
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING ||
MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7 */
operation->block_length = ( PSA_ALG_IS_STREAM_CIPHER( alg ) ? 1 :
PSA_BLOCK_CIPHER_BLOCK_LENGTH( key_type ) );
operation->iv_length = PSA_CIPHER_IV_LENGTH( key_type, alg );
operation->block_length = (PSA_ALG_IS_STREAM_CIPHER(alg) ? 1 :
PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type));
operation->iv_length = PSA_CIPHER_IV_LENGTH(key_type, alg);
exit:
return( mbedtls_to_psa_error( ret ) );
return mbedtls_to_psa_error(ret);
}
psa_status_t mbedtls_psa_cipher_encrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
return( psa_cipher_setup( operation, attributes,
key_buffer, key_buffer_size,
alg, MBEDTLS_ENCRYPT ) );
return psa_cipher_setup(operation, attributes,
key_buffer, key_buffer_size,
alg, MBEDTLS_ENCRYPT);
}
psa_status_t mbedtls_psa_cipher_decrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
return( psa_cipher_setup( operation, attributes,
key_buffer, key_buffer_size,
alg, MBEDTLS_DECRYPT ) );
return psa_cipher_setup(operation, attributes,
key_buffer, key_buffer_size,
alg, MBEDTLS_DECRYPT);
}
psa_status_t mbedtls_psa_cipher_set_iv(
mbedtls_psa_cipher_operation_t *operation,
const uint8_t *iv, size_t iv_length )
const uint8_t *iv, size_t iv_length)
{
if( iv_length != operation->iv_length )
return( PSA_ERROR_INVALID_ARGUMENT );
if (iv_length != operation->iv_length) {
return PSA_ERROR_INVALID_ARGUMENT;
}
return( mbedtls_to_psa_error(
mbedtls_cipher_set_iv( &operation->ctx.cipher,
iv, iv_length ) ) );
return mbedtls_to_psa_error(
mbedtls_cipher_set_iv(&operation->ctx.cipher,
iv, iv_length));
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING)
@ -300,43 +303,42 @@ static psa_status_t psa_cipher_update_ecb(
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t *output_length )
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t block_size = ctx->cipher_info->block_size;
size_t internal_output_length = 0;
*output_length = 0;
if( input_length == 0 )
{
if (input_length == 0) {
status = PSA_SUCCESS;
goto exit;
}
if( ctx->unprocessed_len > 0 )
{
if (ctx->unprocessed_len > 0) {
/* Fill up to block size, and run the block if there's a full one. */
size_t bytes_to_copy = block_size - ctx->unprocessed_len;
if( input_length < bytes_to_copy )
if (input_length < bytes_to_copy) {
bytes_to_copy = input_length;
}
memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ),
input, bytes_to_copy );
memcpy(&(ctx->unprocessed_data[ctx->unprocessed_len]),
input, bytes_to_copy);
input_length -= bytes_to_copy;
input += bytes_to_copy;
ctx->unprocessed_len += bytes_to_copy;
if( ctx->unprocessed_len == block_size )
{
if (ctx->unprocessed_len == block_size) {
status = mbedtls_to_psa_error(
mbedtls_cipher_update( ctx,
ctx->unprocessed_data,
block_size,
output, &internal_output_length ) );
mbedtls_cipher_update(ctx,
ctx->unprocessed_data,
block_size,
output, &internal_output_length));
if( status != PSA_SUCCESS )
if (status != PSA_SUCCESS) {
goto exit;
}
output += internal_output_length;
*output_length += internal_output_length;
@ -344,16 +346,16 @@ static psa_status_t psa_cipher_update_ecb(
}
}
while( input_length >= block_size )
{
while (input_length >= block_size) {
/* Run all full blocks we have, one by one */
status = mbedtls_to_psa_error(
mbedtls_cipher_update( ctx, input,
block_size,
output, &internal_output_length ) );
mbedtls_cipher_update(ctx, input,
block_size,
output, &internal_output_length));
if( status != PSA_SUCCESS )
if (status != PSA_SUCCESS) {
goto exit;
}
input_length -= block_size;
input += block_size;
@ -362,122 +364,119 @@ static psa_status_t psa_cipher_update_ecb(
*output_length += internal_output_length;
}
if( input_length > 0 )
{
if (input_length > 0) {
/* Save unprocessed bytes for later processing */
memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ),
input, input_length );
memcpy(&(ctx->unprocessed_data[ctx->unprocessed_len]),
input, input_length);
ctx->unprocessed_len += input_length;
}
status = PSA_SUCCESS;
exit:
return( status );
return status;
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING */
psa_status_t mbedtls_psa_cipher_update(
mbedtls_psa_cipher_operation_t *operation,
const uint8_t *input, size_t input_length,
uint8_t *output, size_t output_size, size_t *output_length )
uint8_t *output, size_t output_size, size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t expected_output_size;
if( ! PSA_ALG_IS_STREAM_CIPHER( operation->alg ) )
{
if (!PSA_ALG_IS_STREAM_CIPHER(operation->alg)) {
/* Take the unprocessed partial block left over from previous
* update calls, if any, plus the input to this call. Remove
* the last partial block, if any. You get the data that will be
* output in this call. */
expected_output_size =
( operation->ctx.cipher.unprocessed_len + input_length )
(operation->ctx.cipher.unprocessed_len + input_length)
/ operation->block_length * operation->block_length;
}
else
{
} else {
expected_output_size = input_length;
}
if( output_size < expected_output_size )
return( PSA_ERROR_BUFFER_TOO_SMALL );
if (output_size < expected_output_size) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING)
if( operation->alg == PSA_ALG_ECB_NO_PADDING )
{
if (operation->alg == PSA_ALG_ECB_NO_PADDING) {
/* mbedtls_cipher_update has an API inconsistency: it will only
* process a single block at a time in ECB mode. Abstract away that
* inconsistency here to match the PSA API behaviour. */
status = psa_cipher_update_ecb( &operation->ctx.cipher,
input,
input_length,
output,
output_length );
}
else
* process a single block at a time in ECB mode. Abstract away that
* inconsistency here to match the PSA API behaviour. */
status = psa_cipher_update_ecb(&operation->ctx.cipher,
input,
input_length,
output,
output_length);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING */
{
status = mbedtls_to_psa_error(
mbedtls_cipher_update( &operation->ctx.cipher, input,
input_length, output, output_length ) );
mbedtls_cipher_update(&operation->ctx.cipher, input,
input_length, output, output_length));
if( *output_length > output_size )
return( PSA_ERROR_CORRUPTION_DETECTED );
if (*output_length > output_size) {
return PSA_ERROR_CORRUPTION_DETECTED;
}
}
return( status );
return status;
}
psa_status_t mbedtls_psa_cipher_finish(
mbedtls_psa_cipher_operation_t *operation,
uint8_t *output, size_t output_size, size_t *output_length )
uint8_t *output, size_t output_size, size_t *output_length)
{
psa_status_t status = PSA_ERROR_GENERIC_ERROR;
uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH];
if( operation->ctx.cipher.unprocessed_len != 0 )
{
if( operation->alg == PSA_ALG_ECB_NO_PADDING ||
operation->alg == PSA_ALG_CBC_NO_PADDING )
{
if (operation->ctx.cipher.unprocessed_len != 0) {
if (operation->alg == PSA_ALG_ECB_NO_PADDING ||
operation->alg == PSA_ALG_CBC_NO_PADDING) {
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
}
status = mbedtls_to_psa_error(
mbedtls_cipher_finish( &operation->ctx.cipher,
temp_output_buffer,
output_length ) );
if( status != PSA_SUCCESS )
mbedtls_cipher_finish(&operation->ctx.cipher,
temp_output_buffer,
output_length));
if (status != PSA_SUCCESS) {
goto exit;
}
if( *output_length == 0 )
if (*output_length == 0) {
; /* Nothing to copy. Note that output may be NULL in this case. */
else if( output_size >= *output_length )
memcpy( output, temp_output_buffer, *output_length );
else
} else if (output_size >= *output_length) {
memcpy(output, temp_output_buffer, *output_length);
} else {
status = PSA_ERROR_BUFFER_TOO_SMALL;
}
exit:
mbedtls_platform_zeroize( temp_output_buffer,
sizeof( temp_output_buffer ) );
mbedtls_platform_zeroize(temp_output_buffer,
sizeof(temp_output_buffer));
return( status );
return status;
}
psa_status_t mbedtls_psa_cipher_abort(
mbedtls_psa_cipher_operation_t *operation )
mbedtls_psa_cipher_operation_t *operation)
{
/* Sanity check (shouldn't happen: operation->alg should
* always have been initialized to a valid value). */
if( ! PSA_ALG_IS_CIPHER( operation->alg ) )
return( PSA_ERROR_BAD_STATE );
if (!PSA_ALG_IS_CIPHER(operation->alg)) {
return PSA_ERROR_BAD_STATE;
}
mbedtls_cipher_free( &operation->ctx.cipher );
mbedtls_cipher_free(&operation->ctx.cipher);
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_cipher_encrypt(
@ -491,47 +490,51 @@ psa_status_t mbedtls_psa_cipher_encrypt(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_cipher_operation_t operation = MBEDTLS_PSA_CIPHER_OPERATION_INIT;
size_t update_output_length, finish_output_length;
status = mbedtls_psa_cipher_encrypt_setup( &operation, attributes,
key_buffer, key_buffer_size,
alg );
if( status != PSA_SUCCESS )
status = mbedtls_psa_cipher_encrypt_setup(&operation, attributes,
key_buffer, key_buffer_size,
alg);
if (status != PSA_SUCCESS) {
goto exit;
if( iv_length > 0 )
{
status = mbedtls_psa_cipher_set_iv( &operation, iv, iv_length );
if( status != PSA_SUCCESS )
goto exit;
}
status = mbedtls_psa_cipher_update( &operation, input, input_length,
output, output_size,
&update_output_length );
if( status != PSA_SUCCESS )
if (iv_length > 0) {
status = mbedtls_psa_cipher_set_iv(&operation, iv, iv_length);
if (status != PSA_SUCCESS) {
goto exit;
}
}
status = mbedtls_psa_cipher_update(&operation, input, input_length,
output, output_size,
&update_output_length);
if (status != PSA_SUCCESS) {
goto exit;
}
status = mbedtls_psa_cipher_finish(
&operation,
mbedtls_buffer_offset( output, update_output_length ),
output_size - update_output_length, &finish_output_length );
if( status != PSA_SUCCESS )
mbedtls_buffer_offset(output, update_output_length),
output_size - update_output_length, &finish_output_length);
if (status != PSA_SUCCESS) {
goto exit;
}
*output_length = update_output_length + finish_output_length;
exit:
if( status == PSA_SUCCESS )
status = mbedtls_psa_cipher_abort( &operation );
else
mbedtls_psa_cipher_abort( &operation );
if (status == PSA_SUCCESS) {
status = mbedtls_psa_cipher_abort(&operation);
} else {
mbedtls_psa_cipher_abort(&operation);
}
return( status );
return status;
}
psa_status_t mbedtls_psa_cipher_decrypt(
@ -543,52 +546,56 @@ psa_status_t mbedtls_psa_cipher_decrypt(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_cipher_operation_t operation = MBEDTLS_PSA_CIPHER_OPERATION_INIT;
size_t olength, accumulated_length;
status = mbedtls_psa_cipher_decrypt_setup( &operation, attributes,
key_buffer, key_buffer_size,
alg );
if( status != PSA_SUCCESS )
status = mbedtls_psa_cipher_decrypt_setup(&operation, attributes,
key_buffer, key_buffer_size,
alg);
if (status != PSA_SUCCESS) {
goto exit;
}
if( operation.iv_length > 0 )
{
status = mbedtls_psa_cipher_set_iv( &operation,
input, operation.iv_length );
if( status != PSA_SUCCESS )
if (operation.iv_length > 0) {
status = mbedtls_psa_cipher_set_iv(&operation,
input, operation.iv_length);
if (status != PSA_SUCCESS) {
goto exit;
}
}
status = mbedtls_psa_cipher_update(
&operation,
mbedtls_buffer_offset_const( input, operation.iv_length ),
mbedtls_buffer_offset_const(input, operation.iv_length),
input_length - operation.iv_length,
output, output_size, &olength );
if( status != PSA_SUCCESS )
output, output_size, &olength);
if (status != PSA_SUCCESS) {
goto exit;
}
accumulated_length = olength;
status = mbedtls_psa_cipher_finish(
&operation,
mbedtls_buffer_offset( output, accumulated_length ),
output_size - accumulated_length, &olength );
if( status != PSA_SUCCESS )
mbedtls_buffer_offset(output, accumulated_length),
output_size - accumulated_length, &olength);
if (status != PSA_SUCCESS) {
goto exit;
}
*output_length = accumulated_length + olength;
exit:
if ( status == PSA_SUCCESS )
status = mbedtls_psa_cipher_abort( &operation );
else
mbedtls_psa_cipher_abort( &operation );
if (status == PSA_SUCCESS) {
status = mbedtls_psa_cipher_abort(&operation);
} else {
mbedtls_psa_cipher_abort(&operation);
}
return( status );
return status;
}
#endif /* MBEDTLS_PSA_BUILTIN_CIPHER */

View File

@ -38,7 +38,7 @@
*/
const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
psa_algorithm_t alg, psa_key_type_t key_type, size_t key_bits,
mbedtls_cipher_id_t *cipher_id );
mbedtls_cipher_id_t *cipher_id);
/**
* \brief Set the key for a multipart symmetric encryption operation.
@ -68,7 +68,7 @@ psa_status_t mbedtls_psa_cipher_encrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
/**
* \brief Set the key for a multipart symmetric decryption operation.
@ -98,7 +98,7 @@ psa_status_t mbedtls_psa_cipher_decrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
/** Set the IV for a symmetric encryption or decryption operation.
*
@ -124,7 +124,7 @@ psa_status_t mbedtls_psa_cipher_decrypt_setup(
*/
psa_status_t mbedtls_psa_cipher_set_iv(
mbedtls_psa_cipher_operation_t *operation,
const uint8_t *iv, size_t iv_length );
const uint8_t *iv, size_t iv_length);
/** Encrypt or decrypt a message fragment in an active cipher operation.
*
@ -150,7 +150,7 @@ psa_status_t mbedtls_psa_cipher_set_iv(
psa_status_t mbedtls_psa_cipher_update(
mbedtls_psa_cipher_operation_t *operation,
const uint8_t *input, size_t input_length,
uint8_t *output, size_t output_size, size_t *output_length );
uint8_t *output, size_t output_size, size_t *output_length);
/** Finish encrypting or decrypting a message in a cipher operation.
*
@ -180,7 +180,7 @@ psa_status_t mbedtls_psa_cipher_update(
*/
psa_status_t mbedtls_psa_cipher_finish(
mbedtls_psa_cipher_operation_t *operation,
uint8_t *output, size_t output_size, size_t *output_length );
uint8_t *output, size_t output_size, size_t *output_length);
/** Abort a cipher operation.
*
@ -197,7 +197,7 @@ psa_status_t mbedtls_psa_cipher_finish(
*
* \retval #PSA_SUCCESS
*/
psa_status_t mbedtls_psa_cipher_abort( mbedtls_psa_cipher_operation_t *operation );
psa_status_t mbedtls_psa_cipher_abort(mbedtls_psa_cipher_operation_t *operation);
/** Encrypt a message using a symmetric cipher.
*
@ -241,17 +241,17 @@ psa_status_t mbedtls_psa_cipher_abort( mbedtls_psa_cipher_operation_t *operation
* This is a decryption operation for an algorithm that includes
* padding, and the ciphertext does not contain valid padding.
*/
psa_status_t mbedtls_psa_cipher_encrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *iv,
size_t iv_length,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t mbedtls_psa_cipher_encrypt(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *iv,
size_t iv_length,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length);
/** Decrypt a message using a symmetric cipher.
*
@ -292,14 +292,14 @@ psa_status_t mbedtls_psa_cipher_encrypt( const psa_key_attributes_t *attributes,
* This is a decryption operation for an algorithm that includes
* padding, and the ciphertext does not contain valid padding.
*/
psa_status_t mbedtls_psa_cipher_decrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t mbedtls_psa_cipher_decrypt(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length);
#endif /* PSA_CRYPTO_CIPHER_H */

View File

@ -26,32 +26,31 @@
#include <string.h>
#include "mbedtls/platform.h"
void psa_reset_key_attributes( psa_key_attributes_t *attributes )
void psa_reset_key_attributes(psa_key_attributes_t *attributes)
{
mbedtls_free( attributes->domain_parameters );
memset( attributes, 0, sizeof( *attributes ) );
mbedtls_free(attributes->domain_parameters);
memset(attributes, 0, sizeof(*attributes));
}
psa_status_t psa_set_key_domain_parameters( psa_key_attributes_t *attributes,
psa_key_type_t type,
const uint8_t *data,
size_t data_length )
psa_status_t psa_set_key_domain_parameters(psa_key_attributes_t *attributes,
psa_key_type_t type,
const uint8_t *data,
size_t data_length)
{
uint8_t *copy = NULL;
if( data_length != 0 )
{
copy = mbedtls_calloc( 1, data_length );
if( copy == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
memcpy( copy, data, data_length );
if (data_length != 0) {
copy = mbedtls_calloc(1, data_length);
if (copy == NULL) {
return PSA_ERROR_INSUFFICIENT_MEMORY;
}
memcpy(copy, data, data_length);
}
/* After this point, this function is guaranteed to succeed, so it
* can start modifying `*attributes`. */
if( attributes->domain_parameters != NULL )
{
mbedtls_free( attributes->domain_parameters );
if (attributes->domain_parameters != NULL) {
mbedtls_free(attributes->domain_parameters);
attributes->domain_parameters = NULL;
attributes->domain_parameters_size = 0;
}
@ -59,20 +58,22 @@ psa_status_t psa_set_key_domain_parameters( psa_key_attributes_t *attributes,
attributes->domain_parameters = copy;
attributes->domain_parameters_size = data_length;
attributes->core.type = type;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t psa_get_key_domain_parameters(
const psa_key_attributes_t *attributes,
uint8_t *data, size_t data_size, size_t *data_length )
uint8_t *data, size_t data_size, size_t *data_length)
{
if( attributes->domain_parameters_size > data_size )
return( PSA_ERROR_BUFFER_TOO_SMALL );
if (attributes->domain_parameters_size > data_size) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
*data_length = attributes->domain_parameters_size;
if( attributes->domain_parameters_size != 0 )
memcpy( data, attributes->domain_parameters,
attributes->domain_parameters_size );
return( PSA_SUCCESS );
if (attributes->domain_parameters_size != 0) {
memcpy(data, attributes->domain_parameters,
attributes->domain_parameters_size);
}
return PSA_SUCCESS;
}
#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */

View File

@ -35,22 +35,22 @@
* \return 0 if the buffer contents are equal, non-zero otherwise
*/
static inline int mbedtls_psa_safer_memcmp(
const uint8_t *a, const uint8_t *b, size_t n )
const uint8_t *a, const uint8_t *b, size_t n)
{
size_t i;
unsigned char diff = 0;
for( i = 0; i < n; i++ )
for (i = 0; i < n; i++) {
diff |= a[i] ^ b[i];
}
return( diff );
return diff;
}
/** The data structure representing a key slot, containing key material
* and metadata for one key.
*/
typedef struct
{
typedef struct {
psa_core_key_attributes_t attr;
/*
@ -80,8 +80,7 @@ typedef struct
/* Dynamically allocated key data buffer.
* Format as specified in psa_export_key(). */
struct key_data
{
struct key_data {
uint8_t *data;
size_t bytes;
} key;
@ -90,7 +89,7 @@ typedef struct
/* A mask of key attribute flags used only internally.
* Currently there aren't any. */
#define PSA_KA_MASK_INTERNAL_ONLY ( \
0 )
0)
/** Test whether a key slot is occupied.
*
@ -101,9 +100,9 @@ typedef struct
*
* \return 1 if the slot is occupied, 0 otherwise.
*/
static inline int psa_is_key_slot_occupied( const psa_key_slot_t *slot )
static inline int psa_is_key_slot_occupied(const psa_key_slot_t *slot)
{
return( slot->attr.type != 0 );
return slot->attr.type != 0;
}
/** Test whether a key slot is locked.
@ -114,9 +113,9 @@ static inline int psa_is_key_slot_occupied( const psa_key_slot_t *slot )
*
* \return 1 if the slot is locked, 0 otherwise.
*/
static inline int psa_is_key_slot_locked( const psa_key_slot_t *slot )
static inline int psa_is_key_slot_locked(const psa_key_slot_t *slot)
{
return( slot->lock_count > 0 );
return slot->lock_count > 0;
}
/** Retrieve flags from psa_key_slot_t::attr::core::flags.
@ -127,10 +126,10 @@ static inline int psa_is_key_slot_locked( const psa_key_slot_t *slot )
* \return The key attribute flags in the given slot,
* bitwise-anded with \p mask.
*/
static inline uint16_t psa_key_slot_get_flags( const psa_key_slot_t *slot,
uint16_t mask )
static inline uint16_t psa_key_slot_get_flags(const psa_key_slot_t *slot,
uint16_t mask)
{
return( slot->attr.flags & mask );
return slot->attr.flags & mask;
}
/** Set flags in psa_key_slot_t::attr::core::flags.
@ -139,12 +138,12 @@ static inline uint16_t psa_key_slot_get_flags( const psa_key_slot_t *slot,
* \param mask The mask of bits to modify.
* \param value The new value of the selected bits.
*/
static inline void psa_key_slot_set_flags( psa_key_slot_t *slot,
uint16_t mask,
uint16_t value )
static inline void psa_key_slot_set_flags(psa_key_slot_t *slot,
uint16_t mask,
uint16_t value)
{
slot->attr.flags = ( ( ~mask & slot->attr.flags ) |
( mask & value ) );
slot->attr.flags = ((~mask & slot->attr.flags) |
(mask & value));
}
/** Turn on flags in psa_key_slot_t::attr::core::flags.
@ -152,8 +151,8 @@ static inline void psa_key_slot_set_flags( psa_key_slot_t *slot,
* \param[in,out] slot The key slot to modify.
* \param mask The mask of bits to set.
*/
static inline void psa_key_slot_set_bits_in_flags( psa_key_slot_t *slot,
uint16_t mask )
static inline void psa_key_slot_set_bits_in_flags(psa_key_slot_t *slot,
uint16_t mask)
{
slot->attr.flags |= mask;
}
@ -163,8 +162,8 @@ static inline void psa_key_slot_set_bits_in_flags( psa_key_slot_t *slot,
* \param[in,out] slot The key slot to modify.
* \param mask The mask of bits to clear.
*/
static inline void psa_key_slot_clear_bits( psa_key_slot_t *slot,
uint16_t mask )
static inline void psa_key_slot_clear_bits(psa_key_slot_t *slot,
uint16_t mask)
{
slot->attr.flags &= ~mask;
}
@ -177,9 +176,9 @@ static inline void psa_key_slot_clear_bits( psa_key_slot_t *slot,
* secure element, otherwise the behaviour is undefined.
*/
static inline psa_key_slot_number_t psa_key_slot_get_slot_number(
const psa_key_slot_t *slot )
const psa_key_slot_t *slot)
{
return( *( (psa_key_slot_number_t *)( slot->key.data ) ) );
return *((psa_key_slot_number_t *) (slot->key.data));
}
#endif
@ -196,10 +195,10 @@ static inline psa_key_slot_number_t psa_key_slot_get_slot_number(
* On success, the returned key slot is locked. It is the responsibility of
* the caller to unlock the key slot when it does not access it anymore.
*/
psa_status_t psa_get_and_lock_key_slot_with_policy( mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot,
psa_key_usage_t usage,
psa_algorithm_t alg );
psa_status_t psa_get_and_lock_key_slot_with_policy(mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot,
psa_key_usage_t usage,
psa_algorithm_t alg);
/** Completely wipe a slot in memory, including its policy.
*
@ -212,7 +211,7 @@ psa_status_t psa_get_and_lock_key_slot_with_policy( mbedtls_svc_key_id_t key,
* already fully wiped.
* \retval #PSA_ERROR_CORRUPTION_DETECTED
*/
psa_status_t psa_wipe_key_slot( psa_key_slot_t *slot );
psa_status_t psa_wipe_key_slot(psa_key_slot_t *slot);
/** Try to allocate a buffer to an empty key slot.
*
@ -226,11 +225,11 @@ psa_status_t psa_wipe_key_slot( psa_key_slot_t *slot );
* \retval #PSA_ERROR_ALREADY_EXISTS
* Trying to allocate a buffer to a non-empty key slot.
*/
psa_status_t psa_allocate_buffer_to_slot( psa_key_slot_t *slot,
size_t buffer_length );
psa_status_t psa_allocate_buffer_to_slot(psa_key_slot_t *slot,
size_t buffer_length);
/** Wipe key data from a slot. Preserves metadata such as the policy. */
psa_status_t psa_remove_key_data_from_memory( psa_key_slot_t *slot );
psa_status_t psa_remove_key_data_from_memory(psa_key_slot_t *slot);
/** Copy key data (in export format) into an empty key slot.
*
@ -249,9 +248,9 @@ psa_status_t psa_remove_key_data_from_memory( psa_key_slot_t *slot );
* \retval #PSA_ERROR_ALREADY_EXISTS
* There was other key material already present in the slot.
*/
psa_status_t psa_copy_key_material_into_slot( psa_key_slot_t *slot,
const uint8_t *data,
size_t data_length );
psa_status_t psa_copy_key_material_into_slot(psa_key_slot_t *slot,
const uint8_t *data,
size_t data_length);
/** Convert an mbed TLS error code to a PSA error code
*
@ -262,7 +261,7 @@ psa_status_t psa_copy_key_material_into_slot( psa_key_slot_t *slot,
*
* \return The corresponding PSA error code
*/
psa_status_t mbedtls_to_psa_error( int ret );
psa_status_t mbedtls_to_psa_error(int ret);
/** Import a key in binary format.
*
@ -294,7 +293,7 @@ psa_status_t psa_import_key_into_slot(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits );
size_t *key_buffer_length, size_t *bits);
/** Export a key in binary format
*
@ -321,7 +320,7 @@ psa_status_t psa_import_key_into_slot(
psa_status_t psa_export_key_internal(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length );
uint8_t *data, size_t data_size, size_t *data_length);
/** Export a public key or the public part of a key pair in binary format.
*
@ -349,7 +348,7 @@ psa_status_t psa_export_key_internal(
psa_status_t psa_export_public_key_internal(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length );
uint8_t *data, size_t data_size, size_t *data_length);
/**
* \brief Generate a key.
@ -371,10 +370,10 @@ psa_status_t psa_export_public_key_internal(
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* The size of \p key_buffer is too small.
*/
psa_status_t psa_generate_key_internal( const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length );
psa_status_t psa_generate_key_internal(const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length);
/** Sign a message with a private key. For hash-and-sign algorithms,
* this includes the hashing step.
@ -417,7 +416,7 @@ psa_status_t psa_sign_message_builtin(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *input, size_t input_length,
uint8_t *signature, size_t signature_size, size_t *signature_length );
uint8_t *signature, size_t signature_size, size_t *signature_length);
/** Verify the signature of a message with a public key, using
* a hash-and-sign verification algorithm.
@ -454,7 +453,7 @@ psa_status_t psa_verify_message_builtin(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *input, size_t input_length,
const uint8_t *signature, size_t signature_length );
const uint8_t *signature, size_t signature_length);
/** Sign an already-calculated hash with a private key.
*
@ -493,7 +492,7 @@ psa_status_t psa_sign_hash_builtin(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
uint8_t *signature, size_t signature_size, size_t *signature_length );
uint8_t *signature, size_t signature_size, size_t *signature_length);
/**
* \brief Verify the signature a hash or short message using a public key.
@ -528,7 +527,7 @@ psa_status_t psa_verify_hash_builtin(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
const uint8_t *signature, size_t signature_length );
const uint8_t *signature, size_t signature_length);
/**
* \brief Validate the key bit size for unstructured keys.
@ -547,8 +546,8 @@ psa_status_t psa_verify_hash_builtin(
* The type and/or the size in bits of the key or the combination of
* the two is not supported.
*/
psa_status_t psa_validate_unstructured_key_bit_size( psa_key_type_t type,
size_t bits );
psa_status_t psa_validate_unstructured_key_bit_size(psa_key_type_t type,
size_t bits);
/** Perform a key agreement and return the raw shared secret, using
built-in raw key agreement functions.
@ -605,6 +604,6 @@ psa_status_t psa_key_agreement_raw_builtin(
size_t peer_key_length,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length );
size_t *shared_secret_length);
#endif /* PSA_CRYPTO_CORE_H */

View File

@ -27,8 +27,8 @@
/*
* Initialization and termination functions
*/
psa_status_t psa_driver_wrapper_init( void );
void psa_driver_wrapper_free( void );
psa_status_t psa_driver_wrapper_init(void);
void psa_driver_wrapper_free(void);
/*
* Signature functions
@ -42,7 +42,7 @@ psa_status_t psa_driver_wrapper_sign_message(
size_t input_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length );
size_t *signature_length);
psa_status_t psa_driver_wrapper_verify_message(
const psa_key_attributes_t *attributes,
@ -52,19 +52,19 @@ psa_status_t psa_driver_wrapper_verify_message(
const uint8_t *input,
size_t input_length,
const uint8_t *signature,
size_t signature_length );
size_t signature_length);
psa_status_t psa_driver_wrapper_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
uint8_t *signature, size_t signature_size, size_t *signature_length );
uint8_t *signature, size_t signature_size, size_t *signature_length);
psa_status_t psa_driver_wrapper_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
const uint8_t *signature, size_t signature_length );
const uint8_t *signature, size_t signature_length);
/*
* Key handling functions
@ -74,42 +74,42 @@ psa_status_t psa_driver_wrapper_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits );
size_t *key_buffer_length, size_t *bits);
psa_status_t psa_driver_wrapper_export_key(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length );
uint8_t *data, size_t data_size, size_t *data_length);
psa_status_t psa_driver_wrapper_export_public_key(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length );
uint8_t *data, size_t data_size, size_t *data_length);
psa_status_t psa_driver_wrapper_get_key_buffer_size(
const psa_key_attributes_t *attributes,
size_t *key_buffer_size );
size_t *key_buffer_size);
psa_status_t psa_driver_wrapper_get_key_buffer_size_from_key_data(
const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
size_t *key_buffer_size );
size_t *key_buffer_size);
psa_status_t psa_driver_wrapper_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length );
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length);
psa_status_t psa_driver_wrapper_get_builtin_key(
psa_drv_slot_number_t slot_number,
psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length );
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length);
psa_status_t psa_driver_wrapper_copy_key(
psa_key_attributes_t *attributes,
const uint8_t *source_key, size_t source_key_length,
uint8_t *target_key_buffer, size_t target_key_buffer_size,
size_t *target_key_buffer_length );
size_t *target_key_buffer_length);
/*
* Cipher functions
*/
@ -124,7 +124,7 @@ psa_status_t psa_driver_wrapper_cipher_encrypt(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
psa_status_t psa_driver_wrapper_cipher_decrypt(
const psa_key_attributes_t *attributes,
@ -135,24 +135,24 @@ psa_status_t psa_driver_wrapper_cipher_decrypt(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
psa_status_t psa_driver_wrapper_cipher_encrypt_setup(
psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
psa_status_t psa_driver_wrapper_cipher_decrypt_setup(
psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
psa_status_t psa_driver_wrapper_cipher_set_iv(
psa_cipher_operation_t *operation,
const uint8_t *iv,
size_t iv_length );
size_t iv_length);
psa_status_t psa_driver_wrapper_cipher_update(
psa_cipher_operation_t *operation,
@ -160,16 +160,16 @@ psa_status_t psa_driver_wrapper_cipher_update(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
psa_status_t psa_driver_wrapper_cipher_finish(
psa_cipher_operation_t *operation,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
psa_status_t psa_driver_wrapper_cipher_abort(
psa_cipher_operation_t *operation );
psa_cipher_operation_t *operation);
/*
* Hashing functions
@ -184,25 +184,25 @@ psa_status_t psa_driver_wrapper_hash_compute(
psa_status_t psa_driver_wrapper_hash_setup(
psa_hash_operation_t *operation,
psa_algorithm_t alg );
psa_algorithm_t alg);
psa_status_t psa_driver_wrapper_hash_clone(
const psa_hash_operation_t *source_operation,
psa_hash_operation_t *target_operation );
psa_hash_operation_t *target_operation);
psa_status_t psa_driver_wrapper_hash_update(
psa_hash_operation_t *operation,
const uint8_t *input,
size_t input_length );
size_t input_length);
psa_status_t psa_driver_wrapper_hash_finish(
psa_hash_operation_t *operation,
uint8_t *hash,
size_t hash_size,
size_t *hash_length );
size_t *hash_length);
psa_status_t psa_driver_wrapper_hash_abort(
psa_hash_operation_t *operation );
psa_hash_operation_t *operation);
/*
* AEAD functions
@ -215,7 +215,7 @@ psa_status_t psa_driver_wrapper_aead_encrypt(
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *plaintext, size_t plaintext_length,
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length );
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length);
psa_status_t psa_driver_wrapper_aead_decrypt(
const psa_key_attributes_t *attributes,
@ -224,34 +224,34 @@ psa_status_t psa_driver_wrapper_aead_decrypt(
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *ciphertext, size_t ciphertext_length,
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length );
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length);
psa_status_t psa_driver_wrapper_aead_encrypt_setup(
psa_aead_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
psa_status_t psa_driver_wrapper_aead_decrypt_setup(
psa_aead_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
psa_status_t psa_driver_wrapper_aead_set_nonce(
psa_aead_operation_t *operation,
const uint8_t *nonce,
size_t nonce_length );
size_t nonce_length);
psa_status_t psa_driver_wrapper_aead_set_lengths(
psa_aead_operation_t *operation,
size_t ad_length,
size_t plaintext_length );
size_t plaintext_length);
psa_status_t psa_driver_wrapper_aead_update_ad(
psa_aead_operation_t *operation,
const uint8_t *input,
size_t input_length );
size_t input_length);
psa_status_t psa_driver_wrapper_aead_update(
psa_aead_operation_t *operation,
@ -259,7 +259,7 @@ psa_status_t psa_driver_wrapper_aead_update(
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
psa_status_t psa_driver_wrapper_aead_finish(
psa_aead_operation_t *operation,
@ -268,7 +268,7 @@ psa_status_t psa_driver_wrapper_aead_finish(
size_t *ciphertext_length,
uint8_t *tag,
size_t tag_size,
size_t *tag_length );
size_t *tag_length);
psa_status_t psa_driver_wrapper_aead_verify(
psa_aead_operation_t *operation,
@ -276,10 +276,10 @@ psa_status_t psa_driver_wrapper_aead_verify(
size_t plaintext_size,
size_t *plaintext_length,
const uint8_t *tag,
size_t tag_length );
size_t tag_length);
psa_status_t psa_driver_wrapper_aead_abort(
psa_aead_operation_t *operation );
psa_aead_operation_t *operation);
/*
* MAC functions
@ -293,40 +293,40 @@ psa_status_t psa_driver_wrapper_mac_compute(
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length );
size_t *mac_length);
psa_status_t psa_driver_wrapper_mac_sign_setup(
psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
psa_status_t psa_driver_wrapper_mac_verify_setup(
psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg );
psa_algorithm_t alg);
psa_status_t psa_driver_wrapper_mac_update(
psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length );
size_t input_length);
psa_status_t psa_driver_wrapper_mac_sign_finish(
psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length );
size_t *mac_length);
psa_status_t psa_driver_wrapper_mac_verify_finish(
psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length );
size_t mac_length);
psa_status_t psa_driver_wrapper_mac_abort(
psa_mac_operation_t *operation );
psa_mac_operation_t *operation);
/*
* Asymmetric cryptography
@ -342,7 +342,7 @@ psa_status_t psa_driver_wrapper_asymmetric_encrypt(
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
psa_status_t psa_driver_wrapper_asymmetric_decrypt(
const psa_key_attributes_t *attributes,
@ -355,7 +355,7 @@ psa_status_t psa_driver_wrapper_asymmetric_decrypt(
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
size_t *output_length);
/*
* Raw Key Agreement
@ -369,7 +369,7 @@ psa_status_t psa_driver_wrapper_key_agreement(
size_t peer_key_length,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length );
size_t *shared_secret_length);
#endif /* PSA_CRYPTO_DRIVER_WRAPPERS_H */

View File

@ -45,25 +45,25 @@
psa_status_t mbedtls_psa_ecp_load_representation(
psa_key_type_t type, size_t curve_bits,
const uint8_t *data, size_t data_length,
mbedtls_ecp_keypair **p_ecp )
mbedtls_ecp_keypair **p_ecp)
{
mbedtls_ecp_group_id grp_id = MBEDTLS_ECP_DP_NONE;
psa_status_t status;
mbedtls_ecp_keypair *ecp = NULL;
size_t curve_bytes = data_length;
int explicit_bits = ( curve_bits != 0 );
int explicit_bits = (curve_bits != 0);
if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) &&
PSA_KEY_TYPE_ECC_GET_FAMILY( type ) != PSA_ECC_FAMILY_MONTGOMERY )
{
if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type) &&
PSA_KEY_TYPE_ECC_GET_FAMILY(type) != PSA_ECC_FAMILY_MONTGOMERY) {
/* A Weierstrass public key is represented as:
* - The byte 0x04;
* - `x_P` as a `ceiling(m/8)`-byte string, big-endian;
* - `y_P` as a `ceiling(m/8)`-byte string, big-endian.
* So its data length is 2m+1 where m is the curve size in bits.
*/
if( ( data_length & 1 ) == 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
if ((data_length & 1) == 0) {
return PSA_ERROR_INVALID_ARGUMENT;
}
curve_bytes = data_length / 2;
/* Montgomery public keys are represented in compressed format, meaning
@ -73,31 +73,29 @@ psa_status_t mbedtls_psa_ecp_load_representation(
* format, meaning their curve_bytes is equal to the amount of input. */
}
if( explicit_bits )
{
if (explicit_bits) {
/* With an explicit bit-size, the data must have the matching length. */
if( curve_bytes != PSA_BITS_TO_BYTES( curve_bits ) )
return( PSA_ERROR_INVALID_ARGUMENT );
}
else
{
if (curve_bytes != PSA_BITS_TO_BYTES(curve_bits)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
} else {
/* We need to infer the bit-size from the data. Since the only
* information we have is the length in bytes, the value of curve_bits
* at this stage is rounded up to the nearest multiple of 8. */
curve_bits = PSA_BYTES_TO_BITS( curve_bytes );
curve_bits = PSA_BYTES_TO_BITS(curve_bytes);
}
/* Allocate and initialize a key representation. */
ecp = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) );
if( ecp == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
mbedtls_ecp_keypair_init( ecp );
ecp = mbedtls_calloc(1, sizeof(mbedtls_ecp_keypair));
if (ecp == NULL) {
return PSA_ERROR_INSUFFICIENT_MEMORY;
}
mbedtls_ecp_keypair_init(ecp);
/* Load the group. */
grp_id = mbedtls_ecc_group_of_psa( PSA_KEY_TYPE_ECC_GET_FAMILY( type ),
curve_bits, !explicit_bits );
if( grp_id == MBEDTLS_ECP_DP_NONE )
{
grp_id = mbedtls_ecc_group_of_psa(PSA_KEY_TYPE_ECC_GET_FAMILY(type),
curve_bits, !explicit_bits);
if (grp_id == MBEDTLS_ECP_DP_NONE) {
/* We can't distinguish between a nonsensical family/size combination
* (which would warrant PSA_ERROR_INVALID_ARGUMENT) and a
* well-regarded curve that Mbed TLS just doesn't know about (which
@ -109,48 +107,48 @@ psa_status_t mbedtls_psa_ecp_load_representation(
}
status = mbedtls_to_psa_error(
mbedtls_ecp_group_load( &ecp->grp, grp_id ) );
if( status != PSA_SUCCESS )
mbedtls_ecp_group_load(&ecp->grp, grp_id));
if (status != PSA_SUCCESS) {
goto exit;
}
/* Load the key material. */
if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) )
{
if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type)) {
/* Load the public value. */
status = mbedtls_to_psa_error(
mbedtls_ecp_point_read_binary( &ecp->grp, &ecp->Q,
data,
data_length ) );
if( status != PSA_SUCCESS )
mbedtls_ecp_point_read_binary(&ecp->grp, &ecp->Q,
data,
data_length));
if (status != PSA_SUCCESS) {
goto exit;
}
/* Check that the point is on the curve. */
status = mbedtls_to_psa_error(
mbedtls_ecp_check_pubkey( &ecp->grp, &ecp->Q ) );
if( status != PSA_SUCCESS )
mbedtls_ecp_check_pubkey(&ecp->grp, &ecp->Q));
if (status != PSA_SUCCESS) {
goto exit;
}
else
{
}
} else {
/* Load and validate the secret value. */
status = mbedtls_to_psa_error(
mbedtls_ecp_read_key( ecp->grp.id,
ecp,
data,
data_length ) );
if( status != PSA_SUCCESS )
mbedtls_ecp_read_key(ecp->grp.id,
ecp,
data,
data_length));
if (status != PSA_SUCCESS) {
goto exit;
}
}
*p_ecp = ecp;
exit:
if( status != PSA_SUCCESS )
{
mbedtls_ecp_keypair_free( ecp );
mbedtls_free( ecp );
if (status != PSA_SUCCESS) {
mbedtls_ecp_keypair_free(ecp);
mbedtls_free(ecp);
}
return( status );
return status;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) ||
@ -165,116 +163,119 @@ psa_status_t mbedtls_psa_ecp_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits )
size_t *key_buffer_length, size_t *bits)
{
psa_status_t status;
mbedtls_ecp_keypair *ecp = NULL;
/* Parse input */
status = mbedtls_psa_ecp_load_representation( attributes->core.type,
attributes->core.bits,
data,
data_length,
&ecp );
if( status != PSA_SUCCESS )
status = mbedtls_psa_ecp_load_representation(attributes->core.type,
attributes->core.bits,
data,
data_length,
&ecp);
if (status != PSA_SUCCESS) {
goto exit;
}
if( PSA_KEY_TYPE_ECC_GET_FAMILY( attributes->core.type ) ==
PSA_ECC_FAMILY_MONTGOMERY )
if (PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->core.type) ==
PSA_ECC_FAMILY_MONTGOMERY) {
*bits = ecp->grp.nbits + 1;
else
} else {
*bits = ecp->grp.nbits;
}
/* Re-export the data to PSA export format. There is currently no support
* for other input formats then the export format, so this is a 1-1
* copy operation. */
status = mbedtls_psa_ecp_export_key( attributes->core.type,
ecp,
key_buffer,
key_buffer_size,
key_buffer_length );
status = mbedtls_psa_ecp_export_key(attributes->core.type,
ecp,
key_buffer,
key_buffer_size,
key_buffer_length);
exit:
/* Always free the PK object (will also free contained ECP context) */
mbedtls_ecp_keypair_free( ecp );
mbedtls_free( ecp );
mbedtls_ecp_keypair_free(ecp);
mbedtls_free(ecp);
return( status );
return status;
}
psa_status_t mbedtls_psa_ecp_export_key( psa_key_type_t type,
mbedtls_ecp_keypair *ecp,
uint8_t *data,
size_t data_size,
size_t *data_length )
psa_status_t mbedtls_psa_ecp_export_key(psa_key_type_t type,
mbedtls_ecp_keypair *ecp,
uint8_t *data,
size_t data_size,
size_t *data_length)
{
psa_status_t status;
if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) )
{
if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type)) {
/* Check whether the public part is loaded */
if( mbedtls_ecp_is_zero( &ecp->Q ) )
{
if (mbedtls_ecp_is_zero(&ecp->Q)) {
/* Calculate the public key */
status = mbedtls_to_psa_error(
mbedtls_ecp_mul( &ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE ) );
if( status != PSA_SUCCESS )
return( status );
mbedtls_ecp_mul(&ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE));
if (status != PSA_SUCCESS) {
return status;
}
}
status = mbedtls_to_psa_error(
mbedtls_ecp_point_write_binary( &ecp->grp, &ecp->Q,
MBEDTLS_ECP_PF_UNCOMPRESSED,
data_length,
data,
data_size ) );
if( status != PSA_SUCCESS )
memset( data, 0, data_size );
mbedtls_ecp_point_write_binary(&ecp->grp, &ecp->Q,
MBEDTLS_ECP_PF_UNCOMPRESSED,
data_length,
data,
data_size));
if (status != PSA_SUCCESS) {
memset(data, 0, data_size);
}
return( status );
}
else
{
if( data_size < PSA_BITS_TO_BYTES( ecp->grp.nbits ) )
return( PSA_ERROR_BUFFER_TOO_SMALL );
return status;
} else {
if (data_size < PSA_BITS_TO_BYTES(ecp->grp.nbits)) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
status = mbedtls_to_psa_error(
mbedtls_ecp_write_key( ecp,
data,
PSA_BITS_TO_BYTES( ecp->grp.nbits ) ) );
if( status == PSA_SUCCESS )
*data_length = PSA_BITS_TO_BYTES( ecp->grp.nbits );
else
memset( data, 0, data_size );
mbedtls_ecp_write_key(ecp,
data,
PSA_BITS_TO_BYTES(ecp->grp.nbits)));
if (status == PSA_SUCCESS) {
*data_length = PSA_BITS_TO_BYTES(ecp->grp.nbits);
} else {
memset(data, 0, data_size);
}
return( status );
return status;
}
}
psa_status_t mbedtls_psa_ecp_export_public_key(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length )
uint8_t *data, size_t data_size, size_t *data_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_keypair *ecp = NULL;
status = mbedtls_psa_ecp_load_representation(
attributes->core.type, attributes->core.bits,
key_buffer, key_buffer_size, &ecp );
if( status != PSA_SUCCESS )
return( status );
key_buffer, key_buffer_size, &ecp);
if (status != PSA_SUCCESS) {
return status;
}
status = mbedtls_psa_ecp_export_key(
PSA_KEY_TYPE_ECC_PUBLIC_KEY(
PSA_KEY_TYPE_ECC_GET_FAMILY( attributes->core.type ) ),
ecp, data, data_size, data_length );
PSA_KEY_TYPE_ECC_PUBLIC_KEY(
PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->core.type)),
ecp, data, data_size, data_length);
mbedtls_ecp_keypair_free( ecp );
mbedtls_free( ecp );
mbedtls_ecp_keypair_free(ecp);
mbedtls_free(ecp);
return( status );
return status;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
@ -282,45 +283,47 @@ psa_status_t mbedtls_psa_ecp_export_public_key(
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR)
psa_status_t mbedtls_psa_ecp_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length )
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(
attributes->core.type );
attributes->core.type);
mbedtls_ecp_group_id grp_id =
mbedtls_ecc_group_of_psa( curve, attributes->core.bits, 0 );
mbedtls_ecc_group_of_psa(curve, attributes->core.bits, 0);
const mbedtls_ecp_curve_info *curve_info =
mbedtls_ecp_curve_info_from_grp_id( grp_id );
mbedtls_ecp_curve_info_from_grp_id(grp_id);
mbedtls_ecp_keypair ecp;
if( attributes->domain_parameters_size != 0 )
return( PSA_ERROR_NOT_SUPPORTED );
if (attributes->domain_parameters_size != 0) {
return PSA_ERROR_NOT_SUPPORTED;
}
if( grp_id == MBEDTLS_ECP_DP_NONE || curve_info == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
if (grp_id == MBEDTLS_ECP_DP_NONE || curve_info == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
mbedtls_ecp_keypair_init( &ecp );
ret = mbedtls_ecp_gen_key( grp_id, &ecp,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE );
if( ret != 0 )
{
mbedtls_ecp_keypair_free( &ecp );
return( mbedtls_to_psa_error( ret ) );
mbedtls_ecp_keypair_init(&ecp);
ret = mbedtls_ecp_gen_key(grp_id, &ecp,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE);
if (ret != 0) {
mbedtls_ecp_keypair_free(&ecp);
return mbedtls_to_psa_error(ret);
}
status = mbedtls_to_psa_error(
mbedtls_ecp_write_key( &ecp, key_buffer, key_buffer_size ) );
mbedtls_ecp_write_key(&ecp, key_buffer, key_buffer_size));
mbedtls_ecp_keypair_free( &ecp );
mbedtls_ecp_keypair_free(&ecp);
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
*key_buffer_length = key_buffer_size;
}
return( status );
return status;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) */
@ -334,7 +337,7 @@ psa_status_t mbedtls_psa_ecdsa_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
uint8_t *signature, size_t signature_size, size_t *signature_length )
uint8_t *signature, size_t signature_size, size_t *signature_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_keypair *ecp = NULL;
@ -342,72 +345,70 @@ psa_status_t mbedtls_psa_ecdsa_sign_hash(
size_t curve_bytes;
mbedtls_mpi r, s;
status = mbedtls_psa_ecp_load_representation( attributes->core.type,
attributes->core.bits,
key_buffer,
key_buffer_size,
&ecp );
if( status != PSA_SUCCESS )
return( status );
status = mbedtls_psa_ecp_load_representation(attributes->core.type,
attributes->core.bits,
key_buffer,
key_buffer_size,
&ecp);
if (status != PSA_SUCCESS) {
return status;
}
curve_bytes = PSA_BITS_TO_BYTES( ecp->grp.pbits );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
curve_bytes = PSA_BITS_TO_BYTES(ecp->grp.pbits);
mbedtls_mpi_init(&r);
mbedtls_mpi_init(&s);
if( signature_size < 2 * curve_bytes )
{
if (signature_size < 2 * curve_bytes) {
ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
goto cleanup;
}
if( PSA_ALG_ECDSA_IS_DETERMINISTIC( alg ) )
{
if (PSA_ALG_ECDSA_IS_DETERMINISTIC(alg)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg );
mbedtls_md_type_t md_alg = mbedtls_hash_info_md_from_psa( hash_alg );
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det_ext(
&ecp->grp, &r, &s,
&ecp->d, hash,
hash_length, md_alg,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE ) );
psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH(alg);
mbedtls_md_type_t md_alg = mbedtls_hash_info_md_from_psa(hash_alg);
MBEDTLS_MPI_CHK(mbedtls_ecdsa_sign_det_ext(
&ecp->grp, &r, &s,
&ecp->d, hash,
hash_length, md_alg,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE));
#else
ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
goto cleanup;
ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
goto cleanup;
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
}
else
{
} else {
(void) alg;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ecp->grp, &r, &s, &ecp->d,
hash, hash_length,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE ) );
MBEDTLS_MPI_CHK(mbedtls_ecdsa_sign(&ecp->grp, &r, &s, &ecp->d,
hash, hash_length,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE));
}
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &r,
signature,
curve_bytes ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &s,
signature + curve_bytes,
curve_bytes ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&r,
signature,
curve_bytes));
MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&s,
signature + curve_bytes,
curve_bytes));
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
if( ret == 0 )
mbedtls_mpi_free(&r);
mbedtls_mpi_free(&s);
if (ret == 0) {
*signature_length = 2 * curve_bytes;
}
mbedtls_ecp_keypair_free( ecp );
mbedtls_free( ecp );
mbedtls_ecp_keypair_free(ecp);
mbedtls_free(ecp);
return( mbedtls_to_psa_error( ret ) );
return mbedtls_to_psa_error(ret);
}
psa_status_t mbedtls_psa_ecdsa_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
const uint8_t *signature, size_t signature_length )
const uint8_t *signature, size_t signature_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_keypair *ecp = NULL;
@ -415,51 +416,50 @@ psa_status_t mbedtls_psa_ecdsa_verify_hash(
size_t curve_bytes;
mbedtls_mpi r, s;
(void)alg;
(void) alg;
status = mbedtls_psa_ecp_load_representation( attributes->core.type,
attributes->core.bits,
key_buffer,
key_buffer_size,
&ecp );
if( status != PSA_SUCCESS )
return( status );
status = mbedtls_psa_ecp_load_representation(attributes->core.type,
attributes->core.bits,
key_buffer,
key_buffer_size,
&ecp);
if (status != PSA_SUCCESS) {
return status;
}
curve_bytes = PSA_BITS_TO_BYTES( ecp->grp.pbits );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
curve_bytes = PSA_BITS_TO_BYTES(ecp->grp.pbits);
mbedtls_mpi_init(&r);
mbedtls_mpi_init(&s);
if( signature_length != 2 * curve_bytes )
{
if (signature_length != 2 * curve_bytes) {
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &r,
signature,
curve_bytes ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &s,
signature + curve_bytes,
curve_bytes ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&r,
signature,
curve_bytes));
MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&s,
signature + curve_bytes,
curve_bytes));
/* Check whether the public part is loaded. If not, load it. */
if( mbedtls_ecp_is_zero( &ecp->Q ) )
{
if (mbedtls_ecp_is_zero(&ecp->Q)) {
MBEDTLS_MPI_CHK(
mbedtls_ecp_mul( &ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G,
mbedtls_psa_get_random, MBEDTLS_PSA_RANDOM_STATE ) );
mbedtls_ecp_mul(&ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G,
mbedtls_psa_get_random, MBEDTLS_PSA_RANDOM_STATE));
}
ret = mbedtls_ecdsa_verify( &ecp->grp, hash, hash_length,
&ecp->Q, &r, &s );
ret = mbedtls_ecdsa_verify(&ecp->grp, hash, hash_length,
&ecp->Q, &r, &s);
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
mbedtls_ecp_keypair_free( ecp );
mbedtls_free( ecp );
mbedtls_mpi_free(&r);
mbedtls_mpi_free(&s);
mbedtls_ecp_keypair_free(ecp);
mbedtls_free(ecp);
return( mbedtls_to_psa_error( ret ) );
return mbedtls_to_psa_error(ret);
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
@ -475,64 +475,72 @@ psa_status_t mbedtls_psa_key_agreement_ecdh(
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *peer_key, size_t peer_key_length,
uint8_t *shared_secret, size_t shared_secret_size,
size_t *shared_secret_length )
size_t *shared_secret_length)
{
psa_status_t status;
if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( attributes->core.type ) ||
! PSA_ALG_IS_ECDH(alg) )
return( PSA_ERROR_INVALID_ARGUMENT );
if (!PSA_KEY_TYPE_IS_ECC_KEY_PAIR(attributes->core.type) ||
!PSA_ALG_IS_ECDH(alg)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
mbedtls_ecp_keypair *ecp = NULL;
status = mbedtls_psa_ecp_load_representation(
attributes->core.type,
attributes->core.bits,
key_buffer,
key_buffer_size,
&ecp );
if( status != PSA_SUCCESS )
return( status );
attributes->core.type,
attributes->core.bits,
key_buffer,
key_buffer_size,
&ecp);
if (status != PSA_SUCCESS) {
return status;
}
mbedtls_ecp_keypair *their_key = NULL;
mbedtls_ecdh_context ecdh;
size_t bits = 0;
psa_ecc_family_t curve = mbedtls_ecc_group_to_psa( ecp->grp.id, &bits );
mbedtls_ecdh_init( &ecdh );
psa_ecc_family_t curve = mbedtls_ecc_group_to_psa(ecp->grp.id, &bits);
mbedtls_ecdh_init(&ecdh);
status = mbedtls_psa_ecp_load_representation(
PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve),
bits,
peer_key,
peer_key_length,
&their_key );
if( status != PSA_SUCCESS )
PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve),
bits,
peer_key,
peer_key_length,
&their_key);
if (status != PSA_SUCCESS) {
goto exit;
}
status = mbedtls_to_psa_error(
mbedtls_ecdh_get_params( &ecdh, their_key, MBEDTLS_ECDH_THEIRS ) );
if( status != PSA_SUCCESS )
mbedtls_ecdh_get_params(&ecdh, their_key, MBEDTLS_ECDH_THEIRS));
if (status != PSA_SUCCESS) {
goto exit;
}
status = mbedtls_to_psa_error(
mbedtls_ecdh_get_params( &ecdh, ecp, MBEDTLS_ECDH_OURS ) );
if( status != PSA_SUCCESS )
mbedtls_ecdh_get_params(&ecdh, ecp, MBEDTLS_ECDH_OURS));
if (status != PSA_SUCCESS) {
goto exit;
}
status = mbedtls_to_psa_error(
mbedtls_ecdh_calc_secret( &ecdh,
shared_secret_length,
shared_secret, shared_secret_size,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE ) );
if( status != PSA_SUCCESS )
mbedtls_ecdh_calc_secret(&ecdh,
shared_secret_length,
shared_secret, shared_secret_size,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE));
if (status != PSA_SUCCESS) {
goto exit;
if( PSA_BITS_TO_BYTES( bits ) != *shared_secret_length )
}
if (PSA_BITS_TO_BYTES(bits) != *shared_secret_length) {
status = PSA_ERROR_CORRUPTION_DETECTED;
}
exit:
if( status != PSA_SUCCESS )
mbedtls_platform_zeroize( shared_secret, shared_secret_size );
mbedtls_ecdh_free( &ecdh );
mbedtls_ecp_keypair_free( their_key );
mbedtls_free( their_key );
mbedtls_ecp_keypair_free( ecp );
mbedtls_free( ecp );
return( status );
if (status != PSA_SUCCESS) {
mbedtls_platform_zeroize(shared_secret, shared_secret_size);
}
mbedtls_ecdh_free(&ecdh);
mbedtls_ecp_keypair_free(their_key);
mbedtls_free(their_key);
mbedtls_ecp_keypair_free(ecp);
mbedtls_free(ecp);
return status;
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */

View File

@ -42,11 +42,11 @@
* contents of the context and the context itself
* when done.
*/
psa_status_t mbedtls_psa_ecp_load_representation( psa_key_type_t type,
size_t curve_bits,
const uint8_t *data,
size_t data_length,
mbedtls_ecp_keypair **p_ecp );
psa_status_t mbedtls_psa_ecp_load_representation(psa_key_type_t type,
size_t curve_bits,
const uint8_t *data,
size_t data_length,
mbedtls_ecp_keypair **p_ecp);
/** Import an ECP key in binary format.
*
@ -78,7 +78,7 @@ psa_status_t mbedtls_psa_ecp_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits );
size_t *key_buffer_length, size_t *bits);
/** Export an ECP key to export representation
*
@ -88,11 +88,11 @@ psa_status_t mbedtls_psa_ecp_import_key(
* \param[in] data_size The length of the buffer to export to
* \param[out] data_length The amount of bytes written to \p data
*/
psa_status_t mbedtls_psa_ecp_export_key( psa_key_type_t type,
mbedtls_ecp_keypair *ecp,
uint8_t *data,
size_t data_size,
size_t *data_length );
psa_status_t mbedtls_psa_ecp_export_key(psa_key_type_t type,
mbedtls_ecp_keypair *ecp,
uint8_t *data,
size_t data_size,
size_t *data_length);
/** Export an ECP public key or the public part of an ECP key pair in binary
* format.
@ -121,7 +121,7 @@ psa_status_t mbedtls_psa_ecp_export_key( psa_key_type_t type,
psa_status_t mbedtls_psa_ecp_export_public_key(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length );
uint8_t *data, size_t data_size, size_t *data_length);
/**
* \brief Generate an ECP key.
@ -144,7 +144,7 @@ psa_status_t mbedtls_psa_ecp_export_public_key(
*/
psa_status_t mbedtls_psa_ecp_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length );
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length);
/** Sign an already-calculated hash with ECDSA.
*
@ -182,7 +182,7 @@ psa_status_t mbedtls_psa_ecdsa_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
uint8_t *signature, size_t signature_size, size_t *signature_length );
uint8_t *signature, size_t signature_size, size_t *signature_length);
/**
* \brief Verify an ECDSA hash or short message signature.
@ -217,7 +217,7 @@ psa_status_t mbedtls_psa_ecdsa_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
const uint8_t *signature, size_t signature_length );
const uint8_t *signature, size_t signature_length);
/** Perform a key agreement and return the raw ECDH shared secret.
@ -266,5 +266,5 @@ psa_status_t mbedtls_psa_key_agreement_ecdh(
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *peer_key, size_t peer_key_length,
uint8_t *shared_secret, size_t shared_secret_size,
size_t *shared_secret_length );
size_t *shared_secret_length);
#endif /* PSA_CRYPTO_ECP_H */

View File

@ -31,10 +31,9 @@
#if defined(MBEDTLS_PSA_BUILTIN_HASH)
psa_status_t mbedtls_psa_hash_abort(
mbedtls_psa_hash_operation_t *operation )
mbedtls_psa_hash_operation_t *operation)
{
switch( operation->alg )
{
switch (operation->alg) {
case 0:
/* The object has (apparently) been initialized but it is not
* in use. It's ok to call abort on such an object, and there's
@ -42,243 +41,240 @@ psa_status_t mbedtls_psa_hash_abort(
break;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
mbedtls_md5_free( &operation->ctx.md5 );
mbedtls_md5_free(&operation->ctx.md5);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
case PSA_ALG_RIPEMD160:
mbedtls_ripemd160_free( &operation->ctx.ripemd160 );
mbedtls_ripemd160_free(&operation->ctx.ripemd160);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
case PSA_ALG_SHA_1:
mbedtls_sha1_free( &operation->ctx.sha1 );
mbedtls_sha1_free(&operation->ctx.sha1);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
case PSA_ALG_SHA_224:
mbedtls_sha256_free( &operation->ctx.sha256 );
mbedtls_sha256_free(&operation->ctx.sha256);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
case PSA_ALG_SHA_256:
mbedtls_sha256_free( &operation->ctx.sha256 );
mbedtls_sha256_free(&operation->ctx.sha256);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
case PSA_ALG_SHA_384:
mbedtls_sha512_free( &operation->ctx.sha512 );
mbedtls_sha512_free(&operation->ctx.sha512);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
case PSA_ALG_SHA_512:
mbedtls_sha512_free( &operation->ctx.sha512 );
mbedtls_sha512_free(&operation->ctx.sha512);
break;
#endif
default:
return( PSA_ERROR_BAD_STATE );
return PSA_ERROR_BAD_STATE;
}
operation->alg = 0;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_hash_setup(
mbedtls_psa_hash_operation_t *operation,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* A context must be freshly initialized before it can be set up. */
if( operation->alg != 0 )
{
return( PSA_ERROR_BAD_STATE );
if (operation->alg != 0) {
return PSA_ERROR_BAD_STATE;
}
switch( alg )
{
switch (alg) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
mbedtls_md5_init( &operation->ctx.md5 );
ret = mbedtls_md5_starts( &operation->ctx.md5 );
mbedtls_md5_init(&operation->ctx.md5);
ret = mbedtls_md5_starts(&operation->ctx.md5);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
case PSA_ALG_RIPEMD160:
mbedtls_ripemd160_init( &operation->ctx.ripemd160 );
ret = mbedtls_ripemd160_starts( &operation->ctx.ripemd160 );
mbedtls_ripemd160_init(&operation->ctx.ripemd160);
ret = mbedtls_ripemd160_starts(&operation->ctx.ripemd160);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
case PSA_ALG_SHA_1:
mbedtls_sha1_init( &operation->ctx.sha1 );
ret = mbedtls_sha1_starts( &operation->ctx.sha1 );
mbedtls_sha1_init(&operation->ctx.sha1);
ret = mbedtls_sha1_starts(&operation->ctx.sha1);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
case PSA_ALG_SHA_224:
mbedtls_sha256_init( &operation->ctx.sha256 );
ret = mbedtls_sha256_starts( &operation->ctx.sha256, 1 );
mbedtls_sha256_init(&operation->ctx.sha256);
ret = mbedtls_sha256_starts(&operation->ctx.sha256, 1);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
case PSA_ALG_SHA_256:
mbedtls_sha256_init( &operation->ctx.sha256 );
ret = mbedtls_sha256_starts( &operation->ctx.sha256, 0 );
mbedtls_sha256_init(&operation->ctx.sha256);
ret = mbedtls_sha256_starts(&operation->ctx.sha256, 0);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
case PSA_ALG_SHA_384:
mbedtls_sha512_init( &operation->ctx.sha512 );
ret = mbedtls_sha512_starts( &operation->ctx.sha512, 1 );
mbedtls_sha512_init(&operation->ctx.sha512);
ret = mbedtls_sha512_starts(&operation->ctx.sha512, 1);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
case PSA_ALG_SHA_512:
mbedtls_sha512_init( &operation->ctx.sha512 );
ret = mbedtls_sha512_starts( &operation->ctx.sha512, 0 );
mbedtls_sha512_init(&operation->ctx.sha512);
ret = mbedtls_sha512_starts(&operation->ctx.sha512, 0);
break;
#endif
default:
return( PSA_ALG_IS_HASH( alg ) ?
PSA_ERROR_NOT_SUPPORTED :
PSA_ERROR_INVALID_ARGUMENT );
return PSA_ALG_IS_HASH(alg) ?
PSA_ERROR_NOT_SUPPORTED :
PSA_ERROR_INVALID_ARGUMENT;
}
if( ret == 0 )
if (ret == 0) {
operation->alg = alg;
else
mbedtls_psa_hash_abort( operation );
return( mbedtls_to_psa_error( ret ) );
} else {
mbedtls_psa_hash_abort(operation);
}
return mbedtls_to_psa_error(ret);
}
psa_status_t mbedtls_psa_hash_clone(
const mbedtls_psa_hash_operation_t *source_operation,
mbedtls_psa_hash_operation_t *target_operation )
mbedtls_psa_hash_operation_t *target_operation)
{
switch( source_operation->alg )
{
switch (source_operation->alg) {
case 0:
return( PSA_ERROR_BAD_STATE );
return PSA_ERROR_BAD_STATE;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
mbedtls_md5_clone( &target_operation->ctx.md5,
&source_operation->ctx.md5 );
mbedtls_md5_clone(&target_operation->ctx.md5,
&source_operation->ctx.md5);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
case PSA_ALG_RIPEMD160:
mbedtls_ripemd160_clone( &target_operation->ctx.ripemd160,
&source_operation->ctx.ripemd160 );
mbedtls_ripemd160_clone(&target_operation->ctx.ripemd160,
&source_operation->ctx.ripemd160);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
case PSA_ALG_SHA_1:
mbedtls_sha1_clone( &target_operation->ctx.sha1,
&source_operation->ctx.sha1 );
mbedtls_sha1_clone(&target_operation->ctx.sha1,
&source_operation->ctx.sha1);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
case PSA_ALG_SHA_224:
mbedtls_sha256_clone( &target_operation->ctx.sha256,
&source_operation->ctx.sha256 );
mbedtls_sha256_clone(&target_operation->ctx.sha256,
&source_operation->ctx.sha256);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
case PSA_ALG_SHA_256:
mbedtls_sha256_clone( &target_operation->ctx.sha256,
&source_operation->ctx.sha256 );
mbedtls_sha256_clone(&target_operation->ctx.sha256,
&source_operation->ctx.sha256);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
case PSA_ALG_SHA_384:
mbedtls_sha512_clone( &target_operation->ctx.sha512,
&source_operation->ctx.sha512 );
mbedtls_sha512_clone(&target_operation->ctx.sha512,
&source_operation->ctx.sha512);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
case PSA_ALG_SHA_512:
mbedtls_sha512_clone( &target_operation->ctx.sha512,
&source_operation->ctx.sha512 );
mbedtls_sha512_clone(&target_operation->ctx.sha512,
&source_operation->ctx.sha512);
break;
#endif
default:
(void) source_operation;
(void) target_operation;
return( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
}
target_operation->alg = source_operation->alg;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_hash_update(
mbedtls_psa_hash_operation_t *operation,
const uint8_t *input,
size_t input_length )
size_t input_length)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
switch( operation->alg )
{
switch (operation->alg) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
ret = mbedtls_md5_update( &operation->ctx.md5,
input, input_length );
ret = mbedtls_md5_update(&operation->ctx.md5,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
case PSA_ALG_RIPEMD160:
ret = mbedtls_ripemd160_update( &operation->ctx.ripemd160,
input, input_length );
ret = mbedtls_ripemd160_update(&operation->ctx.ripemd160,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
case PSA_ALG_SHA_1:
ret = mbedtls_sha1_update( &operation->ctx.sha1,
input, input_length );
ret = mbedtls_sha1_update(&operation->ctx.sha1,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
case PSA_ALG_SHA_224:
ret = mbedtls_sha256_update( &operation->ctx.sha256,
input, input_length );
ret = mbedtls_sha256_update(&operation->ctx.sha256,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
case PSA_ALG_SHA_256:
ret = mbedtls_sha256_update( &operation->ctx.sha256,
input, input_length );
ret = mbedtls_sha256_update(&operation->ctx.sha256,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
case PSA_ALG_SHA_384:
ret = mbedtls_sha512_update( &operation->ctx.sha512,
input, input_length );
ret = mbedtls_sha512_update(&operation->ctx.sha512,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
case PSA_ALG_SHA_512:
ret = mbedtls_sha512_update( &operation->ctx.sha512,
input, input_length );
ret = mbedtls_sha512_update(&operation->ctx.sha512,
input, input_length);
break;
#endif
default:
(void) input;
(void) input_length;
return( PSA_ERROR_BAD_STATE );
return PSA_ERROR_BAD_STATE;
}
return( mbedtls_to_psa_error( ret ) );
return mbedtls_to_psa_error(ret);
}
psa_status_t mbedtls_psa_hash_finish(
mbedtls_psa_hash_operation_t *operation,
uint8_t *hash,
size_t hash_size,
size_t *hash_length )
size_t *hash_length)
{
psa_status_t status;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t actual_hash_length = PSA_HASH_LENGTH( operation->alg );
size_t actual_hash_length = PSA_HASH_LENGTH(operation->alg);
/* Fill the output buffer with something that isn't a valid hash
* (barring an attack on the hash and deliberately-crafted input),
@ -286,62 +282,62 @@ psa_status_t mbedtls_psa_hash_finish(
*hash_length = hash_size;
/* If hash_size is 0 then hash may be NULL and then the
* call to memset would have undefined behavior. */
if( hash_size != 0 )
memset( hash, '!', hash_size );
if (hash_size != 0) {
memset(hash, '!', hash_size);
}
if( hash_size < actual_hash_length )
{
if (hash_size < actual_hash_length) {
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto exit;
}
switch( operation->alg )
{
switch (operation->alg) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
ret = mbedtls_md5_finish( &operation->ctx.md5, hash );
ret = mbedtls_md5_finish(&operation->ctx.md5, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
case PSA_ALG_RIPEMD160:
ret = mbedtls_ripemd160_finish( &operation->ctx.ripemd160, hash );
ret = mbedtls_ripemd160_finish(&operation->ctx.ripemd160, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
case PSA_ALG_SHA_1:
ret = mbedtls_sha1_finish( &operation->ctx.sha1, hash );
ret = mbedtls_sha1_finish(&operation->ctx.sha1, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
case PSA_ALG_SHA_224:
ret = mbedtls_sha256_finish( &operation->ctx.sha256, hash );
ret = mbedtls_sha256_finish(&operation->ctx.sha256, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
case PSA_ALG_SHA_256:
ret = mbedtls_sha256_finish( &operation->ctx.sha256, hash );
ret = mbedtls_sha256_finish(&operation->ctx.sha256, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
case PSA_ALG_SHA_384:
ret = mbedtls_sha512_finish( &operation->ctx.sha512, hash );
ret = mbedtls_sha512_finish(&operation->ctx.sha512, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
case PSA_ALG_SHA_512:
ret = mbedtls_sha512_finish( &operation->ctx.sha512, hash );
ret = mbedtls_sha512_finish(&operation->ctx.sha512, hash);
break;
#endif
default:
(void) hash;
return( PSA_ERROR_BAD_STATE );
return PSA_ERROR_BAD_STATE;
}
status = mbedtls_to_psa_error( ret );
status = mbedtls_to_psa_error(ret);
exit:
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
*hash_length = actual_hash_length;
return( status );
}
return status;
}
psa_status_t mbedtls_psa_hash_compute(
@ -357,22 +353,26 @@ psa_status_t mbedtls_psa_hash_compute(
psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
*hash_length = hash_size;
status = mbedtls_psa_hash_setup( &operation, alg );
if( status != PSA_SUCCESS )
status = mbedtls_psa_hash_setup(&operation, alg);
if (status != PSA_SUCCESS) {
goto exit;
status = mbedtls_psa_hash_update( &operation, input, input_length );
if( status != PSA_SUCCESS )
}
status = mbedtls_psa_hash_update(&operation, input, input_length);
if (status != PSA_SUCCESS) {
goto exit;
status = mbedtls_psa_hash_finish( &operation, hash, hash_size, hash_length );
if( status != PSA_SUCCESS )
}
status = mbedtls_psa_hash_finish(&operation, hash, hash_size, hash_length);
if (status != PSA_SUCCESS) {
goto exit;
}
exit:
abort_status = mbedtls_psa_hash_abort( &operation );
if( status == PSA_SUCCESS )
return( abort_status );
else
return( status );
abort_status = mbedtls_psa_hash_abort(&operation);
if (status == PSA_SUCCESS) {
return abort_status;
} else {
return status;
}
}
#endif /* MBEDTLS_PSA_BUILTIN_HASH */

View File

@ -93,7 +93,7 @@ psa_status_t mbedtls_psa_hash_compute(
*/
psa_status_t mbedtls_psa_hash_setup(
mbedtls_psa_hash_operation_t *operation,
psa_algorithm_t alg );
psa_algorithm_t alg);
/** Clone an Mbed TLS hash operation.
*
@ -125,7 +125,7 @@ psa_status_t mbedtls_psa_hash_setup(
*/
psa_status_t mbedtls_psa_hash_clone(
const mbedtls_psa_hash_operation_t *source_operation,
mbedtls_psa_hash_operation_t *target_operation );
mbedtls_psa_hash_operation_t *target_operation);
/** Add a message fragment to a multipart Mbed TLS hash operation.
*
@ -153,7 +153,7 @@ psa_status_t mbedtls_psa_hash_clone(
psa_status_t mbedtls_psa_hash_update(
mbedtls_psa_hash_operation_t *operation,
const uint8_t *input,
size_t input_length );
size_t input_length);
/** Finish the calculation of the Mbed TLS-calculated hash of a message.
*
@ -193,7 +193,7 @@ psa_status_t mbedtls_psa_hash_finish(
mbedtls_psa_hash_operation_t *operation,
uint8_t *hash,
size_t hash_size,
size_t *hash_length );
size_t *hash_length);
/** Abort an Mbed TLS hash operation.
*
@ -220,6 +220,6 @@ psa_status_t mbedtls_psa_hash_finish(
* \retval #PSA_ERROR_CORRUPTION_DETECTED
*/
psa_status_t mbedtls_psa_hash_abort(
mbedtls_psa_hash_operation_t *operation );
mbedtls_psa_hash_operation_t *operation);
#endif /* PSA_CRYPTO_HASH_H */

View File

@ -69,14 +69,14 @@
* The library has already been initialized.
*/
psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
void (* entropy_init )( mbedtls_entropy_context *ctx ),
void (* entropy_free )( mbedtls_entropy_context *ctx ) );
void (* entropy_init)(mbedtls_entropy_context *ctx),
void (* entropy_free)(mbedtls_entropy_context *ctx));
#endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
#if defined(MBEDTLS_TEST_HOOKS) && defined(MBEDTLS_PSA_CRYPTO_C)
psa_status_t psa_mac_key_can_do(
psa_algorithm_t algorithm,
psa_key_type_t key_type );
psa_key_type_t key_type);
#endif /* MBEDTLS_TEST_HOOKS && MBEDTLS_PSA_CRYPTO_C */
#endif /* PSA_CRYPTO_INVASIVE_H */

View File

@ -45,8 +45,7 @@ typedef uint64_t psa_storage_uid_t;
/**
* \brief A container for metadata associated with a specific uid
*/
struct psa_storage_info_t
{
struct psa_storage_info_t {
uint32_t size; /**< The size of the data associated with a uid **/
psa_storage_create_flags_t flags; /**< The flags set when the uid was created **/
};
@ -104,7 +103,7 @@ psa_status_t psa_its_get(psa_storage_uid_t uid,
uint32_t data_offset,
uint32_t data_length,
void *p_data,
size_t *p_data_length );
size_t *p_data_length);
/**
* \brief Retrieve the metadata about the provided uid

View File

@ -33,22 +33,22 @@
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
static psa_status_t psa_hmac_abort_internal(
mbedtls_psa_hmac_operation_t *hmac )
mbedtls_psa_hmac_operation_t *hmac)
{
mbedtls_platform_zeroize( hmac->opad, sizeof( hmac->opad ) );
return( psa_hash_abort( &hmac->hash_ctx ) );
mbedtls_platform_zeroize(hmac->opad, sizeof(hmac->opad));
return psa_hash_abort(&hmac->hash_ctx);
}
static psa_status_t psa_hmac_setup_internal(
mbedtls_psa_hmac_operation_t *hmac,
const uint8_t *key,
size_t key_length,
psa_algorithm_t hash_alg )
psa_algorithm_t hash_alg)
{
uint8_t ipad[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
size_t i;
size_t hash_size = PSA_HASH_LENGTH( hash_alg );
size_t block_size = PSA_HASH_BLOCK_LENGTH( hash_alg );
size_t hash_size = PSA_HASH_LENGTH(hash_alg);
size_t block_size = PSA_HASH_BLOCK_LENGTH(hash_alg);
psa_status_t status;
hmac->alg = hash_alg;
@ -59,134 +59,149 @@ static psa_status_t psa_hmac_setup_internal(
/* The size checks against the ipad and opad buffers cannot be written
* `block_size > sizeof( ipad ) || block_size > sizeof( hmac->opad )`
* because that triggers -Wlogical-op on GCC 7.3. */
if( block_size > sizeof( ipad ) )
return( PSA_ERROR_NOT_SUPPORTED );
if( block_size > sizeof( hmac->opad ) )
return( PSA_ERROR_NOT_SUPPORTED );
if( block_size < hash_size )
return( PSA_ERROR_NOT_SUPPORTED );
if (block_size > sizeof(ipad)) {
return PSA_ERROR_NOT_SUPPORTED;
}
if (block_size > sizeof(hmac->opad)) {
return PSA_ERROR_NOT_SUPPORTED;
}
if (block_size < hash_size) {
return PSA_ERROR_NOT_SUPPORTED;
}
if( key_length > block_size )
{
status = psa_hash_compute( hash_alg, key, key_length,
ipad, sizeof( ipad ), &key_length );
if( status != PSA_SUCCESS )
if (key_length > block_size) {
status = psa_hash_compute(hash_alg, key, key_length,
ipad, sizeof(ipad), &key_length);
if (status != PSA_SUCCESS) {
goto cleanup;
}
}
/* A 0-length key is not commonly used in HMAC when used as a MAC,
* but it is permitted. It is common when HMAC is used in HKDF, for
* example. Don't call `memcpy` in the 0-length because `key` could be
* an invalid pointer which would make the behavior undefined. */
else if( key_length != 0 )
memcpy( ipad, key, key_length );
else if (key_length != 0) {
memcpy(ipad, key, key_length);
}
/* ipad contains the key followed by garbage. Xor and fill with 0x36
* to create the ipad value. */
for( i = 0; i < key_length; i++ )
for (i = 0; i < key_length; i++) {
ipad[i] ^= 0x36;
memset( ipad + key_length, 0x36, block_size - key_length );
}
memset(ipad + key_length, 0x36, block_size - key_length);
/* Copy the key material from ipad to opad, flipping the requisite bits,
* and filling the rest of opad with the requisite constant. */
for( i = 0; i < key_length; i++ )
for (i = 0; i < key_length; i++) {
hmac->opad[i] = ipad[i] ^ 0x36 ^ 0x5C;
memset( hmac->opad + key_length, 0x5C, block_size - key_length );
}
memset(hmac->opad + key_length, 0x5C, block_size - key_length);
status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
if( status != PSA_SUCCESS )
status = psa_hash_setup(&hmac->hash_ctx, hash_alg);
if (status != PSA_SUCCESS) {
goto cleanup;
}
status = psa_hash_update( &hmac->hash_ctx, ipad, block_size );
status = psa_hash_update(&hmac->hash_ctx, ipad, block_size);
cleanup:
mbedtls_platform_zeroize( ipad, sizeof( ipad ) );
mbedtls_platform_zeroize(ipad, sizeof(ipad));
return( status );
return status;
}
static psa_status_t psa_hmac_update_internal(
mbedtls_psa_hmac_operation_t *hmac,
const uint8_t *data,
size_t data_length )
size_t data_length)
{
return( psa_hash_update( &hmac->hash_ctx, data, data_length ) );
return psa_hash_update(&hmac->hash_ctx, data, data_length);
}
static psa_status_t psa_hmac_finish_internal(
mbedtls_psa_hmac_operation_t *hmac,
uint8_t *mac,
size_t mac_size )
size_t mac_size)
{
uint8_t tmp[PSA_HASH_MAX_SIZE];
psa_algorithm_t hash_alg = hmac->alg;
size_t hash_size = 0;
size_t block_size = PSA_HASH_BLOCK_LENGTH( hash_alg );
size_t block_size = PSA_HASH_BLOCK_LENGTH(hash_alg);
psa_status_t status;
status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
if( status != PSA_SUCCESS )
return( status );
status = psa_hash_finish(&hmac->hash_ctx, tmp, sizeof(tmp), &hash_size);
if (status != PSA_SUCCESS) {
return status;
}
/* From here on, tmp needs to be wiped. */
status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
if( status != PSA_SUCCESS )
status = psa_hash_setup(&hmac->hash_ctx, hash_alg);
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_hash_update( &hmac->hash_ctx, hmac->opad, block_size );
if( status != PSA_SUCCESS )
status = psa_hash_update(&hmac->hash_ctx, hmac->opad, block_size);
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_hash_update( &hmac->hash_ctx, tmp, hash_size );
if( status != PSA_SUCCESS )
status = psa_hash_update(&hmac->hash_ctx, tmp, hash_size);
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
if( status != PSA_SUCCESS )
status = psa_hash_finish(&hmac->hash_ctx, tmp, sizeof(tmp), &hash_size);
if (status != PSA_SUCCESS) {
goto exit;
}
memcpy( mac, tmp, mac_size );
memcpy(mac, tmp, mac_size);
exit:
mbedtls_platform_zeroize( tmp, hash_size );
return( status );
mbedtls_platform_zeroize(tmp, hash_size);
return status;
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC)
static psa_status_t cmac_setup( mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer )
static psa_status_t cmac_setup(mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(PSA_WANT_KEY_TYPE_DES)
/* Mbed TLS CMAC does not accept 3DES with only two keys, nor does it accept
* to do CMAC with pure DES, so return NOT_SUPPORTED here. */
if( psa_get_key_type( attributes ) == PSA_KEY_TYPE_DES &&
( psa_get_key_bits( attributes ) == 64 ||
psa_get_key_bits( attributes ) == 128 ) )
return( PSA_ERROR_NOT_SUPPORTED );
if (psa_get_key_type(attributes) == PSA_KEY_TYPE_DES &&
(psa_get_key_bits(attributes) == 64 ||
psa_get_key_bits(attributes) == 128)) {
return PSA_ERROR_NOT_SUPPORTED;
}
#endif
const mbedtls_cipher_info_t * cipher_info =
const mbedtls_cipher_info_t *cipher_info =
mbedtls_cipher_info_from_psa(
PSA_ALG_CMAC,
psa_get_key_type( attributes ),
psa_get_key_bits( attributes ),
NULL );
psa_get_key_type(attributes),
psa_get_key_bits(attributes),
NULL);
if( cipher_info == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
if (cipher_info == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
ret = mbedtls_cipher_setup( &operation->ctx.cmac, cipher_info );
if( ret != 0 )
ret = mbedtls_cipher_setup(&operation->ctx.cmac, cipher_info);
if (ret != 0) {
goto exit;
}
ret = mbedtls_cipher_cmac_starts( &operation->ctx.cmac,
key_buffer,
psa_get_key_bits( attributes ) );
ret = mbedtls_cipher_cmac_starts(&operation->ctx.cmac,
key_buffer,
psa_get_key_bits(attributes));
exit:
return( mbedtls_to_psa_error( ret ) );
return mbedtls_to_psa_error(ret);
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */
@ -197,62 +212,53 @@ exit:
* called, mbedtls_psa_mac_abort can run and will do the right thing. */
static psa_status_t mac_init(
mbedtls_psa_mac_operation_t *operation,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
operation->alg = alg;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
mbedtls_cipher_init( &operation->ctx.cmac );
if (PSA_ALG_FULL_LENGTH_MAC(operation->alg) == PSA_ALG_CMAC) {
mbedtls_cipher_init(&operation->ctx.cmac);
status = PSA_SUCCESS;
}
else
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
if (PSA_ALG_IS_HMAC(operation->alg)) {
/* We'll set up the hash operation later in psa_hmac_setup_internal. */
operation->ctx.hmac.alg = 0;
status = PSA_SUCCESS;
}
else
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
{
(void) operation;
status = PSA_ERROR_NOT_SUPPORTED;
}
if( status != PSA_SUCCESS )
memset( operation, 0, sizeof( *operation ) );
return( status );
if (status != PSA_SUCCESS) {
memset(operation, 0, sizeof(*operation));
}
return status;
}
psa_status_t mbedtls_psa_mac_abort( mbedtls_psa_mac_operation_t *operation )
psa_status_t mbedtls_psa_mac_abort(mbedtls_psa_mac_operation_t *operation)
{
if( operation->alg == 0 )
{
if (operation->alg == 0) {
/* The object has (apparently) been initialized but it is not
* in use. It's ok to call abort on such an object, and there's
* nothing to do. */
return( PSA_SUCCESS );
}
else
return PSA_SUCCESS;
} else
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
mbedtls_cipher_free( &operation->ctx.cmac );
}
else
if (PSA_ALG_FULL_LENGTH_MAC(operation->alg) == PSA_ALG_CMAC) {
mbedtls_cipher_free(&operation->ctx.cmac);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
psa_hmac_abort_internal( &operation->ctx.hmac );
}
else
if (PSA_ALG_IS_HMAC(operation->alg)) {
psa_hmac_abort_internal(&operation->ctx.hmac);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
{
/* Sanity check (shouldn't happen: operation->alg should
@ -262,52 +268,50 @@ psa_status_t mbedtls_psa_mac_abort( mbedtls_psa_mac_operation_t *operation )
operation->alg = 0;
return( PSA_SUCCESS );
return PSA_SUCCESS;
bad_state:
/* If abort is called on an uninitialized object, we can't trust
* anything. Wipe the object in case it contains confidential data.
* This may result in a memory leak if a pointer gets overwritten,
* but it's too late to do anything about this. */
memset( operation, 0, sizeof( *operation ) );
return( PSA_ERROR_BAD_STATE );
memset(operation, 0, sizeof(*operation));
return PSA_ERROR_BAD_STATE;
}
static psa_status_t psa_mac_setup( mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
static psa_status_t psa_mac_setup(mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
/* A context must be freshly initialized before it can be set up. */
if( operation->alg != 0 )
return( PSA_ERROR_BAD_STATE );
if (operation->alg != 0) {
return PSA_ERROR_BAD_STATE;
}
status = mac_init( operation, alg );
if( status != PSA_SUCCESS )
return( status );
status = mac_init(operation, alg);
if (status != PSA_SUCCESS) {
return status;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( alg ) == PSA_ALG_CMAC )
{
if (PSA_ALG_FULL_LENGTH_MAC(alg) == PSA_ALG_CMAC) {
/* Key buffer size for CMAC is dictated by the key bits set on the
* attributes, and previously validated by the core on key import. */
(void) key_buffer_size;
status = cmac_setup( operation, attributes, key_buffer );
}
else
status = cmac_setup(operation, attributes, key_buffer);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( alg ) )
{
status = psa_hmac_setup_internal( &operation->ctx.hmac,
key_buffer,
key_buffer_size,
PSA_ALG_HMAC_GET_HASH( alg ) );
}
else
if (PSA_ALG_IS_HMAC(alg)) {
status = psa_hmac_setup_internal(&operation->ctx.hmac,
key_buffer,
key_buffer_size,
PSA_ALG_HMAC_GET_HASH(alg));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
{
(void) attributes;
@ -316,10 +320,11 @@ static psa_status_t psa_mac_setup( mbedtls_psa_mac_operation_t *operation,
status = PSA_ERROR_NOT_SUPPORTED;
}
if( status != PSA_SUCCESS )
mbedtls_psa_mac_abort( operation );
if (status != PSA_SUCCESS) {
mbedtls_psa_mac_abort(operation);
}
return( status );
return status;
}
psa_status_t mbedtls_psa_mac_sign_setup(
@ -327,10 +332,10 @@ psa_status_t mbedtls_psa_mac_sign_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
return( psa_mac_setup( operation, attributes,
key_buffer, key_buffer_size, alg ) );
return psa_mac_setup(operation, attributes,
key_buffer, key_buffer_size, alg);
}
psa_status_t mbedtls_psa_mac_verify_setup(
@ -338,69 +343,63 @@ psa_status_t mbedtls_psa_mac_verify_setup(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
return( psa_mac_setup( operation, attributes,
key_buffer, key_buffer_size, alg ) );
return psa_mac_setup(operation, attributes,
key_buffer, key_buffer_size, alg);
}
psa_status_t mbedtls_psa_mac_update(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length )
size_t input_length)
{
if( operation->alg == 0 )
return( PSA_ERROR_BAD_STATE );
if (operation->alg == 0) {
return PSA_ERROR_BAD_STATE;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
return( mbedtls_to_psa_error(
mbedtls_cipher_cmac_update( &operation->ctx.cmac,
input, input_length ) ) );
}
else
if (PSA_ALG_FULL_LENGTH_MAC(operation->alg) == PSA_ALG_CMAC) {
return mbedtls_to_psa_error(
mbedtls_cipher_cmac_update(&operation->ctx.cmac,
input, input_length));
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
return( psa_hmac_update_internal( &operation->ctx.hmac,
input, input_length ) );
}
else
if (PSA_ALG_IS_HMAC(operation->alg)) {
return psa_hmac_update_internal(&operation->ctx.hmac,
input, input_length);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
{
/* This shouldn't happen if `operation` was initialized by
* a setup function. */
(void) input;
(void) input_length;
return( PSA_ERROR_BAD_STATE );
return PSA_ERROR_BAD_STATE;
}
}
static psa_status_t psa_mac_finish_internal(
mbedtls_psa_mac_operation_t *operation,
uint8_t *mac, size_t mac_size )
uint8_t *mac, size_t mac_size)
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
if (PSA_ALG_FULL_LENGTH_MAC(operation->alg) == PSA_ALG_CMAC) {
uint8_t tmp[PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE];
int ret = mbedtls_cipher_cmac_finish( &operation->ctx.cmac, tmp );
if( ret == 0 )
memcpy( mac, tmp, mac_size );
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
return( mbedtls_to_psa_error( ret ) );
}
else
int ret = mbedtls_cipher_cmac_finish(&operation->ctx.cmac, tmp);
if (ret == 0) {
memcpy(mac, tmp, mac_size);
}
mbedtls_platform_zeroize(tmp, sizeof(tmp));
return mbedtls_to_psa_error(ret);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
return( psa_hmac_finish_internal( &operation->ctx.hmac,
mac, mac_size ) );
}
else
if (PSA_ALG_IS_HMAC(operation->alg)) {
return psa_hmac_finish_internal(&operation->ctx.hmac,
mac, mac_size);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
{
/* This shouldn't happen if `operation` was initialized by
@ -408,7 +407,7 @@ static psa_status_t psa_mac_finish_internal(
(void) operation;
(void) mac;
(void) mac_size;
return( PSA_ERROR_BAD_STATE );
return PSA_ERROR_BAD_STATE;
}
}
@ -416,46 +415,52 @@ psa_status_t mbedtls_psa_mac_sign_finish(
mbedtls_psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
size_t *mac_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->alg == 0 )
return( PSA_ERROR_BAD_STATE );
if (operation->alg == 0) {
return PSA_ERROR_BAD_STATE;
}
status = psa_mac_finish_internal( operation, mac, mac_size );
if( status == PSA_SUCCESS )
status = psa_mac_finish_internal(operation, mac, mac_size);
if (status == PSA_SUCCESS) {
*mac_length = mac_size;
}
return( status );
return status;
}
psa_status_t mbedtls_psa_mac_verify_finish(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length )
size_t mac_length)
{
uint8_t actual_mac[PSA_MAC_MAX_SIZE];
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->alg == 0 )
return( PSA_ERROR_BAD_STATE );
if (operation->alg == 0) {
return PSA_ERROR_BAD_STATE;
}
/* Consistency check: requested MAC length fits our local buffer */
if( mac_length > sizeof( actual_mac ) )
return( PSA_ERROR_INVALID_ARGUMENT );
if (mac_length > sizeof(actual_mac)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
status = psa_mac_finish_internal( operation, actual_mac, mac_length );
if( status != PSA_SUCCESS )
status = psa_mac_finish_internal(operation, actual_mac, mac_length);
if (status != PSA_SUCCESS) {
goto cleanup;
}
if( mbedtls_psa_safer_memcmp( mac, actual_mac, mac_length ) != 0 )
if (mbedtls_psa_safer_memcmp(mac, actual_mac, mac_length) != 0) {
status = PSA_ERROR_INVALID_SIGNATURE;
}
cleanup:
mbedtls_platform_zeroize( actual_mac, sizeof( actual_mac ) );
mbedtls_platform_zeroize(actual_mac, sizeof(actual_mac));
return( status );
return status;
}
psa_status_t mbedtls_psa_mac_compute(
@ -467,32 +472,34 @@ psa_status_t mbedtls_psa_mac_compute(
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
size_t *mac_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_mac_operation_t operation = MBEDTLS_PSA_MAC_OPERATION_INIT;
status = psa_mac_setup( &operation,
attributes, key_buffer, key_buffer_size,
alg );
if( status != PSA_SUCCESS )
status = psa_mac_setup(&operation,
attributes, key_buffer, key_buffer_size,
alg);
if (status != PSA_SUCCESS) {
goto exit;
if( input_length > 0 )
{
status = mbedtls_psa_mac_update( &operation, input, input_length );
if( status != PSA_SUCCESS )
goto exit;
}
status = psa_mac_finish_internal( &operation, mac, mac_size );
if( status == PSA_SUCCESS )
if (input_length > 0) {
status = mbedtls_psa_mac_update(&operation, input, input_length);
if (status != PSA_SUCCESS) {
goto exit;
}
}
status = psa_mac_finish_internal(&operation, mac, mac_size);
if (status == PSA_SUCCESS) {
*mac_length = mac_size;
}
exit:
mbedtls_psa_mac_abort( &operation );
mbedtls_psa_mac_abort(&operation);
return( status );
return status;
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC || MBEDTLS_PSA_BUILTIN_ALG_CMAC */

View File

@ -164,7 +164,7 @@ psa_status_t mbedtls_psa_mac_verify_setup(
psa_status_t mbedtls_psa_mac_update(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length );
size_t input_length);
/** Finish the calculation of the MAC of a message using Mbed TLS.
*
@ -207,7 +207,7 @@ psa_status_t mbedtls_psa_mac_sign_finish(
mbedtls_psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length );
size_t *mac_length);
/** Finish the calculation of the MAC of a message and compare it with
* an expected value using Mbed TLS.
@ -247,7 +247,7 @@ psa_status_t mbedtls_psa_mac_sign_finish(
psa_status_t mbedtls_psa_mac_verify_finish(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length );
size_t mac_length);
/** Abort a MAC operation using Mbed TLS.
*
@ -271,6 +271,6 @@ psa_status_t mbedtls_psa_mac_verify_finish(
* \retval #PSA_ERROR_CORRUPTION_DETECTED
*/
psa_status_t mbedtls_psa_mac_abort(
mbedtls_psa_mac_operation_t *operation );
mbedtls_psa_mac_operation_t *operation);
#endif /* PSA_CRYPTO_MAC_H */

File diff suppressed because it is too large Load Diff

View File

@ -41,9 +41,9 @@
typedef mbedtls_psa_external_random_context_t mbedtls_psa_random_context_t;
/* Trivial wrapper around psa_generate_random(). */
int mbedtls_psa_get_random( void *p_rng,
unsigned char *output,
size_t output_size );
int mbedtls_psa_get_random(void *p_rng,
unsigned char *output,
size_t output_size);
/* The PSA RNG API doesn't need any externally maintained state. */
#define MBEDTLS_PSA_RANDOM_STATE NULL
@ -89,12 +89,12 @@ int mbedtls_psa_get_random( void *p_rng,
*
* \param p_rng Pointer to the Mbed TLS DRBG state.
*/
static inline void mbedtls_psa_drbg_init( mbedtls_psa_drbg_context_t *p_rng )
static inline void mbedtls_psa_drbg_init(mbedtls_psa_drbg_context_t *p_rng)
{
#if defined(MBEDTLS_CTR_DRBG_C)
mbedtls_ctr_drbg_init( p_rng );
mbedtls_ctr_drbg_init(p_rng);
#elif defined(MBEDTLS_HMAC_DRBG_C)
mbedtls_hmac_drbg_init( p_rng );
mbedtls_hmac_drbg_init(p_rng);
#endif
}
@ -102,12 +102,12 @@ static inline void mbedtls_psa_drbg_init( mbedtls_psa_drbg_context_t *p_rng )
*
* \param p_rng Pointer to the Mbed TLS DRBG state.
*/
static inline void mbedtls_psa_drbg_free( mbedtls_psa_drbg_context_t *p_rng )
static inline void mbedtls_psa_drbg_free(mbedtls_psa_drbg_context_t *p_rng)
{
#if defined(MBEDTLS_CTR_DRBG_C)
mbedtls_ctr_drbg_free( p_rng );
mbedtls_ctr_drbg_free(p_rng);
#elif defined(MBEDTLS_HMAC_DRBG_C)
mbedtls_hmac_drbg_free( p_rng );
mbedtls_hmac_drbg_free(p_rng);
#endif
}
@ -116,10 +116,9 @@ static inline void mbedtls_psa_drbg_free( mbedtls_psa_drbg_context_t *p_rng )
* The random generator context is composed of an entropy context and
* a DRBG context.
*/
typedef struct
{
void (* entropy_init )( mbedtls_entropy_context *ctx );
void (* entropy_free )( mbedtls_entropy_context *ctx );
typedef struct {
void (* entropy_init)(mbedtls_entropy_context *ctx);
void (* entropy_free)(mbedtls_entropy_context *ctx);
mbedtls_entropy_context entropy;
mbedtls_psa_drbg_context_t drbg;
} mbedtls_psa_random_context_t;
@ -182,21 +181,21 @@ extern mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state;
*/
static inline int mbedtls_psa_drbg_seed(
mbedtls_entropy_context *entropy,
const unsigned char *custom, size_t len )
const unsigned char *custom, size_t len)
{
#if defined(MBEDTLS_CTR_DRBG_C)
return( mbedtls_ctr_drbg_seed( MBEDTLS_PSA_RANDOM_STATE,
mbedtls_entropy_func,
entropy,
custom, len ) );
return mbedtls_ctr_drbg_seed(MBEDTLS_PSA_RANDOM_STATE,
mbedtls_entropy_func,
entropy,
custom, len);
#elif defined(MBEDTLS_HMAC_DRBG_C)
const mbedtls_md_info_t *md_info =
mbedtls_md_info_from_type( MBEDTLS_PSA_HMAC_DRBG_MD_TYPE );
return( mbedtls_hmac_drbg_seed( MBEDTLS_PSA_RANDOM_STATE,
md_info,
mbedtls_entropy_func,
entropy,
custom, len ) );
mbedtls_md_info_from_type(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE);
return mbedtls_hmac_drbg_seed(MBEDTLS_PSA_RANDOM_STATE,
md_info,
mbedtls_entropy_func,
entropy,
custom, len);
#endif
}

View File

@ -52,46 +52,47 @@
* way to return the exact bit size of a key.
* To keep things simple, reject non-byte-aligned key sizes. */
static psa_status_t psa_check_rsa_key_byte_aligned(
const mbedtls_rsa_context *rsa )
const mbedtls_rsa_context *rsa)
{
mbedtls_mpi n;
psa_status_t status;
mbedtls_mpi_init( &n );
mbedtls_mpi_init(&n);
status = mbedtls_to_psa_error(
mbedtls_rsa_export( rsa, &n, NULL, NULL, NULL, NULL ) );
if( status == PSA_SUCCESS )
{
if( mbedtls_mpi_bitlen( &n ) % 8 != 0 )
mbedtls_rsa_export(rsa, &n, NULL, NULL, NULL, NULL));
if (status == PSA_SUCCESS) {
if (mbedtls_mpi_bitlen(&n) % 8 != 0) {
status = PSA_ERROR_NOT_SUPPORTED;
}
}
mbedtls_mpi_free( &n );
return( status );
mbedtls_mpi_free(&n);
return status;
}
psa_status_t mbedtls_psa_rsa_load_representation(
psa_key_type_t type, const uint8_t *data, size_t data_length,
mbedtls_rsa_context **p_rsa )
mbedtls_rsa_context **p_rsa)
{
psa_status_t status;
mbedtls_pk_context ctx;
size_t bits;
mbedtls_pk_init( &ctx );
mbedtls_pk_init(&ctx);
/* Parse the data. */
if( PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
if (PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
status = mbedtls_to_psa_error(
mbedtls_pk_parse_key( &ctx, data, data_length, NULL, 0,
mbedtls_psa_get_random, MBEDTLS_PSA_RANDOM_STATE ) );
else
mbedtls_pk_parse_key(&ctx, data, data_length, NULL, 0,
mbedtls_psa_get_random, MBEDTLS_PSA_RANDOM_STATE));
} else {
status = mbedtls_to_psa_error(
mbedtls_pk_parse_public_key( &ctx, data, data_length ) );
if( status != PSA_SUCCESS )
mbedtls_pk_parse_public_key(&ctx, data, data_length));
}
if (status != PSA_SUCCESS) {
goto exit;
}
/* We have something that the pkparse module recognizes. If it is a
* valid RSA key, store it. */
if( mbedtls_pk_get_type( &ctx ) != MBEDTLS_PK_RSA )
{
if (mbedtls_pk_get_type(&ctx) != MBEDTLS_PK_RSA) {
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
@ -99,24 +100,24 @@ psa_status_t mbedtls_psa_rsa_load_representation(
/* The size of an RSA key doesn't have to be a multiple of 8. Mbed TLS
* supports non-byte-aligned key sizes, but not well. For example,
* mbedtls_rsa_get_len() returns the key size in bytes, not in bits. */
bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( mbedtls_pk_rsa( ctx ) ) );
if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
{
bits = PSA_BYTES_TO_BITS(mbedtls_rsa_get_len(mbedtls_pk_rsa(ctx)));
if (bits > PSA_VENDOR_RSA_MAX_KEY_BITS) {
status = PSA_ERROR_NOT_SUPPORTED;
goto exit;
}
status = psa_check_rsa_key_byte_aligned( mbedtls_pk_rsa( ctx ) );
if( status != PSA_SUCCESS )
status = psa_check_rsa_key_byte_aligned(mbedtls_pk_rsa(ctx));
if (status != PSA_SUCCESS) {
goto exit;
}
/* Copy out the pointer to the RSA context, and reset the PK context
* such that pk_free doesn't free the RSA context we just grabbed. */
*p_rsa = mbedtls_pk_rsa( ctx );
*p_rsa = mbedtls_pk_rsa(ctx);
ctx.pk_info = NULL;
exit:
mbedtls_pk_free( &ctx );
return( status );
mbedtls_pk_free(&ctx);
return status;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) ||
@ -132,179 +133,182 @@ psa_status_t mbedtls_psa_rsa_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits )
size_t *key_buffer_length, size_t *bits)
{
psa_status_t status;
mbedtls_rsa_context *rsa = NULL;
/* Parse input */
status = mbedtls_psa_rsa_load_representation( attributes->core.type,
data,
data_length,
&rsa );
if( status != PSA_SUCCESS )
status = mbedtls_psa_rsa_load_representation(attributes->core.type,
data,
data_length,
&rsa);
if (status != PSA_SUCCESS) {
goto exit;
}
*bits = (psa_key_bits_t) PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( rsa ) );
*bits = (psa_key_bits_t) PSA_BYTES_TO_BITS(mbedtls_rsa_get_len(rsa));
/* Re-export the data to PSA export format, such that we can store export
* representation in the key slot. Export representation in case of RSA is
* the smallest representation that's allowed as input, so a straight-up
* allocation of the same size as the input buffer will be large enough. */
status = mbedtls_psa_rsa_export_key( attributes->core.type,
rsa,
key_buffer,
key_buffer_size,
key_buffer_length );
status = mbedtls_psa_rsa_export_key(attributes->core.type,
rsa,
key_buffer,
key_buffer_size,
key_buffer_length);
exit:
/* Always free the RSA object */
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
mbedtls_rsa_free(rsa);
mbedtls_free(rsa);
return( status );
return status;
}
psa_status_t mbedtls_psa_rsa_export_key( psa_key_type_t type,
mbedtls_rsa_context *rsa,
uint8_t *data,
size_t data_size,
size_t *data_length )
psa_status_t mbedtls_psa_rsa_export_key(psa_key_type_t type,
mbedtls_rsa_context *rsa,
uint8_t *data,
size_t data_size,
size_t *data_length)
{
#if defined(MBEDTLS_PK_WRITE_C)
int ret;
mbedtls_pk_context pk;
uint8_t *pos = data + data_size;
mbedtls_pk_init( &pk );
mbedtls_pk_init(&pk);
pk.pk_info = &mbedtls_rsa_info;
pk.pk_ctx = rsa;
/* PSA Crypto API defines the format of an RSA key as a DER-encoded
* representation of the non-encrypted PKCS#1 RSAPrivateKey for a
* private key and of the RFC3279 RSAPublicKey for a public key. */
if( PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
ret = mbedtls_pk_write_key_der( &pk, data, data_size );
else
ret = mbedtls_pk_write_pubkey( &pos, data, &pk );
if (PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
ret = mbedtls_pk_write_key_der(&pk, data, data_size);
} else {
ret = mbedtls_pk_write_pubkey(&pos, data, &pk);
}
if( ret < 0 )
{
if (ret < 0) {
/* Clean up in case pk_write failed halfway through. */
memset( data, 0, data_size );
return( mbedtls_to_psa_error( ret ) );
memset(data, 0, data_size);
return mbedtls_to_psa_error(ret);
}
/* The mbedtls_pk_xxx functions write to the end of the buffer.
* Move the data to the beginning and erase remaining data
* at the original location. */
if( 2 * (size_t) ret <= data_size )
{
memcpy( data, data + data_size - ret, ret );
memset( data + data_size - ret, 0, ret );
}
else if( (size_t) ret < data_size )
{
memmove( data, data + data_size - ret, ret );
memset( data + ret, 0, data_size - ret );
if (2 * (size_t) ret <= data_size) {
memcpy(data, data + data_size - ret, ret);
memset(data + data_size - ret, 0, ret);
} else if ((size_t) ret < data_size) {
memmove(data, data + data_size - ret, ret);
memset(data + ret, 0, data_size - ret);
}
*data_length = ret;
return( PSA_SUCCESS );
return PSA_SUCCESS;
#else
(void) type;
(void) rsa;
(void) data;
(void) data_size;
(void) data_length;
return( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
#endif /* MBEDTLS_PK_WRITE_C */
}
psa_status_t mbedtls_psa_rsa_export_public_key(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length )
uint8_t *data, size_t data_size, size_t *data_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_rsa_context *rsa = NULL;
status = mbedtls_psa_rsa_load_representation(
attributes->core.type, key_buffer, key_buffer_size, &rsa );
if( status != PSA_SUCCESS )
return( status );
attributes->core.type, key_buffer, key_buffer_size, &rsa);
if (status != PSA_SUCCESS) {
return status;
}
status = mbedtls_psa_rsa_export_key( PSA_KEY_TYPE_RSA_PUBLIC_KEY,
rsa,
data,
data_size,
data_length );
status = mbedtls_psa_rsa_export_key(PSA_KEY_TYPE_RSA_PUBLIC_KEY,
rsa,
data,
data_size,
data_length);
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
mbedtls_rsa_free(rsa);
mbedtls_free(rsa);
return( status );
return status;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) && \
defined(MBEDTLS_GENPRIME)
static psa_status_t psa_rsa_read_exponent( const uint8_t *domain_parameters,
size_t domain_parameters_size,
int *exponent )
static psa_status_t psa_rsa_read_exponent(const uint8_t *domain_parameters,
size_t domain_parameters_size,
int *exponent)
{
size_t i;
uint32_t acc = 0;
if( domain_parameters_size == 0 )
{
if (domain_parameters_size == 0) {
*exponent = 65537;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
/* Mbed TLS encodes the public exponent as an int. For simplicity, only
* support values that fit in a 32-bit integer, which is larger than
* int on just about every platform anyway. */
if( domain_parameters_size > sizeof( acc ) )
return( PSA_ERROR_NOT_SUPPORTED );
for( i = 0; i < domain_parameters_size; i++ )
acc = ( acc << 8 ) | domain_parameters[i];
if( acc > INT_MAX )
return( PSA_ERROR_NOT_SUPPORTED );
if (domain_parameters_size > sizeof(acc)) {
return PSA_ERROR_NOT_SUPPORTED;
}
for (i = 0; i < domain_parameters_size; i++) {
acc = (acc << 8) | domain_parameters[i];
}
if (acc > INT_MAX) {
return PSA_ERROR_NOT_SUPPORTED;
}
*exponent = acc;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_rsa_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length )
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
{
psa_status_t status;
mbedtls_rsa_context rsa;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int exponent;
status = psa_rsa_read_exponent( attributes->domain_parameters,
attributes->domain_parameters_size,
&exponent );
if( status != PSA_SUCCESS )
return( status );
status = psa_rsa_read_exponent(attributes->domain_parameters,
attributes->domain_parameters_size,
&exponent);
if (status != PSA_SUCCESS) {
return status;
}
mbedtls_rsa_init( &rsa );
ret = mbedtls_rsa_gen_key( &rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
(unsigned int)attributes->core.bits,
exponent );
if( ret != 0 )
return( mbedtls_to_psa_error( ret ) );
mbedtls_rsa_init(&rsa);
ret = mbedtls_rsa_gen_key(&rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
(unsigned int) attributes->core.bits,
exponent);
if (ret != 0) {
return mbedtls_to_psa_error(ret);
}
status = mbedtls_psa_rsa_export_key( attributes->core.type,
&rsa, key_buffer, key_buffer_size,
key_buffer_length );
mbedtls_rsa_free( &rsa );
status = mbedtls_psa_rsa_export_key(attributes->core.type,
&rsa, key_buffer, key_buffer_size,
key_buffer_length);
mbedtls_rsa_free(&rsa);
return( status );
return status;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR)
* defined(MBEDTLS_GENPRIME) */
@ -318,131 +322,131 @@ psa_status_t mbedtls_psa_rsa_generate_key(
/* Decode the hash algorithm from alg and store the mbedtls encoding in
* md_alg. Verify that the hash length is acceptable. */
static psa_status_t psa_rsa_decode_md_type( psa_algorithm_t alg,
size_t hash_length,
mbedtls_md_type_t *md_alg )
static psa_status_t psa_rsa_decode_md_type(psa_algorithm_t alg,
size_t hash_length,
mbedtls_md_type_t *md_alg)
{
psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg );
*md_alg = mbedtls_hash_info_md_from_psa( hash_alg );
psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH(alg);
*md_alg = mbedtls_hash_info_md_from_psa(hash_alg);
/* The Mbed TLS RSA module uses an unsigned int for hash length
* parameters. Validate that it fits so that we don't risk an
* overflow later. */
#if SIZE_MAX > UINT_MAX
if( hash_length > UINT_MAX )
return( PSA_ERROR_INVALID_ARGUMENT );
if (hash_length > UINT_MAX) {
return PSA_ERROR_INVALID_ARGUMENT;
}
#endif
/* For signatures using a hash, the hash length must be correct. */
if( alg != PSA_ALG_RSA_PKCS1V15_SIGN_RAW )
{
if( *md_alg == MBEDTLS_MD_NONE )
return( PSA_ERROR_NOT_SUPPORTED );
if( mbedtls_hash_info_get_size( *md_alg ) != hash_length )
return( PSA_ERROR_INVALID_ARGUMENT );
if (alg != PSA_ALG_RSA_PKCS1V15_SIGN_RAW) {
if (*md_alg == MBEDTLS_MD_NONE) {
return PSA_ERROR_NOT_SUPPORTED;
}
if (mbedtls_hash_info_get_size(*md_alg) != hash_length) {
return PSA_ERROR_INVALID_ARGUMENT;
}
}
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_rsa_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
uint8_t *signature, size_t signature_size, size_t *signature_length )
uint8_t *signature, size_t signature_size, size_t *signature_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_rsa_context *rsa = NULL;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md_type_t md_alg;
status = mbedtls_psa_rsa_load_representation( attributes->core.type,
key_buffer,
key_buffer_size,
&rsa );
if( status != PSA_SUCCESS )
return( status );
status = mbedtls_psa_rsa_load_representation(attributes->core.type,
key_buffer,
key_buffer_size,
&rsa);
if (status != PSA_SUCCESS) {
return status;
}
status = psa_rsa_decode_md_type( alg, hash_length, &md_alg );
if( status != PSA_SUCCESS )
status = psa_rsa_decode_md_type(alg, hash_length, &md_alg);
if (status != PSA_SUCCESS) {
goto exit;
}
if( signature_size < mbedtls_rsa_get_len( rsa ) )
{
if (signature_size < mbedtls_rsa_get_len(rsa)) {
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN)
if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) )
{
ret = mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE );
if( ret == 0 )
{
ret = mbedtls_rsa_pkcs1_sign( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
md_alg,
(unsigned int) hash_length,
hash,
signature );
if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg)) {
ret = mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE);
if (ret == 0) {
ret = mbedtls_rsa_pkcs1_sign(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
md_alg,
(unsigned int) hash_length,
hash,
signature);
}
}
else
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
if( PSA_ALG_IS_RSA_PSS( alg ) )
{
ret = mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
if (PSA_ALG_IS_RSA_PSS(alg)) {
ret = mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md_alg);
if( ret == 0 )
{
ret = mbedtls_rsa_rsassa_pss_sign( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_MD_NONE,
(unsigned int) hash_length,
hash,
signature );
if (ret == 0) {
ret = mbedtls_rsa_rsassa_pss_sign(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_MD_NONE,
(unsigned int) hash_length,
hash,
signature);
}
}
else
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS */
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
if( ret == 0 )
*signature_length = mbedtls_rsa_get_len( rsa );
status = mbedtls_to_psa_error( ret );
if (ret == 0) {
*signature_length = mbedtls_rsa_get_len(rsa);
}
status = mbedtls_to_psa_error(ret);
exit:
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
mbedtls_rsa_free(rsa);
mbedtls_free(rsa);
return( status );
return status;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
static int rsa_pss_expected_salt_len( psa_algorithm_t alg,
const mbedtls_rsa_context *rsa,
size_t hash_length )
static int rsa_pss_expected_salt_len(psa_algorithm_t alg,
const mbedtls_rsa_context *rsa,
size_t hash_length)
{
if( PSA_ALG_IS_RSA_PSS_ANY_SALT( alg ) )
return( MBEDTLS_RSA_SALT_LEN_ANY );
if (PSA_ALG_IS_RSA_PSS_ANY_SALT(alg)) {
return MBEDTLS_RSA_SALT_LEN_ANY;
}
/* Otherwise: standard salt length, i.e. largest possible salt length
* up to the hash length. */
int klen = (int) mbedtls_rsa_get_len( rsa ); // known to fit
int klen = (int) mbedtls_rsa_get_len(rsa); // known to fit
int hlen = (int) hash_length; // known to fit
int room = klen - 2 - hlen;
if( room < 0 )
return( 0 ); // there is no valid signature in this case anyway
else if( room > hlen )
return( hlen );
else
return( room );
if (room < 0) {
return 0; // there is no valid signature in this case anyway
} else if (room > hlen) {
return hlen;
} else {
return room;
}
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS */
@ -450,63 +454,58 @@ psa_status_t mbedtls_psa_rsa_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
const uint8_t *signature, size_t signature_length )
const uint8_t *signature, size_t signature_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_rsa_context *rsa = NULL;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md_type_t md_alg;
status = mbedtls_psa_rsa_load_representation( attributes->core.type,
key_buffer,
key_buffer_size,
&rsa );
if( status != PSA_SUCCESS )
status = mbedtls_psa_rsa_load_representation(attributes->core.type,
key_buffer,
key_buffer_size,
&rsa);
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_rsa_decode_md_type( alg, hash_length, &md_alg );
if( status != PSA_SUCCESS )
status = psa_rsa_decode_md_type(alg, hash_length, &md_alg);
if (status != PSA_SUCCESS) {
goto exit;
}
if( signature_length != mbedtls_rsa_get_len( rsa ) )
{
if (signature_length != mbedtls_rsa_get_len(rsa)) {
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN)
if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) )
{
ret = mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE );
if( ret == 0 )
{
ret = mbedtls_rsa_pkcs1_verify( rsa,
md_alg,
(unsigned int) hash_length,
hash,
signature );
if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg)) {
ret = mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE);
if (ret == 0) {
ret = mbedtls_rsa_pkcs1_verify(rsa,
md_alg,
(unsigned int) hash_length,
hash,
signature);
}
}
else
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
if( PSA_ALG_IS_RSA_PSS( alg ) )
{
ret = mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
if( ret == 0 )
{
int slen = rsa_pss_expected_salt_len( alg, rsa, hash_length );
ret = mbedtls_rsa_rsassa_pss_verify_ext( rsa,
md_alg,
(unsigned) hash_length,
hash,
md_alg,
slen,
signature );
if (PSA_ALG_IS_RSA_PSS(alg)) {
ret = mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md_alg);
if (ret == 0) {
int slen = rsa_pss_expected_salt_len(alg, rsa, hash_length);
ret = mbedtls_rsa_rsassa_pss_verify_ext(rsa,
md_alg,
(unsigned) hash_length,
hash,
md_alg,
slen,
signature);
}
}
else
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS */
{
status = PSA_ERROR_INVALID_ARGUMENT;
@ -516,15 +515,15 @@ psa_status_t mbedtls_psa_rsa_verify_hash(
/* Mbed TLS distinguishes "invalid padding" from "valid padding but
* the rest of the signature is invalid". This has little use in
* practice and PSA doesn't report this distinction. */
status = ( ret == MBEDTLS_ERR_RSA_INVALID_PADDING ) ?
status = (ret == MBEDTLS_ERR_RSA_INVALID_PADDING) ?
PSA_ERROR_INVALID_SIGNATURE :
mbedtls_to_psa_error( ret );
mbedtls_to_psa_error(ret);
exit:
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
mbedtls_rsa_free(rsa);
mbedtls_free(rsa);
return( status );
return status;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
@ -535,27 +534,27 @@ exit:
/****************************************************************/
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
static int psa_rsa_oaep_set_padding_mode( psa_algorithm_t alg,
mbedtls_rsa_context *rsa )
static int psa_rsa_oaep_set_padding_mode(psa_algorithm_t alg,
mbedtls_rsa_context *rsa)
{
psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH( alg );
mbedtls_md_type_t md_alg = mbedtls_hash_info_md_from_psa( hash_alg );
psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH(alg);
mbedtls_md_type_t md_alg = mbedtls_hash_info_md_from_psa(hash_alg);
return( mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg ) );
return mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md_alg);
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
psa_status_t mbedtls_psa_asymmetric_encrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
psa_status_t mbedtls_psa_asymmetric_encrypt(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
(void) key_buffer;
@ -568,94 +567,88 @@ psa_status_t mbedtls_psa_asymmetric_encrypt( const psa_key_attributes_t *attribu
(void) output_size;
(void) output_length;
if( PSA_KEY_TYPE_IS_RSA( attributes->core.type ) )
{
if (PSA_KEY_TYPE_IS_RSA(attributes->core.type)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
mbedtls_rsa_context *rsa = NULL;
status = mbedtls_psa_rsa_load_representation( attributes->core.type,
key_buffer,
key_buffer_size,
&rsa );
if( status != PSA_SUCCESS )
status = mbedtls_psa_rsa_load_representation(attributes->core.type,
key_buffer,
key_buffer_size,
&rsa);
if (status != PSA_SUCCESS) {
goto rsa_exit;
}
if( output_size < mbedtls_rsa_get_len( rsa ) )
{
if (output_size < mbedtls_rsa_get_len(rsa)) {
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto rsa_exit;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
{
if (alg == PSA_ALG_RSA_PKCS1V15_CRYPT) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
status = mbedtls_to_psa_error(
mbedtls_rsa_pkcs1_encrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
input_length,
input,
output ) );
mbedtls_rsa_pkcs1_encrypt(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
input_length,
input,
output));
#else
status = PSA_ERROR_NOT_SUPPORTED;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
}
else
if( PSA_ALG_IS_RSA_OAEP( alg ) )
{
} else
if (PSA_ALG_IS_RSA_OAEP(alg)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
status = mbedtls_to_psa_error(
psa_rsa_oaep_set_padding_mode( alg, rsa ) );
if( status != PSA_SUCCESS )
psa_rsa_oaep_set_padding_mode(alg, rsa));
if (status != PSA_SUCCESS) {
goto rsa_exit;
}
status = mbedtls_to_psa_error(
mbedtls_rsa_rsaes_oaep_encrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
salt, salt_length,
input_length,
input,
output ) );
mbedtls_rsa_rsaes_oaep_encrypt(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
salt, salt_length,
input_length,
input,
output));
#else
status = PSA_ERROR_NOT_SUPPORTED;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
}
else
{
} else {
status = PSA_ERROR_INVALID_ARGUMENT;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
rsa_exit:
if( status == PSA_SUCCESS )
*output_length = mbedtls_rsa_get_len( rsa );
if (status == PSA_SUCCESS) {
*output_length = mbedtls_rsa_get_len(rsa);
}
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
mbedtls_rsa_free(rsa);
mbedtls_free(rsa);
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
}
else
{
} else {
status = PSA_ERROR_NOT_SUPPORTED;
}
return status;
}
psa_status_t mbedtls_psa_asymmetric_decrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
psa_status_t mbedtls_psa_asymmetric_decrypt(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
(void) key_buffer;
@ -670,78 +663,71 @@ psa_status_t mbedtls_psa_asymmetric_decrypt( const psa_key_attributes_t *attribu
*output_length = 0;
if( attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
{
if (attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
mbedtls_rsa_context *rsa = NULL;
status = mbedtls_psa_rsa_load_representation( attributes->core.type,
key_buffer,
key_buffer_size,
&rsa );
if( status != PSA_SUCCESS )
status = mbedtls_psa_rsa_load_representation(attributes->core.type,
key_buffer,
key_buffer_size,
&rsa);
if (status != PSA_SUCCESS) {
goto rsa_exit;
}
if( input_length != mbedtls_rsa_get_len( rsa ) )
{
if (input_length != mbedtls_rsa_get_len(rsa)) {
status = PSA_ERROR_INVALID_ARGUMENT;
goto rsa_exit;
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
{
if (alg == PSA_ALG_RSA_PKCS1V15_CRYPT) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
status = mbedtls_to_psa_error(
mbedtls_rsa_pkcs1_decrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
output_length,
input,
output,
output_size ) );
mbedtls_rsa_pkcs1_decrypt(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
output_length,
input,
output,
output_size));
#else
status = PSA_ERROR_NOT_SUPPORTED;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
}
else
if( PSA_ALG_IS_RSA_OAEP( alg ) )
{
} else
if (PSA_ALG_IS_RSA_OAEP(alg)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
status = mbedtls_to_psa_error(
psa_rsa_oaep_set_padding_mode( alg, rsa ) );
if( status != PSA_SUCCESS )
psa_rsa_oaep_set_padding_mode(alg, rsa));
if (status != PSA_SUCCESS) {
goto rsa_exit;
}
status = mbedtls_to_psa_error(
mbedtls_rsa_rsaes_oaep_decrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
salt, salt_length,
output_length,
input,
output,
output_size ) );
mbedtls_rsa_rsaes_oaep_decrypt(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
salt, salt_length,
output_length,
input,
output,
output_size));
#else
status = PSA_ERROR_NOT_SUPPORTED;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
}
else
{
} else {
status = PSA_ERROR_INVALID_ARGUMENT;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
rsa_exit:
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
mbedtls_rsa_free(rsa);
mbedtls_free(rsa);
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
}
else
{
} else {
status = PSA_ERROR_NOT_SUPPORTED;
}

View File

@ -34,10 +34,10 @@
* contents of the context and the context itself
* when done.
*/
psa_status_t mbedtls_psa_rsa_load_representation( psa_key_type_t type,
const uint8_t *data,
size_t data_length,
mbedtls_rsa_context **p_rsa );
psa_status_t mbedtls_psa_rsa_load_representation(psa_key_type_t type,
const uint8_t *data,
size_t data_length,
mbedtls_rsa_context **p_rsa);
/** Import an RSA key in binary format.
*
@ -69,7 +69,7 @@ psa_status_t mbedtls_psa_rsa_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits );
size_t *key_buffer_length, size_t *bits);
/** Export an RSA key to export representation
*
@ -79,11 +79,11 @@ psa_status_t mbedtls_psa_rsa_import_key(
* \param[in] data_size The length of the buffer to export to
* \param[out] data_length The amount of bytes written to \p data
*/
psa_status_t mbedtls_psa_rsa_export_key( psa_key_type_t type,
mbedtls_rsa_context *rsa,
uint8_t *data,
size_t data_size,
size_t *data_length );
psa_status_t mbedtls_psa_rsa_export_key(psa_key_type_t type,
mbedtls_rsa_context *rsa,
uint8_t *data,
size_t data_size,
size_t *data_length);
/** Export a public RSA key or the public part of an RSA key pair in binary
* format.
@ -112,7 +112,7 @@ psa_status_t mbedtls_psa_rsa_export_key( psa_key_type_t type,
psa_status_t mbedtls_psa_rsa_export_public_key(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length );
uint8_t *data, size_t data_size, size_t *data_length);
/**
* \brief Generate an RSA key.
@ -135,7 +135,7 @@ psa_status_t mbedtls_psa_rsa_export_public_key(
*/
psa_status_t mbedtls_psa_rsa_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length );
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length);
/** Sign an already-calculated hash with an RSA private key.
*
@ -174,7 +174,7 @@ psa_status_t mbedtls_psa_rsa_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
uint8_t *signature, size_t signature_size, size_t *signature_length );
uint8_t *signature, size_t signature_size, size_t *signature_length);
/**
* \brief Verify the signature a hash or short message using a public RSA key.
@ -210,7 +210,7 @@ psa_status_t mbedtls_psa_rsa_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
const uint8_t *signature, size_t signature_length );
const uint8_t *signature, size_t signature_length);
/**
* \brief Encrypt a short message with a public key.
@ -256,17 +256,17 @@ psa_status_t mbedtls_psa_rsa_verify_hash(
* It is implementation-dependent whether a failure to initialize
* results in this error code.
*/
psa_status_t mbedtls_psa_asymmetric_encrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t mbedtls_psa_asymmetric_encrypt(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length);
/**
* \brief Decrypt a short message with a private key.
@ -314,16 +314,16 @@ psa_status_t mbedtls_psa_asymmetric_encrypt( const psa_key_attributes_t *attribu
* It is implementation-dependent whether a failure to initialize
* results in this error code.
*/
psa_status_t mbedtls_psa_asymmetric_decrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t mbedtls_psa_asymmetric_decrypt(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length);
#endif /* PSA_CRYPTO_RSA_H */

View File

@ -48,19 +48,16 @@
/* This structure is identical to psa_drv_se_context_t declared in
* `crypto_se_driver.h`, except that some parts are writable here
* (non-const, or pointer to non-const). */
typedef struct
{
typedef struct {
void *persistent_data;
size_t persistent_data_size;
uintptr_t transient_data;
} psa_drv_se_internal_context_t;
struct psa_se_drv_table_entry_s
{
struct psa_se_drv_table_entry_s {
psa_key_location_t location;
const psa_drv_se_t *methods;
union
{
union {
psa_drv_se_internal_context_t internal;
psa_drv_se_context_t context;
} u;
@ -69,46 +66,49 @@ struct psa_se_drv_table_entry_s
static psa_se_drv_table_entry_t driver_table[PSA_MAX_SE_DRIVERS];
psa_se_drv_table_entry_t *psa_get_se_driver_entry(
psa_key_lifetime_t lifetime )
psa_key_lifetime_t lifetime)
{
size_t i;
psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION( lifetime );
psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
/* In the driver table, location=0 means an entry that isn't used.
* No driver has a location of 0 because it's a reserved value
* (which designates transparent keys). Make sure we never return
* a driver entry for location 0. */
if( location == 0 )
return( NULL );
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
if( driver_table[i].location == location )
return( &driver_table[i] );
if (location == 0) {
return NULL;
}
return( NULL );
for (i = 0; i < PSA_MAX_SE_DRIVERS; i++) {
if (driver_table[i].location == location) {
return &driver_table[i];
}
}
return NULL;
}
const psa_drv_se_t *psa_get_se_driver_methods(
const psa_se_drv_table_entry_t *driver )
const psa_se_drv_table_entry_t *driver)
{
return( driver->methods );
return driver->methods;
}
psa_drv_se_context_t *psa_get_se_driver_context(
psa_se_drv_table_entry_t *driver )
psa_se_drv_table_entry_t *driver)
{
return( &driver->u.context );
return &driver->u.context;
}
int psa_get_se_driver( psa_key_lifetime_t lifetime,
const psa_drv_se_t **p_methods,
psa_drv_se_context_t **p_drv_context)
int psa_get_se_driver(psa_key_lifetime_t lifetime,
const psa_drv_se_t **p_methods,
psa_drv_se_context_t **p_drv_context)
{
psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry( lifetime );
if( p_methods != NULL )
*p_methods = ( driver ? driver->methods : NULL );
if( p_drv_context != NULL )
*p_drv_context = ( driver ? &driver->u.context : NULL );
return( driver != NULL );
psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry(lifetime);
if (p_methods != NULL) {
*p_methods = (driver ? driver->methods : NULL);
}
if (p_drv_context != NULL) {
*p_drv_context = (driver ? &driver->u.context : NULL);
}
return driver != NULL;
}
@ -119,32 +119,35 @@ int psa_get_se_driver( psa_key_lifetime_t lifetime,
static psa_status_t psa_get_se_driver_its_file_uid(
const psa_se_drv_table_entry_t *driver,
psa_storage_uid_t *uid )
psa_storage_uid_t *uid)
{
if( driver->location > PSA_MAX_SE_LOCATION )
return( PSA_ERROR_NOT_SUPPORTED );
if (driver->location > PSA_MAX_SE_LOCATION) {
return PSA_ERROR_NOT_SUPPORTED;
}
#if SIZE_MAX > UINT32_MAX
/* ITS file sizes are limited to 32 bits. */
if( driver->u.internal.persistent_data_size > UINT32_MAX )
return( PSA_ERROR_NOT_SUPPORTED );
if (driver->u.internal.persistent_data_size > UINT32_MAX) {
return PSA_ERROR_NOT_SUPPORTED;
}
#endif
/* See the documentation of PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE. */
*uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + driver->location;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t psa_load_se_persistent_data(
const psa_se_drv_table_entry_t *driver )
const psa_se_drv_table_entry_t *driver)
{
psa_status_t status;
psa_storage_uid_t uid;
size_t length;
status = psa_get_se_driver_its_file_uid( driver, &uid );
if( status != PSA_SUCCESS )
return( status );
status = psa_get_se_driver_its_file_uid(driver, &uid);
if (status != PSA_SUCCESS) {
return status;
}
/* Read the amount of persistent data that the driver requests.
* If the data in storage is larger, it is truncated. If the data
@ -153,97 +156,98 @@ psa_status_t psa_load_se_persistent_data(
/* psa_get_se_driver_its_file_uid ensures that the size_t
* persistent_data_size is in range, but compilers don't know that,
* so cast to reassure them. */
return( psa_its_get( uid, 0,
(uint32_t) driver->u.internal.persistent_data_size,
driver->u.internal.persistent_data,
&length ) );
return psa_its_get(uid, 0,
(uint32_t) driver->u.internal.persistent_data_size,
driver->u.internal.persistent_data,
&length);
}
psa_status_t psa_save_se_persistent_data(
const psa_se_drv_table_entry_t *driver )
const psa_se_drv_table_entry_t *driver)
{
psa_status_t status;
psa_storage_uid_t uid;
status = psa_get_se_driver_its_file_uid( driver, &uid );
if( status != PSA_SUCCESS )
return( status );
status = psa_get_se_driver_its_file_uid(driver, &uid);
if (status != PSA_SUCCESS) {
return status;
}
/* psa_get_se_driver_its_file_uid ensures that the size_t
* persistent_data_size is in range, but compilers don't know that,
* so cast to reassure them. */
return( psa_its_set( uid,
(uint32_t) driver->u.internal.persistent_data_size,
driver->u.internal.persistent_data,
0 ) );
return psa_its_set(uid,
(uint32_t) driver->u.internal.persistent_data_size,
driver->u.internal.persistent_data,
0);
}
psa_status_t psa_destroy_se_persistent_data( psa_key_location_t location )
psa_status_t psa_destroy_se_persistent_data(psa_key_location_t location)
{
psa_storage_uid_t uid;
if( location > PSA_MAX_SE_LOCATION )
return( PSA_ERROR_NOT_SUPPORTED );
if (location > PSA_MAX_SE_LOCATION) {
return PSA_ERROR_NOT_SUPPORTED;
}
uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + location;
return( psa_its_remove( uid ) );
return psa_its_remove(uid);
}
psa_status_t psa_find_se_slot_for_key(
const psa_key_attributes_t *attributes,
psa_key_creation_method_t method,
psa_se_drv_table_entry_t *driver,
psa_key_slot_number_t *slot_number )
psa_key_slot_number_t *slot_number)
{
psa_status_t status;
psa_key_location_t key_location =
PSA_KEY_LIFETIME_GET_LOCATION( psa_get_key_lifetime( attributes ) );
PSA_KEY_LIFETIME_GET_LOCATION(psa_get_key_lifetime(attributes));
/* If the location is wrong, it's a bug in the library. */
if( driver->location != key_location )
return( PSA_ERROR_CORRUPTION_DETECTED );
if (driver->location != key_location) {
return PSA_ERROR_CORRUPTION_DETECTED;
}
/* If the driver doesn't support key creation in any way, give up now. */
if( driver->methods->key_management == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
if (driver->methods->key_management == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
if( psa_get_key_slot_number( attributes, slot_number ) == PSA_SUCCESS )
{
if (psa_get_key_slot_number(attributes, slot_number) == PSA_SUCCESS) {
/* The application wants to use a specific slot. Allow it if
* the driver supports it. On a system with isolation,
* the crypto service must check that the application is
* permitted to request this slot. */
psa_drv_se_validate_slot_number_t p_validate_slot_number =
driver->methods->key_management->p_validate_slot_number;
if( p_validate_slot_number == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
status = p_validate_slot_number( &driver->u.context,
driver->u.internal.persistent_data,
attributes, method,
*slot_number );
}
else if( method == PSA_KEY_CREATION_REGISTER )
{
if (p_validate_slot_number == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
status = p_validate_slot_number(&driver->u.context,
driver->u.internal.persistent_data,
attributes, method,
*slot_number);
} else if (method == PSA_KEY_CREATION_REGISTER) {
/* The application didn't specify a slot number. This doesn't
* make sense when registering a slot. */
return( PSA_ERROR_INVALID_ARGUMENT );
}
else
{
return PSA_ERROR_INVALID_ARGUMENT;
} else {
/* The application didn't tell us which slot to use. Let the driver
* choose. This is the normal case. */
psa_drv_se_allocate_key_t p_allocate =
driver->methods->key_management->p_allocate;
if( p_allocate == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
status = p_allocate( &driver->u.context,
driver->u.internal.persistent_data,
attributes, method,
slot_number );
if (p_allocate == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
status = p_allocate(&driver->u.context,
driver->u.internal.persistent_data,
attributes, method,
slot_number);
}
return( status );
return status;
}
psa_status_t psa_destroy_se_key( psa_se_drv_table_entry_t *driver,
psa_key_slot_number_t slot_number )
psa_status_t psa_destroy_se_key(psa_se_drv_table_entry_t *driver,
psa_key_slot_number_t slot_number)
{
psa_status_t status;
psa_status_t storage_status;
@ -255,40 +259,42 @@ psa_status_t psa_destroy_se_key( psa_se_drv_table_entry_t *driver,
* locked in a read-only state: we can use the keys but not
* destroy them. Hence, if the driver doesn't support destroying
* keys, it's really a lack of permission. */
if( driver->methods->key_management == NULL ||
driver->methods->key_management->p_destroy == NULL )
return( PSA_ERROR_NOT_PERMITTED );
if (driver->methods->key_management == NULL ||
driver->methods->key_management->p_destroy == NULL) {
return PSA_ERROR_NOT_PERMITTED;
}
status = driver->methods->key_management->p_destroy(
&driver->u.context,
driver->u.internal.persistent_data,
slot_number );
storage_status = psa_save_se_persistent_data( driver );
return( status == PSA_SUCCESS ? storage_status : status );
slot_number);
storage_status = psa_save_se_persistent_data(driver);
return status == PSA_SUCCESS ? storage_status : status;
}
psa_status_t psa_init_all_se_drivers( void )
psa_status_t psa_init_all_se_drivers(void)
{
size_t i;
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
for (i = 0; i < PSA_MAX_SE_DRIVERS; i++) {
psa_se_drv_table_entry_t *driver = &driver_table[i];
if( driver->location == 0 )
if (driver->location == 0) {
continue; /* skipping unused entry */
const psa_drv_se_t *methods = psa_get_se_driver_methods( driver );
if( methods->p_init != NULL )
{
}
const psa_drv_se_t *methods = psa_get_se_driver_methods(driver);
if (methods->p_init != NULL) {
psa_status_t status = methods->p_init(
&driver->u.context,
driver->u.internal.persistent_data,
driver->location );
if( status != PSA_SUCCESS )
return( status );
status = psa_save_se_persistent_data( driver );
if( status != PSA_SUCCESS )
return( status );
driver->location);
if (status != PSA_SUCCESS) {
return status;
}
status = psa_save_se_persistent_data(driver);
if (status != PSA_SUCCESS) {
return status;
}
}
}
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
@ -304,70 +310,74 @@ psa_status_t psa_register_se_driver(
size_t i;
psa_status_t status;
if( methods->hal_version != PSA_DRV_SE_HAL_VERSION )
return( PSA_ERROR_NOT_SUPPORTED );
if (methods->hal_version != PSA_DRV_SE_HAL_VERSION) {
return PSA_ERROR_NOT_SUPPORTED;
}
/* Driver table entries are 0-initialized. 0 is not a valid driver
* location because it means a transparent key. */
#if defined(static_assert)
static_assert( PSA_KEY_LOCATION_LOCAL_STORAGE == 0,
"Secure element support requires 0 to mean a local key" );
static_assert(PSA_KEY_LOCATION_LOCAL_STORAGE == 0,
"Secure element support requires 0 to mean a local key");
#endif
if( location == PSA_KEY_LOCATION_LOCAL_STORAGE )
return( PSA_ERROR_INVALID_ARGUMENT );
if( location > PSA_MAX_SE_LOCATION )
return( PSA_ERROR_NOT_SUPPORTED );
if (location == PSA_KEY_LOCATION_LOCAL_STORAGE) {
return PSA_ERROR_INVALID_ARGUMENT;
}
if (location > PSA_MAX_SE_LOCATION) {
return PSA_ERROR_NOT_SUPPORTED;
}
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
if( driver_table[i].location == 0 )
for (i = 0; i < PSA_MAX_SE_DRIVERS; i++) {
if (driver_table[i].location == 0) {
break;
}
/* Check that location isn't already in use up to the first free
* entry. Since entries are created in order and never deleted,
* there can't be a used entry after the first free entry. */
if( driver_table[i].location == location )
return( PSA_ERROR_ALREADY_EXISTS );
if (driver_table[i].location == location) {
return PSA_ERROR_ALREADY_EXISTS;
}
}
if (i == PSA_MAX_SE_DRIVERS) {
return PSA_ERROR_INSUFFICIENT_MEMORY;
}
if( i == PSA_MAX_SE_DRIVERS )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
driver_table[i].location = location;
driver_table[i].methods = methods;
driver_table[i].u.internal.persistent_data_size =
methods->persistent_data_size;
if( methods->persistent_data_size != 0 )
{
if (methods->persistent_data_size != 0) {
driver_table[i].u.internal.persistent_data =
mbedtls_calloc( 1, methods->persistent_data_size );
if( driver_table[i].u.internal.persistent_data == NULL )
{
mbedtls_calloc(1, methods->persistent_data_size);
if (driver_table[i].u.internal.persistent_data == NULL) {
status = PSA_ERROR_INSUFFICIENT_MEMORY;
goto error;
}
/* Load the driver's persistent data. On first use, the persistent
* data does not exist in storage, and is initialized to
* all-bits-zero by the calloc call just above. */
status = psa_load_se_persistent_data( &driver_table[i] );
if( status != PSA_SUCCESS && status != PSA_ERROR_DOES_NOT_EXIST )
status = psa_load_se_persistent_data(&driver_table[i]);
if (status != PSA_SUCCESS && status != PSA_ERROR_DOES_NOT_EXIST) {
goto error;
}
}
return( PSA_SUCCESS );
return PSA_SUCCESS;
error:
memset( &driver_table[i], 0, sizeof( driver_table[i] ) );
return( status );
memset(&driver_table[i], 0, sizeof(driver_table[i]));
return status;
}
void psa_unregister_all_se_drivers( void )
void psa_unregister_all_se_drivers(void)
{
size_t i;
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
if( driver_table[i].u.internal.persistent_data != NULL )
mbedtls_free( driver_table[i].u.internal.persistent_data );
for (i = 0; i < PSA_MAX_SE_DRIVERS; i++) {
if (driver_table[i].u.internal.persistent_data != NULL) {
mbedtls_free(driver_table[i].u.internal.persistent_data);
}
}
memset( driver_table, 0, sizeof( driver_table ) );
memset(driver_table, 0, sizeof(driver_table));
}

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