Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passing same buffer as input and output to mbedtls_cipher_update leads to error #59

Closed
cdriper opened this issue Nov 20, 2018 · 0 comments

Comments

@cdriper
Copy link

cdriper commented Nov 20, 2018

I ported your code to Visual Studio and found a critical bug in aes_decrypt() code (AES decryption worked in a wrong way).
It's forbidden to pass same buffers as input and output to mbedtls_cipher_update.

Quote from mbedtls_cipher_update description:

param output: buffer for the output data. Should be able to hold at least ilen + block_size. Cannot be the same buffer as input!

Possible fix (with extra buffer allocation):

void aes_decrypt(aes_ctx_t *ctx, void *dst, const void *src, size_t l) 
{
    int bExtraBuff = 0; 

    if (src == dst)
    {
        bExtraBuff = 1;

        dst = malloc(l);
        assert(dst);
    }

    size_t out_len = 0;
    
    /* Prepare context */
    mbedtls_cipher_reset(&ctx->cipher_dec);
    
    /* XTS doesn't need per-block updating */
    if (mbedtls_cipher_get_cipher_mode(&ctx->cipher_dec) == MBEDTLS_MODE_XTS)
        mbedtls_cipher_update(&ctx->cipher_dec, (const unsigned char * )src, l, (unsigned char *)dst, &out_len);
    else
    {
        unsigned int blk_size = mbedtls_cipher_get_block_size(&ctx->cipher_dec);
        
        /* Do per-block updating */
        for (int offset = 0; (unsigned int)offset < l; offset += blk_size)
        {
            int len = ((unsigned int)(l - offset) > blk_size) ? blk_size : (unsigned int) (l - offset);
            mbedtls_cipher_update(&ctx->cipher_dec, (const unsigned char * )src + offset, len, (unsigned char *)dst + offset, &out_len);
        }
    }
    
    /* Flush all data */
    mbedtls_cipher_finish(&ctx->cipher_dec, NULL, NULL);

    if (bExtraBuff)
    {
        memcpy( (void*)src, dst, l );
        free(dst);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant