1
0
mirror of https://github.com/Mbed-TLS/mbedtls.git synced 2025-08-08 17:42:09 +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:52:35 +01:00
parent 480f683d15
commit 1b6c09a62e
391 changed files with 73134 additions and 75084 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->rk), "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

@@ -35,24 +35,25 @@
#if !defined(MBEDTLS_ARC4_ALT)
void mbedtls_arc4_init( mbedtls_arc4_context *ctx )
void mbedtls_arc4_init(mbedtls_arc4_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_arc4_context ) );
memset(ctx, 0, sizeof(mbedtls_arc4_context));
}
void mbedtls_arc4_free( mbedtls_arc4_context *ctx )
void mbedtls_arc4_free(mbedtls_arc4_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_arc4_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_arc4_context));
}
/*
* ARC4 key schedule
*/
void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
unsigned int keylen )
void mbedtls_arc4_setup(mbedtls_arc4_context *ctx, const unsigned char *key,
unsigned int keylen)
{
int i, j, a;
unsigned int k;
@@ -62,17 +63,19 @@ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
ctx->y = 0;
m = ctx->m;
for( i = 0; i < 256; i++ )
for (i = 0; i < 256; i++) {
m[i] = (unsigned char) i;
}
j = k = 0;
for( i = 0; i < 256; i++, k++ )
{
if( k >= keylen ) k = 0;
for (i = 0; i < 256; i++, k++) {
if (k >= keylen) {
k = 0;
}
a = m[i];
j = ( j + a + key[k] ) & 0xFF;
j = (j + a + key[k]) & 0xFF;
m[i] = m[j];
m[j] = (unsigned char) a;
}
@@ -81,8 +84,8 @@ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
/*
* ARC4 cipher function
*/
int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,
unsigned char *output )
int mbedtls_arc4_crypt(mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,
unsigned char *output)
{
int x, y, a, b;
size_t i;
@@ -92,22 +95,21 @@ int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned
y = ctx->y;
m = ctx->m;
for( i = 0; i < length; i++ )
{
x = ( x + 1 ) & 0xFF; a = m[x];
y = ( y + a ) & 0xFF; b = m[y];
for (i = 0; i < length; i++) {
x = (x + 1) & 0xFF; a = m[x];
y = (y + a) & 0xFF; b = m[y];
m[x] = (unsigned char) b;
m[y] = (unsigned char) a;
output[i] = (unsigned char)
( input[i] ^ m[(unsigned char)( a + b )] );
(input[i] ^ m[(unsigned char) (a + b)]);
}
ctx->x = x;
ctx->y = y;
return( 0 );
return 0;
}
#endif /* !MBEDTLS_ARC4_ALT */
@@ -142,45 +144,47 @@ static const unsigned char arc4_test_ct[3][8] =
/*
* Checkup routine
*/
int mbedtls_arc4_self_test( int verbose )
int mbedtls_arc4_self_test(int verbose)
{
int i, ret = 0;
unsigned char ibuf[8];
unsigned char obuf[8];
mbedtls_arc4_context ctx;
mbedtls_arc4_init( &ctx );
mbedtls_arc4_init(&ctx);
for( i = 0; i < 3; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ARC4 test #%d: ", i + 1 );
for (i = 0; i < 3; i++) {
if (verbose != 0) {
mbedtls_printf(" ARC4 test #%d: ", i + 1);
}
memcpy( ibuf, arc4_test_pt[i], 8 );
memcpy(ibuf, arc4_test_pt[i], 8);
mbedtls_arc4_setup( &ctx, arc4_test_key[i], 8 );
mbedtls_arc4_crypt( &ctx, 8, ibuf, obuf );
mbedtls_arc4_setup(&ctx, arc4_test_key[i], 8);
mbedtls_arc4_crypt(&ctx, 8, ibuf, obuf);
if( memcmp( obuf, arc4_test_ct[i], 8 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
if (memcmp(obuf, arc4_test_ct[i], 8) != 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:
mbedtls_arc4_free( &ctx );
mbedtls_arc4_free(&ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_SELF_TEST */

File diff suppressed because it is too large Load Diff

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,105 +260,106 @@ 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_platform_zeroize( seq, sizeof( *seq ) );
mbedtls_free( seq );
mbedtls_platform_zeroize(seq, sizeof(*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;
}
@@ -352,124 +369,128 @@ 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;
}
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));
}
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_asn1_free_named_data( cur );
mbedtls_free( cur );
mbedtls_asn1_free_named_data(cur);
mbedtls_free(cur);
}
}
mbedtls_asn1_named_data *mbedtls_asn1_find_named_data( mbedtls_asn1_named_data *list,
const char *oid, size_t len )
mbedtls_asn1_named_data *mbedtls_asn1_find_named_data(mbedtls_asn1_named_data *list,
const char *oid, size_t len)
{
while( list != NULL )
{
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, unsigned char *start, size_t len )
int mbedtls_asn1_write_len(unsigned char **p, 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, unsigned char *start, unsigned char tag )
int mbedtls_asn1_write_tag(unsigned char **p, 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, unsigned char *start,
const unsigned char *buf, size_t size )
int mbedtls_asn1_write_raw_buffer(unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t size)
{
size_t len = 0;
if( *p < start || (size_t)( *p - start ) < size )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
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, unsigned char *start, const mbedtls_mpi *X )
int mbedtls_asn1_write_mpi(unsigned char **p, 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, unsigned char *start )
int mbedtls_asn1_write_null(unsigned char **p, 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, unsigned char *start,
const char *oid, size_t oid_len )
int mbedtls_asn1_write_oid(unsigned char **p, unsigned char *start,
const char *oid, size_t oid_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
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, unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len )
int mbedtls_asn1_write_algorithm_identifier(unsigned char **p, unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len)
{
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, unsigned char *start, int boolean )
int mbedtls_asn1_write_bool(unsigned char **p, 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, unsigned char *start, int val, int tag )
static int asn1_write_tagged_int(unsigned char **p, 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, unsigned char *start, int val )
int mbedtls_asn1_write_int(unsigned char **p, 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, unsigned char *start, int val )
int mbedtls_asn1_write_enum(unsigned char **p, 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, unsigned char *start, int tag,
const char *text, size_t text_len )
int mbedtls_asn1_write_tagged_string(unsigned char **p, unsigned char *start, int tag,
const char *text, size_t text_len)
{
int ret = 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, unsigned char *start,
const char *text, size_t text_len )
int mbedtls_asn1_write_utf8_string(unsigned char **p, unsigned char *start,
const char *text, size_t text_len)
{
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_UTF8_STRING, text, text_len) );
return mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_UTF8_STRING, text, text_len);
}
int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len )
int mbedtls_asn1_write_printable_string(unsigned char **p, unsigned char *start,
const char *text, size_t text_len)
{
return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_PRINTABLE_STRING, text, text_len) );
return mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_PRINTABLE_STRING, text,
text_len);
}
int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start,
const char *text, size_t text_len )
int mbedtls_asn1_write_ia5_string(unsigned char **p, 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,
unsigned char *start,
const unsigned char *buf,
size_t bits )
int mbedtls_asn1_write_named_bitstring(unsigned char **p,
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, unsigned char *start,
const unsigned char *buf, size_t bits )
int mbedtls_asn1_write_bitstring(unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t bits)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
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, unsigned char *start,
const unsigned char *buf, size_t size )
int mbedtls_asn1_write_octet_string(unsigned char **p, unsigned char *start,
const unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
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

View File

@@ -35,42 +35,42 @@
#if !defined(MBEDTLS_BLOWFISH_ALT)
/* Parameter validation macros */
#define BLOWFISH_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA )
#define BLOWFISH_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define BLOWFISH_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA)
#define BLOWFISH_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
static const uint32_t P[MBEDTLS_BLOWFISH_ROUNDS + 2] = {
0x243F6A88L, 0x85A308D3L, 0x13198A2EL, 0x03707344L,
0xA4093822L, 0x299F31D0L, 0x082EFA98L, 0xEC4E6C89L,
0x452821E6L, 0x38D01377L, 0xBE5466CFL, 0x34E90C6CL,
0xC0AC29B7L, 0xC97C50DDL, 0x3F84D5B5L, 0xB5470917L,
0x9216D5D9L, 0x8979FB1BL
0x243F6A88L, 0x85A308D3L, 0x13198A2EL, 0x03707344L,
0xA4093822L, 0x299F31D0L, 0x082EFA98L, 0xEC4E6C89L,
0x452821E6L, 0x38D01377L, 0xBE5466CFL, 0x34E90C6CL,
0xC0AC29B7L, 0xC97C50DDL, 0x3F84D5B5L, 0xB5470917L,
0x9216D5D9L, 0x8979FB1BL
};
/* declarations of data at the end of this file */
static const uint32_t S[4][256];
static uint32_t F( mbedtls_blowfish_context *ctx, uint32_t x )
static uint32_t F(mbedtls_blowfish_context *ctx, uint32_t x)
{
unsigned short a, b, c, d;
uint32_t y;
unsigned short a, b, c, d;
uint32_t y;
d = MBEDTLS_BYTE_0( x );
x >>= 8;
c = MBEDTLS_BYTE_0( x );
x >>= 8;
b = MBEDTLS_BYTE_0( x );
x >>= 8;
a = MBEDTLS_BYTE_0( x );
y = ctx->S[0][a] + ctx->S[1][b];
y = y ^ ctx->S[2][c];
y = y + ctx->S[3][d];
d = MBEDTLS_BYTE_0(x);
x >>= 8;
c = MBEDTLS_BYTE_0(x);
x >>= 8;
b = MBEDTLS_BYTE_0(x);
x >>= 8;
a = MBEDTLS_BYTE_0(x);
y = ctx->S[0][a] + ctx->S[1][b];
y = y ^ ctx->S[2][c];
y = y + ctx->S[3][d];
return( y );
return y;
}
static void blowfish_enc( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t *xr )
static void blowfish_enc(mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t *xr)
{
uint32_t Xl, Xr, temp;
short i;
@@ -78,10 +78,9 @@ static void blowfish_enc( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t
Xl = *xl;
Xr = *xr;
for( i = 0; i < MBEDTLS_BLOWFISH_ROUNDS; ++i )
{
for (i = 0; i < MBEDTLS_BLOWFISH_ROUNDS; ++i) {
Xl = Xl ^ ctx->P[i];
Xr = F( ctx, Xl ) ^ Xr;
Xr = F(ctx, Xl) ^ Xr;
temp = Xl;
Xl = Xr;
@@ -99,7 +98,7 @@ static void blowfish_enc( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t
*xr = Xr;
}
static void blowfish_dec( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t *xr )
static void blowfish_dec(mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t *xr)
{
uint32_t Xl, Xr, temp;
short i;
@@ -107,10 +106,9 @@ static void blowfish_dec( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t
Xl = *xl;
Xr = *xr;
for( i = MBEDTLS_BLOWFISH_ROUNDS + 1; i > 1; --i )
{
for (i = MBEDTLS_BLOWFISH_ROUNDS + 1; i > 1; --i) {
Xl = Xl ^ ctx->P[i];
Xr = F( ctx, Xl ) ^ Xr;
Xr = F(ctx, Xl) ^ Xr;
temp = Xl;
Xl = Xr;
@@ -128,56 +126,55 @@ static void blowfish_dec( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t
*xr = Xr;
}
void mbedtls_blowfish_init( mbedtls_blowfish_context *ctx )
void mbedtls_blowfish_init(mbedtls_blowfish_context *ctx)
{
BLOWFISH_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_blowfish_context ) );
BLOWFISH_VALIDATE(ctx != NULL);
memset(ctx, 0, sizeof(mbedtls_blowfish_context));
}
void mbedtls_blowfish_free( mbedtls_blowfish_context *ctx )
void mbedtls_blowfish_free(mbedtls_blowfish_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_blowfish_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_blowfish_context));
}
/*
* Blowfish key schedule
*/
int mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx,
const unsigned char *key,
unsigned int keybits )
int mbedtls_blowfish_setkey(mbedtls_blowfish_context *ctx,
const unsigned char *key,
unsigned int keybits)
{
unsigned int i, j, k;
uint32_t data, datal, datar;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( key != NULL );
BLOWFISH_VALIDATE_RET(ctx != NULL);
BLOWFISH_VALIDATE_RET(key != NULL);
if( keybits < MBEDTLS_BLOWFISH_MIN_KEY_BITS ||
if (keybits < MBEDTLS_BLOWFISH_MIN_KEY_BITS ||
keybits > MBEDTLS_BLOWFISH_MAX_KEY_BITS ||
keybits % 8 != 0 )
{
return( MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA );
keybits % 8 != 0) {
return MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA;
}
keybits >>= 3;
for( i = 0; i < 4; i++ )
{
for( j = 0; j < 256; j++ )
for (i = 0; i < 4; i++) {
for (j = 0; j < 256; j++) {
ctx->S[i][j] = S[i][j];
}
}
j = 0;
for( i = 0; i < MBEDTLS_BLOWFISH_ROUNDS + 2; ++i )
{
for (i = 0; i < MBEDTLS_BLOWFISH_ROUNDS + 2; ++i) {
data = 0x00000000;
for( k = 0; k < 4; ++k )
{
data = ( data << 8 ) | key[j++];
if( j >= keybits )
for (k = 0; k < 4; ++k) {
data = (data << 8) | key[j++];
if (j >= keybits) {
j = 0;
}
}
ctx->P[i] = P[i] ^ data;
}
@@ -185,107 +182,99 @@ int mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx,
datal = 0x00000000;
datar = 0x00000000;
for( i = 0; i < MBEDTLS_BLOWFISH_ROUNDS + 2; i += 2 )
{
blowfish_enc( ctx, &datal, &datar );
for (i = 0; i < MBEDTLS_BLOWFISH_ROUNDS + 2; i += 2) {
blowfish_enc(ctx, &datal, &datar);
ctx->P[i] = datal;
ctx->P[i + 1] = datar;
}
for( i = 0; i < 4; i++ )
{
for( j = 0; j < 256; j += 2 )
{
blowfish_enc( ctx, &datal, &datar );
for (i = 0; i < 4; i++) {
for (j = 0; j < 256; j += 2) {
blowfish_enc(ctx, &datal, &datar);
ctx->S[i][j] = datal;
ctx->S[i][j + 1] = datar;
}
}
return( 0 );
return 0;
}
/*
* Blowfish-ECB block encryption/decryption
*/
int mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx,
int mode,
const unsigned char input[MBEDTLS_BLOWFISH_BLOCKSIZE],
unsigned char output[MBEDTLS_BLOWFISH_BLOCKSIZE] )
int mbedtls_blowfish_crypt_ecb(mbedtls_blowfish_context *ctx,
int mode,
const unsigned char input[MBEDTLS_BLOWFISH_BLOCKSIZE],
unsigned char output[MBEDTLS_BLOWFISH_BLOCKSIZE])
{
uint32_t X0, X1;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT );
BLOWFISH_VALIDATE_RET( input != NULL );
BLOWFISH_VALIDATE_RET( output != NULL );
BLOWFISH_VALIDATE_RET(ctx != NULL);
BLOWFISH_VALIDATE_RET(mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT);
BLOWFISH_VALIDATE_RET(input != NULL);
BLOWFISH_VALIDATE_RET(output != NULL);
X0 = MBEDTLS_GET_UINT32_BE( input, 0 );
X1 = MBEDTLS_GET_UINT32_BE( input, 4 );
X0 = MBEDTLS_GET_UINT32_BE(input, 0);
X1 = MBEDTLS_GET_UINT32_BE(input, 4);
if( mode == MBEDTLS_BLOWFISH_DECRYPT )
{
blowfish_dec( ctx, &X0, &X1 );
}
else /* MBEDTLS_BLOWFISH_ENCRYPT */
{
blowfish_enc( ctx, &X0, &X1 );
if (mode == MBEDTLS_BLOWFISH_DECRYPT) {
blowfish_dec(ctx, &X0, &X1);
} else { /* MBEDTLS_BLOWFISH_ENCRYPT */
blowfish_enc(ctx, &X0, &X1);
}
MBEDTLS_PUT_UINT32_BE( X0, output, 0 );
MBEDTLS_PUT_UINT32_BE( X1, output, 4 );
MBEDTLS_PUT_UINT32_BE(X0, output, 0);
MBEDTLS_PUT_UINT32_BE(X1, output, 4);
return( 0 );
return 0;
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* Blowfish-CBC buffer encryption/decryption
*/
int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
int mode,
size_t length,
unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
int mbedtls_blowfish_crypt_cbc(mbedtls_blowfish_context *ctx,
int mode,
size_t length,
unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],
const unsigned char *input,
unsigned char *output)
{
int i;
unsigned char temp[MBEDTLS_BLOWFISH_BLOCKSIZE];
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT );
BLOWFISH_VALIDATE_RET( iv != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || input != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || output != NULL );
BLOWFISH_VALIDATE_RET(ctx != NULL);
BLOWFISH_VALIDATE_RET(mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT);
BLOWFISH_VALIDATE_RET(iv != NULL);
BLOWFISH_VALIDATE_RET(length == 0 || input != NULL);
BLOWFISH_VALIDATE_RET(length == 0 || output != NULL);
if( length % MBEDTLS_BLOWFISH_BLOCKSIZE )
return( MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH );
if (length % MBEDTLS_BLOWFISH_BLOCKSIZE) {
return MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH;
}
if( mode == MBEDTLS_BLOWFISH_DECRYPT )
{
while( length > 0 )
{
memcpy( temp, input, MBEDTLS_BLOWFISH_BLOCKSIZE );
mbedtls_blowfish_crypt_ecb( ctx, mode, input, output );
if (mode == MBEDTLS_BLOWFISH_DECRYPT) {
while (length > 0) {
memcpy(temp, input, MBEDTLS_BLOWFISH_BLOCKSIZE);
mbedtls_blowfish_crypt_ecb(ctx, mode, input, output);
for( i = 0; i < MBEDTLS_BLOWFISH_BLOCKSIZE;i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
for (i = 0; i < MBEDTLS_BLOWFISH_BLOCKSIZE; i++) {
output[i] = (unsigned char) (output[i] ^ iv[i]);
}
memcpy( iv, temp, MBEDTLS_BLOWFISH_BLOCKSIZE );
memcpy(iv, temp, MBEDTLS_BLOWFISH_BLOCKSIZE);
input += MBEDTLS_BLOWFISH_BLOCKSIZE;
output += MBEDTLS_BLOWFISH_BLOCKSIZE;
length -= MBEDTLS_BLOWFISH_BLOCKSIZE;
}
}
else
{
while( length > 0 )
{
for( i = 0; i < MBEDTLS_BLOWFISH_BLOCKSIZE; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
} else {
while (length > 0) {
for (i = 0; i < MBEDTLS_BLOWFISH_BLOCKSIZE; i++) {
output[i] = (unsigned char) (input[i] ^ iv[i]);
}
mbedtls_blowfish_crypt_ecb( ctx, mode, output, output );
memcpy( iv, output, MBEDTLS_BLOWFISH_BLOCKSIZE );
mbedtls_blowfish_crypt_ecb(ctx, mode, output, output);
memcpy(iv, output, MBEDTLS_BLOWFISH_BLOCKSIZE);
input += MBEDTLS_BLOWFISH_BLOCKSIZE;
output += MBEDTLS_BLOWFISH_BLOCKSIZE;
@@ -293,7 +282,7 @@ int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
}
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
@@ -301,59 +290,57 @@ int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
/*
* Blowfish CFB buffer encryption/decryption
*/
int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx,
int mode,
size_t length,
size_t *iv_off,
unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
int mbedtls_blowfish_crypt_cfb64(mbedtls_blowfish_context *ctx,
int mode,
size_t length,
size_t *iv_off,
unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],
const unsigned char *input,
unsigned char *output)
{
int c;
size_t n;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT );
BLOWFISH_VALIDATE_RET( iv != NULL );
BLOWFISH_VALIDATE_RET( iv_off != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || input != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || output != NULL );
BLOWFISH_VALIDATE_RET(ctx != NULL);
BLOWFISH_VALIDATE_RET(mode == MBEDTLS_BLOWFISH_ENCRYPT ||
mode == MBEDTLS_BLOWFISH_DECRYPT);
BLOWFISH_VALIDATE_RET(iv != NULL);
BLOWFISH_VALIDATE_RET(iv_off != NULL);
BLOWFISH_VALIDATE_RET(length == 0 || input != NULL);
BLOWFISH_VALIDATE_RET(length == 0 || output != NULL);
n = *iv_off;
if( n >= 8 )
return( MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA );
if (n >= 8) {
return MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA;
}
if( mode == MBEDTLS_BLOWFISH_DECRYPT )
{
while( length-- )
{
if( n == 0 )
mbedtls_blowfish_crypt_ecb( ctx, MBEDTLS_BLOWFISH_ENCRYPT, iv, iv );
if (mode == MBEDTLS_BLOWFISH_DECRYPT) {
while (length--) {
if (n == 0) {
mbedtls_blowfish_crypt_ecb(ctx, MBEDTLS_BLOWFISH_ENCRYPT, iv, iv);
}
c = *input++;
*output++ = (unsigned char)( c ^ iv[n] );
*output++ = (unsigned char) (c ^ iv[n]);
iv[n] = (unsigned char) c;
n = ( n + 1 ) % MBEDTLS_BLOWFISH_BLOCKSIZE;
n = (n + 1) % MBEDTLS_BLOWFISH_BLOCKSIZE;
}
}
else
{
while( length-- )
{
if( n == 0 )
mbedtls_blowfish_crypt_ecb( ctx, MBEDTLS_BLOWFISH_ENCRYPT, iv, iv );
} else {
while (length--) {
if (n == 0) {
mbedtls_blowfish_crypt_ecb(ctx, MBEDTLS_BLOWFISH_ENCRYPT, iv, iv);
}
iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );
iv[n] = *output++ = (unsigned char) (iv[n] ^ *input++);
n = ( n + 1 ) % MBEDTLS_BLOWFISH_BLOCKSIZE;
n = (n + 1) % MBEDTLS_BLOWFISH_BLOCKSIZE;
}
}
*iv_off = n;
return( 0 );
return 0;
}
#endif /*MBEDTLS_CIPHER_MODE_CFB */
@@ -361,46 +348,48 @@ int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx,
/*
* Blowfish CTR buffer encryption/decryption
*/
int mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[MBEDTLS_BLOWFISH_BLOCKSIZE],
unsigned char stream_block[MBEDTLS_BLOWFISH_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
int mbedtls_blowfish_crypt_ctr(mbedtls_blowfish_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[MBEDTLS_BLOWFISH_BLOCKSIZE],
unsigned char stream_block[MBEDTLS_BLOWFISH_BLOCKSIZE],
const unsigned char *input,
unsigned char *output)
{
int c, i;
size_t n;
BLOWFISH_VALIDATE_RET( ctx != NULL );
BLOWFISH_VALIDATE_RET( nonce_counter != NULL );
BLOWFISH_VALIDATE_RET( stream_block != NULL );
BLOWFISH_VALIDATE_RET( nc_off != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || input != NULL );
BLOWFISH_VALIDATE_RET( length == 0 || output != NULL );
BLOWFISH_VALIDATE_RET(ctx != NULL);
BLOWFISH_VALIDATE_RET(nonce_counter != NULL);
BLOWFISH_VALIDATE_RET(stream_block != NULL);
BLOWFISH_VALIDATE_RET(nc_off != NULL);
BLOWFISH_VALIDATE_RET(length == 0 || input != NULL);
BLOWFISH_VALIDATE_RET(length == 0 || output != NULL);
n = *nc_off;
if( n >= 8 )
return( MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA );
if (n >= 8) {
return MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA;
}
while( length-- )
{
if( n == 0 ) {
mbedtls_blowfish_crypt_ecb( ctx, MBEDTLS_BLOWFISH_ENCRYPT, nonce_counter,
stream_block );
while (length--) {
if (n == 0) {
mbedtls_blowfish_crypt_ecb(ctx, MBEDTLS_BLOWFISH_ENCRYPT, nonce_counter,
stream_block);
for( i = MBEDTLS_BLOWFISH_BLOCKSIZE; i > 0; i-- )
if( ++nonce_counter[i - 1] != 0 )
for (i = MBEDTLS_BLOWFISH_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 ) % MBEDTLS_BLOWFISH_BLOCKSIZE;
n = (n + 1) % MBEDTLS_BLOWFISH_BLOCKSIZE;
}
*nc_off = n;
return( 0 );
return 0;
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */

File diff suppressed because it is too large Load Diff

View File

@@ -40,10 +40,10 @@
#if !defined(MBEDTLS_CCM_ALT)
#define CCM_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CCM_BAD_INPUT )
#define CCM_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define CCM_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_CCM_BAD_INPUT)
#define CCM_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1
@@ -51,54 +51,57 @@
/*
* Initialize context
*/
void mbedtls_ccm_init( mbedtls_ccm_context *ctx )
void mbedtls_ccm_init(mbedtls_ccm_context *ctx)
{
CCM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_ccm_context ) );
CCM_VALIDATE(ctx != NULL);
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;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( key != NULL );
CCM_VALIDATE_RET(ctx != NULL);
CCM_VALIDATE_RET(key != NULL);
cipher_info = mbedtls_cipher_info_from_values( cipher, keybits,
MBEDTLS_MODE_ECB );
if( cipher_info == NULL )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
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));
}
/*
@@ -111,38 +114,38 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx )
* (Always using b as the source helps the compiler optimise a bit better.)
*/
#define UPDATE_CBC_MAC \
for( i = 0; i < 16; i++ ) \
y[i] ^= b[i]; \
for (i = 0; i < 16; i++) \
y[i] ^= b[i]; \
\
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, y, 16, y, &olen ) ) != 0 ) \
return( ret );
if ((ret = mbedtls_cipher_update(&ctx->cipher_ctx, y, 16, y, &olen)) != 0) \
return ret;
/*
* Encrypt or decrypt a partial block with CTR
* Warning: using b for temporary storage! src and dst must not be b!
* This avoids allocating one more 16 bytes buffer while allowing src == dst.
*/
#define CTR_CRYPT( dst, src, len ) \
#define CTR_CRYPT(dst, src, len) \
do \
{ \
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctr, \
16, b, &olen ) ) != 0 ) \
if ((ret = mbedtls_cipher_update(&ctx->cipher_ctx, ctr, \
16, b, &olen)) != 0) \
{ \
return( ret ); \
return ret; \
} \
\
for( i = 0; i < (len); i++ ) \
(dst)[i] = (src)[i] ^ b[i]; \
} while( 0 )
\
for (i = 0; i < (len); i++) \
(dst)[i] = (src)[i] ^ b[i]; \
} while (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;
unsigned char i;
@@ -161,15 +164,18 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
*
* 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;
}
/* 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;
}
if( add_len >= 0xFF00 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if (add_len >= 0xFF00) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
q = 16 - 1 - (unsigned char) iv_len;
@@ -186,49 +192,49 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
* 2 .. 0 q - 1
*/
b[0] = 0;
b[0] |= ( add_len > 0 ) << 6;
b[0] |= ( ( tag_len - 2 ) / 2 ) << 3;
b[0] |= (add_len > 0) << 6;
b[0] |= ((tag_len - 2) / 2) << 3;
b[0] |= q - 1;
memcpy( b + 1, iv, iv_len );
memcpy(b + 1, iv, iv_len);
for( i = 0, len_left = length; i < q; i++, len_left >>= 8 )
b[15-i] = MBEDTLS_BYTE_0( len_left );
for (i = 0, len_left = length; i < q; i++, len_left >>= 8) {
b[15-i] = MBEDTLS_BYTE_0(len_left);
}
if( len_left > 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if (len_left > 0) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
/* Start CBC-MAC with first block */
memset( y, 0, 16 );
memset(y, 0, 16);
UPDATE_CBC_MAC;
/*
* If there is additional data, update CBC-MAC with
* add_len, add, 0 (padding to a block boundary)
*/
if( add_len > 0 )
{
if (add_len > 0) {
size_t use_len;
len_left = add_len;
src = add;
memset( b, 0, 16 );
MBEDTLS_PUT_UINT16_BE( add_len, b, 0 );
memset(b, 0, 16);
MBEDTLS_PUT_UINT16_BE(add_len, b, 0);
use_len = len_left < 16 - 2 ? len_left : 16 - 2;
memcpy( b + 2, src, use_len );
memcpy(b + 2, src, use_len);
len_left -= use_len;
src += use_len;
UPDATE_CBC_MAC;
while( len_left > 0 )
{
while (len_left > 0) {
use_len = len_left > 16 ? 16 : len_left;
memset( b, 0, 16 );
memcpy( b, src, use_len );
memset(b, 0, 16);
memcpy(b, src, use_len);
UPDATE_CBC_MAC;
len_left -= use_len;
@@ -247,8 +253,8 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
* 2 .. 0 q - 1
*/
ctr[0] = q - 1;
memcpy( ctr + 1, iv, iv_len );
memset( ctr + 1 + iv_len, 0, q );
memcpy(ctr + 1, iv, iv_len);
memset(ctr + 1 + iv_len, 0, q);
ctr[15] = 1;
/*
@@ -261,23 +267,20 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
src = input;
dst = output;
while( len_left > 0 )
{
while (len_left > 0) {
size_t use_len = len_left > 16 ? 16 : len_left;
if( mode == CCM_ENCRYPT )
{
memset( b, 0, 16 );
memcpy( b, src, use_len );
if (mode == CCM_ENCRYPT) {
memset(b, 0, 16);
memcpy(b, src, use_len);
UPDATE_CBC_MAC;
}
CTR_CRYPT( dst, src, use_len );
CTR_CRYPT(dst, src, use_len);
if( mode == CCM_DECRYPT )
{
memset( b, 0, 16 );
memcpy( b, dst, use_len );
if (mode == CCM_DECRYPT) {
memset(b, 0, 16);
memcpy(b, dst, use_len);
UPDATE_CBC_MAC;
}
@@ -289,120 +292,124 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
* Increment counter.
* No need to check for overflow thanks to the length check above.
*/
for( i = 0; i < q; i++ )
if( ++ctr[15-i] != 0 )
for (i = 0; i < q; i++) {
if (++ctr[15-i] != 0) {
break;
}
}
}
/*
* Authentication: reset counter and crypt/mask internal tag
*/
for( i = 0; i < q; i++ )
for (i = 0; i < q; i++) {
ctr[15-i] = 0;
}
CTR_CRYPT( y, y, 16 );
memcpy( tag, y, tag_len );
CTR_CRYPT(y, y, 16);
memcpy(tag, y, tag_len);
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)
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
return( ccm_auth_crypt( ctx, CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len ) );
CCM_VALIDATE_RET(ctx != NULL);
CCM_VALIDATE_RET(iv != NULL);
CCM_VALIDATE_RET(add_len == 0 || add != NULL);
CCM_VALIDATE_RET(length == 0 || input != NULL);
CCM_VALIDATE_RET(length == 0 || output != NULL);
CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
return ccm_auth_crypt(ctx, CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len);
}
int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
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)
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( tag_len == 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
CCM_VALIDATE_RET(ctx != NULL);
CCM_VALIDATE_RET(iv != NULL);
CCM_VALIDATE_RET(add_len == 0 || add != NULL);
CCM_VALIDATE_RET(length == 0 || input != NULL);
CCM_VALIDATE_RET(length == 0 || output != NULL);
CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
if (tag_len == 0) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
return( mbedtls_ccm_star_encrypt_and_tag( ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len ) );
return mbedtls_ccm_star_encrypt_and_tag(ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len);
}
/*
* Authenticated decryption
*/
int mbedtls_ccm_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)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char check_tag[16];
unsigned char i;
int diff;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
CCM_VALIDATE_RET(ctx != NULL);
CCM_VALIDATE_RET(iv != NULL);
CCM_VALIDATE_RET(add_len == 0 || add != NULL);
CCM_VALIDATE_RET(length == 0 || input != NULL);
CCM_VALIDATE_RET(length == 0 || output != NULL);
CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
if( ( ret = ccm_auth_crypt( ctx, CCM_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, check_tag, tag_len ) ) != 0 )
{
return( ret );
if ((ret = ccm_auth_crypt(ctx, CCM_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, check_tag, tag_len)) != 0) {
return ret;
}
/* Check tag in "constant-time" */
for( diff = 0, i = 0; i < tag_len; i++ )
for (diff = 0, i = 0; i < tag_len; i++) {
diff |= tag[i] ^ check_tag[i];
if( diff != 0 )
{
mbedtls_platform_zeroize( output, length );
return( MBEDTLS_ERR_CCM_AUTH_FAILED );
}
return( 0 );
if (diff != 0) {
mbedtls_platform_zeroize(output, length);
return MBEDTLS_ERR_CCM_AUTH_FAILED;
}
return 0;
}
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
int mbedtls_ccm_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len)
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
CCM_VALIDATE_RET(ctx != NULL);
CCM_VALIDATE_RET(iv != NULL);
CCM_VALIDATE_RET(add_len == 0 || add != NULL);
CCM_VALIDATE_RET(length == 0 || input != NULL);
CCM_VALIDATE_RET(length == 0 || output != NULL);
CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
if( tag_len == 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if (tag_len == 0) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
return( mbedtls_ccm_star_auth_decrypt( ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len ) );
return mbedtls_ccm_star_auth_decrypt(ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len);
}
#endif /* !MBEDTLS_CCM_ALT */
@@ -439,7 +446,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 };
@@ -455,7 +462,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;
/*
@@ -468,70 +475,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 */

File diff suppressed because it is too large Load Diff

View File

@@ -37,17 +37,17 @@
#if !defined(MBEDTLS_CHACHA20_ALT)
/* Parameter validation macros */
#define CHACHA20_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA )
#define CHACHA20_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define CHACHA20_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA)
#define CHACHA20_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
#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.
@@ -64,31 +64,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);
}
/**
@@ -99,17 +99,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);
}
/**
@@ -118,29 +118,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];
@@ -148,40 +149,38 @@ 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)
{
CHACHA20_VALIDATE( ctx != NULL );
CHACHA20_VALIDATE(ctx != NULL);
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_VALIDATE_RET( ctx != NULL );
CHACHA20_VALIDATE_RET( key != NULL );
CHACHA20_VALIDATE_RET(ctx != NULL);
CHACHA20_VALIDATE_RET(key != NULL);
/* ChaCha20 constants - the string "expand 32-byte k" */
ctx->state[0] = 0x61707865;
@@ -190,58 +189,57 @@ 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)
{
CHACHA20_VALIDATE_RET( ctx != NULL );
CHACHA20_VALIDATE_RET( nonce != NULL );
CHACHA20_VALIDATE_RET(ctx != NULL);
CHACHA20_VALIDATE_RET(nonce != NULL);
/* 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;
size_t i;
CHACHA20_VALIDATE_RET( ctx != NULL );
CHACHA20_VALIDATE_RET( size == 0 || input != NULL );
CHACHA20_VALIDATE_RET( size == 0 || output != NULL );
CHACHA20_VALIDATE_RET(ctx != NULL);
CHACHA20_VALIDATE_RET(size == 0 || input != NULL);
CHACHA20_VALIDATE_RET(size == 0 || output != NULL);
/* Use leftover keystream bytes, if available */
while( size > 0U && ctx->keystream_bytes_used < CHACHA20_BLOCK_SIZE_BYTES )
{
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++;
@@ -249,15 +247,13 @@ 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]++;
for( i = 0U; i < 64U; i += 8U )
{
output[offset + i ] = input[offset + i ] ^ ctx->keystream8[i ];
for (i = 0U; i < 64U; i += 8U) {
output[offset + i] = input[offset + i] ^ ctx->keystream8[i];
output[offset + i+1] = input[offset + i+1] ^ ctx->keystream8[i+1];
output[offset + i+2] = input[offset + i+2] ^ ctx->keystream8[i+2];
output[offset + i+3] = input[offset + i+3] ^ ctx->keystream8[i+3];
@@ -272,14 +268,12 @@ int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,
}
/* 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]++;
for( i = 0U; i < size; i++)
{
for (i = 0U; i < size; i++) {
output[offset + i] = input[offset + i] ^ ctx->keystream8[i];
}
@@ -287,39 +281,41 @@ int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,
}
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;
CHACHA20_VALIDATE_RET( key != NULL );
CHACHA20_VALIDATE_RET( nonce != NULL );
CHACHA20_VALIDATE_RET( data_len == 0 || input != NULL );
CHACHA20_VALIDATE_RET( data_len == 0 || output != NULL );
CHACHA20_VALIDATE_RET(key != NULL);
CHACHA20_VALIDATE_RET(nonce != NULL);
CHACHA20_VALIDATE_RET(data_len == 0 || input != NULL);
CHACHA20_VALIDATE_RET(data_len == 0 || output != NULL);
mbedtls_chacha20_init( &ctx );
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 */
@@ -495,50 +491,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

@@ -33,34 +33,35 @@
#if !defined(MBEDTLS_CHACHAPOLY_ALT)
/* Parameter validation macros */
#define CHACHAPOLY_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA )
#define CHACHAPOLY_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define CHACHAPOLY_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA)
#define CHACHAPOLY_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
#define CHACHAPOLY_STATE_INIT ( 0 )
#define CHACHAPOLY_STATE_AAD ( 1 )
#define CHACHAPOLY_STATE_CIPHERTEXT ( 2 ) /* Encrypting or decrypting */
#define CHACHAPOLY_STATE_FINISHED ( 3 )
#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);
}
/**
@@ -68,86 +69,89 @@ 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)
{
CHACHAPOLY_VALIDATE( ctx != NULL );
CHACHAPOLY_VALIDATE(ctx != NULL);
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;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( key != NULL );
CHACHAPOLY_VALIDATE_RET(ctx != NULL);
CHACHAPOLY_VALIDATE_RET(key != NULL);
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];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET(ctx != NULL);
CHACHAPOLY_VALIDATE_RET(nonce != NULL);
/* Set counter = 0, will be update to 1 when generating Poly1305 key */
ret = mbedtls_chacha20_starts( &ctx->chacha20_ctx, nonce, 0U );
if( ret != 0 )
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;
@@ -155,100 +159,99 @@ 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)
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET(ctx != NULL);
CHACHAPOLY_VALIDATE_RET(aad_len == 0 || aad != NULL);
if( ctx->state != CHACHAPOLY_STATE_AAD )
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
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;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || output != NULL );
CHACHAPOLY_VALIDATE_RET(ctx != NULL);
CHACHAPOLY_VALIDATE_RET(len == 0 || input != NULL);
CHACHAPOLY_VALIDATE_RET(len == 0 || output != NULL);
if( ( ctx->state != CHACHAPOLY_STATE_AAD ) &&
( ctx->state != CHACHAPOLY_STATE_CIPHERTEXT ) )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
if ((ctx->state != CHACHAPOLY_STATE_AAD) &&
(ctx->state != CHACHAPOLY_STATE_CIPHERTEXT)) {
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];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( mac != NULL );
CHACHAPOLY_VALIDATE_RET(ctx != NULL);
CHACHAPOLY_VALIDATE_RET(mac != NULL);
if( ctx->state == CHACHAPOLY_STATE_INIT )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
if (ctx->state == CHACHAPOLY_STATE_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;
@@ -259,104 +262,107 @@ 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])
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
CHACHAPOLY_VALIDATE_RET(ctx != NULL);
CHACHAPOLY_VALIDATE_RET(nonce != NULL);
CHACHAPOLY_VALIDATE_RET(tag != NULL);
CHACHAPOLY_VALIDATE_RET(aad_len == 0 || aad != NULL);
CHACHAPOLY_VALIDATE_RET(length == 0 || input != NULL);
CHACHAPOLY_VALIDATE_RET(length == 0 || output != NULL);
return( chachapoly_crypt_and_tag( ctx, MBEDTLS_CHACHAPOLY_ENCRYPT,
length, nonce, aad, aad_len,
input, output, tag ) );
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;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
CHACHAPOLY_VALIDATE_RET(ctx != NULL);
CHACHAPOLY_VALIDATE_RET(nonce != NULL);
CHACHAPOLY_VALIDATE_RET(tag != NULL);
CHACHAPOLY_VALIDATE_RET(aad_len == 0 || aad != NULL);
CHACHAPOLY_VALIDATE_RET(length == 0 || input != NULL);
CHACHAPOLY_VALIDATE_RET(length == 0 || output != NULL);
if( ( ret = chachapoly_crypt_and_tag( ctx,
MBEDTLS_CHACHAPOLY_DECRYPT, length, nonce,
aad, aad_len, input, output, check_tag ) ) != 0 )
{
return( ret );
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 */
@@ -452,20 +458,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;
@@ -473,43 +479,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

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

@@ -33,7 +33,7 @@
#include <stdint.h>
/* Define `inline` on some non-C99-compliant compilers. */
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
#if (defined(__ARMCC_VERSION) || defined(_MSC_VER)) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
#endif
@@ -75,9 +75,9 @@
* 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.
@@ -92,9 +92,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;
}
/** Byte Reading Macros
@@ -102,14 +102,14 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* 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))
/**
* Get the unsigned 32 bits integer corresponding to four bytes in
@@ -121,12 +121,12 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* integer from.
*/
#ifndef MBEDTLS_GET_UINT32_BE
#define MBEDTLS_GET_UINT32_BE( data , offset ) \
#define MBEDTLS_GET_UINT32_BE(data, offset) \
( \
( (uint32_t) ( data )[( offset ) ] << 24 ) \
| ( (uint32_t) ( data )[( offset ) + 1] << 16 ) \
| ( (uint32_t) ( data )[( offset ) + 2] << 8 ) \
| ( (uint32_t) ( data )[( offset ) + 3] ) \
((uint32_t) (data)[(offset)] << 24) \
| ((uint32_t) (data)[(offset) + 1] << 16) \
| ((uint32_t) (data)[(offset) + 2] << 8) \
| ((uint32_t) (data)[(offset) + 3]) \
)
#endif
@@ -140,13 +140,13 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* byte of the 32 bits unsigned integer \p n.
*/
#ifndef MBEDTLS_PUT_UINT32_BE
#define MBEDTLS_PUT_UINT32_BE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_3( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_2( n ); \
( data )[( offset ) + 2] = MBEDTLS_BYTE_1( n ); \
( data )[( offset ) + 3] = MBEDTLS_BYTE_0( n ); \
}
#define MBEDTLS_PUT_UINT32_BE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_3(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_2(n); \
(data)[(offset) + 2] = MBEDTLS_BYTE_1(n); \
(data)[(offset) + 3] = MBEDTLS_BYTE_0(n); \
}
#endif
/**
@@ -159,12 +159,12 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* integer from.
*/
#ifndef MBEDTLS_GET_UINT32_LE
#define MBEDTLS_GET_UINT32_LE( data, offset ) \
#define MBEDTLS_GET_UINT32_LE(data, offset) \
( \
( (uint32_t) ( data )[( offset ) ] ) \
| ( (uint32_t) ( data )[( offset ) + 1] << 8 ) \
| ( (uint32_t) ( data )[( offset ) + 2] << 16 ) \
| ( (uint32_t) ( data )[( offset ) + 3] << 24 ) \
((uint32_t) (data)[(offset)]) \
| ((uint32_t) (data)[(offset) + 1] << 8) \
| ((uint32_t) (data)[(offset) + 2] << 16) \
| ((uint32_t) (data)[(offset) + 3] << 24) \
)
#endif
@@ -178,13 +178,13 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* byte of the 32 bits unsigned integer \p n.
*/
#ifndef MBEDTLS_PUT_UINT32_LE
#define MBEDTLS_PUT_UINT32_LE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_0( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_1( n ); \
( data )[( offset ) + 2] = MBEDTLS_BYTE_2( n ); \
( data )[( offset ) + 3] = MBEDTLS_BYTE_3( n ); \
}
#define MBEDTLS_PUT_UINT32_LE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_0(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_1(n); \
(data)[(offset) + 2] = MBEDTLS_BYTE_2(n); \
(data)[(offset) + 3] = MBEDTLS_BYTE_3(n); \
}
#endif
/**
@@ -197,10 +197,10 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* integer from.
*/
#ifndef MBEDTLS_GET_UINT16_LE
#define MBEDTLS_GET_UINT16_LE( data, offset ) \
#define MBEDTLS_GET_UINT16_LE(data, offset) \
( \
( (uint16_t) ( data )[( offset ) ] ) \
| ( (uint16_t) ( data )[( offset ) + 1] << 8 ) \
((uint16_t) (data)[(offset)]) \
| ((uint16_t) (data)[(offset) + 1] << 8) \
)
#endif
@@ -214,11 +214,11 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* byte of the 16 bits unsigned integer \p n.
*/
#ifndef MBEDTLS_PUT_UINT16_LE
#define MBEDTLS_PUT_UINT16_LE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_0( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_1( n ); \
}
#define MBEDTLS_PUT_UINT16_LE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_0(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_1(n); \
}
#endif
/**
@@ -231,10 +231,10 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* integer from.
*/
#ifndef MBEDTLS_GET_UINT16_BE
#define MBEDTLS_GET_UINT16_BE( data, offset ) \
#define MBEDTLS_GET_UINT16_BE(data, offset) \
( \
( (uint16_t) ( data )[( offset ) ] << 8 ) \
| ( (uint16_t) ( data )[( offset ) + 1] ) \
((uint16_t) (data)[(offset)] << 8) \
| ((uint16_t) (data)[(offset) + 1]) \
)
#endif
@@ -248,11 +248,11 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* byte of the 16 bits unsigned integer \p n.
*/
#ifndef MBEDTLS_PUT_UINT16_BE
#define MBEDTLS_PUT_UINT16_BE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_1( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_0( n ); \
}
#define MBEDTLS_PUT_UINT16_BE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_1(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_0(n); \
}
#endif
/**
@@ -265,16 +265,16 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* integer from.
*/
#ifndef MBEDTLS_GET_UINT64_BE
#define MBEDTLS_GET_UINT64_BE( data, offset ) \
#define MBEDTLS_GET_UINT64_BE(data, offset) \
( \
( (uint64_t) ( data )[( offset ) ] << 56 ) \
| ( (uint64_t) ( data )[( offset ) + 1] << 48 ) \
| ( (uint64_t) ( data )[( offset ) + 2] << 40 ) \
| ( (uint64_t) ( data )[( offset ) + 3] << 32 ) \
| ( (uint64_t) ( data )[( offset ) + 4] << 24 ) \
| ( (uint64_t) ( data )[( offset ) + 5] << 16 ) \
| ( (uint64_t) ( data )[( offset ) + 6] << 8 ) \
| ( (uint64_t) ( data )[( offset ) + 7] ) \
((uint64_t) (data)[(offset)] << 56) \
| ((uint64_t) (data)[(offset) + 1] << 48) \
| ((uint64_t) (data)[(offset) + 2] << 40) \
| ((uint64_t) (data)[(offset) + 3] << 32) \
| ((uint64_t) (data)[(offset) + 4] << 24) \
| ((uint64_t) (data)[(offset) + 5] << 16) \
| ((uint64_t) (data)[(offset) + 6] << 8) \
| ((uint64_t) (data)[(offset) + 7]) \
)
#endif
@@ -288,17 +288,17 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* byte of the 64 bits unsigned integer \p n.
*/
#ifndef MBEDTLS_PUT_UINT64_BE
#define MBEDTLS_PUT_UINT64_BE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_7( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_6( n ); \
( data )[( offset ) + 2] = MBEDTLS_BYTE_5( n ); \
( data )[( offset ) + 3] = MBEDTLS_BYTE_4( n ); \
( data )[( offset ) + 4] = MBEDTLS_BYTE_3( n ); \
( data )[( offset ) + 5] = MBEDTLS_BYTE_2( n ); \
( data )[( offset ) + 6] = MBEDTLS_BYTE_1( n ); \
( data )[( offset ) + 7] = MBEDTLS_BYTE_0( n ); \
}
#define MBEDTLS_PUT_UINT64_BE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_7(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_6(n); \
(data)[(offset) + 2] = MBEDTLS_BYTE_5(n); \
(data)[(offset) + 3] = MBEDTLS_BYTE_4(n); \
(data)[(offset) + 4] = MBEDTLS_BYTE_3(n); \
(data)[(offset) + 5] = MBEDTLS_BYTE_2(n); \
(data)[(offset) + 6] = MBEDTLS_BYTE_1(n); \
(data)[(offset) + 7] = MBEDTLS_BYTE_0(n); \
}
#endif
/**
@@ -311,16 +311,16 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* integer from.
*/
#ifndef MBEDTLS_GET_UINT64_LE
#define MBEDTLS_GET_UINT64_LE( data, offset ) \
#define MBEDTLS_GET_UINT64_LE(data, offset) \
( \
( (uint64_t) ( data )[( offset ) + 7] << 56 ) \
| ( (uint64_t) ( data )[( offset ) + 6] << 48 ) \
| ( (uint64_t) ( data )[( offset ) + 5] << 40 ) \
| ( (uint64_t) ( data )[( offset ) + 4] << 32 ) \
| ( (uint64_t) ( data )[( offset ) + 3] << 24 ) \
| ( (uint64_t) ( data )[( offset ) + 2] << 16 ) \
| ( (uint64_t) ( data )[( offset ) + 1] << 8 ) \
| ( (uint64_t) ( data )[( offset ) ] ) \
((uint64_t) (data)[(offset) + 7] << 56) \
| ((uint64_t) (data)[(offset) + 6] << 48) \
| ((uint64_t) (data)[(offset) + 5] << 40) \
| ((uint64_t) (data)[(offset) + 4] << 32) \
| ((uint64_t) (data)[(offset) + 3] << 24) \
| ((uint64_t) (data)[(offset) + 2] << 16) \
| ((uint64_t) (data)[(offset) + 1] << 8) \
| ((uint64_t) (data)[(offset)]) \
)
#endif
@@ -334,17 +334,17 @@ static inline const unsigned char *mbedtls_buffer_offset_const(
* byte of the 64 bits unsigned integer \p n.
*/
#ifndef MBEDTLS_PUT_UINT64_LE
#define MBEDTLS_PUT_UINT64_LE( n, data, offset ) \
{ \
( data )[( offset ) ] = MBEDTLS_BYTE_0( n ); \
( data )[( offset ) + 1] = MBEDTLS_BYTE_1( n ); \
( data )[( offset ) + 2] = MBEDTLS_BYTE_2( n ); \
( data )[( offset ) + 3] = MBEDTLS_BYTE_3( n ); \
( data )[( offset ) + 4] = MBEDTLS_BYTE_4( n ); \
( data )[( offset ) + 5] = MBEDTLS_BYTE_5( n ); \
( data )[( offset ) + 6] = MBEDTLS_BYTE_6( n ); \
( data )[( offset ) + 7] = MBEDTLS_BYTE_7( n ); \
}
#define MBEDTLS_PUT_UINT64_LE(n, data, offset) \
{ \
(data)[(offset)] = MBEDTLS_BYTE_0(n); \
(data)[(offset) + 1] = MBEDTLS_BYTE_1(n); \
(data)[(offset) + 2] = MBEDTLS_BYTE_2(n); \
(data)[(offset) + 3] = MBEDTLS_BYTE_3(n); \
(data)[(offset) + 4] = MBEDTLS_BYTE_4(n); \
(data)[(offset) + 5] = MBEDTLS_BYTE_5(n); \
(data)[(offset) + 6] = MBEDTLS_BYTE_6(n); \
(data)[(offset) + 7] = MBEDTLS_BYTE_7(n); \
}
#endif
#endif /* MBEDTLS_LIBRARY_COMMON_H */

View File

@@ -17,7 +17,7 @@
* limitations under the License.
*/
/*
/*
* The following functions are implemented without using comparison operators, as those
* might be translated to branches by some compilers on some platforms.
*/
@@ -46,17 +46,16 @@
#include <string.h>
int mbedtls_ct_memcmp( const void *a,
const void *b,
size_t n )
int mbedtls_ct_memcmp(const void *a,
const void *b,
size_t n)
{
size_t i;
volatile const unsigned char *A = (volatile const unsigned char *) a;
volatile const unsigned char *B = (volatile const unsigned char *) b;
volatile unsigned char diff = 0;
for( i = 0; i < n; i++ )
{
for (i = 0; i < n; i++) {
/* Read volatile data in order before computing diff.
* This avoids IAR compiler warning:
* 'the order of volatile accesses is undefined ..' */
@@ -64,10 +63,10 @@ int mbedtls_ct_memcmp( const void *a,
diff |= x ^ y;
}
return( (int)diff );
return (int) diff;
}
unsigned mbedtls_ct_uint_mask( unsigned value )
unsigned mbedtls_ct_uint_mask(unsigned value)
{
/* MSVC has a warning about unary minus on unsigned, but this is
* well-defined and precisely what we want to do here */
@@ -75,7 +74,7 @@ unsigned mbedtls_ct_uint_mask( unsigned value )
#pragma warning( push )
#pragma warning( disable : 4146 )
#endif
return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
return -((value | -value) >> (sizeof(value) * 8 - 1));
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
@@ -83,7 +82,7 @@ unsigned mbedtls_ct_uint_mask( unsigned value )
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
size_t mbedtls_ct_size_mask( size_t value )
size_t mbedtls_ct_size_mask(size_t value)
{
/* MSVC has a warning about unary minus on unsigned integer types,
* but this is well-defined and precisely what we want to do here. */
@@ -91,7 +90,7 @@ size_t mbedtls_ct_size_mask( size_t value )
#pragma warning( push )
#pragma warning( disable : 4146 )
#endif
return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
return -((value | -value) >> (sizeof(value) * 8 - 1));
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
@@ -101,7 +100,7 @@ size_t mbedtls_ct_size_mask( size_t value )
#if defined(MBEDTLS_BIGNUM_C)
mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask( mbedtls_mpi_uint value )
mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask(mbedtls_mpi_uint value)
{
/* MSVC has a warning about unary minus on unsigned, but this is
* well-defined and precisely what we want to do here */
@@ -109,7 +108,7 @@ mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask( mbedtls_mpi_uint value )
#pragma warning( push )
#pragma warning( disable : 4146 )
#endif
return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
return -((value | -value) >> (sizeof(value) * 8 - 1));
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
@@ -131,25 +130,25 @@ mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask( mbedtls_mpi_uint value )
*
* \return All-bits-one if \p x is less than \p y, otherwise zero.
*/
static size_t mbedtls_ct_size_mask_lt( size_t x,
size_t y )
static size_t mbedtls_ct_size_mask_lt(size_t x,
size_t y)
{
/* This has the most significant bit set if and only if x < y */
const size_t sub = x - y;
/* sub1 = (x < y) ? 1 : 0 */
const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 );
const size_t sub1 = sub >> (sizeof(sub) * 8 - 1);
/* mask = (x < y) ? 0xff... : 0x00... */
const size_t mask = mbedtls_ct_size_mask( sub1 );
const size_t mask = mbedtls_ct_size_mask(sub1);
return( mask );
return mask;
}
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)
{
return( ~mbedtls_ct_size_mask_lt( x, y ) );
return ~mbedtls_ct_size_mask_lt(x, y);
}
#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
@@ -161,21 +160,21 @@ size_t mbedtls_ct_size_mask_ge( size_t x,
* Constant flow with respect to c.
*/
MBEDTLS_STATIC_TESTABLE
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)
{
/* low_mask is: 0 if low <= c, 0x...ff if low > c */
unsigned low_mask = ( (unsigned) c - low ) >> 8;
unsigned low_mask = ((unsigned) c - low) >> 8;
/* high_mask is: 0 if c <= high, 0x...ff if c > high */
unsigned high_mask = ( (unsigned) high - c ) >> 8;
return( ~( low_mask | high_mask ) & 0xff );
unsigned high_mask = ((unsigned) high - c) >> 8;
return ~(low_mask | high_mask) & 0xff;
}
#endif /* MBEDTLS_BASE64_C */
unsigned mbedtls_ct_size_bool_eq( size_t x,
size_t y )
unsigned mbedtls_ct_size_bool_eq(size_t x,
size_t y)
{
/* diff = 0 if x == y, non-zero otherwise */
const size_t diff = x ^ y;
@@ -188,16 +187,16 @@ unsigned mbedtls_ct_size_bool_eq( size_t x,
#endif
/* diff_msb's most significant bit is equal to x != y */
const size_t diff_msb = ( diff | (size_t) -diff );
const size_t diff_msb = (diff | (size_t) -diff);
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
/* diff1 = (x != y) ? 1 : 0 */
const unsigned diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
const unsigned diff1 = diff_msb >> (sizeof(diff_msb) * 8 - 1);
return( 1 ^ diff1 );
return 1 ^ diff1;
}
#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
@@ -213,19 +212,19 @@ unsigned mbedtls_ct_size_bool_eq( size_t x,
*
* \return 1 if \p x greater than \p y, otherwise 0.
*/
static unsigned mbedtls_ct_size_gt( size_t x,
size_t y )
static unsigned mbedtls_ct_size_gt(size_t x,
size_t y)
{
/* Return the sign bit (1 for negative) of (y - x). */
return( ( y - x ) >> ( sizeof( size_t ) * 8 - 1 ) );
return (y - x) >> (sizeof(size_t) * 8 - 1);
}
#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
#if defined(MBEDTLS_BIGNUM_C)
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)
{
mbedtls_mpi_uint ret;
mbedtls_mpi_uint cond;
@@ -233,12 +232,12 @@ unsigned mbedtls_ct_mpi_uint_lt( const mbedtls_mpi_uint x,
/*
* Check if the most significant bits (MSB) of the operands are different.
*/
cond = ( x ^ y );
cond = (x ^ y);
/*
* If the MSB are the same then the difference x-y will be negative (and
* have its MSB set to 1 during conversion to unsigned) if and only if x<y.
*/
ret = ( x - y ) & ~cond;
ret = (x - y) & ~cond;
/*
* If the MSB are different, then the operand with the MSB of 1 is the
* bigger. (That is if y has MSB of 1, then x<y is true and it is false if
@@ -247,19 +246,19 @@ unsigned mbedtls_ct_mpi_uint_lt( const mbedtls_mpi_uint x,
ret |= y & cond;
ret = ret >> ( sizeof( mbedtls_mpi_uint ) * 8 - 1 );
ret = ret >> (sizeof(mbedtls_mpi_uint) * 8 - 1);
return (unsigned) ret;
}
#endif /* MBEDTLS_BIGNUM_C */
unsigned mbedtls_ct_uint_if( unsigned condition,
unsigned if1,
unsigned if0 )
unsigned mbedtls_ct_uint_if(unsigned condition,
unsigned if1,
unsigned if0)
{
unsigned mask = mbedtls_ct_uint_mask( condition );
return( ( mask & if1 ) | (~mask & if0 ) );
unsigned mask = mbedtls_ct_uint_mask(condition);
return (mask & if1) | (~mask & if0);
}
#if defined(MBEDTLS_BIGNUM_C)
@@ -278,9 +277,9 @@ unsigned mbedtls_ct_uint_if( unsigned condition,
*
* \return \c if1 if \p condition is nonzero, otherwise \c if0.
* */
static int mbedtls_ct_cond_select_sign( unsigned char condition,
int if1,
int if0 )
static int mbedtls_ct_cond_select_sign(unsigned char condition,
int if1,
int if0)
{
/* In order to avoid questions about what we can reasonably assume about
* the representations of signed integers, move everything to unsigned
@@ -292,16 +291,16 @@ static int mbedtls_ct_cond_select_sign( unsigned char condition,
const unsigned mask = condition << 1;
/* select uif1 or uif0 */
unsigned ur = ( uif0 & ~mask ) | ( uif1 & mask );
unsigned ur = (uif0 & ~mask) | (uif1 & mask);
/* ur is now 0 or 2, convert back to -1 or +1 */
return( (int) ur - 1 );
return (int) ur - 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)
{
size_t i;
@@ -319,43 +318,44 @@ void mbedtls_ct_mpi_uint_cond_assign( size_t n,
#pragma warning( pop )
#endif
for( i = 0; i < n; i++ )
dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
for (i = 0; i < n; i++) {
dest[i] = (src[i] & mask) | (dest[i] & ~mask);
}
}
#endif /* MBEDTLS_BIGNUM_C */
#if defined(MBEDTLS_BASE64_C)
unsigned char mbedtls_ct_base64_enc_char( unsigned char value )
unsigned char mbedtls_ct_base64_enc_char(unsigned char value)
{
unsigned char digit = 0;
/* For each range of values, if value is in that range, mask digit with
* the corresponding value. Since value can only be in a single range,
* only at most one masking will change digit. */
digit |= mbedtls_ct_uchar_mask_of_range( 0, 25, value ) & ( 'A' + value );
digit |= mbedtls_ct_uchar_mask_of_range( 26, 51, value ) & ( 'a' + value - 26 );
digit |= mbedtls_ct_uchar_mask_of_range( 52, 61, value ) & ( '0' + value - 52 );
digit |= mbedtls_ct_uchar_mask_of_range( 62, 62, value ) & '+';
digit |= mbedtls_ct_uchar_mask_of_range( 63, 63, value ) & '/';
return( digit );
digit |= mbedtls_ct_uchar_mask_of_range(0, 25, value) & ('A' + value);
digit |= mbedtls_ct_uchar_mask_of_range(26, 51, value) & ('a' + value - 26);
digit |= mbedtls_ct_uchar_mask_of_range(52, 61, value) & ('0' + value - 52);
digit |= mbedtls_ct_uchar_mask_of_range(62, 62, value) & '+';
digit |= mbedtls_ct_uchar_mask_of_range(63, 63, value) & '/';
return digit;
}
signed char mbedtls_ct_base64_dec_value( unsigned char c )
signed char mbedtls_ct_base64_dec_value(unsigned char c)
{
unsigned char val = 0;
/* For each range of digits, if c is in that range, mask val with
* the corresponding value. Since c can only be in a single range,
* only at most one masking will change val. Set val to one plus
* the desired value so that it stays 0 if c is in none of the ranges. */
val |= mbedtls_ct_uchar_mask_of_range( 'A', 'Z', c ) & ( c - 'A' + 0 + 1 );
val |= mbedtls_ct_uchar_mask_of_range( 'a', 'z', c ) & ( c - 'a' + 26 + 1 );
val |= mbedtls_ct_uchar_mask_of_range( '0', '9', c ) & ( c - '0' + 52 + 1 );
val |= mbedtls_ct_uchar_mask_of_range( '+', '+', c ) & ( c - '+' + 62 + 1 );
val |= mbedtls_ct_uchar_mask_of_range( '/', '/', c ) & ( c - '/' + 63 + 1 );
val |= mbedtls_ct_uchar_mask_of_range('A', 'Z', c) & (c - 'A' + 0 + 1);
val |= mbedtls_ct_uchar_mask_of_range('a', 'z', c) & (c - 'a' + 26 + 1);
val |= mbedtls_ct_uchar_mask_of_range('0', '9', c) & (c - '0' + 52 + 1);
val |= mbedtls_ct_uchar_mask_of_range('+', '+', c) & (c - '+' + 62 + 1);
val |= mbedtls_ct_uchar_mask_of_range('/', '/', c) & (c - '/' + 63 + 1);
/* At this point, val is 0 if c is an invalid digit and v+1 if c is
* a digit with the value v. */
return( val - 1 );
return val - 1;
}
#endif /* MBEDTLS_BASE64_C */
@@ -378,72 +378,71 @@ signed char mbedtls_ct_base64_dec_value( unsigned char c )
* \param total Total size of the buffer.
* \param offset Offset from which to copy \p total - \p offset bytes.
*/
static void mbedtls_ct_mem_move_to_left( void *start,
size_t total,
size_t offset )
static void mbedtls_ct_mem_move_to_left(void *start,
size_t total,
size_t offset)
{
volatile unsigned char *buf = start;
size_t i, n;
if( total == 0 )
if (total == 0) {
return;
for( i = 0; i < total; i++ )
{
unsigned no_op = mbedtls_ct_size_gt( total - offset, i );
}
for (i = 0; i < total; i++) {
unsigned no_op = mbedtls_ct_size_gt(total - offset, i);
/* The first `total - offset` passes are a no-op. The last
* `offset` passes shift the data one byte to the left and
* zero out the last byte. */
for( n = 0; n < total - 1; n++ )
{
for (n = 0; n < total - 1; n++) {
unsigned char current = buf[n];
unsigned char next = buf[n+1];
buf[n] = mbedtls_ct_uint_if( no_op, current, next );
buf[n] = mbedtls_ct_uint_if(no_op, current, next);
}
buf[total-1] = mbedtls_ct_uint_if( no_op, buf[total-1], 0 );
buf[total-1] = mbedtls_ct_uint_if(no_op, buf[total-1], 0);
}
}
#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
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)
{
/* mask = c1 == c2 ? 0xff : 0x00 */
const size_t equal = mbedtls_ct_size_bool_eq( c1, c2 );
const unsigned char mask = (unsigned char) mbedtls_ct_size_mask( equal );
const size_t equal = mbedtls_ct_size_bool_eq(c1, c2);
const unsigned char mask = (unsigned char) mbedtls_ct_size_mask(equal);
/* dest[i] = c1 == c2 ? src[i] : dest[i] */
for( size_t i = 0; i < len; i++ )
dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
}
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 )
{
size_t offsetval;
for( offsetval = offset_min; offsetval <= offset_max; offsetval++ )
{
mbedtls_ct_memcpy_if_eq( dest, src + offsetval, len,
offsetval, offset );
for (size_t i = 0; i < len; i++) {
dest[i] = (src[i] & mask) | (dest[i] & ~mask);
}
}
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 )
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)
{
size_t offsetval;
for (offsetval = offset_min; offsetval <= offset_max; offsetval++) {
mbedtls_ct_memcpy_if_eq(dest, src + offsetval, len,
offsetval, offset);
}
}
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)
{
/*
* This function breaks the HMAC abstraction and uses the md_clone()
@@ -459,79 +458,79 @@ int mbedtls_ct_hmac( mbedtls_md_context_t *ctx,
*
* Then we only need to compute HASH(okey + inner_hash) and we're done.
*/
const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
const mbedtls_md_type_t md_alg = mbedtls_md_get_type(ctx->md_info);
/* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5,
* all of which have the same block size except SHA-384. */
const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
const unsigned char * const ikey = ctx->hmac_ctx;
const unsigned char * const okey = ikey + block_size;
const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
const size_t hash_size = mbedtls_md_get_size(ctx->md_info);
unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
mbedtls_md_context_t aux;
size_t offset;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md_init( &aux );
mbedtls_md_init(&aux);
#define MD_CHK( func_call ) \
#define MD_CHK(func_call) \
do { \
ret = (func_call); \
if( ret != 0 ) \
goto cleanup; \
} while( 0 )
if (ret != 0) \
goto cleanup; \
} while (0)
MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
MD_CHK(mbedtls_md_setup(&aux, ctx->md_info, 0));
/* After hmac_start() of hmac_reset(), ikey has already been hashed,
* so we can start directly with the message */
MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
MD_CHK(mbedtls_md_update(ctx, add_data, add_data_len));
MD_CHK(mbedtls_md_update(ctx, data, min_data_len));
/* Fill the hash buffer in advance with something that is
* not a valid hash (barring an attack on the hash and
* deliberately-crafted input), in case the caller doesn't
* check the return status properly. */
memset( output, '!', hash_size );
memset(output, '!', hash_size);
/* For each possible length, compute the hash up to that point */
for( offset = min_data_len; offset <= max_data_len; offset++ )
{
MD_CHK( mbedtls_md_clone( &aux, ctx ) );
MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
for (offset = min_data_len; offset <= max_data_len; offset++) {
MD_CHK(mbedtls_md_clone(&aux, ctx));
MD_CHK(mbedtls_md_finish(&aux, aux_out));
/* Keep only the correct inner_hash in the output buffer */
mbedtls_ct_memcpy_if_eq( output, aux_out, hash_size,
offset, data_len_secret );
mbedtls_ct_memcpy_if_eq(output, aux_out, hash_size,
offset, data_len_secret);
if( offset < max_data_len )
MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
if (offset < max_data_len) {
MD_CHK(mbedtls_md_update(ctx, data + offset, 1));
}
}
/* The context needs to finish() before it starts() again */
MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
MD_CHK(mbedtls_md_finish(ctx, aux_out));
/* Now compute HASH(okey + inner_hash) */
MD_CHK( mbedtls_md_starts( ctx ) );
MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
MD_CHK( mbedtls_md_finish( ctx, output ) );
MD_CHK(mbedtls_md_starts(ctx));
MD_CHK(mbedtls_md_update(ctx, okey, block_size));
MD_CHK(mbedtls_md_update(ctx, output, hash_size));
MD_CHK(mbedtls_md_finish(ctx, output));
/* Done, get ready for next time */
MD_CHK( mbedtls_md_hmac_reset( ctx ) );
MD_CHK(mbedtls_md_hmac_reset(ctx));
#undef MD_CHK
cleanup:
mbedtls_md_free( &aux );
return( ret );
mbedtls_md_free(&aux);
return ret;
}
#endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
#if defined(MBEDTLS_BIGNUM_C)
#define MPI_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
#define MPI_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA)
/*
* Conditionally assign X = Y, without leaking information
@@ -545,30 +544,31 @@ cleanup:
*/
__declspec(noinline)
#endif
int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X,
const mbedtls_mpi *Y,
unsigned char assign )
int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X,
const mbedtls_mpi *Y,
unsigned char assign)
{
int ret = 0;
size_t i;
mbedtls_mpi_uint limb_mask;
MPI_VALIDATE_RET( X != NULL );
MPI_VALIDATE_RET( Y != NULL );
MPI_VALIDATE_RET(X != NULL);
MPI_VALIDATE_RET(Y != NULL);
/* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
limb_mask = mbedtls_ct_mpi_uint_mask( assign );;
limb_mask = mbedtls_ct_mpi_uint_mask(assign);;
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
X->s = mbedtls_ct_cond_select_sign( assign, Y->s, X->s );
X->s = mbedtls_ct_cond_select_sign(assign, Y->s, X->s);
mbedtls_ct_mpi_uint_cond_assign( Y->n, X->p, Y->p, assign );
mbedtls_ct_mpi_uint_cond_assign(Y->n, X->p, Y->p, assign);
for( i = Y->n; i < X->n; i++ )
for (i = Y->n; i < X->n; i++) {
X->p[i] &= ~limb_mask;
}
cleanup:
return( ret );
return ret;
}
/*
@@ -577,73 +577,74 @@ cleanup:
* Here it is not ok to simply swap the pointers, which would lead to
* different memory access patterns when X and Y are used afterwards.
*/
int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X,
mbedtls_mpi *Y,
unsigned char swap )
int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X,
mbedtls_mpi *Y,
unsigned char swap)
{
int ret, s;
size_t i;
mbedtls_mpi_uint limb_mask;
mbedtls_mpi_uint tmp;
MPI_VALIDATE_RET( X != NULL );
MPI_VALIDATE_RET( Y != NULL );
MPI_VALIDATE_RET(X != NULL);
MPI_VALIDATE_RET(Y != NULL);
if( X == Y )
return( 0 );
if (X == Y) {
return 0;
}
/* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
limb_mask = mbedtls_ct_mpi_uint_mask( swap );
limb_mask = mbedtls_ct_mpi_uint_mask(swap);
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Y, X->n));
s = X->s;
X->s = mbedtls_ct_cond_select_sign( swap, Y->s, X->s );
Y->s = mbedtls_ct_cond_select_sign( swap, s, Y->s );
X->s = mbedtls_ct_cond_select_sign(swap, Y->s, X->s);
Y->s = mbedtls_ct_cond_select_sign(swap, s, Y->s);
for( i = 0; i < X->n; i++ )
{
for (i = 0; i < X->n; i++) {
tmp = X->p[i];
X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
X->p[i] = (X->p[i] & ~limb_mask) | (Y->p[i] & limb_mask);
Y->p[i] = (Y->p[i] & ~limb_mask) | (tmp & limb_mask);
}
cleanup:
return( ret );
return ret;
}
/*
* Compare signed values in constant time
*/
int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
const mbedtls_mpi *Y,
unsigned *ret )
int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X,
const mbedtls_mpi *Y,
unsigned *ret)
{
size_t i;
/* The value of any of these variables is either 0 or 1 at all times. */
unsigned cond, done, X_is_negative, Y_is_negative;
MPI_VALIDATE_RET( X != NULL );
MPI_VALIDATE_RET( Y != NULL );
MPI_VALIDATE_RET( ret != NULL );
MPI_VALIDATE_RET(X != NULL);
MPI_VALIDATE_RET(Y != NULL);
MPI_VALIDATE_RET(ret != NULL);
if( X->n != Y->n )
if (X->n != Y->n) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
/*
* Set sign_N to 1 if N >= 0, 0 if N < 0.
* We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
*/
X_is_negative = ( X->s & 2 ) >> 1;
Y_is_negative = ( Y->s & 2 ) >> 1;
X_is_negative = (X->s & 2) >> 1;
Y_is_negative = (Y->s & 2) >> 1;
/*
* If the signs are different, then the positive operand is the bigger.
* That is if X is negative (X_is_negative == 1), then X < Y is true and it
* is false if X is positive (X_is_negative == 0).
*/
cond = ( X_is_negative ^ Y_is_negative );
cond = (X_is_negative ^ Y_is_negative);
*ret = cond & X_is_negative;
/*
@@ -652,8 +653,7 @@ int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
*/
done = cond;
for( i = X->n; i > 0; i-- )
{
for (i = X->n; i > 0; i--) {
/*
* If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
* X and Y are negative.
@@ -661,8 +661,8 @@ int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
* Again even if we can make a decision, we just mark the result and
* the fact that we are done and continue looping.
*/
cond = mbedtls_ct_mpi_uint_lt( Y->p[i - 1], X->p[i - 1] );
*ret |= cond & ( 1 - done ) & X_is_negative;
cond = mbedtls_ct_mpi_uint_lt(Y->p[i - 1], X->p[i - 1]);
*ret |= cond & (1 - done) & X_is_negative;
done |= cond;
/*
@@ -672,24 +672,24 @@ int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
* Again even if we can make a decision, we just mark the result and
* the fact that we are done and continue looping.
*/
cond = mbedtls_ct_mpi_uint_lt( X->p[i - 1], Y->p[i - 1] );
*ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
cond = mbedtls_ct_mpi_uint_lt(X->p[i - 1], Y->p[i - 1]);
*ret |= cond & (1 - done) & (1 - X_is_negative);
done |= cond;
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_BIGNUM_C */
#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
unsigned char *input,
size_t ilen,
unsigned char *output,
size_t output_max_len,
size_t *olen )
int mbedtls_ct_rsaes_pkcs1_v15_unpadding(int mode,
unsigned char *input,
size_t ilen,
unsigned char *output,
size_t output_max_len,
size_t *olen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i, plaintext_max_size;
@@ -710,29 +710,25 @@ int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
size_t plaintext_size = 0;
unsigned output_too_large;
plaintext_max_size = ( output_max_len > ilen - 11 ) ? ilen - 11
plaintext_max_size = (output_max_len > ilen - 11) ? ilen - 11
: output_max_len;
/* Check and get padding length in constant time and constant
* memory trace. The first byte must be 0. */
bad |= input[0];
if( mode == MBEDTLS_RSA_PRIVATE )
{
if (mode == MBEDTLS_RSA_PRIVATE) {
/* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
* where PS must be at least 8 nonzero bytes. */
bad |= input[1] ^ MBEDTLS_RSA_CRYPT;
/* Read the whole buffer. Set pad_done to nonzero if we find
* the 0x00 byte and remember the padding length in pad_count. */
for( i = 2; i < ilen; i++ )
{
pad_done |= ((input[i] | (unsigned char)-input[i]) >> 7) ^ 1;
pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
for (i = 2; i < ilen; i++) {
pad_done |= ((input[i] | (unsigned char) -input[i]) >> 7) ^ 1;
pad_count += ((pad_done | (unsigned char) -pad_done) >> 7) ^ 1;
}
}
else
{
} else {
/* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
* where PS must be at least 8 bytes with the value 0xFF. */
bad |= input[1] ^ MBEDTLS_RSA_SIGN;
@@ -740,19 +736,18 @@ int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
/* Read the whole buffer. Set pad_done to nonzero if we find
* the 0x00 byte and remember the padding length in pad_count.
* If there's a non-0xff byte in the padding, the padding is bad. */
for( i = 2; i < ilen; i++ )
{
pad_done |= mbedtls_ct_uint_if( input[i], 0, 1 );
pad_count += mbedtls_ct_uint_if( pad_done, 0, 1 );
bad |= mbedtls_ct_uint_if( pad_done, 0, input[i] ^ 0xFF );
for (i = 2; i < ilen; i++) {
pad_done |= mbedtls_ct_uint_if(input[i], 0, 1);
pad_count += mbedtls_ct_uint_if(pad_done, 0, 1);
bad |= mbedtls_ct_uint_if(pad_done, 0, input[i] ^ 0xFF);
}
}
/* If pad_done is still zero, there's no data, only unfinished padding. */
bad |= mbedtls_ct_uint_if( pad_done, 0, 1 );
bad |= mbedtls_ct_uint_if(pad_done, 0, 1);
/* There must be at least 8 bytes of padding. */
bad |= mbedtls_ct_size_gt( 8, pad_count );
bad |= mbedtls_ct_size_gt(8, pad_count);
/* If the padding is valid, set plaintext_size to the number of
* remaining bytes after stripping the padding. If the padding
@@ -762,24 +757,24 @@ int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
* validity through timing. RSA keys are small enough that all the
* size_t values involved fit in unsigned int. */
plaintext_size = mbedtls_ct_uint_if(
bad, (unsigned) plaintext_max_size,
(unsigned) ( ilen - pad_count - 3 ) );
bad, (unsigned) plaintext_max_size,
(unsigned) (ilen - pad_count - 3));
/* Set output_too_large to 0 if the plaintext fits in the output
* buffer and to 1 otherwise. */
output_too_large = mbedtls_ct_size_gt( plaintext_size,
plaintext_max_size );
output_too_large = mbedtls_ct_size_gt(plaintext_size,
plaintext_max_size);
/* Set ret without branches to avoid timing attacks. Return:
* - INVALID_PADDING if the padding is bad (bad != 0).
* - OUTPUT_TOO_LARGE if the padding is good but the decrypted
* plaintext does not fit in the output buffer.
* - 0 if the padding is correct. */
ret = - (int) mbedtls_ct_uint_if(
bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
mbedtls_ct_uint_if( output_too_large,
- MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
0 ) );
ret = -(int) mbedtls_ct_uint_if(
bad, -MBEDTLS_ERR_RSA_INVALID_PADDING,
mbedtls_ct_uint_if(output_too_large,
-MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
0));
/* If the padding is bad or the plaintext is too large, zero the
* data that we're about to copy to the output buffer.
@@ -787,17 +782,18 @@ int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
* from the same buffer whether the padding is good or not to
* avoid leaking the padding validity through overall timing or
* through memory or cache access patterns. */
bad = mbedtls_ct_uint_mask( bad | output_too_large );
for( i = 11; i < ilen; i++ )
bad = mbedtls_ct_uint_mask(bad | output_too_large);
for (i = 11; i < ilen; i++) {
input[i] &= ~bad;
}
/* If the plaintext is too large, truncate it to the buffer size.
* Copy anyway to avoid revealing the length through timing, because
* revealing the length is as bad as revealing the padding validity
* for a Bleichenbacher attack. */
plaintext_size = mbedtls_ct_uint_if( output_too_large,
(unsigned) plaintext_max_size,
(unsigned) plaintext_size );
plaintext_size = mbedtls_ct_uint_if(output_too_large,
(unsigned) plaintext_max_size,
(unsigned) plaintext_size);
/* Move the plaintext to the leftmost position where it can start in
* the working buffer, i.e. make it start plaintext_max_size from
@@ -805,9 +801,9 @@ int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
* does not depend on the plaintext size. After this move, the
* starting location of the plaintext is no longer sensitive
* information. */
mbedtls_ct_mem_move_to_left( input + ilen - plaintext_max_size,
plaintext_max_size,
plaintext_max_size - plaintext_size );
mbedtls_ct_mem_move_to_left(input + ilen - plaintext_max_size,
plaintext_max_size,
plaintext_max_size - plaintext_size);
/* Finally copy the decrypted plaintext plus trailing zeros into the output
* buffer. If output_max_len is 0, then output may be an invalid pointer
@@ -816,8 +812,9 @@ int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
* user-provided output buffer), which is independent from plaintext
* length, validity of padding, success of the decryption, and other
* secrets. */
if( output_max_len != 0 )
memcpy( output, input + ilen - plaintext_max_size, plaintext_max_size );
if (output_max_len != 0) {
memcpy(output, input + ilen - plaintext_max_size, plaintext_max_size);
}
/* Report the amount of data we copied to the output buffer. In case
* of errors (bad padding or output too large), the value of *olen
@@ -825,7 +822,7 @@ int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
* to the good case limits the risks of leaking the padding validity. */
*olen = plaintext_size;
return( ret );
return ret;
}
#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */

View File

@@ -43,7 +43,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_MODES_USE_MAC)
@@ -58,7 +58,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_MODES_USE_MAC */
@@ -75,7 +75,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 */
@@ -94,8 +94,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 */
@@ -110,8 +110,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)
@@ -125,8 +125,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);
#endif /* MBEDTLS_BIGNUM_C */
@@ -141,9 +141,9 @@ unsigned mbedtls_ct_mpi_uint_lt( const mbedtls_mpi_uint x,
*
* \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)
@@ -159,10 +159,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 */
@@ -177,7 +177,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.
*
@@ -191,7 +191,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 */
@@ -208,10 +208,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.
*
@@ -239,12 +239,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.
*
@@ -282,14 +282,14 @@ void mbedtls_ct_memcpy_offset( unsigned char *dest,
* \retval #MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED
* The hardware accelerator failed.
*/
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_SSL_SOME_MODES_USE_MAC */
@@ -323,12 +323,12 @@ 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( int mode,
unsigned char *input,
size_t ilen,
unsigned char *output,
size_t output_max_len,
size_t *olen );
int mbedtls_ct_rsaes_pkcs1_v15_unpadding(int mode,
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 is 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)
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 */
#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

@@ -47,35 +47,38 @@
#if !defined(MBEDTLS_DHM_ALT)
#define DHM_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_DHM_BAD_INPUT_DATA )
#define DHM_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define DHM_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_DHM_BAD_INPUT_DATA)
#define DHM_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
/*
* 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;
}
/*
@@ -90,232 +93,242 @@ 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)
{
DHM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_dhm_context ) );
DHM_VALIDATE(ctx != NULL);
memset(ctx, 0, sizeof(mbedtls_dhm_context));
}
/*
* 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;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( p != NULL && *p != NULL );
DHM_VALIDATE_RET( end != NULL );
DHM_VALIDATE_RET(ctx != NULL);
DHM_VALIDATE_RET(p != NULL && *p != NULL);
DHM_VALIDATE_RET(end != NULL);
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;
}
ctx->len = mbedtls_mpi_size( &ctx->P );
ctx->len = mbedtls_mpi_size(&ctx->P);
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;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( output != NULL );
DHM_VALIDATE_RET( olen != NULL );
DHM_VALIDATE_RET( f_rng != NULL );
DHM_VALIDATE_RET(ctx != NULL);
DHM_VALIDATE_RET(output != NULL);
DHM_VALIDATE_RET(olen != NULL);
DHM_VALIDATE_RET(f_rng != NULL);
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;
ctx->len = n1;
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;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( P != NULL );
DHM_VALIDATE_RET( G != NULL );
DHM_VALIDATE_RET(ctx != NULL);
DHM_VALIDATE_RET(P != NULL);
DHM_VALIDATE_RET(G != NULL);
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);
}
ctx->len = mbedtls_mpi_size( &ctx->P );
return( 0 );
ctx->len = mbedtls_mpi_size(&ctx->P);
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;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( input != NULL );
DHM_VALIDATE_RET(ctx != NULL);
DHM_VALIDATE_RET(input != NULL);
if( ilen < 1 || ilen > ctx->len )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (ilen < 1 || ilen > ctx->len) {
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;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( output != NULL );
DHM_VALIDATE_RET( f_rng != NULL );
DHM_VALIDATE_RET(ctx != NULL);
DHM_VALIDATE_RET(output != NULL);
DHM_VALIDATE_RET(f_rng != NULL);
if( olen < 1 || olen > ctx->len )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (olen < 1 || olen > ctx->len) {
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;
}
@@ -325,40 +338,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;
}
/*
@@ -366,111 +377,113 @@ 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;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( output != NULL );
DHM_VALIDATE_RET( olen != NULL );
DHM_VALIDATE_RET(ctx != NULL);
DHM_VALIDATE_RET(output != NULL);
DHM_VALIDATE_RET(olen != NULL);
if( output_size < ctx->len )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if (output_size < ctx->len) {
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 */
if( f_rng != NULL )
{
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 ) );
if (f_rng != NULL) {
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));
} else {
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&GYb, &ctx->GY));
}
else
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &GYb, &ctx->GY ) );
/* 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 */
if( f_rng != NULL )
{
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 ) );
if (f_rng != NULL) {
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;
@@ -479,32 +492,32 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
mbedtls_pem_context pem;
#endif /* MBEDTLS_PEM_PARSE_C */
DHM_VALIDATE_RET( dhm != NULL );
DHM_VALIDATE_RET( dhmin != NULL );
DHM_VALIDATE_RET(dhm != NULL);
DHM_VALIDATE_RET(dhmin != NULL);
#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 */
@@ -517,55 +530,51 @@ 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;
}
}
ret = 0;
dhm->len = mbedtls_mpi_size( &dhm->P );
dhm->len = mbedtls_mpi_size(&dhm->P);
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)
@@ -576,71 +585,71 @@ 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 );
fseek( f, 0, SEEK_END );
if( ( size = ftell( f ) ) == -1 )
{
fclose( f );
return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );
if ((f = fopen(path, "rb")) == NULL) {
return MBEDTLS_ERR_DHM_FILE_IO_ERROR;
}
fseek( f, 0, SEEK_SET );
fseek(f, 0, SEEK_END);
if ((size = ftell(f)) == -1) {
fclose(f);
return MBEDTLS_ERR_DHM_FILE_IO_ERROR;
}
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;
DHM_VALIDATE_RET( dhm != NULL );
DHM_VALIDATE_RET( path != NULL );
DHM_VALIDATE_RET(dhm != NULL);
DHM_VALIDATE_RET(path != NULL);
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 */
@@ -650,60 +659,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

@@ -35,30 +35,30 @@
#include <string.h>
/* Parameter validation macros based on platform_util.h */
#define ECDH_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA )
#define ECDH_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define ECDH_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA)
#define ECDH_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
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)
@@ -69,41 +69,42 @@ 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)
{
ECDH_VALIDATE_RET( grp != NULL );
ECDH_VALIDATE_RET( d != NULL );
ECDH_VALIDATE_RET( Q != NULL );
ECDH_VALIDATE_RET( f_rng != NULL );
return( ecdh_gen_public_restartable( grp, d, Q, f_rng, p_rng, NULL ) );
ECDH_VALIDATE_RET(grp != NULL);
ECDH_VALIDATE_RET(d != NULL);
ECDH_VALIDATE_RET(Q != NULL);
ECDH_VALIDATE_RET(f_rng != NULL);
return ecdh_gen_public_restartable(grp, d, Q, f_rng, p_rng, NULL);
}
#endif /* !MBEDTLS_ECDH_GEN_PUBLIC_ALT */
@@ -111,79 +112,78 @@ 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)
{
ECDH_VALIDATE_RET( grp != NULL );
ECDH_VALIDATE_RET( Q != NULL );
ECDH_VALIDATE_RET( d != NULL );
ECDH_VALIDATE_RET( z != NULL );
return( ecdh_compute_shared_restartable( grp, z, Q, d,
f_rng, p_rng, NULL ) );
ECDH_VALIDATE_RET(grp != NULL);
ECDH_VALIDATE_RET(Q != NULL);
ECDH_VALIDATE_RET(d != NULL);
ECDH_VALIDATE_RET(z != 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)
{
ECDH_VALIDATE( ctx != NULL );
ECDH_VALIDATE(ctx != NULL);
#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
@@ -193,59 +193,57 @@ 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)
{
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET(ctx != NULL);
#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
}
@@ -253,9 +251,9 @@ 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)
{
ECDH_VALIDATE( ctx != NULL );
ECDH_VALIDATE(ctx != NULL);
ctx->restart_enabled = 1;
}
@@ -264,26 +262,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;
@@ -295,14 +293,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;
@@ -310,40 +308,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;
}
/*
@@ -353,16 +357,16 @@ 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;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( olen != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET( f_rng != NULL );
ECDH_VALIDATE_RET(ctx != NULL);
ECDH_VALIDATE_RET(olen != NULL);
ECDH_VALIDATE_RET(buf != NULL);
ECDH_VALIDATE_RET(f_rng != NULL);
#if defined(MBEDTLS_ECP_RESTARTABLE)
restart_enabled = ctx->restart_enabled;
@@ -371,33 +375,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);
}
/*
@@ -407,323 +410,330 @@ 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;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET( *buf != NULL );
ECDH_VALIDATE_RET( end != NULL );
ECDH_VALIDATE_RET(ctx != NULL);
ECDH_VALIDATE_RET(buf != NULL);
ECDH_VALIDATE_RET(*buf != NULL);
ECDH_VALIDATE_RET(end != NULL);
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;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( key != NULL );
ECDH_VALIDATE_RET( side == MBEDTLS_ECDH_OURS ||
side == MBEDTLS_ECDH_THEIRS );
ECDH_VALIDATE_RET(ctx != NULL);
ECDH_VALIDATE_RET(key != NULL);
ECDH_VALIDATE_RET(side == MBEDTLS_ECDH_OURS ||
side == MBEDTLS_ECDH_THEIRS);
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;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( olen != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET( f_rng != NULL );
ECDH_VALIDATE_RET(ctx != NULL);
ECDH_VALIDATE_RET(olen != NULL);
ECDH_VALIDATE_RET(buf != NULL);
ECDH_VALIDATE_RET(f_rng != NULL);
#if defined(MBEDTLS_ECP_RESTARTABLE)
restart_enabled = ctx->restart_enabled;
#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)
{
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET(ctx != NULL);
ECDH_VALIDATE_RET(buf != NULL);
#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;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( olen != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET(ctx != NULL);
ECDH_VALIDATE_RET(olen != NULL);
ECDH_VALIDATE_RET(buf != NULL);
#if defined(MBEDTLS_ECP_RESTARTABLE)
restart_enabled = ctx->restart_enabled;
#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

@@ -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

@@ -48,103 +48,104 @@
#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
#if defined(MBEDTLS_HAVEGE_C)
mbedtls_havege_init( &ctx->havege_data );
mbedtls_havege_init(&ctx->havege_data);
#endif
/* Reminder: Update ENTROPY_HAVE_STRONG in the test files
* when adding more strong entropy sources here. */
#if defined(MBEDTLS_TEST_NULL_ENTROPY)
mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL,
1, MBEDTLS_ENTROPY_SOURCE_STRONG );
mbedtls_entropy_add_source(ctx, mbedtls_null_entropy_poll, NULL,
1, MBEDTLS_ENTROPY_SOURCE_STRONG);
#endif
#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_TIMING_C)
mbedtls_entropy_add_source( ctx, mbedtls_hardclock_poll, NULL,
MBEDTLS_ENTROPY_MIN_HARDCLOCK,
MBEDTLS_ENTROPY_SOURCE_WEAK );
mbedtls_entropy_add_source(ctx, mbedtls_hardclock_poll, NULL,
MBEDTLS_ENTROPY_MIN_HARDCLOCK,
MBEDTLS_ENTROPY_SOURCE_WEAK);
#endif
#if defined(MBEDTLS_HAVEGE_C)
mbedtls_entropy_add_source( ctx, mbedtls_havege_poll, &ctx->havege_data,
MBEDTLS_ENTROPY_MIN_HAVEGE,
MBEDTLS_ENTROPY_SOURCE_STRONG );
mbedtls_entropy_add_source(ctx, mbedtls_havege_poll, &ctx->havege_data,
MBEDTLS_ENTROPY_MIN_HAVEGE,
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_HAVEGE_C)
mbedtls_havege_free( &ctx->havege_data );
mbedtls_havege_free(&ctx->havege_data);
#endif
#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;
}
@@ -158,18 +159,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];
@@ -177,14 +179,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_ret( data, len, tmp, 0 ) ) != 0 )
if ((ret = mbedtls_sha512_ret(data, len, tmp, 0)) != 0) {
goto cleanup;
}
#else
if( ( ret = mbedtls_sha256_ret( data, len, tmp, 0 ) ) != 0 )
if ((ret = mbedtls_sha256_ret(data, len, tmp, 0)) != 0) {
goto cleanup;
}
#endif
p = tmp;
use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
@@ -199,55 +202,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_ret( &ctx->accumulator, 0 ) ) != 0 )
if (ctx->accumulator_started == 0 &&
(ret = mbedtls_sha512_starts_ret(&ctx->accumulator, 0)) != 0) {
goto cleanup;
else
} else {
ctx->accumulator_started = 1;
if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )
}
if ((ret = mbedtls_sha512_update_ret(&ctx->accumulator, header, 2)) != 0) {
goto cleanup;
ret = mbedtls_sha512_update_ret( &ctx->accumulator, p, use_len );
}
ret = mbedtls_sha512_update_ret(&ctx->accumulator, p, use_len);
#else
if( ctx->accumulator_started == 0 &&
( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
if (ctx->accumulator_started == 0 &&
(ret = mbedtls_sha256_starts_ret(&ctx->accumulator, 0)) != 0) {
goto cleanup;
else
} else {
ctx->accumulator_started = 1;
if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )
}
if ((ret = mbedtls_sha256_update_ret(&ctx->accumulator, header, 2)) != 0) {
goto cleanup;
ret = mbedtls_sha256_update_ret( &ctx->accumulator, p, use_len );
}
ret = mbedtls_sha256_update_ret(&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;
@@ -255,121 +264,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)
/*
@@ -377,109 +390,118 @@ 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_ret( &ctx->accumulator, buf ) ) != 0 )
if ((ret = mbedtls_sha512_finish_ret(&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_ret( &ctx->accumulator, 0 ) ) != 0 )
mbedtls_sha512_free(&ctx->accumulator);
mbedtls_sha512_init(&ctx->accumulator);
if ((ret = mbedtls_sha512_starts_ret(&ctx->accumulator, 0)) != 0) {
goto exit;
if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
}
if ((ret = mbedtls_sha512_update_ret(&ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
goto exit;
}
/*
* Perform second SHA-512 on entropy
*/
if( ( ret = mbedtls_sha512_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
buf, 0 ) ) != 0 )
if ((ret = mbedtls_sha512_ret(buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
buf, 0)) != 0) {
goto exit;
}
#else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
if( ( ret = mbedtls_sha256_finish_ret( &ctx->accumulator, buf ) ) != 0 )
if ((ret = mbedtls_sha256_finish_ret(&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_ret( &ctx->accumulator, 0 ) ) != 0 )
mbedtls_sha256_free(&ctx->accumulator);
mbedtls_sha256_init(&ctx->accumulator);
if ((ret = mbedtls_sha256_starts_ret(&ctx->accumulator, 0)) != 0) {
goto exit;
if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
}
if ((ret = mbedtls_sha256_update_ret(&ctx->accumulator, buf,
MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
goto exit;
}
/*
* Perform second SHA-256 on entropy
*/
if( ( ret = mbedtls_sha256_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
buf, 0 ) ) != 0 )
if ((ret = mbedtls_sha256_ret(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;
}
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;
}
@@ -487,44 +509,49 @@ 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;
}
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 */
@@ -533,60 +560,58 @@ 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;
}
#endif /* !MBEDTLS_TEST_NULL_ENTROPY */
#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;
}
/*
@@ -600,45 +625,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 */
@@ -648,7 +678,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;
#if !defined(MBEDTLS_TEST_NULL_ENTROPY)
@@ -658,23 +688,27 @@ int mbedtls_entropy_self_test( int verbose )
size_t i, j;
#endif /* !MBEDTLS_TEST_NULL_ENTROPY */
if( verbose != 0 )
mbedtls_printf( " ENTROPY test: " );
if (verbose != 0) {
mbedtls_printf(" ENTROPY test: ");
}
#if !defined(MBEDTLS_TEST_NULL_ENTROPY)
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:
@@ -684,44 +718,44 @@ 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);
#endif /* !MBEDTLS_TEST_NULL_ENTROPY */
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

@@ -45,7 +45,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 config.h"
#error \
"Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in config.h"
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
@@ -56,29 +57,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 */
@@ -94,15 +93,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__ */
@@ -114,9 +113,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) */
@@ -136,7 +135,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;
@@ -144,23 +143,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;
@@ -168,14 +167,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);
@@ -184,105 +182,111 @@ 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 );
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 );
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_TEST_NULL_ENTROPY)
int mbedtls_null_entropy_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
int mbedtls_null_entropy_poll(void *data,
unsigned char *output, size_t len, size_t *olen)
{
((void) data);
((void) output);
*olen = 0;
if( len < sizeof(unsigned char) )
return( 0 );
if (len < sizeof(unsigned char)) {
return 0;
}
output[0] = 0;
*olen = sizeof(unsigned char);
return( 0 );
return 0;
}
#endif
#if defined(MBEDTLS_TIMING_C)
int mbedtls_hardclock_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
int mbedtls_hardclock_poll(void *data,
unsigned char *output, size_t len, size_t *olen)
{
unsigned long timer = mbedtls_timing_hardclock();
((void) data);
*olen = 0;
if( len < sizeof(unsigned long) )
return( 0 );
if (len < sizeof(unsigned long)) {
return 0;
}
memcpy( output, &timer, sizeof(unsigned long) );
memcpy(output, &timer, sizeof(unsigned long));
*olen = sizeof(unsigned long);
return( 0 );
return 0;
}
#endif /* MBEDTLS_TIMING_C */
#if defined(MBEDTLS_HAVEGE_C)
int mbedtls_havege_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
int mbedtls_havege_poll(void *data,
unsigned char *output, size_t len, size_t *olen)
{
mbedtls_havege_state *hs = (mbedtls_havege_state *) data;
*olen = 0;
if( mbedtls_havege_random( hs, output, len ) != 0 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
if (mbedtls_havege_random(hs, output, len) != 0) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
*olen = len;
return( 0 );
return 0;
}
#endif /* MBEDTLS_HAVEGE_C */
#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 */

File diff suppressed because it is too large Load Diff

View File

@@ -49,10 +49,10 @@
* ------------------------------------------------------------------------
*/
#define SWAP(X,Y) { uint32_t *T = (X); (X) = (Y); (Y) = T; }
#define SWAP(X, Y) { uint32_t *T = (X); (X) = (Y); (Y) = T; }
#define TST1_ENTER if( PTEST & 1 ) { PTEST ^= 3; PTEST >>= 1;
#define TST2_ENTER if( PTEST & 1 ) { PTEST ^= 3; PTEST >>= 1;
#define TST1_ENTER if (PTEST & 1) { PTEST ^= 3; PTEST >>= 1;
#define TST2_ENTER if (PTEST & 1) { PTEST ^= 3; PTEST >>= 1;
#define TST1_LEAVE U1++; }
#define TST2_LEAVE U2++; }
@@ -69,14 +69,14 @@
TST1_LEAVE TST1_LEAVE TST1_LEAVE TST1_LEAVE \
TST1_LEAVE TST1_LEAVE TST1_LEAVE TST1_LEAVE \
\
PTX = (PT1 >> 18) & 7; \
PTX = (PT1 >> 18) & 7; \
PT1 &= 0x1FFF; \
PT2 &= 0x1FFF; \
CLK = (uint32_t) mbedtls_timing_hardclock(); \
\
i = 0; \
A = &WALK[PT1 ]; RES[i++] ^= *A; \
B = &WALK[PT2 ]; RES[i++] ^= *B; \
A = &WALK[PT1]; RES[i++] ^= *A; \
B = &WALK[PT2]; RES[i++] ^= *B; \
C = &WALK[PT1 ^ 1]; RES[i++] ^= *C; \
D = &WALK[PT2 ^ 4]; RES[i++] ^= *D; \
\
@@ -91,7 +91,7 @@
C = &WALK[PT1 ^ 3]; RES[i++] ^= *C; \
D = &WALK[PT2 ^ 6]; RES[i++] ^= *D; \
\
if( PTEST & 1 ) SWAP( A, C ); \
if (PTEST & 1) SWAP(A, C); \
\
IN = (*A >> (5)) ^ (*A << (27)) ^ CLK; \
*A = (*B >> (6)) ^ (*B << (26)) ^ CLK; \
@@ -116,7 +116,7 @@
TST2_LEAVE TST2_LEAVE TST2_LEAVE TST2_LEAVE \
TST2_LEAVE TST2_LEAVE TST2_LEAVE TST2_LEAVE \
\
C = &WALK[PT1 ^ 5]; \
C = &WALK[PT1 ^ 5]; \
D = &WALK[PT2 ^ 5]; \
\
RES[i++] ^= *A; \
@@ -124,7 +124,7 @@
RES[i++] ^= *C; \
RES[i++] ^= *D; \
\
IN = (*A >> ( 9)) ^ (*A << (23)) ^ CLK; \
IN = (*A >> (9)) ^ (*A << (23)) ^ CLK; \
*A = (*B >> (10)) ^ (*B << (22)) ^ CLK; \
*B = IN ^ U2; \
*C = (*C >> (11)) ^ (*C << (21)) ^ CLK; \
@@ -141,17 +141,17 @@
*C = (*C >> (15)) ^ (*C << (17)) ^ CLK; \
*D = (*D >> (16)) ^ (*D << (16)) ^ CLK; \
\
PT1 = ( RES[( i - 8 ) ^ PTX] ^ \
WALK[PT1 ^ PTX ^ 7] ) & (~1); \
PT1 = (RES[(i - 8) ^ PTX] ^ \
WALK[PT1 ^ PTX ^ 7]) & (~1); \
PT1 ^= (PT2 ^ 0x10) & 0x10; \
\
for( n++, i = 0; i < 16; i++ ) \
hs->pool[n % MBEDTLS_HAVEGE_COLLECT_SIZE] ^= RES[i];
for (n++, i = 0; i < 16; i++) \
hs->pool[n % MBEDTLS_HAVEGE_COLLECT_SIZE] ^= RES[i];
/*
* Entropy gathering function
*/
static void havege_fill( mbedtls_havege_state *hs )
static void havege_fill(mbedtls_havege_state *hs)
{
size_t n = 0;
size_t i;
@@ -166,16 +166,15 @@ static void havege_fill( mbedtls_havege_state *hs )
PTX = U1 = 0;
PTY = U2 = 0;
(void)PTX;
(void) PTX;
memset( RES, 0, sizeof( RES ) );
memset(RES, 0, sizeof(RES));
while( n < MBEDTLS_HAVEGE_COLLECT_SIZE * 4 )
{
ONE_ITERATION
while (n < MBEDTLS_HAVEGE_COLLECT_SIZE * 4) {
ONE_ITERATION
ONE_ITERATION
ONE_ITERATION
ONE_ITERATION
}
hs->PT1 = PT1;
@@ -188,50 +187,52 @@ static void havege_fill( mbedtls_havege_state *hs )
/*
* HAVEGE initialization
*/
void mbedtls_havege_init( mbedtls_havege_state *hs )
void mbedtls_havege_init(mbedtls_havege_state *hs)
{
memset( hs, 0, sizeof( mbedtls_havege_state ) );
memset(hs, 0, sizeof(mbedtls_havege_state));
havege_fill( hs );
havege_fill(hs);
}
void mbedtls_havege_free( mbedtls_havege_state *hs )
void mbedtls_havege_free(mbedtls_havege_state *hs)
{
if( hs == NULL )
if (hs == NULL) {
return;
}
mbedtls_platform_zeroize( hs, sizeof( mbedtls_havege_state ) );
mbedtls_platform_zeroize(hs, sizeof(mbedtls_havege_state));
}
/*
* HAVEGE rand function
*/
int mbedtls_havege_random( void *p_rng, unsigned char *buf, size_t len )
int mbedtls_havege_random(void *p_rng, unsigned char *buf, size_t len)
{
uint32_t val;
size_t use_len;
mbedtls_havege_state *hs = (mbedtls_havege_state *) p_rng;
unsigned char *p = buf;
while( len > 0 )
{
while (len > 0) {
use_len = len;
if( use_len > sizeof( val ) )
use_len = sizeof( val );
if (use_len > sizeof(val)) {
use_len = sizeof(val);
}
if( hs->offset[1] >= MBEDTLS_HAVEGE_COLLECT_SIZE )
havege_fill( hs );
if (hs->offset[1] >= MBEDTLS_HAVEGE_COLLECT_SIZE) {
havege_fill(hs);
}
val = hs->pool[hs->offset[0]++];
val ^= hs->pool[hs->offset[1]++];
memcpy( p, &val, use_len );
memcpy(p, &val, use_len);
len -= use_len;
p += use_len;
}
return( 0 );
return 0;
}
#endif /* MBEDTLS_HAVEGE_C */

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,74 +52,81 @@ 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_ret( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional,
size_t add_len )
int mbedtls_hmac_drbg_update_ret(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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional,
size_t add_len )
void mbedtls_hmac_drbg_update(mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional,
size_t add_len)
{
(void) mbedtls_hmac_drbg_update_ret( ctx, additional, add_len );
(void) mbedtls_hmac_drbg_update_ret(ctx, additional, add_len);
}
#endif /* MBEDTLS_DEPRECATED_REMOVED */
/*
* 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
/*
@@ -127,15 +134,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_ret( ctx, data, data_len ) ) != 0 )
return( ret );
if ((ret = mbedtls_hmac_drbg_update_ret(ctx, data, data_len)) != 0) {
return ret;
}
return( 0 );
return 0;
}
/*
@@ -143,9 +152,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;
@@ -154,33 +163,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
@@ -188,11 +195,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;
@@ -200,32 +206,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_ret( ctx, seed, seedlen ) ) != 0 )
if ((ret = mbedtls_hmac_drbg_update_ret(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);
}
/*
@@ -234,40 +240,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,
@@ -280,20 +287,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;
}
@@ -301,7 +307,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;
}
@@ -309,7 +315,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;
}
@@ -318,131 +324,141 @@ 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_ret( ctx,
additional, add_len ) ) != 0 )
if (additional != NULL && add_len != 0) {
if ((ret = mbedtls_hmac_drbg_update_ret(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_ret( ctx,
additional, add_len ) ) != 0 )
if ((ret = mbedtls_hmac_drbg_update_ret(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;
}
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;
}
@@ -450,46 +466,47 @@ 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;
}
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_ret( ctx, buf, n );
ret = mbedtls_hmac_drbg_update_ret(ctx, buf, n);
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
if( f != NULL )
fclose( f );
if( ret != 0 )
return( ret );
return( mbedtls_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 */
@@ -498,10 +515,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
@@ -513,7 +530,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,
@@ -521,14 +539,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,
@@ -536,85 +556,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

@@ -67,21 +67,22 @@ static const unsigned char PI_SUBST[256] =
0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14
};
void mbedtls_md2_init( mbedtls_md2_context *ctx )
void mbedtls_md2_init(mbedtls_md2_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_md2_context ) );
memset(ctx, 0, sizeof(mbedtls_md2_context));
}
void mbedtls_md2_free( mbedtls_md2_context *ctx )
void mbedtls_md2_free(mbedtls_md2_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md2_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_md2_context));
}
void mbedtls_md2_clone( mbedtls_md2_context *dst,
const mbedtls_md2_context *src )
void mbedtls_md2_clone(mbedtls_md2_context *dst,
const mbedtls_md2_context *src)
{
*dst = *src;
}
@@ -89,67 +90,63 @@ void mbedtls_md2_clone( mbedtls_md2_context *dst,
/*
* MD2 context setup
*/
int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx )
int mbedtls_md2_starts_ret(mbedtls_md2_context *ctx)
{
memset( ctx->cksum, 0, 16 );
memset( ctx->state, 0, 46 );
memset( ctx->buffer, 0, 16 );
memset(ctx->cksum, 0, 16);
memset(ctx->state, 0, 46);
memset(ctx->buffer, 0, 16);
ctx->left = 0;
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_starts( mbedtls_md2_context *ctx )
void mbedtls_md2_starts(mbedtls_md2_context *ctx)
{
mbedtls_md2_starts_ret( ctx );
mbedtls_md2_starts_ret(ctx);
}
#endif
#if !defined(MBEDTLS_MD2_PROCESS_ALT)
int mbedtls_internal_md2_process( mbedtls_md2_context *ctx )
int mbedtls_internal_md2_process(mbedtls_md2_context *ctx)
{
int i, j;
unsigned char t = 0;
for( i = 0; i < 16; i++ )
{
for (i = 0; i < 16; i++) {
ctx->state[i + 16] = ctx->buffer[i];
ctx->state[i + 32] =
(unsigned char)( ctx->buffer[i] ^ ctx->state[i]);
(unsigned char) (ctx->buffer[i] ^ ctx->state[i]);
}
for( i = 0; i < 18; i++ )
{
for( j = 0; j < 48; j++ )
{
for (i = 0; i < 18; i++) {
for (j = 0; j < 48; j++) {
ctx->state[j] = (unsigned char)
( ctx->state[j] ^ PI_SUBST[t] );
(ctx->state[j] ^ PI_SUBST[t]);
t = ctx->state[j];
}
t = (unsigned char)( t + i );
t = (unsigned char) (t + i);
}
t = ctx->cksum[15];
for( i = 0; i < 16; i++ )
{
for (i = 0; i < 16; i++) {
ctx->cksum[i] = (unsigned char)
( ctx->cksum[i] ^ PI_SUBST[ctx->buffer[i] ^ t] );
(ctx->cksum[i] ^ PI_SUBST[ctx->buffer[i] ^ t]);
t = ctx->cksum[i];
}
/* Zeroise variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &t, sizeof( t ) );
mbedtls_platform_zeroize(&t, sizeof(t));
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_process( mbedtls_md2_context *ctx )
void mbedtls_md2_process(mbedtls_md2_context *ctx)
{
mbedtls_internal_md2_process( ctx );
mbedtls_internal_md2_process(ctx);
}
#endif
#endif /* !MBEDTLS_MD2_PROCESS_ALT */
@@ -157,78 +154,81 @@ void mbedtls_md2_process( mbedtls_md2_context *ctx )
/*
* MD2 process buffer
*/
int mbedtls_md2_update_ret( mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_md2_update_ret(mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
while( ilen > 0 )
{
if( ilen > 16 - ctx->left )
while (ilen > 0) {
if (ilen > 16 - ctx->left) {
fill = 16 - ctx->left;
else
} else {
fill = ilen;
}
memcpy( ctx->buffer + ctx->left, input, fill );
memcpy(ctx->buffer + ctx->left, input, fill);
ctx->left += fill;
input += fill;
ilen -= fill;
if( ctx->left == 16 )
{
if (ctx->left == 16) {
ctx->left = 0;
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_md2_process(ctx)) != 0) {
return ret;
}
}
}
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_update( mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen )
void mbedtls_md2_update(mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_md2_update_ret( ctx, input, ilen );
mbedtls_md2_update_ret(ctx, input, ilen);
}
#endif
/*
* MD2 final digest
*/
int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,
unsigned char output[16] )
int mbedtls_md2_finish_ret(mbedtls_md2_context *ctx,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i;
unsigned char x;
x = (unsigned char)( 16 - ctx->left );
x = (unsigned char) (16 - ctx->left);
for( i = ctx->left; i < 16; i++ )
for (i = ctx->left; i < 16; i++) {
ctx->buffer[i] = x;
}
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_md2_process(ctx)) != 0) {
return ret;
}
memcpy( ctx->buffer, ctx->cksum, 16 );
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
memcpy(ctx->buffer, ctx->cksum, 16);
if ((ret = mbedtls_internal_md2_process(ctx)) != 0) {
return ret;
}
memcpy( output, ctx->state, 16 );
memcpy(output, ctx->state, 16);
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_finish( mbedtls_md2_context *ctx,
unsigned char output[16] )
void mbedtls_md2_finish(mbedtls_md2_context *ctx,
unsigned char output[16])
{
mbedtls_md2_finish_ret( ctx, output );
mbedtls_md2_finish_ret(ctx, output);
}
#endif
@@ -237,36 +237,39 @@ void mbedtls_md2_finish( mbedtls_md2_context *ctx,
/*
* output = MD2( input buffer )
*/
int mbedtls_md2_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
int mbedtls_md2_ret(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md2_context ctx;
mbedtls_md2_init( &ctx );
mbedtls_md2_init(&ctx);
if( ( ret = mbedtls_md2_starts_ret( &ctx ) ) != 0 )
if ((ret = mbedtls_md2_starts_ret(&ctx)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md2_update_ret( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_md2_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md2_finish_ret( &ctx, output ) ) != 0 )
if ((ret = mbedtls_md2_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_md2_free( &ctx );
mbedtls_md2_free(&ctx);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
void mbedtls_md2(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
mbedtls_md2_ret( input, ilen, output );
mbedtls_md2_ret(input, ilen, output);
}
#endif
@@ -312,40 +315,43 @@ static const unsigned char md2_test_sum[7][16] =
/*
* Checkup routine
*/
int mbedtls_md2_self_test( int verbose )
int mbedtls_md2_self_test(int verbose)
{
int i, ret = 0;
unsigned char md2sum[16];
for( i = 0; i < 7; i++ )
{
if( verbose != 0 )
mbedtls_printf( " MD2 test #%d: ", i + 1 );
for (i = 0; i < 7; i++) {
if (verbose != 0) {
mbedtls_printf(" MD2 test #%d: ", i + 1);
}
ret = mbedtls_md2_ret( md2_test_str[i], md2_test_strlen[i], md2sum );
if( ret != 0 )
ret = mbedtls_md2_ret(md2_test_str[i], md2_test_strlen[i], md2sum);
if (ret != 0) {
goto fail;
}
if( memcmp( md2sum, md2_test_sum[i], 16 ) != 0 )
{
if (memcmp(md2sum, md2_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

@@ -37,21 +37,22 @@
#if !defined(MBEDTLS_MD4_ALT)
void mbedtls_md4_init( mbedtls_md4_context *ctx )
void mbedtls_md4_init(mbedtls_md4_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_md4_context ) );
memset(ctx, 0, sizeof(mbedtls_md4_context));
}
void mbedtls_md4_free( mbedtls_md4_context *ctx )
void mbedtls_md4_free(mbedtls_md4_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md4_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_md4_context));
}
void mbedtls_md4_clone( mbedtls_md4_context *dst,
const mbedtls_md4_context *src )
void mbedtls_md4_clone(mbedtls_md4_context *dst,
const mbedtls_md4_context *src)
{
*dst = *src;
}
@@ -59,7 +60,7 @@ void mbedtls_md4_clone( mbedtls_md4_context *dst,
/*
* MD4 context setup
*/
int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx )
int mbedtls_md4_starts_ret(mbedtls_md4_context *ctx)
{
ctx->total[0] = 0;
ctx->total[1] = 0;
@@ -69,43 +70,42 @@ int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx )
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_starts( mbedtls_md4_context *ctx )
void mbedtls_md4_starts(mbedtls_md4_context *ctx)
{
mbedtls_md4_starts_ret( ctx );
mbedtls_md4_starts_ret(ctx);
}
#endif
#if !defined(MBEDTLS_MD4_PROCESS_ALT)
int mbedtls_internal_md4_process( mbedtls_md4_context *ctx,
const unsigned char data[64] )
int mbedtls_internal_md4_process(mbedtls_md4_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))))
local.A = ctx->state[0];
local.B = ctx->state[1];
@@ -113,86 +113,86 @@ int mbedtls_internal_md4_process( mbedtls_md4_context *ctx,
local.D = ctx->state[3];
#define F(x, y, z) (((x) & (y)) | ((~(x)) & (z)))
#define P(a,b,c,d,x,s) \
#define P(a, b, c, d, x, s) \
do \
{ \
(a) += F((b),(c),(d)) + (x); \
(a) = S((a),(s)); \
} while( 0 )
(a) += F((b), (c), (d)) + (x); \
(a) = S((a), (s)); \
} while (0)
P( local.A, local.B, local.C, local.D, local.X[ 0], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 1], 7 );
P( local.C, local.D, local.A, local.B, local.X[ 2], 11 );
P( local.B, local.C, local.D, local.A, local.X[ 3], 19 );
P( local.A, local.B, local.C, local.D, local.X[ 4], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 5], 7 );
P( local.C, local.D, local.A, local.B, local.X[ 6], 11 );
P( local.B, local.C, local.D, local.A, local.X[ 7], 19 );
P( local.A, local.B, local.C, local.D, local.X[ 8], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 9], 7 );
P( local.C, local.D, local.A, local.B, local.X[10], 11 );
P( local.B, local.C, local.D, local.A, local.X[11], 19 );
P( local.A, local.B, local.C, local.D, local.X[12], 3 );
P( local.D, local.A, local.B, local.C, local.X[13], 7 );
P( local.C, local.D, local.A, local.B, local.X[14], 11 );
P( local.B, local.C, local.D, local.A, local.X[15], 19 );
P(local.A, local.B, local.C, local.D, local.X[0], 3);
P(local.D, local.A, local.B, local.C, local.X[1], 7);
P(local.C, local.D, local.A, local.B, local.X[2], 11);
P(local.B, local.C, local.D, local.A, local.X[3], 19);
P(local.A, local.B, local.C, local.D, local.X[4], 3);
P(local.D, local.A, local.B, local.C, local.X[5], 7);
P(local.C, local.D, local.A, local.B, local.X[6], 11);
P(local.B, local.C, local.D, local.A, local.X[7], 19);
P(local.A, local.B, local.C, local.D, local.X[8], 3);
P(local.D, local.A, local.B, local.C, local.X[9], 7);
P(local.C, local.D, local.A, local.B, local.X[10], 11);
P(local.B, local.C, local.D, local.A, local.X[11], 19);
P(local.A, local.B, local.C, local.D, local.X[12], 3);
P(local.D, local.A, local.B, local.C, local.X[13], 7);
P(local.C, local.D, local.A, local.B, local.X[14], 11);
P(local.B, local.C, local.D, local.A, local.X[15], 19);
#undef P
#undef F
#define F(x,y,z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
#define P(a,b,c,d,x,s) \
#define F(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
#define P(a, b, c, d, x, s) \
do \
{ \
(a) += F((b),(c),(d)) + (x) + 0x5A827999; \
(a) = S((a),(s)); \
} while( 0 )
(a) += F((b), (c), (d)) + (x) + 0x5A827999; \
(a) = S((a), (s)); \
} while (0)
P( local.A, local.B, local.C, local.D, local.X[ 0], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 4], 5 );
P( local.C, local.D, local.A, local.B, local.X[ 8], 9 );
P( local.B, local.C, local.D, local.A, local.X[12], 13 );
P( local.A, local.B, local.C, local.D, local.X[ 1], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 5], 5 );
P( local.C, local.D, local.A, local.B, local.X[ 9], 9 );
P( local.B, local.C, local.D, local.A, local.X[13], 13 );
P( local.A, local.B, local.C, local.D, local.X[ 2], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 6], 5 );
P( local.C, local.D, local.A, local.B, local.X[10], 9 );
P( local.B, local.C, local.D, local.A, local.X[14], 13 );
P( local.A, local.B, local.C, local.D, local.X[ 3], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 7], 5 );
P( local.C, local.D, local.A, local.B, local.X[11], 9 );
P( local.B, local.C, local.D, local.A, local.X[15], 13 );
P(local.A, local.B, local.C, local.D, local.X[0], 3);
P(local.D, local.A, local.B, local.C, local.X[4], 5);
P(local.C, local.D, local.A, local.B, local.X[8], 9);
P(local.B, local.C, local.D, local.A, local.X[12], 13);
P(local.A, local.B, local.C, local.D, local.X[1], 3);
P(local.D, local.A, local.B, local.C, local.X[5], 5);
P(local.C, local.D, local.A, local.B, local.X[9], 9);
P(local.B, local.C, local.D, local.A, local.X[13], 13);
P(local.A, local.B, local.C, local.D, local.X[2], 3);
P(local.D, local.A, local.B, local.C, local.X[6], 5);
P(local.C, local.D, local.A, local.B, local.X[10], 9);
P(local.B, local.C, local.D, local.A, local.X[14], 13);
P(local.A, local.B, local.C, local.D, local.X[3], 3);
P(local.D, local.A, local.B, local.C, local.X[7], 5);
P(local.C, local.D, local.A, local.B, local.X[11], 9);
P(local.B, local.C, local.D, local.A, local.X[15], 13);
#undef P
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
#define P(a,b,c,d,x,s) \
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define P(a, b, c, d, x, s) \
do \
{ \
(a) += F((b),(c),(d)) + (x) + 0x6ED9EBA1; \
(a) = S((a),(s)); \
} while( 0 )
(a) += F((b), (c), (d)) + (x) + 0x6ED9EBA1; \
(a) = S((a), (s)); \
} while (0)
P( local.A, local.B, local.C, local.D, local.X[ 0], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 8], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 4], 11 );
P( local.B, local.C, local.D, local.A, local.X[12], 15 );
P( local.A, local.B, local.C, local.D, local.X[ 2], 3 );
P( local.D, local.A, local.B, local.C, local.X[10], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 6], 11 );
P( local.B, local.C, local.D, local.A, local.X[14], 15 );
P( local.A, local.B, local.C, local.D, local.X[ 1], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 9], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 5], 11 );
P( local.B, local.C, local.D, local.A, local.X[13], 15 );
P( local.A, local.B, local.C, local.D, local.X[ 3], 3 );
P( local.D, local.A, local.B, local.C, local.X[11], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 7], 11 );
P( local.B, local.C, local.D, local.A, local.X[15], 15 );
P(local.A, local.B, local.C, local.D, local.X[0], 3);
P(local.D, local.A, local.B, local.C, local.X[8], 9);
P(local.C, local.D, local.A, local.B, local.X[4], 11);
P(local.B, local.C, local.D, local.A, local.X[12], 15);
P(local.A, local.B, local.C, local.D, local.X[2], 3);
P(local.D, local.A, local.B, local.C, local.X[10], 9);
P(local.C, local.D, local.A, local.B, local.X[6], 11);
P(local.B, local.C, local.D, local.A, local.X[14], 15);
P(local.A, local.B, local.C, local.D, local.X[1], 3);
P(local.D, local.A, local.B, local.C, local.X[9], 9);
P(local.C, local.D, local.A, local.B, local.X[5], 11);
P(local.B, local.C, local.D, local.A, local.X[13], 15);
P(local.A, local.B, local.C, local.D, local.X[3], 3);
P(local.D, local.A, local.B, local.C, local.X[11], 9);
P(local.C, local.D, local.A, local.B, local.X[7], 11);
P(local.B, local.C, local.D, local.A, local.X[15], 15);
#undef F
#undef P
@@ -203,16 +203,16 @@ int mbedtls_internal_md4_process( mbedtls_md4_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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_process( mbedtls_md4_context *ctx,
const unsigned char data[64] )
void mbedtls_md4_process(mbedtls_md4_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_md4_process( ctx, data );
mbedtls_internal_md4_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_MD4_PROCESS_ALT */
@@ -220,16 +220,17 @@ void mbedtls_md4_process( mbedtls_md4_context *ctx,
/*
* MD4 process buffer
*/
int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_md4_update_ret(mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen)
{
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;
@@ -237,52 +238,52 @@ int mbedtls_md4_update_ret( mbedtls_md4_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),
(void *) input, fill );
if (left && ilen >= fill) {
memcpy((void *) (ctx->buffer + left),
(void *) input, fill);
if( ( ret = mbedtls_internal_md4_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_md4_process(ctx, ctx->buffer)) != 0) {
return ret;
}
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
if( ( ret = mbedtls_internal_md4_process( ctx, input ) ) != 0 )
return( ret );
while (ilen >= 64) {
if ((ret = mbedtls_internal_md4_process(ctx, input)) != 0) {
return ret;
}
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
memcpy( (void *) (ctx->buffer + left),
(void *) input, ilen );
if (ilen > 0) {
memcpy((void *) (ctx->buffer + left),
(void *) input, ilen);
}
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_update( mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen )
void mbedtls_md4_update(mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_md4_update_ret( ctx, input, ilen );
mbedtls_md4_update_ret(ctx, input, ilen);
}
#endif
static const unsigned char md4_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
@@ -291,45 +292,47 @@ static const unsigned char md4_padding[64] =
/*
* MD4 final digest
*/
int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,
unsigned char output[16] )
int mbedtls_md4_finish_ret(mbedtls_md4_context *ctx,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint32_t last, padn;
uint32_t high, low;
unsigned char msglen[8];
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, msglen, 0 );
MBEDTLS_PUT_UINT32_LE( high, msglen, 4 );
MBEDTLS_PUT_UINT32_LE(low, msglen, 0);
MBEDTLS_PUT_UINT32_LE(high, msglen, 4);
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
padn = (last < 56) ? (56 - last) : (120 - last);
ret = mbedtls_md4_update_ret( ctx, (unsigned char *)md4_padding, padn );
if( ret != 0 )
return( ret );
ret = mbedtls_md4_update_ret(ctx, (unsigned char *) md4_padding, padn);
if (ret != 0) {
return ret;
}
if( ( ret = mbedtls_md4_update_ret( ctx, msglen, 8 ) ) != 0 )
return( ret );
if ((ret = mbedtls_md4_update_ret(ctx, msglen, 8)) != 0) {
return ret;
}
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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_finish( mbedtls_md4_context *ctx,
unsigned char output[16] )
void mbedtls_md4_finish(mbedtls_md4_context *ctx,
unsigned char output[16])
{
mbedtls_md4_finish_ret( ctx, output );
mbedtls_md4_finish_ret(ctx, output);
}
#endif
@@ -338,36 +341,39 @@ void mbedtls_md4_finish( mbedtls_md4_context *ctx,
/*
* output = MD4( input buffer )
*/
int mbedtls_md4_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
int mbedtls_md4_ret(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md4_context ctx;
mbedtls_md4_init( &ctx );
mbedtls_md4_init(&ctx);
if( ( ret = mbedtls_md4_starts_ret( &ctx ) ) != 0 )
if ((ret = mbedtls_md4_starts_ret(&ctx)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md4_update_ret( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_md4_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md4_finish_ret( &ctx, output ) ) != 0 )
if ((ret = mbedtls_md4_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_md4_free( &ctx );
mbedtls_md4_free(&ctx);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
void mbedtls_md4(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
mbedtls_md4_ret( input, ilen, output );
mbedtls_md4_ret(input, ilen, output);
}
#endif
@@ -413,40 +419,43 @@ static const unsigned char md4_test_sum[7][16] =
/*
* Checkup routine
*/
int mbedtls_md4_self_test( int verbose )
int mbedtls_md4_self_test(int verbose)
{
int i, ret = 0;
unsigned char md4sum[16];
for( i = 0; i < 7; i++ )
{
if( verbose != 0 )
mbedtls_printf( " MD4 test #%d: ", i + 1 );
for (i = 0; i < 7; i++) {
if (verbose != 0) {
mbedtls_printf(" MD4 test #%d: ", i + 1);
}
ret = mbedtls_md4_ret( md4_test_str[i], md4_test_strlen[i], md4sum );
if( ret != 0 )
ret = mbedtls_md4_ret(md4_test_str[i], md4_test_strlen[i], md4sum);
if (ret != 0) {
goto fail;
}
if( memcmp( md4sum, md4_test_sum[i], 16 ) != 0 )
{
if (memcmp(md4sum, md4_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

@@ -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_ret( mbedtls_md5_context *ctx )
int mbedtls_md5_starts_ret(mbedtls_md5_context *ctx)
{
ctx->total[0] = 0;
ctx->total[1] = 0;
@@ -68,138 +69,137 @@ int mbedtls_md5_starts_ret( mbedtls_md5_context *ctx )
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_starts( mbedtls_md5_context *ctx )
void mbedtls_md5_starts(mbedtls_md5_context *ctx)
{
mbedtls_md5_starts_ret( ctx );
mbedtls_md5_starts_ret(ctx);
}
#endif
#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
@@ -209,16 +209,16 @@ 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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_process( mbedtls_md5_context *ctx,
const unsigned char data[64] )
void mbedtls_md5_process(mbedtls_md5_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_md5_process( ctx, data );
mbedtls_internal_md5_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_MD5_PROCESS_ALT */
@@ -226,16 +226,17 @@ void mbedtls_md5_process( mbedtls_md5_context *ctx,
/*
* MD5 process buffer
*/
int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_md5_update_ret(mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen)
{
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;
@@ -243,51 +244,51 @@ int mbedtls_md5_update_ret( 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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_update( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen )
void mbedtls_md5_update(mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_md5_update_ret( ctx, input, ilen );
mbedtls_md5_update_ret(ctx, input, ilen);
}
#endif
/*
* MD5 final digest
*/
int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
unsigned char output[16] )
int mbedtls_md5_finish_ret(mbedtls_md5_context *ctx,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint32_t used;
@@ -300,51 +301,50 @@ int mbedtls_md5_finish_ret( 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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_finish( mbedtls_md5_context *ctx,
unsigned char output[16] )
void mbedtls_md5_finish(mbedtls_md5_context *ctx,
unsigned char output[16])
{
mbedtls_md5_finish_ret( ctx, output );
mbedtls_md5_finish_ret(ctx, output);
}
#endif
@@ -353,36 +353,39 @@ void mbedtls_md5_finish( mbedtls_md5_context *ctx,
/*
* output = MD5( input buffer )
*/
int mbedtls_md5_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
int mbedtls_md5_ret(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md5_context ctx;
mbedtls_md5_init( &ctx );
mbedtls_md5_init(&ctx);
if( ( ret = mbedtls_md5_starts_ret( &ctx ) ) != 0 )
if ((ret = mbedtls_md5_starts_ret(&ctx)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md5_update_ret( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_md5_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_md5_finish_ret( &ctx, output ) ) != 0 )
if ((ret = mbedtls_md5_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_md5_free( &ctx );
mbedtls_md5_free(&ctx);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
void mbedtls_md5(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
mbedtls_md5_ret( input, ilen, output );
mbedtls_md5_ret(input, ilen, output);
}
#endif
@@ -427,40 +430,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_ret( md5_test_buf[i], md5_test_buflen[i], md5sum );
if( ret != 0 )
ret = mbedtls_md5_ret(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

@@ -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,95 +442,97 @@ 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_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;
@@ -542,202 +540,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_EXPERIMENTAL */

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

@@ -41,23 +41,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; \
}
/*
@@ -65,26 +65,26 @@
* 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; \
}
/*
* Macro to generate a function for retrieving a single attribute from an
* 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
@@ -92,34 +92,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
@@ -127,20 +127,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
@@ -153,79 +153,84 @@ typedef struct {
static const oid_x520_attr_t oid_x520_attr_type[] =
{
{
{ ADD_LEN( MBEDTLS_OID_AT_CN ), "id-at-commonName", "Common Name" },
{ ADD_LEN(MBEDTLS_OID_AT_CN), "id-at-commonName", "Common Name" },
"CN",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_COUNTRY ), "id-at-countryName", "Country" },
{ ADD_LEN(MBEDTLS_OID_AT_COUNTRY), "id-at-countryName", "Country" },
"C",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_LOCALITY ), "id-at-locality", "Locality" },
{ ADD_LEN(MBEDTLS_OID_AT_LOCALITY), "id-at-locality", "Locality" },
"L",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_STATE ), "id-at-state", "State" },
{ ADD_LEN(MBEDTLS_OID_AT_STATE), "id-at-state", "State" },
"ST",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_ORGANIZATION ),"id-at-organizationName", "Organization" },
{ ADD_LEN(MBEDTLS_OID_AT_ORGANIZATION), "id-at-organizationName", "Organization" },
"O",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_ORG_UNIT ), "id-at-organizationalUnitName", "Org Unit" },
{ ADD_LEN(MBEDTLS_OID_AT_ORG_UNIT), "id-at-organizationalUnitName", "Org Unit" },
"OU",
},
{
{ ADD_LEN( MBEDTLS_OID_PKCS9_EMAIL ), "emailAddress", "E-mail address" },
{ ADD_LEN(MBEDTLS_OID_PKCS9_EMAIL), "emailAddress", "E-mail address" },
"emailAddress",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_SERIAL_NUMBER ),"id-at-serialNumber", "Serial number" },
{ ADD_LEN(MBEDTLS_OID_AT_SERIAL_NUMBER), "id-at-serialNumber", "Serial number" },
"serialNumber",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_POSTAL_ADDRESS ),"id-at-postalAddress", "Postal address" },
{ ADD_LEN(MBEDTLS_OID_AT_POSTAL_ADDRESS), "id-at-postalAddress",
"Postal address" },
"postalAddress",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_POSTAL_CODE ), "id-at-postalCode", "Postal code" },
{ ADD_LEN(MBEDTLS_OID_AT_POSTAL_CODE), "id-at-postalCode", "Postal code" },
"postalCode",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_SUR_NAME ), "id-at-surName", "Surname" },
{ ADD_LEN(MBEDTLS_OID_AT_SUR_NAME), "id-at-surName", "Surname" },
"SN",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_GIVEN_NAME ), "id-at-givenName", "Given name" },
{ ADD_LEN(MBEDTLS_OID_AT_GIVEN_NAME), "id-at-givenName", "Given name" },
"GN",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_INITIALS ), "id-at-initials", "Initials" },
{ ADD_LEN(MBEDTLS_OID_AT_INITIALS), "id-at-initials", "Initials" },
"initials",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_GENERATION_QUALIFIER ), "id-at-generationQualifier", "Generation qualifier" },
{ ADD_LEN(MBEDTLS_OID_AT_GENERATION_QUALIFIER), "id-at-generationQualifier",
"Generation qualifier" },
"generationQualifier",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_TITLE ), "id-at-title", "Title" },
{ ADD_LEN(MBEDTLS_OID_AT_TITLE), "id-at-title", "Title" },
"title",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_DN_QUALIFIER ),"id-at-dnQualifier", "Distinguished Name qualifier" },
{ ADD_LEN(MBEDTLS_OID_AT_DN_QUALIFIER), "id-at-dnQualifier",
"Distinguished Name qualifier" },
"dnQualifier",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_PSEUDONYM ), "id-at-pseudonym", "Pseudonym" },
{ ADD_LEN(MBEDTLS_OID_AT_PSEUDONYM), "id-at-pseudonym", "Pseudonym" },
"pseudonym",
},
{
{ ADD_LEN( MBEDTLS_OID_DOMAIN_COMPONENT ), "id-domainComponent", "Domain component" },
{ ADD_LEN(MBEDTLS_OID_DOMAIN_COMPONENT), "id-domainComponent",
"Domain component" },
"DC",
},
{
{ ADD_LEN( MBEDTLS_OID_AT_UNIQUE_IDENTIFIER ), "id-at-uniqueIdentifier", "Unique Identifier" },
{ ADD_LEN(MBEDTLS_OID_AT_UNIQUE_IDENTIFIER), "id-at-uniqueIdentifier",
"Unique Identifier" },
"uniqueIdentifier",
},
{
@@ -235,7 +240,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
@@ -248,27 +257,32 @@ typedef struct {
static const oid_x509_ext_t oid_x509_ext[] =
{
{
{ ADD_LEN( MBEDTLS_OID_BASIC_CONSTRAINTS ), "id-ce-basicConstraints", "Basic Constraints" },
{ ADD_LEN(MBEDTLS_OID_BASIC_CONSTRAINTS), "id-ce-basicConstraints",
"Basic Constraints" },
MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS,
},
{
{ ADD_LEN( MBEDTLS_OID_KEY_USAGE ), "id-ce-keyUsage", "Key Usage" },
{ ADD_LEN(MBEDTLS_OID_KEY_USAGE), "id-ce-keyUsage", "Key Usage" },
MBEDTLS_OID_X509_EXT_KEY_USAGE,
},
{
{ ADD_LEN( MBEDTLS_OID_EXTENDED_KEY_USAGE ), "id-ce-extKeyUsage", "Extended Key Usage" },
{ ADD_LEN(MBEDTLS_OID_EXTENDED_KEY_USAGE), "id-ce-extKeyUsage",
"Extended Key Usage" },
MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE,
},
{
{ ADD_LEN( MBEDTLS_OID_SUBJECT_ALT_NAME ), "id-ce-subjectAltName", "Subject Alt Name" },
{ ADD_LEN(MBEDTLS_OID_SUBJECT_ALT_NAME), "id-ce-subjectAltName",
"Subject Alt Name" },
MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME,
},
{
{ ADD_LEN( MBEDTLS_OID_NS_CERT_TYPE ), "id-netscape-certtype", "Netscape Certificate Type" },
{ ADD_LEN(MBEDTLS_OID_NS_CERT_TYPE), "id-netscape-certtype",
"Netscape Certificate Type" },
MBEDTLS_OID_X509_EXT_NS_CERT_TYPE,
},
{
{ ADD_LEN( MBEDTLS_OID_CERTIFICATE_POLICIES ), "id-ce-certificatePolicies", "Certificate Policies" },
{ ADD_LEN(MBEDTLS_OID_CERTIFICATE_POLICIES), "id-ce-certificatePolicies",
"Certificate Policies" },
MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES,
},
{
@@ -282,27 +296,38 @@ FN_OID_GET_ATTR1(mbedtls_oid_get_x509_ext_type, oid_x509_ext_t, x509_ext, int, e
static const mbedtls_oid_descriptor_t oid_ext_key_usage[] =
{
{ ADD_LEN( MBEDTLS_OID_SERVER_AUTH ), "id-kp-serverAuth", "TLS Web Server Authentication" },
{ ADD_LEN( MBEDTLS_OID_CLIENT_AUTH ), "id-kp-clientAuth", "TLS Web Client Authentication" },
{ ADD_LEN( MBEDTLS_OID_CODE_SIGNING ), "id-kp-codeSigning", "Code Signing" },
{ ADD_LEN( MBEDTLS_OID_EMAIL_PROTECTION ), "id-kp-emailProtection", "E-mail Protection" },
{ ADD_LEN( MBEDTLS_OID_TIME_STAMPING ), "id-kp-timeStamping", "Time Stamping" },
{ ADD_LEN( MBEDTLS_OID_OCSP_SIGNING ), "id-kp-OCSPSigning", "OCSP Signing" },
{ ADD_LEN( MBEDTLS_OID_WISUN_FAN ), "id-kp-wisun-fan-device", "Wi-SUN Alliance Field Area Network (FAN)" },
{ ADD_LEN(MBEDTLS_OID_SERVER_AUTH), "id-kp-serverAuth",
"TLS Web Server Authentication" },
{ ADD_LEN(MBEDTLS_OID_CLIENT_AUTH), "id-kp-clientAuth",
"TLS Web Client Authentication" },
{ ADD_LEN(MBEDTLS_OID_CODE_SIGNING), "id-kp-codeSigning", "Code Signing" },
{ ADD_LEN(MBEDTLS_OID_EMAIL_PROTECTION), "id-kp-emailProtection", "E-mail Protection" },
{ ADD_LEN(MBEDTLS_OID_TIME_STAMPING), "id-kp-timeStamping", "Time Stamping" },
{ ADD_LEN(MBEDTLS_OID_OCSP_SIGNING), "id-kp-OCSPSigning", "OCSP Signing" },
{ ADD_LEN(MBEDTLS_OID_WISUN_FAN), "id-kp-wisun-fan-device",
"Wi-SUN Alliance Field Area Network (FAN)" },
{ NULL, 0, NULL, NULL },
};
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[] =
{
{ ADD_LEN( MBEDTLS_OID_ANY_POLICY ), "anyPolicy", "Any Policy" },
{ ADD_LEN(MBEDTLS_OID_ANY_POLICY), "anyPolicy", "Any Policy" },
{ NULL, 0, NULL, NULL },
};
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)
#if defined(MBEDTLS_MD_C)
/*
@@ -319,51 +344,51 @@ static const oid_sig_alg_t oid_sig_alg[] =
#if defined(MBEDTLS_RSA_C)
#if defined(MBEDTLS_MD2_C)
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_MD2 ), "md2WithRSAEncryption", "RSA with MD2" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_MD2), "md2WithRSAEncryption", "RSA with MD2" },
MBEDTLS_MD_MD2, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_MD2_C */
#if defined(MBEDTLS_MD4_C)
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_MD4 ), "md4WithRSAEncryption", "RSA with MD4" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_MD4), "md4WithRSAEncryption", "RSA with MD4" },
MBEDTLS_MD_MD4, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_MD4_C */
#if defined(MBEDTLS_MD5_C)
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_MD5 ), "md5WithRSAEncryption", "RSA with MD5" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_MD5), "md5WithRSAEncryption", "RSA with MD5" },
MBEDTLS_MD_MD5, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_MD5_C */
#if defined(MBEDTLS_SHA1_C)
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_SHA1 ), "sha-1WithRSAEncryption", "RSA with SHA1" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_SHA1), "sha-1WithRSAEncryption", "RSA with SHA1" },
MBEDTLS_MD_SHA1, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_SHA1_C */
#if defined(MBEDTLS_SHA256_C)
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_SHA224 ), "sha224WithRSAEncryption", "RSA with SHA-224" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_SHA224), "sha224WithRSAEncryption", "RSA with SHA-224" },
MBEDTLS_MD_SHA224, MBEDTLS_PK_RSA,
},
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_SHA256 ), "sha256WithRSAEncryption", "RSA with SHA-256" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_SHA256), "sha256WithRSAEncryption", "RSA with SHA-256" },
MBEDTLS_MD_SHA256, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA512_C)
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_SHA384 ), "sha384WithRSAEncryption", "RSA with SHA-384" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_SHA384), "sha384WithRSAEncryption", "RSA with SHA-384" },
MBEDTLS_MD_SHA384, MBEDTLS_PK_RSA,
},
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_SHA512 ), "sha512WithRSAEncryption", "RSA with SHA-512" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_SHA512), "sha512WithRSAEncryption", "RSA with SHA-512" },
MBEDTLS_MD_SHA512, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_SHA512_C */
#if defined(MBEDTLS_SHA1_C)
{
{ ADD_LEN( MBEDTLS_OID_RSA_SHA_OBS ), "sha-1WithRSAEncryption", "RSA with SHA1" },
{ ADD_LEN(MBEDTLS_OID_RSA_SHA_OBS), "sha-1WithRSAEncryption", "RSA with SHA1" },
MBEDTLS_MD_SHA1, MBEDTLS_PK_RSA,
},
#endif /* MBEDTLS_SHA1_C */
@@ -371,34 +396,34 @@ static const oid_sig_alg_t oid_sig_alg[] =
#if defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_SHA1_C)
{
{ ADD_LEN( MBEDTLS_OID_ECDSA_SHA1 ), "ecdsa-with-SHA1", "ECDSA with SHA1" },
{ ADD_LEN(MBEDTLS_OID_ECDSA_SHA1), "ecdsa-with-SHA1", "ECDSA with SHA1" },
MBEDTLS_MD_SHA1, MBEDTLS_PK_ECDSA,
},
#endif /* MBEDTLS_SHA1_C */
#if defined(MBEDTLS_SHA256_C)
{
{ ADD_LEN( MBEDTLS_OID_ECDSA_SHA224 ), "ecdsa-with-SHA224", "ECDSA with SHA224" },
{ ADD_LEN(MBEDTLS_OID_ECDSA_SHA224), "ecdsa-with-SHA224", "ECDSA with SHA224" },
MBEDTLS_MD_SHA224, MBEDTLS_PK_ECDSA,
},
{
{ ADD_LEN( MBEDTLS_OID_ECDSA_SHA256 ), "ecdsa-with-SHA256", "ECDSA with SHA256" },
{ ADD_LEN(MBEDTLS_OID_ECDSA_SHA256), "ecdsa-with-SHA256", "ECDSA with SHA256" },
MBEDTLS_MD_SHA256, MBEDTLS_PK_ECDSA,
},
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA512_C)
{
{ ADD_LEN( MBEDTLS_OID_ECDSA_SHA384 ), "ecdsa-with-SHA384", "ECDSA with SHA384" },
{ ADD_LEN(MBEDTLS_OID_ECDSA_SHA384), "ecdsa-with-SHA384", "ECDSA with SHA384" },
MBEDTLS_MD_SHA384, MBEDTLS_PK_ECDSA,
},
{
{ ADD_LEN( MBEDTLS_OID_ECDSA_SHA512 ), "ecdsa-with-SHA512", "ECDSA with SHA512" },
{ ADD_LEN(MBEDTLS_OID_ECDSA_SHA512), "ecdsa-with-SHA512", "ECDSA with SHA512" },
MBEDTLS_MD_SHA512, MBEDTLS_PK_ECDSA,
},
#endif /* MBEDTLS_SHA512_C */
#endif /* MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_RSA_C)
{
{ ADD_LEN( MBEDTLS_OID_RSASSA_PSS ), "RSASSA-PSS", "RSASSA-PSS" },
{ ADD_LEN(MBEDTLS_OID_RSASSA_PSS), "RSASSA-PSS", "RSASSA-PSS" },
MBEDTLS_MD_NONE, MBEDTLS_PK_RSASSA_PSS,
},
#endif /* MBEDTLS_RSA_C */
@@ -409,9 +434,25 @@ static const oid_sig_alg_t oid_sig_alg[] =
};
FN_OID_TYPED_FROM_ASN1(oid_sig_alg_t, sig_alg, oid_sig_alg)
FN_OID_GET_DESCRIPTOR_ATTR1(mbedtls_oid_get_sig_alg_desc, oid_sig_alg_t, sig_alg, const char *, description)
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_DESCRIPTOR_ATTR1(mbedtls_oid_get_sig_alg_desc,
oid_sig_alg_t,
sig_alg,
const char *,
description)
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)
#endif /* MBEDTLS_MD_C */
/*
@@ -425,15 +466,15 @@ typedef struct {
static const oid_pk_alg_t oid_pk_alg[] =
{
{
{ ADD_LEN( MBEDTLS_OID_PKCS1_RSA ), "rsaEncryption", "RSA" },
{ ADD_LEN(MBEDTLS_OID_PKCS1_RSA), "rsaEncryption", "RSA" },
MBEDTLS_PK_RSA,
},
{
{ ADD_LEN( MBEDTLS_OID_EC_ALG_UNRESTRICTED ), "id-ecPublicKey", "Generic EC key" },
{ ADD_LEN(MBEDTLS_OID_EC_ALG_UNRESTRICTED), "id-ecPublicKey", "Generic EC key" },
MBEDTLS_PK_ECKEY,
},
{
{ ADD_LEN( MBEDTLS_OID_EC_ALG_ECDH ), "id-ecDH", "EC key for ECDH" },
{ ADD_LEN(MBEDTLS_OID_EC_ALG_ECDH), "id-ecDH", "EC key for ECDH" },
MBEDTLS_PK_ECKEY_DH,
},
{
@@ -444,7 +485,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)
/*
@@ -459,67 +504,67 @@ static const oid_ecp_grp_t oid_ecp_grp[] =
{
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP192R1 ), "secp192r1", "secp192r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP192R1), "secp192r1", "secp192r1" },
MBEDTLS_ECP_DP_SECP192R1,
},
#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP224R1 ), "secp224r1", "secp224r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP224R1), "secp224r1", "secp224r1" },
MBEDTLS_ECP_DP_SECP224R1,
},
#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP256R1 ), "secp256r1", "secp256r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP256R1), "secp256r1", "secp256r1" },
MBEDTLS_ECP_DP_SECP256R1,
},
#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP384R1 ), "secp384r1", "secp384r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP384R1), "secp384r1", "secp384r1" },
MBEDTLS_ECP_DP_SECP384R1,
},
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP521R1 ), "secp521r1", "secp521r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP521R1), "secp521r1", "secp521r1" },
MBEDTLS_ECP_DP_SECP521R1,
},
#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP192K1 ), "secp192k1", "secp192k1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP192K1), "secp192k1", "secp192k1" },
MBEDTLS_ECP_DP_SECP192K1,
},
#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP224K1 ), "secp224k1", "secp224k1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP224K1), "secp224k1", "secp224k1" },
MBEDTLS_ECP_DP_SECP224K1,
},
#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_SECP256K1 ), "secp256k1", "secp256k1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_SECP256K1), "secp256k1", "secp256k1" },
MBEDTLS_ECP_DP_SECP256K1,
},
#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_BP256R1 ), "brainpoolP256r1","brainpool256r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_BP256R1), "brainpoolP256r1", "brainpool256r1" },
MBEDTLS_ECP_DP_BP256R1,
},
#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_BP384R1 ), "brainpoolP384r1","brainpool384r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_BP384R1), "brainpoolP384r1", "brainpool384r1" },
MBEDTLS_ECP_DP_BP384R1,
},
#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
{
{ ADD_LEN( MBEDTLS_OID_EC_GRP_BP512R1 ), "brainpoolP512r1","brainpool512r1" },
{ ADD_LEN(MBEDTLS_OID_EC_GRP_BP512R1), "brainpoolP512r1", "brainpool512r1" },
MBEDTLS_ECP_DP_BP512R1,
},
#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */
@@ -531,7 +576,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)
@@ -546,11 +595,11 @@ typedef struct {
static const oid_cipher_alg_t oid_cipher_alg[] =
{
{
{ ADD_LEN( MBEDTLS_OID_DES_CBC ), "desCBC", "DES-CBC" },
{ ADD_LEN(MBEDTLS_OID_DES_CBC), "desCBC", "DES-CBC" },
MBEDTLS_CIPHER_DES_CBC,
},
{
{ ADD_LEN( MBEDTLS_OID_DES_EDE3_CBC ), "des-ede3-cbc", "DES-EDE3-CBC" },
{ ADD_LEN(MBEDTLS_OID_DES_EDE3_CBC), "des-ede3-cbc", "DES-EDE3-CBC" },
MBEDTLS_CIPHER_DES_EDE3_CBC,
},
{
@@ -560,7 +609,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 */
#if defined(MBEDTLS_MD_C)
@@ -576,51 +629,51 @@ static const oid_md_alg_t oid_md_alg[] =
{
#if defined(MBEDTLS_MD2_C)
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD2 ), "id-md2", "MD2" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_MD2), "id-md2", "MD2" },
MBEDTLS_MD_MD2,
},
#endif /* MBEDTLS_MD2_C */
#if defined(MBEDTLS_MD4_C)
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD4 ), "id-md4", "MD4" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_MD4), "id-md4", "MD4" },
MBEDTLS_MD_MD4,
},
#endif /* MBEDTLS_MD4_C */
#if defined(MBEDTLS_MD5_C)
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD5 ), "id-md5", "MD5" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_MD5), "id-md5", "MD5" },
MBEDTLS_MD_MD5,
},
#endif /* MBEDTLS_MD5_C */
#if defined(MBEDTLS_SHA1_C)
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA1 ), "id-sha1", "SHA-1" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_SHA1), "id-sha1", "SHA-1" },
MBEDTLS_MD_SHA1,
},
#endif /* MBEDTLS_SHA1_C */
#if defined(MBEDTLS_SHA256_C)
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA224 ), "id-sha224", "SHA-224" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_SHA224), "id-sha224", "SHA-224" },
MBEDTLS_MD_SHA224,
},
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA256 ), "id-sha256", "SHA-256" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_SHA256), "id-sha256", "SHA-256" },
MBEDTLS_MD_SHA256,
},
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA512_C)
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA384 ), "id-sha384", "SHA-384" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_SHA384), "id-sha384", "SHA-384" },
MBEDTLS_MD_SHA384,
},
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA512 ), "id-sha512", "SHA-512" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_SHA512), "id-sha512", "SHA-512" },
MBEDTLS_MD_SHA512,
},
#endif /* MBEDTLS_SHA512_C */
#if defined(MBEDTLS_RIPEMD160_C)
{
{ ADD_LEN( MBEDTLS_OID_DIGEST_ALG_RIPEMD160 ), "id-ripemd160", "RIPEMD-160" },
{ ADD_LEN(MBEDTLS_OID_DIGEST_ALG_RIPEMD160), "id-ripemd160", "RIPEMD-160" },
MBEDTLS_MD_RIPEMD160,
},
#endif /* MBEDTLS_RIPEMD160_C */
@@ -632,7 +685,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
@@ -646,27 +703,27 @@ static const oid_md_hmac_t oid_md_hmac[] =
{
#if defined(MBEDTLS_SHA1_C)
{
{ ADD_LEN( MBEDTLS_OID_HMAC_SHA1 ), "hmacSHA1", "HMAC-SHA-1" },
{ ADD_LEN(MBEDTLS_OID_HMAC_SHA1), "hmacSHA1", "HMAC-SHA-1" },
MBEDTLS_MD_SHA1,
},
#endif /* MBEDTLS_SHA1_C */
#if defined(MBEDTLS_SHA256_C)
{
{ ADD_LEN( MBEDTLS_OID_HMAC_SHA224 ), "hmacSHA224", "HMAC-SHA-224" },
{ ADD_LEN(MBEDTLS_OID_HMAC_SHA224), "hmacSHA224", "HMAC-SHA-224" },
MBEDTLS_MD_SHA224,
},
{
{ ADD_LEN( MBEDTLS_OID_HMAC_SHA256 ), "hmacSHA256", "HMAC-SHA-256" },
{ ADD_LEN(MBEDTLS_OID_HMAC_SHA256), "hmacSHA256", "HMAC-SHA-256" },
MBEDTLS_MD_SHA256,
},
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA512_C)
{
{ ADD_LEN( MBEDTLS_OID_HMAC_SHA384 ), "hmacSHA384", "HMAC-SHA-384" },
{ ADD_LEN(MBEDTLS_OID_HMAC_SHA384), "hmacSHA384", "HMAC-SHA-384" },
MBEDTLS_MD_SHA384,
},
{
{ ADD_LEN( MBEDTLS_OID_HMAC_SHA512 ), "hmacSHA512", "HMAC-SHA-512" },
{ ADD_LEN(MBEDTLS_OID_HMAC_SHA512), "hmacSHA512", "HMAC-SHA-512" },
MBEDTLS_MD_SHA512,
},
#endif /* MBEDTLS_SHA512_C */
@@ -693,11 +750,13 @@ typedef struct {
static const oid_pkcs12_pbe_alg_t oid_pkcs12_pbe_alg[] =
{
{
{ ADD_LEN( MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC ), "pbeWithSHAAnd3-KeyTripleDES-CBC", "PBE with SHA1 and 3-Key 3DES" },
{ ADD_LEN(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,
},
{
{ ADD_LEN( MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC ), "pbeWithSHAAnd2-KeyTripleDES-CBC", "PBE with SHA1 and 2-Key 3DES" },
{ ADD_LEN(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,
},
{
@@ -707,21 +766,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;
@@ -732,32 +797,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;
@@ -85,13 +84,13 @@ int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
unsigned char buf[256];
rk = ctx->rk;
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"
@@ -103,22 +102,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;
@@ -127,20 +126,21 @@ int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,
uint32_t *ctrl;
unsigned char buf[256];
if( ( (long) input & 15 ) != 0 ||
( (long) output & 15 ) != 0 )
return( MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED );
if (((long) input & 15) != 0 ||
((long) output & 15) != 0) {
return MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED;
}
rk = ctx->rk;
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"
@@ -153,12 +153,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

@@ -35,151 +35,170 @@
#include "mbedtls/platform.h"
#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(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \
( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
(defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C))
/*
* 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;
}
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_ret( &md5_ctx ) ) != 0 )
if ((ret = mbedtls_md5_starts_ret(&md5_ctx)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )
}
if ((ret = mbedtls_md5_update_ret(&md5_ctx, pwd, pwdlen)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ) != 0 )
}
if ((ret = mbedtls_md5_update_ret(&md5_ctx, iv, 8)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )
goto exit;
if( keylen <= 16 )
{
memcpy( key, md5sum, keylen );
}
if ((ret = mbedtls_md5_finish_ret(&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_ret( &md5_ctx ) ) != 0 )
if ((ret = mbedtls_md5_starts_ret(&md5_ctx)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, md5sum, 16 ) ) != 0 )
}
if ((ret = mbedtls_md5_update_ret(&md5_ctx, md5sum, 16)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )
}
if ((ret = mbedtls_md5_update_ret(&md5_ctx, pwd, pwdlen)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ) != 0 )
}
if ((ret = mbedtls_md5_update_ret(&md5_ctx, iv, 8)) != 0) {
goto exit;
if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )
}
if ((ret = mbedtls_md5_finish_ret(&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;
}
#if defined(MBEDTLS_DES_C)
/*
* 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 */
@@ -187,45 +206,47 @@ 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 /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
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;
unsigned char *buf;
const unsigned char *s1, *s2, *end;
#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \
( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
(defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C))
unsigned char pem_iv[16];
mbedtls_cipher_type_t enc_alg = MBEDTLS_CIPHER_NONE;
#else
@@ -234,154 +255,181 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
if( 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(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \
( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
(defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C))
enc++;
s1 += 22;
if( *s1 == '\r' ) s1++;
if( *s1 == '\n' ) s1++;
else return( MBEDTLS_ERR_PEM_INVALID_DATA );
if (*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 /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
}
if( s1 >= s2 )
return( MBEDTLS_ERR_PEM_INVALID_DATA );
ret = mbedtls_base64_decode( NULL, 0, &len, s1, s2 - s1 );
if( ret == MBEDTLS_ERR_BASE64_INVALID_CHARACTER )
return( MBEDTLS_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(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \
( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
if( pwd == NULL )
{
mbedtls_platform_zeroize( buf, len );
mbedtls_free( buf );
return( MBEDTLS_ERR_PEM_PASSWORD_REQUIRED );
(defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C))
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;
}
/*
@@ -390,16 +438,15 @@ 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 /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
}
@@ -407,77 +454,73 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const
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 */

View File

@@ -44,17 +44,17 @@
#include <stdint.h>
/* Parameter validation macros based on platform_util.h */
#define PK_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA )
#define PK_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define PK_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA)
#define PK_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
/*
* Initialise a mbedtls_pk_context
*/
void mbedtls_pk_init( mbedtls_pk_context *ctx )
void mbedtls_pk_init(mbedtls_pk_context *ctx)
{
PK_VALIDATE( ctx != NULL );
PK_VALIDATE(ctx != NULL);
ctx->pk_info = NULL;
ctx->pk_ctx = NULL;
@@ -63,24 +63,26 @@ void mbedtls_pk_init( mbedtls_pk_context *ctx )
/*
* Free (the components of) a mbedtls_pk_context
*/
void mbedtls_pk_free( mbedtls_pk_context *ctx )
void mbedtls_pk_free(mbedtls_pk_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
if ( ctx->pk_info != NULL )
ctx->pk_info->ctx_free_func( ctx->pk_ctx );
if (ctx->pk_info != NULL) {
ctx->pk_info->ctx_free_func(ctx->pk_ctx);
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pk_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_pk_context));
}
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/*
* Initialize a restart context
*/
void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx )
void mbedtls_pk_restart_init(mbedtls_pk_restart_ctx *ctx)
{
PK_VALIDATE( ctx != NULL );
PK_VALIDATE(ctx != NULL);
ctx->pk_info = NULL;
ctx->rs_ctx = NULL;
}
@@ -88,15 +90,14 @@ void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx )
/*
* Free the components of a restart context
*/
void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx )
void mbedtls_pk_restart_free(mbedtls_pk_restart_ctx *ctx)
{
if( ctx == NULL || ctx->pk_info == NULL ||
ctx->pk_info->rs_free_func == NULL )
{
if (ctx == NULL || ctx->pk_info == NULL ||
ctx->pk_info->rs_free_func == NULL) {
return;
}
ctx->pk_info->rs_free_func( ctx->rs_ctx );
ctx->pk_info->rs_free_func(ctx->rs_ctx);
ctx->pk_info = NULL;
ctx->rs_ctx = NULL;
@@ -106,79 +107,85 @@ void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx )
/*
* Get pk_info structure from type
*/
const mbedtls_pk_info_t * mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type )
const mbedtls_pk_info_t *mbedtls_pk_info_from_type(mbedtls_pk_type_t pk_type)
{
switch( pk_type ) {
switch (pk_type) {
#if defined(MBEDTLS_RSA_C)
case MBEDTLS_PK_RSA:
return( &mbedtls_rsa_info );
return &mbedtls_rsa_info;
#endif
#if defined(MBEDTLS_ECP_C)
case MBEDTLS_PK_ECKEY:
return( &mbedtls_eckey_info );
return &mbedtls_eckey_info;
case MBEDTLS_PK_ECKEY_DH:
return( &mbedtls_eckeydh_info );
return &mbedtls_eckeydh_info;
#endif
#if defined(MBEDTLS_ECDSA_C)
case MBEDTLS_PK_ECDSA:
return( &mbedtls_ecdsa_info );
return &mbedtls_ecdsa_info;
#endif
/* MBEDTLS_PK_RSA_ALT omitted on purpose */
default:
return( NULL );
return NULL;
}
}
/*
* Initialise context
*/
int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info )
int mbedtls_pk_setup(mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info)
{
PK_VALIDATE_RET( ctx != NULL );
if( info == NULL || ctx->pk_info != NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
PK_VALIDATE_RET(ctx != NULL);
if (info == NULL || ctx->pk_info != NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
if ((ctx->pk_ctx = info->ctx_alloc_func()) == NULL) {
return MBEDTLS_ERR_PK_ALLOC_FAILED;
}
ctx->pk_info = info;
return( 0 );
return 0;
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
/*
* Initialise a PSA-wrapping context
*/
int mbedtls_pk_setup_opaque( mbedtls_pk_context *ctx,
const psa_key_id_t key )
int mbedtls_pk_setup_opaque(mbedtls_pk_context *ctx,
const psa_key_id_t key)
{
const mbedtls_pk_info_t * const info = &mbedtls_pk_opaque_info;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t *pk_ctx;
psa_key_type_t type;
if( ctx == NULL || ctx->pk_info != NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (ctx == NULL || ctx->pk_info != NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( PSA_SUCCESS != psa_get_key_attributes( key, &attributes ) )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
type = psa_get_key_type( &attributes );
psa_reset_key_attributes( &attributes );
if (PSA_SUCCESS != psa_get_key_attributes(key, &attributes)) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
type = psa_get_key_type(&attributes);
psa_reset_key_attributes(&attributes);
/* Current implementation of can_do() relies on this. */
if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) )
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ;
if (!PSA_KEY_TYPE_IS_ECC_KEY_PAIR(type)) {
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
}
if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
if ((ctx->pk_ctx = info->ctx_alloc_func()) == NULL) {
return MBEDTLS_ERR_PK_ALLOC_FAILED;
}
ctx->pk_info = info;
pk_ctx = (psa_key_id_t *) ctx->pk_ctx;
*pk_ctx = key;
return( 0 );
return 0;
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */
@@ -186,20 +193,22 @@ int mbedtls_pk_setup_opaque( mbedtls_pk_context *ctx,
/*
* Initialize an RSA-alt context
*/
int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,
mbedtls_pk_rsa_alt_decrypt_func decrypt_func,
mbedtls_pk_rsa_alt_sign_func sign_func,
mbedtls_pk_rsa_alt_key_len_func key_len_func )
int mbedtls_pk_setup_rsa_alt(mbedtls_pk_context *ctx, void *key,
mbedtls_pk_rsa_alt_decrypt_func decrypt_func,
mbedtls_pk_rsa_alt_sign_func sign_func,
mbedtls_pk_rsa_alt_key_len_func key_len_func)
{
mbedtls_rsa_alt_context *rsa_alt;
const mbedtls_pk_info_t *info = &mbedtls_rsa_alt_info;
PK_VALIDATE_RET( ctx != NULL );
if( ctx->pk_info != NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
PK_VALIDATE_RET(ctx != NULL);
if (ctx->pk_info != NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
if ((ctx->pk_ctx = info->ctx_alloc_func()) == NULL) {
return MBEDTLS_ERR_PK_ALLOC_FAILED;
}
ctx->pk_info = info;
@@ -210,377 +219,406 @@ int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,
rsa_alt->sign_func = sign_func;
rsa_alt->key_len_func = key_len_func;
return( 0 );
return 0;
}
#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
/*
* Tell if a PK can do the operations of the given type
*/
int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type )
int mbedtls_pk_can_do(const mbedtls_pk_context *ctx, mbedtls_pk_type_t type)
{
/* A context with null pk_info is not set up yet and can't do anything.
* For backward compatibility, also accept NULL instead of a context
* pointer. */
if( ctx == NULL || ctx->pk_info == NULL )
return( 0 );
if (ctx == NULL || ctx->pk_info == NULL) {
return 0;
}
return( ctx->pk_info->can_do( type ) );
return ctx->pk_info->can_do(type);
}
/*
* Helper for mbedtls_pk_sign and mbedtls_pk_verify
*/
static inline int pk_hashlen_helper( mbedtls_md_type_t md_alg, size_t *hash_len )
static inline int pk_hashlen_helper(mbedtls_md_type_t md_alg, size_t *hash_len)
{
const mbedtls_md_info_t *md_info;
if( *hash_len != 0 && md_alg == MBEDTLS_MD_NONE )
return( 0 );
if (*hash_len != 0 && md_alg == MBEDTLS_MD_NONE) {
return 0;
}
if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )
return( -1 );
if ((md_info = mbedtls_md_info_from_type(md_alg)) == NULL) {
return -1;
}
if ( *hash_len != 0 && *hash_len != mbedtls_md_get_size( md_info ) )
return ( -1 );
if (*hash_len != 0 && *hash_len != mbedtls_md_get_size(md_info)) {
return -1;
}
*hash_len = mbedtls_md_get_size( md_info );
return( 0 );
*hash_len = mbedtls_md_get_size(md_info);
return 0;
}
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/*
* Helper to set up a restart context if needed
*/
static int pk_restart_setup( mbedtls_pk_restart_ctx *ctx,
const mbedtls_pk_info_t *info )
static int pk_restart_setup(mbedtls_pk_restart_ctx *ctx,
const mbedtls_pk_info_t *info)
{
/* Don't do anything if already set up or invalid */
if( ctx == NULL || ctx->pk_info != NULL )
return( 0 );
if (ctx == NULL || ctx->pk_info != NULL) {
return 0;
}
/* Should never happen when we're called */
if( info->rs_alloc_func == NULL || info->rs_free_func == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (info->rs_alloc_func == NULL || info->rs_free_func == NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( ( ctx->rs_ctx = info->rs_alloc_func() ) == NULL )
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
if ((ctx->rs_ctx = info->rs_alloc_func()) == NULL) {
return MBEDTLS_ERR_PK_ALLOC_FAILED;
}
ctx->pk_info = info;
return( 0 );
return 0;
}
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/*
* Verify a signature (restartable)
*/
int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
mbedtls_pk_restart_ctx *rs_ctx )
int mbedtls_pk_verify_restartable(mbedtls_pk_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
mbedtls_pk_restart_ctx *rs_ctx)
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) ||
hash != NULL );
PK_VALIDATE_RET( sig != NULL );
PK_VALIDATE_RET(ctx != NULL);
PK_VALIDATE_RET((md_alg == MBEDTLS_MD_NONE && hash_len == 0) ||
hash != NULL);
PK_VALIDATE_RET(sig != NULL);
if( ctx->pk_info == NULL ||
pk_hashlen_helper( md_alg, &hash_len ) != 0 )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (ctx->pk_info == NULL ||
pk_hashlen_helper(md_alg, &hash_len) != 0) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/* optimization: use non-restartable version if restart disabled */
if( rs_ctx != NULL &&
if (rs_ctx != NULL &&
mbedtls_ecp_restart_is_enabled() &&
ctx->pk_info->verify_rs_func != NULL )
{
ctx->pk_info->verify_rs_func != NULL) {
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 )
return( ret );
if ((ret = pk_restart_setup(rs_ctx, ctx->pk_info)) != 0) {
return ret;
}
ret = ctx->pk_info->verify_rs_func( ctx->pk_ctx,
md_alg, hash, hash_len, sig, sig_len, rs_ctx->rs_ctx );
ret = ctx->pk_info->verify_rs_func(ctx->pk_ctx,
md_alg, hash, hash_len, sig, sig_len, rs_ctx->rs_ctx);
if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
mbedtls_pk_restart_free( rs_ctx );
if (ret != MBEDTLS_ERR_ECP_IN_PROGRESS) {
mbedtls_pk_restart_free(rs_ctx);
}
return( ret );
return ret;
}
#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
(void) rs_ctx;
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
if( ctx->pk_info->verify_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (ctx->pk_info->verify_func == NULL) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
return( ctx->pk_info->verify_func( ctx->pk_ctx, md_alg, hash, hash_len,
sig, sig_len ) );
return ctx->pk_info->verify_func(ctx->pk_ctx, md_alg, hash, hash_len,
sig, sig_len);
}
/*
* Verify a signature
*/
int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len )
int mbedtls_pk_verify(mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len)
{
return( mbedtls_pk_verify_restartable( ctx, md_alg, hash, hash_len,
sig, sig_len, NULL ) );
return mbedtls_pk_verify_restartable(ctx, md_alg, hash, hash_len,
sig, sig_len, NULL);
}
/*
* Verify a signature with options
*/
int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len )
int mbedtls_pk_verify_ext(mbedtls_pk_type_t type, const void *options,
mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len)
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) ||
hash != NULL );
PK_VALIDATE_RET( sig != NULL );
PK_VALIDATE_RET(ctx != NULL);
PK_VALIDATE_RET((md_alg == MBEDTLS_MD_NONE && hash_len == 0) ||
hash != NULL);
PK_VALIDATE_RET(sig != NULL);
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (ctx->pk_info == NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( ! mbedtls_pk_can_do( ctx, type ) )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (!mbedtls_pk_can_do(ctx, type)) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
if( type == MBEDTLS_PK_RSASSA_PSS )
{
if (type == MBEDTLS_PK_RSASSA_PSS) {
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21)
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_pk_rsassa_pss_options *pss_opts;
#if SIZE_MAX > UINT_MAX
if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
#endif /* SIZE_MAX > UINT_MAX */
if( options == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (options == NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
pss_opts = (const mbedtls_pk_rsassa_pss_options *) options;
if( sig_len < mbedtls_pk_get_len( ctx ) )
return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
if (sig_len < mbedtls_pk_get_len(ctx)) {
return MBEDTLS_ERR_RSA_VERIFY_FAILED;
}
ret = mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_pk_rsa( *ctx ),
NULL, NULL, MBEDTLS_RSA_PUBLIC,
md_alg, (unsigned int) hash_len, hash,
pss_opts->mgf1_hash_id,
pss_opts->expected_salt_len,
sig );
if( ret != 0 )
return( ret );
ret = mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_pk_rsa(*ctx),
NULL, NULL, MBEDTLS_RSA_PUBLIC,
md_alg, (unsigned int) hash_len, hash,
pss_opts->mgf1_hash_id,
pss_opts->expected_salt_len,
sig);
if (ret != 0) {
return ret;
}
if( sig_len > mbedtls_pk_get_len( ctx ) )
return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );
if (sig_len > mbedtls_pk_get_len(ctx)) {
return MBEDTLS_ERR_PK_SIG_LEN_MISMATCH;
}
return( 0 );
return 0;
#else
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
#endif /* MBEDTLS_RSA_C && MBEDTLS_PKCS1_V21 */
}
/* General case: no options */
if( options != NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (options != NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
return( mbedtls_pk_verify( ctx, md_alg, hash, hash_len, sig, sig_len ) );
return mbedtls_pk_verify(ctx, md_alg, hash, hash_len, sig, sig_len);
}
/*
* Make a signature (restartable)
*/
int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_pk_restart_ctx *rs_ctx )
int mbedtls_pk_sign_restartable(mbedtls_pk_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_pk_restart_ctx *rs_ctx)
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) ||
hash != NULL );
PK_VALIDATE_RET( sig != NULL );
PK_VALIDATE_RET(ctx != NULL);
PK_VALIDATE_RET((md_alg == MBEDTLS_MD_NONE && hash_len == 0) ||
hash != NULL);
PK_VALIDATE_RET(sig != NULL);
if( ctx->pk_info == NULL ||
pk_hashlen_helper( md_alg, &hash_len ) != 0 )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (ctx->pk_info == NULL ||
pk_hashlen_helper(md_alg, &hash_len) != 0) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/* optimization: use non-restartable version if restart disabled */
if( rs_ctx != NULL &&
if (rs_ctx != NULL &&
mbedtls_ecp_restart_is_enabled() &&
ctx->pk_info->sign_rs_func != NULL )
{
ctx->pk_info->sign_rs_func != NULL) {
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 )
return( ret );
if ((ret = pk_restart_setup(rs_ctx, ctx->pk_info)) != 0) {
return ret;
}
ret = ctx->pk_info->sign_rs_func( ctx->pk_ctx, md_alg,
hash, hash_len, sig, sig_len, f_rng, p_rng, rs_ctx->rs_ctx );
ret = ctx->pk_info->sign_rs_func(ctx->pk_ctx, md_alg,
hash, hash_len, sig, sig_len, f_rng, p_rng,
rs_ctx->rs_ctx);
if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
mbedtls_pk_restart_free( rs_ctx );
if (ret != MBEDTLS_ERR_ECP_IN_PROGRESS) {
mbedtls_pk_restart_free(rs_ctx);
}
return( ret );
return ret;
}
#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
(void) rs_ctx;
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
if( ctx->pk_info->sign_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (ctx->pk_info->sign_func == NULL) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
return( ctx->pk_info->sign_func( ctx->pk_ctx, md_alg, hash, hash_len,
sig, sig_len, f_rng, p_rng ) );
return ctx->pk_info->sign_func(ctx->pk_ctx, md_alg, hash, hash_len,
sig, sig_len, f_rng, p_rng);
}
/*
* Make a signature
*/
int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
int mbedtls_pk_sign(mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
{
return( mbedtls_pk_sign_restartable( ctx, md_alg, hash, hash_len,
sig, sig_len, f_rng, p_rng, NULL ) );
return mbedtls_pk_sign_restartable(ctx, md_alg, hash, hash_len,
sig, sig_len, f_rng, p_rng, NULL);
}
/*
* Decrypt message
*/
int mbedtls_pk_decrypt( mbedtls_pk_context *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 mbedtls_pk_decrypt(mbedtls_pk_context *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)
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( input != NULL || ilen == 0 );
PK_VALIDATE_RET( output != NULL || osize == 0 );
PK_VALIDATE_RET( olen != NULL );
PK_VALIDATE_RET(ctx != NULL);
PK_VALIDATE_RET(input != NULL || ilen == 0);
PK_VALIDATE_RET(output != NULL || osize == 0);
PK_VALIDATE_RET(olen != NULL);
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (ctx->pk_info == NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( ctx->pk_info->decrypt_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (ctx->pk_info->decrypt_func == NULL) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
return( ctx->pk_info->decrypt_func( ctx->pk_ctx, input, ilen,
output, olen, osize, f_rng, p_rng ) );
return ctx->pk_info->decrypt_func(ctx->pk_ctx, input, ilen,
output, olen, osize, f_rng, p_rng);
}
/*
* Encrypt message
*/
int mbedtls_pk_encrypt( mbedtls_pk_context *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 mbedtls_pk_encrypt(mbedtls_pk_context *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)
{
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( input != NULL || ilen == 0 );
PK_VALIDATE_RET( output != NULL || osize == 0 );
PK_VALIDATE_RET( olen != NULL );
PK_VALIDATE_RET(ctx != NULL);
PK_VALIDATE_RET(input != NULL || ilen == 0);
PK_VALIDATE_RET(output != NULL || osize == 0);
PK_VALIDATE_RET(olen != NULL);
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (ctx->pk_info == NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( ctx->pk_info->encrypt_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (ctx->pk_info->encrypt_func == NULL) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
return( ctx->pk_info->encrypt_func( ctx->pk_ctx, input, ilen,
output, olen, osize, f_rng, p_rng ) );
return ctx->pk_info->encrypt_func(ctx->pk_ctx, input, ilen,
output, olen, osize, f_rng, p_rng);
}
/*
* Check public-private key pair
*/
int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv )
int mbedtls_pk_check_pair(const mbedtls_pk_context *pub, const mbedtls_pk_context *prv)
{
PK_VALIDATE_RET( pub != NULL );
PK_VALIDATE_RET( prv != NULL );
PK_VALIDATE_RET(pub != NULL);
PK_VALIDATE_RET(prv != NULL);
if( pub->pk_info == NULL ||
prv->pk_info == NULL )
{
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
if (pub->pk_info == NULL ||
prv->pk_info == NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( prv->pk_info->check_pair_func == NULL )
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
if( prv->pk_info->type == MBEDTLS_PK_RSA_ALT )
{
if( pub->pk_info->type != MBEDTLS_PK_RSA )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
}
else
{
if( pub->pk_info != prv->pk_info )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (prv->pk_info->check_pair_func == NULL) {
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
}
return( prv->pk_info->check_pair_func( pub->pk_ctx, prv->pk_ctx ) );
if (prv->pk_info->type == MBEDTLS_PK_RSA_ALT) {
if (pub->pk_info->type != MBEDTLS_PK_RSA) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
} else {
if (pub->pk_info != prv->pk_info) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
}
return prv->pk_info->check_pair_func(pub->pk_ctx, prv->pk_ctx);
}
/*
* Get key size in bits
*/
size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx )
size_t mbedtls_pk_get_bitlen(const mbedtls_pk_context *ctx)
{
/* For backward compatibility, accept NULL or a context that
* isn't set up yet, and return a fake value that should be safe. */
if( ctx == NULL || ctx->pk_info == NULL )
return( 0 );
if (ctx == NULL || ctx->pk_info == NULL) {
return 0;
}
return( ctx->pk_info->get_bitlen( ctx->pk_ctx ) );
return ctx->pk_info->get_bitlen(ctx->pk_ctx);
}
/*
* Export debug information
*/
int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items )
int mbedtls_pk_debug(const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items)
{
PK_VALIDATE_RET( ctx != NULL );
if( ctx->pk_info == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
PK_VALIDATE_RET(ctx != NULL);
if (ctx->pk_info == NULL) {
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}
if( ctx->pk_info->debug_func == NULL )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (ctx->pk_info->debug_func == NULL) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
ctx->pk_info->debug_func( ctx->pk_ctx, items );
return( 0 );
ctx->pk_info->debug_func(ctx->pk_ctx, items);
return 0;
}
/*
* Access the PK type name
*/
const char *mbedtls_pk_get_name( const mbedtls_pk_context *ctx )
const char *mbedtls_pk_get_name(const mbedtls_pk_context *ctx)
{
if( ctx == NULL || ctx->pk_info == NULL )
return( "invalid PK" );
if (ctx == NULL || ctx->pk_info == NULL) {
return "invalid PK";
}
return( ctx->pk_info->name );
return ctx->pk_info->name;
}
/*
* Access the PK type
*/
mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx )
mbedtls_pk_type_t mbedtls_pk_get_type(const mbedtls_pk_context *ctx)
{
if( ctx == NULL || ctx->pk_info == NULL )
return( MBEDTLS_PK_NONE );
if (ctx == NULL || ctx->pk_info == NULL) {
return MBEDTLS_PK_NONE;
}
return( ctx->pk_info->type );
return ctx->pk_info->type;
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
@@ -590,15 +628,15 @@ mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx )
*
* Currently only works for EC private keys.
*/
int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk,
psa_key_id_t *key,
psa_algorithm_t hash_alg )
int mbedtls_pk_wrap_as_opaque(mbedtls_pk_context *pk,
psa_key_id_t *key,
psa_algorithm_t hash_alg)
{
#if !defined(MBEDTLS_ECP_C)
((void) pk);
((void) key);
((void) hash_alg);
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
#else
const mbedtls_ecp_keypair *ec;
unsigned char d[MBEDTLS_ECP_MAX_BYTES];
@@ -610,32 +648,35 @@ int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk,
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* export the private key material in the format PSA wants */
if( mbedtls_pk_get_type( pk ) != MBEDTLS_PK_ECKEY )
return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
if (mbedtls_pk_get_type(pk) != MBEDTLS_PK_ECKEY) {
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
ec = mbedtls_pk_ec( *pk );
d_len = ( ec->grp.nbits + 7 ) / 8;
if( ( ret = mbedtls_mpi_write_binary( &ec->d, d, d_len ) ) != 0 )
return( ret );
ec = mbedtls_pk_ec(*pk);
d_len = (ec->grp.nbits + 7) / 8;
if ((ret = mbedtls_mpi_write_binary(&ec->d, d, d_len)) != 0) {
return ret;
}
curve_id = mbedtls_ecc_group_to_psa( ec->grp.id, &bits );
key_type = PSA_KEY_TYPE_ECC_KEY_PAIR( curve_id );
curve_id = mbedtls_ecc_group_to_psa(ec->grp.id, &bits);
key_type = PSA_KEY_TYPE_ECC_KEY_PAIR(curve_id);
/* prepare the key attributes */
psa_set_key_type( &attributes, key_type );
psa_set_key_bits( &attributes, bits );
psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH );
psa_set_key_algorithm( &attributes, PSA_ALG_ECDSA(hash_alg) );
psa_set_key_type(&attributes, key_type);
psa_set_key_bits(&attributes, bits);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(hash_alg));
/* import private key into PSA */
if( PSA_SUCCESS != psa_import_key( &attributes, d, d_len, key ) )
return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
if (PSA_SUCCESS != psa_import_key(&attributes, d, d_len, key)) {
return MBEDTLS_ERR_PK_HW_ACCEL_FAILED;
}
/* make PK context wrap the key slot */
mbedtls_pk_free( pk );
mbedtls_pk_init( pk );
mbedtls_pk_free(pk);
mbedtls_pk_init(pk);
return( mbedtls_pk_setup_opaque( pk, *key ) );
return mbedtls_pk_setup_opaque(pk, *key);
#endif /* MBEDTLS_ECP_C */
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */

File diff suppressed because it is too large Load Diff

View File

@@ -33,46 +33,41 @@
#include <string.h>
void mbedtls_pkcs11_init( mbedtls_pkcs11_context *ctx )
void mbedtls_pkcs11_init(mbedtls_pkcs11_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_pkcs11_context ) );
memset(ctx, 0, sizeof(mbedtls_pkcs11_context));
}
int mbedtls_pkcs11_x509_cert_bind( mbedtls_x509_crt *cert, pkcs11h_certificate_t pkcs11_cert )
int mbedtls_pkcs11_x509_cert_bind(mbedtls_x509_crt *cert, pkcs11h_certificate_t pkcs11_cert)
{
int ret = 1;
unsigned char *cert_blob = NULL;
size_t cert_blob_size = 0;
if( cert == NULL )
{
if (cert == NULL) {
ret = 2;
goto cleanup;
}
if( pkcs11h_certificate_getCertificateBlob( pkcs11_cert, NULL,
&cert_blob_size ) != CKR_OK )
{
if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert, NULL,
&cert_blob_size) != CKR_OK) {
ret = 3;
goto cleanup;
}
cert_blob = mbedtls_calloc( 1, cert_blob_size );
if( NULL == cert_blob )
{
cert_blob = mbedtls_calloc(1, cert_blob_size);
if (NULL == cert_blob) {
ret = 4;
goto cleanup;
}
if( pkcs11h_certificate_getCertificateBlob( pkcs11_cert, cert_blob,
&cert_blob_size ) != CKR_OK )
{
if (pkcs11h_certificate_getCertificateBlob(pkcs11_cert, cert_blob,
&cert_blob_size) != CKR_OK) {
ret = 5;
goto cleanup;
}
if( 0 != mbedtls_x509_crt_parse( cert, cert_blob, cert_blob_size ) )
{
if (0 != mbedtls_x509_crt_parse(cert, cert_blob, cert_blob_size)) {
ret = 6;
goto cleanup;
}
@@ -80,121 +75,128 @@ int mbedtls_pkcs11_x509_cert_bind( mbedtls_x509_crt *cert, pkcs11h_certificate_t
ret = 0;
cleanup:
if( NULL != cert_blob )
mbedtls_free( cert_blob );
if (NULL != cert_blob) {
mbedtls_free(cert_blob);
}
return( ret );
return ret;
}
int mbedtls_pkcs11_priv_key_bind( mbedtls_pkcs11_context *priv_key,
pkcs11h_certificate_t pkcs11_cert )
int mbedtls_pkcs11_priv_key_bind(mbedtls_pkcs11_context *priv_key,
pkcs11h_certificate_t pkcs11_cert)
{
int ret = 1;
mbedtls_x509_crt cert;
mbedtls_x509_crt_init( &cert );
mbedtls_x509_crt_init(&cert);
if( priv_key == NULL )
if (priv_key == NULL) {
goto cleanup;
}
if( 0 != mbedtls_pkcs11_x509_cert_bind( &cert, pkcs11_cert ) )
if (0 != mbedtls_pkcs11_x509_cert_bind(&cert, pkcs11_cert)) {
goto cleanup;
}
priv_key->len = mbedtls_pk_get_len( &cert.pk );
priv_key->len = mbedtls_pk_get_len(&cert.pk);
priv_key->pkcs11h_cert = pkcs11_cert;
ret = 0;
cleanup:
mbedtls_x509_crt_free( &cert );
mbedtls_x509_crt_free(&cert);
return( ret );
return ret;
}
void mbedtls_pkcs11_priv_key_free( mbedtls_pkcs11_context *priv_key )
void mbedtls_pkcs11_priv_key_free(mbedtls_pkcs11_context *priv_key)
{
if( NULL != priv_key )
pkcs11h_certificate_freeCertificate( priv_key->pkcs11h_cert );
if (NULL != priv_key) {
pkcs11h_certificate_freeCertificate(priv_key->pkcs11h_cert);
}
}
int mbedtls_pkcs11_decrypt( mbedtls_pkcs11_context *ctx,
int mode, size_t *olen,
const unsigned char *input,
unsigned char *output,
size_t output_max_len )
int mbedtls_pkcs11_decrypt(mbedtls_pkcs11_context *ctx,
int mode, size_t *olen,
const unsigned char *input,
unsigned char *output,
size_t output_max_len)
{
size_t input_len, output_len;
if( NULL == ctx )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (NULL == ctx) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
if( MBEDTLS_RSA_PRIVATE != mode )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (MBEDTLS_RSA_PRIVATE != mode) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
output_len = input_len = ctx->len;
if( input_len < 16 || input_len > output_max_len )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (input_len < 16 || input_len > output_max_len) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
/* Determine size of output buffer */
if( pkcs11h_certificate_decryptAny( ctx->pkcs11h_cert, CKM_RSA_PKCS, input,
input_len, NULL, &output_len ) != CKR_OK )
{
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (pkcs11h_certificate_decryptAny(ctx->pkcs11h_cert, CKM_RSA_PKCS, input,
input_len, NULL, &output_len) != CKR_OK) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
if( output_len > output_max_len )
return( MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE );
if (output_len > output_max_len) {
return MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
}
if( pkcs11h_certificate_decryptAny( ctx->pkcs11h_cert, CKM_RSA_PKCS, input,
input_len, output, &output_len ) != CKR_OK )
{
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (pkcs11h_certificate_decryptAny(ctx->pkcs11h_cert, CKM_RSA_PKCS, input,
input_len, output, &output_len) != CKR_OK) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
*olen = output_len;
return( 0 );
return 0;
}
int mbedtls_pkcs11_sign( mbedtls_pkcs11_context *ctx,
int mode,
mbedtls_md_type_t md_alg,
unsigned int hashlen,
const unsigned char *hash,
unsigned char *sig )
int mbedtls_pkcs11_sign(mbedtls_pkcs11_context *ctx,
int mode,
mbedtls_md_type_t md_alg,
unsigned int hashlen,
const unsigned char *hash,
unsigned char *sig)
{
size_t sig_len = 0, asn_len = 0, oid_size = 0;
unsigned char *p = sig;
const char *oid;
if( NULL == ctx )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (NULL == ctx) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
if( MBEDTLS_RSA_PRIVATE != mode )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (MBEDTLS_RSA_PRIVATE != mode) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
if( md_alg != MBEDTLS_MD_NONE )
{
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
if( md_info == NULL )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (md_alg != MBEDTLS_MD_NONE) {
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
if (md_info == NULL) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
hashlen = mbedtls_md_get_size( md_info );
hashlen = mbedtls_md_get_size(md_info);
asn_len = 10 + oid_size;
}
sig_len = ctx->len;
if( hashlen > sig_len || asn_len > sig_len ||
hashlen + asn_len > sig_len )
{
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (hashlen > sig_len || asn_len > sig_len ||
hashlen + asn_len > sig_len) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
if( md_alg != MBEDTLS_MD_NONE )
{
if (md_alg != MBEDTLS_MD_NONE) {
/*
* DigestInfo ::= SEQUENCE {
* digestAlgorithm DigestAlgorithmIdentifier,
@@ -205,12 +207,12 @@ int mbedtls_pkcs11_sign( mbedtls_pkcs11_context *ctx,
* Digest ::= OCTET STRING
*/
*p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
*p++ = (unsigned char) ( 0x08 + oid_size + hashlen );
*p++ = (unsigned char) (0x08 + oid_size + hashlen);
*p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
*p++ = (unsigned char) ( 0x04 + oid_size );
*p++ = (unsigned char) (0x04 + oid_size);
*p++ = MBEDTLS_ASN1_OID;
*p++ = oid_size & 0xFF;
memcpy( p, oid, oid_size );
memcpy(p, oid, oid_size);
p += oid_size;
*p++ = MBEDTLS_ASN1_NULL;
*p++ = 0x00;
@@ -218,15 +220,14 @@ int mbedtls_pkcs11_sign( mbedtls_pkcs11_context *ctx,
*p++ = hashlen;
}
memcpy( p, hash, hashlen );
memcpy(p, hash, hashlen);
if( pkcs11h_certificate_signAny( ctx->pkcs11h_cert, CKM_RSA_PKCS, sig,
asn_len + hashlen, sig, &sig_len ) != CKR_OK )
{
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
if (pkcs11h_certificate_signAny(ctx->pkcs11h_cert, CKM_RSA_PKCS, sig,
asn_len + hashlen, sig, &sig_len) != CKR_OK) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
return( 0 );
return 0;
}
#endif /* defined(MBEDTLS_PKCS11_C) */

View File

@@ -45,8 +45,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;
@@ -59,76 +59,82 @@ 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_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t len,
unsigned char *output )
int mbedtls_pkcs12_pbe_sha1_rc4_128(mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t len,
unsigned char *output)
{
#if !defined(MBEDTLS_ARC4_C)
((void) pbe_params);
@@ -138,39 +144,39 @@ int mbedtls_pkcs12_pbe_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode,
((void) data);
((void) len);
((void) output);
return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
return MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE;
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char key[16];
mbedtls_arc4_context ctx;
((void) mode);
mbedtls_arc4_init( &ctx );
mbedtls_arc4_init(&ctx);
if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, MBEDTLS_MD_SHA1,
pwd, pwdlen,
key, 16, NULL, 0 ) ) != 0 )
{
return( ret );
if ((ret = pkcs12_pbe_derive_key_iv(pbe_params, MBEDTLS_MD_SHA1,
pwd, pwdlen,
key, 16, NULL, 0)) != 0) {
return ret;
}
mbedtls_arc4_setup( &ctx, key, 16 );
if( ( ret = mbedtls_arc4_crypt( &ctx, len, data, output ) ) != 0 )
mbedtls_arc4_setup(&ctx, key, 16);
if ((ret = mbedtls_arc4_crypt(&ctx, len, data, output)) != 0) {
goto exit;
}
exit:
mbedtls_platform_zeroize( key, sizeof( key ) );
mbedtls_arc4_free( &ctx );
mbedtls_platform_zeroize(key, sizeof(key));
mbedtls_arc4_free(&ctx);
return( ret );
return ret;
#endif /* MBEDTLS_ARC4_C */
}
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];
@@ -179,73 +185,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
@@ -254,10 +263,10 @@ static void pkcs12_fill_buffer( unsigned char *data, size_t data_len,
}
}
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;
@@ -276,114 +285,119 @@ int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen,
mbedtls_md_context_t md_ctx;
// 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 );
md_info = mbedtls_md_info_from_type( md_type );
if( md_info == NULL )
return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
mbedtls_md_init( &md_ctx );
if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
return( ret );
hlen = mbedtls_md_get_size( md_info );
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);
md_info = mbedtls_md_info_from_type(md_type);
if (md_info == NULL) {
return MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE;
}
mbedtls_md_init(&md_ctx);
if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
return ret;
}
hlen = mbedtls_md_get_size(md_info);
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 )
{
while (datalen > 0) {
// 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_finish( &md_ctx, hash_output ) ) != 0 )
if ((ret = mbedtls_md_update(&md_ctx, diversifier, v)) != 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 )
goto exit;
}
use_len = ( datalen > hlen ) ? hlen : datalen;
memcpy( p, hash_output, use_len );
datalen -= use_len;
p += use_len;
if( datalen == 0 )
break;
// Concatenating copies of hash_output into hash_block (B)
pkcs12_fill_buffer( hash_block, v, hash_output, hlen );
// B += 1
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_salt != 0) {
if ((ret = mbedtls_md_update(&md_ctx, salt_block, v)) != 0) {
goto exit;
}
}
if( use_password != 0 )
{
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) {
goto exit;
}
}
use_len = (datalen > hlen) ? hlen : datalen;
memcpy(p, hash_output, use_len);
datalen -= use_len;
p += use_len;
if (datalen == 0) {
break;
}
// Concatenating copies of hash_output into hash_block (B)
pkcs12_fill_buffer(hash_block, v, hash_output, hlen);
// B += 1
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) {
// 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);
}
}
}
@@ -391,14 +405,14 @@ 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));
mbedtls_md_free( &md_ctx );
mbedtls_md_free(&md_ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_PKCS12_C */

View File

@@ -45,18 +45,19 @@
#include "mbedtls/platform.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,
@@ -66,45 +67,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;
@@ -128,42 +136,46 @@ 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;
}
md_info = mbedtls_md_info_from_type( md_type );
if( md_info == NULL )
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 );
md_info = mbedtls_md_info_from_type(md_type);
if (md_info == NULL) {
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 );
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 (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
@@ -171,143 +183,156 @@ 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_md_init( &md_ctx );
mbedtls_cipher_init( &cipher_ctx );
mbedtls_md_init(&md_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_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
goto exit;
if( ( ret = mbedtls_pkcs5_pbkdf2_hmac( &md_ctx, pwd, pwdlen, salt.p, salt.len,
iterations, keylen, key ) ) != 0 )
{
if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
goto exit;
}
if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 )
if ((ret = mbedtls_pkcs5_pbkdf2_hmac(&md_ctx, pwd, pwdlen, salt.p, salt.len,
iterations, keylen, key)) != 0) {
goto exit;
}
if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen,
(mbedtls_operation_t) mode ) ) != 0 )
if ((ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0) {
goto exit;
}
if( ( ret = mbedtls_cipher_crypt( &cipher_ctx, iv, enc_scheme_params.len,
data, datalen, output, &olen ) ) != 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) {
ret = MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH;
}
exit:
mbedtls_md_free( &md_ctx );
mbedtls_cipher_free( &cipher_ctx );
mbedtls_md_free(&md_ctx);
mbedtls_cipher_free(&cipher_ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_ASN1_PARSE_C */
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)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int j;
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
//
for( j = 0; j < md_size; j++ )
for (j = 0; j < md_size; j++) {
work[j] ^= md1[j];
}
}
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_SELF_TEST)
#if !defined(MBEDTLS_SHA1_C)
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] =
{
@@ -319,7 +344,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] =
{
@@ -331,10 +356,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] =
{
@@ -355,58 +380,58 @@ 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)
{
mbedtls_md_context_t sha1_ctx;
const mbedtls_md_info_t *info_sha1;
int ret, i;
unsigned char key[64];
mbedtls_md_init( &sha1_ctx );
mbedtls_md_init(&sha1_ctx);
info_sha1 = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );
if( info_sha1 == NULL )
{
info_sha1 = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
if (info_sha1 == NULL) {
ret = 1;
goto exit;
}
if( ( ret = mbedtls_md_setup( &sha1_ctx, info_sha1, 1 ) ) != 0 )
{
if ((ret = mbedtls_md_setup(&sha1_ctx, info_sha1, 1)) != 0) {
ret = 1;
goto exit;
}
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( &sha1_ctx, 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(&sha1_ctx, 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:
mbedtls_md_free( &sha1_ctx );
mbedtls_md_free(&sha1_ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_SHA1_C */

File diff suppressed because it is too large Load Diff

View File

@@ -51,10 +51,10 @@
#include "mbedtls/platform.h"
/* Parameter validation macros based on platform_util.h */
#define PK_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA )
#define PK_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define PK_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA)
#define PK_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
#if defined(MBEDTLS_RSA_C)
/*
@@ -63,38 +63,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 */
@@ -102,27 +105,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;
}
/*
@@ -130,93 +133,91 @@ 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;
PK_VALIDATE_RET( p != NULL );
PK_VALIDATE_RET( *p != NULL );
PK_VALIDATE_RET( start != NULL );
PK_VALIDATE_RET( key != NULL );
PK_VALIDATE_RET(p != NULL);
PK_VALIDATE_RET(*p != NULL);
PK_VALIDATE_RET(start != NULL);
PK_VALIDATE_RET(key != NULL);
#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;
psa_key_id_t* key_id = (psa_key_id_t*) key->pk_ctx;
psa_key_id_t *key_id = (psa_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( mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_pubkey_der(mbedtls_pk_context *key, unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *c;
@@ -224,17 +225,19 @@ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, si
mbedtls_pk_type_t pk_type;
const char *oid;
PK_VALIDATE_RET( key != NULL );
if( size == 0 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
PK_VALIDATE_RET( buf != NULL );
PK_VALIDATE_RET(key != NULL);
if (size == 0) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
PK_VALIDATE_RET(buf != NULL);
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 {
@@ -244,162 +247,169 @@ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, si
*--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;
psa_key_id_t key_id;
psa_ecc_family_t curve;
size_t bits;
key_id = *((psa_key_id_t*) key->pk_ctx );
if( PSA_SUCCESS != psa_get_key_attributes( key_id, &attributes ) )
return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
key_type = psa_get_key_type( &attributes );
bits = psa_get_key_bits( &attributes );
psa_reset_key_attributes( &attributes );
key_id = *((psa_key_id_t *) key->pk_ctx);
if (PSA_SUCCESS != psa_get_key_attributes(key_id, &attributes)) {
return MBEDTLS_ERR_PK_HW_ACCEL_FAILED;
}
key_type = psa_get_key_type(&attributes);
bits = psa_get_key_bits(&attributes);
psa_reset_key_attributes(&attributes);
curve = PSA_KEY_TYPE_ECC_GET_FAMILY( key_type );
if( curve == 0 )
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
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;
}
#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( mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_key_der(mbedtls_pk_context *key, unsigned char *buf, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *c;
size_t len = 0;
PK_VALIDATE_RET( key != NULL );
if( size == 0 )
return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
PK_VALIDATE_RET( buf != NULL );
PK_VALIDATE_RET(key != NULL);
if (size == 0) {
return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
}
PK_VALIDATE_RET(buf != NULL);
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;
/*
@@ -414,44 +424,46 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
*/
/* 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)
@@ -481,7 +493,7 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
* publicExponent INTEGER -- e 1 + 3 + MPI_MAX + 1
* }
*/
#define RSA_PUB_DER_MAX_BYTES ( 38 + 2 * MBEDTLS_MPI_MAX_SIZE )
#define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE)
/*
* RSA private keys:
@@ -498,10 +510,10 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
* otherPrimeInfos OtherPrimeInfos OPTIONAL 0 (not supported)
* }
*/
#define MPI_MAX_SIZE_2 ( MBEDTLS_MPI_MAX_SIZE / 2 + \
MBEDTLS_MPI_MAX_SIZE % 2 )
#define RSA_PRV_DER_MAX_BYTES ( 47 + 3 * MBEDTLS_MPI_MAX_SIZE \
+ 5 * MPI_MAX_SIZE_2 )
#define MPI_MAX_SIZE_2 (MBEDTLS_MPI_MAX_SIZE / 2 + \
MBEDTLS_MPI_MAX_SIZE % 2)
#define RSA_PRV_DER_MAX_BYTES (47 + 3 * MBEDTLS_MPI_MAX_SIZE \
+ 5 * MPI_MAX_SIZE_2)
#else /* MBEDTLS_RSA_C */
@@ -522,7 +534,7 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
* + 2 * ECP_MAX (coords) [1]
* }
*/
#define ECP_PUB_DER_MAX_BYTES ( 30 + 2 * MBEDTLS_ECP_MAX_BYTES )
#define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES)
/*
* EC private keys:
@@ -533,7 +545,7 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
* publicKey [1] BIT STRING OPTIONAL 1 + 2 + [1] above
* }
*/
#define ECP_PRV_DER_MAX_BYTES ( 29 + 3 * MBEDTLS_ECP_MAX_BYTES )
#define ECP_PRV_DER_MAX_BYTES (29 + 3 * MBEDTLS_ECP_MAX_BYTES)
#else /* MBEDTLS_ECP_C */
@@ -542,75 +554,69 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
#endif /* MBEDTLS_ECP_C */
#define PUB_DER_MAX_BYTES ( RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES )
#define PRV_DER_MAX_BYTES ( RSA_PRV_DER_MAX_BYTES > ECP_PRV_DER_MAX_BYTES ? \
RSA_PRV_DER_MAX_BYTES : ECP_PRV_DER_MAX_BYTES )
#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
#define PRV_DER_MAX_BYTES (RSA_PRV_DER_MAX_BYTES > ECP_PRV_DER_MAX_BYTES ? \
RSA_PRV_DER_MAX_BYTES : ECP_PRV_DER_MAX_BYTES)
int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_pubkey_pem(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;
PK_VALIDATE_RET( key != NULL );
PK_VALIDATE_RET( buf != NULL || size == 0 );
PK_VALIDATE_RET(key != NULL);
PK_VALIDATE_RET(buf != NULL || size == 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( mbedtls_pk_context *key, unsigned char *buf, size_t size )
int mbedtls_pk_write_key_pem(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;
PK_VALIDATE_RET( key != NULL );
PK_VALIDATE_RET( buf != NULL || size == 0 );
PK_VALIDATE_RET(key != NULL);
PK_VALIDATE_RET(buf != NULL || size == 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

@@ -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,7 +231,7 @@ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *, const char *, ...
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static void platform_exit_uninit( int status )
static void platform_exit_uninit(int status)
{
((void) status);
}
@@ -239,12 +239,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 */
@@ -255,21 +255,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 */
@@ -280,41 +280,41 @@ 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 );
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 );
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;
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 );
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 */
@@ -323,11 +323,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
@@ -337,28 +337,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 */
@@ -367,19 +367,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 */
@@ -82,9 +83,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
@@ -92,42 +93,43 @@ 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) )
#if !(defined(_WIN32) && !defined(EFIX64) && !defined(EFI32))
#define PLATFORM_UTIL_USE_GMTIME
#endif /* ! ( defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) ) */
#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(EFIX64) && !defined(EFI32)
return( ( gmtime_s( tm_buf, tt ) == 0 ) ? tm_buf : NULL );
return (gmtime_s(tm_buf, tt) == 0) ? tm_buf : NULL;
#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 */

View File

@@ -33,19 +33,19 @@
#if !defined(MBEDTLS_POLY1305_ALT)
/* Parameter validation macros */
#define POLY1305_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA )
#define POLY1305_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define POLY1305_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA)
#define POLY1305_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
#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;
@@ -55,15 +55,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
@@ -79,10 +79,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;
@@ -96,9 +96,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];
@@ -107,67 +107,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;
@@ -187,8 +186,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;
@@ -208,73 +207,74 @@ 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)
{
POLY1305_VALIDATE( ctx != NULL );
POLY1305_VALIDATE(ctx != NULL);
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])
{
POLY1305_VALIDATE_RET( ctx != NULL );
POLY1305_VALIDATE_RET( key != NULL );
POLY1305_VALIDATE_RET(ctx != NULL);
POLY1305_VALIDATE_RET(key != NULL);
/* 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;
@@ -284,129 +284,124 @@ 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;
POLY1305_VALIDATE_RET( ctx != NULL );
POLY1305_VALIDATE_RET( ilen == 0 || input != NULL );
POLY1305_VALIDATE_RET(ctx != NULL);
POLY1305_VALIDATE_RET(ilen == 0 || input != NULL);
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])
{
POLY1305_VALIDATE_RET( ctx != NULL );
POLY1305_VALIDATE_RET( mac != NULL );
POLY1305_VALIDATE_RET(ctx != NULL);
POLY1305_VALIDATE_RET(mac != NULL);
/* 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;
POLY1305_VALIDATE_RET( key != NULL );
POLY1305_VALIDATE_RET( mac != NULL );
POLY1305_VALIDATE_RET( ilen == 0 || input != NULL );
POLY1305_VALIDATE_RET(key != NULL);
POLY1305_VALIDATE_RET(mac != NULL);
POLY1305_VALIDATE_RET(ilen == 0 || input != NULL);
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 */
@@ -479,46 +474,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

@@ -31,12 +31,10 @@
#include "mbedtls/cipher.h"
#include "mbedtls/gcm.h"
typedef struct
{
typedef struct {
psa_algorithm_t core_alg;
uint8_t tag_length;
union
{
union {
unsigned dummy; /* Make the union non-empty even with no supported algorithms. */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
mbedtls_ccm_context ccm;
@@ -50,25 +48,24 @@ typedef struct
} ctx;
} aead_operation_t;
#define AEAD_OPERATION_INIT {0, 0, {0}}
#define AEAD_OPERATION_INIT { 0, 0, { 0 } }
static void psa_aead_abort_internal( aead_operation_t *operation )
static void psa_aead_abort_internal(aead_operation_t *operation)
{
switch( operation->core_alg )
{
switch (operation->core_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 */
}
@@ -78,7 +75,7 @@ static psa_status_t psa_aead_setup(
aead_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
psa_algorithm_t alg )
psa_algorithm_t alg)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t key_bits;
@@ -88,85 +85,92 @@ static psa_status_t psa_aead_setup(
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->core_alg = PSA_ALG_CCM;
full_tag_length = 16;
/* 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->core_alg = PSA_ALG_GCM;
full_tag_length = 16;
/* 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->core_alg = PSA_ALG_CHACHA20_POLY1305;
full_tag_length = 16;
/* 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;
}
if( PSA_AEAD_TAG_LENGTH( attributes->core.type,
key_bits, alg )
> full_tag_length )
return( PSA_ERROR_INVALID_ARGUMENT );
if (PSA_AEAD_TAG_LENGTH(attributes->core.type,
key_bits, alg)
> full_tag_length) {
return PSA_ERROR_INVALID_ARGUMENT;
}
operation->tag_length = PSA_AEAD_TAG_LENGTH( attributes->core.type,
key_bits,
alg );
operation->tag_length = PSA_AEAD_TAG_LENGTH(attributes->core.type,
key_bits,
alg);
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t mbedtls_psa_aead_encrypt(
@@ -176,82 +180,75 @@ 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;
aead_operation_t operation = AEAD_OPERATION_INIT;
uint8_t *tag;
(void) key_buffer_size;
status = psa_aead_setup( &operation, attributes, key_buffer, alg );
if( status != PSA_SUCCESS )
status = psa_aead_setup(&operation, attributes, key_buffer, alg);
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.core_alg == PSA_ALG_CCM )
{
if (operation.core_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.core_alg == PSA_ALG_GCM )
{
if (operation.core_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.core_alg == PSA_ALG_CHACHA20_POLY1305 )
{
if( nonce_length != 12 )
{
if( nonce_length == 8 )
if (operation.core_alg == PSA_ALG_CHACHA20_POLY1305) {
if (nonce_length != 12) {
if (nonce_length == 8) {
status = PSA_ERROR_NOT_SUPPORTED;
else
} else {
status = PSA_ERROR_INVALID_ARGUMENT;
}
goto exit;
}
if( operation.tag_length != 16 )
{
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;
@@ -260,16 +257,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:
psa_aead_abort_internal( &operation );
psa_aead_abort_internal(&operation);
return( status );
return status;
}
/* Locate the tag in a ciphertext buffer containing the encrypted data
@@ -277,20 +275,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(
@@ -300,79 +300,74 @@ 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;
aead_operation_t operation = AEAD_OPERATION_INIT;
const uint8_t *tag = NULL;
(void) key_buffer_size;
status = psa_aead_setup( &operation, attributes, key_buffer, alg );
if( status != PSA_SUCCESS )
status = psa_aead_setup(&operation, attributes, key_buffer, alg);
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.core_alg == PSA_ALG_CCM )
{
if (operation.core_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.core_alg == PSA_ALG_GCM )
{
if (operation.core_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.core_alg == PSA_ALG_CHACHA20_POLY1305 )
{
if( nonce_length != 12 )
{
if( nonce_length == 8 )
if (operation.core_alg == PSA_ALG_CHACHA20_POLY1305) {
if (nonce_length != 12) {
if (nonce_length == 8) {
status = PSA_ERROR_NOT_SUPPORTED;
else
} else {
status = PSA_ERROR_INVALID_ARGUMENT;
}
goto exit;
}
if( operation.tag_length != 16 )
{
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;
@@ -380,19 +375,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:
psa_aead_abort_internal( &operation );
psa_aead_abort_internal(&operation);
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
*plaintext_length = ciphertext_length - operation.tag_length;
return( status );
}
return status;
}
#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,6 +146,6 @@ 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);
#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;
@@ -83,31 +82,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;
@@ -122,15 +120,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,174 +364,175 @@ 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( 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)
{
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(
@@ -541,52 +544,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

@@ -39,22 +39,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;
/*
@@ -84,8 +84,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;
@@ -94,7 +93,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.
*
@@ -105,9 +104,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.
@@ -118,9 +117,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.
@@ -131,10 +130,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.
@@ -143,12 +142,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.
@@ -156,8 +155,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;
}
@@ -167,8 +166,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;
}
@@ -181,9 +180,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
@@ -198,7 +197,7 @@ static inline psa_key_slot_number_t psa_key_slot_get_slot_number(
* 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.
*
@@ -212,11 +211,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.
*
@@ -235,9 +234,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
*
@@ -248,7 +247,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.
*
@@ -280,7 +279,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
*
@@ -307,7 +306,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.
*
@@ -335,7 +334,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.
@@ -357,10 +356,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.
@@ -403,7 +402,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.
@@ -440,7 +439,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.
*
@@ -479,7 +478,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.
@@ -514,6 +513,6 @@ 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);
#endif /* PSA_CRYPTO_CORE_H */

File diff suppressed because it is too large Load Diff

View File

@@ -28,8 +28,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
@@ -43,7 +43,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,
@@ -53,19 +53,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
@@ -75,30 +75,30 @@ 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_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);
/*
* Cipher functions
@@ -114,7 +114,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,
@@ -125,24 +125,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,
@@ -150,16 +150,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
@@ -174,25 +174,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
@@ -205,7 +205,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,
@@ -214,7 +214,7 @@ 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);
/*
* MAC functions
@@ -228,40 +228,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);
#endif /* PSA_CRYPTO_DRIVER_WRAPPERS_H */

View File

@@ -44,25 +44,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
@@ -72,31 +72,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
@@ -108,48 +106,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) ||
@@ -164,116 +162,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) */
@@ -281,45 +282,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) */
@@ -333,7 +336,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;
@@ -341,73 +344,71 @@ 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 );
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
mbedtls_md_type_t md_alg = mbedtls_md_get_type( md_info );
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);
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa(hash_alg);
mbedtls_md_type_t md_alg = mbedtls_md_get_type(md_info);
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) || \

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,6 +217,6 @@ 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);
#endif /* PSA_CRYPTO_ECP_H */

View File

@@ -33,48 +33,47 @@
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
const mbedtls_md_info_t *mbedtls_md_info_from_psa( psa_algorithm_t alg )
const mbedtls_md_info_t *mbedtls_md_info_from_psa(psa_algorithm_t alg)
{
switch( alg )
{
switch (alg) {
#if defined(MBEDTLS_MD2_C)
case PSA_ALG_MD2:
return( &mbedtls_md2_info );
return &mbedtls_md2_info;
#endif
#if defined(MBEDTLS_MD4_C)
case PSA_ALG_MD4:
return( &mbedtls_md4_info );
return &mbedtls_md4_info;
#endif
#if defined(MBEDTLS_MD5_C)
case PSA_ALG_MD5:
return( &mbedtls_md5_info );
return &mbedtls_md5_info;
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case PSA_ALG_RIPEMD160:
return( &mbedtls_ripemd160_info );
return &mbedtls_ripemd160_info;
#endif
#if defined(MBEDTLS_SHA1_C)
case PSA_ALG_SHA_1:
return( &mbedtls_sha1_info );
return &mbedtls_sha1_info;
#endif
#if defined(MBEDTLS_SHA256_C)
case PSA_ALG_SHA_224:
return( &mbedtls_sha224_info );
return &mbedtls_sha224_info;
#endif
#if defined(MBEDTLS_SHA256_C)
case PSA_ALG_SHA_256:
return( &mbedtls_sha256_info );
return &mbedtls_sha256_info;
#endif
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
case PSA_ALG_SHA_384:
return( &mbedtls_sha384_info );
return &mbedtls_sha384_info;
#endif
#if defined(MBEDTLS_SHA512_C)
case PSA_ALG_SHA_512:
return( &mbedtls_sha512_info );
return &mbedtls_sha512_info;
#endif
default:
return( NULL );
return NULL;
}
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
@@ -84,10 +83,9 @@ const mbedtls_md_info_t *mbedtls_md_info_from_psa( psa_algorithm_t alg )
#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
@@ -95,289 +93,286 @@ psa_status_t mbedtls_psa_hash_abort(
break;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
case PSA_ALG_MD2:
mbedtls_md2_free( &operation->ctx.md2 );
mbedtls_md2_free(&operation->ctx.md2);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
case PSA_ALG_MD4:
mbedtls_md4_free( &operation->ctx.md4 );
mbedtls_md4_free(&operation->ctx.md4);
break;
#endif
#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_MD2)
case PSA_ALG_MD2:
mbedtls_md2_init( &operation->ctx.md2 );
ret = mbedtls_md2_starts_ret( &operation->ctx.md2 );
mbedtls_md2_init(&operation->ctx.md2);
ret = mbedtls_md2_starts_ret(&operation->ctx.md2);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
case PSA_ALG_MD4:
mbedtls_md4_init( &operation->ctx.md4 );
ret = mbedtls_md4_starts_ret( &operation->ctx.md4 );
mbedtls_md4_init(&operation->ctx.md4);
ret = mbedtls_md4_starts_ret(&operation->ctx.md4);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
mbedtls_md5_init( &operation->ctx.md5 );
ret = mbedtls_md5_starts_ret( &operation->ctx.md5 );
mbedtls_md5_init(&operation->ctx.md5);
ret = mbedtls_md5_starts_ret(&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_ret( &operation->ctx.ripemd160 );
mbedtls_ripemd160_init(&operation->ctx.ripemd160);
ret = mbedtls_ripemd160_starts_ret(&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_ret( &operation->ctx.sha1 );
mbedtls_sha1_init(&operation->ctx.sha1);
ret = mbedtls_sha1_starts_ret(&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_ret( &operation->ctx.sha256, 1 );
mbedtls_sha256_init(&operation->ctx.sha256);
ret = mbedtls_sha256_starts_ret(&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_ret( &operation->ctx.sha256, 0 );
mbedtls_sha256_init(&operation->ctx.sha256);
ret = mbedtls_sha256_starts_ret(&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_ret( &operation->ctx.sha512, 1 );
mbedtls_sha512_init(&operation->ctx.sha512);
ret = mbedtls_sha512_starts_ret(&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_ret( &operation->ctx.sha512, 0 );
mbedtls_sha512_init(&operation->ctx.sha512);
ret = mbedtls_sha512_starts_ret(&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_MD2)
case PSA_ALG_MD2:
mbedtls_md2_clone( &target_operation->ctx.md2,
&source_operation->ctx.md2 );
mbedtls_md2_clone(&target_operation->ctx.md2,
&source_operation->ctx.md2);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
case PSA_ALG_MD4:
mbedtls_md4_clone( &target_operation->ctx.md4,
&source_operation->ctx.md4 );
mbedtls_md4_clone(&target_operation->ctx.md4,
&source_operation->ctx.md4);
break;
#endif
#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_MD2)
case PSA_ALG_MD2:
ret = mbedtls_md2_update_ret( &operation->ctx.md2,
input, input_length );
ret = mbedtls_md2_update_ret(&operation->ctx.md2,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
case PSA_ALG_MD4:
ret = mbedtls_md4_update_ret( &operation->ctx.md4,
input, input_length );
ret = mbedtls_md4_update_ret(&operation->ctx.md4,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
ret = mbedtls_md5_update_ret( &operation->ctx.md5,
input, input_length );
ret = mbedtls_md5_update_ret(&operation->ctx.md5,
input, input_length);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
case PSA_ALG_RIPEMD160:
ret = mbedtls_ripemd160_update_ret( &operation->ctx.ripemd160,
input, input_length );
ret = mbedtls_ripemd160_update_ret(&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_ret( &operation->ctx.sha1,
input, input_length );
ret = mbedtls_sha1_update_ret(&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_ret( &operation->ctx.sha256,
input, input_length );
ret = mbedtls_sha256_update_ret(&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_ret( &operation->ctx.sha256,
input, input_length );
ret = mbedtls_sha256_update_ret(&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_ret( &operation->ctx.sha512,
input, input_length );
ret = mbedtls_sha512_update_ret(&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_ret( &operation->ctx.sha512,
input, input_length );
ret = mbedtls_sha512_update_ret(&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),
@@ -385,72 +380,72 @@ 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_MD2)
case PSA_ALG_MD2:
ret = mbedtls_md2_finish_ret( &operation->ctx.md2, hash );
ret = mbedtls_md2_finish_ret(&operation->ctx.md2, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
case PSA_ALG_MD4:
ret = mbedtls_md4_finish_ret( &operation->ctx.md4, hash );
ret = mbedtls_md4_finish_ret(&operation->ctx.md4, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
case PSA_ALG_MD5:
ret = mbedtls_md5_finish_ret( &operation->ctx.md5, hash );
ret = mbedtls_md5_finish_ret(&operation->ctx.md5, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
case PSA_ALG_RIPEMD160:
ret = mbedtls_ripemd160_finish_ret( &operation->ctx.ripemd160, hash );
ret = mbedtls_ripemd160_finish_ret(&operation->ctx.ripemd160, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
case PSA_ALG_SHA_1:
ret = mbedtls_sha1_finish_ret( &operation->ctx.sha1, hash );
ret = mbedtls_sha1_finish_ret(&operation->ctx.sha1, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
case PSA_ALG_SHA_224:
ret = mbedtls_sha256_finish_ret( &operation->ctx.sha256, hash );
ret = mbedtls_sha256_finish_ret(&operation->ctx.sha256, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
case PSA_ALG_SHA_256:
ret = mbedtls_sha256_finish_ret( &operation->ctx.sha256, hash );
ret = mbedtls_sha256_finish_ret(&operation->ctx.sha256, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
case PSA_ALG_SHA_384:
ret = mbedtls_sha512_finish_ret( &operation->ctx.sha512, hash );
ret = mbedtls_sha512_finish_ret(&operation->ctx.sha512, hash);
break;
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
case PSA_ALG_SHA_512:
ret = mbedtls_sha512_finish_ret( &operation->ctx.sha512, hash );
ret = mbedtls_sha512_finish_ret(&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(
@@ -466,22 +461,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

@@ -32,7 +32,7 @@
* \return The Mbed TLS MD information of the hash algorithm. \c NULL if the
* PSA hash algorithm is not supported.
*/
const mbedtls_md_info_t *mbedtls_md_info_from_psa( psa_algorithm_t alg );
const mbedtls_md_info_t *mbedtls_md_info_from_psa(psa_algorithm_t alg);
/** Calculate the hash (digest) of a message using Mbed TLS routines.
*
@@ -102,7 +102,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.
*
@@ -134,7 +134,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.
*
@@ -162,7 +162,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.
*
@@ -202,7 +202,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.
*
@@ -229,6 +229,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

@@ -73,14 +73,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 */

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

@@ -50,45 +50,46 @@
* 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 ) );
else
mbedtls_pk_parse_key(&ctx, data, data_length, NULL, 0));
} 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;
}
@@ -96,24 +97,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) ||
@@ -129,179 +130,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, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE );
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, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE);
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) */
@@ -315,127 +319,129 @@ 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 );
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
*md_alg = mbedtls_md_get_type( md_info );
psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH(alg);
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa(hash_alg);
*md_alg = mbedtls_md_get_type(md_info);
/* 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_info == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
if( mbedtls_md_get_size( md_info ) != hash_length )
return( PSA_ERROR_INVALID_ARGUMENT );
if (alg != PSA_ALG_RSA_PKCS1V15_SIGN_RAW) {
if (md_info == NULL) {
return PSA_ERROR_NOT_SUPPORTED;
}
if (mbedtls_md_get_size(md_info) != 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 ) )
{
mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE );
ret = mbedtls_rsa_pkcs1_sign( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PRIVATE,
md_alg,
(unsigned int) hash_length,
hash,
signature );
}
else
if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg)) {
mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE);
ret = mbedtls_rsa_pkcs1_sign(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PRIVATE,
md_alg,
(unsigned int) hash_length,
hash,
signature);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
if( PSA_ALG_IS_RSA_PSS( alg ) )
{
mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
ret = mbedtls_rsa_rsassa_pss_sign( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PRIVATE,
MBEDTLS_MD_NONE,
(unsigned int) hash_length,
hash,
signature );
}
else
if (PSA_ALG_IS_RSA_PSS(alg)) {
mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md_alg);
ret = mbedtls_rsa_rsassa_pss_sign(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PRIVATE,
MBEDTLS_MD_NONE,
(unsigned int) hash_length,
hash,
signature);
} 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 */
@@ -443,63 +449,60 @@ 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 ) )
{
mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE );
ret = mbedtls_rsa_pkcs1_verify( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PUBLIC,
md_alg,
(unsigned int) hash_length,
hash,
signature );
}
else
if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg)) {
mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V15,
MBEDTLS_MD_NONE);
ret = mbedtls_rsa_pkcs1_verify(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PUBLIC,
md_alg,
(unsigned int) hash_length,
hash,
signature);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
if( PSA_ALG_IS_RSA_PSS( alg ) )
{
int slen = rsa_pss_expected_salt_len( alg, rsa, hash_length );
mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
ret = mbedtls_rsa_rsassa_pss_verify_ext( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PUBLIC,
md_alg,
(unsigned int) hash_length,
hash,
md_alg,
slen,
signature );
}
else
if (PSA_ALG_IS_RSA_PSS(alg)) {
int slen = rsa_pss_expected_salt_len(alg, rsa, hash_length);
mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md_alg);
ret = mbedtls_rsa_rsassa_pss_verify_ext(rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PUBLIC,
md_alg,
(unsigned int) hash_length,
hash,
md_alg,
slen,
signature);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS */
{
status = PSA_ERROR_INVALID_ARGUMENT;
@@ -509,15 +512,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) ||

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,6 +210,6 @@ 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);
#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));
}

View File

@@ -51,7 +51,7 @@
* actually not used since it corresponds to #PSA_KEY_LOCATION_LOCAL_STORAGE
* which doesn't have a driver.
*/
#define PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE ( (psa_key_id_t) 0xfffffe00 )
#define PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE ((psa_key_id_t) 0xfffffe00)
/** The maximum number of registered secure element driver locations. */
#define PSA_MAX_SE_DRIVERS 4
@@ -62,13 +62,13 @@
* state. This function is only intended to be called at the end
* of mbedtls_psa_crypto_free().
*/
void psa_unregister_all_se_drivers( void );
void psa_unregister_all_se_drivers(void);
/** Initialize all secure element drivers.
*
* Called from psa_crypto_init().
*/
psa_status_t psa_init_all_se_drivers( void );
psa_status_t psa_init_all_se_drivers(void);
/** A structure that describes a registered secure element driver.
*
@@ -93,9 +93,9 @@ typedef struct psa_se_drv_table_entry_s psa_se_drv_table_entry_t;
* \retval 0
* \p lifetime does not correspond to a registered driver.
*/
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);
/** Return the secure element driver table entry for a lifetime value.
*
@@ -105,7 +105,7 @@ int psa_get_se_driver( psa_key_lifetime_t lifetime,
* \p NULL if \p lifetime does not correspond to a registered driver.
*/
psa_se_drv_table_entry_t *psa_get_se_driver_entry(
psa_key_lifetime_t lifetime );
psa_key_lifetime_t lifetime);
/** Return the method table for a secure element driver.
*
@@ -115,7 +115,7 @@ psa_se_drv_table_entry_t *psa_get_se_driver_entry(
* \c NULL if \p driver is \c 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 the context of a secure element driver.
*
@@ -125,7 +125,7 @@ const psa_drv_se_t *psa_get_se_driver_methods(
* \c NULL if \p driver is \c NULL.
*/
psa_drv_se_context_t *psa_get_se_driver_context(
psa_se_drv_table_entry_t *driver );
psa_se_drv_table_entry_t *driver);
/** Find a free slot for a key that is to be created.
*
@@ -141,15 +141,15 @@ 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);
/** Destroy a key in a secure element.
*
* This function calls the relevant driver method to destroy a key
* and updates the driver's persistent data.
*/
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);
/** Load the persistent data of a secure element driver.
*
@@ -164,7 +164,7 @@ psa_status_t psa_destroy_se_key( psa_se_drv_table_entry_t *driver,
* \return #PSA_ERROR_INVALID_ARGUMENT
*/
psa_status_t psa_load_se_persistent_data(
const psa_se_drv_table_entry_t *driver );
const psa_se_drv_table_entry_t *driver);
/** Save the persistent data of a secure element driver.
*
@@ -180,7 +180,7 @@ psa_status_t psa_load_se_persistent_data(
* \return #PSA_ERROR_INVALID_ARGUMENT
*/
psa_status_t psa_save_se_persistent_data(
const psa_se_drv_table_entry_t *driver );
const psa_se_drv_table_entry_t *driver);
/** Destroy the persistent data of a secure element driver.
*
@@ -189,14 +189,13 @@ psa_status_t psa_save_se_persistent_data(
* \param[in] location The location identifier for the driver whose
* persistent data is to be erased.
*/
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);
/** The storage representation of a key whose data is in a secure element.
*/
typedef struct
{
uint8_t slot_number[sizeof( psa_key_slot_number_t )];
typedef struct {
uint8_t slot_number[sizeof(psa_key_slot_number_t)];
} psa_se_key_data_storage_t;
#endif /* PSA_CRYPTO_SE_H */

View File

@@ -36,30 +36,31 @@
#include <string.h>
#include "mbedtls/platform.h"
#define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) )
#define ARRAY_LENGTH(array) (sizeof(array) / sizeof(*(array)))
typedef struct
{
typedef struct {
psa_key_slot_t key_slots[MBEDTLS_PSA_KEY_SLOT_COUNT];
unsigned key_slots_initialized : 1;
} psa_global_data_t;
static psa_global_data_t global_data;
int psa_is_valid_key_id( mbedtls_svc_key_id_t key, int vendor_ok )
int psa_is_valid_key_id(mbedtls_svc_key_id_t key, int vendor_ok)
{
psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key );
psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key);
if( ( PSA_KEY_ID_USER_MIN <= key_id ) &&
( key_id <= PSA_KEY_ID_USER_MAX ) )
return( 1 );
if ((PSA_KEY_ID_USER_MIN <= key_id) &&
(key_id <= PSA_KEY_ID_USER_MAX)) {
return 1;
}
if( vendor_ok &&
( PSA_KEY_ID_VENDOR_MIN <= key_id ) &&
( key_id <= PSA_KEY_ID_VENDOR_MAX ) )
return( 1 );
if (vendor_ok &&
(PSA_KEY_ID_VENDOR_MIN <= key_id) &&
(key_id <= PSA_KEY_ID_VENDOR_MAX)) {
return 1;
}
return( 0 );
return 0;
}
/** Get the description in memory of a key given its identifier and lock it.
@@ -94,16 +95,15 @@ int psa_is_valid_key_id( mbedtls_svc_key_id_t key, int vendor_ok )
* There is no key with key identifier \p key in the key slots.
*/
static psa_status_t psa_get_and_lock_key_slot_in_memory(
mbedtls_svc_key_id_t key, psa_key_slot_t **p_slot )
mbedtls_svc_key_id_t key, psa_key_slot_t **p_slot)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key );
psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key);
size_t slot_idx;
psa_key_slot_t *slot = NULL;
if( psa_key_id_is_volatile( key_id ) )
{
slot = &global_data.key_slots[ key_id - PSA_KEY_ID_VOLATILE_MIN ];
if (psa_key_id_is_volatile(key_id)) {
slot = &global_data.key_slots[key_id - PSA_KEY_ID_VOLATILE_MIN];
/*
* Check if both the PSA key identifier key_id and the owner
@@ -113,83 +113,79 @@ static psa_status_t psa_get_and_lock_key_slot_in_memory(
* is equal to zero. This is an invalid value for a PSA key identifier
* and thus cannot be equal to the valid PSA key identifier key_id.
*/
status = mbedtls_svc_key_id_equal( key, slot->attr.id ) ?
status = mbedtls_svc_key_id_equal(key, slot->attr.id) ?
PSA_SUCCESS : PSA_ERROR_DOES_NOT_EXIST;
}
else
{
if ( !psa_is_valid_key_id( key, 1 ) )
return( PSA_ERROR_INVALID_HANDLE );
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
slot = &global_data.key_slots[ slot_idx ];
if( mbedtls_svc_key_id_equal( key, slot->attr.id ) )
break;
} else {
if (!psa_is_valid_key_id(key, 1)) {
return PSA_ERROR_INVALID_HANDLE;
}
status = ( slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT ) ?
for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
slot = &global_data.key_slots[slot_idx];
if (mbedtls_svc_key_id_equal(key, slot->attr.id)) {
break;
}
}
status = (slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT) ?
PSA_SUCCESS : PSA_ERROR_DOES_NOT_EXIST;
}
if( status == PSA_SUCCESS )
{
status = psa_lock_key_slot( slot );
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
status = psa_lock_key_slot(slot);
if (status == PSA_SUCCESS) {
*p_slot = slot;
}
}
return( status );
return status;
}
psa_status_t psa_initialize_key_slots( void )
psa_status_t psa_initialize_key_slots(void)
{
/* Nothing to do: program startup and psa_wipe_all_key_slots() both
* guarantee that the key slots are initialized to all-zero, which
* means that all the key slots are in a valid, empty state. */
global_data.key_slots_initialized = 1;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
void psa_wipe_all_key_slots( void )
void psa_wipe_all_key_slots(void)
{
size_t slot_idx;
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
psa_key_slot_t *slot = &global_data.key_slots[ slot_idx ];
for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
psa_key_slot_t *slot = &global_data.key_slots[slot_idx];
slot->lock_count = 1;
(void) psa_wipe_key_slot( slot );
(void) psa_wipe_key_slot(slot);
}
global_data.key_slots_initialized = 0;
}
psa_status_t psa_get_empty_key_slot( psa_key_id_t *volatile_key_id,
psa_key_slot_t **p_slot )
psa_status_t psa_get_empty_key_slot(psa_key_id_t *volatile_key_id,
psa_key_slot_t **p_slot)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t slot_idx;
psa_key_slot_t *selected_slot, *unlocked_persistent_key_slot;
if( ! global_data.key_slots_initialized )
{
if (!global_data.key_slots_initialized) {
status = PSA_ERROR_BAD_STATE;
goto error;
}
selected_slot = unlocked_persistent_key_slot = NULL;
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
psa_key_slot_t *slot = &global_data.key_slots[ slot_idx ];
if( ! psa_is_key_slot_occupied( slot ) )
{
for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
psa_key_slot_t *slot = &global_data.key_slots[slot_idx];
if (!psa_is_key_slot_occupied(slot)) {
selected_slot = slot;
break;
}
if( ( unlocked_persistent_key_slot == NULL ) &&
( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) ) &&
( ! psa_is_key_slot_locked( slot ) ) )
if ((unlocked_persistent_key_slot == NULL) &&
(!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) &&
(!psa_is_key_slot_locked(slot))) {
unlocked_persistent_key_slot = slot;
}
}
/*
@@ -199,25 +195,24 @@ psa_status_t psa_get_empty_key_slot( psa_key_id_t *volatile_key_id,
* persistent key we are evicting now, we will reload its description from
* storage.
*/
if( ( selected_slot == NULL ) &&
( unlocked_persistent_key_slot != NULL ) )
{
if ((selected_slot == NULL) &&
(unlocked_persistent_key_slot != NULL)) {
selected_slot = unlocked_persistent_key_slot;
selected_slot->lock_count = 1;
psa_wipe_key_slot( selected_slot );
psa_wipe_key_slot(selected_slot);
}
if( selected_slot != NULL )
{
status = psa_lock_key_slot( selected_slot );
if( status != PSA_SUCCESS )
goto error;
if (selected_slot != NULL) {
status = psa_lock_key_slot(selected_slot);
if (status != PSA_SUCCESS) {
goto error;
}
*volatile_key_id = PSA_KEY_ID_VOLATILE_MIN +
( (psa_key_id_t)( selected_slot - global_data.key_slots ) );
((psa_key_id_t) (selected_slot - global_data.key_slots));
*p_slot = selected_slot;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
status = PSA_ERROR_INSUFFICIENT_MEMORY;
@@ -225,53 +220,52 @@ error:
*p_slot = NULL;
*volatile_key_id = 0;
return( status );
return status;
}
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
static psa_status_t psa_load_persistent_key_into_slot( psa_key_slot_t *slot )
static psa_status_t psa_load_persistent_key_into_slot(psa_key_slot_t *slot)
{
psa_status_t status = PSA_SUCCESS;
uint8_t *key_data = NULL;
size_t key_data_length = 0;
status = psa_load_persistent_key( &slot->attr,
&key_data, &key_data_length );
if( status != PSA_SUCCESS )
status = psa_load_persistent_key(&slot->attr,
&key_data, &key_data_length);
if (status != PSA_SUCCESS) {
goto exit;
}
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* Special handling is required for loading keys associated with a
* dynamically registered SE interface. */
const psa_drv_se_t *drv;
psa_drv_se_context_t *drv_context;
if( psa_get_se_driver( slot->attr.lifetime, &drv, &drv_context ) )
{
if (psa_get_se_driver(slot->attr.lifetime, &drv, &drv_context)) {
psa_se_key_data_storage_t *data;
if( key_data_length != sizeof( *data ) )
{
if (key_data_length != sizeof(*data)) {
status = PSA_ERROR_DATA_INVALID;
goto exit;
}
data = (psa_se_key_data_storage_t *) key_data;
status = psa_copy_key_material_into_slot(
slot, data->slot_number, sizeof( data->slot_number ) );
slot, data->slot_number, sizeof(data->slot_number));
goto exit;
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
status = psa_copy_key_material_into_slot( slot, key_data, key_data_length );
status = psa_copy_key_material_into_slot(slot, key_data, key_data_length);
exit:
psa_free_persistent_key_data( key_data, key_data_length );
return( status );
psa_free_persistent_key_data(key_data, key_data_length);
return status;
}
#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
static psa_status_t psa_load_builtin_key_into_slot( psa_key_slot_t *slot )
static psa_status_t psa_load_builtin_key_into_slot(psa_key_slot_t *slot)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
@@ -280,91 +274,98 @@ static psa_status_t psa_load_builtin_key_into_slot( psa_key_slot_t *slot )
size_t key_buffer_size = 0;
size_t key_buffer_length = 0;
if( ! psa_key_id_is_builtin(
MBEDTLS_SVC_KEY_ID_GET_KEY_ID( slot->attr.id ) ) )
{
return( PSA_ERROR_DOES_NOT_EXIST );
if (!psa_key_id_is_builtin(
MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id))) {
return PSA_ERROR_DOES_NOT_EXIST;
}
/* Check the platform function to see whether this key actually exists */
status = mbedtls_psa_platform_get_builtin_key(
slot->attr.id, &lifetime, &slot_number );
if( status != PSA_SUCCESS )
return( status );
slot->attr.id, &lifetime, &slot_number);
if (status != PSA_SUCCESS) {
return status;
}
/* Set required key attributes to ensure get_builtin_key can retrieve the
* full attributes. */
psa_set_key_id( &attributes, slot->attr.id );
psa_set_key_lifetime( &attributes, lifetime );
psa_set_key_id(&attributes, slot->attr.id);
psa_set_key_lifetime(&attributes, lifetime);
/* Get the full key attributes from the driver in order to be able to
* calculate the required buffer size. */
status = psa_driver_wrapper_get_builtin_key(
slot_number, &attributes,
NULL, 0, NULL );
if( status != PSA_ERROR_BUFFER_TOO_SMALL )
{
slot_number, &attributes,
NULL, 0, NULL);
if (status != PSA_ERROR_BUFFER_TOO_SMALL) {
/* Builtin keys cannot be defined by the attributes alone */
if( status == PSA_SUCCESS )
if (status == PSA_SUCCESS) {
status = PSA_ERROR_CORRUPTION_DETECTED;
return( status );
}
return status;
}
/* If the key should exist according to the platform, then ask the driver
* what its expected size is. */
status = psa_driver_wrapper_get_key_buffer_size( &attributes,
&key_buffer_size );
if( status != PSA_SUCCESS )
return( status );
status = psa_driver_wrapper_get_key_buffer_size(&attributes,
&key_buffer_size);
if (status != PSA_SUCCESS) {
return status;
}
/* Allocate a buffer of the required size and load the builtin key directly
* into the (now properly sized) slot buffer. */
status = psa_allocate_buffer_to_slot( slot, key_buffer_size );
if( status != PSA_SUCCESS )
return( status );
status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
if (status != PSA_SUCCESS) {
return status;
}
status = psa_driver_wrapper_get_builtin_key(
slot_number, &attributes,
slot->key.data, slot->key.bytes, &key_buffer_length );
if( status != PSA_SUCCESS )
slot_number, &attributes,
slot->key.data, slot->key.bytes, &key_buffer_length);
if (status != PSA_SUCCESS) {
goto exit;
}
/* Copy actual key length and core attributes into the slot on success */
slot->key.bytes = key_buffer_length;
slot->attr = attributes.core;
exit:
if( status != PSA_SUCCESS )
psa_remove_key_data_from_memory( slot );
return( status );
if (status != PSA_SUCCESS) {
psa_remove_key_data_from_memory(slot);
}
return status;
}
#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
psa_status_t psa_get_and_lock_key_slot( mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot )
psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
*p_slot = NULL;
if( ! global_data.key_slots_initialized )
return( PSA_ERROR_BAD_STATE );
if (!global_data.key_slots_initialized) {
return PSA_ERROR_BAD_STATE;
}
/*
* On success, the pointer to the slot is passed directly to the caller
* thus no need to unlock the key slot here.
*/
status = psa_get_and_lock_key_slot_in_memory( key, p_slot );
if( status != PSA_ERROR_DOES_NOT_EXIST )
return( status );
status = psa_get_and_lock_key_slot_in_memory(key, p_slot);
if (status != PSA_ERROR_DOES_NOT_EXIST) {
return status;
}
/* Loading keys from storage requires support for such a mechanism */
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || \
defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
psa_key_id_t volatile_key_id;
status = psa_get_empty_key_slot( &volatile_key_id, p_slot );
if( status != PSA_SUCCESS )
return( status );
status = psa_get_empty_key_slot(&volatile_key_id, p_slot);
if (status != PSA_SUCCESS) {
return status;
}
(*p_slot)->attr.id = key;
(*p_slot)->attr.lifetime = PSA_KEY_LIFETIME_PERSISTENT;
@@ -372,39 +373,40 @@ psa_status_t psa_get_and_lock_key_slot( mbedtls_svc_key_id_t key,
status = PSA_ERROR_DOES_NOT_EXIST;
#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
/* Load keys in the 'builtin' range through their own interface */
status = psa_load_builtin_key_into_slot( *p_slot );
status = psa_load_builtin_key_into_slot(*p_slot);
#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
if( status == PSA_ERROR_DOES_NOT_EXIST )
status = psa_load_persistent_key_into_slot( *p_slot );
if (status == PSA_ERROR_DOES_NOT_EXIST) {
status = psa_load_persistent_key_into_slot(*p_slot);
}
#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
if( status != PSA_SUCCESS )
{
psa_wipe_key_slot( *p_slot );
if( status == PSA_ERROR_DOES_NOT_EXIST )
if (status != PSA_SUCCESS) {
psa_wipe_key_slot(*p_slot);
if (status == PSA_ERROR_DOES_NOT_EXIST) {
status = PSA_ERROR_INVALID_HANDLE;
}
else
}
} else {
/* Add implicit usage flags. */
psa_extend_key_usage_flags( &(*p_slot)->attr.policy.usage );
psa_extend_key_usage_flags(&(*p_slot)->attr.policy.usage);
}
return( status );
return status;
#else /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
return( PSA_ERROR_INVALID_HANDLE );
return PSA_ERROR_INVALID_HANDLE;
#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
}
psa_status_t psa_unlock_key_slot( psa_key_slot_t *slot )
psa_status_t psa_unlock_key_slot(psa_key_slot_t *slot)
{
if( slot == NULL )
return( PSA_SUCCESS );
if (slot == NULL) {
return PSA_SUCCESS;
}
if( slot->lock_count > 0 )
{
if (slot->lock_count > 0) {
slot->lock_count--;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
/*
@@ -415,25 +417,24 @@ psa_status_t psa_unlock_key_slot( psa_key_slot_t *slot )
* test suite execution).
*/
#ifdef MBEDTLS_CHECK_PARAMS
MBEDTLS_PARAM_FAILED( slot->lock_count > 0 );
MBEDTLS_PARAM_FAILED(slot->lock_count > 0);
#endif
return( PSA_ERROR_CORRUPTION_DETECTED );
return PSA_ERROR_CORRUPTION_DETECTED;
}
psa_status_t psa_validate_key_location( psa_key_lifetime_t lifetime,
psa_se_drv_table_entry_t **p_drv )
psa_status_t psa_validate_key_location(psa_key_lifetime_t lifetime,
psa_se_drv_table_entry_t **p_drv)
{
if ( psa_key_lifetime_is_external( lifetime ) )
{
if (psa_key_lifetime_is_external(lifetime)) {
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* Check whether a driver is registered against this lifetime */
psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry( lifetime );
if( driver != NULL )
{
if (p_drv != NULL)
psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry(lifetime);
if (driver != NULL) {
if (p_drv != NULL) {
*p_drv = driver;
return( PSA_SUCCESS );
}
return PSA_SUCCESS;
}
#else /* MBEDTLS_PSA_CRYPTO_SE_C */
(void) p_drv;
@@ -441,139 +442,138 @@ psa_status_t psa_validate_key_location( psa_key_lifetime_t lifetime,
#if defined(MBEDTLS_PSA_CRYPTO_DRIVERS)
/* Key location for external keys gets checked by the wrapper */
return( PSA_SUCCESS );
return PSA_SUCCESS;
#else /* MBEDTLS_PSA_CRYPTO_DRIVERS */
/* No support for external lifetimes at all, or dynamic interface
* did not find driver for requested lifetime. */
return( PSA_ERROR_INVALID_ARGUMENT );
return PSA_ERROR_INVALID_ARGUMENT;
#endif /* MBEDTLS_PSA_CRYPTO_DRIVERS */
}
else
} else {
/* Local/internal keys are always valid */
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
}
psa_status_t psa_validate_key_persistence( psa_key_lifetime_t lifetime )
psa_status_t psa_validate_key_persistence(psa_key_lifetime_t lifetime)
{
if ( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) )
{
if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
/* Volatile keys are always supported */
return( PSA_SUCCESS );
}
else
{
return PSA_SUCCESS;
} else {
/* Persistent keys require storage support */
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
if( PSA_KEY_LIFETIME_IS_READ_ONLY( lifetime ) )
return( PSA_ERROR_INVALID_ARGUMENT );
else
return( PSA_SUCCESS );
if (PSA_KEY_LIFETIME_IS_READ_ONLY(lifetime)) {
return PSA_ERROR_INVALID_ARGUMENT;
} else {
return PSA_SUCCESS;
}
#else /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
return( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
#endif /* !MBEDTLS_PSA_CRYPTO_STORAGE_C */
}
}
psa_status_t psa_open_key( mbedtls_svc_key_id_t key, psa_key_handle_t *handle )
psa_status_t psa_open_key(mbedtls_svc_key_id_t key, psa_key_handle_t *handle)
{
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || \
defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
psa_status_t status;
psa_key_slot_t *slot;
status = psa_get_and_lock_key_slot( key, &slot );
if( status != PSA_SUCCESS )
{
status = psa_get_and_lock_key_slot(key, &slot);
if (status != PSA_SUCCESS) {
*handle = PSA_KEY_HANDLE_INIT;
if( status == PSA_ERROR_INVALID_HANDLE )
if (status == PSA_ERROR_INVALID_HANDLE) {
status = PSA_ERROR_DOES_NOT_EXIST;
}
return( status );
return status;
}
*handle = key;
return( psa_unlock_key_slot( slot ) );
return psa_unlock_key_slot(slot);
#else /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
(void) key;
*handle = PSA_KEY_HANDLE_INIT;
return( PSA_ERROR_NOT_SUPPORTED );
return PSA_ERROR_NOT_SUPPORTED;
#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
}
psa_status_t psa_close_key( psa_key_handle_t handle )
psa_status_t psa_close_key(psa_key_handle_t handle)
{
psa_status_t status;
psa_key_slot_t *slot;
if( psa_key_handle_is_null( handle ) )
return( PSA_SUCCESS );
status = psa_get_and_lock_key_slot_in_memory( handle, &slot );
if( status != PSA_SUCCESS )
{
if( status == PSA_ERROR_DOES_NOT_EXIST )
status = PSA_ERROR_INVALID_HANDLE;
return( status );
if (psa_key_handle_is_null(handle)) {
return PSA_SUCCESS;
}
status = psa_get_and_lock_key_slot_in_memory(handle, &slot);
if (status != PSA_SUCCESS) {
if (status == PSA_ERROR_DOES_NOT_EXIST) {
status = PSA_ERROR_INVALID_HANDLE;
}
return status;
}
if (slot->lock_count <= 1) {
return psa_wipe_key_slot(slot);
} else {
return psa_unlock_key_slot(slot);
}
if( slot->lock_count <= 1 )
return( psa_wipe_key_slot( slot ) );
else
return( psa_unlock_key_slot( slot ) );
}
psa_status_t psa_purge_key( mbedtls_svc_key_id_t key )
psa_status_t psa_purge_key(mbedtls_svc_key_id_t key)
{
psa_status_t status;
psa_key_slot_t *slot;
status = psa_get_and_lock_key_slot_in_memory( key, &slot );
if( status != PSA_SUCCESS )
return( status );
status = psa_get_and_lock_key_slot_in_memory(key, &slot);
if (status != PSA_SUCCESS) {
return status;
}
if( ( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) ) &&
( slot->lock_count <= 1 ) )
return( psa_wipe_key_slot( slot ) );
else
return( psa_unlock_key_slot( slot ) );
if ((!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) &&
(slot->lock_count <= 1)) {
return psa_wipe_key_slot(slot);
} else {
return psa_unlock_key_slot(slot);
}
}
void mbedtls_psa_get_stats( mbedtls_psa_stats_t *stats )
void mbedtls_psa_get_stats(mbedtls_psa_stats_t *stats)
{
size_t slot_idx;
memset( stats, 0, sizeof( *stats ) );
memset(stats, 0, sizeof(*stats));
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
const psa_key_slot_t *slot = &global_data.key_slots[ slot_idx ];
if( psa_is_key_slot_locked( slot ) )
{
for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
const psa_key_slot_t *slot = &global_data.key_slots[slot_idx];
if (psa_is_key_slot_locked(slot)) {
++stats->locked_slots;
}
if( ! psa_is_key_slot_occupied( slot ) )
{
if (!psa_is_key_slot_occupied(slot)) {
++stats->empty_slots;
continue;
}
if( PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
if (PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
++stats->volatile_slots;
else
{
psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( slot->attr.id );
} else {
psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id);
++stats->persistent_slots;
if( id > stats->max_open_internal_key_id )
if (id > stats->max_open_internal_key_id) {
stats->max_open_internal_key_id = id;
}
}
if( PSA_KEY_LIFETIME_GET_LOCATION( slot->attr.lifetime ) !=
PSA_KEY_LOCATION_LOCAL_STORAGE )
{
psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( slot->attr.id );
if (PSA_KEY_LIFETIME_GET_LOCATION(slot->attr.lifetime) !=
PSA_KEY_LOCATION_LOCAL_STORAGE) {
psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id);
++stats->external_slots;
if( id > stats->max_open_external_key_id )
if (id > stats->max_open_external_key_id) {
stats->max_open_external_key_id = id;
}
}
}
}

View File

@@ -35,8 +35,8 @@
/** The minimum value for a volatile key identifier.
*/
#define PSA_KEY_ID_VOLATILE_MIN ( PSA_KEY_ID_VENDOR_MAX - \
MBEDTLS_PSA_KEY_SLOT_COUNT + 1 )
#define PSA_KEY_ID_VOLATILE_MIN (PSA_KEY_ID_VENDOR_MAX - \
MBEDTLS_PSA_KEY_SLOT_COUNT + 1)
/** The maximum value for a volatile key identifier.
*/
@@ -51,10 +51,10 @@
* \retval 0
* The key identifier is not a volatile key identifier.
*/
static inline int psa_key_id_is_volatile( psa_key_id_t key_id )
static inline int psa_key_id_is_volatile(psa_key_id_t key_id)
{
return( ( key_id >= PSA_KEY_ID_VOLATILE_MIN ) &&
( key_id <= PSA_KEY_ID_VOLATILE_MAX ) );
return (key_id >= PSA_KEY_ID_VOLATILE_MIN) &&
(key_id <= PSA_KEY_ID_VOLATILE_MAX);
}
/** Get the description of a key given its identifier and lock it.
@@ -92,20 +92,20 @@ static inline int psa_key_id_is_volatile( psa_key_id_t key_id )
* \retval #PSA_ERROR_STORAGE_FAILURE
* \retval #PSA_ERROR_DATA_CORRUPT
*/
psa_status_t psa_get_and_lock_key_slot( mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot );
psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot);
/** Initialize the key slot structures.
*
* \retval #PSA_SUCCESS
* Currently this function always succeeds.
*/
psa_status_t psa_initialize_key_slots( void );
psa_status_t psa_initialize_key_slots(void);
/** Delete all data from key slots in memory.
*
* This does not affect persistent storage. */
void psa_wipe_all_key_slots( void );
void psa_wipe_all_key_slots(void);
/** Find a free key slot.
*
@@ -122,8 +122,8 @@ void psa_wipe_all_key_slots( void );
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
* \retval #PSA_ERROR_BAD_STATE
*/
psa_status_t psa_get_empty_key_slot( psa_key_id_t *volatile_key_id,
psa_key_slot_t **p_slot );
psa_status_t psa_get_empty_key_slot(psa_key_id_t *volatile_key_id,
psa_key_slot_t **p_slot);
/** Lock a key slot.
*
@@ -137,14 +137,15 @@ psa_status_t psa_get_empty_key_slot( psa_key_id_t *volatile_key_id,
* The lock counter already reached its maximum value and was not
* increased.
*/
static inline psa_status_t psa_lock_key_slot( psa_key_slot_t *slot )
static inline psa_status_t psa_lock_key_slot(psa_key_slot_t *slot)
{
if( slot->lock_count >= SIZE_MAX )
return( PSA_ERROR_CORRUPTION_DETECTED );
if (slot->lock_count >= SIZE_MAX) {
return PSA_ERROR_CORRUPTION_DETECTED;
}
slot->lock_count++;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
/** Unlock a key slot.
@@ -163,7 +164,7 @@ static inline psa_status_t psa_lock_key_slot( psa_key_slot_t *slot )
* The lock counter was equal to 0.
*
*/
psa_status_t psa_unlock_key_slot( psa_key_slot_t *slot );
psa_status_t psa_unlock_key_slot(psa_key_slot_t *slot);
/** Test whether a lifetime designates a key in an external cryptoprocessor.
*
@@ -177,10 +178,10 @@ psa_status_t psa_unlock_key_slot( psa_key_slot_t *slot );
* The lifetime designates a key that is volatile or in internal
* storage.
*/
static inline int psa_key_lifetime_is_external( psa_key_lifetime_t lifetime )
static inline int psa_key_lifetime_is_external(psa_key_lifetime_t lifetime)
{
return( PSA_KEY_LIFETIME_GET_LOCATION( lifetime )
!= PSA_KEY_LOCATION_LOCAL_STORAGE );
return PSA_KEY_LIFETIME_GET_LOCATION(lifetime)
!= PSA_KEY_LOCATION_LOCAL_STORAGE;
}
/** Validate a key's location.
@@ -197,8 +198,8 @@ static inline int psa_key_lifetime_is_external( psa_key_lifetime_t lifetime )
* \retval #PSA_SUCCESS
* \retval #PSA_ERROR_INVALID_ARGUMENT
*/
psa_status_t psa_validate_key_location( psa_key_lifetime_t lifetime,
psa_se_drv_table_entry_t **p_drv );
psa_status_t psa_validate_key_location(psa_key_lifetime_t lifetime,
psa_se_drv_table_entry_t **p_drv);
/** Validate the persistence of a key.
*
@@ -208,7 +209,7 @@ psa_status_t psa_validate_key_location( psa_key_lifetime_t lifetime,
* \retval #PSA_ERROR_NOT_SUPPORTED The key is persistent but persistent keys
* are not supported.
*/
psa_status_t psa_validate_key_persistence( psa_key_lifetime_t lifetime );
psa_status_t psa_validate_key_persistence(psa_key_lifetime_t lifetime);
/** Validate a key identifier.
*
@@ -219,6 +220,6 @@ psa_status_t psa_validate_key_persistence( psa_key_lifetime_t lifetime );
*
* \retval <> 0 if the key identifier is valid, 0 otherwise.
*/
int psa_is_valid_key_id( mbedtls_svc_key_id_t key, int vendor_ok );
int psa_is_valid_key_id(mbedtls_svc_key_id_t key, int vendor_ok);
#endif /* PSA_CRYPTO_SLOT_MANAGEMENT_H */

View File

@@ -47,22 +47,22 @@
* other than storing a key. Currently, the only such file is the random seed
* file whose name is PSA_CRYPTO_ITS_RANDOM_SEED_UID and whose value is
* 0xFFFFFF52. */
static psa_storage_uid_t psa_its_identifier_of_slot( mbedtls_svc_key_id_t key )
static psa_storage_uid_t psa_its_identifier_of_slot(mbedtls_svc_key_id_t key)
{
#if defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
/* Encode the owner in the upper 32 bits. This means that if
* owner values are nonzero (as they are on a PSA platform),
* no key file will ever have a value less than 0x100000000, so
* the whole range 0..0xffffffff is available for non-key files. */
uint32_t unsigned_owner_id = MBEDTLS_SVC_KEY_ID_GET_OWNER_ID( key );
return( ( (uint64_t) unsigned_owner_id << 32 ) |
MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key ) );
uint32_t unsigned_owner_id = MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(key);
return ((uint64_t) unsigned_owner_id << 32) |
MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key);
#else
/* Use the key id directly as a file name.
* psa_is_key_id_valid() in psa_crypto_slot_management.c
* is responsible for ensuring that key identifiers do not have a
* value that is reserved for non-key files. */
return( key );
return key;
#endif
}
@@ -84,35 +84,38 @@ static psa_storage_uid_t psa_its_identifier_of_slot( mbedtls_svc_key_id_t key )
* \retval #PSA_ERROR_DOES_NOT_EXIST
*/
static psa_status_t psa_crypto_storage_load(
const mbedtls_svc_key_id_t key, uint8_t *data, size_t data_size )
const mbedtls_svc_key_id_t key, uint8_t *data, size_t data_size)
{
psa_status_t status;
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot( key );
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot(key);
struct psa_storage_info_t data_identifier_info;
size_t data_length = 0;
status = psa_its_get_info( data_identifier, &data_identifier_info );
if( status != PSA_SUCCESS )
return( status );
status = psa_its_get_info(data_identifier, &data_identifier_info);
if (status != PSA_SUCCESS) {
return status;
}
status = psa_its_get( data_identifier, 0, (uint32_t) data_size, data, &data_length );
if( data_size != data_length )
return( PSA_ERROR_DATA_INVALID );
status = psa_its_get(data_identifier, 0, (uint32_t) data_size, data, &data_length);
if (data_size != data_length) {
return PSA_ERROR_DATA_INVALID;
}
return( status );
return status;
}
int psa_is_key_present_in_storage( const mbedtls_svc_key_id_t key )
int psa_is_key_present_in_storage(const mbedtls_svc_key_id_t key)
{
psa_status_t ret;
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot( key );
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot(key);
struct psa_storage_info_t data_identifier_info;
ret = psa_its_get_info( data_identifier, &data_identifier_info );
ret = psa_its_get_info(data_identifier, &data_identifier_info);
if( ret == PSA_ERROR_DOES_NOT_EXIST )
return( 0 );
return( 1 );
if (ret == PSA_ERROR_DOES_NOT_EXIST) {
return 0;
}
return 1;
}
/**
@@ -132,65 +135,65 @@ int psa_is_key_present_in_storage( const mbedtls_svc_key_id_t key )
* \retval #PSA_ERROR_STORAGE_FAILURE
* \retval #PSA_ERROR_DATA_INVALID
*/
static psa_status_t psa_crypto_storage_store( const mbedtls_svc_key_id_t key,
const uint8_t *data,
size_t data_length )
static psa_status_t psa_crypto_storage_store(const mbedtls_svc_key_id_t key,
const uint8_t *data,
size_t data_length)
{
psa_status_t status;
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot( key );
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot(key);
struct psa_storage_info_t data_identifier_info;
if( psa_is_key_present_in_storage( key ) == 1 )
return( PSA_ERROR_ALREADY_EXISTS );
status = psa_its_set( data_identifier, (uint32_t) data_length, data, 0 );
if( status != PSA_SUCCESS )
{
return( PSA_ERROR_DATA_INVALID );
if (psa_is_key_present_in_storage(key) == 1) {
return PSA_ERROR_ALREADY_EXISTS;
}
status = psa_its_get_info( data_identifier, &data_identifier_info );
if( status != PSA_SUCCESS )
{
status = psa_its_set(data_identifier, (uint32_t) data_length, data, 0);
if (status != PSA_SUCCESS) {
return PSA_ERROR_DATA_INVALID;
}
status = psa_its_get_info(data_identifier, &data_identifier_info);
if (status != PSA_SUCCESS) {
goto exit;
}
if( data_identifier_info.size != data_length )
{
if (data_identifier_info.size != data_length) {
status = PSA_ERROR_DATA_INVALID;
goto exit;
}
exit:
if( status != PSA_SUCCESS )
{
if (status != PSA_SUCCESS) {
/* Remove the file in case we managed to create it but something
* went wrong. It's ok if the file doesn't exist. If the file exists
* but the removal fails, we're already reporting an error so there's
* nothing else we can do. */
(void) psa_its_remove( data_identifier );
(void) psa_its_remove(data_identifier);
}
return( status );
return status;
}
psa_status_t psa_destroy_persistent_key( const mbedtls_svc_key_id_t key )
psa_status_t psa_destroy_persistent_key(const mbedtls_svc_key_id_t key)
{
psa_status_t ret;
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot( key );
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot(key);
struct psa_storage_info_t data_identifier_info;
ret = psa_its_get_info( data_identifier, &data_identifier_info );
if( ret == PSA_ERROR_DOES_NOT_EXIST )
return( PSA_SUCCESS );
ret = psa_its_get_info(data_identifier, &data_identifier_info);
if (ret == PSA_ERROR_DOES_NOT_EXIST) {
return PSA_SUCCESS;
}
if( psa_its_remove( data_identifier ) != PSA_SUCCESS )
return( PSA_ERROR_DATA_INVALID );
if (psa_its_remove(data_identifier) != PSA_SUCCESS) {
return PSA_ERROR_DATA_INVALID;
}
ret = psa_its_get_info( data_identifier, &data_identifier_info );
if( ret != PSA_ERROR_DOES_NOT_EXIST )
return( PSA_ERROR_DATA_INVALID );
ret = psa_its_get_info(data_identifier, &data_identifier_info);
if (ret != PSA_ERROR_DOES_NOT_EXIST) {
return PSA_ERROR_DATA_INVALID;
}
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
/**
@@ -207,189 +210,200 @@ psa_status_t psa_destroy_persistent_key( const mbedtls_svc_key_id_t key )
*/
static psa_status_t psa_crypto_storage_get_data_length(
const mbedtls_svc_key_id_t key,
size_t *data_length )
size_t *data_length)
{
psa_status_t status;
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot( key );
psa_storage_uid_t data_identifier = psa_its_identifier_of_slot(key);
struct psa_storage_info_t data_identifier_info;
status = psa_its_get_info( data_identifier, &data_identifier_info );
if( status != PSA_SUCCESS )
return( status );
status = psa_its_get_info(data_identifier, &data_identifier_info);
if (status != PSA_SUCCESS) {
return status;
}
*data_length = (size_t) data_identifier_info.size;
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
/**
* Persistent key storage magic header.
*/
#define PSA_KEY_STORAGE_MAGIC_HEADER "PSA\0KEY"
#define PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH ( sizeof( PSA_KEY_STORAGE_MAGIC_HEADER ) )
#define PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH (sizeof(PSA_KEY_STORAGE_MAGIC_HEADER))
typedef struct {
uint8_t magic[PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH];
uint8_t version[4];
uint8_t lifetime[sizeof( psa_key_lifetime_t )];
uint8_t lifetime[sizeof(psa_key_lifetime_t)];
uint8_t type[2];
uint8_t bits[2];
uint8_t policy[sizeof( psa_key_policy_t )];
uint8_t policy[sizeof(psa_key_policy_t)];
uint8_t data_len[4];
uint8_t key_data[];
} psa_persistent_key_storage_format;
void psa_format_key_data_for_storage( const uint8_t *data,
const size_t data_length,
const psa_core_key_attributes_t *attr,
uint8_t *storage_data )
void psa_format_key_data_for_storage(const uint8_t *data,
const size_t data_length,
const psa_core_key_attributes_t *attr,
uint8_t *storage_data)
{
psa_persistent_key_storage_format *storage_format =
(psa_persistent_key_storage_format *) storage_data;
memcpy( storage_format->magic, PSA_KEY_STORAGE_MAGIC_HEADER, PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH );
MBEDTLS_PUT_UINT32_LE( 0, storage_format->version, 0 );
MBEDTLS_PUT_UINT32_LE( attr->lifetime, storage_format->lifetime, 0 );
MBEDTLS_PUT_UINT16_LE( (uint16_t) attr->type, storage_format->type, 0 );
MBEDTLS_PUT_UINT16_LE( (uint16_t) attr->bits, storage_format->bits, 0 );
MBEDTLS_PUT_UINT32_LE( attr->policy.usage, storage_format->policy, 0 );
MBEDTLS_PUT_UINT32_LE( attr->policy.alg, storage_format->policy, sizeof( uint32_t ) );
MBEDTLS_PUT_UINT32_LE( attr->policy.alg2, storage_format->policy, 2 * sizeof( uint32_t ) );
MBEDTLS_PUT_UINT32_LE( data_length, storage_format->data_len, 0 );
memcpy( storage_format->key_data, data, data_length );
memcpy(storage_format->magic, PSA_KEY_STORAGE_MAGIC_HEADER,
PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH);
MBEDTLS_PUT_UINT32_LE(0, storage_format->version, 0);
MBEDTLS_PUT_UINT32_LE(attr->lifetime, storage_format->lifetime, 0);
MBEDTLS_PUT_UINT16_LE((uint16_t) attr->type, storage_format->type, 0);
MBEDTLS_PUT_UINT16_LE((uint16_t) attr->bits, storage_format->bits, 0);
MBEDTLS_PUT_UINT32_LE(attr->policy.usage, storage_format->policy, 0);
MBEDTLS_PUT_UINT32_LE(attr->policy.alg, storage_format->policy, sizeof(uint32_t));
MBEDTLS_PUT_UINT32_LE(attr->policy.alg2, storage_format->policy, 2 * sizeof(uint32_t));
MBEDTLS_PUT_UINT32_LE(data_length, storage_format->data_len, 0);
memcpy(storage_format->key_data, data, data_length);
}
static psa_status_t check_magic_header( const uint8_t *data )
static psa_status_t check_magic_header(const uint8_t *data)
{
if( memcmp( data, PSA_KEY_STORAGE_MAGIC_HEADER,
PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH ) != 0 )
return( PSA_ERROR_DATA_INVALID );
return( PSA_SUCCESS );
if (memcmp(data, PSA_KEY_STORAGE_MAGIC_HEADER,
PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH) != 0) {
return PSA_ERROR_DATA_INVALID;
}
return PSA_SUCCESS;
}
psa_status_t psa_parse_key_data_from_storage( const uint8_t *storage_data,
size_t storage_data_length,
uint8_t **key_data,
size_t *key_data_length,
psa_core_key_attributes_t *attr )
psa_status_t psa_parse_key_data_from_storage(const uint8_t *storage_data,
size_t storage_data_length,
uint8_t **key_data,
size_t *key_data_length,
psa_core_key_attributes_t *attr)
{
psa_status_t status;
const psa_persistent_key_storage_format *storage_format =
(const psa_persistent_key_storage_format *)storage_data;
(const psa_persistent_key_storage_format *) storage_data;
uint32_t version;
if( storage_data_length < sizeof(*storage_format) )
return( PSA_ERROR_DATA_INVALID );
if (storage_data_length < sizeof(*storage_format)) {
return PSA_ERROR_DATA_INVALID;
}
status = check_magic_header( storage_data );
if( status != PSA_SUCCESS )
return( status );
status = check_magic_header(storage_data);
if (status != PSA_SUCCESS) {
return status;
}
version = MBEDTLS_GET_UINT32_LE( storage_format->version, 0 );
if( version != 0 )
return( PSA_ERROR_DATA_INVALID );
version = MBEDTLS_GET_UINT32_LE(storage_format->version, 0);
if (version != 0) {
return PSA_ERROR_DATA_INVALID;
}
*key_data_length = MBEDTLS_GET_UINT32_LE( storage_format->data_len, 0 );
if( *key_data_length > ( storage_data_length - sizeof(*storage_format) ) ||
*key_data_length > PSA_CRYPTO_MAX_STORAGE_SIZE )
return( PSA_ERROR_DATA_INVALID );
*key_data_length = MBEDTLS_GET_UINT32_LE(storage_format->data_len, 0);
if (*key_data_length > (storage_data_length - sizeof(*storage_format)) ||
*key_data_length > PSA_CRYPTO_MAX_STORAGE_SIZE) {
return PSA_ERROR_DATA_INVALID;
}
if( *key_data_length == 0 )
{
if (*key_data_length == 0) {
*key_data = NULL;
}
else
{
*key_data = mbedtls_calloc( 1, *key_data_length );
if( *key_data == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
memcpy( *key_data, storage_format->key_data, *key_data_length );
} else {
*key_data = mbedtls_calloc(1, *key_data_length);
if (*key_data == NULL) {
return PSA_ERROR_INSUFFICIENT_MEMORY;
}
memcpy(*key_data, storage_format->key_data, *key_data_length);
}
attr->lifetime = MBEDTLS_GET_UINT32_LE( storage_format->lifetime, 0 );
attr->type = MBEDTLS_GET_UINT16_LE( storage_format->type, 0 );
attr->bits = MBEDTLS_GET_UINT16_LE( storage_format->bits, 0 );
attr->policy.usage = MBEDTLS_GET_UINT32_LE( storage_format->policy, 0 );
attr->policy.alg = MBEDTLS_GET_UINT32_LE( storage_format->policy, sizeof( uint32_t ) );
attr->policy.alg2 = MBEDTLS_GET_UINT32_LE( storage_format->policy, 2 * sizeof( uint32_t ) );
attr->lifetime = MBEDTLS_GET_UINT32_LE(storage_format->lifetime, 0);
attr->type = MBEDTLS_GET_UINT16_LE(storage_format->type, 0);
attr->bits = MBEDTLS_GET_UINT16_LE(storage_format->bits, 0);
attr->policy.usage = MBEDTLS_GET_UINT32_LE(storage_format->policy, 0);
attr->policy.alg = MBEDTLS_GET_UINT32_LE(storage_format->policy, sizeof(uint32_t));
attr->policy.alg2 = MBEDTLS_GET_UINT32_LE(storage_format->policy, 2 * sizeof(uint32_t));
return( PSA_SUCCESS );
return PSA_SUCCESS;
}
psa_status_t psa_save_persistent_key( const psa_core_key_attributes_t *attr,
const uint8_t *data,
const size_t data_length )
psa_status_t psa_save_persistent_key(const psa_core_key_attributes_t *attr,
const uint8_t *data,
const size_t data_length)
{
size_t storage_data_length;
uint8_t *storage_data;
psa_status_t status;
/* All keys saved to persistent storage always have a key context */
if( data == NULL || data_length == 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
if( data_length > PSA_CRYPTO_MAX_STORAGE_SIZE )
return( PSA_ERROR_INSUFFICIENT_STORAGE );
storage_data_length = data_length + sizeof( psa_persistent_key_storage_format );
storage_data = mbedtls_calloc( 1, storage_data_length );
if( storage_data == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
psa_format_key_data_for_storage( data, data_length, attr, storage_data );
status = psa_crypto_storage_store( attr->id,
storage_data, storage_data_length );
mbedtls_platform_zeroize( storage_data, storage_data_length );
mbedtls_free( storage_data );
return( status );
}
void psa_free_persistent_key_data( uint8_t *key_data, size_t key_data_length )
{
if( key_data != NULL )
{
mbedtls_platform_zeroize( key_data, key_data_length );
if (data == NULL || data_length == 0) {
return PSA_ERROR_INVALID_ARGUMENT;
}
mbedtls_free( key_data );
if (data_length > PSA_CRYPTO_MAX_STORAGE_SIZE) {
return PSA_ERROR_INSUFFICIENT_STORAGE;
}
storage_data_length = data_length + sizeof(psa_persistent_key_storage_format);
storage_data = mbedtls_calloc(1, storage_data_length);
if (storage_data == NULL) {
return PSA_ERROR_INSUFFICIENT_MEMORY;
}
psa_format_key_data_for_storage(data, data_length, attr, storage_data);
status = psa_crypto_storage_store(attr->id,
storage_data, storage_data_length);
mbedtls_platform_zeroize(storage_data, storage_data_length);
mbedtls_free(storage_data);
return status;
}
psa_status_t psa_load_persistent_key( psa_core_key_attributes_t *attr,
uint8_t **data,
size_t *data_length )
void psa_free_persistent_key_data(uint8_t *key_data, size_t key_data_length)
{
if (key_data != NULL) {
mbedtls_platform_zeroize(key_data, key_data_length);
}
mbedtls_free(key_data);
}
psa_status_t psa_load_persistent_key(psa_core_key_attributes_t *attr,
uint8_t **data,
size_t *data_length)
{
psa_status_t status = PSA_SUCCESS;
uint8_t *loaded_data;
size_t storage_data_length = 0;
mbedtls_svc_key_id_t key = attr->id;
status = psa_crypto_storage_get_data_length( key, &storage_data_length );
if( status != PSA_SUCCESS )
return( status );
status = psa_crypto_storage_get_data_length(key, &storage_data_length);
if (status != PSA_SUCCESS) {
return status;
}
loaded_data = mbedtls_calloc( 1, storage_data_length );
loaded_data = mbedtls_calloc(1, storage_data_length);
if( loaded_data == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
if (loaded_data == NULL) {
return PSA_ERROR_INSUFFICIENT_MEMORY;
}
status = psa_crypto_storage_load( key, loaded_data, storage_data_length );
if( status != PSA_SUCCESS )
status = psa_crypto_storage_load(key, loaded_data, storage_data_length);
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_parse_key_data_from_storage( loaded_data, storage_data_length,
data, data_length, attr );
status = psa_parse_key_data_from_storage(loaded_data, storage_data_length,
data, data_length, attr);
/* All keys saved to persistent storage always have a key context */
if( status == PSA_SUCCESS &&
( *data == NULL || *data_length == 0 ) )
if (status == PSA_SUCCESS &&
(*data == NULL || *data_length == 0)) {
status = PSA_ERROR_STORAGE_FAILURE;
}
exit:
mbedtls_platform_zeroize( loaded_data, storage_data_length );
mbedtls_free( loaded_data );
return( status );
mbedtls_platform_zeroize(loaded_data, storage_data_length);
mbedtls_free(loaded_data);
return status;
}
@@ -402,47 +416,48 @@ exit:
psa_crypto_transaction_t psa_crypto_transaction;
psa_status_t psa_crypto_save_transaction( void )
psa_status_t psa_crypto_save_transaction(void)
{
struct psa_storage_info_t p_info;
psa_status_t status;
status = psa_its_get_info( PSA_CRYPTO_ITS_TRANSACTION_UID, &p_info );
if( status == PSA_SUCCESS )
{
status = psa_its_get_info(PSA_CRYPTO_ITS_TRANSACTION_UID, &p_info);
if (status == PSA_SUCCESS) {
/* This shouldn't happen: we're trying to start a transaction while
* there is still a transaction that hasn't been replayed. */
return( PSA_ERROR_CORRUPTION_DETECTED );
return PSA_ERROR_CORRUPTION_DETECTED;
} else if (status != PSA_ERROR_DOES_NOT_EXIST) {
return status;
}
else if( status != PSA_ERROR_DOES_NOT_EXIST )
return( status );
return( psa_its_set( PSA_CRYPTO_ITS_TRANSACTION_UID,
sizeof( psa_crypto_transaction ),
&psa_crypto_transaction,
0 ) );
return psa_its_set(PSA_CRYPTO_ITS_TRANSACTION_UID,
sizeof(psa_crypto_transaction),
&psa_crypto_transaction,
0);
}
psa_status_t psa_crypto_load_transaction( void )
psa_status_t psa_crypto_load_transaction(void)
{
psa_status_t status;
size_t length;
status = psa_its_get( PSA_CRYPTO_ITS_TRANSACTION_UID, 0,
sizeof( psa_crypto_transaction ),
&psa_crypto_transaction, &length );
if( status != PSA_SUCCESS )
return( status );
if( length != sizeof( psa_crypto_transaction ) )
return( PSA_ERROR_DATA_INVALID );
return( PSA_SUCCESS );
status = psa_its_get(PSA_CRYPTO_ITS_TRANSACTION_UID, 0,
sizeof(psa_crypto_transaction),
&psa_crypto_transaction, &length);
if (status != PSA_SUCCESS) {
return status;
}
if (length != sizeof(psa_crypto_transaction)) {
return PSA_ERROR_DATA_INVALID;
}
return PSA_SUCCESS;
}
psa_status_t psa_crypto_stop_transaction( void )
psa_status_t psa_crypto_stop_transaction(void)
{
psa_status_t status = psa_its_remove( PSA_CRYPTO_ITS_TRANSACTION_UID );
psa_status_t status = psa_its_remove(PSA_CRYPTO_ITS_TRANSACTION_UID);
/* Whether or not updating the storage succeeded, the transaction is
* finished now. It's too late to go back, so zero out the in-memory
* data. */
memset( &psa_crypto_transaction, 0, sizeof( psa_crypto_transaction ) );
return( status );
memset(&psa_crypto_transaction, 0, sizeof(psa_crypto_transaction));
return status;
}
#endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
@@ -454,24 +469,21 @@ psa_status_t psa_crypto_stop_transaction( void )
/****************************************************************/
#if defined(MBEDTLS_PSA_INJECT_ENTROPY)
psa_status_t mbedtls_psa_storage_inject_entropy( const unsigned char *seed,
size_t seed_size )
psa_status_t mbedtls_psa_storage_inject_entropy(const unsigned char *seed,
size_t seed_size)
{
psa_status_t status;
struct psa_storage_info_t p_info;
status = psa_its_get_info( PSA_CRYPTO_ITS_RANDOM_SEED_UID, &p_info );
status = psa_its_get_info(PSA_CRYPTO_ITS_RANDOM_SEED_UID, &p_info);
if( PSA_ERROR_DOES_NOT_EXIST == status ) /* No seed exists */
{
status = psa_its_set( PSA_CRYPTO_ITS_RANDOM_SEED_UID, seed_size, seed, 0 );
}
else if( PSA_SUCCESS == status )
{
if (PSA_ERROR_DOES_NOT_EXIST == status) { /* No seed exists */
status = psa_its_set(PSA_CRYPTO_ITS_RANDOM_SEED_UID, seed_size, seed, 0);
} else if (PSA_SUCCESS == status) {
/* You should not be here. Seed needs to be injected only once */
status = PSA_ERROR_NOT_PERMITTED;
}
return( status );
return status;
}
#endif /* MBEDTLS_PSA_INJECT_ENTROPY */

View File

@@ -35,7 +35,7 @@ extern "C" {
/* Limit the maximum key size in storage. This should have no effect
* since the key size is limited in memory. */
#define PSA_CRYPTO_MAX_STORAGE_SIZE ( PSA_BITS_TO_BYTES( PSA_MAX_KEY_BITS ) )
#define PSA_CRYPTO_MAX_STORAGE_SIZE (PSA_BITS_TO_BYTES(PSA_MAX_KEY_BITS))
/* Sanity check: a file size must fit in 32 bits. Allow a generous
* 64kB of metadata. */
#if PSA_CRYPTO_MAX_STORAGE_SIZE > 0xffff0000
@@ -72,7 +72,7 @@ extern "C" {
* \retval 1
* Persistent data present for slot number
*/
int psa_is_key_present_in_storage( const mbedtls_svc_key_id_t key );
int psa_is_key_present_in_storage(const mbedtls_svc_key_id_t key);
/**
* \brief Format key data and metadata and save to a location for given key
@@ -105,9 +105,9 @@ int psa_is_key_present_in_storage( const mbedtls_svc_key_id_t key );
* \retval #PSA_ERROR_DATA_INVALID
* \retval #PSA_ERROR_DATA_CORRUPT
*/
psa_status_t psa_save_persistent_key( const psa_core_key_attributes_t *attr,
const uint8_t *data,
const size_t data_length );
psa_status_t psa_save_persistent_key(const psa_core_key_attributes_t *attr,
const uint8_t *data,
const size_t data_length);
/**
* \brief Parses key data and metadata and load persistent key for given
@@ -135,9 +135,9 @@ psa_status_t psa_save_persistent_key( const psa_core_key_attributes_t *attr,
* \retval #PSA_ERROR_DATA_CORRUPT
* \retval #PSA_ERROR_DOES_NOT_EXIST
*/
psa_status_t psa_load_persistent_key( psa_core_key_attributes_t *attr,
uint8_t **data,
size_t *data_length );
psa_status_t psa_load_persistent_key(psa_core_key_attributes_t *attr,
uint8_t **data,
size_t *data_length);
/**
* \brief Remove persistent data for the given key slot number.
@@ -150,7 +150,7 @@ psa_status_t psa_load_persistent_key( psa_core_key_attributes_t *attr,
* or the key did not exist.
* \retval #PSA_ERROR_DATA_INVALID
*/
psa_status_t psa_destroy_persistent_key( const mbedtls_svc_key_id_t key );
psa_status_t psa_destroy_persistent_key(const mbedtls_svc_key_id_t key);
/**
* \brief Free the temporary buffer allocated by psa_load_persistent_key().
@@ -162,7 +162,7 @@ psa_status_t psa_destroy_persistent_key( const mbedtls_svc_key_id_t key );
* \param key_data_length Size of the key data buffer.
*
*/
void psa_free_persistent_key_data( uint8_t *key_data, size_t key_data_length );
void psa_free_persistent_key_data(uint8_t *key_data, size_t key_data_length);
/**
* \brief Formats key data and metadata for persistent storage
@@ -173,10 +173,10 @@ void psa_free_persistent_key_data( uint8_t *key_data, size_t key_data_length );
* \param[out] storage_data Output buffer for the formatted data.
*
*/
void psa_format_key_data_for_storage( const uint8_t *data,
const size_t data_length,
const psa_core_key_attributes_t *attr,
uint8_t *storage_data );
void psa_format_key_data_for_storage(const uint8_t *data,
const size_t data_length,
const psa_core_key_attributes_t *attr,
uint8_t *storage_data);
/**
* \brief Parses persistent storage data into key data and metadata
@@ -194,11 +194,11 @@ void psa_format_key_data_for_storage( const uint8_t *data,
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
* \retval #PSA_ERROR_DATA_INVALID
*/
psa_status_t psa_parse_key_data_from_storage( const uint8_t *storage_data,
size_t storage_data_length,
uint8_t **key_data,
size_t *key_data_length,
psa_core_key_attributes_t *attr );
psa_status_t psa_parse_key_data_from_storage(const uint8_t *storage_data,
size_t storage_data_length,
uint8_t **key_data,
size_t *key_data_length,
psa_core_key_attributes_t *attr);
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/** This symbol is defined if transaction support is required. */
@@ -220,7 +220,7 @@ typedef uint16_t psa_crypto_transaction_type_t;
* This has the value 0, so zero-initialization sets a transaction's type to
* this value.
*/
#define PSA_CRYPTO_TRANSACTION_NONE ( (psa_crypto_transaction_type_t) 0x0000 )
#define PSA_CRYPTO_TRANSACTION_NONE ((psa_crypto_transaction_type_t) 0x0000)
/** A key creation transaction.
*
@@ -228,7 +228,7 @@ typedef uint16_t psa_crypto_transaction_type_t;
* Keys in RAM or in internal storage are created atomically in storage
* (simple file creation), so they do not need a transaction mechanism.
*/
#define PSA_CRYPTO_TRANSACTION_CREATE_KEY ( (psa_crypto_transaction_type_t) 0x0001 )
#define PSA_CRYPTO_TRANSACTION_CREATE_KEY ((psa_crypto_transaction_type_t) 0x0001)
/** A key destruction transaction.
*
@@ -236,7 +236,7 @@ typedef uint16_t psa_crypto_transaction_type_t;
* Keys in RAM or in internal storage are destroyed atomically in storage
* (simple file deletion), so they do not need a transaction mechanism.
*/
#define PSA_CRYPTO_TRANSACTION_DESTROY_KEY ( (psa_crypto_transaction_type_t) 0x0002 )
#define PSA_CRYPTO_TRANSACTION_DESTROY_KEY ((psa_crypto_transaction_type_t) 0x0002)
/** Transaction data.
*
@@ -274,8 +274,7 @@ typedef uint16_t psa_crypto_transaction_type_t;
* in psa_crypto.c. If you add a new type of transaction, be
* sure to add code for it in psa_crypto_recover_transaction().
*/
typedef union
{
typedef union {
/* Each element of this union must have the following properties
* to facilitate serialization and deserialization:
*
@@ -284,8 +283,7 @@ typedef union
* - Elements of the struct are arranged such a way that there is
* no padding.
*/
struct psa_crypto_transaction_unknown_s
{
struct psa_crypto_transaction_unknown_s {
psa_crypto_transaction_type_t type;
uint16_t unused1;
uint32_t unused2;
@@ -294,8 +292,7 @@ typedef union
} unknown;
/* ::type is #PSA_CRYPTO_TRANSACTION_CREATE_KEY or
* #PSA_CRYPTO_TRANSACTION_DESTROY_KEY. */
struct psa_crypto_transaction_key_s
{
struct psa_crypto_transaction_key_s {
psa_crypto_transaction_type_t type;
uint16_t unused1;
psa_key_lifetime_t lifetime;
@@ -315,7 +312,7 @@ extern psa_crypto_transaction_t psa_crypto_transaction;
* \param type The type of transaction to start.
*/
static inline void psa_crypto_prepare_transaction(
psa_crypto_transaction_type_t type )
psa_crypto_transaction_type_t type)
{
psa_crypto_transaction.unknown.type = type;
}
@@ -330,7 +327,7 @@ static inline void psa_crypto_prepare_transaction(
* \retval #PSA_ERROR_INSUFFICIENT_STORAGE
* \retval #PSA_ERROR_STORAGE_FAILURE
*/
psa_status_t psa_crypto_save_transaction( void );
psa_status_t psa_crypto_save_transaction(void);
/** Load the transaction data from storage, if any.
*
@@ -346,7 +343,7 @@ psa_status_t psa_crypto_save_transaction( void );
* \retval #PSA_ERROR_DATA_INVALID
* \retval #PSA_ERROR_DATA_CORRUPT
*/
psa_status_t psa_crypto_load_transaction( void );
psa_status_t psa_crypto_load_transaction(void);
/** Indicate that the current transaction is finished.
*
@@ -366,13 +363,13 @@ psa_status_t psa_crypto_load_transaction( void );
* It was impossible to determine whether there was transaction data
* in storage, or the transaction data could not be erased.
*/
psa_status_t psa_crypto_stop_transaction( void );
psa_status_t psa_crypto_stop_transaction(void);
/** The ITS file identifier for the transaction data.
*
* 0xffffffNN = special file; 0x74 = 't' for transaction.
*/
#define PSA_CRYPTO_ITS_TRANSACTION_UID ( (psa_key_id_t) 0xffffff74 )
#define PSA_CRYPTO_ITS_TRANSACTION_UID ((psa_key_id_t) 0xffffff74)
#endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
@@ -388,8 +385,8 @@ psa_status_t psa_crypto_stop_transaction( void );
* \retval #PSA_ERROR_NOT_PERMITTED
* The entropy seed file already exists.
*/
psa_status_t mbedtls_psa_storage_inject_entropy( const unsigned char *seed,
size_t seed_size );
psa_status_t mbedtls_psa_storage_inject_entropy(const unsigned char *seed,
size_t seed_size);
#endif /* MBEDTLS_PSA_INJECT_ENTROPY */
#ifdef __cplusplus

View File

@@ -42,10 +42,10 @@
#define PSA_ITS_STORAGE_FILENAME_PATTERN "%08x%08x"
#define PSA_ITS_STORAGE_SUFFIX ".psa_its"
#define PSA_ITS_STORAGE_FILENAME_LENGTH \
( sizeof( PSA_ITS_STORAGE_PREFIX ) - 1 + /*prefix without terminating 0*/ \
16 + /*UID (64-bit number in hex)*/ \
sizeof( PSA_ITS_STORAGE_SUFFIX ) - 1 + /*suffix without terminating 0*/ \
1 /*terminating null byte*/ )
(sizeof(PSA_ITS_STORAGE_PREFIX) - 1 + /*prefix without terminating 0*/ \
16 + /*UID (64-bit number in hex)*/ \
sizeof(PSA_ITS_STORAGE_SUFFIX) - 1 + /*suffix without terminating 0*/ \
1 /*terminating null byte*/)
#define PSA_ITS_STORAGE_TEMP \
PSA_ITS_STORAGE_PREFIX "tempfile" PSA_ITS_STORAGE_SUFFIX
@@ -59,130 +59,140 @@
* use MoveFileExA with the MOVEFILE_REPLACE_EXISTING flag instead.
* Returns 0 on success, nonzero on failure. */
#if defined(_WIN32)
#define rename_replace_existing( oldpath, newpath ) \
( ! MoveFileExA( oldpath, newpath, MOVEFILE_REPLACE_EXISTING ) )
#define rename_replace_existing(oldpath, newpath) \
(!MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
#else
#define rename_replace_existing( oldpath, newpath ) rename( oldpath, newpath )
#define rename_replace_existing(oldpath, newpath) rename(oldpath, newpath)
#endif
typedef struct
{
typedef struct {
uint8_t magic[PSA_ITS_MAGIC_LENGTH];
uint8_t size[sizeof( uint32_t )];
uint8_t flags[sizeof( psa_storage_create_flags_t )];
uint8_t size[sizeof(uint32_t)];
uint8_t flags[sizeof(psa_storage_create_flags_t)];
} psa_its_file_header_t;
static void psa_its_fill_filename( psa_storage_uid_t uid, char *filename )
static void psa_its_fill_filename(psa_storage_uid_t uid, char *filename)
{
/* Break up the UID into two 32-bit pieces so as not to rely on
* long long support in snprintf. */
mbedtls_snprintf( filename, PSA_ITS_STORAGE_FILENAME_LENGTH,
"%s" PSA_ITS_STORAGE_FILENAME_PATTERN "%s",
PSA_ITS_STORAGE_PREFIX,
(unsigned) ( uid >> 32 ),
(unsigned) ( uid & 0xffffffff ),
PSA_ITS_STORAGE_SUFFIX );
mbedtls_snprintf(filename, PSA_ITS_STORAGE_FILENAME_LENGTH,
"%s" PSA_ITS_STORAGE_FILENAME_PATTERN "%s",
PSA_ITS_STORAGE_PREFIX,
(unsigned) (uid >> 32),
(unsigned) (uid & 0xffffffff),
PSA_ITS_STORAGE_SUFFIX);
}
static psa_status_t psa_its_read_file( psa_storage_uid_t uid,
struct psa_storage_info_t *p_info,
FILE **p_stream )
static psa_status_t psa_its_read_file(psa_storage_uid_t uid,
struct psa_storage_info_t *p_info,
FILE **p_stream)
{
char filename[PSA_ITS_STORAGE_FILENAME_LENGTH];
psa_its_file_header_t header;
size_t n;
*p_stream = NULL;
psa_its_fill_filename( uid, filename );
*p_stream = fopen( filename, "rb" );
if( *p_stream == NULL )
return( PSA_ERROR_DOES_NOT_EXIST );
psa_its_fill_filename(uid, filename);
*p_stream = fopen(filename, "rb");
if (*p_stream == NULL) {
return PSA_ERROR_DOES_NOT_EXIST;
}
n = fread( &header, 1, sizeof( header ), *p_stream );
if( n != sizeof( header ) )
return( PSA_ERROR_DATA_CORRUPT );
if( memcmp( header.magic, PSA_ITS_MAGIC_STRING,
PSA_ITS_MAGIC_LENGTH ) != 0 )
return( PSA_ERROR_DATA_CORRUPT );
n = fread(&header, 1, sizeof(header), *p_stream);
if (n != sizeof(header)) {
return PSA_ERROR_DATA_CORRUPT;
}
if (memcmp(header.magic, PSA_ITS_MAGIC_STRING,
PSA_ITS_MAGIC_LENGTH) != 0) {
return PSA_ERROR_DATA_CORRUPT;
}
p_info->size = ( header.size[0] |
header.size[1] << 8 |
header.size[2] << 16 |
header.size[3] << 24 );
p_info->flags = ( header.flags[0] |
header.flags[1] << 8 |
header.flags[2] << 16 |
header.flags[3] << 24 );
return( PSA_SUCCESS );
p_info->size = (header.size[0] |
header.size[1] << 8 |
header.size[2] << 16 |
header.size[3] << 24);
p_info->flags = (header.flags[0] |
header.flags[1] << 8 |
header.flags[2] << 16 |
header.flags[3] << 24);
return PSA_SUCCESS;
}
psa_status_t psa_its_get_info( psa_storage_uid_t uid,
struct psa_storage_info_t *p_info )
psa_status_t psa_its_get_info(psa_storage_uid_t uid,
struct psa_storage_info_t *p_info)
{
psa_status_t status;
FILE *stream = NULL;
status = psa_its_read_file( uid, p_info, &stream );
if( stream != NULL )
fclose( stream );
return( status );
status = psa_its_read_file(uid, p_info, &stream);
if (stream != NULL) {
fclose(stream);
}
return status;
}
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 )
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)
{
psa_status_t status;
FILE *stream = NULL;
size_t n;
struct psa_storage_info_t info;
status = psa_its_read_file( uid, &info, &stream );
if( status != PSA_SUCCESS )
status = psa_its_read_file(uid, &info, &stream);
if (status != PSA_SUCCESS) {
goto exit;
}
status = PSA_ERROR_INVALID_ARGUMENT;
if( data_offset + data_length < data_offset )
if (data_offset + data_length < data_offset) {
goto exit;
}
#if SIZE_MAX < 0xffffffff
if( data_offset + data_length > SIZE_MAX )
if (data_offset + data_length > SIZE_MAX) {
goto exit;
}
#endif
if( data_offset + data_length > info.size )
if (data_offset + data_length > info.size) {
goto exit;
}
status = PSA_ERROR_STORAGE_FAILURE;
#if LONG_MAX < 0xffffffff
while( data_offset > LONG_MAX )
{
if( fseek( stream, LONG_MAX, SEEK_CUR ) != 0 )
while (data_offset > LONG_MAX) {
if (fseek(stream, LONG_MAX, SEEK_CUR) != 0) {
goto exit;
}
data_offset -= LONG_MAX;
}
#endif
if( fseek( stream, data_offset, SEEK_CUR ) != 0 )
if (fseek(stream, data_offset, SEEK_CUR) != 0) {
goto exit;
n = fread( p_data, 1, data_length, stream );
if( n != data_length )
}
n = fread(p_data, 1, data_length, stream);
if (n != data_length) {
goto exit;
}
status = PSA_SUCCESS;
if( p_data_length != NULL )
if (p_data_length != NULL) {
*p_data_length = n;
}
exit:
if( stream != NULL )
fclose( stream );
return( status );
if (stream != NULL) {
fclose(stream);
}
return status;
}
psa_status_t psa_its_set( psa_storage_uid_t uid,
uint32_t data_length,
const void *p_data,
psa_storage_create_flags_t create_flags )
psa_status_t psa_its_set(psa_storage_uid_t uid,
uint32_t data_length,
const void *p_data,
psa_storage_create_flags_t create_flags)
{
if( uid == 0 )
{
return( PSA_ERROR_INVALID_HANDLE );
if (uid == 0) {
return PSA_ERROR_INVALID_HANDLE;
}
psa_status_t status = PSA_ERROR_STORAGE_FAILURE;
@@ -191,60 +201,64 @@ psa_status_t psa_its_set( psa_storage_uid_t uid,
psa_its_file_header_t header;
size_t n;
memcpy( header.magic, PSA_ITS_MAGIC_STRING, PSA_ITS_MAGIC_LENGTH );
MBEDTLS_PUT_UINT32_LE( data_length, header.size, 0 );
MBEDTLS_PUT_UINT32_LE( create_flags, header.flags, 0 );
memcpy(header.magic, PSA_ITS_MAGIC_STRING, PSA_ITS_MAGIC_LENGTH);
MBEDTLS_PUT_UINT32_LE(data_length, header.size, 0);
MBEDTLS_PUT_UINT32_LE(create_flags, header.flags, 0);
psa_its_fill_filename( uid, filename );
stream = fopen( PSA_ITS_STORAGE_TEMP, "wb" );
if( stream == NULL )
psa_its_fill_filename(uid, filename);
stream = fopen(PSA_ITS_STORAGE_TEMP, "wb");
if (stream == NULL) {
goto exit;
}
status = PSA_ERROR_INSUFFICIENT_STORAGE;
n = fwrite( &header, 1, sizeof( header ), stream );
if( n != sizeof( header ) )
n = fwrite(&header, 1, sizeof(header), stream);
if (n != sizeof(header)) {
goto exit;
if( data_length != 0 )
{
n = fwrite( p_data, 1, data_length, stream );
if( n != data_length )
}
if (data_length != 0) {
n = fwrite(p_data, 1, data_length, stream);
if (n != data_length) {
goto exit;
}
}
status = PSA_SUCCESS;
exit:
if( stream != NULL )
{
int ret = fclose( stream );
if( status == PSA_SUCCESS && ret != 0 )
if (stream != NULL) {
int ret = fclose(stream);
if (status == PSA_SUCCESS && ret != 0) {
status = PSA_ERROR_INSUFFICIENT_STORAGE;
}
}
if( status == PSA_SUCCESS )
{
if( rename_replace_existing( PSA_ITS_STORAGE_TEMP, filename ) != 0 )
if (status == PSA_SUCCESS) {
if (rename_replace_existing(PSA_ITS_STORAGE_TEMP, filename) != 0) {
status = PSA_ERROR_STORAGE_FAILURE;
}
}
/* The temporary file may still exist, but only in failure cases where
* we're already reporting an error. So there's nothing we can do on
* failure. If the function succeeded, and in some error cases, the
* temporary file doesn't exist and so remove() is expected to fail.
* Thus we just ignore the return status of remove(). */
(void) remove( PSA_ITS_STORAGE_TEMP );
return( status );
(void) remove(PSA_ITS_STORAGE_TEMP);
return status;
}
psa_status_t psa_its_remove( psa_storage_uid_t uid )
psa_status_t psa_its_remove(psa_storage_uid_t uid)
{
char filename[PSA_ITS_STORAGE_FILENAME_LENGTH];
FILE *stream;
psa_its_fill_filename( uid, filename );
stream = fopen( filename, "rb" );
if( stream == NULL )
return( PSA_ERROR_DOES_NOT_EXIST );
fclose( stream );
if( remove( filename ) != 0 )
return( PSA_ERROR_STORAGE_FAILURE );
return( PSA_SUCCESS );
psa_its_fill_filename(uid, filename);
stream = fopen(filename, "rb");
if (stream == NULL) {
return PSA_ERROR_DOES_NOT_EXIST;
}
fclose(stream);
if (remove(filename) != 0) {
return PSA_ERROR_STORAGE_FAILURE;
}
return PSA_SUCCESS;
}
#endif /* MBEDTLS_PSA_ITS_FILE_C */

View File

@@ -37,21 +37,22 @@
#if !defined(MBEDTLS_RIPEMD160_ALT)
void mbedtls_ripemd160_init( mbedtls_ripemd160_context *ctx )
void mbedtls_ripemd160_init(mbedtls_ripemd160_context *ctx)
{
memset( ctx, 0, sizeof( mbedtls_ripemd160_context ) );
memset(ctx, 0, sizeof(mbedtls_ripemd160_context));
}
void mbedtls_ripemd160_free( mbedtls_ripemd160_context *ctx )
void mbedtls_ripemd160_free(mbedtls_ripemd160_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ripemd160_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_ripemd160_context));
}
void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst,
const mbedtls_ripemd160_context *src )
void mbedtls_ripemd160_clone(mbedtls_ripemd160_context *dst,
const mbedtls_ripemd160_context *src)
{
*dst = *src;
}
@@ -59,7 +60,7 @@ void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst,
/*
* RIPEMD-160 context setup
*/
int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx )
int mbedtls_ripemd160_starts_ret(mbedtls_ripemd160_context *ctx)
{
ctx->total[0] = 0;
ctx->total[1] = 0;
@@ -70,13 +71,13 @@ int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx )
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx )
void mbedtls_ripemd160_starts(mbedtls_ripemd160_context *ctx)
{
mbedtls_ripemd160_starts_ret( ctx );
mbedtls_ripemd160_starts_ret(ctx);
}
#endif
@@ -84,30 +85,29 @@ void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx )
/*
* Process one block
*/
int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
const unsigned char data[64] )
int mbedtls_internal_ripemd160_process(mbedtls_ripemd160_context *ctx,
const unsigned char data[64])
{
struct
{
struct {
uint32_t A, B, C, D, E, Ap, Bp, Cp, Dp, Ep, X[16];
} 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);
local.A = local.Ap = ctx->state[0];
local.B = local.Bp = ctx->state[1];
@@ -115,50 +115,50 @@ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
local.D = local.Dp = ctx->state[3];
local.E = local.Ep = ctx->state[4];
#define F1( x, y, z ) ( (x) ^ (y) ^ (z) )
#define F2( x, y, z ) ( ( (x) & (y) ) | ( ~(x) & (z) ) )
#define F3( x, y, z ) ( ( (x) | ~(y) ) ^ (z) )
#define F4( x, y, z ) ( ( (x) & (z) ) | ( (y) & ~(z) ) )
#define F5( x, y, z ) ( (x) ^ ( (y) | ~(z) ) )
#define F1(x, y, z) ((x) ^ (y) ^ (z))
#define F2(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define F3(x, y, z) (((x) | ~(y)) ^ (z))
#define F4(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define F5(x, y, z) ((x) ^ ((y) | ~(z)))
#define S( x, n ) ( ( (x) << (n) ) | ( (x) >> (32 - (n)) ) )
#define S(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
#define P( a, b, c, d, e, r, s, f, k ) \
#define P(a, b, c, d, e, r, s, f, k) \
do \
{ \
(a) += f( (b), (c), (d) ) + local.X[r] + (k); \
(a) = S( (a), (s) ) + (e); \
(c) = S( (c), 10 ); \
} while( 0 )
(a) += f((b), (c), (d)) + local.X[r] + (k); \
(a) = S((a), (s)) + (e); \
(c) = S((c), 10); \
} while (0)
#define P2( a, b, c, d, e, r, s, rp, sp ) \
#define P2(a, b, c, d, e, r, s, rp, sp) \
do \
{ \
P( (a), (b), (c), (d), (e), (r), (s), F, K ); \
P( a ## p, b ## p, c ## p, d ## p, e ## p, \
(rp), (sp), Fp, Kp ); \
} while( 0 )
P((a), (b), (c), (d), (e), (r), (s), F, K); \
P(a ## p, b ## p, c ## p, d ## p, e ## p, \
(rp), (sp), Fp, Kp); \
} while (0)
#define F F1
#define K 0x00000000
#define Fp F5
#define Kp 0x50A28BE6
P2( local.A, local.B, local.C, local.D, local.E, 0, 11, 5, 8 );
P2( local.E, local.A, local.B, local.C, local.D, 1, 14, 14, 9 );
P2( local.D, local.E, local.A, local.B, local.C, 2, 15, 7, 9 );
P2( local.C, local.D, local.E, local.A, local.B, 3, 12, 0, 11 );
P2( local.B, local.C, local.D, local.E, local.A, 4, 5, 9, 13 );
P2( local.A, local.B, local.C, local.D, local.E, 5, 8, 2, 15 );
P2( local.E, local.A, local.B, local.C, local.D, 6, 7, 11, 15 );
P2( local.D, local.E, local.A, local.B, local.C, 7, 9, 4, 5 );
P2( local.C, local.D, local.E, local.A, local.B, 8, 11, 13, 7 );
P2( local.B, local.C, local.D, local.E, local.A, 9, 13, 6, 7 );
P2( local.A, local.B, local.C, local.D, local.E, 10, 14, 15, 8 );
P2( local.E, local.A, local.B, local.C, local.D, 11, 15, 8, 11 );
P2( local.D, local.E, local.A, local.B, local.C, 12, 6, 1, 14 );
P2( local.C, local.D, local.E, local.A, local.B, 13, 7, 10, 14 );
P2( local.B, local.C, local.D, local.E, local.A, 14, 9, 3, 12 );
P2( local.A, local.B, local.C, local.D, local.E, 15, 8, 12, 6 );
P2(local.A, local.B, local.C, local.D, local.E, 0, 11, 5, 8);
P2(local.E, local.A, local.B, local.C, local.D, 1, 14, 14, 9);
P2(local.D, local.E, local.A, local.B, local.C, 2, 15, 7, 9);
P2(local.C, local.D, local.E, local.A, local.B, 3, 12, 0, 11);
P2(local.B, local.C, local.D, local.E, local.A, 4, 5, 9, 13);
P2(local.A, local.B, local.C, local.D, local.E, 5, 8, 2, 15);
P2(local.E, local.A, local.B, local.C, local.D, 6, 7, 11, 15);
P2(local.D, local.E, local.A, local.B, local.C, 7, 9, 4, 5);
P2(local.C, local.D, local.E, local.A, local.B, 8, 11, 13, 7);
P2(local.B, local.C, local.D, local.E, local.A, 9, 13, 6, 7);
P2(local.A, local.B, local.C, local.D, local.E, 10, 14, 15, 8);
P2(local.E, local.A, local.B, local.C, local.D, 11, 15, 8, 11);
P2(local.D, local.E, local.A, local.B, local.C, 12, 6, 1, 14);
P2(local.C, local.D, local.E, local.A, local.B, 13, 7, 10, 14);
P2(local.B, local.C, local.D, local.E, local.A, 14, 9, 3, 12);
P2(local.A, local.B, local.C, local.D, local.E, 15, 8, 12, 6);
#undef F
#undef K
#undef Fp
@@ -168,22 +168,22 @@ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
#define K 0x5A827999
#define Fp F4
#define Kp 0x5C4DD124
P2( local.E, local.A, local.B, local.C, local.D, 7, 7, 6, 9 );
P2( local.D, local.E, local.A, local.B, local.C, 4, 6, 11, 13 );
P2( local.C, local.D, local.E, local.A, local.B, 13, 8, 3, 15 );
P2( local.B, local.C, local.D, local.E, local.A, 1, 13, 7, 7 );
P2( local.A, local.B, local.C, local.D, local.E, 10, 11, 0, 12 );
P2( local.E, local.A, local.B, local.C, local.D, 6, 9, 13, 8 );
P2( local.D, local.E, local.A, local.B, local.C, 15, 7, 5, 9 );
P2( local.C, local.D, local.E, local.A, local.B, 3, 15, 10, 11 );
P2( local.B, local.C, local.D, local.E, local.A, 12, 7, 14, 7 );
P2( local.A, local.B, local.C, local.D, local.E, 0, 12, 15, 7 );
P2( local.E, local.A, local.B, local.C, local.D, 9, 15, 8, 12 );
P2( local.D, local.E, local.A, local.B, local.C, 5, 9, 12, 7 );
P2( local.C, local.D, local.E, local.A, local.B, 2, 11, 4, 6 );
P2( local.B, local.C, local.D, local.E, local.A, 14, 7, 9, 15 );
P2( local.A, local.B, local.C, local.D, local.E, 11, 13, 1, 13 );
P2( local.E, local.A, local.B, local.C, local.D, 8, 12, 2, 11 );
P2(local.E, local.A, local.B, local.C, local.D, 7, 7, 6, 9);
P2(local.D, local.E, local.A, local.B, local.C, 4, 6, 11, 13);
P2(local.C, local.D, local.E, local.A, local.B, 13, 8, 3, 15);
P2(local.B, local.C, local.D, local.E, local.A, 1, 13, 7, 7);
P2(local.A, local.B, local.C, local.D, local.E, 10, 11, 0, 12);
P2(local.E, local.A, local.B, local.C, local.D, 6, 9, 13, 8);
P2(local.D, local.E, local.A, local.B, local.C, 15, 7, 5, 9);
P2(local.C, local.D, local.E, local.A, local.B, 3, 15, 10, 11);
P2(local.B, local.C, local.D, local.E, local.A, 12, 7, 14, 7);
P2(local.A, local.B, local.C, local.D, local.E, 0, 12, 15, 7);
P2(local.E, local.A, local.B, local.C, local.D, 9, 15, 8, 12);
P2(local.D, local.E, local.A, local.B, local.C, 5, 9, 12, 7);
P2(local.C, local.D, local.E, local.A, local.B, 2, 11, 4, 6);
P2(local.B, local.C, local.D, local.E, local.A, 14, 7, 9, 15);
P2(local.A, local.B, local.C, local.D, local.E, 11, 13, 1, 13);
P2(local.E, local.A, local.B, local.C, local.D, 8, 12, 2, 11);
#undef F
#undef K
#undef Fp
@@ -193,22 +193,22 @@ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
#define K 0x6ED9EBA1
#define Fp F3
#define Kp 0x6D703EF3
P2( local.D, local.E, local.A, local.B, local.C, 3, 11, 15, 9 );
P2( local.C, local.D, local.E, local.A, local.B, 10, 13, 5, 7 );
P2( local.B, local.C, local.D, local.E, local.A, 14, 6, 1, 15 );
P2( local.A, local.B, local.C, local.D, local.E, 4, 7, 3, 11 );
P2( local.E, local.A, local.B, local.C, local.D, 9, 14, 7, 8 );
P2( local.D, local.E, local.A, local.B, local.C, 15, 9, 14, 6 );
P2( local.C, local.D, local.E, local.A, local.B, 8, 13, 6, 6 );
P2( local.B, local.C, local.D, local.E, local.A, 1, 15, 9, 14 );
P2( local.A, local.B, local.C, local.D, local.E, 2, 14, 11, 12 );
P2( local.E, local.A, local.B, local.C, local.D, 7, 8, 8, 13 );
P2( local.D, local.E, local.A, local.B, local.C, 0, 13, 12, 5 );
P2( local.C, local.D, local.E, local.A, local.B, 6, 6, 2, 14 );
P2( local.B, local.C, local.D, local.E, local.A, 13, 5, 10, 13 );
P2( local.A, local.B, local.C, local.D, local.E, 11, 12, 0, 13 );
P2( local.E, local.A, local.B, local.C, local.D, 5, 7, 4, 7 );
P2( local.D, local.E, local.A, local.B, local.C, 12, 5, 13, 5 );
P2(local.D, local.E, local.A, local.B, local.C, 3, 11, 15, 9);
P2(local.C, local.D, local.E, local.A, local.B, 10, 13, 5, 7);
P2(local.B, local.C, local.D, local.E, local.A, 14, 6, 1, 15);
P2(local.A, local.B, local.C, local.D, local.E, 4, 7, 3, 11);
P2(local.E, local.A, local.B, local.C, local.D, 9, 14, 7, 8);
P2(local.D, local.E, local.A, local.B, local.C, 15, 9, 14, 6);
P2(local.C, local.D, local.E, local.A, local.B, 8, 13, 6, 6);
P2(local.B, local.C, local.D, local.E, local.A, 1, 15, 9, 14);
P2(local.A, local.B, local.C, local.D, local.E, 2, 14, 11, 12);
P2(local.E, local.A, local.B, local.C, local.D, 7, 8, 8, 13);
P2(local.D, local.E, local.A, local.B, local.C, 0, 13, 12, 5);
P2(local.C, local.D, local.E, local.A, local.B, 6, 6, 2, 14);
P2(local.B, local.C, local.D, local.E, local.A, 13, 5, 10, 13);
P2(local.A, local.B, local.C, local.D, local.E, 11, 12, 0, 13);
P2(local.E, local.A, local.B, local.C, local.D, 5, 7, 4, 7);
P2(local.D, local.E, local.A, local.B, local.C, 12, 5, 13, 5);
#undef F
#undef K
#undef Fp
@@ -218,22 +218,22 @@ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
#define K 0x8F1BBCDC
#define Fp F2
#define Kp 0x7A6D76E9
P2( local.C, local.D, local.E, local.A, local.B, 1, 11, 8, 15 );
P2( local.B, local.C, local.D, local.E, local.A, 9, 12, 6, 5 );
P2( local.A, local.B, local.C, local.D, local.E, 11, 14, 4, 8 );
P2( local.E, local.A, local.B, local.C, local.D, 10, 15, 1, 11 );
P2( local.D, local.E, local.A, local.B, local.C, 0, 14, 3, 14 );
P2( local.C, local.D, local.E, local.A, local.B, 8, 15, 11, 14 );
P2( local.B, local.C, local.D, local.E, local.A, 12, 9, 15, 6 );
P2( local.A, local.B, local.C, local.D, local.E, 4, 8, 0, 14 );
P2( local.E, local.A, local.B, local.C, local.D, 13, 9, 5, 6 );
P2( local.D, local.E, local.A, local.B, local.C, 3, 14, 12, 9 );
P2( local.C, local.D, local.E, local.A, local.B, 7, 5, 2, 12 );
P2( local.B, local.C, local.D, local.E, local.A, 15, 6, 13, 9 );
P2( local.A, local.B, local.C, local.D, local.E, 14, 8, 9, 12 );
P2( local.E, local.A, local.B, local.C, local.D, 5, 6, 7, 5 );
P2( local.D, local.E, local.A, local.B, local.C, 6, 5, 10, 15 );
P2( local.C, local.D, local.E, local.A, local.B, 2, 12, 14, 8 );
P2(local.C, local.D, local.E, local.A, local.B, 1, 11, 8, 15);
P2(local.B, local.C, local.D, local.E, local.A, 9, 12, 6, 5);
P2(local.A, local.B, local.C, local.D, local.E, 11, 14, 4, 8);
P2(local.E, local.A, local.B, local.C, local.D, 10, 15, 1, 11);
P2(local.D, local.E, local.A, local.B, local.C, 0, 14, 3, 14);
P2(local.C, local.D, local.E, local.A, local.B, 8, 15, 11, 14);
P2(local.B, local.C, local.D, local.E, local.A, 12, 9, 15, 6);
P2(local.A, local.B, local.C, local.D, local.E, 4, 8, 0, 14);
P2(local.E, local.A, local.B, local.C, local.D, 13, 9, 5, 6);
P2(local.D, local.E, local.A, local.B, local.C, 3, 14, 12, 9);
P2(local.C, local.D, local.E, local.A, local.B, 7, 5, 2, 12);
P2(local.B, local.C, local.D, local.E, local.A, 15, 6, 13, 9);
P2(local.A, local.B, local.C, local.D, local.E, 14, 8, 9, 12);
P2(local.E, local.A, local.B, local.C, local.D, 5, 6, 7, 5);
P2(local.D, local.E, local.A, local.B, local.C, 6, 5, 10, 15);
P2(local.C, local.D, local.E, local.A, local.B, 2, 12, 14, 8);
#undef F
#undef K
#undef Fp
@@ -243,22 +243,22 @@ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
#define K 0xA953FD4E
#define Fp F1
#define Kp 0x00000000
P2( local.B, local.C, local.D, local.E, local.A, 4, 9, 12, 8 );
P2( local.A, local.B, local.C, local.D, local.E, 0, 15, 15, 5 );
P2( local.E, local.A, local.B, local.C, local.D, 5, 5, 10, 12 );
P2( local.D, local.E, local.A, local.B, local.C, 9, 11, 4, 9 );
P2( local.C, local.D, local.E, local.A, local.B, 7, 6, 1, 12 );
P2( local.B, local.C, local.D, local.E, local.A, 12, 8, 5, 5 );
P2( local.A, local.B, local.C, local.D, local.E, 2, 13, 8, 14 );
P2( local.E, local.A, local.B, local.C, local.D, 10, 12, 7, 6 );
P2( local.D, local.E, local.A, local.B, local.C, 14, 5, 6, 8 );
P2( local.C, local.D, local.E, local.A, local.B, 1, 12, 2, 13 );
P2( local.B, local.C, local.D, local.E, local.A, 3, 13, 13, 6 );
P2( local.A, local.B, local.C, local.D, local.E, 8, 14, 14, 5 );
P2( local.E, local.A, local.B, local.C, local.D, 11, 11, 0, 15 );
P2( local.D, local.E, local.A, local.B, local.C, 6, 8, 3, 13 );
P2( local.C, local.D, local.E, local.A, local.B, 15, 5, 9, 11 );
P2( local.B, local.C, local.D, local.E, local.A, 13, 6, 11, 11 );
P2(local.B, local.C, local.D, local.E, local.A, 4, 9, 12, 8);
P2(local.A, local.B, local.C, local.D, local.E, 0, 15, 15, 5);
P2(local.E, local.A, local.B, local.C, local.D, 5, 5, 10, 12);
P2(local.D, local.E, local.A, local.B, local.C, 9, 11, 4, 9);
P2(local.C, local.D, local.E, local.A, local.B, 7, 6, 1, 12);
P2(local.B, local.C, local.D, local.E, local.A, 12, 8, 5, 5);
P2(local.A, local.B, local.C, local.D, local.E, 2, 13, 8, 14);
P2(local.E, local.A, local.B, local.C, local.D, 10, 12, 7, 6);
P2(local.D, local.E, local.A, local.B, local.C, 14, 5, 6, 8);
P2(local.C, local.D, local.E, local.A, local.B, 1, 12, 2, 13);
P2(local.B, local.C, local.D, local.E, local.A, 3, 13, 13, 6);
P2(local.A, local.B, local.C, local.D, local.E, 8, 14, 14, 5);
P2(local.E, local.A, local.B, local.C, local.D, 11, 11, 0, 15);
P2(local.D, local.E, local.A, local.B, local.C, 6, 8, 3, 13);
P2(local.C, local.D, local.E, local.A, local.B, 15, 5, 9, 11);
P2(local.B, local.C, local.D, local.E, local.A, 13, 6, 11, 11);
#undef F
#undef K
#undef Fp
@@ -272,16 +272,16 @@ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
ctx->state[0] = local.C;
/* Zeroise variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
mbedtls_platform_zeroize(&local, sizeof(local));
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx,
const unsigned char data[64] )
void mbedtls_ripemd160_process(mbedtls_ripemd160_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_ripemd160_process( ctx, data );
mbedtls_internal_ripemd160_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_RIPEMD160_PROCESS_ALT */
@@ -289,16 +289,17 @@ void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx,
/*
* RIPEMD-160 process buffer
*/
int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_ripemd160_update_ret(mbedtls_ripemd160_context *ctx,
const unsigned char *input,
size_t ilen)
{
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;
@@ -306,50 +307,50 @@ int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_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 (left && ilen >= fill) {
memcpy((void *) (ctx->buffer + left), input, fill);
if( ( ret = mbedtls_internal_ripemd160_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_ripemd160_process(ctx, ctx->buffer)) != 0) {
return ret;
}
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
if( ( ret = mbedtls_internal_ripemd160_process( ctx, input ) ) != 0 )
return( ret );
while (ilen >= 64) {
if ((ret = mbedtls_internal_ripemd160_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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx,
const unsigned char *input,
size_t ilen )
void mbedtls_ripemd160_update(mbedtls_ripemd160_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_ripemd160_update_ret( ctx, input, ilen );
mbedtls_ripemd160_update_ret(ctx, input, ilen);
}
#endif
static const unsigned char ripemd160_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
@@ -358,46 +359,48 @@ static const unsigned char ripemd160_padding[64] =
/*
* RIPEMD-160 final digest
*/
int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx,
unsigned char output[20] )
int mbedtls_ripemd160_finish_ret(mbedtls_ripemd160_context *ctx,
unsigned char output[20])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint32_t last, padn;
uint32_t high, low;
unsigned char msglen[8];
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, msglen, 0 );
MBEDTLS_PUT_UINT32_LE( high, msglen, 4 );
MBEDTLS_PUT_UINT32_LE(low, msglen, 0);
MBEDTLS_PUT_UINT32_LE(high, msglen, 4);
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
padn = (last < 56) ? (56 - last) : (120 - last);
ret = mbedtls_ripemd160_update_ret( ctx, ripemd160_padding, padn );
if( ret != 0 )
return( ret );
ret = mbedtls_ripemd160_update_ret(ctx, ripemd160_padding, padn);
if (ret != 0) {
return ret;
}
ret = mbedtls_ripemd160_update_ret( ctx, msglen, 8 );
if( ret != 0 )
return( ret );
ret = mbedtls_ripemd160_update_ret(ctx, msglen, 8);
if (ret != 0) {
return ret;
}
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[4], output, 16 );
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[4], output, 16);
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx,
unsigned char output[20] )
void mbedtls_ripemd160_finish(mbedtls_ripemd160_context *ctx,
unsigned char output[20])
{
mbedtls_ripemd160_finish_ret( ctx, output );
mbedtls_ripemd160_finish_ret(ctx, output);
}
#endif
@@ -406,36 +409,39 @@ void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx,
/*
* output = RIPEMD-160( input buffer )
*/
int mbedtls_ripemd160_ret( const unsigned char *input,
size_t ilen,
unsigned char output[20] )
int mbedtls_ripemd160_ret(const unsigned char *input,
size_t ilen,
unsigned char output[20])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ripemd160_context ctx;
mbedtls_ripemd160_init( &ctx );
mbedtls_ripemd160_init(&ctx);
if( ( ret = mbedtls_ripemd160_starts_ret( &ctx ) ) != 0 )
if ((ret = mbedtls_ripemd160_starts_ret(&ctx)) != 0) {
goto exit;
}
if( ( ret = mbedtls_ripemd160_update_ret( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_ripemd160_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_ripemd160_finish_ret( &ctx, output ) ) != 0 )
if ((ret = mbedtls_ripemd160_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_ripemd160_free( &ctx );
mbedtls_ripemd160_free(&ctx);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160( const unsigned char *input,
size_t ilen,
unsigned char output[20] )
void mbedtls_ripemd160(const unsigned char *input,
size_t ilen,
unsigned char output[20])
{
mbedtls_ripemd160_ret( input, ilen, output );
mbedtls_ripemd160_ret(input, ilen, output);
}
#endif
@@ -485,43 +491,46 @@ static const unsigned char ripemd160_test_md[TESTS][20] =
/*
* Checkup routine
*/
int mbedtls_ripemd160_self_test( int verbose )
int mbedtls_ripemd160_self_test(int verbose)
{
int i, ret = 0;
unsigned char output[20];
memset( output, 0, sizeof output );
memset(output, 0, sizeof output);
for( i = 0; i < TESTS; i++ )
{
if( verbose != 0 )
mbedtls_printf( " RIPEMD-160 test #%d: ", i + 1 );
for (i = 0; i < TESTS; i++) {
if (verbose != 0) {
mbedtls_printf(" RIPEMD-160 test #%d: ", i + 1);
}
ret = mbedtls_ripemd160_ret( ripemd160_test_str[i],
ripemd160_test_strlen[i], output );
if( ret != 0 )
ret = mbedtls_ripemd160_ret(ripemd160_test_str[i],
ripemd160_test_strlen[i], output);
if (ret != 0) {
goto fail;
}
if( memcmp( output, ripemd160_test_md[i], 20 ) != 0 )
{
if (memcmp(output, ripemd160_test_md[i], 20) != 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 */

File diff suppressed because it is too large Load Diff

View File

@@ -59,9 +59,9 @@
* of (a) and (b) above to attempt to factor N.
*
*/
int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
mbedtls_mpi const *E, mbedtls_mpi const *D,
mbedtls_mpi *P, mbedtls_mpi *Q )
int mbedtls_rsa_deduce_primes(mbedtls_mpi const *N,
mbedtls_mpi const *E, mbedtls_mpi const *D,
mbedtls_mpi *P, mbedtls_mpi *Q)
{
int ret = 0;
@@ -74,48 +74,46 @@ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
mbedtls_mpi K; /* Temporary holding the current candidate */
const unsigned char primes[] = { 2,
3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179,
181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251
};
3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179,
181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251 };
const size_t num_primes = sizeof( primes ) / sizeof( *primes );
const size_t num_primes = sizeof(primes) / sizeof(*primes);
if( P == NULL || Q == NULL || P->p != NULL || Q->p != NULL )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (P == NULL || Q == NULL || P->p != NULL || Q->p != NULL) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 ||
mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
{
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (mbedtls_mpi_cmp_int(N, 0) <= 0 ||
mbedtls_mpi_cmp_int(D, 1) <= 0 ||
mbedtls_mpi_cmp_mpi(D, N) >= 0 ||
mbedtls_mpi_cmp_int(E, 1) <= 0 ||
mbedtls_mpi_cmp_mpi(E, N) >= 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
/*
* Initializations and temporary changes
*/
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &T );
mbedtls_mpi_init(&K);
mbedtls_mpi_init(&T);
/* T := DE - 1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &T, &T, 1 ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, D, E));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&T, &T, 1));
if( ( order = (uint16_t) mbedtls_mpi_lsb( &T ) ) == 0 )
{
if ((order = (uint16_t) mbedtls_mpi_lsb(&T)) == 0) {
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
goto cleanup;
}
/* After this operation, T holds the largest odd divisor of DE - 1. */
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &T, order ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&T, order));
/*
* Actual work
@@ -123,49 +121,49 @@ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
/* Skip trying 2 if N == 1 mod 8 */
attempt = 0;
if( N->p[0] % 8 == 1 )
if (N->p[0] % 8 == 1) {
attempt = 1;
}
for( ; attempt < num_primes; ++attempt )
{
mbedtls_mpi_lset( &K, primes[attempt] );
for (; attempt < num_primes; ++attempt) {
mbedtls_mpi_lset(&K, primes[attempt]);
/* Check if gcd(K,N) = 1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );
if( mbedtls_mpi_cmp_int( P, 1 ) != 0 )
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(P, &K, N));
if (mbedtls_mpi_cmp_int(P, 1) != 0) {
continue;
}
/* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ...
* and check whether they have nontrivial GCD with N. */
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &K, &K, &T, N,
Q /* temporarily use Q for storing Montgomery
* multiplication helper values */ ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&K, &K, &T, N,
Q /* temporarily use Q for storing Montgomery
* multiplication helper values */));
for( iter = 1; iter <= order; ++iter )
{
for (iter = 1; iter <= order; ++iter) {
/* If we reach 1 prematurely, there's no point
* in continuing to square K */
if( mbedtls_mpi_cmp_int( &K, 1 ) == 0 )
if (mbedtls_mpi_cmp_int(&K, 1) == 0) {
break;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&K, &K, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(P, &K, N));
if( mbedtls_mpi_cmp_int( P, 1 ) == 1 &&
mbedtls_mpi_cmp_mpi( P, N ) == -1 )
{
if (mbedtls_mpi_cmp_int(P, 1) == 1 &&
mbedtls_mpi_cmp_mpi(P, N) == -1) {
/*
* Have found a nontrivial divisor P of N.
* Set Q := N / P.
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( Q, NULL, N, P ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(Q, NULL, N, P));
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &K ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, N ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, &K, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&K, &K, &K));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&K, &K, N));
}
/*
@@ -175,8 +173,7 @@ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
* Check if that's the case and abort if not, to avoid very long,
* yet eventually failing, computations if N,D,E were not sane.
*/
if( mbedtls_mpi_cmp_int( &K, 1 ) != 0 )
{
if (mbedtls_mpi_cmp_int(&K, 1) != 0) {
break;
}
}
@@ -185,125 +182,116 @@ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &T );
return( ret );
mbedtls_mpi_free(&K);
mbedtls_mpi_free(&T);
return ret;
}
/*
* Given P, Q and the public exponent E, deduce D.
* This is essentially a modular inversion.
*/
int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,
mbedtls_mpi const *Q,
mbedtls_mpi const *E,
mbedtls_mpi *D )
int mbedtls_rsa_deduce_private_exponent(mbedtls_mpi const *P,
mbedtls_mpi const *Q,
mbedtls_mpi const *E,
mbedtls_mpi *D)
{
int ret = 0;
mbedtls_mpi K, L;
if( D == NULL || mbedtls_mpi_cmp_int( D, 0 ) != 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( E, 0 ) == 0 )
{
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if (D == NULL || mbedtls_mpi_cmp_int(D, 0) != 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
if (mbedtls_mpi_cmp_int(P, 1) <= 0 ||
mbedtls_mpi_cmp_int(Q, 1) <= 0 ||
mbedtls_mpi_cmp_int(E, 0) == 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
mbedtls_mpi_init(&K);
mbedtls_mpi_init(&L);
/* Temporarily put K := P-1 and L := Q-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, P, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&L, Q, 1));
/* Temporarily put D := gcd(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( D, &K, &L ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(D, &K, &L));
/* K := LCM(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &L ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &K, NULL, &K, D ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&K, &K, &L));
MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&K, NULL, &K, D));
/* Compute modular inverse of E in LCM(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( D, E, &K ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(D, E, &K));
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
mbedtls_mpi_free(&K);
mbedtls_mpi_free(&L);
return( ret );
return ret;
}
/*
* Check that RSA CRT parameters are in accordance with core parameters.
*/
int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *DP,
const mbedtls_mpi *DQ, const mbedtls_mpi *QP )
int mbedtls_rsa_validate_crt(const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *DP,
const mbedtls_mpi *DQ, const mbedtls_mpi *QP)
{
int ret = 0;
mbedtls_mpi K, L;
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
mbedtls_mpi_init(&K);
mbedtls_mpi_init(&L);
/* Check that DP - D == 0 mod P - 1 */
if( DP != NULL )
{
if( P == NULL )
{
if (DP != NULL) {
if (P == NULL) {
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, P, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&L, DP, D));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&L, &L, &K));
if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
{
if (mbedtls_mpi_cmp_int(&L, 0) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/* Check that DQ - D == 0 mod Q - 1 */
if( DQ != NULL )
{
if( Q == NULL )
{
if (DQ != NULL) {
if (Q == NULL) {
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, Q, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&L, DQ, D));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&L, &L, &K));
if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
{
if (mbedtls_mpi_cmp_int(&L, 0) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/* Check that QP * Q - 1 == 0 mod P */
if( QP != NULL )
{
if( P == NULL || Q == NULL )
{
if (QP != NULL) {
if (P == NULL || Q == NULL) {
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&K, QP, Q));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, &K, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&K, &K, P));
if (mbedtls_mpi_cmp_int(&K, 0) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
@@ -312,33 +300,32 @@ int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
cleanup:
/* Wrap MPI error codes by RSA check failure error code */
if( ret != 0 &&
if (ret != 0 &&
ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED &&
ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA )
{
ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA) {
ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
}
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
mbedtls_mpi_free(&K);
mbedtls_mpi_free(&L);
return( ret );
return ret;
}
/*
* Check that core RSA parameters are sane.
*/
int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
const mbedtls_mpi *Q, const mbedtls_mpi *D,
const mbedtls_mpi *E,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
int mbedtls_rsa_validate_params(const mbedtls_mpi *N, const mbedtls_mpi *P,
const mbedtls_mpi *Q, const mbedtls_mpi *D,
const mbedtls_mpi *E,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int ret = 0;
mbedtls_mpi K, L;
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
mbedtls_mpi_init(&K);
mbedtls_mpi_init(&L);
/*
* Step 1: If PRNG provided, check that P and Q are prime
@@ -350,16 +337,14 @@ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
* rate of at most 2^-100 and we are aiming for the same certainty here as
* well.
*/
if( f_rng != NULL && P != NULL &&
( ret = mbedtls_mpi_is_prime_ext( P, 50, f_rng, p_rng ) ) != 0 )
{
if (f_rng != NULL && P != NULL &&
(ret = mbedtls_mpi_is_prime_ext(P, 50, f_rng, p_rng)) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
if( f_rng != NULL && Q != NULL &&
( ret = mbedtls_mpi_is_prime_ext( Q, 50, f_rng, p_rng ) ) != 0 )
{
if (f_rng != NULL && Q != NULL &&
(ret = mbedtls_mpi_is_prime_ext(Q, 50, f_rng, p_rng)) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
@@ -372,12 +357,10 @@ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
* Step 2: Check that 1 < N = P * Q
*/
if( P != NULL && Q != NULL && N != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) );
if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( &K, N ) != 0 )
{
if (P != NULL && Q != NULL && N != NULL) {
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&K, P, Q));
if (mbedtls_mpi_cmp_int(N, 1) <= 0 ||
mbedtls_mpi_cmp_mpi(&K, N) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
@@ -387,13 +370,11 @@ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
* Step 3: Check and 1 < D, E < N if present.
*/
if( N != NULL && D != NULL && E != NULL )
{
if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
{
if (N != NULL && D != NULL && E != NULL) {
if (mbedtls_mpi_cmp_int(D, 1) <= 0 ||
mbedtls_mpi_cmp_int(E, 1) <= 0 ||
mbedtls_mpi_cmp_mpi(D, N) >= 0 ||
mbedtls_mpi_cmp_mpi(E, N) >= 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
@@ -403,33 +384,29 @@ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
* Step 4: Check that D, E are inverse modulo P-1 and Q-1
*/
if( P != NULL && Q != NULL && D != NULL && E != NULL )
{
if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( Q, 1 ) <= 0 )
{
if (P != NULL && Q != NULL && D != NULL && E != NULL) {
if (mbedtls_mpi_cmp_int(P, 1) <= 0 ||
mbedtls_mpi_cmp_int(Q, 1) <= 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
/* Compute DE-1 mod P-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&K, D, E));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, &K, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&L, P, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&K, &K, &L));
if (mbedtls_mpi_cmp_int(&K, 0) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
/* Compute DE-1 mod Q-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&K, D, E));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, &K, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&L, Q, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&K, &K, &L));
if (mbedtls_mpi_cmp_int(&K, 0) != 0) {
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
@@ -437,50 +414,46 @@ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
mbedtls_mpi_free(&K);
mbedtls_mpi_free(&L);
/* Wrap MPI error codes by RSA check failure error code */
if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED )
{
if (ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) {
ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
}
return( ret );
return ret;
}
int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, mbedtls_mpi *DP,
mbedtls_mpi *DQ, mbedtls_mpi *QP )
int mbedtls_rsa_deduce_crt(const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, mbedtls_mpi *DP,
mbedtls_mpi *DQ, mbedtls_mpi *QP)
{
int ret = 0;
mbedtls_mpi K;
mbedtls_mpi_init( &K );
mbedtls_mpi_init(&K);
/* DP = D mod P-1 */
if( DP != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DP, D, &K ) );
if (DP != NULL) {
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, P, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(DP, D, &K));
}
/* DQ = D mod Q-1 */
if( DQ != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DQ, D, &K ) );
if (DQ != NULL) {
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&K, Q, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(DQ, D, &K));
}
/* QP = Q^{-1} mod P */
if( QP != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( QP, Q, P ) );
if (QP != NULL) {
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(QP, Q, P));
}
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free(&K);
return( ret );
return ret;
}
#endif /* MBEDTLS_RSA_C */

View File

@@ -35,32 +35,33 @@
#include "mbedtls/platform.h"
#define SHA1_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA1_BAD_INPUT_DATA )
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_SHA1_BAD_INPUT_DATA)
#define SHA1_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond )
#define SHA1_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE(cond)
#if !defined(MBEDTLS_SHA1_ALT)
void mbedtls_sha1_init( mbedtls_sha1_context *ctx )
void mbedtls_sha1_init(mbedtls_sha1_context *ctx)
{
SHA1_VALIDATE( ctx != NULL );
SHA1_VALIDATE(ctx != NULL);
memset( ctx, 0, sizeof( mbedtls_sha1_context ) );
memset(ctx, 0, sizeof(mbedtls_sha1_context));
}
void mbedtls_sha1_free( mbedtls_sha1_context *ctx )
void mbedtls_sha1_free(mbedtls_sha1_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_sha1_context));
}
void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src )
void mbedtls_sha1_clone(mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src)
{
SHA1_VALIDATE( dst != NULL );
SHA1_VALIDATE( src != NULL );
SHA1_VALIDATE(dst != NULL);
SHA1_VALIDATE(src != NULL);
*dst = *src;
}
@@ -68,9 +69,9 @@ void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
/*
* SHA-1 context setup
*/
int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx )
int mbedtls_sha1_starts_ret(mbedtls_sha1_context *ctx)
{
SHA1_VALIDATE_RET( ctx != NULL );
SHA1_VALIDATE_RET(ctx != NULL);
ctx->total[0] = 0;
ctx->total[1] = 0;
@@ -81,62 +82,61 @@ int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx )
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_starts( mbedtls_sha1_context *ctx )
void mbedtls_sha1_starts(mbedtls_sha1_context *ctx)
{
mbedtls_sha1_starts_ret( ctx );
mbedtls_sha1_starts_ret(ctx);
}
#endif
#if !defined(MBEDTLS_SHA1_PROCESS_ALT)
int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] )
int mbedtls_internal_sha1_process(mbedtls_sha1_context *ctx,
const unsigned char data[64])
{
struct
{
struct {
uint32_t temp, W[16], A, B, C, D, E;
} local;
SHA1_VALIDATE_RET( ctx != NULL );
SHA1_VALIDATE_RET( (const unsigned char *)data != NULL );
SHA1_VALIDATE_RET(ctx != NULL);
SHA1_VALIDATE_RET((const unsigned char *) data != NULL);
local.W[ 0] = MBEDTLS_GET_UINT32_BE( data, 0 );
local.W[ 1] = MBEDTLS_GET_UINT32_BE( data, 4 );
local.W[ 2] = MBEDTLS_GET_UINT32_BE( data, 8 );
local.W[ 3] = MBEDTLS_GET_UINT32_BE( data, 12 );
local.W[ 4] = MBEDTLS_GET_UINT32_BE( data, 16 );
local.W[ 5] = MBEDTLS_GET_UINT32_BE( data, 20 );
local.W[ 6] = MBEDTLS_GET_UINT32_BE( data, 24 );
local.W[ 7] = MBEDTLS_GET_UINT32_BE( data, 28 );
local.W[ 8] = MBEDTLS_GET_UINT32_BE( data, 32 );
local.W[ 9] = MBEDTLS_GET_UINT32_BE( data, 36 );
local.W[10] = MBEDTLS_GET_UINT32_BE( data, 40 );
local.W[11] = MBEDTLS_GET_UINT32_BE( data, 44 );
local.W[12] = MBEDTLS_GET_UINT32_BE( data, 48 );
local.W[13] = MBEDTLS_GET_UINT32_BE( data, 52 );
local.W[14] = MBEDTLS_GET_UINT32_BE( data, 56 );
local.W[15] = MBEDTLS_GET_UINT32_BE( data, 60 );
local.W[0] = MBEDTLS_GET_UINT32_BE(data, 0);
local.W[1] = MBEDTLS_GET_UINT32_BE(data, 4);
local.W[2] = MBEDTLS_GET_UINT32_BE(data, 8);
local.W[3] = MBEDTLS_GET_UINT32_BE(data, 12);
local.W[4] = MBEDTLS_GET_UINT32_BE(data, 16);
local.W[5] = MBEDTLS_GET_UINT32_BE(data, 20);
local.W[6] = MBEDTLS_GET_UINT32_BE(data, 24);
local.W[7] = MBEDTLS_GET_UINT32_BE(data, 28);
local.W[8] = MBEDTLS_GET_UINT32_BE(data, 32);
local.W[9] = MBEDTLS_GET_UINT32_BE(data, 36);
local.W[10] = MBEDTLS_GET_UINT32_BE(data, 40);
local.W[11] = MBEDTLS_GET_UINT32_BE(data, 44);
local.W[12] = MBEDTLS_GET_UINT32_BE(data, 48);
local.W[13] = MBEDTLS_GET_UINT32_BE(data, 52);
local.W[14] = MBEDTLS_GET_UINT32_BE(data, 56);
local.W[15] = MBEDTLS_GET_UINT32_BE(data, 60);
#define S(x,n) (((x) << (n)) | (((x) & 0xFFFFFFFF) >> (32 - (n))))
#define S(x, n) (((x) << (n)) | (((x) & 0xFFFFFFFF) >> (32 - (n))))
#define R(t) \
( \
local.temp = local.W[( (t) - 3 ) & 0x0F] ^ \
local.W[( (t) - 8 ) & 0x0F] ^ \
local.W[( (t) - 14 ) & 0x0F] ^ \
local.W[ (t) & 0x0F], \
( local.W[(t) & 0x0F] = S(local.temp,1) ) \
local.temp = local.W[((t) - 3) & 0x0F] ^ \
local.W[((t) - 8) & 0x0F] ^ \
local.W[((t) - 14) & 0x0F] ^ \
local.W[(t) & 0x0F], \
(local.W[(t) & 0x0F] = S(local.temp, 1)) \
)
#define P(a,b,c,d,e,x) \
#define P(a, b, c, d, e, x) \
do \
{ \
(e) += S((a),5) + F((b),(c),(d)) + K + (x); \
(b) = S((b),30); \
} while( 0 )
(e) += S((a), 5) + F((b), (c), (d)) + K + (x); \
(b) = S((b), 30); \
} while (0)
local.A = ctx->state[0];
local.B = ctx->state[1];
@@ -144,110 +144,110 @@ int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
local.D = ctx->state[3];
local.E = ctx->state[4];
#define F(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define K 0x5A827999
P( local.A, local.B, local.C, local.D, local.E, local.W[0] );
P( local.E, local.A, local.B, local.C, local.D, local.W[1] );
P( local.D, local.E, local.A, local.B, local.C, local.W[2] );
P( local.C, local.D, local.E, local.A, local.B, local.W[3] );
P( local.B, local.C, local.D, local.E, local.A, local.W[4] );
P( local.A, local.B, local.C, local.D, local.E, local.W[5] );
P( local.E, local.A, local.B, local.C, local.D, local.W[6] );
P( local.D, local.E, local.A, local.B, local.C, local.W[7] );
P( local.C, local.D, local.E, local.A, local.B, local.W[8] );
P( local.B, local.C, local.D, local.E, local.A, local.W[9] );
P( local.A, local.B, local.C, local.D, local.E, local.W[10] );
P( local.E, local.A, local.B, local.C, local.D, local.W[11] );
P( local.D, local.E, local.A, local.B, local.C, local.W[12] );
P( local.C, local.D, local.E, local.A, local.B, local.W[13] );
P( local.B, local.C, local.D, local.E, local.A, local.W[14] );
P( local.A, local.B, local.C, local.D, local.E, local.W[15] );
P( local.E, local.A, local.B, local.C, local.D, R(16) );
P( local.D, local.E, local.A, local.B, local.C, R(17) );
P( local.C, local.D, local.E, local.A, local.B, R(18) );
P( local.B, local.C, local.D, local.E, local.A, R(19) );
P(local.A, local.B, local.C, local.D, local.E, local.W[0]);
P(local.E, local.A, local.B, local.C, local.D, local.W[1]);
P(local.D, local.E, local.A, local.B, local.C, local.W[2]);
P(local.C, local.D, local.E, local.A, local.B, local.W[3]);
P(local.B, local.C, local.D, local.E, local.A, local.W[4]);
P(local.A, local.B, local.C, local.D, local.E, local.W[5]);
P(local.E, local.A, local.B, local.C, local.D, local.W[6]);
P(local.D, local.E, local.A, local.B, local.C, local.W[7]);
P(local.C, local.D, local.E, local.A, local.B, local.W[8]);
P(local.B, local.C, local.D, local.E, local.A, local.W[9]);
P(local.A, local.B, local.C, local.D, local.E, local.W[10]);
P(local.E, local.A, local.B, local.C, local.D, local.W[11]);
P(local.D, local.E, local.A, local.B, local.C, local.W[12]);
P(local.C, local.D, local.E, local.A, local.B, local.W[13]);
P(local.B, local.C, local.D, local.E, local.A, local.W[14]);
P(local.A, local.B, local.C, local.D, local.E, local.W[15]);
P(local.E, local.A, local.B, local.C, local.D, R(16));
P(local.D, local.E, local.A, local.B, local.C, R(17));
P(local.C, local.D, local.E, local.A, local.B, R(18));
P(local.B, local.C, local.D, local.E, local.A, R(19));
#undef K
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define K 0x6ED9EBA1
P( local.A, local.B, local.C, local.D, local.E, R(20) );
P( local.E, local.A, local.B, local.C, local.D, R(21) );
P( local.D, local.E, local.A, local.B, local.C, R(22) );
P( local.C, local.D, local.E, local.A, local.B, R(23) );
P( local.B, local.C, local.D, local.E, local.A, R(24) );
P( local.A, local.B, local.C, local.D, local.E, R(25) );
P( local.E, local.A, local.B, local.C, local.D, R(26) );
P( local.D, local.E, local.A, local.B, local.C, R(27) );
P( local.C, local.D, local.E, local.A, local.B, R(28) );
P( local.B, local.C, local.D, local.E, local.A, R(29) );
P( local.A, local.B, local.C, local.D, local.E, R(30) );
P( local.E, local.A, local.B, local.C, local.D, R(31) );
P( local.D, local.E, local.A, local.B, local.C, R(32) );
P( local.C, local.D, local.E, local.A, local.B, R(33) );
P( local.B, local.C, local.D, local.E, local.A, R(34) );
P( local.A, local.B, local.C, local.D, local.E, R(35) );
P( local.E, local.A, local.B, local.C, local.D, R(36) );
P( local.D, local.E, local.A, local.B, local.C, R(37) );
P( local.C, local.D, local.E, local.A, local.B, R(38) );
P( local.B, local.C, local.D, local.E, local.A, R(39) );
P(local.A, local.B, local.C, local.D, local.E, R(20));
P(local.E, local.A, local.B, local.C, local.D, R(21));
P(local.D, local.E, local.A, local.B, local.C, R(22));
P(local.C, local.D, local.E, local.A, local.B, R(23));
P(local.B, local.C, local.D, local.E, local.A, R(24));
P(local.A, local.B, local.C, local.D, local.E, R(25));
P(local.E, local.A, local.B, local.C, local.D, R(26));
P(local.D, local.E, local.A, local.B, local.C, R(27));
P(local.C, local.D, local.E, local.A, local.B, R(28));
P(local.B, local.C, local.D, local.E, local.A, R(29));
P(local.A, local.B, local.C, local.D, local.E, R(30));
P(local.E, local.A, local.B, local.C, local.D, R(31));
P(local.D, local.E, local.A, local.B, local.C, R(32));
P(local.C, local.D, local.E, local.A, local.B, R(33));
P(local.B, local.C, local.D, local.E, local.A, R(34));
P(local.A, local.B, local.C, local.D, local.E, R(35));
P(local.E, local.A, local.B, local.C, local.D, R(36));
P(local.D, local.E, local.A, local.B, local.C, R(37));
P(local.C, local.D, local.E, local.A, local.B, R(38));
P(local.B, local.C, local.D, local.E, local.A, R(39));
#undef K
#undef F
#define F(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
#define F(x, y, z) (((x) & (y)) | ((z) & ((x) | (y))))
#define K 0x8F1BBCDC
P( local.A, local.B, local.C, local.D, local.E, R(40) );
P( local.E, local.A, local.B, local.C, local.D, R(41) );
P( local.D, local.E, local.A, local.B, local.C, R(42) );
P( local.C, local.D, local.E, local.A, local.B, R(43) );
P( local.B, local.C, local.D, local.E, local.A, R(44) );
P( local.A, local.B, local.C, local.D, local.E, R(45) );
P( local.E, local.A, local.B, local.C, local.D, R(46) );
P( local.D, local.E, local.A, local.B, local.C, R(47) );
P( local.C, local.D, local.E, local.A, local.B, R(48) );
P( local.B, local.C, local.D, local.E, local.A, R(49) );
P( local.A, local.B, local.C, local.D, local.E, R(50) );
P( local.E, local.A, local.B, local.C, local.D, R(51) );
P( local.D, local.E, local.A, local.B, local.C, R(52) );
P( local.C, local.D, local.E, local.A, local.B, R(53) );
P( local.B, local.C, local.D, local.E, local.A, R(54) );
P( local.A, local.B, local.C, local.D, local.E, R(55) );
P( local.E, local.A, local.B, local.C, local.D, R(56) );
P( local.D, local.E, local.A, local.B, local.C, R(57) );
P( local.C, local.D, local.E, local.A, local.B, R(58) );
P( local.B, local.C, local.D, local.E, local.A, R(59) );
P(local.A, local.B, local.C, local.D, local.E, R(40));
P(local.E, local.A, local.B, local.C, local.D, R(41));
P(local.D, local.E, local.A, local.B, local.C, R(42));
P(local.C, local.D, local.E, local.A, local.B, R(43));
P(local.B, local.C, local.D, local.E, local.A, R(44));
P(local.A, local.B, local.C, local.D, local.E, R(45));
P(local.E, local.A, local.B, local.C, local.D, R(46));
P(local.D, local.E, local.A, local.B, local.C, R(47));
P(local.C, local.D, local.E, local.A, local.B, R(48));
P(local.B, local.C, local.D, local.E, local.A, R(49));
P(local.A, local.B, local.C, local.D, local.E, R(50));
P(local.E, local.A, local.B, local.C, local.D, R(51));
P(local.D, local.E, local.A, local.B, local.C, R(52));
P(local.C, local.D, local.E, local.A, local.B, R(53));
P(local.B, local.C, local.D, local.E, local.A, R(54));
P(local.A, local.B, local.C, local.D, local.E, R(55));
P(local.E, local.A, local.B, local.C, local.D, R(56));
P(local.D, local.E, local.A, local.B, local.C, R(57));
P(local.C, local.D, local.E, local.A, local.B, R(58));
P(local.B, local.C, local.D, local.E, local.A, R(59));
#undef K
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define K 0xCA62C1D6
P( local.A, local.B, local.C, local.D, local.E, R(60) );
P( local.E, local.A, local.B, local.C, local.D, R(61) );
P( local.D, local.E, local.A, local.B, local.C, R(62) );
P( local.C, local.D, local.E, local.A, local.B, R(63) );
P( local.B, local.C, local.D, local.E, local.A, R(64) );
P( local.A, local.B, local.C, local.D, local.E, R(65) );
P( local.E, local.A, local.B, local.C, local.D, R(66) );
P( local.D, local.E, local.A, local.B, local.C, R(67) );
P( local.C, local.D, local.E, local.A, local.B, R(68) );
P( local.B, local.C, local.D, local.E, local.A, R(69) );
P( local.A, local.B, local.C, local.D, local.E, R(70) );
P( local.E, local.A, local.B, local.C, local.D, R(71) );
P( local.D, local.E, local.A, local.B, local.C, R(72) );
P( local.C, local.D, local.E, local.A, local.B, R(73) );
P( local.B, local.C, local.D, local.E, local.A, R(74) );
P( local.A, local.B, local.C, local.D, local.E, R(75) );
P( local.E, local.A, local.B, local.C, local.D, R(76) );
P( local.D, local.E, local.A, local.B, local.C, R(77) );
P( local.C, local.D, local.E, local.A, local.B, R(78) );
P( local.B, local.C, local.D, local.E, local.A, R(79) );
P(local.A, local.B, local.C, local.D, local.E, R(60));
P(local.E, local.A, local.B, local.C, local.D, R(61));
P(local.D, local.E, local.A, local.B, local.C, R(62));
P(local.C, local.D, local.E, local.A, local.B, R(63));
P(local.B, local.C, local.D, local.E, local.A, R(64));
P(local.A, local.B, local.C, local.D, local.E, R(65));
P(local.E, local.A, local.B, local.C, local.D, R(66));
P(local.D, local.E, local.A, local.B, local.C, R(67));
P(local.C, local.D, local.E, local.A, local.B, R(68));
P(local.B, local.C, local.D, local.E, local.A, R(69));
P(local.A, local.B, local.C, local.D, local.E, R(70));
P(local.E, local.A, local.B, local.C, local.D, R(71));
P(local.D, local.E, local.A, local.B, local.C, R(72));
P(local.C, local.D, local.E, local.A, local.B, R(73));
P(local.B, local.C, local.D, local.E, local.A, R(74));
P(local.A, local.B, local.C, local.D, local.E, R(75));
P(local.E, local.A, local.B, local.C, local.D, R(76));
P(local.D, local.E, local.A, local.B, local.C, R(77));
P(local.C, local.D, local.E, local.A, local.B, R(78));
P(local.B, local.C, local.D, local.E, local.A, R(79));
#undef K
#undef F
@@ -259,16 +259,16 @@ int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
ctx->state[4] += local.E;
/* Zeroise buffers and variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
mbedtls_platform_zeroize(&local, sizeof(local));
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] )
void mbedtls_sha1_process(mbedtls_sha1_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_sha1_process( ctx, data );
mbedtls_internal_sha1_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_SHA1_PROCESS_ALT */
@@ -276,19 +276,20 @@ void mbedtls_sha1_process( mbedtls_sha1_context *ctx,
/*
* SHA-1 process buffer
*/
int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_sha1_update_ret(mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
uint32_t left;
SHA1_VALIDATE_RET( ctx != NULL );
SHA1_VALIDATE_RET( ilen == 0 || input != NULL );
SHA1_VALIDATE_RET(ctx != NULL);
SHA1_VALIDATE_RET(ilen == 0 || input != NULL);
if( ilen == 0 )
return( 0 );
if (ilen == 0) {
return 0;
}
left = ctx->total[0] & 0x3F;
fill = 64 - left;
@@ -296,57 +297,59 @@ int mbedtls_sha1_update_ret( mbedtls_sha1_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 (left && ilen >= fill) {
memcpy((void *) (ctx->buffer + left), input, fill);
if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha1_process(ctx, ctx->buffer)) != 0) {
return ret;
}
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
if( ( ret = mbedtls_internal_sha1_process( ctx, input ) ) != 0 )
return( ret );
while (ilen >= 64) {
if ((ret = mbedtls_internal_sha1_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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_update( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen )
void mbedtls_sha1_update(mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_sha1_update_ret( ctx, input, ilen );
mbedtls_sha1_update_ret(ctx, input, ilen);
}
#endif
/*
* SHA-1 final digest
*/
int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
unsigned char output[20] )
int mbedtls_sha1_finish_ret(mbedtls_sha1_context *ctx,
unsigned char output[20])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint32_t used;
uint32_t high, low;
SHA1_VALIDATE_RET( ctx != NULL );
SHA1_VALIDATE_RET( (unsigned char *)output != NULL );
SHA1_VALIDATE_RET(ctx != NULL);
SHA1_VALIDATE_RET((unsigned char *) output != NULL);
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
@@ -355,52 +358,51 @@ int mbedtls_sha1_finish_ret( mbedtls_sha1_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_sha1_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha1_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_BE( high, ctx->buffer, 56 );
MBEDTLS_PUT_UINT32_BE( low, ctx->buffer, 60 );
MBEDTLS_PUT_UINT32_BE(high, ctx->buffer, 56);
MBEDTLS_PUT_UINT32_BE(low, ctx->buffer, 60);
if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha1_process(ctx, ctx->buffer)) != 0) {
return ret;
}
/*
* Output final state
*/
MBEDTLS_PUT_UINT32_BE( ctx->state[0], output, 0 );
MBEDTLS_PUT_UINT32_BE( ctx->state[1], output, 4 );
MBEDTLS_PUT_UINT32_BE( ctx->state[2], output, 8 );
MBEDTLS_PUT_UINT32_BE( ctx->state[3], output, 12 );
MBEDTLS_PUT_UINT32_BE( ctx->state[4], output, 16 );
MBEDTLS_PUT_UINT32_BE(ctx->state[0], output, 0);
MBEDTLS_PUT_UINT32_BE(ctx->state[1], output, 4);
MBEDTLS_PUT_UINT32_BE(ctx->state[2], output, 8);
MBEDTLS_PUT_UINT32_BE(ctx->state[3], output, 12);
MBEDTLS_PUT_UINT32_BE(ctx->state[4], output, 16);
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,
unsigned char output[20] )
void mbedtls_sha1_finish(mbedtls_sha1_context *ctx,
unsigned char output[20])
{
mbedtls_sha1_finish_ret( ctx, output );
mbedtls_sha1_finish_ret(ctx, output);
}
#endif
@@ -409,39 +411,42 @@ void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,
/*
* output = SHA-1( input buffer )
*/
int mbedtls_sha1_ret( const unsigned char *input,
size_t ilen,
unsigned char output[20] )
int mbedtls_sha1_ret(const unsigned char *input,
size_t ilen,
unsigned char output[20])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_sha1_context ctx;
SHA1_VALIDATE_RET( ilen == 0 || input != NULL );
SHA1_VALIDATE_RET( (unsigned char *)output != NULL );
SHA1_VALIDATE_RET(ilen == 0 || input != NULL);
SHA1_VALIDATE_RET((unsigned char *) output != NULL);
mbedtls_sha1_init( &ctx );
mbedtls_sha1_init(&ctx);
if( ( ret = mbedtls_sha1_starts_ret( &ctx ) ) != 0 )
if ((ret = mbedtls_sha1_starts_ret(&ctx)) != 0) {
goto exit;
}
if( ( ret = mbedtls_sha1_update_ret( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_sha1_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_sha1_finish_ret( &ctx, output ) ) != 0 )
if ((ret = mbedtls_sha1_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_sha1_free( &ctx );
mbedtls_sha1_free(&ctx);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1( const unsigned char *input,
size_t ilen,
unsigned char output[20] )
void mbedtls_sha1(const unsigned char *input,
size_t ilen,
unsigned char output[20])
{
mbedtls_sha1_ret( input, ilen, output );
mbedtls_sha1_ret(input, ilen, output);
}
#endif
@@ -474,71 +479,73 @@ static const unsigned char sha1_test_sum[3][20] =
/*
* Checkup routine
*/
int mbedtls_sha1_self_test( int verbose )
int mbedtls_sha1_self_test(int verbose)
{
int i, j, buflen, ret = 0;
unsigned char buf[1024];
unsigned char sha1sum[20];
mbedtls_sha1_context ctx;
mbedtls_sha1_init( &ctx );
mbedtls_sha1_init(&ctx);
/*
* SHA-1
*/
for( i = 0; i < 3; i++ )
{
if( verbose != 0 )
mbedtls_printf( " SHA-1 test #%d: ", i + 1 );
for (i = 0; i < 3; i++) {
if (verbose != 0) {
mbedtls_printf(" SHA-1 test #%d: ", i + 1);
}
if( ( ret = mbedtls_sha1_starts_ret( &ctx ) ) != 0 )
if ((ret = mbedtls_sha1_starts_ret(&ctx)) != 0) {
goto fail;
}
if( i == 2 )
{
memset( buf, 'a', buflen = 1000 );
if (i == 2) {
memset(buf, 'a', buflen = 1000);
for( j = 0; j < 1000; j++ )
{
ret = mbedtls_sha1_update_ret( &ctx, buf, buflen );
if( ret != 0 )
for (j = 0; j < 1000; j++) {
ret = mbedtls_sha1_update_ret(&ctx, buf, buflen);
if (ret != 0) {
goto fail;
}
}
} else {
ret = mbedtls_sha1_update_ret(&ctx, sha1_test_buf[i],
sha1_test_buflen[i]);
if (ret != 0) {
goto fail;
}
}
else
{
ret = mbedtls_sha1_update_ret( &ctx, sha1_test_buf[i],
sha1_test_buflen[i] );
if( ret != 0 )
goto fail;
if ((ret = mbedtls_sha1_finish_ret(&ctx, sha1sum)) != 0) {
goto fail;
}
if( ( ret = mbedtls_sha1_finish_ret( &ctx, sha1sum ) ) != 0 )
goto fail;
if( memcmp( sha1sum, sha1_test_sum[i], 20 ) != 0 )
{
if (memcmp(sha1sum, sha1_test_sum[i], 20) != 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");
}
goto exit;
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
if (verbose != 0) {
mbedtls_printf("failed\n");
}
exit:
mbedtls_sha1_free( &ctx );
mbedtls_sha1_free(&ctx);
return( ret );
return ret;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@@ -35,31 +35,32 @@
#include "mbedtls/platform.h"
#define SHA256_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA256_BAD_INPUT_DATA )
#define SHA256_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond )
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_SHA256_BAD_INPUT_DATA)
#define SHA256_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE(cond)
#if !defined(MBEDTLS_SHA256_ALT)
void mbedtls_sha256_init( mbedtls_sha256_context *ctx )
void mbedtls_sha256_init(mbedtls_sha256_context *ctx)
{
SHA256_VALIDATE( ctx != NULL );
SHA256_VALIDATE(ctx != NULL);
memset( ctx, 0, sizeof( mbedtls_sha256_context ) );
memset(ctx, 0, sizeof(mbedtls_sha256_context));
}
void mbedtls_sha256_free( mbedtls_sha256_context *ctx )
void mbedtls_sha256_free(mbedtls_sha256_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_sha256_context));
}
void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src )
void mbedtls_sha256_clone(mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src)
{
SHA256_VALIDATE( dst != NULL );
SHA256_VALIDATE( src != NULL );
SHA256_VALIDATE(dst != NULL);
SHA256_VALIDATE(src != NULL);
*dst = *src;
}
@@ -67,16 +68,15 @@ void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
/*
* SHA-256 context setup
*/
int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 )
int mbedtls_sha256_starts_ret(mbedtls_sha256_context *ctx, int is224)
{
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 );
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET(is224 == 0 || is224 == 1);
ctx->total[0] = 0;
ctx->total[1] = 0;
if( is224 == 0 )
{
if (is224 == 0) {
/* SHA-256 */
ctx->state[0] = 0x6A09E667;
ctx->state[1] = 0xBB67AE85;
@@ -86,9 +86,7 @@ int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 )
ctx->state[5] = 0x9B05688C;
ctx->state[6] = 0x1F83D9AB;
ctx->state[7] = 0x5BE0CD19;
}
else
{
} else {
/* SHA-224 */
ctx->state[0] = 0xC1059ED8;
ctx->state[1] = 0x367CD507;
@@ -102,14 +100,14 @@ int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 )
ctx->is224 = is224;
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
int is224 )
void mbedtls_sha256_starts(mbedtls_sha256_context *ctx,
int is224)
{
mbedtls_sha256_starts_ret( ctx, is224 );
mbedtls_sha256_starts_ret(ctx, is224);
}
#endif
@@ -134,17 +132,17 @@ static const uint32_t K[] =
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
};
#define SHR(x,n) (((x) & 0xFFFFFFFF) >> (n))
#define ROTR(x,n) (SHR(x,n) | ((x) << (32 - (n))))
#define SHR(x, n) (((x) & 0xFFFFFFFF) >> (n))
#define ROTR(x, n) (SHR(x, n) | ((x) << (32 - (n))))
#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3))
#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10))
#define S0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))
#define S1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))
#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22))
#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25))
#define S2(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define S3(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
#define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define F0(x, y, z) (((x) & (y)) | ((z) & ((x) | (y))))
#define F1(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define R(t) \
( \
@@ -152,41 +150,41 @@ static const uint32_t K[] =
S0(local.W[(t) - 15]) + local.W[(t) - 16] \
)
#define P(a,b,c,d,e,f,g,h,x,K) \
#define P(a, b, c, d, e, f, g, h, x, K) \
do \
{ \
local.temp1 = (h) + S3(e) + F1((e),(f),(g)) + (K) + (x); \
local.temp2 = S2(a) + F0((a),(b),(c)); \
local.temp1 = (h) + S3(e) + F1((e), (f), (g)) + (K) + (x); \
local.temp2 = S2(a) + F0((a), (b), (c)); \
(d) += local.temp1; (h) = local.temp1 + local.temp2; \
} while( 0 )
} while (0)
int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] )
int mbedtls_internal_sha256_process(mbedtls_sha256_context *ctx,
const unsigned char data[64])
{
struct
{
struct {
uint32_t temp1, temp2, W[64];
uint32_t A[8];
} local;
unsigned int i;
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( (const unsigned char *)data != NULL );
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET((const unsigned char *) data != NULL);
for( i = 0; i < 8; i++ )
for (i = 0; i < 8; i++) {
local.A[i] = ctx->state[i];
}
#if defined(MBEDTLS_SHA256_SMALLER)
for( i = 0; i < 64; i++ )
{
if( i < 16 )
local.W[i] = MBEDTLS_GET_UINT32_BE( data, 4 * i );
else
R( i );
for (i = 0; i < 64; i++) {
if (i < 16) {
local.W[i] = MBEDTLS_GET_UINT32_BE(data, 4 * i);
} else {
R(i);
}
P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i] );
P(local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i]);
local.temp1 = local.A[7]; local.A[7] = local.A[6];
local.A[6] = local.A[5]; local.A[5] = local.A[4];
@@ -195,64 +193,64 @@ int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
local.A[0] = local.temp1;
}
#else /* MBEDTLS_SHA256_SMALLER */
for( i = 0; i < 16; i++ )
local.W[i] = MBEDTLS_GET_UINT32_BE( data, 4 * i );
for( i = 0; i < 16; i += 8 )
{
P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i+0], K[i+0] );
P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3],
local.A[4], local.A[5], local.A[6], local.W[i+1], K[i+1] );
P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2],
local.A[3], local.A[4], local.A[5], local.W[i+2], K[i+2] );
P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1],
local.A[2], local.A[3], local.A[4], local.W[i+3], K[i+3] );
P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0],
local.A[1], local.A[2], local.A[3], local.W[i+4], K[i+4] );
P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7],
local.A[0], local.A[1], local.A[2], local.W[i+5], K[i+5] );
P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6],
local.A[7], local.A[0], local.A[1], local.W[i+6], K[i+6] );
P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5],
local.A[6], local.A[7], local.A[0], local.W[i+7], K[i+7] );
for (i = 0; i < 16; i++) {
local.W[i] = MBEDTLS_GET_UINT32_BE(data, 4 * i);
}
for( i = 16; i < 64; i += 8 )
{
P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], R(i+0), K[i+0] );
P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3],
local.A[4], local.A[5], local.A[6], R(i+1), K[i+1] );
P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2],
local.A[3], local.A[4], local.A[5], R(i+2), K[i+2] );
P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1],
local.A[2], local.A[3], local.A[4], R(i+3), K[i+3] );
P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0],
local.A[1], local.A[2], local.A[3], R(i+4), K[i+4] );
P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7],
local.A[0], local.A[1], local.A[2], R(i+5), K[i+5] );
P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6],
local.A[7], local.A[0], local.A[1], R(i+6), K[i+6] );
P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5],
local.A[6], local.A[7], local.A[0], R(i+7), K[i+7] );
for (i = 0; i < 16; i += 8) {
P(local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i+0], K[i+0]);
P(local.A[7], local.A[0], local.A[1], local.A[2], local.A[3],
local.A[4], local.A[5], local.A[6], local.W[i+1], K[i+1]);
P(local.A[6], local.A[7], local.A[0], local.A[1], local.A[2],
local.A[3], local.A[4], local.A[5], local.W[i+2], K[i+2]);
P(local.A[5], local.A[6], local.A[7], local.A[0], local.A[1],
local.A[2], local.A[3], local.A[4], local.W[i+3], K[i+3]);
P(local.A[4], local.A[5], local.A[6], local.A[7], local.A[0],
local.A[1], local.A[2], local.A[3], local.W[i+4], K[i+4]);
P(local.A[3], local.A[4], local.A[5], local.A[6], local.A[7],
local.A[0], local.A[1], local.A[2], local.W[i+5], K[i+5]);
P(local.A[2], local.A[3], local.A[4], local.A[5], local.A[6],
local.A[7], local.A[0], local.A[1], local.W[i+6], K[i+6]);
P(local.A[1], local.A[2], local.A[3], local.A[4], local.A[5],
local.A[6], local.A[7], local.A[0], local.W[i+7], K[i+7]);
}
for (i = 16; i < 64; i += 8) {
P(local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], R(i+0), K[i+0]);
P(local.A[7], local.A[0], local.A[1], local.A[2], local.A[3],
local.A[4], local.A[5], local.A[6], R(i+1), K[i+1]);
P(local.A[6], local.A[7], local.A[0], local.A[1], local.A[2],
local.A[3], local.A[4], local.A[5], R(i+2), K[i+2]);
P(local.A[5], local.A[6], local.A[7], local.A[0], local.A[1],
local.A[2], local.A[3], local.A[4], R(i+3), K[i+3]);
P(local.A[4], local.A[5], local.A[6], local.A[7], local.A[0],
local.A[1], local.A[2], local.A[3], R(i+4), K[i+4]);
P(local.A[3], local.A[4], local.A[5], local.A[6], local.A[7],
local.A[0], local.A[1], local.A[2], R(i+5), K[i+5]);
P(local.A[2], local.A[3], local.A[4], local.A[5], local.A[6],
local.A[7], local.A[0], local.A[1], R(i+6), K[i+6]);
P(local.A[1], local.A[2], local.A[3], local.A[4], local.A[5],
local.A[6], local.A[7], local.A[0], R(i+7), K[i+7]);
}
#endif /* MBEDTLS_SHA256_SMALLER */
for( i = 0; i < 8; i++ )
for (i = 0; i < 8; i++) {
ctx->state[i] += local.A[i];
}
/* Zeroise buffers and variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
mbedtls_platform_zeroize(&local, sizeof(local));
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] )
void mbedtls_sha256_process(mbedtls_sha256_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_sha256_process( ctx, data );
mbedtls_internal_sha256_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_SHA256_PROCESS_ALT */
@@ -260,19 +258,20 @@ void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
/*
* SHA-256 process buffer
*/
int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_sha256_update_ret(mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
uint32_t left;
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( ilen == 0 || input != NULL );
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET(ilen == 0 || input != NULL);
if( ilen == 0 )
return( 0 );
if (ilen == 0) {
return 0;
}
left = ctx->total[0] & 0x3F;
fill = 64 - left;
@@ -280,57 +279,59 @@ int mbedtls_sha256_update_ret( mbedtls_sha256_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 (left && ilen >= fill) {
memcpy((void *) (ctx->buffer + left), input, fill);
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha256_process(ctx, ctx->buffer)) != 0) {
return ret;
}
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
if( ( ret = mbedtls_internal_sha256_process( ctx, input ) ) != 0 )
return( ret );
while (ilen >= 64) {
if ((ret = mbedtls_internal_sha256_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;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_update( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen )
void mbedtls_sha256_update(mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_sha256_update_ret( ctx, input, ilen );
mbedtls_sha256_update_ret(ctx, input, ilen);
}
#endif
/*
* SHA-256 final digest
*/
int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
unsigned char output[32] )
int mbedtls_sha256_finish_ret(mbedtls_sha256_context *ctx,
unsigned char output[32])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint32_t used;
uint32_t high, low;
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( (unsigned char *)output != NULL );
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET((unsigned char *) output != NULL);
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
@@ -339,57 +340,57 @@ int mbedtls_sha256_finish_ret( mbedtls_sha256_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_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha256_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_BE( high, ctx->buffer, 56 );
MBEDTLS_PUT_UINT32_BE( low, ctx->buffer, 60 );
MBEDTLS_PUT_UINT32_BE(high, ctx->buffer, 56);
MBEDTLS_PUT_UINT32_BE(low, ctx->buffer, 60);
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha256_process(ctx, ctx->buffer)) != 0) {
return ret;
}
/*
* Output final state
*/
MBEDTLS_PUT_UINT32_BE( ctx->state[0], output, 0 );
MBEDTLS_PUT_UINT32_BE( ctx->state[1], output, 4 );
MBEDTLS_PUT_UINT32_BE( ctx->state[2], output, 8 );
MBEDTLS_PUT_UINT32_BE( ctx->state[3], output, 12 );
MBEDTLS_PUT_UINT32_BE( ctx->state[4], output, 16 );
MBEDTLS_PUT_UINT32_BE( ctx->state[5], output, 20 );
MBEDTLS_PUT_UINT32_BE( ctx->state[6], output, 24 );
MBEDTLS_PUT_UINT32_BE(ctx->state[0], output, 0);
MBEDTLS_PUT_UINT32_BE(ctx->state[1], output, 4);
MBEDTLS_PUT_UINT32_BE(ctx->state[2], output, 8);
MBEDTLS_PUT_UINT32_BE(ctx->state[3], output, 12);
MBEDTLS_PUT_UINT32_BE(ctx->state[4], output, 16);
MBEDTLS_PUT_UINT32_BE(ctx->state[5], output, 20);
MBEDTLS_PUT_UINT32_BE(ctx->state[6], output, 24);
if( ctx->is224 == 0 )
MBEDTLS_PUT_UINT32_BE( ctx->state[7], output, 28 );
if (ctx->is224 == 0) {
MBEDTLS_PUT_UINT32_BE(ctx->state[7], output, 28);
}
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
unsigned char output[32] )
void mbedtls_sha256_finish(mbedtls_sha256_context *ctx,
unsigned char output[32])
{
mbedtls_sha256_finish_ret( ctx, output );
mbedtls_sha256_finish_ret(ctx, output);
}
#endif
@@ -398,42 +399,45 @@ void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
/*
* output = SHA-256( input buffer )
*/
int mbedtls_sha256_ret( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 )
int mbedtls_sha256_ret(const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_sha256_context ctx;
SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 );
SHA256_VALIDATE_RET( ilen == 0 || input != NULL );
SHA256_VALIDATE_RET( (unsigned char *)output != NULL );
SHA256_VALIDATE_RET(is224 == 0 || is224 == 1);
SHA256_VALIDATE_RET(ilen == 0 || input != NULL);
SHA256_VALIDATE_RET((unsigned char *) output != NULL);
mbedtls_sha256_init( &ctx );
mbedtls_sha256_init(&ctx);
if( ( ret = mbedtls_sha256_starts_ret( &ctx, is224 ) ) != 0 )
if ((ret = mbedtls_sha256_starts_ret(&ctx, is224)) != 0) {
goto exit;
}
if( ( ret = mbedtls_sha256_update_ret( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_sha256_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_sha256_finish_ret( &ctx, output ) ) != 0 )
if ((ret = mbedtls_sha256_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_sha256_free( &ctx );
mbedtls_sha256_free(&ctx);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 )
void mbedtls_sha256(const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224)
{
mbedtls_sha256_ret( input, ilen, output, is224 );
mbedtls_sha256_ret(input, ilen, output, is224);
}
#endif
@@ -491,83 +495,85 @@ static const unsigned char sha256_test_sum[6][32] =
/*
* Checkup routine
*/
int mbedtls_sha256_self_test( int verbose )
int mbedtls_sha256_self_test(int verbose)
{
int i, j, k, buflen, ret = 0;
unsigned char *buf;
unsigned char sha256sum[32];
mbedtls_sha256_context ctx;
buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
if( NULL == buf )
{
if( verbose != 0 )
mbedtls_printf( "Buffer allocation failed\n" );
buf = mbedtls_calloc(1024, sizeof(unsigned char));
if (NULL == buf) {
if (verbose != 0) {
mbedtls_printf("Buffer allocation failed\n");
}
return( 1 );
return 1;
}
mbedtls_sha256_init( &ctx );
mbedtls_sha256_init(&ctx);
for( i = 0; i < 6; i++ )
{
for (i = 0; i < 6; i++) {
j = i % 3;
k = i < 3;
if( verbose != 0 )
mbedtls_printf( " SHA-%d test #%d: ", 256 - k * 32, j + 1 );
if (verbose != 0) {
mbedtls_printf(" SHA-%d test #%d: ", 256 - k * 32, j + 1);
}
if( ( ret = mbedtls_sha256_starts_ret( &ctx, k ) ) != 0 )
if ((ret = mbedtls_sha256_starts_ret(&ctx, k)) != 0) {
goto fail;
}
if( j == 2 )
{
memset( buf, 'a', buflen = 1000 );
if (j == 2) {
memset(buf, 'a', buflen = 1000);
for( j = 0; j < 1000; j++ )
{
ret = mbedtls_sha256_update_ret( &ctx, buf, buflen );
if( ret != 0 )
for (j = 0; j < 1000; j++) {
ret = mbedtls_sha256_update_ret(&ctx, buf, buflen);
if (ret != 0) {
goto fail;
}
}
}
else
{
ret = mbedtls_sha256_update_ret( &ctx, sha256_test_buf[j],
sha256_test_buflen[j] );
if( ret != 0 )
goto fail;
} else {
ret = mbedtls_sha256_update_ret(&ctx, sha256_test_buf[j],
sha256_test_buflen[j]);
if (ret != 0) {
goto fail;
}
}
if( ( ret = mbedtls_sha256_finish_ret( &ctx, sha256sum ) ) != 0 )
if ((ret = mbedtls_sha256_finish_ret(&ctx, sha256sum)) != 0) {
goto fail;
}
if( memcmp( sha256sum, sha256_test_sum[i], 32 - k * 4 ) != 0 )
{
if (memcmp(sha256sum, sha256_test_sum[i], 32 - k * 4) != 0) {
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
goto exit;
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
if (verbose != 0) {
mbedtls_printf("failed\n");
}
exit:
mbedtls_sha256_free( &ctx );
mbedtls_free( buf );
mbedtls_sha256_free(&ctx);
mbedtls_free(buf);
return( ret );
return ret;
}
#endif /* MBEDTLS_SELF_TEST */

View File

@@ -41,13 +41,13 @@
#include "mbedtls/platform.h"
#define SHA512_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA512_BAD_INPUT_DATA )
#define SHA512_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond )
MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_SHA512_BAD_INPUT_DATA)
#define SHA512_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE(cond)
#if !defined(MBEDTLS_SHA512_ALT)
#if defined(MBEDTLS_SHA512_SMALLER)
static void sha512_put_uint64_be( uint64_t n, unsigned char *b, uint8_t i )
static void sha512_put_uint64_be(uint64_t n, unsigned char *b, uint8_t i)
{
MBEDTLS_PUT_UINT64_BE(n, b, i);
}
@@ -55,26 +55,27 @@ static void sha512_put_uint64_be( uint64_t n, unsigned char *b, uint8_t i )
#define sha512_put_uint64_be MBEDTLS_PUT_UINT64_BE
#endif /* MBEDTLS_SHA512_SMALLER */
void mbedtls_sha512_init( mbedtls_sha512_context *ctx )
void mbedtls_sha512_init(mbedtls_sha512_context *ctx)
{
SHA512_VALIDATE( ctx != NULL );
SHA512_VALIDATE(ctx != NULL);
memset( ctx, 0, sizeof( mbedtls_sha512_context ) );
memset(ctx, 0, sizeof(mbedtls_sha512_context));
}
void mbedtls_sha512_free( mbedtls_sha512_context *ctx )
void mbedtls_sha512_free(mbedtls_sha512_context *ctx)
{
if( ctx == NULL )
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) );
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_sha512_context));
}
void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
const mbedtls_sha512_context *src )
void mbedtls_sha512_clone(mbedtls_sha512_context *dst,
const mbedtls_sha512_context *src)
{
SHA512_VALIDATE( dst != NULL );
SHA512_VALIDATE( src != NULL );
SHA512_VALIDATE(dst != NULL);
SHA512_VALIDATE(src != NULL);
*dst = *src;
}
@@ -82,20 +83,19 @@ void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
/*
* SHA-512 context setup
*/
int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 )
int mbedtls_sha512_starts_ret(mbedtls_sha512_context *ctx, int is384)
{
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET(ctx != NULL);
#if !defined(MBEDTLS_SHA512_NO_SHA384)
SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 );
SHA512_VALIDATE_RET(is384 == 0 || is384 == 1);
#else
SHA512_VALIDATE_RET( is384 == 0 );
SHA512_VALIDATE_RET(is384 == 0);
#endif
ctx->total[0] = 0;
ctx->total[1] = 0;
if( is384 == 0 )
{
if (is384 == 0) {
/* SHA-512 */
ctx->state[0] = UL64(0x6A09E667F3BCC908);
ctx->state[1] = UL64(0xBB67AE8584CAA73B);
@@ -105,11 +105,9 @@ int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 )
ctx->state[5] = UL64(0x9B05688C2B3E6C1F);
ctx->state[6] = UL64(0x1F83D9ABFB41BD6B);
ctx->state[7] = UL64(0x5BE0CD19137E2179);
}
else
{
} else {
#if defined(MBEDTLS_SHA512_NO_SHA384)
return( MBEDTLS_ERR_SHA512_BAD_INPUT_DATA );
return MBEDTLS_ERR_SHA512_BAD_INPUT_DATA;
#else
/* SHA-384 */
ctx->state[0] = UL64(0xCBBB9D5DC1059ED8);
@@ -127,14 +125,14 @@ int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 )
ctx->is384 = is384;
#endif
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_starts( mbedtls_sha512_context *ctx,
int is384 )
void mbedtls_sha512_starts(mbedtls_sha512_context *ctx,
int is384)
{
mbedtls_sha512_starts_ret( ctx, is384 );
mbedtls_sha512_starts_ret(ctx, is384);
}
#endif
@@ -187,57 +185,53 @@ static const uint64_t K[80] =
UL64(0x5FCB6FAB3AD6FAEC), UL64(0x6C44198C4A475817)
};
int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
const unsigned char data[128] )
int mbedtls_internal_sha512_process(mbedtls_sha512_context *ctx,
const unsigned char data[128])
{
int i;
struct
{
struct {
uint64_t temp1, temp2, W[80];
uint64_t A[8];
} local;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( (const unsigned char *)data != NULL );
SHA512_VALIDATE_RET(ctx != NULL);
SHA512_VALIDATE_RET((const unsigned char *) data != NULL);
#define SHR(x,n) ((x) >> (n))
#define ROTR(x,n) (SHR((x),(n)) | ((x) << (64 - (n))))
#define SHR(x, n) ((x) >> (n))
#define ROTR(x, n) (SHR((x), (n)) | ((x) << (64 - (n))))
#define S0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7))
#define S1(x) (ROTR(x,19) ^ ROTR(x,61) ^ SHR(x, 6))
#define S1(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHR(x, 6))
#define S2(x) (ROTR(x,28) ^ ROTR(x,34) ^ ROTR(x,39))
#define S3(x) (ROTR(x,14) ^ ROTR(x,18) ^ ROTR(x,41))
#define S2(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39))
#define S3(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41))
#define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
#define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define F0(x, y, z) (((x) & (y)) | ((z) & ((x) | (y))))
#define F1(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define P(a,b,c,d,e,f,g,h,x,K) \
#define P(a, b, c, d, e, f, g, h, x, K) \
do \
{ \
local.temp1 = (h) + S3(e) + F1((e),(f),(g)) + (K) + (x); \
local.temp2 = S2(a) + F0((a),(b),(c)); \
local.temp1 = (h) + S3(e) + F1((e), (f), (g)) + (K) + (x); \
local.temp2 = S2(a) + F0((a), (b), (c)); \
(d) += local.temp1; (h) = local.temp1 + local.temp2; \
} while( 0 )
} while (0)
for( i = 0; i < 8; i++ )
for (i = 0; i < 8; i++) {
local.A[i] = ctx->state[i];
}
#if defined(MBEDTLS_SHA512_SMALLER)
for( i = 0; i < 80; i++ )
{
if( i < 16 )
{
local.W[i] = MBEDTLS_GET_UINT64_BE( data, i << 3 );
}
else
{
for (i = 0; i < 80; i++) {
if (i < 16) {
local.W[i] = MBEDTLS_GET_UINT64_BE(data, i << 3);
} else {
local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] +
S0(local.W[i - 15]) + local.W[i - 16];
S0(local.W[i - 15]) + local.W[i - 16];
}
P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i] );
P(local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i]);
local.temp1 = local.A[7]; local.A[7] = local.A[6];
local.A[6] = local.A[5]; local.A[5] = local.A[4];
@@ -246,54 +240,51 @@ int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
local.A[0] = local.temp1;
}
#else /* MBEDTLS_SHA512_SMALLER */
for( i = 0; i < 16; i++ )
{
local.W[i] = MBEDTLS_GET_UINT64_BE( data, i << 3 );
for (i = 0; i < 16; i++) {
local.W[i] = MBEDTLS_GET_UINT64_BE(data, i << 3);
}
for( ; i < 80; i++ )
{
for (; i < 80; i++) {
local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] +
S0(local.W[i - 15]) + local.W[i - 16];
S0(local.W[i - 15]) + local.W[i - 16];
}
i = 0;
do
{
P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i] ); i++;
P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3],
local.A[4], local.A[5], local.A[6], local.W[i], K[i] ); i++;
P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2],
local.A[3], local.A[4], local.A[5], local.W[i], K[i] ); i++;
P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1],
local.A[2], local.A[3], local.A[4], local.W[i], K[i] ); i++;
P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0],
local.A[1], local.A[2], local.A[3], local.W[i], K[i] ); i++;
P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7],
local.A[0], local.A[1], local.A[2], local.W[i], K[i] ); i++;
P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6],
local.A[7], local.A[0], local.A[1], local.W[i], K[i] ); i++;
P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5],
local.A[6], local.A[7], local.A[0], local.W[i], K[i] ); i++;
}
while( i < 80 );
do {
P(local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i]); i++;
P(local.A[7], local.A[0], local.A[1], local.A[2], local.A[3],
local.A[4], local.A[5], local.A[6], local.W[i], K[i]); i++;
P(local.A[6], local.A[7], local.A[0], local.A[1], local.A[2],
local.A[3], local.A[4], local.A[5], local.W[i], K[i]); i++;
P(local.A[5], local.A[6], local.A[7], local.A[0], local.A[1],
local.A[2], local.A[3], local.A[4], local.W[i], K[i]); i++;
P(local.A[4], local.A[5], local.A[6], local.A[7], local.A[0],
local.A[1], local.A[2], local.A[3], local.W[i], K[i]); i++;
P(local.A[3], local.A[4], local.A[5], local.A[6], local.A[7],
local.A[0], local.A[1], local.A[2], local.W[i], K[i]); i++;
P(local.A[2], local.A[3], local.A[4], local.A[5], local.A[6],
local.A[7], local.A[0], local.A[1], local.W[i], K[i]); i++;
P(local.A[1], local.A[2], local.A[3], local.A[4], local.A[5],
local.A[6], local.A[7], local.A[0], local.W[i], K[i]); i++;
} while (i < 80);
#endif /* MBEDTLS_SHA512_SMALLER */
for( i = 0; i < 8; i++ )
for (i = 0; i < 8; i++) {
ctx->state[i] += local.A[i];
}
/* Zeroise buffers and variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
mbedtls_platform_zeroize(&local, sizeof(local));
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_process( mbedtls_sha512_context *ctx,
const unsigned char data[128] )
void mbedtls_sha512_process(mbedtls_sha512_context *ctx,
const unsigned char data[128])
{
mbedtls_internal_sha512_process( ctx, data );
mbedtls_internal_sha512_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_SHA512_PROCESS_ALT */
@@ -301,76 +292,79 @@ void mbedtls_sha512_process( mbedtls_sha512_context *ctx,
/*
* SHA-512 process buffer
*/
int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen )
int mbedtls_sha512_update_ret(mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
unsigned int left;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( ilen == 0 || input != NULL );
SHA512_VALIDATE_RET(ctx != NULL);
SHA512_VALIDATE_RET(ilen == 0 || input != NULL);
if( ilen == 0 )
return( 0 );
if (ilen == 0) {
return 0;
}
left = (unsigned int) (ctx->total[0] & 0x7F);
fill = 128 - left;
ctx->total[0] += (uint64_t) ilen;
if( ctx->total[0] < (uint64_t) ilen )
if (ctx->total[0] < (uint64_t) ilen) {
ctx->total[1]++;
}
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left), input, fill );
if (left && ilen >= fill) {
memcpy((void *) (ctx->buffer + left), input, fill);
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha512_process(ctx, ctx->buffer)) != 0) {
return ret;
}
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 128 )
{
if( ( ret = mbedtls_internal_sha512_process( ctx, input ) ) != 0 )
return( ret );
while (ilen >= 128) {
if ((ret = mbedtls_internal_sha512_process(ctx, input)) != 0) {
return ret;
}
input += 128;
ilen -= 128;
}
if( ilen > 0 )
memcpy( (void *) (ctx->buffer + left), input, ilen );
if (ilen > 0) {
memcpy((void *) (ctx->buffer + left), input, ilen);
}
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_update( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen )
void mbedtls_sha512_update(mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_sha512_update_ret( ctx, input, ilen );
mbedtls_sha512_update_ret(ctx, input, ilen);
}
#endif
/*
* SHA-512 final digest
*/
int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
unsigned char output[64] )
int mbedtls_sha512_finish_ret(mbedtls_sha512_context *ctx,
unsigned char output[64])
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned used;
uint64_t high, low;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( (unsigned char *)output != NULL );
SHA512_VALIDATE_RET(ctx != NULL);
SHA512_VALIDATE_RET((unsigned char *) output != NULL);
/*
* Add padding: 0x80 then 0x00 until 16 bytes remain for the length
@@ -379,63 +373,61 @@ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
ctx->buffer[used++] = 0x80;
if( used <= 112 )
{
if (used <= 112) {
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 112 - used );
}
else
{
memset(ctx->buffer + used, 0, 112 - used);
} else {
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 128 - used );
memset(ctx->buffer + used, 0, 128 - used);
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha512_process(ctx, ctx->buffer)) != 0) {
return ret;
}
memset( ctx->buffer, 0, 112 );
memset(ctx->buffer, 0, 112);
}
/*
* Add message length
*/
high = ( ctx->total[0] >> 61 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
high = (ctx->total[0] >> 61)
| (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
sha512_put_uint64_be( high, ctx->buffer, 112 );
sha512_put_uint64_be( low, ctx->buffer, 120 );
sha512_put_uint64_be(high, ctx->buffer, 112);
sha512_put_uint64_be(low, ctx->buffer, 120);
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if ((ret = mbedtls_internal_sha512_process(ctx, ctx->buffer)) != 0) {
return ret;
}
/*
* Output final state
*/
sha512_put_uint64_be( ctx->state[0], output, 0 );
sha512_put_uint64_be( ctx->state[1], output, 8 );
sha512_put_uint64_be( ctx->state[2], output, 16 );
sha512_put_uint64_be( ctx->state[3], output, 24 );
sha512_put_uint64_be( ctx->state[4], output, 32 );
sha512_put_uint64_be( ctx->state[5], output, 40 );
sha512_put_uint64_be(ctx->state[0], output, 0);
sha512_put_uint64_be(ctx->state[1], output, 8);
sha512_put_uint64_be(ctx->state[2], output, 16);
sha512_put_uint64_be(ctx->state[3], output, 24);
sha512_put_uint64_be(ctx->state[4], output, 32);
sha512_put_uint64_be(ctx->state[5], output, 40);
int truncated = 0;
#if !defined(MBEDTLS_SHA512_NO_SHA384)
truncated = ctx->is384;
#endif
if( !truncated )
{
sha512_put_uint64_be( ctx->state[6], output, 48 );
sha512_put_uint64_be( ctx->state[7], output, 56 );
if (!truncated) {
sha512_put_uint64_be(ctx->state[6], output, 48);
sha512_put_uint64_be(ctx->state[7], output, 56);
}
return( 0 );
return 0;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_finish( mbedtls_sha512_context *ctx,
unsigned char output[64] )
void mbedtls_sha512_finish(mbedtls_sha512_context *ctx,
unsigned char output[64])
{
mbedtls_sha512_finish_ret( ctx, output );
mbedtls_sha512_finish_ret(ctx, output);
}
#endif
@@ -444,46 +436,49 @@ void mbedtls_sha512_finish( mbedtls_sha512_context *ctx,
/*
* output = SHA-512( input buffer )
*/
int mbedtls_sha512_ret( const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384 )
int mbedtls_sha512_ret(const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_sha512_context ctx;
#if !defined(MBEDTLS_SHA512_NO_SHA384)
SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 );
SHA512_VALIDATE_RET(is384 == 0 || is384 == 1);
#else
SHA512_VALIDATE_RET( is384 == 0 );
SHA512_VALIDATE_RET(is384 == 0);
#endif
SHA512_VALIDATE_RET( ilen == 0 || input != NULL );
SHA512_VALIDATE_RET( (unsigned char *)output != NULL );
SHA512_VALIDATE_RET(ilen == 0 || input != NULL);
SHA512_VALIDATE_RET((unsigned char *) output != NULL);
mbedtls_sha512_init( &ctx );
mbedtls_sha512_init(&ctx);
if( ( ret = mbedtls_sha512_starts_ret( &ctx, is384 ) ) != 0 )
if ((ret = mbedtls_sha512_starts_ret(&ctx, is384)) != 0) {
goto exit;
}
if( ( ret = mbedtls_sha512_update_ret( &ctx, input, ilen ) ) != 0 )
if ((ret = mbedtls_sha512_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if( ( ret = mbedtls_sha512_finish_ret( &ctx, output ) ) != 0 )
if ((ret = mbedtls_sha512_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_sha512_free( &ctx );
mbedtls_sha512_free(&ctx);
return( ret );
return ret;
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512( const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384 )
void mbedtls_sha512(const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384)
{
mbedtls_sha512_ret( input, ilen, output, is384 );
mbedtls_sha512_ret(input, ilen, output, is384);
}
#endif
@@ -495,7 +490,9 @@ void mbedtls_sha512( const unsigned char *input,
static const unsigned char sha512_test_buf[3][113] =
{
{ "abc" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu" },
{
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"
},
{ "" }
};
@@ -559,31 +556,30 @@ static const unsigned char sha512_test_sum[][64] =
0x4E, 0xAD, 0xB2, 0x17, 0xAD, 0x8C, 0xC0, 0x9B }
};
#define ARRAY_LENGTH( a ) ( sizeof( a ) / sizeof( ( a )[0] ) )
#define ARRAY_LENGTH(a) (sizeof(a) / sizeof((a)[0]))
/*
* Checkup routine
*/
int mbedtls_sha512_self_test( int verbose )
int mbedtls_sha512_self_test(int verbose)
{
int i, j, k, buflen, ret = 0;
unsigned char *buf;
unsigned char sha512sum[64];
mbedtls_sha512_context ctx;
buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
if( NULL == buf )
{
if( verbose != 0 )
mbedtls_printf( "Buffer allocation failed\n" );
buf = mbedtls_calloc(1024, sizeof(unsigned char));
if (NULL == buf) {
if (verbose != 0) {
mbedtls_printf("Buffer allocation failed\n");
}
return( 1 );
return 1;
}
mbedtls_sha512_init( &ctx );
mbedtls_sha512_init(&ctx);
for( i = 0; i < (int) ARRAY_LENGTH(sha512_test_sum); i++ )
{
for (i = 0; i < (int) ARRAY_LENGTH(sha512_test_sum); i++) {
j = i % 3;
#if !defined(MBEDTLS_SHA512_NO_SHA384)
k = i < 3;
@@ -591,58 +587,61 @@ int mbedtls_sha512_self_test( int verbose )
k = 0;
#endif
if( verbose != 0 )
mbedtls_printf( " SHA-%d test #%d: ", 512 - k * 128, j + 1 );
if (verbose != 0) {
mbedtls_printf(" SHA-%d test #%d: ", 512 - k * 128, j + 1);
}
if( ( ret = mbedtls_sha512_starts_ret( &ctx, k ) ) != 0 )
if ((ret = mbedtls_sha512_starts_ret(&ctx, k)) != 0) {
goto fail;
}
if( j == 2 )
{
memset( buf, 'a', buflen = 1000 );
if (j == 2) {
memset(buf, 'a', buflen = 1000);
for( j = 0; j < 1000; j++ )
{
ret = mbedtls_sha512_update_ret( &ctx, buf, buflen );
if( ret != 0 )
for (j = 0; j < 1000; j++) {
ret = mbedtls_sha512_update_ret(&ctx, buf, buflen);
if (ret != 0) {
goto fail;
}
}
} else {
ret = mbedtls_sha512_update_ret(&ctx, sha512_test_buf[j],
sha512_test_buflen[j]);
if (ret != 0) {
goto fail;
}
}
else
{
ret = mbedtls_sha512_update_ret( &ctx, sha512_test_buf[j],
sha512_test_buflen[j] );
if( ret != 0 )
goto fail;
if ((ret = mbedtls_sha512_finish_ret(&ctx, sha512sum)) != 0) {
goto fail;
}
if( ( ret = mbedtls_sha512_finish_ret( &ctx, sha512sum ) ) != 0 )
goto fail;
if( memcmp( sha512sum, sha512_test_sum[i], 64 - k * 16 ) != 0 )
{
if (memcmp(sha512sum, sha512_test_sum[i], 64 - k * 16) != 0) {
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
if (verbose != 0) {
mbedtls_printf("\n");
}
goto exit;
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
if (verbose != 0) {
mbedtls_printf("failed\n");
}
exit:
mbedtls_sha512_free( &ctx );
mbedtls_free( buf );
mbedtls_sha512_free(&ctx);
mbedtls_free(buf);
return( ret );
return ret;
}
#undef ARRAY_LENGTH

View File

@@ -32,83 +32,79 @@
#include <string.h>
void mbedtls_ssl_cache_init( mbedtls_ssl_cache_context *cache )
void mbedtls_ssl_cache_init(mbedtls_ssl_cache_context *cache)
{
memset( cache, 0, sizeof( mbedtls_ssl_cache_context ) );
memset(cache, 0, sizeof(mbedtls_ssl_cache_context));
cache->timeout = MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT;
cache->max_entries = MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES;
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &cache->mutex );
mbedtls_mutex_init(&cache->mutex);
#endif
}
int mbedtls_ssl_cache_get( void *data, mbedtls_ssl_session *session )
int mbedtls_ssl_cache_get(void *data, mbedtls_ssl_session *session)
{
int ret = 1;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t = mbedtls_time( NULL );
mbedtls_time_t t = mbedtls_time(NULL);
#endif
mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data;
mbedtls_ssl_cache_entry *cur, *entry;
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_lock( &cache->mutex ) != 0 )
return( 1 );
if (mbedtls_mutex_lock(&cache->mutex) != 0) {
return 1;
}
#endif
cur = cache->chain;
entry = NULL;
while( cur != NULL )
{
while (cur != NULL) {
entry = cur;
cur = cur->next;
#if defined(MBEDTLS_HAVE_TIME)
if( cache->timeout != 0 &&
(int) ( t - entry->timestamp ) > cache->timeout )
if (cache->timeout != 0 &&
(int) (t - entry->timestamp) > cache->timeout) {
continue;
}
#endif
if( session->id_len != entry->session.id_len ||
memcmp( session->id, entry->session.id,
entry->session.id_len ) != 0 )
{
if (session->id_len != entry->session.id_len ||
memcmp(session->id, entry->session.id,
entry->session.id_len) != 0) {
continue;
}
ret = mbedtls_ssl_session_copy( session, &entry->session );
if( ret != 0 )
{
ret = mbedtls_ssl_session_copy(session, &entry->session);
if (ret != 0) {
ret = 1;
goto exit;
}
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
/*
* Restore peer certificate (without rest of the original chain)
*/
if( entry->peer_cert.p != NULL )
{
if (entry->peer_cert.p != NULL) {
/* `session->peer_cert` is NULL after the call to
* mbedtls_ssl_session_copy(), because cache entries
* have the `peer_cert` field set to NULL. */
if( ( session->peer_cert = mbedtls_calloc( 1,
sizeof(mbedtls_x509_crt) ) ) == NULL )
{
if ((session->peer_cert = mbedtls_calloc(1,
sizeof(mbedtls_x509_crt))) == NULL) {
ret = 1;
goto exit;
}
mbedtls_x509_crt_init( session->peer_cert );
if( mbedtls_x509_crt_parse( session->peer_cert, entry->peer_cert.p,
entry->peer_cert.len ) != 0 )
{
mbedtls_free( session->peer_cert );
mbedtls_x509_crt_init(session->peer_cert);
if (mbedtls_x509_crt_parse(session->peer_cert, entry->peer_cert.p,
entry->peer_cert.len) != 0) {
mbedtls_free(session->peer_cert);
session->peer_cert = NULL;
ret = 1;
goto exit;
@@ -122,18 +118,19 @@ int mbedtls_ssl_cache_get( void *data, mbedtls_ssl_session *session )
exit:
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &cache->mutex ) != 0 )
if (mbedtls_mutex_unlock(&cache->mutex) != 0) {
ret = 1;
}
#endif
return( ret );
return ret;
}
int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
int mbedtls_ssl_cache_set(void *data, const mbedtls_ssl_session *session)
{
int ret = 1;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t = mbedtls_time( NULL ), oldest = 0;
mbedtls_time_t t = mbedtls_time(NULL), oldest = 0;
mbedtls_ssl_cache_entry *old = NULL;
#endif
mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data;
@@ -141,32 +138,31 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
int count = 0;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &cache->mutex ) ) != 0 )
return( ret );
if ((ret = mbedtls_mutex_lock(&cache->mutex)) != 0) {
return ret;
}
#endif
cur = cache->chain;
prv = NULL;
while( cur != NULL )
{
while (cur != NULL) {
count++;
#if defined(MBEDTLS_HAVE_TIME)
if( cache->timeout != 0 &&
(int) ( t - cur->timestamp ) > cache->timeout )
{
if (cache->timeout != 0 &&
(int) (t - cur->timestamp) > cache->timeout) {
cur->timestamp = t;
break; /* expired, reuse this slot, update timestamp */
}
#endif
if( memcmp( session->id, cur->session.id, cur->session.id_len ) == 0 )
if (memcmp(session->id, cur->session.id, cur->session.id_len) == 0) {
break; /* client reconnected, keep timestamp for session id */
}
#if defined(MBEDTLS_HAVE_TIME)
if( oldest == 0 || cur->timestamp < oldest )
{
if (oldest == 0 || cur->timestamp < oldest) {
oldest = cur->timestamp;
old = cur;
}
@@ -176,16 +172,13 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
cur = cur->next;
}
if( cur == NULL )
{
if (cur == NULL) {
#if defined(MBEDTLS_HAVE_TIME)
/*
* Reuse oldest entry if max_entries reached
*/
if( count >= cache->max_entries )
{
if( old == NULL )
{
if (count >= cache->max_entries) {
if (old == NULL) {
ret = 1;
goto exit;
}
@@ -197,10 +190,8 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
* Reuse first entry in chain if max_entries reached,
* but move to last place
*/
if( count >= cache->max_entries )
{
if( cache->chain == NULL )
{
if (count >= cache->max_entries) {
if (cache->chain == NULL) {
ret = 1;
goto exit;
}
@@ -211,22 +202,21 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
prv->next = cur;
}
#endif /* MBEDTLS_HAVE_TIME */
else
{
else {
/*
* max_entries not reached, create new entry
*/
cur = mbedtls_calloc( 1, sizeof(mbedtls_ssl_cache_entry) );
if( cur == NULL )
{
cur = mbedtls_calloc(1, sizeof(mbedtls_ssl_cache_entry));
if (cur == NULL) {
ret = 1;
goto exit;
}
if( prv == NULL )
if (prv == NULL) {
cache->chain = cur;
else
} else {
prv->next = cur;
}
}
#if defined(MBEDTLS_HAVE_TIME)
@@ -239,10 +229,9 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
/*
* If we're reusing an entry, free its certificate first
*/
if( cur->peer_cert.p != NULL )
{
mbedtls_free( cur->peer_cert.p );
memset( &cur->peer_cert, 0, sizeof(mbedtls_x509_buf) );
if (cur->peer_cert.p != NULL) {
mbedtls_free(cur->peer_cert.p);
memset(&cur->peer_cert, 0, sizeof(mbedtls_x509_buf));
}
#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
@@ -251,9 +240,8 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
* This inefficiency will go away as soon as we implement on-demand
* parsing of CRTs, in which case there's no need for the `peer_cert`
* field anymore in the first place, and we're done after this call. */
ret = mbedtls_ssl_session_copy( &cur->session, session );
if( ret != 0 )
{
ret = mbedtls_ssl_session_copy(&cur->session, session);
if (ret != 0) {
ret = 1;
goto exit;
}
@@ -261,23 +249,21 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
/* If present, free the X.509 structure and only store the raw CRT data. */
if( cur->session.peer_cert != NULL )
{
if (cur->session.peer_cert != NULL) {
cur->peer_cert.p =
mbedtls_calloc( 1, cur->session.peer_cert->raw.len );
if( cur->peer_cert.p == NULL )
{
mbedtls_calloc(1, cur->session.peer_cert->raw.len);
if (cur->peer_cert.p == NULL) {
ret = 1;
goto exit;
}
memcpy( cur->peer_cert.p,
cur->session.peer_cert->raw.p,
cur->session.peer_cert->raw.len );
memcpy(cur->peer_cert.p,
cur->session.peer_cert->raw.p,
cur->session.peer_cert->raw.len);
cur->peer_cert.len = session->peer_cert->raw.len;
mbedtls_x509_crt_free( cur->session.peer_cert );
mbedtls_free( cur->session.peer_cert );
mbedtls_x509_crt_free(cur->session.peer_cert);
mbedtls_free(cur->session.peer_cert);
cur->session.peer_cert = NULL;
}
#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
@@ -286,52 +272,56 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
exit:
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &cache->mutex ) != 0 )
if (mbedtls_mutex_unlock(&cache->mutex) != 0) {
ret = 1;
}
#endif
return( ret );
return ret;
}
#if defined(MBEDTLS_HAVE_TIME)
void mbedtls_ssl_cache_set_timeout( mbedtls_ssl_cache_context *cache, int timeout )
void mbedtls_ssl_cache_set_timeout(mbedtls_ssl_cache_context *cache, int timeout)
{
if( timeout < 0 ) timeout = 0;
if (timeout < 0) {
timeout = 0;
}
cache->timeout = timeout;
}
#endif /* MBEDTLS_HAVE_TIME */
void mbedtls_ssl_cache_set_max_entries( mbedtls_ssl_cache_context *cache, int max )
void mbedtls_ssl_cache_set_max_entries(mbedtls_ssl_cache_context *cache, int max)
{
if( max < 0 ) max = 0;
if (max < 0) {
max = 0;
}
cache->max_entries = max;
}
void mbedtls_ssl_cache_free( mbedtls_ssl_cache_context *cache )
void mbedtls_ssl_cache_free(mbedtls_ssl_cache_context *cache)
{
mbedtls_ssl_cache_entry *cur, *prv;
cur = cache->chain;
while( cur != NULL )
{
while (cur != NULL) {
prv = cur;
cur = cur->next;
mbedtls_ssl_session_free( &prv->session );
mbedtls_ssl_session_free(&prv->session);
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
mbedtls_free( prv->peer_cert.p );
defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
mbedtls_free(prv->peer_cert.p);
#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
mbedtls_free( prv );
mbedtls_free(prv);
}
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_free( &cache->mutex );
mbedtls_mutex_free(&cache->mutex);
#endif
cache->chain = NULL;
}

View File

@@ -455,14 +455,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_CAMELLIA_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256",
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
"TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA384",
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
"TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -472,14 +474,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_GCM_C)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-GCM-SHA256",
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
"TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-GCM-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-GCM-SHA384",
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
"TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-GCM-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -574,14 +578,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_CAMELLIA_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA256",
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
"TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA384",
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
"TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -591,14 +597,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_GCM_C)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDHE-RSA-WITH-CAMELLIA-128-GCM-SHA256",
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256,
"TLS-ECDHE-RSA-WITH-CAMELLIA-128-GCM-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDHE-RSA-WITH-CAMELLIA-256-GCM-SHA384",
{ MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384,
"TLS-ECDHE-RSA-WITH-CAMELLIA-256-GCM-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -982,14 +990,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_CAMELLIA_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA256",
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
"TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA384",
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,
"TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -999,14 +1009,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_GCM_C)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDH-RSA-WITH-CAMELLIA-128-GCM-SHA256",
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
"TLS-ECDH-RSA-WITH-CAMELLIA-128-GCM-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDH-RSA-WITH-CAMELLIA-256-GCM-SHA384",
{ MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
"TLS-ECDH-RSA-WITH-CAMELLIA-256-GCM-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1101,14 +1113,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_CAMELLIA_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256",
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
"TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA384",
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
"TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1118,14 +1132,16 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_GCM_C)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-GCM-SHA256",
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
"TLS-ECDH-ECDSA-WITH-CAMELLIA-128-GCM-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-GCM-SHA384",
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
"TLS-ECDH-ECDSA-WITH-CAMELLIA-256-GCM-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1478,7 +1494,8 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if defined(MBEDTLS_CAMELLIA_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA256_C)
{ MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-ECDHE-PSK-WITH-CAMELLIA-128-CBC-SHA256",
{ MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
"TLS-ECDHE-PSK-WITH-CAMELLIA-128-CBC-SHA256",
MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1486,7 +1503,8 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_SHA256_C */
#if defined(HAVE_SHA384)
{ MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-ECDHE-PSK-WITH-CAMELLIA-256-CBC-SHA384",
{ MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
"TLS-ECDHE-PSK-WITH-CAMELLIA-256-CBC-SHA384",
MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1808,7 +1826,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
"TLS-RSA-WITH-ARIA-256-GCM-SHA384",
"TLS-RSA-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1816,7 +1834,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384,
"TLS-RSA-WITH-ARIA-256-CBC-SHA384",
"TLS-RSA-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1824,7 +1842,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
"TLS-RSA-WITH-ARIA-128-GCM-SHA256",
"TLS-RSA-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1832,7 +1850,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256,
"TLS-RSA-WITH-ARIA-128-CBC-SHA256",
"TLS-RSA-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1845,7 +1863,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
"TLS-RSA-PSK-WITH-ARIA-256-GCM-SHA384",
"TLS-RSA-PSK-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1853,7 +1871,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,
"TLS-RSA-PSK-WITH-ARIA-256-CBC-SHA384",
"TLS-RSA-PSK-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1861,7 +1879,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
"TLS-RSA-PSK-WITH-ARIA-128-GCM-SHA256",
"TLS-RSA-PSK-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1869,7 +1887,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,
"TLS-RSA-PSK-WITH-ARIA-128-CBC-SHA256",
"TLS-RSA-PSK-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1882,15 +1900,15 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
"TLS-PSK-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384,MBEDTLS_KEY_EXCHANGE_PSK,
"TLS-PSK-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384,
"TLS-PSK-WITH-ARIA-256-CBC-SHA384",
"TLS-PSK-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1898,7 +1916,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
"TLS-PSK-WITH-ARIA-128-GCM-SHA256",
"TLS-PSK-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1906,7 +1924,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256,
"TLS-PSK-WITH-ARIA-128-CBC-SHA256",
"TLS-PSK-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1919,7 +1937,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,
"TLS-ECDH-RSA-WITH-ARIA-256-GCM-SHA384",
"TLS-ECDH-RSA-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1927,7 +1945,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,
"TLS-ECDH-RSA-WITH-ARIA-256-CBC-SHA384",
"TLS-ECDH-RSA-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1935,7 +1953,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,
"TLS-ECDH-RSA-WITH-ARIA-128-GCM-SHA256",
"TLS-ECDH-RSA-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1943,7 +1961,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,
"TLS-ECDH-RSA-WITH-ARIA-128-CBC-SHA256",
"TLS-ECDH-RSA-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1956,7 +1974,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,
"TLS-ECDHE-RSA-WITH-ARIA-256-GCM-SHA384",
"TLS-ECDHE-RSA-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1964,7 +1982,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,
"TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384",
"TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1972,7 +1990,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,
"TLS-ECDHE-RSA-WITH-ARIA-128-GCM-SHA256",
"TLS-ECDHE-RSA-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1980,7 +1998,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,
"TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256",
"TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -1993,7 +2011,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,
"TLS-ECDHE-PSK-WITH-ARIA-256-CBC-SHA384",
"TLS-ECDHE-PSK-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2001,7 +2019,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,
"TLS-ECDHE-PSK-WITH-ARIA-128-CBC-SHA256",
"TLS-ECDHE-PSK-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2014,7 +2032,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384,
"TLS-ECDHE-ECDSA-WITH-ARIA-256-GCM-SHA384",
"TLS-ECDHE-ECDSA-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2022,7 +2040,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,
"TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384",
"TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2030,7 +2048,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256,
"TLS-ECDHE-ECDSA-WITH-ARIA-128-GCM-SHA256",
"TLS-ECDHE-ECDSA-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2038,7 +2056,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,
"TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256",
"TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2051,7 +2069,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,
"TLS-ECDH-ECDSA-WITH-ARIA-256-GCM-SHA384",
"TLS-ECDH-ECDSA-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2059,7 +2077,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,
"TLS-ECDH-ECDSA-WITH-ARIA-256-CBC-SHA384",
"TLS-ECDH-ECDSA-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2067,7 +2085,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,
"TLS-ECDH-ECDSA-WITH-ARIA-128-GCM-SHA256",
"TLS-ECDH-ECDSA-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2075,7 +2093,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,
"TLS-ECDH-ECDSA-WITH-ARIA-128-CBC-SHA256",
"TLS-ECDH-ECDSA-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2088,7 +2106,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384,
"TLS-DHE-RSA-WITH-ARIA-256-GCM-SHA384",
"TLS-DHE-RSA-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2096,7 +2114,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,
"TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384",
"TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2104,7 +2122,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256,
"TLS-DHE-RSA-WITH-ARIA-128-GCM-SHA256",
"TLS-DHE-RSA-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2112,7 +2130,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,
"TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256",
"TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2125,7 +2143,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#if (defined(MBEDTLS_GCM_C) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384,
"TLS-DHE-PSK-WITH-ARIA-256-GCM-SHA384",
"TLS-DHE-PSK-WITH-ARIA-256-GCM-SHA384",
MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2133,7 +2151,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(HAVE_SHA384))
{ MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,
"TLS-DHE-PSK-WITH-ARIA-256-CBC-SHA384",
"TLS-DHE-PSK-WITH-ARIA-256-CBC-SHA384",
MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2141,7 +2159,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256,
"TLS-DHE-PSK-WITH-ARIA-128-GCM-SHA256",
"TLS-DHE-PSK-WITH-ARIA-128-GCM-SHA256",
MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2149,7 +2167,7 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))
{ MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,
"TLS-DHE-PSK-WITH-ARIA-128-CBC-SHA256",
"TLS-DHE-PSK-WITH-ARIA-128-CBC-SHA256",
MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
@@ -2167,56 +2185,53 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
};
#if defined(MBEDTLS_SSL_CIPHERSUITES)
const int *mbedtls_ssl_list_ciphersuites( void )
const int *mbedtls_ssl_list_ciphersuites(void)
{
return( ciphersuite_preference );
return ciphersuite_preference;
}
#else
#define MAX_CIPHERSUITES sizeof( ciphersuite_definitions ) / \
sizeof( ciphersuite_definitions[0] )
#define MAX_CIPHERSUITES sizeof(ciphersuite_definitions) / \
sizeof(ciphersuite_definitions[0])
static int supported_ciphersuites[MAX_CIPHERSUITES];
static int supported_init = 0;
MBEDTLS_CHECK_RETURN_CRITICAL
static int ciphersuite_is_removed( const mbedtls_ssl_ciphersuite_t *cs_info )
static int ciphersuite_is_removed(const mbedtls_ssl_ciphersuite_t *cs_info)
{
(void)cs_info;
(void) cs_info;
#if defined(MBEDTLS_REMOVE_ARC4_CIPHERSUITES)
if( cs_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
return( 1 );
if (cs_info->cipher == MBEDTLS_CIPHER_ARC4_128) {
return 1;
}
#endif /* MBEDTLS_REMOVE_ARC4_CIPHERSUITES */
#if defined(MBEDTLS_REMOVE_3DES_CIPHERSUITES)
if( cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_ECB ||
cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_CBC )
{
return( 1 );
if (cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_ECB ||
cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_CBC) {
return 1;
}
#endif /* MBEDTLS_REMOVE_3DES_CIPHERSUITES */
return( 0 );
return 0;
}
const int *mbedtls_ssl_list_ciphersuites( void )
const int *mbedtls_ssl_list_ciphersuites(void)
{
/*
* On initial call filter out all ciphersuites not supported by current
* build based on presence in the ciphersuite_definitions.
*/
if( supported_init == 0 )
{
if (supported_init == 0) {
const int *p;
int *q;
for( p = ciphersuite_preference, q = supported_ciphersuites;
for (p = ciphersuite_preference, q = supported_ciphersuites;
*p != 0 && q < supported_ciphersuites + MAX_CIPHERSUITES - 1;
p++ )
{
p++) {
const mbedtls_ssl_ciphersuite_t *cs_info;
if( ( cs_info = mbedtls_ssl_ciphersuite_from_id( *p ) ) != NULL &&
!ciphersuite_is_removed( cs_info ) )
{
if ((cs_info = mbedtls_ssl_ciphersuite_from_id(*p)) != NULL &&
!ciphersuite_is_removed(cs_info)) {
*(q++) = *p;
}
}
@@ -2225,105 +2240,106 @@ const int *mbedtls_ssl_list_ciphersuites( void )
supported_init = 1;
}
return( supported_ciphersuites );
return supported_ciphersuites;
}
#endif /* MBEDTLS_SSL_CIPHERSUITES */
const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_string(
const char *ciphersuite_name )
const char *ciphersuite_name)
{
const mbedtls_ssl_ciphersuite_t *cur = ciphersuite_definitions;
if( NULL == ciphersuite_name )
return( NULL );
if (NULL == ciphersuite_name) {
return NULL;
}
while( cur->id != 0 )
{
if( 0 == strcmp( cur->name, ciphersuite_name ) )
return( cur );
while (cur->id != 0) {
if (0 == strcmp(cur->name, ciphersuite_name)) {
return cur;
}
cur++;
}
return( NULL );
return NULL;
}
const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuite )
const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id(int ciphersuite)
{
const mbedtls_ssl_ciphersuite_t *cur = ciphersuite_definitions;
while( cur->id != 0 )
{
if( cur->id == ciphersuite )
return( cur );
while (cur->id != 0) {
if (cur->id == ciphersuite) {
return cur;
}
cur++;
}
return( NULL );
return NULL;
}
const char *mbedtls_ssl_get_ciphersuite_name( const int ciphersuite_id )
const char *mbedtls_ssl_get_ciphersuite_name(const int ciphersuite_id)
{
const mbedtls_ssl_ciphersuite_t *cur;
cur = mbedtls_ssl_ciphersuite_from_id( ciphersuite_id );
cur = mbedtls_ssl_ciphersuite_from_id(ciphersuite_id);
if( cur == NULL )
return( "unknown" );
if (cur == NULL) {
return "unknown";
}
return( cur->name );
return cur->name;
}
int mbedtls_ssl_get_ciphersuite_id( const char *ciphersuite_name )
int mbedtls_ssl_get_ciphersuite_id(const char *ciphersuite_name)
{
const mbedtls_ssl_ciphersuite_t *cur;
cur = mbedtls_ssl_ciphersuite_from_string( ciphersuite_name );
cur = mbedtls_ssl_ciphersuite_from_string(ciphersuite_name);
if( cur == NULL )
return( 0 );
if (cur == NULL) {
return 0;
}
return( cur->id );
return cur->id;
}
#if defined(MBEDTLS_PK_C)
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info )
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg(const mbedtls_ssl_ciphersuite_t *info)
{
switch( info->key_exchange )
{
switch (info->key_exchange) {
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
return( MBEDTLS_PK_RSA );
return MBEDTLS_PK_RSA;
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
return( MBEDTLS_PK_ECDSA );
return MBEDTLS_PK_ECDSA;
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
return( MBEDTLS_PK_ECKEY );
return MBEDTLS_PK_ECKEY;
default:
return( MBEDTLS_PK_NONE );
return MBEDTLS_PK_NONE;
}
}
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info )
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg(const mbedtls_ssl_ciphersuite_t *info)
{
switch( info->key_exchange )
{
switch (info->key_exchange) {
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
return( MBEDTLS_PK_RSA );
return MBEDTLS_PK_RSA;
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
return( MBEDTLS_PK_ECDSA );
return MBEDTLS_PK_ECDSA;
default:
return( MBEDTLS_PK_NONE );
return MBEDTLS_PK_NONE;
}
}
@@ -2331,37 +2347,35 @@ mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphers
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info )
int mbedtls_ssl_ciphersuite_uses_ec(const mbedtls_ssl_ciphersuite_t *info)
{
switch( info->key_exchange )
{
switch (info->key_exchange) {
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
return( 1 );
return 1;
default:
return( 0 );
return 0;
}
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED*/
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info )
int mbedtls_ssl_ciphersuite_uses_psk(const mbedtls_ssl_ciphersuite_t *info)
{
switch( info->key_exchange )
{
switch (info->key_exchange) {
case MBEDTLS_KEY_EXCHANGE_PSK:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
return( 1 );
return 1;
default:
return( 0 );
return 0;
}
}
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */

File diff suppressed because it is too large Load Diff

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