crypto: use auto cleanup for many stack variables

Simplify cleanup paths by using glib's auto cleanup macros for stack
variables, allowing several goto jumps / labels to be eliminated.

Reviewed-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
This commit is contained in:
Daniel P. Berrangé 2019-07-23 16:22:36 +01:00
parent 133cf1e5b1
commit 57b9f113fc
8 changed files with 65 additions and 133 deletions

View file

@ -72,10 +72,12 @@ static void qcrypto_secret_decrypt(QCryptoSecret *secret,
size_t *outputlen,
Error **errp)
{
uint8_t *key = NULL, *ciphertext = NULL, *iv = NULL;
g_autofree uint8_t *key = NULL;
g_autofree uint8_t *ciphertext = NULL;
g_autofree uint8_t *iv = NULL;
size_t keylen, ciphertextlen, ivlen;
QCryptoCipher *aes = NULL;
uint8_t *plaintext = NULL;
g_autoptr(QCryptoCipher) aes = NULL;
g_autofree uint8_t *plaintext = NULL;
*output = NULL;
*outputlen = 0;
@ -83,27 +85,27 @@ static void qcrypto_secret_decrypt(QCryptoSecret *secret,
if (qcrypto_secret_lookup(secret->keyid,
&key, &keylen,
errp) < 0) {
goto cleanup;
return;
}
if (keylen != 32) {
error_setg(errp, "Key should be 32 bytes in length");
goto cleanup;
return;
}
if (!secret->iv) {
error_setg(errp, "IV is required to decrypt secret");
goto cleanup;
return;
}
iv = qbase64_decode(secret->iv, -1, &ivlen, errp);
if (!iv) {
goto cleanup;
return;
}
if (ivlen != 16) {
error_setg(errp, "IV should be 16 bytes in length not %zu",
ivlen);
goto cleanup;
return;
}
aes = qcrypto_cipher_new(QCRYPTO_CIPHER_ALG_AES_256,
@ -111,11 +113,11 @@ static void qcrypto_secret_decrypt(QCryptoSecret *secret,
key, keylen,
errp);
if (!aes) {
goto cleanup;
return;
}
if (qcrypto_cipher_setiv(aes, iv, ivlen, errp) < 0) {
goto cleanup;
return;
}
if (secret->format == QCRYPTO_SECRET_FORMAT_BASE64) {
@ -124,7 +126,7 @@ static void qcrypto_secret_decrypt(QCryptoSecret *secret,
&ciphertextlen,
errp);
if (!ciphertext) {
goto cleanup;
return;
}
plaintext = g_new0(uint8_t, ciphertextlen + 1);
} else {
@ -136,8 +138,7 @@ static void qcrypto_secret_decrypt(QCryptoSecret *secret,
plaintext,
ciphertextlen,
errp) < 0) {
plaintext = NULL;
goto cleanup;
return;
}
if (plaintext[ciphertextlen - 1] > 16 ||
@ -145,9 +146,7 @@ static void qcrypto_secret_decrypt(QCryptoSecret *secret,
error_setg(errp, "Incorrect number of padding bytes (%d) "
"found on decrypted data",
(int)plaintext[ciphertextlen - 1]);
g_free(plaintext);
plaintext = NULL;
goto cleanup;
return;
}
/* Even though plaintext may contain arbitrary NUL
@ -156,14 +155,8 @@ static void qcrypto_secret_decrypt(QCryptoSecret *secret,
ciphertextlen -= plaintext[ciphertextlen - 1];
plaintext[ciphertextlen] = '\0';
*output = plaintext;
*output = g_steal_pointer(&plaintext);
*outputlen = ciphertextlen;
cleanup:
g_free(ciphertext);
g_free(iv);
g_free(key);
qcrypto_cipher_free(aes);
}