When psa_mac_start(), psa_encrypt_setup() or psa_cipher_setup()
failed, depending on when the failure happened, it was possible that
psa_mac_abort() or psa_cipher_abort() would crash because it would try
to call a free() function uninitialized data in the operation
structure. Refactor the functions so that they initialize the
operation structure before doing anything else.
Add non-regression tests and a few more positive and negative unit
tests for psa_mac_start() and psa_cipher_setup() (the latter via
psa_encrypt_setip()).
In psa_export_key, ensure that each byte of the output buffer either
contains its original value, is zero, or is part of the actual output.
Specifically, don't risk having partial output on error, and don't
leave extra data at the end of the buffer when exporting an asymmetric
key.
Test that exporting to a previously zeroed buffer leaves the buffer
zeroed outside the actual output if any.
Exporting an asymmetric key only worked if the target buffer had
exactly the right size, because psa_export_key uses
mbedtls_pk_write_key_der or mbedtls_pk_write_pubkey_der and these
functions write to the end of the buffer, which psa_export_key did not
correct for. Fix this by moving the data to the beginning of the
buffer if necessary.
Add non-regression tests.
psa_import_key must check that the imported key data matches the
expected key type. Implement the missing check for EC keys that the
curve is the expected one.
Avoid lines longer than 80 columns.
Remove some redundant parentheses, e.g. change
if( ( a == b ) && ( c == d ) )
to
if( a == b && c == d )
which makes lines less long and makes the remaining parentheses more
relevant.
Add missing parentheses around return statements.
There should be no semantic change in this commit.
Store the temporary key in the long-key case (where the key is first
hashed) directly into ipad. This reduces the stack usage a little, at
a slight cost in complexity.
In psa_mac_start, the hash of the key and ipad contain material that
can be used to make HMAC calculations with the key, therefore they
must be wiped.
In psa_mac_finish_internal, tmp contains an intermediate value which
could reveal the HMAC. This is definitely sensitive in the verify case,
and marginally sensitive in the finish case (it isn't if the hash
function is ideal, but it could make things worse if the hash function
is partially broken).
Split algorithm-specific code out of psa_mac_start. This makes the
function easier to read.
The behavior is mostly unchanged. In a few cases, errors before
setting a key trigger a context wipe where they didn't. This is a
marginal performance loss but only cases that are an error in caller
code.