[PATCH 0/5] cover: RFE libvirt secret encryption on disk
Libvirt secrets are stored unencrypted on the disk. With this series we want to start encrypting the secrets. 1. Introduce the GnuTLS decryption wrapper functions that work exact opposite to the encryption wrappers. The new test added works fine because during test execution, we use the mock implementation of virRandomBytes while generating the iv and the key. 2. Add a new service called virt-secrets-init-encryption, that is linked to the virtsecretd service. virtsecretd service only starts after the new service generates a random encryption key. 3. Add a new secret.conf configuration file that helps user to set a. secrets_encryption_key - allows the user to specify the encryption key file path, in case the default key is not to be used. b. encrypt_data - set to 0 or 1. If set to 1, then the newly added secrets will be encrypted. 4. Add encryption scheme or cipher attribute that will allow us to choose the last used cipher. New modes can be added to the enum. 5. Once we have the encryption key, and a reliable way to tell the daemon what encryption scheme the secret object must use, we can encrypt the secrets on disk and store them in <uuid>.<encryption_scheme> format. It is important to note that if the encryption key is changed between restarts, then the respective secret will not be loaded by the driver. This is a sincere attempt to improve upon the already submitted patch https://lists.libvirt.org/archives/list/devel@lists.libvirt.org/thread/KE6GV... Resolves: https://issues.redhat.com/browse/RHEL-7125 RFC: https://patchew.org/Libvirt/20251127072232.38426-1-armenon@redhat.com/ --- Changes in v1: - Previously, encrypt_data was set to 1 regardless of what is present in the secrets config file. This is now changed. encrypt_data is first read from the config file, and it is set to 1 only if secrets_encryption_key is not NULL or if systemd credential named "secrets-encryption-key" exists. - Rename from secrets.conf to secret.conf. Move secrets_config.c from src/conf to src/secret/ - Add a special error code 'VIR_ERR_INVALID_ENCR_KEY_SECRET' for when the secret key length is invalid. - Add the 2 directives to load credential into libvirtd service as well. Rename unit file name from secret-init-encryption.in to virt-secret-init-encryption.service.in. - Remove unnecessary configuration settings and make it inline. Arun Menon (5): util: Add support for GnuTLS decryption secret: Set up default encryption secret key for the virtsecretd service secret: Add secret.conf configuration file and parse it secret: Add encryptionSchemeType attribute to store ciphers secret: Add functionality to load and save secrets in encrypted format include/libvirt/virterror.h | 1 + libvirt.spec.in | 7 + po/POTFILES | 1 + src/conf/secret_conf.c | 6 + src/conf/secret_conf.h | 9 + src/conf/virsecretobj.c | 184 ++++++++++++++---- src/conf/virsecretobj.h | 18 +- src/libvirt_private.syms | 1 + src/meson.build | 1 + src/remote/libvirtd.service.in | 2 + src/secret/libvirt_secrets.aug | 40 ++++ src/secret/meson.build | 34 ++++ src/secret/secret.conf.in | 14 ++ src/secret/secret_config.c | 171 ++++++++++++++++ src/secret/secret_config.h | 40 ++++ src/secret/secret_driver.c | 34 +++- src/secret/test_libvirt_secrets.aug.in | 6 + .../virt-secret-init-encryption.service.in | 7 + src/secret/virtsecretd.service.extra.in | 8 + src/util/vircrypto.c | 126 +++++++++++- src/util/vircrypto.h | 8 + src/util/virerror.c | 3 + tests/vircryptotest.c | 65 +++++++ 23 files changed, 736 insertions(+), 50 deletions(-) create mode 100644 src/secret/libvirt_secrets.aug create mode 100644 src/secret/secret.conf.in create mode 100644 src/secret/secret_config.c create mode 100644 src/secret/secret_config.h create mode 100644 src/secret/test_libvirt_secrets.aug.in create mode 100644 src/secret/virt-secret-init-encryption.service.in -- 2.51.1
Adds `virCryptoDecryptDataAESgnutls` and `virCryptoDecryptData` as wrapper functions for GnuTLS decryption. These functions are the inverse of the existing GnuTLS encryption wrappers. This commit also includes a corresponding test case to validate data decryption. Signed-off-by: Arun Menon <armenon@redhat.com> Reviewed-by: Peter Krempa <pkrempa@redhat.com> --- src/libvirt_private.syms | 1 + src/util/vircrypto.c | 126 ++++++++++++++++++++++++++++++++++++++- src/util/vircrypto.h | 8 +++ tests/vircryptotest.c | 65 ++++++++++++++++++++ 4 files changed, 199 insertions(+), 1 deletion(-) diff --git a/src/libvirt_private.syms b/src/libvirt_private.syms index 4e57e4a8f6..63a1ae4c70 100644 --- a/src/libvirt_private.syms +++ b/src/libvirt_private.syms @@ -2254,6 +2254,7 @@ virConfWriteMem; # util/vircrypto.h +virCryptoDecryptData; virCryptoEncryptData; virCryptoHashBuf; virCryptoHashString; diff --git a/src/util/vircrypto.c b/src/util/vircrypto.c index 3ce23264ca..00f723bb75 100644 --- a/src/util/vircrypto.c +++ b/src/util/vircrypto.c @@ -98,7 +98,7 @@ virCryptoHashString(virCryptoHash hash, } -/* virCryptoEncryptDataAESgntuls: +/* virCryptoEncryptDataAESgnutls: * * Performs the AES gnutls encryption * @@ -233,3 +233,127 @@ virCryptoEncryptData(virCryptoCipher algorithm, _("algorithm=%1$d is not supported"), algorithm); return -1; } + +/* virCryptoDecryptDataAESgnutls: + * + * Performs the AES gnutls decryption + * + * Same input as virCryptoDecryptData, except the algorithm is replaced + * by the specific gnutls algorithm. + * + * Decrypts the @data buffer using the @deckey and if available the @iv + * + * Returns 0 on success with the plaintext being filled. It is the + * caller's responsibility to clear and free it. Returns -1 on failure + * w/ error set. + */ +static int +virCryptoDecryptDataAESgnutls(gnutls_cipher_algorithm_t gnutls_dec_alg, + uint8_t *deckey, + size_t deckeylen, + uint8_t *iv, + size_t ivlen, + uint8_t *data, + size_t datalen, + uint8_t **plaintextret, + size_t *plaintextlenret) +{ + int rc; + uint8_t padding_length; + gnutls_cipher_hd_t handle = NULL; + gnutls_datum_t dec_key = { .data = deckey, .size = deckeylen }; + gnutls_datum_t iv_buf = { .data = iv, .size = ivlen }; + g_autofree uint8_t *plaintext = NULL; + size_t plaintextlen; + + if ((rc = gnutls_cipher_init(&handle, gnutls_dec_alg, + &dec_key, &iv_buf)) < 0) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("failed to initialize cipher: '%1$s'"), + gnutls_strerror(rc)); + return -1; + } + + plaintext = g_memdup2(data, datalen); + plaintextlen = datalen; + if (plaintextlen == 0) { + virReportError(VIR_ERR_INTERNAL_ERROR, "%s", + _("decrypted data has zero length")); + goto error; + } + rc = gnutls_cipher_decrypt(handle, plaintext, plaintextlen); + gnutls_cipher_deinit(handle); + if (rc < 0) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("failed to decrypt the data: '%1$s'"), + gnutls_strerror(rc)); + goto error; + } + /* Before encryption, padding is added to the data. + * The last byte indicates the padding length, because in PKCS#7, all + * padding bytes are set to the padding length value. + */ + padding_length = plaintext[plaintextlen - 1]; + if (padding_length > plaintextlen) { + virReportError(VIR_ERR_INVALID_SECRET, "%s", + _("decrypted data has invalid padding")); + goto error; + } + *plaintextlenret = plaintextlen - padding_length; + *plaintextret = g_steal_pointer(&plaintext); + return 0; + error: + virSecureErase(plaintext, plaintextlen); + return -1; +} + +/* virCryptoDecryptData: + * @algorithm: algorithm desired for decryption + * @deckey: decryption key + * @deckeylen: decryption key length + * @iv: initialization vector + * @ivlen: length of initialization vector + * @data: data to decrypt + * @datalen: length of data + * @plaintext: stream of bytes allocated to store plaintext + * @plaintextlen: size of the stream of bytes + * Returns 0 on success, -1 on failure with error set + */ +int +virCryptoDecryptData(virCryptoCipher algorithm, + uint8_t *deckey, + size_t deckeylen, + uint8_t *iv, + size_t ivlen, + uint8_t *data, + size_t datalen, + uint8_t **plaintext, + size_t *plaintextlen) +{ + switch (algorithm) { + case VIR_CRYPTO_CIPHER_AES256CBC: + if (deckeylen != 32) { + virReportError(VIR_ERR_INVALID_ARG, + _("AES256CBC decryption invalid keylen=%1$zu"), + deckeylen); + return -1; + } + if (ivlen != 16) { + virReportError(VIR_ERR_INVALID_ARG, + _("AES256CBC initialization vector invalid len=%1$zu"), + ivlen); + return -1; + } + return virCryptoDecryptDataAESgnutls(GNUTLS_CIPHER_AES_256_CBC, + deckey, deckeylen, iv, ivlen, + data, datalen, + plaintext, plaintextlen); + case VIR_CRYPTO_CIPHER_NONE: + case VIR_CRYPTO_CIPHER_LAST: + break; + } + + virReportError(VIR_ERR_INVALID_ARG, + _("algorithm=%1$d is not supported"), algorithm); + return -1; +} diff --git a/src/util/vircrypto.h b/src/util/vircrypto.h index 5f079ac335..2e8557839d 100644 --- a/src/util/vircrypto.h +++ b/src/util/vircrypto.h @@ -61,3 +61,11 @@ int virCryptoEncryptData(virCryptoCipher algorithm, uint8_t **ciphertext, size_t *ciphertextlen) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(6) ATTRIBUTE_NONNULL(8) ATTRIBUTE_NONNULL(9) G_GNUC_WARN_UNUSED_RESULT; + +int virCryptoDecryptData(virCryptoCipher algorithm, + uint8_t *deckey, size_t deckeylen, + uint8_t *iv, size_t ivlen, + uint8_t *data, size_t datalen, + uint8_t **plaintext, size_t *plaintextlen) + ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(6) + ATTRIBUTE_NONNULL(8) ATTRIBUTE_NONNULL(9) G_GNUC_WARN_UNUSED_RESULT; diff --git a/tests/vircryptotest.c b/tests/vircryptotest.c index 9ffe70756e..864fa8838d 100644 --- a/tests/vircryptotest.c +++ b/tests/vircryptotest.c @@ -62,6 +62,14 @@ struct testCryptoEncryptData { size_t ciphertextlen; }; +struct testCryptoDecryptData { + virCryptoCipher algorithm; + uint8_t *input; + size_t inputlen; + uint8_t *plaintext; + size_t plaintextlen; +}; + static int testCryptoEncrypt(const void *opaque) { @@ -101,6 +109,44 @@ testCryptoEncrypt(const void *opaque) return 0; } +static int +testCryptoDecrypt(const void *opaque) +{ + const struct testCryptoDecryptData *data = opaque; + g_autofree uint8_t *deckey = NULL; + size_t deckeylen = 32; + g_autofree uint8_t *iv = NULL; + size_t ivlen = 16; + g_autofree uint8_t *plaintext = NULL; + size_t plaintextlen = 0; + + deckey = g_new0(uint8_t, deckeylen); + iv = g_new0(uint8_t, ivlen); + + if (virRandomBytes(deckey, deckeylen) < 0 || + virRandomBytes(iv, ivlen) < 0) { + fprintf(stderr, "Failed to generate random bytes\n"); + return -1; + } + + if (virCryptoDecryptData(data->algorithm, deckey, deckeylen, iv, ivlen, + data->input, data->inputlen, + &plaintext, &plaintextlen) < 0) + return -1; + + if (data->plaintextlen != plaintextlen) { + fprintf(stderr, "Expected plaintexlen(%zu) doesn't match (%zu)\n", + data->plaintextlen, plaintextlen); + return -1; + } + + if (memcmp(data->plaintext, plaintext, plaintextlen)) { + fprintf(stderr, "Expected plaintext doesn't match\n"); + return -1; + } + + return 0; +} static int mymain(void) @@ -155,7 +201,26 @@ mymain(void) #undef VIR_CRYPTO_ENCRYPT +#define VIR_CRYPTO_DECRYPT(a, n, i, il, c, cl) \ + do { \ + struct testCryptoDecryptData data = { \ + .algorithm = a, \ + .input = i, \ + .inputlen = il, \ + .plaintext = c, \ + .plaintextlen = cl, \ + }; \ + if (virTestRun("Decrypt " n, testCryptoDecrypt, &data) < 0) \ + ret = -1; \ + } while (0) + + VIR_CRYPTO_DECRYPT(VIR_CRYPTO_CIPHER_AES256CBC, "aes256cbc", + expected_ciphertext, 16, secretdata, 7); + +#undef VIR_CRYPTO_DECRYPT + return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE; + } /* Forces usage of not so random virRandomBytes */ -- 2.51.1
This commit sets the foundation for encrypting the libvirt secrets by providing a secure way to pass a secret encryption key to the virtsecretd service. A random secret key is generated using the new virt-secret-init-encryption service. This key can be consumed by the virtsecretd service. By using the "Before=" directive in the new virt-secret-init-encryption service and using "Requires=" directive in the virtsecretd service, we make sure that the daemon is run only after we have an encrypted secret key file generated and placed in /var/lib/libvirt/secrets. The virtsecretd service can then read the key from CREDENTIALS_DIRECTORY. [1] This setup therefore provides a default key out-of-the-box for initial use. A subsequent commit will introduce the logic for virtsecretd to access and use this key via the $CREDENTIALS_DIRECTORY environment variable. [2] [1] https://www.freedesktop.org/software/systemd/man/latest/systemd-creds.html [2] https://systemd.io/CREDENTIALS/ Signed-off-by: Arun Menon <armenon@redhat.com> --- libvirt.spec.in | 4 ++++ src/meson.build | 1 + src/remote/libvirtd.service.in | 2 ++ src/secret/meson.build | 15 +++++++++++++++ src/secret/virt-secret-init-encryption.service.in | 7 +++++++ src/secret/virtsecretd.service.extra.in | 8 ++++++++ 6 files changed, 37 insertions(+) create mode 100644 src/secret/virt-secret-init-encryption.service.in diff --git a/libvirt.spec.in b/libvirt.spec.in index ccfe75135b..8505a220c7 100644 --- a/libvirt.spec.in +++ b/libvirt.spec.in @@ -1890,13 +1890,16 @@ exit 0 %pre daemon-driver-secret %libvirt_sysconfig_pre virtsecretd %libvirt_systemd_unix_pre virtsecretd +%libvirt_systemd_oneshot_pre virt-secret-init-encryption %posttrans daemon-driver-secret %libvirt_sysconfig_posttrans virtsecretd %libvirt_systemd_unix_posttrans virtsecretd +%libvirt_systemd_unix_posttrans virt-secret-init-encryption %preun daemon-driver-secret %libvirt_systemd_unix_preun virtsecretd +%libvirt_systemd_unix_preun virt-secret-init-encryption %pre daemon-driver-storage-core %libvirt_sysconfig_pre virtstoraged @@ -2248,6 +2251,7 @@ exit 0 %{_datadir}/augeas/lenses/virtsecretd.aug %{_datadir}/augeas/lenses/tests/test_virtsecretd.aug %{_unitdir}/virtsecretd.service +%{_unitdir}/virt-secret-init-encryption.service %{_unitdir}/virtsecretd.socket %{_unitdir}/virtsecretd-ro.socket %{_unitdir}/virtsecretd-admin.socket diff --git a/src/meson.build b/src/meson.build index 47c978cc1f..f18f562fd9 100644 --- a/src/meson.build +++ b/src/meson.build @@ -837,6 +837,7 @@ if conf.has('WITH_LIBVIRTD') 'sbindir': sbindir, 'sysconfdir': sysconfdir, 'initconfdir': initconfdir, + 'localstatedir': localstatedir, 'name': unit['name'], 'service': unit['service'], 'SERVICE': unit['service'].to_upper(), diff --git a/src/remote/libvirtd.service.in b/src/remote/libvirtd.service.in index b0a062e885..84447e0bcf 100644 --- a/src/remote/libvirtd.service.in +++ b/src/remote/libvirtd.service.in @@ -29,6 +29,8 @@ Conflicts=xendomains.service Type=notify-reload Environment=LIBVIRTD_ARGS="--timeout 120" EnvironmentFile=-@initconfdir@/libvirtd +Environment=SECRETS_ENCRYPTION_KEY=%d/secrets-encryption-key +LoadCredentialEncrypted=secrets-encryption-key:@localstatedir@/lib/libvirt/secrets/secrets-encryption-key ExecStart=@sbindir@/libvirtd $LIBVIRTD_ARGS ExecReload=/bin/kill -HUP $MAINPID KillMode=process diff --git a/src/secret/meson.build b/src/secret/meson.build index 3b859ea7b4..b0977eadc8 100644 --- a/src/secret/meson.build +++ b/src/secret/meson.build @@ -31,6 +31,21 @@ if conf.has('WITH_SECRETS') 'name': 'virtsecretd', } + virt_secret_init_encryption_conf = configuration_data() + + virt_secret_init_encryption_conf.set('localstatedir', localstatedir) + virt_secret_init_encryption_conf.set('name', 'Libvirt Secret Encryption Init') + virt_secret_init_encryption_conf.set('service', 'virt-secret-init-encryption') + virt_secret_init_encryption_conf.set('SERVICE', 'virt-secret-init-encryption'.to_upper()) + + configure_file( + input: 'virt-secret-init-encryption.service.in', + output: '@0@.service'.format('virt-secret-init-encryption'), + configuration: virt_secret_init_encryption_conf, + install: true, + install_dir: unitdir, + ) + virt_daemon_units += { 'service': 'virtsecretd', 'name': 'secret', diff --git a/src/secret/virt-secret-init-encryption.service.in b/src/secret/virt-secret-init-encryption.service.in new file mode 100644 index 0000000000..0a23d452e8 --- /dev/null +++ b/src/secret/virt-secret-init-encryption.service.in @@ -0,0 +1,7 @@ +[Unit] +Before=virtsecretd.service +ConditionPathExists=!@localstatedir@/lib/libvirt/secrets/secrets-encryption-key + +[Service] +Type=oneshot +ExecStart=/usr/bin/sh -c 'umask 0066 && (dd if=/dev/urandom status=none bs=32 count=1 | systemd-creds encrypt --name=secrets-encryption-key - @localstatedir@/lib/libvirt/secrets/secrets-encryption-key)' diff --git a/src/secret/virtsecretd.service.extra.in b/src/secret/virtsecretd.service.extra.in index 1fc8c672f7..116458b22a 100644 --- a/src/secret/virtsecretd.service.extra.in +++ b/src/secret/virtsecretd.service.extra.in @@ -1,2 +1,10 @@ # The contents of this unit will be merged into a base template. # Additional units might be merged as well. See meson.build for details. +# +[Unit] +Requires=virt-secret-init-encryption.service +After=virt-secret-init-encryption.service + +[Service] +LoadCredentialEncrypted=secrets-encryption-key:@localstatedir@/lib/libvirt/secrets/secrets-encryption-key +Environment=SECRETS_ENCRYPTION_KEY=%d/secrets-encryption-key -- 2.51.1
On Tue, Dec 09, 2025 at 01:22:28 +0530, Arun Menon via Devel wrote:
This commit sets the foundation for encrypting the libvirt secrets by providing a secure way to pass a secret encryption key to the virtsecretd service.
A random secret key is generated using the new virt-secret-init-encryption service. This key can be consumed by the virtsecretd service.
By using the "Before=" directive in the new virt-secret-init-encryption service and using "Requires=" directive in the virtsecretd service, we make sure that the daemon is run only after we have an encrypted secret key file generated and placed in /var/lib/libvirt/secrets. The virtsecretd service can then read the key from CREDENTIALS_DIRECTORY. [1]
This setup therefore provides a default key out-of-the-box for initial use. A subsequent commit will introduce the logic for virtsecretd to access and use this key via the $CREDENTIALS_DIRECTORY environment variable. [2]
[1] https://www.freedesktop.org/software/systemd/man/latest/systemd-creds.html [2] https://systemd.io/CREDENTIALS/
Signed-off-by: Arun Menon <armenon@redhat.com> --- libvirt.spec.in | 4 ++++ src/meson.build | 1 + src/remote/libvirtd.service.in | 2 ++ src/secret/meson.build | 15 +++++++++++++++ src/secret/virt-secret-init-encryption.service.in | 7 +++++++ src/secret/virtsecretd.service.extra.in | 8 ++++++++ 6 files changed, 37 insertions(+) create mode 100644 src/secret/virt-secret-init-encryption.service.in
[...]
diff --git a/src/remote/libvirtd.service.in b/src/remote/libvirtd.service.in index b0a062e885..84447e0bcf 100644 --- a/src/remote/libvirtd.service.in +++ b/src/remote/libvirtd.service.in @@ -29,6 +29,8 @@ Conflicts=xendomains.service Type=notify-reload Environment=LIBVIRTD_ARGS="--timeout 120" EnvironmentFile=-@initconfdir@/libvirtd +Environment=SECRETS_ENCRYPTION_KEY=%d/secrets-encryption-key +LoadCredentialEncrypted=secrets-encryption-key:@localstatedir@/lib/libvirt/secrets/secrets-encryption-key ExecStart=@sbindir@/libvirtd $LIBVIRTD_ARGS ExecReload=/bin/kill -HUP $MAINPID KillMode=process
IIUC the libvird.service.in unit needs to depend the same way on 'virt-secret-init-encryption.service' as virtsecredtd.service does.
diff --git a/src/secret/meson.build b/src/secret/meson.build index 3b859ea7b4..b0977eadc8 100644 --- a/src/secret/meson.build +++ b/src/secret/meson.build @@ -31,6 +31,21 @@ if conf.has('WITH_SECRETS') 'name': 'virtsecretd', }
+ virt_secret_init_encryption_conf = configuration_data() + + virt_secret_init_encryption_conf.set('localstatedir', localstatedir)
---
+ virt_secret_init_encryption_conf.set('name', 'Libvirt Secret Encryption Init') + virt_secret_init_encryption_conf.set('service', 'virt-secret-init-encryption') + virt_secret_init_encryption_conf.set('SERVICE', 'virt-secret-init-encryption'.to_upper())
^^^ None of the above substitutions are actually used in 'virt-secret-init-encryption.service.in'.
+ + configure_file( + input: 'virt-secret-init-encryption.service.in', + output: '@0@.service'.format('virt-secret-init-encryption'), + configuration: virt_secret_init_encryption_conf, + install: true, + install_dir: unitdir, + ) + virt_daemon_units += { 'service': 'virtsecretd', 'name': 'secret', diff --git a/src/secret/virt-secret-init-encryption.service.in b/src/secret/virt-secret-init-encryption.service.in new file mode 100644 index 0000000000..0a23d452e8 --- /dev/null +++ b/src/secret/virt-secret-init-encryption.service.in @@ -0,0 +1,7 @@ +[Unit] +Before=virtsecretd.service
libvirtd.service too
+ConditionPathExists=!@localstatedir@/lib/libvirt/secrets/secrets-encryption-key + +[Service] +Type=oneshot +ExecStart=/usr/bin/sh -c 'umask 0066 && (dd if=/dev/urandom status=none bs=32 count=1 | systemd-creds encrypt --name=secrets-encryption-key - @localstatedir@/lib/libvirt/secrets/secrets-encryption-key)' diff --git a/src/secret/virtsecretd.service.extra.in b/src/secret/virtsecretd.service.extra.in index 1fc8c672f7..116458b22a 100644 --- a/src/secret/virtsecretd.service.extra.in +++ b/src/secret/virtsecretd.service.extra.in @@ -1,2 +1,10 @@ # The contents of this unit will be merged into a base template. # Additional units might be merged as well. See meson.build for details. +# +[Unit] +Requires=virt-secret-init-encryption.service +After=virt-secret-init-encryption.service
[1]
A new configuration file called secret.conf is introduced to let the user configure the path to the secrets encryption key. This key will be used to encrypt/decrypt the secrets in libvirt. By default the path is set to the runtime directory /run/libvirt/secrets, and it is commented in the config file. After parsing the file, the virtsecretd driver checks if an encryption key is present in the path and is valid. If no encryption key is present in the path, then the service will by default use the encryption key stored in the CREDENTIALS_DIRECTORY. Add logic to parse the encryption key file and store the key. It also checks for the encrypt_data attribute in the config file. The encryption and decryption logic will be added in the subsequent patches. Signed-off-by: Arun Menon <armenon@redhat.com> --- include/libvirt/virterror.h | 1 + libvirt.spec.in | 3 + po/POTFILES | 1 + src/secret/libvirt_secrets.aug | 40 ++++++ src/secret/meson.build | 19 +++ src/secret/secret.conf.in | 14 ++ src/secret/secret_config.c | 171 +++++++++++++++++++++++++ src/secret/secret_config.h | 40 ++++++ src/secret/secret_driver.c | 9 ++ src/secret/test_libvirt_secrets.aug.in | 6 + src/util/virerror.c | 3 + 11 files changed, 307 insertions(+) create mode 100644 src/secret/libvirt_secrets.aug create mode 100644 src/secret/secret.conf.in create mode 100644 src/secret/secret_config.c create mode 100644 src/secret/secret_config.h create mode 100644 src/secret/test_libvirt_secrets.aug.in diff --git a/include/libvirt/virterror.h b/include/libvirt/virterror.h index f02da046a3..5d9e06b4bb 100644 --- a/include/libvirt/virterror.h +++ b/include/libvirt/virterror.h @@ -353,6 +353,7 @@ typedef enum { command within timeout (Since: 11.2.0) */ VIR_ERR_AGENT_COMMAND_FAILED = 113, /* guest agent responded with failure to a command (Since: 11.2.0) */ + VIR_ERR_INVALID_ENCR_KEY_SECRET = 114, /* encrypion key is invalid (Since: 12.0.0) */ # ifdef VIR_ENUM_SENTINELS VIR_ERR_NUMBER_LAST /* (Since: 5.0.0) */ diff --git a/libvirt.spec.in b/libvirt.spec.in index 8505a220c7..bb1dcc367f 100644 --- a/libvirt.spec.in +++ b/libvirt.spec.in @@ -2250,6 +2250,9 @@ exit 0 %config(noreplace) %{_sysconfdir}/libvirt/virtsecretd.conf %{_datadir}/augeas/lenses/virtsecretd.aug %{_datadir}/augeas/lenses/tests/test_virtsecretd.aug +%{_datadir}/augeas/lenses/libvirt_secrets.aug +%{_datadir}/augeas/lenses/tests/test_libvirt_secrets.aug +%config(noreplace) %{_sysconfdir}/libvirt/secret.conf %{_unitdir}/virtsecretd.service %{_unitdir}/virt-secret-init-encryption.service %{_unitdir}/virtsecretd.socket diff --git a/po/POTFILES b/po/POTFILES index f0aad35c8c..045981a9ac 100644 --- a/po/POTFILES +++ b/po/POTFILES @@ -233,6 +233,7 @@ src/rpc/virnettlscert.c src/rpc/virnettlsconfig.c src/rpc/virnettlscontext.c src/secret/secret_driver.c +src/secret/secret_config.c src/security/security_apparmor.c src/security/security_dac.c src/security/security_driver.c diff --git a/src/secret/libvirt_secrets.aug b/src/secret/libvirt_secrets.aug new file mode 100644 index 0000000000..8dda373e62 --- /dev/null +++ b/src/secret/libvirt_secrets.aug @@ -0,0 +1,40 @@ +(* /etc/libvirt/secret.conf *) + +module Libvirt_secrets = + autoload xfm + + let eol = del /[ \t]*\n/ "\n" + let value_sep = del /[ \t]*=[ \t]*/ " = " + let indent = del /[ \t]*/ "" + + let array_sep = del /,[ \t\n]*/ ", " + let array_start = del /\[[ \t\n]*/ "[ " + let array_end = del /\]/ "]" + + let str_val = del /\"/ "\"" . store /[^\"]*/ . del /\"/ "\"" + let bool_val = store /0|1/ + let int_val = store /[0-9]+/ + let str_array_element = [ seq "el" . str_val ] . del /[ \t\n]*/ "" + let str_array_val = counter "el" . array_start . ( str_array_element . ( array_sep . str_array_element ) * ) ? . array_end + + let str_entry (kw:string) = [ key kw . value_sep . str_val ] + let bool_entry (kw:string) = [ key kw . value_sep . bool_val ] + let int_entry (kw:string) = [ key kw . value_sep . int_val ] + let str_array_entry (kw:string) = [ key kw . value_sep . str_array_val ] + + let secrets_entry = str_entry "secrets_encryption_key" + | bool_entry "encrypt_data" + + (* Each entry in the config is one of the following three ... *) + let entry = secrets_entry + let comment = [ label "#comment" . del /#[ \t]*/ "# " . store /([^ \t\n][^\n]*)?/ . del /\n/ "\n" ] + let empty = [ label "#empty" . eol ] + + let record = indent . entry . eol + + let lns = ( record | comment | empty ) * + + let filter = incl "/etc/libvirt/secret.conf" + . Util.stdexcl + + let xfm = transform lns filter diff --git a/src/secret/meson.build b/src/secret/meson.build index b0977eadc8..c29b992190 100644 --- a/src/secret/meson.build +++ b/src/secret/meson.build @@ -1,5 +1,6 @@ secret_driver_sources = [ 'secret_driver.c', + 'secret_config.c', ] driver_source_files += files(secret_driver_sources) @@ -27,6 +28,24 @@ if conf.has('WITH_SECRETS') ], } + secret_conf = configure_file( + input: 'secret.conf.in', + output: 'secret.conf', + copy: true + ) + virt_conf_files += secret_conf + + virt_aug_files += files('libvirt_secrets.aug') + + virt_test_aug_files += { + 'name': 'test_libvirt_secrets.aug', + 'aug': files('test_libvirt_secrets.aug.in'), + 'conf': files('secret.conf.in'), + 'test_name': 'libvirt_secrets', + 'test_srcdir': meson.current_source_dir(), + 'test_builddir': meson.current_build_dir(), + } + virt_daemon_confs += { 'name': 'virtsecretd', } diff --git a/src/secret/secret.conf.in b/src/secret/secret.conf.in new file mode 100644 index 0000000000..a231c48f8d --- /dev/null +++ b/src/secret/secret.conf.in @@ -0,0 +1,14 @@ +# +# Configuration file for the secrets driver. +# +# The secret encryption key is used to override default encryption +# key path. The user can create an encryption key and set the secret_encryption_key +# to the path on which it resides. +# The key must be 32-bytes long. +#secrets_encryption_key = "/run/libvirt/secrets/secret-encryption-key" + +# The encrypt_data setting is used to indicate if the encryption is on or off. +# 0 indicates off and 1 indicates on. By default it is on +# if secrets_encryption_key is set to a non-NULL +# path, or if a systemd credential named "secrets-encryption-key" exists. +#encrypt_data = 1 diff --git a/src/secret/secret_config.c b/src/secret/secret_config.c new file mode 100644 index 0000000000..b63567944e --- /dev/null +++ b/src/secret/secret_config.c @@ -0,0 +1,171 @@ +/* + * secret_config.c: secret.conf config file handling + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#include <config.h> +#include <fcntl.h> +#include "configmake.h" +#include "datatypes.h" +#include "virlog.h" +#include "virerror.h" +#include "virfile.h" +#include "virutil.h" +#include "virsecureerase.h" +#include "secret_config.h" + + +#define VIR_FROM_THIS VIR_FROM_SECRET + +VIR_LOG_INIT("secret.secret_config"); + +static virClass *virSecretDaemonConfigClass; +static void virSecretDaemonConfigDispose(void *obj); + +static int +virSecretConfigOnceInit(void) +{ + if (!VIR_CLASS_NEW(virSecretDaemonConfig, virClassForObject())) + return -1; + + return 0; +} + + +VIR_ONCE_GLOBAL_INIT(virSecretConfig); + + +int +virSecretDaemonConfigFilePath(bool privileged, char **configfile) +{ + if (privileged) { + *configfile = g_strdup(SYSCONFDIR "/libvirt/secret.conf"); + } else { + g_autofree char *configdir = NULL; + + configdir = virGetUserConfigDirectory(); + + *configfile = g_strdup_printf("%s/secret.conf", configdir); + } + + return 0; +} + + +static int +virSecretLoadDaemonConfig(virSecretDaemonConfig *cfg, + const char *filename) +{ + g_autoptr(virConf) conf = NULL; + int res; + + if (virFileExists(filename)) { + conf = virConfReadFile(filename, 0); + if (!conf) + return -1; + res = virConfGetValueBool(conf, "encrypt_data", &cfg->encryptData); + if (res < 0) { + return -1; + } else if (res == 1) { + cfg->encryptDataWasSet = true; + } else { + cfg->encryptDataWasSet = false; + } + + if (virConfGetValueString(conf, "secrets_encryption_key", + &cfg->secretsEncryptionKeyPath) < 0) { + return -1; + } + } + return 0; +} + + +static int virGetSecretsEncryptionKey(virSecretDaemonConfig *cfg, + uint8_t **secretsEncryptionKey, + size_t *secretsKeyLen) +{ + VIR_AUTOCLOSE fd = -1; + int encryption_key_length; + + if ((encryption_key_length = virFileReadAll(cfg->secretsEncryptionKeyPath, VIR_SECRETS_ENCRYPTION_KEY_LEN, (char**)secretsEncryptionKey)) < 0) { + return -1; + } + if (encryption_key_length != VIR_SECRETS_ENCRYPTION_KEY_LEN) { + virReportError(VIR_ERR_INVALID_ENCR_KEY_SECRET, + _("Encryption key length must be '%1$d' '%2$s'"), + VIR_SECRETS_ENCRYPTION_KEY_LEN, cfg->secretsEncryptionKeyPath); + } + + *secretsKeyLen = (size_t)encryption_key_length; + return 0; +} + + +virSecretDaemonConfig * +virSecretDaemonConfigNew(bool privileged) +{ + g_autoptr(virSecretDaemonConfig) cfg = NULL; + g_autofree char *configdir = NULL; + g_autofree char *configfile = NULL; + const char *credentials_directory; + + if (virSecretConfigInitialize() < 0) + return NULL; + + if (!(cfg = virObjectNew(virSecretDaemonConfigClass))) + return NULL; + + cfg->secretsEncryptionKeyPath = NULL; + + if (virSecretDaemonConfigFilePath(privileged, &configfile) < 0) + return NULL; + + if (virSecretLoadDaemonConfig(cfg, configfile) < 0) + return NULL; + + credentials_directory = getenv("CREDENTIALS_DIRECTORY"); + + if (!cfg->secretsEncryptionKeyPath && credentials_directory) { + cfg->secretsEncryptionKeyPath = g_strdup_printf("%s/secrets-encryption-key", + credentials_directory); + if (!virFileExists(cfg->secretsEncryptionKeyPath)) { + g_clear_pointer(&cfg->secretsEncryptionKeyPath, g_free); + } + } + + if (!cfg->encryptDataWasSet) { + if (!cfg->secretsEncryptionKeyPath) { + /* No path specified by user or environment, disable encryption */ + cfg->encryptData = false; + } else { + cfg->encryptData = true; + } + } else { + if (cfg->encryptData) { + if (!cfg->secretsEncryptionKeyPath) { + /* Built-in default path must be used */ + cfg->secretsEncryptionKeyPath = g_strdup("/run/libvirt/secrets/encryption-key"); + } + } + } + VIR_DEBUG("Secrets encryption key path: %s", NULLSTR(cfg->secretsEncryptionKeyPath)); + + if (cfg->encryptData) { + if (virGetSecretsEncryptionKey(cfg, &cfg->secretsEncryptionKey, &cfg->secretsKeyLen) < 0) { + return NULL; + } + } + return g_steal_pointer(&cfg); +} + + +static void +virSecretDaemonConfigDispose(void *obj) +{ + virSecretDaemonConfig *cfg = obj; + + virSecureErase(cfg->secretsEncryptionKey, cfg->secretsKeyLen); + g_free(cfg->secretsEncryptionKeyPath); +} diff --git a/src/secret/secret_config.h b/src/secret/secret_config.h new file mode 100644 index 0000000000..888acf272b --- /dev/null +++ b/src/secret/secret_config.h @@ -0,0 +1,40 @@ +/* + * secret_config.h: secret.conf config file handling + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#pragma once + +#include "internal.h" +#include "virinhibitor.h" +#include "secret_event.h" +#define VIR_SECRETS_ENCRYPTION_KEY_LEN 32 + +typedef struct _virSecretDaemonConfig virSecretDaemonConfig; +struct _virSecretDaemonConfig { + virObject parent; + /* secrets encryption key path from secret.conf file */ + char *secretsEncryptionKeyPath; + + /* Store the key to encrypt secrets on the disk */ + unsigned char *secretsEncryptionKey; + + size_t secretsKeyLen; + + /* Indicates if the newly written secrets are encrypted or not. + */ + bool encryptData; + + /* Indicates if the config file has encrypt_data set or not. + */ + bool encryptDataWasSet; +}; + +G_DEFINE_AUTOPTR_CLEANUP_FUNC(virSecretDaemonConfig, virObjectUnref); + +int virSecretDaemonConfigFilePath(bool privileged, char **configfile); +virSecretDaemonConfig *virSecretDaemonConfigNew(bool privileged); +int virSecretDaemonConfigLoadFile(virSecretDaemonConfig *data, + const char *filename, + bool allow_missing); diff --git a/src/secret/secret_driver.c b/src/secret/secret_driver.c index 04c3ca49f1..408a629ea0 100644 --- a/src/secret/secret_driver.c +++ b/src/secret/secret_driver.c @@ -70,6 +70,9 @@ struct _virSecretDriverState { /* Immutable pointer, self-locking APIs */ virInhibitor *inhibitor; + + /* Settings from secret.conf file */ + virSecretDaemonConfig *config; }; static virSecretDriverState *driver; @@ -454,6 +457,7 @@ secretStateCleanupLocked(void) VIR_FREE(driver->configDir); virObjectUnref(driver->secretEventState); + virObjectUnref(driver->config); virInhibitorFree(driver->inhibitor); if (driver->lockFD != -1) @@ -518,6 +522,8 @@ secretStateInitialize(bool privileged, driver->stateDir); goto error; } + if (!(driver->config = virSecretDaemonConfigNew(driver->privileged))) + goto error; driver->inhibitor = virInhibitorNew( VIR_INHIBITOR_WHAT_NONE, @@ -553,6 +559,9 @@ secretStateReload(void) if (!driver) return -1; + if (!(driver->config = virSecretDaemonConfigNew(driver->privileged))) + return -1; + ignore_value(virSecretLoadAllConfigs(driver->secrets, driver->configDir)); return 0; diff --git a/src/secret/test_libvirt_secrets.aug.in b/src/secret/test_libvirt_secrets.aug.in new file mode 100644 index 0000000000..1bb205e0f2 --- /dev/null +++ b/src/secret/test_libvirt_secrets.aug.in @@ -0,0 +1,6 @@ +module Test_libvirt_secrets = + @CONFIG@ + + test Libvirt_secrets.lns get conf = +{ "secrets_encryption_key" = "/run/libvirt/secrets/secret-encryption-key" } +{ "encrypt_data" = "1" } diff --git a/src/util/virerror.c b/src/util/virerror.c index abb014b522..b7d23f81c7 100644 --- a/src/util/virerror.c +++ b/src/util/virerror.c @@ -1296,6 +1296,9 @@ static const virErrorMsgTuple virErrorMsgStrings[] = { [VIR_ERR_AGENT_COMMAND_FAILED] = { N_("guest agent command failed"), N_("guest agent command failed: %1$s") }, + [VIR_ERR_INVALID_ENCR_KEY_SECRET] = { + N_("Invalid encryption key for the secret"), + N_("Invalid encryption key for the secret: %1$s") }, }; G_STATIC_ASSERT(G_N_ELEMENTS(virErrorMsgStrings) == VIR_ERR_NUMBER_LAST); -- 2.51.1
On Tue, Dec 09, 2025 at 01:22:29 +0530, Arun Menon via Devel wrote:
A new configuration file called secret.conf is introduced to let the user configure the path to the secrets encryption key. This key will be used to encrypt/decrypt the secrets in libvirt.
By default the path is set to the runtime directory /run/libvirt/secrets, and it is commented in the config file. After parsing the file, the virtsecretd driver checks if an encryption key is present in the path and is valid.
If no encryption key is present in the path, then the service will by default use the encryption key stored in the CREDENTIALS_DIRECTORY.
Add logic to parse the encryption key file and store the key. It also checks for the encrypt_data attribute in the config file. The encryption and decryption logic will be added in the subsequent patches.
Signed-off-by: Arun Menon <armenon@redhat.com> --- include/libvirt/virterror.h | 1 + libvirt.spec.in | 3 + po/POTFILES | 1 + src/secret/libvirt_secrets.aug | 40 ++++++ src/secret/meson.build | 19 +++ src/secret/secret.conf.in | 14 ++ src/secret/secret_config.c | 171 +++++++++++++++++++++++++ src/secret/secret_config.h | 40 ++++++ src/secret/secret_driver.c | 9 ++ src/secret/test_libvirt_secrets.aug.in | 6 + src/util/virerror.c | 3 + 11 files changed, 307 insertions(+) create mode 100644 src/secret/libvirt_secrets.aug create mode 100644 src/secret/secret.conf.in create mode 100644 src/secret/secret_config.c create mode 100644 src/secret/secret_config.h create mode 100644 src/secret/test_libvirt_secrets.aug.in
Build fails after this patch with: ' '-Dabs_top_srcdir="/home/pipo/libvirt"' -MD -MQ src/libvirt_driver_secret.so.p/secret_secret_driver.c.o -MF src/libvirt_driver_secret.so.p/secret_secret_driver.c.o.d -o src/libvirt_driver_secret.so.p/secret_secret_driver.c.o -c ../../../libvirt/src/secret/secret_driver.c ../../../libvirt/src/secret/secret_driver.c:75:5: error: unknown type name ‘virSecretDaemonConfig’ 75 | virSecretDaemonConfig *config; | ^~~~~~~~~~~~~~~~~~~~~ ../../../libvirt/src/secret/secret_driver.c: In function ‘secretStateInitialize’: ../../../libvirt/src/secret/secret_driver.c:525:28: error: implicit declaration of function ‘virSecretDaemonConfigNew’ [-Wimplicit-function-declaration] 525 | if (!(driver->config = virSecretDaemonConfigNew(driver->privileged))) | ^~~~~~~~~~~~~~~~~~~~~~~~ ../../../libvirt/src/secret/secret_driver.c:525:28: error: nested extern declaration of ‘virSecretDaemonConfigNew’ [-Werror=nested-externs] ../../../libvirt/src/secret/secret_driver.c:525:26: error: assignment to ‘int *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion] 525 | if (!(driver->config = virSecretDaemonConfigNew(driver->privileged))) | ^ ../../../libvirt/src/secret/secret_driver.c: In function ‘secretStateReload’: ../../../libvirt/src/secret/secret_driver.c:562:26: error: assignment to ‘int *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion] 562 | if (!(driver->config = virSecretDaemonConfigNew(driver->privileged))) | ^ Since it succeeds after the last patch you likely misplaced some header inclusion into the wrong patch. [...]
diff --git a/src/secret/secret_config.c b/src/secret/secret_config.c new file mode 100644 index 0000000000..b63567944e --- /dev/null +++ b/src/secret/secret_config.c
[...]
+ + +static int virGetSecretsEncryptionKey(virSecretDaemonConfig *cfg, + uint8_t **secretsEncryptionKey, + size_t *secretsKeyLen)
inconsistent function header formatting
+{ + VIR_AUTOCLOSE fd = -1; + int encryption_key_length; + + if ((encryption_key_length = virFileReadAll(cfg->secretsEncryptionKeyPath, VIR_SECRETS_ENCRYPTION_KEY_LEN, (char**)secretsEncryptionKey)) < 0) {
break the very long line on argument boundaries
+ return -1; + } + if (encryption_key_length != VIR_SECRETS_ENCRYPTION_KEY_LEN) { + virReportError(VIR_ERR_INVALID_ENCR_KEY_SECRET, + _("Encryption key length must be '%1$d' '%2$s'"), + VIR_SECRETS_ENCRYPTION_KEY_LEN, cfg->secretsEncryptionKeyPath); + } + + *secretsKeyLen = (size_t)encryption_key_length; + return 0; +} + + +virSecretDaemonConfig * +virSecretDaemonConfigNew(bool privileged) +{ + g_autoptr(virSecretDaemonConfig) cfg = NULL; + g_autofree char *configdir = NULL; + g_autofree char *configfile = NULL; + const char *credentials_directory; + + if (virSecretConfigInitialize() < 0) + return NULL; + + if (!(cfg = virObjectNew(virSecretDaemonConfigClass))) + return NULL; + + cfg->secretsEncryptionKeyPath = NULL;
all of 'cfg' ought to be initialized to NULL at this point so this isn't needed.
+ + if (virSecretDaemonConfigFilePath(privileged, &configfile) < 0) + return NULL; + + if (virSecretLoadDaemonConfig(cfg, configfile) < 0) + return NULL; + + credentials_directory = getenv("CREDENTIALS_DIRECTORY"); + + if (!cfg->secretsEncryptionKeyPath && credentials_directory) { + cfg->secretsEncryptionKeyPath = g_strdup_printf("%s/secrets-encryption-key", + credentials_directory); + if (!virFileExists(cfg->secretsEncryptionKeyPath)) { + g_clear_pointer(&cfg->secretsEncryptionKeyPath, g_free); + } + } + + if (!cfg->encryptDataWasSet) { + if (!cfg->secretsEncryptionKeyPath) { + /* No path specified by user or environment, disable encryption */ + cfg->encryptData = false; + } else { + cfg->encryptData = true; + } + } else { + if (cfg->encryptData) { + if (!cfg->secretsEncryptionKeyPath) { + /* Built-in default path must be used */ + cfg->secretsEncryptionKeyPath = g_strdup("/run/libvirt/secrets/encryption-key");
This ought to use some form of config-time variable to place it correctly, otherwise it won't respect users' build-time options.
+ } + } + } + VIR_DEBUG("Secrets encryption key path: %s", NULLSTR(cfg->secretsEncryptionKeyPath)); + + if (cfg->encryptData) { + if (virGetSecretsEncryptionKey(cfg, &cfg->secretsEncryptionKey, &cfg->secretsKeyLen) < 0) { + return NULL; + } + } + return g_steal_pointer(&cfg); +}
[...]
diff --git a/src/secret/secret_driver.c b/src/secret/secret_driver.c index 04c3ca49f1..408a629ea0 100644 --- a/src/secret/secret_driver.c +++ b/src/secret/secret_driver.c @@ -70,6 +70,9 @@ struct _virSecretDriverState {
/* Immutable pointer, self-locking APIs */ virInhibitor *inhibitor; + + /* Settings from secret.conf file */ + virSecretDaemonConfig *config; };
Please use the annotation about how to access the data (as all other values above have). In this case I expect that the correct annotation is: /* Require lock to get reference on 'config', * then lockless thereafter */ same as the 'config' member of struct _virQEMUDriver.
The new attribute will store the available cipher modes with which secrets can be encrypted. At the moment only aes256cbc encryption method is used. This can be extended in future with other modes of cipher. Rename the file-name structure attribute from base64File to secretValueFile. Signed-off-by: Arun Menon <armenon@redhat.com> --- src/conf/secret_conf.c | 6 ++++++ src/conf/secret_conf.h | 9 +++++++++ src/conf/virsecretobj.c | 22 +++++++++++----------- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/conf/secret_conf.c b/src/conf/secret_conf.c index 966536599e..dd808aa21a 100644 --- a/src/conf/secret_conf.c +++ b/src/conf/secret_conf.c @@ -32,6 +32,12 @@ #define VIR_FROM_THIS VIR_FROM_SECRET +VIR_ENUM_IMPL(virSecretEncryptionScheme, + VIR_SECRET_ENCRYPTION_SCHEME_LAST, + "none", + "aes256cbc", +); + VIR_LOG_INIT("conf.secret_conf"); void diff --git a/src/conf/secret_conf.h b/src/conf/secret_conf.h index 8f8f47933a..c11558357e 100644 --- a/src/conf/secret_conf.h +++ b/src/conf/secret_conf.h @@ -21,6 +21,7 @@ #pragma once #include "internal.h" +#include "virenum.h" typedef struct _virSecretDef virSecretDef; struct _virSecretDef { @@ -32,6 +33,12 @@ struct _virSecretDef { char *usage_id; /* May be NULL */ }; +typedef enum { + VIR_SECRET_ENCRYPTION_SCHEME_NONE = 0, + VIR_SECRET_ENCRYPTION_SCHEME_AES256CBC = 1, + VIR_SECRET_ENCRYPTION_SCHEME_LAST +} virSecretEncryptionScheme; + void virSecretDefFree(virSecretDef *def); G_DEFINE_AUTOPTR_CLEANUP_FUNC(virSecretDef, virSecretDefFree); @@ -53,3 +60,5 @@ char *virSecretDefFormat(const virSecretDef *def); #define VIR_CONNECT_LIST_SECRETS_FILTERS_ALL \ (VIR_CONNECT_LIST_SECRETS_FILTERS_EPHEMERAL | \ VIR_CONNECT_LIST_SECRETS_FILTERS_PRIVATE) + +VIR_ENUM_DECL(virSecretEncryptionScheme); diff --git a/src/conf/virsecretobj.c b/src/conf/virsecretobj.c index 66270e2751..a3dd7983bb 100644 --- a/src/conf/virsecretobj.c +++ b/src/conf/virsecretobj.c @@ -39,7 +39,7 @@ VIR_LOG_INIT("conf.virsecretobj"); struct _virSecretObj { virObjectLockable parent; char *configFile; - char *base64File; + char *secretValueFile; virSecretDef *def; unsigned char *value; /* May be NULL */ size_t value_size; @@ -139,7 +139,7 @@ virSecretObjDispose(void *opaque) g_free(obj->value); } g_free(obj->configFile); - g_free(obj->base64File); + g_free(obj->secretValueFile); } @@ -378,11 +378,11 @@ virSecretObjListAdd(virSecretObjList *secrets, if (!(obj = virSecretObjNew())) goto cleanup; - /* Generate the possible configFile and base64File strings + /* Generate the possible configFile and secretValueFile strings * using the configDir, uuidstr, and appropriate suffix */ if (!(obj->configFile = virFileBuildPath(configDir, uuidstr, ".xml")) || - !(obj->base64File = virFileBuildPath(configDir, uuidstr, ".base64"))) + !(obj->secretValueFile = virFileBuildPath(configDir, uuidstr, ".base64"))) goto cleanup; if (virHashAddEntry(secrets->objs, uuidstr, obj) < 0) @@ -656,7 +656,7 @@ virSecretObjDeleteData(virSecretObj *obj) { /* The configFile will already be removed, so secret won't be * loaded again if this fails */ - unlink(obj->base64File); + unlink(obj->secretValueFile); } @@ -691,7 +691,7 @@ virSecretObjSaveData(virSecretObj *obj) base64 = g_base64_encode(obj->value, obj->value_size); - if (virFileRewriteStr(obj->base64File, S_IRUSR | S_IWUSR, base64) < 0) + if (virFileRewriteStr(obj->secretValueFile, S_IRUSR | S_IWUSR, base64) < 0) return -1; return 0; @@ -813,26 +813,26 @@ virSecretLoadValue(virSecretObj *obj) struct stat st; g_autofree char *contents = NULL; - if ((fd = open(obj->base64File, O_RDONLY)) == -1) { + if ((fd = open(obj->secretValueFile, O_RDONLY)) == -1) { if (errno == ENOENT) { ret = 0; goto cleanup; } virReportSystemError(errno, _("cannot open '%1$s'"), - obj->base64File); + obj->secretValueFile); goto cleanup; } if (fstat(fd, &st) < 0) { virReportSystemError(errno, _("cannot stat '%1$s'"), - obj->base64File); + obj->secretValueFile); goto cleanup; } if ((size_t)st.st_size != st.st_size) { virReportError(VIR_ERR_INTERNAL_ERROR, _("'%1$s' file does not fit in memory"), - obj->base64File); + obj->secretValueFile); goto cleanup; } @@ -845,7 +845,7 @@ virSecretLoadValue(virSecretObj *obj) if (saferead(fd, contents, st.st_size) != st.st_size) { virReportSystemError(errno, _("cannot read '%1$s'"), - obj->base64File); + obj->secretValueFile); goto cleanup; } contents[st.st_size] = '\0'; -- 2.51.1
On Tue, Dec 09, 2025 at 01:22:30 +0530, Arun Menon via Devel wrote:
The new attribute will store the available cipher modes with which secrets can be encrypted. At the moment only aes256cbc encryption method is used. This can be extended in future with other modes of cipher.
Rename the file-name structure attribute from base64File to secretValueFile.
Signed-off-by: Arun Menon <armenon@redhat.com> --- src/conf/secret_conf.c | 6 ++++++ src/conf/secret_conf.h | 9 +++++++++ src/conf/virsecretobj.c | 22 +++++++++++----------- 3 files changed, 26 insertions(+), 11 deletions(-)
diff --git a/src/conf/secret_conf.c b/src/conf/secret_conf.c index 966536599e..dd808aa21a 100644 --- a/src/conf/secret_conf.c +++ b/src/conf/secret_conf.c @@ -32,6 +32,12 @@
#define VIR_FROM_THIS VIR_FROM_SECRET
+VIR_ENUM_IMPL(virSecretEncryptionScheme, + VIR_SECRET_ENCRYPTION_SCHEME_LAST, + "none", + "aes256cbc", +); + VIR_LOG_INIT("conf.secret_conf");
Any reason for this to be in conf/secret_conf ? It's not used in the XML, but rather an impl detail of the secret driver.
void diff --git a/src/conf/secret_conf.h b/src/conf/secret_conf.h index 8f8f47933a..c11558357e 100644 --- a/src/conf/secret_conf.h +++ b/src/conf/secret_conf.h @@ -21,6 +21,7 @@ #pragma once
#include "internal.h" +#include "virenum.h"
typedef struct _virSecretDef virSecretDef; struct _virSecretDef { @@ -32,6 +33,12 @@ struct _virSecretDef { char *usage_id; /* May be NULL */ };
+typedef enum { + VIR_SECRET_ENCRYPTION_SCHEME_NONE = 0, + VIR_SECRET_ENCRYPTION_SCHEME_AES256CBC = 1, + VIR_SECRET_ENCRYPTION_SCHEME_LAST +} virSecretEncryptionScheme; + void virSecretDefFree(virSecretDef *def); G_DEFINE_AUTOPTR_CLEANUP_FUNC(virSecretDef, virSecretDefFree);
@@ -53,3 +60,5 @@ char *virSecretDefFormat(const virSecretDef *def); #define VIR_CONNECT_LIST_SECRETS_FILTERS_ALL \ (VIR_CONNECT_LIST_SECRETS_FILTERS_EPHEMERAL | \ VIR_CONNECT_LIST_SECRETS_FILTERS_PRIVATE) + +VIR_ENUM_DECL(virSecretEncryptionScheme); diff --git a/src/conf/virsecretobj.c b/src/conf/virsecretobj.c index 66270e2751..a3dd7983bb 100644 --- a/src/conf/virsecretobj.c +++ b/src/conf/virsecretobj.c @@ -39,7 +39,7 @@ VIR_LOG_INIT("conf.virsecretobj"); struct _virSecretObj { virObjectLockable parent; char *configFile; - char *base64File; + char *secretValueFile;
Rename of this field is okay to stay as a separate patch.
Now that we have the functionality to provide the secrets driver with an encryption key through a configuration file or using system credentials, and the newly introduced attribute to iterate over the encryption schemes, we can use the key to save and load secrets. Encrypt all secrets that are going to be saved on the disk if the 'secrets_encryption_key' path is set in the secret.conf file OR if a valid systemd generated credential exists. While loading secrets, identify the decryption method by matching the file extension of the stored secret against the known encryptionSchemeType values. If no matching scheme is found, the secret is skipped. If the encryption key is changed across restarts, then also the secret driver will fail to load the secrets from the disk that were encrypted with the former key. Signed-off-by: Arun Menon <armenon@redhat.com> --- src/conf/virsecretobj.c | 166 ++++++++++++++++++++++++++++++------- src/conf/virsecretobj.h | 18 +++- src/secret/secret_driver.c | 25 ++++-- 3 files changed, 169 insertions(+), 40 deletions(-) diff --git a/src/conf/virsecretobj.c b/src/conf/virsecretobj.c index a3dd7983bb..60a1323625 100644 --- a/src/conf/virsecretobj.c +++ b/src/conf/virsecretobj.c @@ -31,6 +31,10 @@ #include "virhash.h" #include "virlog.h" #include "virstring.h" +#include "virsecret.h" +#include "virrandom.h" +#include "vircrypto.h" +#include "virsecureerase.h" #define VIR_FROM_THIS VIR_FROM_SECRET @@ -45,6 +49,16 @@ struct _virSecretObj { size_t value_size; }; +typedef struct _virSecretSchemeInfo { + const char *suffix; + virCryptoCipher cipher; +} virSecretSchemeInfo; + +virSecretSchemeInfo schemeInfo[] = { + { ".base64", -1 }, + { ".aes256cbc", VIR_CRYPTO_CIPHER_AES256CBC }, +}; + static virClass *virSecretObjClass; static virClass *virSecretObjListClass; static void virSecretObjDispose(void *obj); @@ -323,7 +337,8 @@ virSecretObj * virSecretObjListAdd(virSecretObjList *secrets, virSecretDef **newdef, const char *configDir, - virSecretDef **oldDef) + virSecretDef **oldDef, + bool encryptData) { virSecretObj *obj; virSecretDef *objdef; @@ -363,6 +378,8 @@ virSecretObjListAdd(virSecretObjList *secrets, } else { /* No existing secret with same UUID, * try look for matching usage instead */ + const char *secretSuffix = ".base64"; + g_autofree char *encryptionSchemeSuffix = NULL; if ((obj = virSecretObjListFindByUsageLocked(secrets, (*newdef)->usage_type, (*newdef)->usage_id))) { @@ -379,10 +396,17 @@ virSecretObjListAdd(virSecretObjList *secrets, goto cleanup; /* Generate the possible configFile and secretValueFile strings - * using the configDir, uuidstr, and appropriate suffix + * using the configDir, uuidstr, and appropriate suffix. + * By default, the latest encryption cipher will be used to encrypt secrets. */ + + if (encryptData) { + encryptionSchemeSuffix = g_strdup_printf(".%s", virSecretEncryptionSchemeTypeToString(VIR_SECRET_ENCRYPTION_SCHEME_LAST- 1)); + } else { + encryptionSchemeSuffix = g_strdup(secretSuffix); + } if (!(obj->configFile = virFileBuildPath(configDir, uuidstr, ".xml")) || - !(obj->secretValueFile = virFileBuildPath(configDir, uuidstr, ".base64"))) + !(obj->secretValueFile = virFileBuildPath(configDir, uuidstr, encryptionSchemeSuffix))) goto cleanup; if (virHashAddEntry(secrets->objs, uuidstr, obj) < 0) @@ -682,15 +706,40 @@ virSecretObjSaveConfig(virSecretObj *obj) int -virSecretObjSaveData(virSecretObj *obj) +virSecretObjSaveData(virSecretObj *obj, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen) { g_autofree char *base64 = NULL; + g_autofree uint8_t *secret = NULL; + g_autofree uint8_t *encryptedValue = NULL; + size_t encryptedValueLen = 0; + size_t secretLen = 0; + uint8_t iv[16] = { 0 }; if (!obj->value) return 0; - base64 = g_base64_encode(obj->value, obj->value_size); - + if (encryptData && secretsEncryptionKey) { + if (virRandomBytes(iv, sizeof(iv)) < 0) { + return -1; + } + if (virCryptoEncryptData(VIR_CRYPTO_CIPHER_LAST-1, + secretsEncryptionKey, secretsKeyLen, + iv, sizeof(iv), + (uint8_t *)obj->value, obj->value_size, + &encryptedValue, &encryptedValueLen) < 0) { + return -1; + } + secretLen = sizeof(iv) + encryptedValueLen; + secret = g_new0(uint8_t, secretLen); + memcpy(secret, iv, sizeof(iv)); + memcpy(secret + sizeof(iv), encryptedValue, encryptedValueLen); + base64 = g_base64_encode(secret, secretLen); + } else { + base64 = g_base64_encode(obj->value, obj->value_size); + } if (virFileRewriteStr(obj->secretValueFile, S_IRUSR | S_IWUSR, base64) < 0) return -1; @@ -737,7 +786,10 @@ virSecretObjGetValue(virSecretObj *obj) int virSecretObjSetValue(virSecretObj *obj, const unsigned char *value, - size_t value_size) + size_t value_size, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen) { virSecretDef *def = obj->def; g_autofree unsigned char *old_value = NULL; @@ -753,7 +805,10 @@ virSecretObjSetValue(virSecretObj *obj, obj->value = g_steal_pointer(&new_value); obj->value_size = value_size; - if (!def->isephemeral && virSecretObjSaveData(obj) < 0) + if (!def->isephemeral && virSecretObjSaveData(obj, + encryptData, + secretsEncryptionKey, + secretsKeyLen) < 0) goto error; /* Saved successfully - drop old value */ @@ -807,11 +862,24 @@ virSecretLoadValidateUUID(virSecretDef *def, static int -virSecretLoadValue(virSecretObj *obj) +virSecretLoadValue(virSecretObj *obj, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen) { - int ret = -1, fd = -1; + int ret = -1; + VIR_AUTOCLOSE fd = -1; struct stat st; + size_t i; + g_autofree char *contents = NULL; + g_autofree uint8_t *contents_encrypted = NULL; + g_autofree uint8_t *decryptedValue = NULL; + g_autofree char *encryptionScheme = NULL; + + size_t decryptedValueLen = 0; + uint8_t iv[16] = { 0 }; + uint8_t *ciphertext = NULL; + size_t ciphertextLen = 0; if ((fd = open(obj->secretValueFile, O_RDONLY)) == -1) { if (errno == ENOENT) { @@ -841,25 +909,52 @@ virSecretLoadValue(virSecretObj *obj) goto cleanup; } - contents = g_new0(char, st.st_size + 1); - - if (saferead(fd, contents, st.st_size) != st.st_size) { - virReportSystemError(errno, _("cannot read '%1$s'"), - obj->secretValueFile); - goto cleanup; + /* Iterate over the encryption schemes and decrypt the contents + * of the file on the disk, by matching the file extension with the encryption + * scheme. + * If there is no scheme matching the file extension, then that secret is not loaded. */ + + for (i = 0; i < G_N_ELEMENTS(schemeInfo); i++) { + if (virStringHasSuffix(obj->secretValueFile, schemeInfo[i].suffix)) { + contents = g_new0(char, st.st_size + 1); + if (saferead(fd, contents, st.st_size) != st.st_size) { + virReportSystemError(errno, _("cannot read '%1$s'"), + obj->secretValueFile); + goto cleanup; + } + contents[st.st_size] = '\0'; + if (schemeInfo[i].cipher != -1) { + contents_encrypted = g_base64_decode(contents, &obj->value_size); + if (sizeof(iv) > obj->value_size) { + virReportError(VIR_ERR_INVALID_SECRET, + _("Encrypted secret size '%1$zu' is invalid"), + obj->value_size); + goto cleanup; + } + memcpy(iv, contents_encrypted, sizeof(iv)); + ciphertext = contents_encrypted + sizeof(iv); + ciphertextLen = st.st_size - sizeof(iv); + if (virCryptoDecryptData(schemeInfo[i].cipher, + secretsEncryptionKey, secretsKeyLen, + iv, sizeof(iv), + ciphertext, ciphertextLen, + &decryptedValue, &decryptedValueLen) < 0) { + goto cleanup; + } + g_free(obj->value); + obj->value = g_steal_pointer(&decryptedValue); + obj->value_size = decryptedValueLen; + } else { + obj->value = g_base64_decode(contents, &obj->value_size); + } + break; + } } - contents[st.st_size] = '\0'; - - VIR_FORCE_CLOSE(fd); - - obj->value = g_base64_decode(contents, &obj->value_size); - ret = 0; - cleanup: - if (contents != NULL) - memset(contents, 0, st.st_size); - VIR_FORCE_CLOSE(fd); + virSecureErase(contents_encrypted, obj->value_size); + virSecureErase(contents, st.st_size); + virSecureErase(iv, sizeof(iv)); return ret; } @@ -868,7 +963,10 @@ static virSecretObj * virSecretLoad(virSecretObjList *secrets, const char *file, const char *path, - const char *configDir) + const char *configDir, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen) { g_autoptr(virSecretDef) def = NULL; virSecretObj *obj = NULL; @@ -879,10 +977,10 @@ virSecretLoad(virSecretObjList *secrets, if (virSecretLoadValidateUUID(def, file) < 0) return NULL; - if (!(obj = virSecretObjListAdd(secrets, &def, configDir, NULL))) + if (!(obj = virSecretObjListAdd(secrets, &def, configDir, NULL, encryptData))) return NULL; - if (virSecretLoadValue(obj) < 0) { + if (virSecretLoadValue(obj, secretsEncryptionKey, secretsKeyLen) < 0) { virSecretObjListRemove(secrets, obj); g_clear_pointer(&obj, virObjectUnref); return NULL; @@ -894,7 +992,10 @@ virSecretLoad(virSecretObjList *secrets, int virSecretLoadAllConfigs(virSecretObjList *secrets, - const char *configDir) + const char *configDir, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen) { g_autoptr(DIR) dir = NULL; struct dirent *de; @@ -915,7 +1016,10 @@ virSecretLoadAllConfigs(virSecretObjList *secrets, if (!(path = virFileBuildPath(configDir, de->d_name, NULL))) continue; - if (!(obj = virSecretLoad(secrets, de->d_name, path, configDir))) { + if (!(obj = virSecretLoad(secrets, de->d_name, path, configDir, + encryptData, + secretsEncryptionKey, + secretsKeyLen))) { VIR_ERROR(_("Error reading secret: %1$s"), virGetLastErrorMessage()); continue; diff --git a/src/conf/virsecretobj.h b/src/conf/virsecretobj.h index 17897c5513..2e4d980988 100644 --- a/src/conf/virsecretobj.h +++ b/src/conf/virsecretobj.h @@ -51,7 +51,8 @@ virSecretObj * virSecretObjListAdd(virSecretObjList *secrets, virSecretDef **newdef, const char *configDir, - virSecretDef **oldDef); + virSecretDef **oldDef, + bool encryptData); typedef bool (*virSecretObjListACLFilter)(virConnectPtr conn, @@ -86,7 +87,10 @@ int virSecretObjSaveConfig(virSecretObj *obj); int -virSecretObjSaveData(virSecretObj *obj); +virSecretObjSaveData(virSecretObj *obj, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen); virSecretDef * virSecretObjGetDef(virSecretObj *obj); @@ -101,7 +105,10 @@ virSecretObjGetValue(virSecretObj *obj); int virSecretObjSetValue(virSecretObj *obj, const unsigned char *value, - size_t value_size); + size_t value_size, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen); size_t virSecretObjGetValueSize(virSecretObj *obj); @@ -112,4 +119,7 @@ virSecretObjSetValueSize(virSecretObj *obj, int virSecretLoadAllConfigs(virSecretObjList *secrets, - const char *configDir); + const char *configDir, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen); diff --git a/src/secret/secret_driver.c b/src/secret/secret_driver.c index 408a629ea0..8c0796c86a 100644 --- a/src/secret/secret_driver.c +++ b/src/secret/secret_driver.c @@ -30,6 +30,7 @@ #include "virlog.h" #include "viralloc.h" #include "secret_conf.h" +#include "secret_config.h" #include "virsecretobj.h" #include "secret_driver.h" #include "virthread.h" @@ -42,6 +43,7 @@ #include "secret_event.h" #include "virutil.h" #include "virinhibitor.h" +#include "virfile.h" #define VIR_FROM_THIS VIR_FROM_SECRET @@ -221,13 +223,17 @@ secretDefineXML(virConnectPtr conn, goto cleanup; if (!(obj = virSecretObjListAdd(driver->secrets, &def, - driver->configDir, &backup))) + driver->configDir, &backup, + driver->config->encryptData))) goto cleanup; objDef = virSecretObjGetDef(obj); if (!objDef->isephemeral) { if (backup && backup->isephemeral) { - if (virSecretObjSaveData(obj) < 0) + if (virSecretObjSaveData(obj, + driver->config->encryptData, + driver->config->secretsEncryptionKey, + driver->config->secretsKeyLen) < 0) goto restore_backup; } @@ -331,7 +337,10 @@ secretSetValue(virSecretPtr secret, if (virSecretSetValueEnsureACL(secret->conn, def) < 0) goto cleanup; - if (virSecretObjSetValue(obj, value, value_size) < 0) + if (virSecretObjSetValue(obj, value, value_size, + driver->config->encryptData, + driver->config->secretsEncryptionKey, + driver->config->secretsKeyLen) < 0) goto cleanup; event = virSecretEventValueChangedNew(def->uuid, @@ -540,7 +549,10 @@ secretStateInitialize(bool privileged, if (!(driver->secrets = virSecretObjListNew())) goto error; - if (virSecretLoadAllConfigs(driver->secrets, driver->configDir) < 0) + if (virSecretLoadAllConfigs(driver->secrets, driver->configDir, + driver->config->encryptData, + driver->config->secretsEncryptionKey, + driver->config->secretsKeyLen) < 0) goto error; return VIR_DRV_STATE_INIT_COMPLETE; @@ -562,7 +574,10 @@ secretStateReload(void) if (!(driver->config = virSecretDaemonConfigNew(driver->privileged))) return -1; - ignore_value(virSecretLoadAllConfigs(driver->secrets, driver->configDir)); + ignore_value(virSecretLoadAllConfigs(driver->secrets, driver->configDir, + driver->config->encryptData, + driver->config->secretsEncryptionKey, + driver->config->secretsKeyLen)); return 0; } -- 2.51.1
On Tue, Dec 09, 2025 at 01:22:31 +0530, Arun Menon via Devel wrote:
Now that we have the functionality to provide the secrets driver with an encryption key through a configuration file or using system credentials, and the newly introduced attribute to iterate over the encryption schemes, we can use the key to save and load secrets.
Encrypt all secrets that are going to be saved on the disk if the 'secrets_encryption_key' path is set in the secret.conf file OR if a valid systemd generated credential exists.
While loading secrets, identify the decryption method by matching the file extension of the stored secret against the known encryptionSchemeType values. If no matching scheme is found, the secret is skipped. If the encryption key is changed across restarts, then also the secret driver will fail to load the secrets from the disk that were encrypted with the former key.
Signed-off-by: Arun Menon <armenon@redhat.com> --- src/conf/virsecretobj.c | 166 ++++++++++++++++++++++++++++++------- src/conf/virsecretobj.h | 18 +++- src/secret/secret_driver.c | 25 ++++-- 3 files changed, 169 insertions(+), 40 deletions(-)
diff --git a/src/conf/virsecretobj.c b/src/conf/virsecretobj.c index a3dd7983bb..60a1323625 100644 --- a/src/conf/virsecretobj.c +++ b/src/conf/virsecretobj.c @@ -31,6 +31,10 @@ #include "virhash.h" #include "virlog.h" #include "virstring.h" +#include "virsecret.h" +#include "virrandom.h" +#include "vircrypto.h" +#include "virsecureerase.h"
#define VIR_FROM_THIS VIR_FROM_SECRET
@@ -45,6 +49,16 @@ struct _virSecretObj { size_t value_size; };
+typedef struct _virSecretSchemeInfo { + const char *suffix; + virCryptoCipher cipher; +} virSecretSchemeInfo; + +virSecretSchemeInfo schemeInfo[] = { + { ".base64", -1 }, + { ".aes256cbc", VIR_CRYPTO_CIPHER_AES256CBC },
If you order the entries in this struct the other way around you'll not have to use VIR_SECRET_ENCRYPTION_SCHEME_LAST - 1 everywhere. In fact you won't even need the virSecretEncryptionScheme type at all.
+}; + static virClass *virSecretObjClass; static virClass *virSecretObjListClass; static void virSecretObjDispose(void *obj); @@ -323,7 +337,8 @@ virSecretObj * virSecretObjListAdd(virSecretObjList *secrets, virSecretDef **newdef, const char *configDir, - virSecretDef **oldDef) + virSecretDef **oldDef, + bool encryptData) { virSecretObj *obj; virSecretDef *objdef; @@ -363,6 +378,8 @@ virSecretObjListAdd(virSecretObjList *secrets, } else { /* No existing secret with same UUID, * try look for matching usage instead */ + const char *secretSuffix = ".base64"; + g_autofree char *encryptionSchemeSuffix = NULL; if ((obj = virSecretObjListFindByUsageLocked(secrets, (*newdef)->usage_type, (*newdef)->usage_id))) { @@ -379,10 +396,17 @@ virSecretObjListAdd(virSecretObjList *secrets, goto cleanup;
/* Generate the possible configFile and secretValueFile strings - * using the configDir, uuidstr, and appropriate suffix + * using the configDir, uuidstr, and appropriate suffix. + * By default, the latest encryption cipher will be used to encrypt secrets. */ + + if (encryptData) { + encryptionSchemeSuffix = g_strdup_printf(".%s", virSecretEncryptionSchemeTypeToString(VIR_SECRET_ENCRYPTION_SCHEME_LAST- 1));
use schemeinfo[0].suffix and you won't have to copy these any more.
+ } else { + encryptionSchemeSuffix = g_strdup(secretSuffix); + } if (!(obj->configFile = virFileBuildPath(configDir, uuidstr, ".xml")) || - !(obj->secretValueFile = virFileBuildPath(configDir, uuidstr, ".base64"))) + !(obj->secretValueFile = virFileBuildPath(configDir, uuidstr, encryptionSchemeSuffix))) goto cleanup;
if (virHashAddEntry(secrets->objs, uuidstr, obj) < 0) @@ -682,15 +706,40 @@ virSecretObjSaveConfig(virSecretObj *obj)
int -virSecretObjSaveData(virSecretObj *obj) +virSecretObjSaveData(virSecretObj *obj, + bool encryptData, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen) { g_autofree char *base64 = NULL; + g_autofree uint8_t *secret = NULL; + g_autofree uint8_t *encryptedValue = NULL; + size_t encryptedValueLen = 0; + size_t secretLen = 0; + uint8_t iv[16] = { 0 };
if (!obj->value) return 0;
- base64 = g_base64_encode(obj->value, obj->value_size); - + if (encryptData && secretsEncryptionKey) { + if (virRandomBytes(iv, sizeof(iv)) < 0) { + return -1; + } + if (virCryptoEncryptData(VIR_CRYPTO_CIPHER_LAST-1,
Umm so this is a 3rd distinct way how you specify AES in this series. use the entry from the struct instead so that there isn't multiple places that'll need to be changed if a different one is to be picked.
+ secretsEncryptionKey, secretsKeyLen, + iv, sizeof(iv), + (uint8_t *)obj->value, obj->value_size, + &encryptedValue, &encryptedValueLen) < 0) { + return -1; + } + secretLen = sizeof(iv) + encryptedValueLen; + secret = g_new0(uint8_t, secretLen); + memcpy(secret, iv, sizeof(iv)); + memcpy(secret + sizeof(iv), encryptedValue, encryptedValueLen); + base64 = g_base64_encode(secret, secretLen); + } else { + base64 = g_base64_encode(obj->value, obj->value_size); + } if (virFileRewriteStr(obj->secretValueFile, S_IRUSR | S_IWUSR, base64) < 0) return -1;
[...]
@@ -807,11 +862,24 @@ virSecretLoadValidateUUID(virSecretDef *def,
static int -virSecretLoadValue(virSecretObj *obj) +virSecretLoadValue(virSecretObj *obj, + uint8_t *secretsEncryptionKey, + size_t secretsKeyLen) { - int ret = -1, fd = -1; + int ret = -1; + VIR_AUTOCLOSE fd = -1; struct stat st; + size_t i; + g_autofree char *contents = NULL; + g_autofree uint8_t *contents_encrypted = NULL; + g_autofree uint8_t *decryptedValue = NULL;
Mix of snake-case and camel case
+ g_autofree char *encryptionScheme = NULL;
This variable is unused.
+ + size_t decryptedValueLen = 0; + uint8_t iv[16] = { 0 }; + uint8_t *ciphertext = NULL; + size_t ciphertextLen = 0;
if ((fd = open(obj->secretValueFile, O_RDONLY)) == -1) { if (errno == ENOENT) { @@ -841,25 +909,52 @@ virSecretLoadValue(virSecretObj *obj) goto cleanup; }
- contents = g_new0(char, st.st_size + 1); - - if (saferead(fd, contents, st.st_size) != st.st_size) { - virReportSystemError(errno, _("cannot read '%1$s'"), - obj->secretValueFile); - goto cleanup; + /* Iterate over the encryption schemes and decrypt the contents + * of the file on the disk, by matching the file extension with the encryption + * scheme. + * If there is no scheme matching the file extension, then that secret is not loaded. */ + + for (i = 0; i < G_N_ELEMENTS(schemeInfo); i++) { + if (virStringHasSuffix(obj->secretValueFile, schemeInfo[i].suffix)) { + contents = g_new0(char, st.st_size + 1); + if (saferead(fd, contents, st.st_size) != st.st_size) { + virReportSystemError(errno, _("cannot read '%1$s'"), + obj->secretValueFile); + goto cleanup; + } + contents[st.st_size] = '\0'; + if (schemeInfo[i].cipher != -1) { + contents_encrypted = g_base64_decode(contents, &obj->value_size); + if (sizeof(iv) > obj->value_size) { + virReportError(VIR_ERR_INVALID_SECRET, + _("Encrypted secret size '%1$zu' is invalid"), + obj->value_size); + goto cleanup; + } + memcpy(iv, contents_encrypted, sizeof(iv)); + ciphertext = contents_encrypted + sizeof(iv); + ciphertextLen = st.st_size - sizeof(iv); + if (virCryptoDecryptData(schemeInfo[i].cipher, + secretsEncryptionKey, secretsKeyLen, + iv, sizeof(iv), + ciphertext, ciphertextLen, + &decryptedValue, &decryptedValueLen) < 0) { + goto cleanup; + } + g_free(obj->value); + obj->value = g_steal_pointer(&decryptedValue); + obj->value_size = decryptedValueLen; + } else { + obj->value = g_base64_decode(contents, &obj->value_size); + } + break; + } } - contents[st.st_size] = '\0'; - - VIR_FORCE_CLOSE(fd); - - obj->value = g_base64_decode(contents, &obj->value_size); - ret = 0; - cleanup: - if (contents != NULL) - memset(contents, 0, st.st_size); - VIR_FORCE_CLOSE(fd); + virSecureErase(contents_encrypted, obj->value_size); + virSecureErase(contents, st.st_size); + virSecureErase(iv, sizeof(iv)); return ret; }
diff --git a/src/secret/secret_driver.c b/src/secret/secret_driver.c index 408a629ea0..8c0796c86a 100644 --- a/src/secret/secret_driver.c +++ b/src/secret/secret_driver.c @@ -30,6 +30,7 @@ #include "virlog.h" #include "viralloc.h" #include "secret_conf.h" +#include "secret_config.h"
This likely fixes the build issue from 3/5.
#include "virsecretobj.h" #include "secret_driver.h" #include "virthread.h"
participants (2)
-
Arun Menon -
Peter Krempa